Debian Codegraph @

src/panfrost/compiler/bifrost/gen_disasm.py

raw
1 # Copyright (C) 2020 Collabora, Ltd.
2 # SPDX-License-Identifier: MIT
3
4 import sys
5 import itertools
6 from bifrost_isa import parse_instructions, opname_to_c, expand_states
7 from mako.template import Template
8
9 instructions = parse_instructions(sys.argv[1], include_unused = True)
10
11 # Constructs a reserved mask for a derived to cull impossible encodings
12
13 def reserved_mask(derived):
14 ((pos, width), opts) = derived
15 reserved = [x is None for x in opts]
16 mask = sum([(y << x) for x, y in enumerate(reserved)])
17 return (pos, width, mask)
18
19 def reserved_masks(op):
20 masks = [reserved_mask(m) for m in op[2].get("derived", [])]
21 return [m for m in masks if m[2] != 0]
22
23 # To decode instructions, pattern match based on the rules:
24 #
25 # 1. Execution unit (FMA or ADD) must line up.
26 # 2. All exact bits must match.
27 # 3. No fields should be reserved in a legal encoding.
28 # 4. Tiebreaker: Longer exact masks (greater unsigned bitwise inverses) win.
29 #
30 # To implement, filter the execution unit and check for exact bits in
31 # descending order of exact mask length. Check for reserved fields per
32 # candidate and succeed if it matches.
33 # found.
34
35 def decode_op(instructions, is_fma):
36 # Filter out the desired execution unit
37 options = [n for n in instructions.keys() if (n[0] == '*') == is_fma]
38
39 # Sort by exact masks, descending
40 MAX_MASK = (1 << (23 if is_fma else 20)) - 1
41 options.sort(key = lambda n: (MAX_MASK ^ instructions[n][2]["exact"][0]))
42
43 # Map to what we need to template
44 mapped = [(opname_to_c(op), instructions[op][2]["exact"], reserved_masks(instructions[op])) for op in options]
45
46 # Generate checks in order
47 template = """void
48 bi_disasm_${unit}(FILE *fp, unsigned bits, struct bifrost_regs *srcs, struct bifrost_regs *next_regs, unsigned staging_register, unsigned branch_offset, struct bi_constants *consts, bool last)
49 {
50 fputs(" ", fp);
51
52 % for (i, (name, (emask, ebits), derived)) in enumerate(options):
53 % if len(derived) > 0:
54 ${"else " if i > 0 else ""}if (unlikely(((bits & ${hex(emask)}) == ${hex(ebits)})
55 % for (pos, width, reserved) in derived:
56 && !(${hex(reserved)} & (1 << _BITS(bits, ${pos}, ${width})))
57 % endfor
58 ))
59 % else:
60 ${"else " if i > 0 else ""}if (unlikely(((bits & ${hex(emask)}) == ${hex(ebits)})))
61 % endif
62 bi_disasm_${name}(fp, bits, srcs, next_regs, staging_register, branch_offset, consts, last);
63 % endfor
64 else
65 fprintf(fp, "INSTR_INVALID_ENC ${unit} %X", bits);
66
67 fputs("\\n", fp);
68 }"""
69
70 return Template(template).render(options = mapped, unit = "fma" if is_fma else "add")
71
72 # Decoding emits a series of function calls to e.g. `fma_fadd_v2f16`. We need to
73 # emit functions to disassemble a single decoded instruction in a particular
74 # state. Sync prototypes to avoid moves when calling.
75
76 disasm_op_template = Template("""static void
77 bi_disasm_${c_name}(FILE *fp, unsigned bits, struct bifrost_regs *srcs, struct bifrost_regs *next_regs, unsigned staging_register, unsigned branch_offset, struct bi_constants *consts, bool last)
78 {
79 ${body.strip()}
80 }
81 """)
82
83 lut_template_only = Template(""" static const char *${field}[] = {
84 ${", ".join(['"' + x + '"' for x in table])}
85 };
86 """)
87
88 # Given a lookup table written logically, generate an accessor
89 lut_template = Template(""" static const char *${field}_table[] = {
90 ${", ".join(['"' + x + '"' for x in table])}
91 };
92
93 const char *${field} = ${field}_table[_BITS(bits, ${pos}, ${width})];
94 """)
95
96 # Helpers for decoding follow. pretty_mods applies dot syntax
97
98 def pretty_mods(opts, default):
99 return [('.' + (opt or 'reserved') if opt != default else '') for opt in opts]
100
101 # Recursively searches for the set of free variables required by an expression
102
103 def find_context_keys_expr(expr):
104 if isinstance(expr, list):
105 return set.union(*[find_context_keys_expr(x) for x in expr[1:]])
106 elif expr[0] == '#':
107 return set()
108 else:
109 return set([expr])
110
111 def find_context_keys(desc, test):
112 keys = set()
113
114 if len(test) > 0:
115 keys |= find_context_keys_expr(test)
116
117 for i, (_, vals) in enumerate(desc.get('derived', [])):
118 for j, val in enumerate(vals):
119 if val is not None:
120 keys |= find_context_keys_expr(val)
121
122 return keys
123
124 # Compiles a logic expression to Python expression, ctx -> { T, F }
125
126 EVALUATORS = {
127 'and': ' and ',
128 'or': ' or ',
129 'eq': ' == ',
130 'neq': ' != ',
131 }
132
133 def compile_derived_inner(expr, keys):
134 if expr == []:
135 return 'True'
136 elif expr is None or expr[0] == 'alias':
137 return 'False'
138 elif isinstance(expr, list):
139 args = [compile_derived_inner(arg, keys) for arg in expr[1:]]
140 return '(' + EVALUATORS[expr[0]].join(args) + ')'
141 elif expr[0] == '#':
142 return "'{}'".format(expr[1:])
143 elif expr == 'ordering':
144 return expr
145 else:
146 return "ctx[{}]".format(keys.index(expr))
147
148 def compile_derived(expr, keys):
149 return eval('lambda ctx, ordering: ' + compile_derived_inner(expr, keys))
150
151 # Generate all possible combinations of values and evaluate the derived values
152 # by bruteforce evaluation to generate a forward mapping (values -> deriveds)
153
154 def evaluate_forward_derived(vals, ctx, ordering):
155 for j, expr in enumerate(vals):
156 if expr(ctx, ordering):
157 return j
158
159 return None
160
161 def evaluate_forward(keys, derivf, testf, ctx, ordering):
162 if not testf(ctx, ordering):
163 return None
164
165 deriv = []
166
167 for vals in derivf:
168 evaled = evaluate_forward_derived(vals, ctx, ordering)
169
170 if evaled is None:
171 return None
172
173 deriv.append(evaled)
174
175 return deriv
176
177 def evaluate_forwards(keys, derivf, testf, mod_vals, ordered):
178 orderings = ["lt", "gt"] if ordered else [None]
179 return [[evaluate_forward(keys, derivf, testf, i, order) for i in itertools.product(*mod_vals)] for order in orderings]
180
181 # Invert the forward mapping (values -> deriveds) of finite sets to produce a
182 # backwards mapping (deriveds -> values), suitable for disassembly. This is
183 # possible since the encoding is unambiguous, so this mapping is a bijection
184 # (after reserved/impossible encodings)
185
186 def invert_lut(value_size, forward, derived, mod_map, keys, mod_vals):
187 backwards = [None] * (1 << value_size)
188 for (i, deriveds), ctx in zip(enumerate(forward), itertools.product(*mod_vals)):
189 # Skip reserved
190 if deriveds == None:
191 continue
192
193 shift = 0
194 param = 0
195 for j, ((x, width), y) in enumerate(derived):
196 param += (deriveds[j] << shift)
197 shift += width
198
199 assert(param not in backwards)
200 backwards[param] = ctx
201
202 return backwards
203
204 # Compute the value of all indirectly specified modifiers by using the
205 # backwards mapping (deriveds -> values) as a run-time lookup table.
206
207 def build_lut(mnemonic, desc, test):
208 # Construct the system
209 facts = []
210
211 mod_map = {}
212
213 for ((name, pos, width), default, values) in desc.get('modifiers', []):
214 mod_map[name] = (width, values, pos, default)
215
216 derived = desc.get('derived', [])
217
218 # Find the keys and impose an order
219 key_set = find_context_keys(desc, test)
220 ordered = 'ordering' in key_set
221 key_set.discard('ordering')
222 keys = sorted(list(key_set))
223
224 # Evaluate the deriveds for every possible state, forming a (state -> deriveds) map
225 testf = compile_derived(test, keys)
226 derivf = [[compile_derived(expr, keys) for expr in v] for (_, v) in derived]
227 mod_vals = [mod_map[k][1] for k in keys]
228 forward = evaluate_forwards(keys, derivf, testf, mod_vals, ordered)
229
230 # Now invert that map to get a (deriveds -> state) map
231 value_size = sum([width for ((x, width), y) in derived])
232 backwards = [invert_lut(value_size, f, derived, mod_map, keys, mod_vals) for f in forward]
233
234 # From that map, we can generate LUTs
235 output = ""
236
237 if ordered:
238 output += "bool ordering = (_BITS(bits, {}, 3) > _BITS(bits, {}, 3));\n".format(desc["srcs"][0][0], desc["srcs"][1][0])
239
240 for j, key in enumerate(keys):
241 # Only generate tables for indirect specifiers
242 if mod_map[key][2] is not None:
243 continue
244
245 idx_parts = []
246 shift = 0
247
248 for ((pos, width), _) in derived:
249 idx_parts.append("(_BITS(bits, {}, {}) << {})".format(pos, width, shift))
250 shift += width
251
252 built_idx = (" | ".join(idx_parts)) if len(idx_parts) > 0 else "0"
253
254 default = mod_map[key][3]
255
256 if ordered:
257 for i, order in enumerate(backwards):
258 options = [ctx[j] if ctx is not None and ctx[j] is not None else "reserved" for ctx in order]
259 output += lut_template_only.render(field = key + "_" + str(i), table = pretty_mods(options, default))
260
261 output += " const char *{} = ordering ? {}_1[{}] : {}_0[{}];\n".format(key, key, built_idx, key, built_idx)
262 else:
263 options = [ctx[j] if ctx is not None and ctx[j] is not None else "reserved" for ctx in backwards[0]]
264 output += lut_template_only.render(field = key + "_table", table = pretty_mods(options, default))
265 output += " const char *{} = {}_table[{}];\n".format(key, key, built_idx)
266
267 return output
268
269 def disasm_mod(mod, skip_mods):
270 if mod[0][0] in skip_mods:
271 return ''
272 else:
273 return ' fputs({}, fp);\n'.format(mod[0][0])
274
275 def disasm_op(name, op):
276 (mnemonic, test, desc) = op
277 is_fma = mnemonic[0] == '*'
278
279 # Modifiers may be either direct (pos is not None) or indirect (pos is
280 # None). If direct, we just do the bit lookup. If indirect, we use a LUT.
281
282 body = ""
283 skip_mods = []
284
285 body += build_lut(mnemonic, desc, test)
286
287 for ((mod, pos, width), default, opts) in desc.get('modifiers', []):
288 if pos is not None:
289 body += lut_template.render(field = mod, table = pretty_mods(opts, default), pos = pos, width = width) + "\n"
290
291 # Mnemonic, followed by modifiers
292 body += ' fputs("{}", fp);\n'.format(mnemonic)
293
294 srcs = desc.get('srcs', [])
295
296 for mod in desc.get('modifiers', []):
297 # Skip per-source until next block
298 if mod[0][0][-1] in "0123" and int(mod[0][0][-1]) < len(srcs):
299 continue
300
301 body += disasm_mod(mod, skip_mods)
302
303 body += ' fputs(" ", fp);\n'
304 body += ' bi_disasm_dest_{}(fp, next_regs, last);\n'.format('fma' if is_fma else 'add')
305
306 # Next up, each source. Source modifiers are inserterd here
307
308 for i, (pos, mask) in enumerate(srcs):
309 body += ' fputs(", ", fp);\n'
310 body += ' dump_src(fp, _BITS(bits, {}, 3), *srcs, branch_offset, consts, {});\n'.format(pos, "true" if is_fma else "false")
311
312 # Error check if needed
313 if (mask != 0xFF):
314 body += ' if (!({} & (1 << _BITS(bits, {}, 3)))) fputs("(INVALID)", fp);\n'.format(hex(mask), pos, 3)
315
316 # Print modifiers suffixed with this src number (e.g. abs0 for src0)
317 for mod in desc.get('modifiers', []):
318 if mod[0][0][-1] == str(i):
319 body += disasm_mod(mod, skip_mods)
320
321 # And each immediate
322 for (imm, pos, width) in desc.get('immediates', []):
323 body += ' fprintf(fp, ", {}:%u", _BITS(bits, {}, {}));\n'.format(imm, pos, width)
324
325 # Attach a staging register if one is used
326 if desc.get('staging'):
327 body += ' fprintf(fp, ", @r%u", staging_register);\n'
328
329 return disasm_op_template.render(c_name = opname_to_c(name), body = body)
330
331 print('#include "util/macros.h"')
332 print('#include "bifrost/disassemble.h"')
333 print('#include "bifrost/bi_disasm.h"')
334 print('#include "bifrost.h"')
335
336 states = expand_states(instructions)
337 print('#define _BITS(bits, pos, width) (((bits) >> (pos)) & ((1 << (width)) - 1))')
338
339 for st in states:
340 print(disasm_op(st, states[st]))
341
342 print(decode_op(states, True))
343 print(decode_op(states, False))