| 1 |
# Copyright (C) 2020 Collabora, Ltd. |
| 2 |
# SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
import sys |
| 5 |
from bifrost_isa import * |
| 6 |
from functools import reduce |
| 7 |
from mako.template import Template |
| 8 |
|
| 9 |
# Consider pseudo instructions when getting the modifier list |
| 10 |
instructions_with_pseudo = {} |
| 11 |
for arg in sys.argv[1:]: |
| 12 |
new_instructions = parse_instructions(arg, include_pseudo = True) |
| 13 |
instructions_with_pseudo.update(new_instructions) |
| 14 |
|
| 15 |
ir_instructions_with_pseudo = partition_mnemonics(instructions_with_pseudo) |
| 16 |
modifier_lists = order_modifiers(ir_instructions_with_pseudo) |
| 17 |
|
| 18 |
# ...but strip for packing |
| 19 |
instructions = parse_instructions(sys.argv[2]) # skip the pseudo instructions in sys.argv[1] |
| 20 |
ir_instructions = partition_mnemonics(instructions) |
| 21 |
|
| 22 |
# Packs sources into an argument. Offset argument to work around a quirk of our |
| 23 |
# compiler IR when dealing with staging registers (TODO: reorder in the IR to |
| 24 |
# fix this) |
| 25 |
def pack_sources(sources, body, pack_exprs, offset, is_fma): |
| 26 |
for i, src in enumerate(sources): |
| 27 |
# FMA first two args are restricted, but that's checked once for all |
| 28 |
# FMA so the compiler has less work to do |
| 29 |
expected = 0xFB if (is_fma and i < 2) else 0xFF |
| 30 |
|
| 31 |
# Validate the source |
| 32 |
if src[1] != expected: |
| 33 |
assert((src[1] & expected) == src[1]) |
| 34 |
body.append('assert((1 << src{}) & {});'.format(i, hex(src[1]))) |
| 35 |
|
| 36 |
# Sources are state-invariant |
| 37 |
for state in pack_exprs: |
| 38 |
state.append('(src{} << {})'.format(i, src[0])) |
| 39 |
|
| 40 |
# Try to map from a modifier list `domain` to the list `target` |
| 41 |
def map_modifier(body, prefix, mod, domain, target): |
| 42 |
# We don't want to map reserveds, that's invalid IR anyway |
| 43 |
def reserved_to_none(arr): |
| 44 |
return [None if x == 'reserved' else x for x in arr] |
| 45 |
|
| 46 |
# Trim out reserveds at the end |
| 47 |
noned_domain = reserved_to_none(domain) |
| 48 |
noned_target = reserved_to_none(target) |
| 49 |
none_indices = [i for i, x in enumerate(noned_target) if x != None] |
| 50 |
trimmed = noned_target[0: none_indices[-1] + 1] |
| 51 |
|
| 52 |
if trimmed == noned_domain[0:len(trimmed)]: |
| 53 |
# Identity map, possibly on the left subset |
| 54 |
return mod |
| 55 |
else: |
| 56 |
# Generate a table as a fallback |
| 57 |
table = ", ".join([str(target.index(x)) if x in target else "~0" for x in domain]) |
| 58 |
body.append("static uint8_t {}_table[] = {{ {} }};".format(prefix, table)) |
| 59 |
|
| 60 |
if len(domain) > 2: |
| 61 |
# no need to validate bools |
| 62 |
body.append("assert({} < {});".format(mod, len(domain))) |
| 63 |
|
| 64 |
return "{}_table[{}]".format(prefix, mod) |
| 65 |
|
| 66 |
SRC_SWIZZLE_BUCKETS = [ |
| 67 |
set(['h00', 'h0', 'b0101']), |
| 68 |
set(['h01', 'none', 'b0123']), # Identity |
| 69 |
set(['h10', 'b2301']), |
| 70 |
set(['h11', 'h1', 'b2323']), |
| 71 |
set(['b0000', 'b00', 'b0']), |
| 72 |
set(['b1111', 'b11', 'b1']), |
| 73 |
set(['b2222', 'b22', 'b2']), |
| 74 |
set(['b3333', 'b33', 'b3']), |
| 75 |
set(['b0011', 'b01']), |
| 76 |
set(['b2233', 'b23']), |
| 77 |
set(['b1032']), |
| 78 |
set(['b3210']), |
| 79 |
set(['b0022', 'b02']), |
| 80 |
set(['b1100', 'b10']), |
| 81 |
set(['b2200', 'b20']), |
| 82 |
set(['b3300', 'b30']), |
| 83 |
set(['b2211', 'b21']), |
| 84 |
set(['b3311', 'b31']), |
| 85 |
set(['b1122', 'b12']), |
| 86 |
set(['b3322', 'b32']), |
| 87 |
set(['b0033', 'b03']), |
| 88 |
set(['b1133', 'b13']), |
| 89 |
] |
| 90 |
|
| 91 |
DST_SWIZZLE_BUCKETS = [ |
| 92 |
set(['h0',]), |
| 93 |
set(['none', 'w0']), # Identity |
| 94 |
set([]), |
| 95 |
set(['h1']), |
| 96 |
set(['b0']), |
| 97 |
set(['b1']), |
| 98 |
set(['b2']), |
| 99 |
set(['b3']), |
| 100 |
] |
| 101 |
|
| 102 |
ALL_SRC_SWIZZLES = reduce(lambda x, y: x | y, SRC_SWIZZLE_BUCKETS) |
| 103 |
ALL_DST_SWIZZLES = reduce(lambda x, y: x | y, DST_SWIZZLE_BUCKETS) |
| 104 |
|
| 105 |
def pick_from_bucket(opts, bucket): |
| 106 |
intersection = set(opts) & bucket |
| 107 |
assert(len(intersection) <= 1) |
| 108 |
return intersection.pop() if len(intersection) == 1 else None |
| 109 |
|
| 110 |
def src_swizzle_to_mod_map(opts): |
| 111 |
for opt in opts: |
| 112 |
assert opt == 'reserved' or opt in ALL_SRC_SWIZZLES, opt |
| 113 |
return [pick_from_bucket(opts, bucket) for bucket in SRC_SWIZZLE_BUCKETS] |
| 114 |
|
| 115 |
def dst_swizzle_to_mod_map(opts): |
| 116 |
for opt in opts: |
| 117 |
assert opt in ['reserved', 'd0'] or opt in ALL_DST_SWIZZLES, opt |
| 118 |
return [pick_from_bucket(opts, bucket) for bucket in DST_SWIZZLE_BUCKETS] |
| 119 |
|
| 120 |
def pack_modifier(mod, width, default, opts, body, pack_exprs): |
| 121 |
# Destructure the modifier name |
| 122 |
(raw, arg) = (mod[0:-1], mod[-1]) if mod[-1] in "0123" else (mod, 0) |
| 123 |
|
| 124 |
SWIZZLES = ["lane", "lanes", "replicate", "swz", "widen", "swap"] |
| 125 |
|
| 126 |
ir_value = "bytes2" if mod == "bytes2" else "{}[{}]".format(raw, arg) if mod[-1] in "0123" else mod |
| 127 |
lists = modifier_lists[raw] |
| 128 |
|
| 129 |
# Swizzles need to be packed "specially" |
| 130 |
if raw in SWIZZLES: |
| 131 |
# Construct a list |
| 132 |
lists = src_swizzle_to_mod_map(opts) |
| 133 |
ir_value = "src[{}].swizzle".format(arg) |
| 134 |
elif raw == "lane_dest": |
| 135 |
lists = dst_swizzle_to_mod_map(opts) |
| 136 |
ir_value = "dest->swizzle" |
| 137 |
elif raw in ["abs", "sign"]: |
| 138 |
ir_value = "src[{}].abs".format(arg) |
| 139 |
elif raw in ["neg", "not"]: |
| 140 |
ir_value = "src[{}].neg".format(arg) |
| 141 |
|
| 142 |
ir_value = "I->{}".format(ir_value) |
| 143 |
|
| 144 |
# We need to map from ir_opts to opts |
| 145 |
mapped = map_modifier(body, mod, ir_value, lists, opts) |
| 146 |
body.append('unsigned {} = {};'.format(mod, mapped)) |
| 147 |
body.append('assert({} < {});'.format(mod, 1 << width)) |
| 148 |
|
| 149 |
# Compiles an S-expression (and/or/eq/neq, modifiers, `ordering`, immediates) |
| 150 |
# into a C boolean expression suitable to stick in an if-statement. Takes an |
| 151 |
# imm_map to map modifiers to immediate values, parametrized by the ctx that |
| 152 |
# we're looking up in (the first, non-immediate argument of the equality) |
| 153 |
|
| 154 |
SEXPR_BINARY = { |
| 155 |
"and": "&&", |
| 156 |
"or": "||", |
| 157 |
"eq": "==", |
| 158 |
"neq": "!=" |
| 159 |
} |
| 160 |
|
| 161 |
def compile_s_expr(expr, imm_map, ctx): |
| 162 |
if expr[0] == 'alias': |
| 163 |
return compile_s_expr(expr[1], imm_map, ctx) |
| 164 |
elif expr == ['eq', 'ordering', '#gt']: |
| 165 |
return '(src0 > src1)' |
| 166 |
elif expr == ['neq', 'ordering', '#lt']: |
| 167 |
return '(src0 >= src1)' |
| 168 |
elif expr == ['neq', 'ordering', '#gt']: |
| 169 |
return '(src0 <= src1)' |
| 170 |
elif expr == ['eq', 'ordering', '#lt']: |
| 171 |
return '(src0 < src1)' |
| 172 |
elif expr == ['eq', 'ordering', '#eq']: |
| 173 |
return '(src0 == src1)' |
| 174 |
elif isinstance(expr, list): |
| 175 |
sep = " {} ".format(SEXPR_BINARY[expr[0]]) |
| 176 |
return "(" + sep.join([compile_s_expr(s, imm_map, expr[1]) for s in expr[1:]]) + ")" |
| 177 |
elif expr[0] == '#': |
| 178 |
return str(imm_map[ctx][expr[1:]]) |
| 179 |
else: |
| 180 |
return expr |
| 181 |
|
| 182 |
# Packs a derived value. We just iterate through the possible choices and test |
| 183 |
# whether the encoding matches, and if so we use it. |
| 184 |
|
| 185 |
def pack_derived(pos, exprs, imm_map, body, pack_exprs): |
| 186 |
body.append('unsigned derived_{} = 0;'.format(pos)) |
| 187 |
|
| 188 |
first = True |
| 189 |
for i, expr in enumerate(exprs): |
| 190 |
if expr is not None: |
| 191 |
cond = compile_s_expr(expr, imm_map, None) |
| 192 |
body.append('{}if {} derived_{} = {};'.format('' if first else 'else ', cond, pos, i)) |
| 193 |
first = False |
| 194 |
|
| 195 |
assert (not first) |
| 196 |
body.append('else UNREACHABLE("No pattern match at pos {}");'.format(pos)) |
| 197 |
body.append('') |
| 198 |
|
| 199 |
assert(pos is not None) |
| 200 |
pack_exprs.append('(derived_{} << {})'.format(pos, pos)) |
| 201 |
|
| 202 |
# Generates a routine to pack a single variant of a single- instruction. |
| 203 |
# Template applies the needed formatting and combine to OR together all the |
| 204 |
# pack_exprs to avoid bit fields. |
| 205 |
# |
| 206 |
# Argument swapping is sensitive to the order of operations. Dependencies: |
| 207 |
# sources (RW), modifiers (RW), derived values (W). Hence we emit sources and |
| 208 |
# modifiers first, then perform a swap if necessary overwriting |
| 209 |
# sources/modifiers, and last calculate derived values and pack. |
| 210 |
|
| 211 |
variant_template = Template("""static inline unsigned |
| 212 |
bi_pack_${name}(${", ".join(["bi_instr *I"] + ["enum bifrost_packed_src src{}".format(i) for i in range(srcs)])}) |
| 213 |
{ |
| 214 |
${"\\n".join([(" " + x) for x in common_body])} |
| 215 |
% if single_state: |
| 216 |
% for (pack_exprs, s_body, _) in states: |
| 217 |
${"\\n".join([" " + x for x in s_body + ["return {};".format( " | ".join(pack_exprs))]])} |
| 218 |
% endfor |
| 219 |
% else: |
| 220 |
% for i, (pack_exprs, s_body, cond) in enumerate(states): |
| 221 |
${'} else ' if i > 0 else ''}if ${cond} { |
| 222 |
${"\\n".join([" " + x for x in s_body + ["return {};".format(" | ".join(pack_exprs))]])} |
| 223 |
% endfor |
| 224 |
} else { |
| 225 |
UNREACHABLE("No matching state found in ${name}"); |
| 226 |
} |
| 227 |
% endif |
| 228 |
} |
| 229 |
""") |
| 230 |
|
| 231 |
def pack_variant(opname, states): |
| 232 |
# Expressions to be ORed together for the final pack, an array per state |
| 233 |
pack_exprs = [[hex(state[1]["exact"][1])] for state in states] |
| 234 |
|
| 235 |
# Computations which need to be done to encode first, across states |
| 236 |
common_body = [] |
| 237 |
|
| 238 |
# Map from modifier names to a map from modifier values to encoded values |
| 239 |
# String -> { String -> Uint }. This can be shared across states since |
| 240 |
# modifiers are (except the pos values) constant across state. |
| 241 |
imm_map = {} |
| 242 |
|
| 243 |
# Pack sources. Offset over to deal with staging/immediate weirdness in our |
| 244 |
# IR (TODO: reorder sources upstream so this goes away). Note sources are |
| 245 |
# constant across states. |
| 246 |
staging = states[0][1].get("staging", "") |
| 247 |
offset = 0 |
| 248 |
if staging in ["r", "rw"]: |
| 249 |
offset += 1 |
| 250 |
|
| 251 |
pack_sources(states[0][1].get("srcs", []), common_body, pack_exprs, offset, opname[0] == '*') |
| 252 |
|
| 253 |
modifiers_handled = [] |
| 254 |
for st in states: |
| 255 |
for ((mod, _, width), default, opts) in st[1].get("modifiers", []): |
| 256 |
if mod in modifiers_handled: |
| 257 |
continue |
| 258 |
|
| 259 |
modifiers_handled.append(mod) |
| 260 |
pack_modifier(mod, width, default, opts, common_body, pack_exprs) |
| 261 |
|
| 262 |
imm_map[mod] = { x: y for y, x in enumerate(opts) } |
| 263 |
|
| 264 |
for i, st in enumerate(states): |
| 265 |
for ((mod, pos, width), default, opts) in st[1].get("modifiers", []): |
| 266 |
if pos is not None: |
| 267 |
pack_exprs[i].append('({} << {})'.format(mod, pos)) |
| 268 |
|
| 269 |
for ((src_a, src_b), cond, remap) in st[1].get("swaps", []): |
| 270 |
# Figure out which vars to swap, in order to swap the arguments. This |
| 271 |
# always includes the sources themselves, and may include source |
| 272 |
# modifiers (with the same source indices). We swap based on which |
| 273 |
# matches A, this is arbitrary but if we swapped both nothing would end |
| 274 |
# up swapping at all since it would swap back. |
| 275 |
|
| 276 |
vars_to_swap = ['src'] |
| 277 |
for ((mod, _, width), default, opts) in st[1].get("modifiers", []): |
| 278 |
if mod[-1] in str(src_a): |
| 279 |
vars_to_swap.append(mod[0:-1]) |
| 280 |
|
| 281 |
common_body.append('if {}'.format(compile_s_expr(cond, imm_map, None)) + ' {') |
| 282 |
|
| 283 |
# Emit the swaps. We use a temp, and wrap in a block to avoid naming |
| 284 |
# collisions with multiple swaps. {{Doubling}} to escape the format. |
| 285 |
|
| 286 |
for v in vars_to_swap: |
| 287 |
common_body.append(' {{ unsigned temp = {}{}; {}{} = {}{}; {}{} = temp; }}'.format(v, src_a, v, src_a, v, src_b, v, src_b)) |
| 288 |
|
| 289 |
# Also, remap. Bidrectional swaps are explicit in the XML. |
| 290 |
for v in remap: |
| 291 |
maps = remap[v] |
| 292 |
imm = imm_map[v] |
| 293 |
|
| 294 |
for i, l in enumerate(maps): |
| 295 |
common_body.append(' {}if ({} == {}) {} = {};'.format('' if i == 0 else 'else ', v, imm[l], v, imm[maps[l]])) |
| 296 |
|
| 297 |
common_body.append('}') |
| 298 |
common_body.append('') |
| 299 |
|
| 300 |
for (name, pos, width) in st[1].get("immediates", []): |
| 301 |
common_body.append('unsigned {} = I->{};'.format(name, name)) |
| 302 |
common_body.append('assert({} < {});'.format(name, hex(1 << width))) |
| 303 |
|
| 304 |
for st in pack_exprs: |
| 305 |
st.append('({} << {})'.format(name, pos)) |
| 306 |
|
| 307 |
# After this, we have to branch off, since deriveds *do* vary based on state. |
| 308 |
state_body = [[] for s in states] |
| 309 |
|
| 310 |
for i, (_, st) in enumerate(states): |
| 311 |
for ((pos, width), exprs) in st.get("derived", []): |
| 312 |
pack_derived(pos, exprs, imm_map, state_body[i], pack_exprs[i]) |
| 313 |
|
| 314 |
# How do we pick a state? Accumulate the conditions |
| 315 |
state_conds = [compile_s_expr(st[0], imm_map, None) for st in states] if len(states) > 1 else [None] |
| 316 |
|
| 317 |
if state_conds == None: |
| 318 |
assert (states[0][0] == None) |
| 319 |
|
| 320 |
# Finally, we'll collect everything together |
| 321 |
return variant_template.render(name = opname_to_c(opname), states = zip(pack_exprs, state_body, state_conds), common_body = common_body, single_state = (len(states) == 1), srcs = 4) |
| 322 |
|
| 323 |
print(COPYRIGHT + '#include "compiler.h"') |
| 324 |
|
| 325 |
for i, bucket in enumerate(SRC_SWIZZLE_BUCKETS): |
| 326 |
for swz in bucket: |
| 327 |
bi_swz = 'BI_SWIZZLE_' + swz.upper() |
| 328 |
print(f'static_assert({bi_swz} == {i}, "Swizzle sanity");') |
| 329 |
|
| 330 |
packs = [pack_variant(e, instructions[e]) for e in instructions] |
| 331 |
for p in packs: |
| 332 |
print(p) |
| 333 |
|
| 334 |
top_pack = Template("""unsigned |
| 335 |
bi_pack_${'fma' if unit == '*' else 'add'}(bi_instr *I, |
| 336 |
enum bifrost_packed_src src0, |
| 337 |
enum bifrost_packed_src src1, |
| 338 |
enum bifrost_packed_src src2, |
| 339 |
enum bifrost_packed_src src3) |
| 340 |
{ |
| 341 |
if (!I) |
| 342 |
return bi_pack_${opname_to_c(unit + 'NOP')}(I, src0, src1, src2, src3); |
| 343 |
|
| 344 |
% if unit == '*': |
| 345 |
assert((1 << src0) & 0xfb); |
| 346 |
assert((1 << src1) & 0xfb); |
| 347 |
|
| 348 |
% endif |
| 349 |
switch (I->op) { |
| 350 |
% for opcode in ops: |
| 351 |
% if unit + opcode in instructions: |
| 352 |
case BI_OPCODE_${opcode.replace('.', '_').upper()}: |
| 353 |
return bi_pack_${opname_to_c(unit + opcode)}(I, src0, src1, src2, src3); |
| 354 |
% endif |
| 355 |
% endfor |
| 356 |
default: |
| 357 |
#ifndef NDEBUG |
| 358 |
bi_print_instr(I, stderr); |
| 359 |
#endif |
| 360 |
UNREACHABLE("Cannot pack instruction as ${unit}"); |
| 361 |
} |
| 362 |
} |
| 363 |
""") |
| 364 |
|
| 365 |
for unit in ['*', '+']: |
| 366 |
print(top_pack.render(ops = ir_instructions, instructions = instructions, opname_to_c = opname_to_c, unit = unit)) |