Skip to content
Merged
2 changes: 1 addition & 1 deletion docs/design.md

Large diffs are not rendered by default.

9 changes: 7 additions & 2 deletions docs/shader_library.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,13 @@ What stops the rest, by the translator's message:
`gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. The translator
now decodes these words from the blob with `rdna2_decode` (`restore_vcc_tuples`) and reads them as the
`[s100,...,vcc_lo,vcc_hi]` lists it already takes (design.md *Scalar/buffer memory*); synthetic cases are in
`tests/semantic/test_vcc_tuple_fallback.py`. The count above was measured before this change; it has not been
re-run on the real library.
`tests/semantic/test_vcc_tuple_fallback.py`. The junk llvm-mc prints at such a word's second dword is often longer
than that dword (an 8-byte `exp`, say) and swallows the instruction after the tuple too, so the words after a restored
instruction are decoded from the blob until the stream is back at one llvm-mc printed. A word llvm-mc itself rejected
is not taken for swallowed code and stays refused. They are decoded for the program's own wave size: in wave64 a
swallowed VOP3 compare writes an SGPR pair. The table above was measured before both changes. Measured since,
over the 2,684 compute programs (llvm-mc 21.1.8): 1,816 translate with the tuples alone and 2,567 with the swallowed
instructions, all of which pass `spirv-val`; the modules of the 1,816 are byte-identical.
* **443: an instruction llvm-mc prints with another encoding than the blob's** (`v_fma_mix*`, `v_interp_p2_f16`):
the existing `check_printed_encodings` refusal.
* **90 CS: "CS thread-group-size SGPR"**: RSRC2 `TG_SIZE_EN`, which no FSSM compute shader sets.
Expand Down
7 changes: 4 additions & 3 deletions tests/semantic/test_library_compute_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def test_short_prologue_has_two_literals(self):

def test_recovered_vcc_tuple(self):
code = raw_words(fixture("vcc_tuple_word"))
self.assertEqual(rdna2spirv.restore_skipped_instructions([], code, 0, len(code))[0]["args"][0]["r"],
self.assertEqual(rdna2spirv.restore_vcc_tuples([], code, 0, len(code))[0]["args"][0]["r"],
[104, 105, "vcc_lo", "vcc_hi"])

def run_wave32(self, name, memory):
Expand Down Expand Up @@ -94,8 +94,9 @@ def test_vopc_dpp_encoded_fields_and_recovery(self):
self.assertEqual((row["op"], row["args"][0]["t"], row["args"][1]["r"], row["args"][2]["r"]),
("v_cmp_gt_f32_dpp", "vcc_lo" if wave32 else "vcc", 7, 12))
self.assertIn(control, row["mods"])
junk = {"pc": 4, "enc": blob[4:].hex()}
recovered, = rdna2spirv.restore_skipped_instructions([junk], blob, 0, len(blob))
# a listing entry as llvm-mc prints the second word: restore_vcc_tuples reads its op, as it does a real one
junk = {"pc": 4, "enc": blob[4:].hex(), "op": "s_nop", "args": [{"k": "imm", "v": 0}], "mods": []}
recovered, = rdna2spirv.restore_vcc_tuples([junk], blob, 0, len(blob), wave32=wave32)
self.assertEqual((recovered["pc"], recovered["enc"]), (0, blob.hex()))
self.assertFalse(rdna2_decode.decode_bytes(blob[:4])["insns"])

Expand Down
226 changes: 223 additions & 3 deletions tests/semantic/test_vcc_tuple_fallback.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,11 @@ def listing_and_blob(program, variant="invalid"):
if text is not None:
lines.append(f"\t{text:<40}{encoding(raw)}")
continue
second = bytes.fromhex(raw)[4:8]
raw_bytes = bytes.fromhex(raw)
lines.append(INVALID)
if len(raw_bytes) == 4:
continue
second = raw_bytes[4:8]
if variant == "invalid":
lines.append(INVALID)
elif variant == "junk": # the second word decodes as an instruction of its own, bytes as stored
Expand Down Expand Up @@ -136,6 +139,65 @@ def test_image_resource_in_vcc(self):
with self.subTest(printed_as=variant):
self.assertIn("OpFunctionCall %uint %desc_lookup_fn", translate(program, variant))

def test_junk_that_swallows_the_next_instructions(self):
# The junk at the tuple's second word is longer than that word, so it covers the s_mov_b32 after the tuple
# (and the first word of the 8-byte one after that, whose literal then prints as junk too). None of them is
# printed at its own place; all of them are decoded from the blob.
literal = ("s_mov_b32 s11, 0x12345678", "ff 03 8b be 78 56 34 12")
swallowed = ("s_mov_b32 s10, s4", "04 03 8a be")
tail = [WAIT, ("v_mov_b32_e32 v10, s100", "64 02 14 7e"), ("v_mov_b32_e32 v11, vcc_hi", "6b 02 16 7e"),
("v_mov_b32_e32 v12, s10", "0a 02 18 7e"), ("v_mov_b32_e32 v13, s11", "0b 02 1a 7e")] + STORE_X4
program = SET_SGPR_V + [(None, LOAD_X8_VCC), swallowed, literal] + tail
hidden = bytes.fromhex(LOAD_X8_VCC)[4:] + bytes.fromhex(swallowed[1]) + bytes.fromhex(literal[1])
# an exp whose ignored bits are set is printed with other bytes than the blob holds
normalized = bytes.fromhex("60 0d 00 f8 00 00 00 00")
for name, junk in (("8 bytes", [hidden[:8]]), ("12 bytes, then 4", [hidden[:12], hidden[12:]]),
("8 bytes, normalized", [normalized])):
with self.subTest(junk=name):
data, blob = listing_and_blob(program)
lines = data.decode().splitlines()
first = next(i for i, line in enumerate(lines) if line == INVALID)
after = [] if sum(map(len, junk)) > 8 else lines[first + 3:first + 4]
lines[first:first + 4] = [INVALID] + [f"\ts_nop 0{'':<33}" + encoding(j.hex()) for j in junk] + after
spv = translate_listing(NAME, ("\n".join(lines) + "\n").encode(), fssm=blob)
mem = run(spv, {BASE + 4 * i: 0x11110000 + i for i in range(8)})
self.assertEqual([mem.get(OUT + 4 * i) for i in range(4)],
[0x11110000, 0x11110007, 0x1000, 0x12345678])

def test_swallowed_compare_in_wave64_writes_a_pair(self):
# The junk exp covers the tuple's second word and the compare's first; the compare's second prints on its own.
program = SET_SGPR_V + [
("s_mov_b32 s12, 0", "80 03 8c be"), ("s_mov_b32 s13, 0", "80 03 8d be"),
(None, LOAD_X8_VCC),
("v_cmp_gt_u32_e64 s[12:13], 40, v0", "0c 00 c4 d4 a8 00 02 00"),
WAIT,
("s_bcnt1_i32_b64 s10, s[12:13]", "0c 10 8a be"),
("v_mov_b32_e32 v10, s10", "0a 02 14 7e"),
("v_lshlrev_b32_e32 v6, 2, v0", "82 00 0c 34"),
("v_add_nc_u32_e32 v6, 0x3000, v6", "ff 0c 0c 4a 00 30 00 00"),
("global_store_dword v6, v10, s[0:1]", "00 80 70 dc 06 0a 00 00"),
("s_endpgm", "00 00 81 bf"),
]
data, blob = listing_and_blob(program)
blob = bytearray(blob)
struct.pack_into("<4I", blob, 0x138, 0x88, 64, 1, 1)
struct.pack_into("<I", blob, fssm_header.WAVE_FLAGS_OFFSET, 0) # wave64
lines = data.decode().splitlines()
first = lines.index(INVALID)
lines[first:first + 3] = [INVALID, "\texp mrt0 v0, v0, v0, v0 done vm " + encoding("0f 18 00 f8 00 00 00 00"),
f"\ts_nop 0{'':<33}" + encoding("a8 00 02 00")]
spv = translate_listing(NAME, ("\n".join(lines) + "\n").encode(), fssm=bytes(blob))
mem = {BASE + 4 * i: 0 for i in range(8)}
si.run_workgroup(spv, 64, 64, inputs_for=lambda i: {
"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, push_constants=[0] * 36, memory=mem)
self.assertEqual([mem.get(OUT + 4 * i) for i in range(64)], [0x28] * 64)

def test_rejected_word_after_a_tuple_is_still_refused(self):
# inside no printed instruction: llvm-mc rejected the word itself, so it is not taken for swallowed code
program = SET_SGPR_V + [(None, LOAD_X8_VCC), (None, "04 03 8a be 04 03 8a be"), WAIT] + STORE_X4
with self.assertRaisesRegex(rdna2spirv.Unsupported, "fall-through into undecodable words"):
translate(program)

def test_other_undecodable_words_are_still_refused(self):
# SHADER-813: a rejected word that is not a tuple into vcc (sdata 112, not a register) stays undecodable,
# and the code that runs into it is refused
Expand All @@ -147,11 +209,169 @@ def test_other_undecodable_words_are_still_refused(self):
def test_nsa_mimg_with_vcc_tuple_does_not_read_past_code_end(self):
# A 12-byte NSA1 image_load whose 3rd dword lies past code_end must not be restored across stop.
mimg_nsa1 = bytes.fromhex("0a 1f 00 f0 01 04 19 00 02 00 00 00")
self.assertEqual(rdna2spirv.restore_skipped_instructions([], mimg_nsa1, 0, 8), [])
restored = rdna2spirv.restore_skipped_instructions([], mimg_nsa1, 0, 12)
self.assertEqual(rdna2spirv.restore_vcc_tuples([], mimg_nsa1, 0, 8), [])
restored = rdna2spirv.restore_vcc_tuples([], mimg_nsa1, 0, 12)
self.assertEqual(len(restored), 1)
self.assertEqual((restored[0]["pc"], len(restored[0]["enc"]) // 2), (0, 12))

def test_skipped_data_word_before_branch_target_is_not_restored(self):
# An unreachable data word skipped by s_branch whose bytes equal the first dword of a vcc-tuple load must
# not be restored across the branch target instruction that immediately follows it.
program = SET_SGPR_V + [
("s_branch 1", "01 00 82 bf"),
(None, "02 19 2c f4"),
("v_mov_b32_e32 v10, 7", "87 02 14 7e"),
("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"),
("global_store_dword v6, v10, s[0:1]", "00 80 70 dc 06 0a 00 00"),
("s_endpgm", "00 00 81 bf"),
]
mem = run(translate(program), {})
self.assertEqual(mem.get(OUT), 7)

def test_skipped_data_word_before_branch_target_vcc_load(self):
# Same skipped data word right before a real vcc-tuple load at the branch target: the data word is skipped
# and the real vcc-tuple load at the target is restored cleanly across all three listing variants.
program = SET_SGPR_V + [
("s_branch 1", "01 00 82 bf"),
(None, "02 19 2c f4"),
(None, LOAD_X8_VCC), WAIT,
("v_mov_b32_e32 v10, s100", "64 02 14 7e"), ("v_mov_b32_e32 v11, s105", "69 02 16 7e"),
("v_mov_b32_e32 v12, vcc_lo", "6a 02 18 7e"), ("v_mov_b32_e32 v13, vcc_hi", "6b 02 1a 7e"),
] + STORE_X4
words = [0x22220000 + i for i in range(8)]
for variant in PROGRAM_VARIANTS:
with self.subTest(printed_as=variant):
mem = run(translate(program, variant), {BASE + 4 * i: w for i, w in enumerate(words)})
self.assertEqual([mem.get(OUT + 4 * i) for i in range(4)], [words[0], words[5], words[6], words[7]])

def test_data_word_after_endpgm_before_branch_target_is_not_restored(self):
# An unreachable data word after s_endpgm right before a branch target is likewise ignored.
program = SET_SGPR_V + [
("s_cmp_eq_i32 s4, s4", "04 04 00 bf"),
("s_cbranch_scc1 2", "02 00 85 bf"),
("s_endpgm", "00 00 81 bf"),
(None, "02 19 2c f4"),
("v_mov_b32_e32 v10, 7", "87 02 14 7e"),
("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"),
("global_store_dword v6, v10, s[0:1]", "00 80 70 dc 06 0a 00 00"),
("s_endpgm", "00 00 81 bf"),
]
mem = run(translate(program), {})
self.assertEqual(mem.get(OUT), 7)

def test_fallthrough_into_data_word_before_branch_target_refused(self):
# When fall-through reaches a data word equal to the first dword of a vcc-tuple load right before a branch
# target, restore_vcc_tuples must not swallow the branch target; reachable_code refuses the fall-through.
program = SET_SGPR_V + [
("s_cmp_eq_i32 s4, s4", "04 04 00 bf"),
("s_cbranch_scc1 1", "01 00 85 bf"),
(None, "02 19 2c f4"),
("v_mov_b32_e32 v10, 7", "87 02 14 7e"),
("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"),
("global_store_dword v6, v10, s[0:1]", "00 80 70 dc 06 0a 00 00"),
("s_endpgm", "00 00 81 bf"),
]
with self.assertRaisesRegex(rdna2spirv.Unsupported, "fall-through into undecodable words"):
translate(program)


class ResyncTest(unittest.TestCase):
"""restore_vcc_tuples on hand-built instruction lists: where the words after a restored tuple are decoded, and
where that stops."""
LITERAL = "ff 03 8b be 78 56 34 12" # s_mov_b32 s11, 0x12345678
MOV = "04 03 8a be" # s_mov_b32 s10, s4
END = "00 00 81 bf" # s_endpgm
BAD = "ff ff ff ff" # no instruction

def restore(self, words, printed, code_start=0, normalized=()):
"""printed, normalized: (pc, bytes) of the instructions llvm-mc listed; returns [(pc, size)] in order."""
blob = bytes.fromhex("".join(words))
insns = [{"pc": pc, "enc": blob[pc:pc + n].hex(), "op": "x", "args": []} for pc, n in printed]
insns += [{"pc": pc, "enc": "00" * n, "op": "x", "args": [], "normalized": True} for pc, n in normalized]
insns.sort(key=lambda i: i["pc"])
out = rdna2spirv.restore_vcc_tuples(insns, blob, code_start, len(blob))
return [(i["pc"], len(i["enc"]) // 2) for i in out]

def test_stops_at_a_printed_instruction(self):
# the tuple's junk covers words 1 and 2; the s_mov_b32 at 12 is printed, with its own operands, and stays
words = [LOAD_X8_VCC, self.MOV, self.MOV, self.END]
self.assertEqual(self.restore(words, [(4, 8), (12, 4), (16, 4)]), [(0, 8), (8, 4), (12, 4), (16, 4)])
blob = bytes.fromhex("".join(words))
insns = [{"pc": 4, "enc": blob[4:12].hex(), "op": "x", "args": []},
{"pc": 12, "enc": blob[12:16].hex(), "op": "printed", "args": []}]
self.assertIn("printed", [i["op"] for i in rdna2spirv.restore_vcc_tuples(insns, blob, 0, len(blob))])

def test_crosses_a_start_that_is_a_literal_printed_on_its_own(self):
# The 8-byte instruction at 12 runs across a printed start (16): its own literal, which llvm-mc printed as an
# instruction because the junk before it ended there. So a resync may not stop at every printed start.
words = [LOAD_X8_VCC, self.MOV, self.LITERAL, self.END]
self.assertEqual(self.restore(words, [(4, 12), (16, 4), (20, 4)]), [(0, 8), (8, 4), (12, 8), (20, 4)])

def test_wave_size_reaches_the_decoder(self):
blob = bytes.fromhex(LOAD_X8_VCC + "0c 00 c4 d4 a8 00 02 00" + self.END) # v_cmp_gt_u32_e64 s12 / s[12:13]
for wave32, n in ((True, 1), (False, 2)):
with self.subTest(wave32=wave32):
insns = [{"pc": 4, "enc": blob[4:16].hex(), "op": "x", "args": []},
{"pc": 16, "enc": self.END.replace(" ", ""), "op": "s_endpgm", "args": []}]
out = rdna2spirv.restore_vcc_tuples(insns, blob, 0, len(blob), wave32=wave32)
self.assertEqual((out[1]["pc"], out[1]["args"][0].get("n", 1)), (8, n))

def branch(self, op, dwords):
return {"s_branch": "%02x %02x 82 bf", "s_cbranch_scc1": "%02x %02x 85 bf"}[op] % (dwords & 255, dwords >> 8 & 255)

def restore_ops(self, words, printed):
blob = bytes.fromhex("".join(words))
insns = [{"pc": pc, "enc": blob[pc:pc + n].hex(), "op": op, "args": args} for pc, n, op, args in printed]
return [i["pc"] for i in rdna2spirv.restore_vcc_tuples(insns, blob, 0, len(blob))]

def test_a_swallowed_branch_is_followed(self):
# the s_branch at 8, in the first tuple's junk, is the only way to the second tuple at 16
words = [LOAD_X8_VCC, self.branch("s_branch", 1), self.BAD, LOAD_X8_VCC, self.END]
self.assertEqual(self.restore_ops(words, [(4, 8, "x", []), (24, 4, "s_endpgm", [])]), [0, 8, 16, 24])

def test_a_branch_to_a_swallowed_instruction_does_not_hide_it(self):
# 0: scc1 -> 16 (swallowed), then the jump to 24, from where the tuple at 8 is reached last
imm = [{"k": "imm", "v": 3}]
words = [self.branch("s_cbranch_scc1", 3), self.branch("s_branch", 4), LOAD_X8_VCC, self.MOV, self.END,
self.branch("s_cbranch_scc1", -6), self.END]
printed = [(0, 4, "s_cbranch_scc1", imm), (4, 4, "s_branch", [{"k": "imm", "v": 4}]),
(12, 8, "x", []), (20, 4, "s_endpgm", []),
(24, 4, "s_cbranch_scc1", [{"k": "imm", "v": -5}]), (28, 4, "s_endpgm", [])]
self.assertEqual(self.restore_ops(words, printed), [0, 4, 8, 16, 20, 24, 28])
# the same with the branches to the two taken in the other order
printed[0], printed[4] = (0, 4, "s_cbranch_scc1", [{"k": "imm", "v": 1}]), (24, 4, "s_cbranch_scc1",
[{"k": "imm", "v": -3}])
self.assertEqual(self.restore_ops(words, printed), [0, 4, 8, 16, 20, 24, 28])

def test_what_follows_a_branched_into_tuple_is_dropped_with_it(self):
# a branch lands on the tuple's second word, so neither the tuple nor the words after it are taken for code
words = [self.branch("s_cbranch_scc1", 1), LOAD_X8_VCC, self.MOV, self.END]
printed = [(0, 4, "s_cbranch_scc1", [{"k": "imm", "v": 1}]), (8, 8, "x", []), (16, 4, "s_endpgm", [])]
self.assertEqual(self.restore_ops(words, printed), [0, 8, 16])

def test_drops_out_when_a_decode_fails(self):
# a word no decoder takes inside the junk: the s_mov_b32 after it is not picked up again
words = [LOAD_X8_VCC, self.BAD, self.MOV, self.END]
self.assertEqual(self.restore(words, [(4, 12), (16, 4)]), [(0, 8), (16, 4)])

def test_two_junk_regions_are_separate(self):
# Two regions of normalized junk with matched instructions between them: the first ends at the match, so the
# rejected word at 20, between the regions, is in neither and is not decoded after the second tuple.
words = [LOAD_X8_VCC, self.MOV, LOAD_X8_VCC, self.MOV, self.MOV, self.END]
self.assertEqual(self.restore(words, [(8, 4), (28, 4)], normalized=[(4, 4), (24, 4)]),
[(0, 8), (8, 4), (12, 8), (24, 4), (28, 4)])

def test_nothing_is_decoded_before_a_tuple(self):
# the first words are inside junk of something else: no tuple, so they stay as they are
words = [self.MOV, self.MOV, self.END]
self.assertEqual(self.restore(words, [], normalized=[(0, 8)]), [(0, 8)])

def test_resync_to_the_last_word(self):
self.assertEqual(self.restore([LOAD_X8_VCC, self.MOV, self.MOV], [(4, 12)]), [(0, 8), (8, 4), (12, 4)])

def test_a_tuple_at_the_very_end_of_the_code(self):
self.assertEqual(self.restore([self.MOV, LOAD_X8_VCC], [(0, 4)]), [(0, 4), (4, 8)])


if __name__ == "__main__":
unittest.main()
2 changes: 1 addition & 1 deletion tests/test_rdna2spirv_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ def test_fall_through_into_undecodable_words_is_refused(self):
export = [0x0F, 0x18, 0x00, 0xF8, 0x00, 0x01, 0x00, 0x01]
endpgm = [0x00, 0x00, 0x81, 0xBF]
# The word of the finding was [0x00,0x50,0x16,0xCC, 0x01,0x05,0x0E,0x0C]; the translator recovers that one
# v_dot4_i32_i8 form from the program's words now (restore_skipped_instructions), so it is no longer a gap.
# v_dot4_i32_i8 form from the program's words now (rdna2spirv.skipped_form), so it is no longer a gap.
# This is the same instruction with another op_sel, which is not recovered and stays skipped.
gap = [0x00, 0x58, 0x16, 0xCC, 0x01, 0x05, 0x0E, 0x0C]

Expand Down
Loading
Loading