Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions tests/semantic/test_salu_flbit_64.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,10 @@ def test_inline_source(self):
self.assertEqual(run_lines(["s_flbit_i32_b64 s0, 1"])[0], 63)
self.assertEqual(run_lines(["s_flbit_i32_i64 s0, -1"])[0], M32)

def test_lane_mask_source_is_rejected(self):
with self.assertRaises(rdna2spirv.Unsupported):
def test_lane_mask_source_translates(self):
# exec is a lane mask: the count comes from the subgroup's 64-bit mask (Gen.wave_mask), which the
# single-invocation interpreter cannot run, so this checks that it translates instead of being refused.
with self.assertRaises(si.UnsupportedConstruct):
run_lines(["s_flbit_i32_b64 s0, exec"])


Expand Down
9 changes: 9 additions & 0 deletions tests/semantic/test_salu_quadmask_bitreplicate.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,15 @@ def test_seeded(self):
self.assertEqual(run([f"s_mov_b32 s2, {lo:#x}", "s_bitreplicate_b64_b32 s[10:11], s2"])[:2],
(bitreplicate(lo) & M32, bitreplicate(lo) >> 32))

def test_bitreplicate_constant_into_vcc(self):
# Lane L's VCC bit is source bit L // 2; the single invocation is lane 0, so source bit 0 decides.
for x, want in ((0x0F0F0F0F, 1), (0x33333332, 0), (0x1, 1), (0x2, 0)):
with self.subTest(x=hex(x)):
spv = translate([f"s_bitreplicate_b64_b32 vcc, {x:#x}",
"v_cndmask_b32_e64 v0, 0x40000000, 0x40000001, vcc",
"exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"])
self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], 0x40000000 + want)

def test_lane_masks_rejected(self):
for lines in (["v_cmp_gt_u32_e32 vcc, 5, v0", "s_quadmask_b64 s[10:11], vcc"],
["s_quadmask_b32 s10, exec_lo"],
Expand Down
32 changes: 28 additions & 4 deletions tests/test_fspx_unpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,27 @@ def test_code_range(self):
self.assertEqual(fspx_unpack.code_range(program(with_prologue=False)), (0, 12 + 4))
self.assertEqual(fspx_unpack.code_range(program(endpgm=False))[1], None)

def test_two_word_prologue(self):
# Some pipeline-library programs carry two hash words (24 bytes), then their code.
code = prologue()[:24] + V_MOV * 3 + ENDPGM + S_NOP * 4
self.assertEqual(fspx_unpack.code_range(code), (24, 24 + 12 + 4))
# One VOP3 word alone is not a prologue.
code = prologue()[:12] + V_MOV * 3 + ENDPGM + S_NOP * 4
self.assertEqual(fspx_unpack.code_range(code)[0], 0)

def test_code_range_last(self):
code = prologue() + V_MOV * 3 + ENDPGM + V_MOV + ENDPGM + S_NOP
self.assertEqual(fspx_unpack.code_range(code), (36, 36 + 12 + 4))
self.assertEqual(fspx_unpack.code_range_last(code), (36, 36 + 12 + 4 + 4 + 4))

def test_branch_targets_inside(self):
enc = "; encoding: [0x00,0x00,0x00,0x00]"
listing = f"\ts_cbranch_execz 1 {enc}\n\ts_nop 0 {enc}\n\ts_endpgm {enc}\n"
self.assertTrue(fspx_unpack.branch_targets_inside(listing, 12)) # 0 + 4 + 4 = 8: inside
self.assertFalse(fspx_unpack.branch_targets_inside(listing, 8)) # 8 is past an 8-byte range
back = f"\ts_nop 0 {enc}\n\ts_branch 65534 {enc}\n" # -2: 4 + 4 - 8 = 0
self.assertTrue(fspx_unpack.branch_targets_inside(back, 8))

def test_unaligned_endpgm_bytes_are_not_the_end(self):
code = prologue() + b"\0\0" + ENDPGM + b"\0\0" + V_MOV + ENDPGM
start, end = fspx_unpack.code_range(code)
Expand Down Expand Up @@ -214,17 +235,20 @@ def test_empty_disassembly_writes_no_listing(self):
self.assertEqual(os.listdir(os.path.join(out, "disasm")), [])
self.assertEqual(os.listdir(os.path.join(out, "fspx")), [])

def test_disassembly_with_invalid_words_keeps_listing(self):
def test_disassembly_with_invalid_words_takes_the_decoder_listing(self):
# llvm-mc reports an invalid word in a program tools/rdna2_decode.py decodes whole: the compute fallback of
# shader_disasm.disasm takes the decoder's listing (fewer invalid words), without llvm-mc's messages.
result, out = self.disassemble("import sys\n"
"print('\\ts_endpgm')\n"
"sys.stderr.write('warning: invalid instruction encoding\\n')\n")
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(result.stderr, "")
with open(os.path.join(out, "disasm", "one.s"), encoding="utf-8") as f:
listing = f.read()
self.assertIn("1 invalid words", listing)
self.assertIn("\ts_endpgm", listing)
self.assertIn("warning: invalid instruction encoding", listing)
self.assertIn("0 invalid words", listing)
self.assertIn("v_mov_b32", listing)
self.assertIn("s_endpgm", listing)
self.assertNotIn("warning: invalid instruction encoding", listing)

def test_clean_disassembly_keeps_listing(self):
result, out = self.disassemble("print('\\ts_endpgm')\n")
Expand Down
76 changes: 70 additions & 6 deletions tools/fspx_unpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,13 +144,32 @@ def code_range(code: bytes):
"""(start, end) of the instructions in a kind-6 program: after the 36-byte prologue when it is there, through
the first s_endpgm. end is None when the program has no s_endpgm."""
words = struct.unpack_from(f"<{len(code) // 4}I", code)
start = PROLOGUE_SIZE if len(words) > 8 and all(words[k] >> 16 == 0xD580 for k in PROLOGUE_WORDS) else 0
# Most programs carry three hash words; some pipeline-library programs of 1.0.2.1 carry two (a 24-byte prologue,
# then s_inst_prefetch), measured on the 50 programs the runtime found untranslated. Two or three count.
hash_words = 0
while hash_words < len(PROLOGUE_WORDS) and len(words) > PROLOGUE_WORDS[hash_words] + 2 and \
words[PROLOGUE_WORDS[hash_words]] >> 16 == 0xD580:
hash_words += 1
start = hash_words * PROLOGUE_SIZE // len(PROLOGUE_WORDS) if hash_words >= 2 and len(words) > 8 else 0
pos = code.find(ENDPGM, start)
while pos >= 0 and pos % 4:
pos = code.find(ENDPGM, pos + 1)
return start, (pos + 4 if pos >= 0 else None)


def code_range_last(code: bytes):
"""code_range through the last 4-byte-aligned s_endpgm instead of the first, as shader_library.code_range: a
program with an early exit branches to code after its first s_endpgm (28 of the 50 pipeline-library programs the
runtime dumped as untranslated: "branch target outside code")."""
start, first = code_range(code)
if first is None:
return start, None
last = code.rfind(ENDPGM)
while last >= first and (last - start) % 4:
last = code.rfind(ENDPGM, 0, last)
return start, max(first, last + 4)


def psv_stage(container_parts: dict):
"""PSVRuntimeInfo1 ShaderStage, or None (PSV0 = u32 size of the runtime info, then the info)."""
psv = container_parts.get(b"PSV0", b"")
Expand All @@ -160,16 +179,53 @@ def psv_stage(container_parts: dict):
return psv[4 + 24] if size > 24 and len(psv) > 4 + 24 else None


def unpack_payload(payload: bytes):
def branch_targets_inside(asm: str, size: int) -> bool:
"""Whether every s_branch / s_cbranch_* of a shader_disasm.py listing lands inside [0, size)."""
pc = 0
for line in asm.splitlines():
if "; encoding: [" not in line:
continue
text, enc = line.split("; encoding: [", 1)
length = enc.count(",") + 1
parts = text.split()
if parts and (parts[0] == "s_branch" or parts[0].startswith("s_cbranch_")) and len(parts) > 1:
try:
k = int(parts[1].rstrip(","), 0)
except ValueError:
k = None
if k is not None:
if k > 0x7FFF:
k -= 0x10000
target = pc + 4 + 4 * k
if not 0 <= target < size:
return False
pc += length
return True


def branch_closed_end(code: bytes, start: int, mcpu: str, disasm) -> int | None:
"""The end (after its s_endpgm) of the shortest range from `start` through an aligned s_endpgm whose branches all
stay inside it, or None. Tried from the first s_endpgm on."""
pos = code.find(ENDPGM, start)
while pos >= 0:
if (pos - start) % 4 == 0:
asm, invalid, _ = disasm.disasm(code[start:pos + 4], mcpu, compute=True)
if asm.strip() and branch_targets_inside(asm, pos + 4 - start):
return pos + 4
pos = code.find(ENDPGM, pos + 1)
return None


def unpack_payload(payload: bytes, last_endpgm: bool = False):
status, entries = parse_fspx(payload)
if status:
return None, status
blob = {k: payload[o:o + s] for k, (o, s) in entries.items()}
start, end = code_range(blob[6])
start, end = (code_range_last if last_endpgm else code_range)(blob[6])
meta = {
"version": struct.unpack_from("<I", payload, 4)[0],
"directory": {str(k): [o, s] for k, (o, s) in sorted(entries.items())},
"code": {"start": start, "end": end, "prologue": start == PROLOGUE_SIZE},
"code": {"start": start, "end": end, "prologue": start > 0},
**decode_kind0(blob[0]),
}
return (meta, blob), 0
Expand All @@ -183,6 +239,9 @@ def main(argv=None) -> int:
ap.add_argument("--mcpu", default="gfx1030",
help="llvm-mc CPU for --disasm (default gfx1030: the programs use v_dot4 instructions, which "
"gfx1010 and gfx1013 do not decode)")
ap.add_argument("--last-endpgm", action="store_true",
help="end each program at its last s_endpgm, not its first (pipeline-library programs the "
"runtime dumped with LEONIDA_DUMP_MISSING: early exits branch past the first)")
a = ap.parse_args(argv)
# An output in the input folder can replace a .dxbc input and, when the input is the folder itself,
# os.makedirs writes there before open() tries to read the folder as a file. Refuse before either.
Expand Down Expand Up @@ -231,7 +290,7 @@ def main(argv=None) -> int:
continue
for n, (off, container, payload) in enumerate(items):
name = f"{stem}_{n:02d}" if len(items) > 1 else stem
got, status = unpack_payload(payload)
got, status = unpack_payload(payload, a.last_endpgm)
if not got:
print(f"{name}: FSPX status {status}", file=sys.stderr)
bad += 1
Expand All @@ -254,7 +313,12 @@ def main(argv=None) -> int:
listing = None
if disasm and meta["code"]["end"]:
start, end = meta["code"]["start"], meta["code"]["end"]
asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu)
if a.last_endpgm:
# The last s_endpgm can lie in data after the code; the first s_endpgm whose listing keeps
# every branch inside the code is the program's end.
end = branch_closed_end(blob[6], start, a.mcpu, disasm) or end
meta["code"]["end"] = end
asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu, compute=True)
if not asm.strip():
reason = (err.strip().splitlines() or ["no output"])[0]
print(f"{name}: {reason}", file=sys.stderr)
Expand Down
26 changes: 26 additions & 0 deletions tools/rdna2_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,32 @@ def finish(op: str, args: list, mods: list, nbytes: int) -> tuple[dict, int]:
dst_op = _sreg(sdst, 1 if wave32 else 2) if sd else _vcc_operand(wave32)
args = [dst_op, s0, s1] if not name.startswith("v_cmpx_") else [s0, s1]
return finish(name + "_sdwa", args, mods, 8)
if is_dpp16 or is_dpp8:
# VOPC with DPP (src0 = 0xFA / 0xE9 / 0xEA): 8 bytes, as for VOP1/VOP2. Read as 4 before, the DPP word
# became an invalid instruction (lib_cs_01473 of the 1.0.2.1 pipeline library: v_cmp_gt_f32 quad_perm).
if not need(8):
return None, 4
w1 = struct.unpack_from("<I", code, pc + 4)[0]
s0 = _vreg(w1 & 0xFF, 1)
s1 = _vreg(vsrc1, 1)
if is_dpp16:
ctrl = (w1 >> 8) & 0x1FF
s0["neg"], s0["abs"] = bool((w1 >> 20) & 1), bool((w1 >> 21) & 1)
s1["neg"], s1["abs"] = bool((w1 >> 22) & 1), bool((w1 >> 23) & 1)
mods.append(_format_dpp16_ctrl(ctrl))
mods.append(f"row_mask:0x{(w1 >> 28) & 0xF:x}")
mods.append(f"bank_mask:0x{(w1 >> 24) & 0xF:x}")
if (w1 >> 19) & 1:
mods.append("bound_ctrl:1")
if (w1 >> 18) & 1:
mods.append("fi:1")
else:
lanes = [(w1 >> (8 + 3 * i)) & 7 for i in range(8)]
mods.append(f"dpp8:[{','.join(str(x) for x in lanes)}]")
if src0 == 234:
mods.append("fi:1")
args = [_vcc_operand(wave32), s0, s1] if not name.startswith("v_cmpx_") else [s0, s1]
return finish(name + "_dpp", args, mods, 8)
lit = None
nbytes = 4
if src0 == 255:
Expand Down
48 changes: 38 additions & 10 deletions tools/rdna2spirv.py
Original file line number Diff line number Diff line change
Expand Up @@ -7253,7 +7253,15 @@ def selectors(key, count, limit):
args = [dict(a) for a in ins["args"]]
if len(args) < 2:
raise Unsupported("DPP operands")
if args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1:
# VOPC with DPP (v_cmp_*_dpp vcc, ...: 12 compares in pipeline-library reductions of 1.0.2.1) writes a lane
# mask, which the DPP write guard (VGPR stores) does not cover: taken when every lane writes, i.e. full row
# and bank masks with bound_ctrl:1 or DPP8, so no lane keeps its old bit.
lane_mask_dst = (args[0].get("k") == "special" and args[0].get("t", "") in ("vcc", "vcc_lo")
and base_op(ins["op"]).startswith("v_cmp_"))
if lane_mask_dst:
if row_mask != 0xF or bank_mask != 0xF or not (bound or dpp8 is not None):
raise Unsupported("DPP compare with a partial write mask")
elif args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1:
raise Unsupported("DPP destination")
if args[1].get("n", 1) != 1:
raise Unsupported("DPP 64-bit source")
Expand Down Expand Up @@ -7433,7 +7441,7 @@ def selectors(key, count, limit):
self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}")
args[1] = {"k": "ssa", "v": src0}
previous = self.dpp_guard
self.dpp_guard = write
self.dpp_guard = None if lane_mask_dst else write
try:
return self._insn({**ins, "args": args})
finally:
Expand Down Expand Up @@ -7584,21 +7592,39 @@ def _insn(self, ins):
d, x = a[0], a[1]
wide_src = op == "s_quadmask_b64"
wide_dst = op != "s_quadmask_b32"
mask_words = None
if self.is_mask_op(x):
raise Unsupported(op + " on a lane mask")
# s_bitreplicate_b64_b32 of a 32-bit lane mask into plain scalar data (6 pipeline-library programs of
# 1.0.2.1): the wave's mask word as data, then replicated as any scalar (wave_mask, as s_ff1 reads it).
if op != "s_bitreplicate_b64_b32" or (d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc"))):
raise Unsupported(op + " on a lane mask")
lo, hi = self.wave_mask(x)
half = self.mask_half(x) if self.wave64 else None
mask_words = [hi if half == "hi" else lo]
if d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc")):
if op != "s_bitreplicate_b64_b32" or d["t"] != "exec":
if op != "s_bitreplicate_b64_b32" or d["t"] not in ("exec", "vcc") or mask_words is not None:
raise Unsupported(op + " on a lane mask")
# EXEC's bit for lane L comes from scalar-source bit L // 2.
# EXEC's (or VCC's) bit for lane L comes from scalar-source bit L // 2. VCC from a constant
# (s_bitreplicate_b64_b32 vcc, 0xf0f0f0f: 6 pipeline-library programs of 1.0.2.1) is a lane mask
# each invocation holds as 0 or ~0, as a compare leaves it.
shift, shifted, bit = (self.tmp() for _ in range(3))
lane = self.wave_lane()
word = self.src_u(x)
self.emit(f"{shift} = OpShiftRightLogical %uint {lane} {self.cu(1)}")
self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {shift}")
self.emit(f"{bit} = OpBitwiseAnd %uint {shifted} {self.cu(1)}")
self.set_exec(bit)
# As a lane mask (0 or ~0): set_exec takes this lane's bit of the value it is given (lane_bit_on),
# which a mask answers for every lane and a plain 0/1 only for lanes 0 and 32.
mask = self.tmp()
self.emit(f"{mask} = OpISub %uint {self.cu(0)} {bit}")
if d["t"] == "vcc":
self.emit(f"OpStore %vcc {mask}")
else:
self.set_exec(mask)
return
if wide_src:
if mask_words is not None:
words = mask_words
elif wide_src:
lo, hi = self.src64_data(x, op)
words = [lo, hi]
else:
Expand Down Expand Up @@ -8348,11 +8374,13 @@ def sel(c, t, f):
# Leading-bit count of a 64-bit value, from bit 63 down: b64 counts the zeros before the first 1; i64
# counts the bits before the first one that differs from the sign bit (b64 of ~S0 when S0 < 0). -1 when
# there is none (0, and for i64 also -1). SCC is not written. The pair is 64-bit data (as for
# s_lshl_b64); a lane-mask source stays Unsupported (#210).
# s_lshl_b64); a lane-mask source reads the wave mask (Gen.wave_mask).
x = a[1]
if self.holds_lane_mask(x):
raise Unsupported(op + " of a lane mask")
if x["k"] == "sgpr" and x.get("n") == 2:
# The wave's mask as its 64 bits, as s_ff1_i32_b64 of a lane mask reads it (18 pipeline-library
# programs of 1.0.2.1: the highest active lane, 63 - lane).
lo, hi = self.wave_mask(x)
elif x["k"] == "sgpr" and x.get("n") == 2:
lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1)
elif x["k"] == "imm":
v = x["v"] & 0xFFFFFFFFFFFFFFFF
Expand Down
14 changes: 13 additions & 1 deletion tools/shader_disasm.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,19 @@ def probe(mcpu: str) -> None:
f"{install_hint()}")


def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True):
def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True, compute: bool = False):
"""`compute`: a pipeline-library or FSPX compute program. llvm-mc 21 does not decode SMEM loads whose SOFFSET is
SGPR_NULL (0x7D, e.g. s_load_dwordx8 ... 0xd60 with soffset null): it reports the first dword invalid, then reads
the second (0xFA......) as an 8-byte EXP and the rest of the listing goes out of step (gfx1013 and gfx1030 alike).
In 749 of the 2,684 library programs of 1.0.2.1 that refused 945 programs ('fall-through into undecodable
words'). tools/rdna2_decode.py decodes them; such a program takes its listing when it has fewer invalid words."""
if compute and backend != "python":
asm, bad, err = disasm(code, mcpu, backend=backend, wave32=wave32)
if bad:
py_asm, py_bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32)
if py_bad < bad:
return py_asm, py_bad, ""
return asm, bad, err
if backend == "python":
asm, bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32)
return asm, bad, ""
Expand Down
Loading
Loading