File size: 7,473 Bytes
81de6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import torch
from torch import nn
from .allocator import EID,EVENT_OPS,LANES
from .graph import GraphPreparation
from . import physical as p
from . import allocation_constants as d
from . import allocation_constants as e


PID = {o: i for i, o in enumerate(p.OPS)}

class TensorStackLower(nn.Module):

    def __init__(self):
        super().__init__()
        self.register_buffer('regmap', torch.tensor(d.REGS))
        self.register_buffer('callee', torch.tensor(sorted(e.CALLEE)))
        self.register_buffer('ordinary', torch.tensor([PID.get(o, 0) for o in EVENT_OPS]))
        self.eval().requires_grad_(False)

    def stack(self, x, events):
        B, V = x['op'].shape
        dev = events.device
        flat = events.reshape(B, -1, 3)
        T = flat.shape[1]
        op, r, v = flat.unbind(-1)
        store = op == EID['store']
        load = op == EID['load']
        mem = store | load
        idx = torch.arange(T, device=dev)[None, :].expand(B, -1)
        t = idx // LANES
        valid = (v >= 0) & (v < V)
        safe = v.clamp(0, V - 1)
        dest = torch.where(store & valid, safe, V)
        first = torch.full((B, V + 1), T, device=dev, dtype=torch.long).scatter_reduce(1, dest, idx, reduce='amin')[:, :V]
        order = first.argsort(dim=1, stable=True)
        last = GraphPreparation.exact(x)
        owners = torch.full((B, V), -1, device=dev, dtype=torch.long)
        mapping = owners.clone()
        slots = torch.zeros(B, device=dev, dtype=torch.long)
        peak = slots.clone()
        reuses = slots.clone()
        error = (mem & ~valid).any(1)
        ar = torch.arange(V, device=dev)[None, :]
        for j in range(V):
            val = order[:, j:j + 1]
            pos = first.gather(1, val).squeeze(1)
            active = pos < T
            time = pos // LANES
            occupied = (owners >= 0) & (last.gather(1, owners.clamp_min(0)) >= time[:, None])
            free = ~occupied
            k = free.long().argmax(1)
            error = error | active & ~free.any(1)
            old = owners.gather(1, k[:, None]).squeeze(1)
            reuses += (active & (k < slots)).long()
            slots = torch.maximum(slots, torch.where(active, k + 1, slots))
            peak = torch.maximum(peak, torch.where(active, occupied.sum(1) + 1, peak))
            owners.scatter_(1, k[:, None], torch.where(active, val[:, 0], old)[:, None])
            mapping.scatter_(1, val, torch.where(active, k, -1)[:, None])
        homes = mapping.gather(1, safe)
        error = error | (mem & ((homes < 0) | (first.gather(1, safe) > idx) | (last.gather(1, safe) < t))).any(1)
        routed = torch.stack((op, r, torch.where(mem, homes, v)), dim=-1).reshape_as(events)
        return (routed, dict(slots=slots, distinct_spilled=(first < T).sum(1), reuses=reuses, peak_backed=peak, frame=(4 * slots + 15) // 16 * 16), error)

    def lower(self, events, metrics, capacity):
        B = events.shape[0]
        dev = events.device
        op, r, s = events.reshape(B, -1, 3).unbind(-1)
        frame = metrics['frame']
        slots = metrics['slots']
        regs = self.regmap[r.clamp(0, 14)]
        src = self.regmap[s.clamp(0, 14)]
        active = (op != 0) & (op != EID['release'])
        ret = op == EID['ret']
        count = op == EID['count']
        store = op == EID['store']
        load = op == EID['load']
        mem = store | load
        div = torch.zeros_like(active)
        signed = div.clone()
        rem = div.clone()
        for name in ('udiv', 'urem', 'sdiv', 'srem'):
            m = op == EID[name]
            div |= m
            if name.startswith('s'):
                signed |= m
            if name.endswith('rem'):
                rem |= m
        saveable = active & ~(store | ret | count)
        saved = torch.stack([((regs == k) & saveable).any(1) for k in self.callee.unbind()], 1)
        nsave = saved.sum(1)
        hasframe = frame > 0
        prefix = nsave + hasframe.long() + 1
        lengths = torch.where(active & ~ret, torch.where(div, 4, 1), 0)
        offset = lengths.cumsum(1) - lengths + prefix[:, None]
        body_end = prefix + lengths.sum(1)
        retreg = (regs * ret).sum(1)
        retmov = retreg != 0
        suffix = retmov.long() + hasframe.long() + nsave + 1
        total = body_end + suffix
        error = (total > capacity) | (ret.sum(1) != 1) | (active & ((r < 0) | (r >= 15))).any(1) | (mem & ((s < 0) | (s >= slots[:, None]))).any(1)
        buf = torch.zeros((B, capacity, 5), device=dev, dtype=torch.long)

        def emit(pos, mask, kind, a=-1, b=-1, imm=0, stack=0):
            pos = pos.reshape(B, -1)
            mask = mask.reshape_as(pos) & (pos >= 0) & (pos < capacity)

            def field(z):
                if isinstance(z, int):
                    return torch.full_like(pos, z)
                return z.reshape(B, -1).expand_as(pos)
            data = torch.stack((field(kind), field(a) + 1, field(b) + 1, field(imm), field(stack)), dim=-1)
            buf.scatter_add_(1, pos.clamp(0, capacity - 1)[..., None].expand(-1, -1, 5), data * mask[..., None])
        rank = saved.long().cumsum(1) - 1
        cr = self.callee[None, :].expand(B, -1)
        emit(rank, saved, PID['push'], cr)
        emit(nsave, hasframe, PID['frame_sub'], imm=frame)
        emit(prefix - 1, torch.ones_like(hasframe), PID['mov'], 8, 2)
        rr = torch.zeros_like(active)
        im = torch.zeros_like(active)
        shift = torch.zeros_like(active)
        for name in p.RR:
            rr |= op == EID[name]
        for name in p.IMM:
            m = op == EID[name]
            im |= m
            if name.startswith(('shl', 'shr', 'sar')):
                shift |= m
        const = op == EID['const']
        ordinary = active & ~(ret | div | count)
        k = self.ordinary[op]
        error |= (ordinary & (k == 0)).any(1)
        emit(offset, ordinary, k, regs, torch.where(rr, src, -1), torch.where(const | im, torch.where(shift, s & 31, s), 0), torch.where(mem, s * 4, 0))
        emit(offset, count, PID['mov'], 1, regs)
        emit(offset, div, PID['mov'], 0, regs)
        emit(offset + 1, div, torch.where(signed, PID['cdq'], PID['xor']), torch.where(signed, -1, 2), torch.where(signed, -1, 2))
        emit(offset + 2, div, torch.where(signed, PID['idiv'], PID['div']), src)
        emit(offset + 3, div, PID['mov'], regs, torch.where(rem, 2, 0))
        emit(body_end, retmov, PID['mov'], 0, retreg)
        post = body_end + retmov.long()
        emit(post, hasframe, PID['frame_add'], imm=frame)
        popbase = post + hasframe.long()
        emit(popbase[:, None] + nsave[:, None] - rank - 1, saved, PID['pop'], cr)
        emit(total - 1, torch.ones_like(hasframe), PID['ret'])
        return (dict(signature=buf[:, :, 0].contiguous(), register=(buf[:, :, 1:3] - 1).contiguous(), immediate=buf[:, :, 3:4].contiguous(), stack=buf[:, :, 4:5].contiguous()), total, error)

    def forward(self, x, events, capacity=None):
        capacity = capacity or 8 * x['op'].shape[1] + 32
        if capacity < 1:
            raise ValueError('positive physical capacity required')
        routed, metrics, error = self.stack(x, events)
        physical, lengths, lower_error = self.lower(routed, metrics, capacity)
        return (physical, lengths, routed, metrics, error | lower_error)