From 4b9a89124a470d266f0ed314db17a79fc45957be Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:08:08 -0600 Subject: [PATCH 01/18] fspx_unpack: code_range takes the 24-byte prologue of some pipeline-library programs 50 of the 2,684 library programs in shaders.rpf (1.0.2.1) start with two VOP3 opcode-0x180 words (words 0 and 3) instead of three, and their code starts at word 6. code_range only knew the 36-byte form, so it disassembled them from word 0 and they never decoded: 1 of the 50 translated. With the 24-byte form all 50 disassemble with 0 invalid words and 49 translate and pass spirv-val. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/fspx.md | 6 ++++++ tests/test_fspx_unpack.py | 10 ++++++++++ tools/fspx_unpack.py | 20 ++++++++++++++++---- tools/shader_library.py | 2 +- 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/docs/fspx.md b/docs/fspx.md index a603545e93..a7efdbb520 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -136,6 +136,12 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. SGPRs (`s[0:1]`, `s4`..`s15`), `M0`, `VCC`, `EXEC` (including inactive lanes across 64 threads) and `SCC` (both 0 and 1) unchanged, and execution resumes cleanly at `+36` bytes. So they are hardware no-ops on RDNA2. - `tools/fspx_unpack.py` disassembles from the end of the prologue. + - **A 24-byte variant**: some programs of the pipeline library in `shaders.rpf` (`tools/shader_library.py`) carry + only the first two of those words, at words 0 and 3, and their code starts at word 6 (`s_inst_prefetch` in all of + them). Counted on the 1.0.2.1 library: 50 of 2,684 programs; read from word 0 they never decode (the prologue + words are invalid encodings and the rest desyncs), and only 1 of the 50 translated. With `code_range` taking + the 24-byte form, all 50 disassemble with 0 invalid words and 49 translate and pass `spirv-val` (the other one + stops at `s_sethalt`). A program whose words 0, 3 and 6 are all prologue words still takes the 36-byte form. - **Target.** The programs use `v_dot4_i32_i8` (1,458 times) and `v_dot4c_i32_i8` (25,813 times), which fits the provider's name (`FSR4_Int8`). `llvm-mc` (LLVM 23.1.5) decodes them for `gfx1011`, `gfx1012`, `gfx1030`, `gfx1031`, `gfx1033`, `gfx1034` and `gfx1036`, but not for `gfx1010`, `gfx1013` (the target `shader_disasm.py` uses for the diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 946da380cf..8b34502499 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -144,6 +144,16 @@ 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_short_prologue(self): + # Two VOP3 opcode-0x180 words (0 and 3), then code: the 24-byte prologue of some pipeline-library programs. + code = prologue()[:24] + V_MOV * 3 + ENDPGM + self.assertEqual(fspx_unpack.code_range(code), (24, 24 + 12 + 4)) + # Only word 0 is not a prologue. + code = prologue()[:12] + V_MOV * 6 + ENDPGM + self.assertEqual(fspx_unpack.code_range(code)[0], 0) + # The long one still wins when word 6 is a prologue word too. + self.assertEqual(fspx_unpack.code_range(program())[0], 36) + 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) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index 5cb94813e7..5ce01f9a60 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -24,7 +24,7 @@ DIR/fspx/.json the decoded kind-0 entry, the directory and the code range DIR/fspx/.code the kind-6 program DIR/fspx/.state the kind-0 entry as it is (its SHA-256 is the index's fspx_state_sha256) - DIR/disasm/.s with --disasm: tools/shader_disasm.py output for the code after the prologue + DIR/disasm/.s with --disasm: tools/shader_disasm.py output for the code after the prologue (36 or 24 bytes) """ import argparse import json @@ -46,6 +46,11 @@ # kind-7 hash; llvm-mc rejects them. Measured on all 29 shaders of the 1.0.2.1 DLL (docs/fspx.md). PROLOGUE_WORDS = (0, 3, 6) PROLOGUE_SIZE = 36 +# Some programs of the pipeline library in shaders.rpf carry only two of those words (0 and 3): a 24-byte prologue, with +# the code starting at word 6 (50 of the 2,684 library programs of 1.0.2.1, docs/fspx.md). Read from word 0 they never +# decode. +SHORT_PROLOGUE_WORDS = (0, 3) +SHORT_PROLOGUE_SIZE = 24 STAGE_COMPUTE = 5 # PSVRuntimeInfo1 ShaderStage (DirectX): 5 = compute @@ -141,10 +146,17 @@ def decode_kind0(b: bytes) -> dict: 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 + """(start, end) of the instructions in a kind-6 program: after the 36- or 24-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 + def vop3_180(ks): + return all(words[k] >> 16 == 0xD580 for k in ks) + if len(words) > 8 and vop3_180(PROLOGUE_WORDS): + start = PROLOGUE_SIZE + elif len(words) > 6 and vop3_180(SHORT_PROLOGUE_WORDS): + start = SHORT_PROLOGUE_SIZE + else: + start = 0 pos = code.find(ENDPGM, start) while pos >= 0 and pos % 4: pos = code.find(ENDPGM, pos + 1) @@ -169,7 +181,7 @@ def unpack_payload(payload: bytes): meta = { "version": struct.unpack_from(" 0}, **decode_kind0(blob[0]), } return (meta, blob), 0 diff --git a/tools/shader_library.py b/tools/shader_library.py index 233e6ba565..d6e768a93d 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -354,7 +354,7 @@ def extraction_paths(): code = program(b, lib, i) start, end = code_range(code) meta = {"program": i, "stage": st, "offset": lib["programs"][i][0], "size": len(code), - "code": {"start": start, "end": end, "prologue": start == fspx_unpack.PROLOGUE_SIZE}} + "code": {"start": start, "end": end, "prologue": start > 0}} state = blob(b, lib, cs_state[i]) if i in cs_state else None if state is not None: meta.update(fspx_unpack.decode_kind0(state)) From 1ea2ffbcadac0ea8cd58fe0794a513ff68661af4 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:25:31 -0600 Subject: [PATCH 02/18] rdna2spirv: s_bitreplicate_b64_b32 into VCC, s_flbit_i32_b64 of a lane mask - s_bitreplicate_b64_b32 with a VCC destination: lane L gets S0 bit L // 2, stored as mov64 stores a mask into VCC (EXEC already took this path). - s_flbit_i32_b64 of a lane mask reads the wave's whole mask (wave_mask), as s_ff1_i32_b64 does; s_flbit_i32_i64 of a mask stays Unsupported. Both occur in pipeline-library compute programs that the retail boot creates. Tests: tests/semantic/test_lane_mask_bitreplicate_flbit.py runs both on every lane of a wave64 (run_workgroup); docs/design.md contract rows updated. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 4 +- .../test_lane_mask_bitreplicate_flbit.py | 65 +++++++++++++++++++ tests/semantic/test_salu_flbit_64.py | 5 +- tools/rdna2spirv.py | 19 ++++-- 4 files changed, 85 insertions(+), 8 deletions(-) create mode 100644 tests/semantic/test_lane_mask_bitreplicate_flbit.py diff --git a/docs/design.md b/docs/design.md index ba4c33fa1c..de55f9283b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -449,9 +449,9 @@ How the generated SPIR-V expects the runtime to work: | `v_bfi_b32` | `(S0 & S1) \| (~S0 & S2)` (RDNA2 ISA, VOP3 opcode 330). A literal or known same-block SGPR mask of zero or all ones selects S2 or S1 directly. A contiguous mask uses `OpBitFieldInsert` with S1 shifted down by the field offset, since RDNA2 reads the bits in place. For sparse constant masks the translator precomputes the complement. Runtime masks use the full bitwise expression. Checked by the hand-written `bfi_known_mask.asm` and `tests/semantic/test_bfi_known_mask.py`. | | `v_bfm_b32` | The low five bits of S0 give the width and those of S1 give the offset. The result is the low 32 bits of `((1 << width) - 1) << offset` (RDNA2 ISA §12.12, VOP3 opcode 867). Literal and same-block SGPR constants are folded in the translator, including zero width and shifts that discard the high bits. Runtime operands keep their low-five-bit masks. Checked by `tests/semantic/test_bfm_known_operands.py` and `test_alu_int_misc.py`. | | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | -| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | +| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210), except under `s_flbit_i32_b64`, which reads the wave's whole mask as real bits (`wave_mask`, as `s_ff1_i32_b64` does): 63 minus the last active lane (the 1.0.2.1 pipeline library reads EXEC this way; wave64 run of EXEC and VCC masks in `tests/semantic/test_lane_mask_bitreplicate_flbit.py`). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | | `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by the unit test `ValuBfeMeasuredOnRdna2.test_translator_gives_the_gfx1036_words` in `tests/test_int_hw_probe.py`. | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | +| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. An EXEC or VCC destination of `s_bitreplicate_b64_b32` gives lane L bit L // 2 of S0 (EXEC since 6ecd922d9; VCC, which the 1.0.2.1 pipeline library writes from a constant, checked on every lane of a wave64 by `tests/semantic/test_lane_mask_bitreplicate_flbit.py`). Any other lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | | 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| | Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). **A computed value written to EXEC** (`s_lshl_b32`, `s_add_u32`, `s_bfm_b32`, and every other SALU result that reaches `exec_lo`/`exec_hi` through `Gen.dst`) takes each lane's bit too: until 2026-11-24 the generic path tested the value for non-zero, so `s_lshl_b32 exec_lo, 1, s5` ran all 32 lanes of that half (SHADER-1264; `Gen.exec_bit`). The words are the GPU's, recorded in `runtime/test/shaders/cs_w32_exec_computed.asm` and `cs_w64_exec_computed.asm` (RTX 5070), and `tests/semantic/test_exec_computed.py` replays them through the CPU interpreter. A value that already holds this lane's bit of a mask (0 or ~0) gives the same answer. | | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | diff --git a/tests/semantic/test_lane_mask_bitreplicate_flbit.py b/tests/semantic/test_lane_mask_bitreplicate_flbit.py new file mode 100644 index 0000000000..66743bd2cc --- /dev/null +++ b/tests/semantic/test_lane_mask_bitreplicate_flbit.py @@ -0,0 +1,65 @@ +"""s_bitreplicate_b64_b32 into VCC and s_flbit_i32_b64 of a lane mask, run on every lane of a wave64 in +spirv_mini_interp.run_workgroup. + +RDNA2 ISA, SOP1: + - s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i], i in 0..31; SCC is not written. Into VCC, lane L's bit is S0 bit + L // 2. + - s_flbit_i32_b64: the zeros above the first 1 from bit 63, -1 when S0 is 0. Of EXEC that is 63 minus the wave's + last active lane. +Synthetic programs only. +""" +import unittest + +import saveexec_run as h +import support +import spirv_mini_interp as si + +OUT_AT = 256 + + +def run(lines): + spv = support.translate_lines("cs_lane_mask_bitreplicate_flbit", lines, fssm=h.fssm()) + return 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=h.VSHARP + [0] * 28, memory={}) + + +def lane_index(): + return ["v_mbcnt_lo_u32_b32 v1, -1, 0", "v_mbcnt_hi_u32_b32 v1, -1, v1", "v_lshlrev_b32_e32 v21, 2, v1"] + + +def flbit_model(mask): + return 63 - (mask.bit_length() - 1) if mask else 0xFFFFFFFF + + +class LaneMaskBitreplicateFlbit(unittest.TestCase): + def test_bitreplicate_into_vcc(self): + for k in (0x0F0F0F0F, 0xFF00FF00, 0, 0xFFFFFFFF, 0x80000001, 0x12345678): + with self.subTest(k=hex(k)): + mem = run(lane_index() + [f"s_bitreplicate_b64_b32 vcc, {k:#x}", "v_cndmask_b32_e64 v2, 0, 1, vcc", + "buffer_store_dword v2, v21, s[0:3], 0 offen", "s_endpgm"]) + got = [mem[4 * lane] for lane in range(64)] + self.assertEqual(got, [(k >> (lane // 2)) & 1 for lane in range(64)]) + + def test_flbit_of_exec(self): + for mask in (h.ALL64, 1, 0x8000000000000000, 0x00000000FFFFFFFF, 0x0000F00000000000, 0x10): + with self.subTest(exec=hex(mask)): + mem = run(lane_index() + [f"s_mov_b32 exec_lo, {mask & 0xFFFFFFFF:#x}", f"s_mov_b32 exec_hi, {mask >> 32:#x}", + "s_flbit_i32_b64 s10, exec", "s_mov_b64 exec, -1", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + f"v_mov_b32_e32 v21, {OUT_AT}", "buffer_store_dword v20, v21, s[0:3], 0 offen", + "s_endpgm"]) + self.assertEqual(mem[OUT_AT], flbit_model(mask)) + + def test_flbit_of_vcc(self): + # VCC from a compare: the lanes l with l < n. + for n in (0, 1, 31, 33, 64): + with self.subTest(n=n): + mem = run(lane_index() + [f"v_cmp_gt_u32_e32 vcc, {n}, v1", "s_flbit_i32_b64 s10, vcc", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + f"v_mov_b32_e32 v21, {OUT_AT}", "buffer_store_dword v20, v21, s[0:3], 0 offen", + "s_endpgm"]) + self.assertEqual(mem[OUT_AT], flbit_model((1 << n) - 1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_salu_flbit_64.py b/tests/semantic/test_salu_flbit_64.py index faf480eb32..743602719f 100644 --- a/tests/semantic/test_salu_flbit_64.py +++ b/tests/semantic/test_salu_flbit_64.py @@ -123,9 +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): + # b64 of a lane mask reads the whole wave's mask: tests/semantic/test_lane_mask_bitreplicate_flbit.py. + def test_i64_lane_mask_source_is_rejected(self): with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["s_flbit_i32_b64 s0, exec"]) + run_lines(["s_flbit_i32_i64 s0, exec"]) if __name__ == "__main__": diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index e2acd97dee..35d71ffc39 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7580,8 +7580,15 @@ def _insn(self, ins): if self.is_mask_op(x): raise Unsupported(op + " on a lane mask") 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"): raise Unsupported(op + " on a lane mask") + if d["t"] == "vcc": + # VCC's bit for lane L is scalar-source bit L // 2 too, stored as mov64 stores a mask into VCC + # (this lane's bit as 0xFFFFFFFF / 0). + half = self.tmp() + self.emit(f"{half} = OpShiftRightLogical %uint {self.wave_lane()} {self.cu(1)}") + self.emit(f"OpStore %vcc {self._scalar_word_lane_bit(self.src_u(x), half)}") + return # EXEC's bit for lane L comes from scalar-source bit L // 2. shift, shifted, bit = (self.tmp() for _ in range(3)) lane = self.wave_lane() @@ -8341,11 +8348,15 @@ 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 of b64 is the wave's mask (wave_mask); of i64 it stays Unsupported. 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: + if op != "s_flbit_i32_b64": + raise Unsupported(op + " of a lane mask") + # The wave's mask as real bits, as s_ff1_i32_b64 reads one: the result is the zeros above the + # wave's last active 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 From ce98fbefee2bee293e04835ed30183164be2fd31 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 00:35:11 +0100 Subject: [PATCH 03/18] fix: rdna2spirv decodes scalar, image and buffer tuples that run into vcc from the blob when llvm-mc rejects them llvm-mc skips the first word of s_buffer_load_dwordx8 into s[100:107], an image resource in s[100:107] or a buffer resource in s[104:107] and leaves the second word as junk, so translate() refused those shaders (reachable instruction with normalized encoding) or translated them without the load. restore_vcc_tuples reads the uncovered words of the code range with rdna2_decode and keeps only instructions whose operands hold a VCCTuple list, the form the translator already takes. Other undecodable words are unchanged. --- docs/shader_library.md | 8 +- tests/semantic/test_vcc_tuple_fallback.py | 149 ++++++++++++++++++++++ tools/rdna2spirv.py | 36 ++++++ 3 files changed, 190 insertions(+), 3 deletions(-) create mode 100644 tests/semantic/test_vcc_tuple_fallback.py diff --git a/docs/shader_library.md b/docs/shader_library.md index 09a1997a97..483426225f 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -165,9 +165,11 @@ What stops the rest, by the translator's message: run into `vcc` (SGPRs 106 and 107): `s_load_dwordx8`/`x4`/`x16` writing `s[100:107]`, `s[104:107]` or `s[92:107]`, and image instructions whose resource is `s[100:107]`. In the compute programs alone that is 37,952 SMEM, 22,248 MIMG and 2,298 MUBUF words. The same words with the register field one tuple lower decode; with - `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. A decoder - fallback for these encodings would cover most of the remaining programs. The translator already reads - `[s100,...,vcc_lo,vcc_hi]` lists (design.md *Scalar/buffer memory*). + `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. * **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. diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py new file mode 100644 index 0000000000..dd02b4509a --- /dev/null +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -0,0 +1,149 @@ +"""A scalar tuple that runs into vcc is translated from the blob when llvm-mc cannot decode it. + +llvm-mc rejects s_buffer_load_dwordx8 into s[100:107], a buffer resource in s[104:107] and an image resource in +s[100:107] (SGPRs 106 and 107 are vcc). It skips the first word as invalid and leaves the second word as junk, so +translate() refused every such shader ("reachable instruction with normalized encoding", or "fall-through into +undecodable words"; docs/shader_library.md section 5), or, when the junk matched the blob, translated a program +with the load missing. The words are now decoded from the blob as the VCCTuple lists the translator takes. + +Hand-built listings and blobs of synthetic instructions (encodings from llvm-mc 19, the three tuple words patched in +their register field), no game data. + + python -I tests/semantic/test_vcc_tuple_fallback.py -v +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +from support import rdna2spirv, translate_listing # noqa: E402 +import fssm_header # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +NAME = "cs_vcc_tuple" +CODE_START = 0x148 +BASE, OUT = 0x1000, 0x3000 +INVALID = "; warning: invalid instruction encoding" + +SET_SGPR_V = [ # s4..s7 = a V# over BASE (32 bytes), as tests/semantic/test_fspx_rules.py builds it + ("s_mov_b32 s4, 0x1000", "ff 03 84 be 00 10 00 00"), + ("s_mov_b32 s5, 0", "80 03 85 be"), + ("s_mov_b32 s6, 32", "a0 03 86 be"), + ("s_mov_b32 s7, 0x30000000", "ff 03 87 be 00 00 00 30"), +] +WAIT = ("s_waitcnt lgkmcnt(0)", "7f c0 8c bf") +WAIT_V = ("s_waitcnt vmcnt(0)", "70 3f 8c bf") +STORE_X4 = [ + ("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"), + ("global_store_dwordx4 v6, v[10:13], s[0:1]", "00 80 78 dc 06 0a 00 00"), + ("s_endpgm", "00 00 81 bf"), +] +# the words llvm-mc cannot decode (each is two dwords): the llvm-mc 19 encoding of the same instruction one tuple +# lower, with its register field patched into vcc +LOAD_X8_VCC = "02 19 2c f4 00 00 00 fa" # s_buffer_load_dwordx8 [s100..s105,vcc_lo,vcc_hi], s[4:7], 0x0 +LOAD_X4_VCC = "02 1a 28 f4 00 00 00 fa" # s_buffer_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], s[4:7], 0x0 +LOAD_DW_FROM_VCC = "b4 02 20 f4 00 00 00 fa" # s_buffer_load_dword s10, [s104,s105,vcc_lo,vcc_hi], 0x0 +BUFFER_LOAD_VCC = "00 10 30 e0 01 0b 1a 80" # buffer_load_dword v11, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen +IMAGE_LOAD_VCC = "08 1f 00 f0 01 04 19 00" # image_load v[4:7], v[1:2], [s100..s105,vcc_lo,vcc_hi] 2D unorm +PROGRAM_VARIANTS = ("invalid", "junk", "normalized") + + +def encoding(raw): + return "; encoding: [" + ",".join(f"0x{b:02x}" for b in bytes.fromhex(raw)) + "]" + + +def listing_and_blob(program, variant="invalid"): + """program: (text, hex) pairs; a pair whose text is None is a word llvm-mc rejects, listed as the variant says.""" + code = b"".join(bytes.fromhex(raw) for _, raw in program) + lines = [] + for text, raw in program: + if text is not None: + lines.append(f"\t{text:<40}{encoding(raw)}") + continue + second = bytes.fromhex(raw)[4:8] + lines.append(INVALID) + if variant == "invalid": + lines.append(INVALID) + elif variant == "junk": # the second word decodes as an instruction of its own, bytes as stored + lines.append(f"\ts_nop 0{'':<33}" + encoding(second.hex())) + else: # printed with another encoding than the blob holds + lines.append("\texp mrt0 v0, v0, v0, v0 done vm " + encoding("0f 18 00 f8 00 00 00 00")) + head = f"; {NAME} code 0x{CODE_START:x}..0x{CODE_START + len(code):x} (scan), gfx1013, 2 invalid words" + header = bytearray(CODE_START) + struct.pack_into("<4I", header, 0x138, 0x88, 32, 1, 1) + struct.pack_into(" lo for lo, hi in spans)] + return sorted(kept + restored, key=lambda i: i["pc"]) + + def output_signature(path, name): """OSG1 elements as (register, system value), one per register (first element wins).""" d = shader_container(path, name) @@ -17420,6 +17455,7 @@ def translate(path): ins["normalized"] = True ins["pc"] = at pos = at + len(enc) + insns = restore_vcc_tuples(insns, blob, info["code_start"], info.get("code_end")) insns = fold_far_branches(insns) insns = reachable_code(insns, info.get("code_end")) if any(i.get("normalized") for i in insns): From f7a338b14d5b70b6d183be5f1e7427582d41e3b3 Mon Sep 17 00:00:00 2001 From: JARVIX <273200855+jarvixaiassistant-glitch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:33:36 +0000 Subject: [PATCH 04/18] rdna2spirv: clamp restore_vcc_tuples decode slice to code_end Clamp blob[at:at + 20] to min(at + 20, stop) and check at + nbytes <= stop so multi-dword NSA MIMG instructions starting near code_end cannot read trailing bytes past code_end. Adds synthetic 12-byte NSA1 regression test. --- tests/semantic/test_vcc_tuple_fallback.py | 8 ++++++++ tools/rdna2spirv.py | 14 ++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index dd02b4509a..67e6bc5211 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -144,6 +144,14 @@ def test_other_undecodable_words_are_still_refused(self): with self.assertRaisesRegex(rdna2spirv.Unsupported, "fall-through into undecodable words"): translate(program) + 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_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)) + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index b5ff30b95b..c5135bcd46 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17165,15 +17165,17 @@ def restore_vcc_tuples(insns, blob, code_start, code_end): stop = min(len(blob), code_end if code_end is not None else len(blob)) restored, at = [], code_start while at + 8 <= stop: - found = None if at in covered else rdna2_decode.decode_bytes(blob[at:at + 20])["insns"][:1] + found = None if at in covered else rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] if found and found[0]["pc"] == 0 and any( a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"]): ins = found[0] - ins["pc"] = at - restored.append(ins) - at += len(ins["enc"]) // 2 - else: - at += 4 + nbytes = len(ins["enc"]) // 2 + if at + nbytes <= stop: + ins["pc"] = at + restored.append(ins) + at += nbytes + continue + at += 4 if not restored: return insns spans = [(r["pc"], r["pc"] + len(r["enc"]) // 2) for r in restored] From f605f8aee471020da29f9bf63df5036cd04ccd26 Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:30:46 +0100 Subject: [PATCH 05/18] rdna2spirv: put back the instructions llvm-mc's junk swallowed after a tuple into vcc llvm-mc rejects a scalar tuple that runs into vcc and prints the second word as junk. That junk is often longer than the word, so it also covers the instruction after the tuple, which stayed missing and refused the program with 'fall-through into undecodable words'. The words after a restored tuple are now decoded from the blob until the stream is back at a printed instruction. Pipeline library of 1.0.2.1, 2,684 compute programs: 1,816 -> 2,567 translate and pass spirv-val; the 1,816 modules are byte-identical. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- docs/shader_library.md | 8 +++- tests/semantic/test_vcc_tuple_fallback.py | 31 +++++++++++++++ tools/rdna2spirv.py | 47 ++++++++++++++++------- 4 files changed, 71 insertions(+), 17 deletions(-) diff --git a/docs/design.md b/docs/design.md index ba4c33fa1c..dd724a3837 100644 --- a/docs/design.md +++ b/docs/design.md @@ -291,7 +291,7 @@ How the generated SPIR-V expects the runtime to work: | Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88) and, with the same eight words, on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel), so the `vdst` preservation, the sign/zero extension, the ushort load across a dword and the element-size end check are GPU-checked on AMD too. `tools/hw_oracle` was not used for this; the Vulkan path above is what the translator runs. Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** Measured on an AMD Radeon RX 7900 XTX (`gfx1100`, driver 26.10.1) by running the instructions as a raw compute kernel (`tools/hw_oracle`, wave32, seeded synthetic bytes): the four loads zero-/sign-extend at byte offsets 0..7, the ushort at byte offset 3 merges byte 0 of the next dword, and with `NUM_RECORDS` = 8 the end check uses the element size (a ubyte at 7 reads where one at 8 returns 0, a ushort at 6 reads 0x5eee where one at 7 returns 0, an sshort at 7 returns 0 where an sbyte at 7 reads). `buffer_load_format_x` with `FORMAT` code 5 and `tbuffer_load_format_x format:[BUF_FMT_8_UINT]` return that byte zero-extended with the same 1-byte end check (at `NUM_RECORDS` 8, offset 7 reads 0x5e and 8 returns 0), and a V# whose `DST_SEL`s are 1/2/3/4 returns the integer 1 in all four components, not the fetched byte. The inactive-lane clause rests on the NVIDIA run. **Not GPU-verified.** | | 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. **Not GPU-verified.** | | Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). | -| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). | +| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). Where llvm-mc rejects such a tuple, `restore_vcc_tuples` decodes it from the blob, and with it the instructions its junk text swallowed, up to the next instruction llvm-mc printed (corpus count: `docs/shader_library.md`, section 5). | | 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | | Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | | Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | diff --git a/docs/shader_library.md b/docs/shader_library.md index 483426225f..71de878473 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -168,8 +168,12 @@ 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. 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. diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 67e6bc5211..01938dab40 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -136,6 +136,37 @@ 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_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 diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 6ab9cf395e..1790e04a63 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17157,25 +17157,44 @@ def restore_vcc_tuples(insns, blob, code_start, code_end): translator takes for these instructions. Every blob dword in the code range that no matched instruction covers is offered to it; the instruction is used only if its operands hold such a list, so no other undecodable word changes. Instructions printed inside the words of a restored one are dropped. The instructions already carry - their blob offsets in "pc"; returns the list sorted by it.""" + their blob offsets in "pc"; returns the list sorted by it. + + The junk can be longer than the second word it starts at, and then it also swallows the instruction after the + tuple, which no printed instruction covers once the junk is dropped. The words after a restored instruction are + therefore decoded the same way until the stream is back at an instruction llvm-mc printed there. A word that + llvm-mc itself rejected, inside no printed instruction, is not one of those and stays undecodable.""" import rdna2_decode - covered = set() + printed, covered, starts = set(), set(), set() + unplaced = None # the pc of the first junk since an instruction that matched the blob for ins in insns: - if not ins.get("normalized"): - covered.update(range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4)) + if ins.get("normalized"): + # Its pc is a lower bound: the word llvm-mc rejected before it was not counted. + unplaced = ins["pc"] if unplaced is None else unplaced + continue + if unplaced is not None: + printed.update(range(unplaced, ins["pc"], 4)) + unplaced = None + words = range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4) + printed.update(words) + starts.add(ins["pc"]) + covered.update(words) stop = min(len(blob), code_end if code_end is not None else len(blob)) restored, at = [], code_start - while at + 8 <= stop: - found = None if at in covered else rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] - if found and found[0]["pc"] == 0 and any( - a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"]): + resync = False # at follows a restored instruction and is inside junk llvm-mc printed, not at a start + while at + 4 <= stop: + found = None + if resync or at not in covered: + found = rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] + if found and found[0]["pc"] == 0 and at + len(found[0]["enc"]) // 2 <= stop and (resync or any( + a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"])): ins = found[0] - nbytes = len(ins["enc"]) // 2 - if at + nbytes <= stop: - ins["pc"] = at - restored.append(ins) - at += nbytes - continue + ins["pc"] = at + restored.append(ins) + at += len(ins["enc"]) // 2 + # nothing runs on past these, so the words after them are not known to be code + resync = at in printed and at not in starts and base_op(ins["op"]) not in ("s_branch", "s_endpgm", "s_setpc_b64") + continue + resync = False at += 4 if not restored: return insns From 688674095cba178f3e0ae9d66710f364af4f5d50 Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:45:15 +0100 Subject: [PATCH 06/18] test_vcc_tuple_fallback: cover where a resync starts and stops Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_vcc_tuple_fallback.py | 56 +++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 01938dab40..6bbf1719ee 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -184,5 +184,61 @@ def test_nsa_mimg_with_vcc_tuple_does_not_read_past_code_end(self): self.assertEqual((restored[0]["pc"], len(restored[0]["enc"]) // 2), (0, 12)) +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_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() From ebcb0acad599f0199b827a7ebc8008585aaa5dd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCzgar=20Koray=20Gen=C3=A7?= Date: Tue, 24 Nov 2026 08:42:05 -0800 Subject: [PATCH 07/18] tools: decode the pipeline-library compute programs llvm-mc refuses llvm-mc 21 cannot decode SMEM loads whose SOFFSET is null (0x7D), so whole pipeline-library compute programs of 1.0.2.1 came out with invalid words and failed to translate. For compute programs, shader_disasm now falls back to rdna2_decode when that decodes more of the program, and rdna2_decode reads VOPC with DPP16/DPP8 as the 8-byte form it is. rdna2spirv: - SMEM with vcc as its base reads the vcc_lo/vcc_hi pair. - s_flbit_i32_b64 of a lane mask reads the wave's 64-bit mask (18 library programs), as s_ff1_i32_b64 already does. - s_bitreplicate_b64_b32 of a lane mask into plain scalar data replicates the wave's mask word (6 library programs); into exec/vcc it stays Unsupported. test_salu_flbit_64: the lane-mask case now translates (the subgroup op is outside the single-invocation interpreter), so the test checks that. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_salu_flbit_64.py | 6 ++++-- tools/fspx_unpack.py | 2 +- tools/rdna2_decode.py | 26 ++++++++++++++++++++++++++ tools/rdna2spirv.py | 21 ++++++++++++++++----- tools/shader_disasm.py | 14 +++++++++++++- tools/shader_library.py | 2 +- 6 files changed, 61 insertions(+), 10 deletions(-) diff --git a/tests/semantic/test_salu_flbit_64.py b/tests/semantic/test_salu_flbit_64.py index faf480eb32..cf11818075 100644 --- a/tests/semantic/test_salu_flbit_64.py +++ b/tests/semantic/test_salu_flbit_64.py @@ -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"]) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index 5cb94813e7..cc1d5de819 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -254,7 +254,7 @@ 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) + 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) diff --git a/tools/rdna2_decode.py b/tools/rdna2_decode.py index d503784657..b95d7ad22c 100644 --- a/tools/rdna2_decode.py +++ b/tools/rdna2_decode.py @@ -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("> 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: diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 8d91dac70e..1cf8a7a90f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7584,8 +7584,15 @@ 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": raise Unsupported(op + " on a lane mask") @@ -7598,7 +7605,9 @@ def _insn(self, ins): self.emit(f"{bit} = OpBitwiseAnd %uint {shifted} {self.cu(1)}") self.set_exec(bit) 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: @@ -8348,11 +8357,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 diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index a119e74aaf..4436c117da 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -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, "" diff --git a/tools/shader_library.py b/tools/shader_library.py index 233e6ba565..a491589070 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -392,7 +392,7 @@ def extraction_paths(): def one(job): entry, name, code, start, end = job - asm, invalid, err = disasm.disasm(code, a.mcpu) + asm, invalid, err = disasm.disasm(code, a.mcpu, compute=True) entry["invalid_words"] = invalid with open(os.path.join(disasm_dir, name + ".s"), "w", encoding="utf-8", newline="\n") as f: f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n") From bf0c4d99ce4fca375a89538d200efdd7cb70f84d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCzgar=20Koray=20Gen=C3=A7?= Date: Tue, 24 Nov 2026 09:02:59 -0800 Subject: [PATCH 08/18] tests: fspx_unpack takes the decoder listing when llvm-mc reports invalid words Co-Authored-By: Claude Opus 5.5 --- tests/test_fspx_unpack.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 946da380cf..e16111af89 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -214,7 +214,9 @@ 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") @@ -222,9 +224,10 @@ def test_disassembly_with_invalid_words_keeps_listing(self): 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") From bec14f22599924c9d6d98b76714e00b6e0cc798a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCzgar=20Koray=20Gen=C3=A7?= Date: Tue, 24 Nov 2026 09:17:13 -0800 Subject: [PATCH 09/18] tools: the last pipeline-library compute programs of 1.0.2.1 The retail boot reached 50 pipeline-library compute programs that had no translation. Dumped from the running game, they all translate and pass spirv-val after these changes: - fspx_unpack.code_range: some programs carry a 24-byte hash prologue (two VOP3 words, then s_inst_prefetch) instead of 36 bytes; two or three hash words now count (shader_library uses the same range). - fspx_unpack --last-endpgm: early exits branch past the first s_endpgm, and data after the code can hold s_endpgm words, so a program ends at the first s_endpgm whose listing keeps every branch inside the code. - rdna2spirv: v_cmp_*_dpp into vcc (12 compares in reductions), taken when every lane writes (full row/bank masks with bound_ctrl:1, or DPP8). - rdna2spirv: s_bitreplicate_b64_b32 of a constant into vcc (6 programs), as the exec form does. Co-Authored-By: Claude Opus 5.5 --- .../test_salu_quadmask_bitreplicate.py | 9 +++ tests/test_fspx_unpack.py | 21 ++++++ tools/fspx_unpack.py | 74 +++++++++++++++++-- tools/rdna2spirv.py | 27 +++++-- tools/shader_library.py | 2 +- 5 files changed, 122 insertions(+), 11 deletions(-) diff --git a/tests/semantic/test_salu_quadmask_bitreplicate.py b/tests/semantic/test_salu_quadmask_bitreplicate.py index 9fa67cbbfb..6ededcbb6f 100644 --- a/tests/semantic/test_salu_quadmask_bitreplicate.py +++ b/tests/semantic/test_salu_quadmask_bitreplicate.py @@ -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"], diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index e16111af89..852b70cbf4 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -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) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index cc1d5de819..a2a8f09740 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -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"") @@ -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(" 0}, **decode_kind0(blob[0]), } return (meta, blob), 0 @@ -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. @@ -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 @@ -254,6 +313,11 @@ def main(argv=None) -> int: listing = None if disasm and meta["code"]["end"]: start, end = meta["code"]["start"], meta["code"]["end"] + 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] diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 1cf8a7a90f..748f10f3fb 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -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") @@ -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: @@ -7594,16 +7602,25 @@ def _insn(self, ins): 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 mask_words is not None: words = mask_words diff --git a/tools/shader_library.py b/tools/shader_library.py index a491589070..193eb6a2cb 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -354,7 +354,7 @@ def extraction_paths(): code = program(b, lib, i) start, end = code_range(code) meta = {"program": i, "stage": st, "offset": lib["programs"][i][0], "size": len(code), - "code": {"start": start, "end": end, "prologue": start == fspx_unpack.PROLOGUE_SIZE}} + "code": {"start": start, "end": end, "prologue": start > 0}} state = blob(b, lib, cs_state[i]) if i in cs_state else None if state is not None: meta.update(fspx_unpack.decode_kind0(state)) From 091cd9680bc90a7bbad8ec0333be3878e198b2e3 Mon Sep 17 00:00:00 2001 From: JARVIX <273200855+jarvixaiassistant-glitch@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:48:02 +0000 Subject: [PATCH 10/18] rdna2spirv: restrict restore_vcc_tuples to reachable offsets and protect branch targets Do not scan unreachable embedded data words skipped by s_branch or after s_endpgm / s_setpc_b64 in restore_vcc_tuples. Walk only offsets reachable from code_start via matched instructions, fall-through, and direct/folded far branches, and discard any restored instruction whose interior dwords are targeted by a reachable branch. Fixes the synthetic edge case reported on #596 / #674 by @Snooozs where an unreachable data word equal to the first dword of an 8-byte vcc-tuple load right before a branch target caused restore_vcc_tuples to swallow the target instruction and fail with 'branch into data'. Adds regression tests covering: skipped data word before a matched branch target, skipped data word before a vcc-tuple load at the branch target, data word after s_endpgm before a branch target, and fall-through into a data word directly before a branch target. --- tests/semantic/test_vcc_tuple_fallback.py | 65 ++++++++++++++++++++++- tools/rdna2spirv.py | 63 ++++++++++++++++------ 2 files changed, 111 insertions(+), 17 deletions(-) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 67e6bc5211..9e8f3452e1 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -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 @@ -152,6 +155,66 @@ def test_nsa_mimg_with_vcc_tuple_does_not_read_past_code_end(self): 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) + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index c5135bcd46..b7164d948a 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17153,29 +17153,60 @@ def restore_vcc_tuples(insns, blob, code_start, code_end): s[100:107], a buffer resource in s[104:107]): it skips the first word as invalid and then prints the second word as an instruction of its own, one that is junk or does not match the blob (docs/shader_library.md section 5). The pure-Python decoder reads such a word as a VCCTuple list, [s100,...,s105,vcc_lo,vcc_hi], the form the - translator takes for these instructions. Every blob dword in the code range that no matched instruction covers - is offered to it; the instruction is used only if its operands hold such a list, so no other undecodable word - changes. Instructions printed inside the words of a restored one are dropped. The instructions already carry - their blob offsets in "pc"; returns the list sorted by it.""" + translator takes for these instructions. Only uncovered offsets reached from code_start by fall-through or + branches (including folded far branches) are offered to it, so unreachable embedded data words skipped by a + branch or after s_endpgm are never decoded across a following branch target; the instruction is used only if + its operands hold such a list and no reachable branch targets its interior dwords. Instructions printed inside + the words of a restored one are dropped. The instructions already carry their blob offsets in "pc"; returns + the list sorted by it.""" import rdna2_decode covered = set() for ins in insns: if not ins.get("normalized"): covered.update(range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4)) + folded = fold_far_branches(insns) + by_pc = {ins["pc"]: ins for ins in folded + if all(o in covered for o in range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4))} stop = min(len(blob), code_end if code_end is not None else len(blob)) - restored, at = [], code_start - while at + 8 <= stop: - found = None if at in covered else rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] - if found and found[0]["pc"] == 0 and any( - a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"]): - ins = found[0] - nbytes = len(ins["enc"]) // 2 - if at + nbytes <= stop: - ins["pc"] = at - restored.append(ins) - at += nbytes + restored, restored_covered, reachable_targets = [], set(), set() + seen, work = set(), [code_start] + while work: + at = work.pop() + while code_start <= at < stop and at not in seen: + seen.add(at) + ins = by_pc.get(at) + if ins is not None: + op = base_op(ins["op"]) + nxt = at + len(ins["enc"]) // 2 + if op in BRANCHES: + imm = next((x for x in ins["args"] if x["k"] == "imm"), None) + v = (imm["v"] & 0xFFFF) if imm else 0 + tgt = ins["target"] if "target" in ins else nxt + 4 * (v - 0x10000 if v & 0x8000 else v) + reachable_targets.add(tgt) + work.append(tgt) + if op == "s_branch": + break + if op in ("s_endpgm", "s_setpc_b64"): + break + at = nxt continue - at += 4 + if at in covered or at in restored_covered or at + 8 > stop: + break + found = rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] + if found and found[0]["pc"] == 0 and any( + a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"]): + r = found[0] + nbytes = len(r["enc"]) // 2 + if (at + nbytes <= stop + and not any(o in restored_covered for o in range(at, at + nbytes, 4))): + r["pc"] = at + restored.append(r) + restored_covered.update(range(at, at + nbytes, 4)) + at += nbytes + continue + break + restored = [r for r in restored + if not any(o in reachable_targets for o in range(r["pc"] + 4, r["pc"] + len(r["enc"]) // 2, 4))] if not restored: return insns spans = [(r["pc"], r["pc"] + len(r["enc"]) // 2) for r in restored] From 66cad1b445a7f99bbba64420e01fc869bae268ae Mon Sep 17 00:00:00 2001 From: Moriz82 <72836413+Moriz82@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:13:57 -0600 Subject: [PATCH 11/18] shader_library: keep each state of a compute program, select by code hash (TOOLS-LIBRARY-COMPUTE-BY-HASH) The run time finds a pipeline-library compute program by the SHA-256 of its code and of its record's state blob. shader_library.py kept one state per program, the last record's, so when two compute records used one program with different state blobs only one of the two pairs got an entry and a .state file. Each distinct state of a program is now written: the first under the program's name, each further one as _state_, with its own .code, .json, .state, listing and index entry. library.json names the entry of each record. A program with one state, the case of every program in the measured 1.0.2.1 library, is written exactly as before. --compute-hashes FILE writes only the compute programs whose code has one of the SHA-256 digests listed in FILE, with every state they are used with. It cannot be combined with --stages, and a digest no compute program has is an error before anything is written. tests/test_shader_library.py gets three tests on a synthetic library; all three fail on the base. The standard-library tests and the translator suite add no failing file. No retail library was read for this change. AI-assisted (Claude Code). Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 --- docs/shader_library.md | 6 +- tests/test_shader_library.py | 123 +++++++++++++++++++++++++++++++++++ tools/shader_library.py | 90 +++++++++++++++++++++---- 3 files changed, 204 insertions(+), 15 deletions(-) diff --git a/docs/shader_library.md b/docs/shader_library.md index be62ed2b68..98c8ce88e9 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -154,7 +154,9 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/.state`, its record's state blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library, every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs, - 2,693 records). It also writes `index.json` with each program's stage, and + 2,693 records). A program that records use with different state blobs is written once per distinct state, the + first under its name and each further one as `_state_`, so each pair of keys has an entry + (the library measured above has no such program). It also writes `index.json` with each program's stage, and `library.json` with the header and both pipeline tables, stage to program name. Programs are named `lib__`. * `--disasm` writes `disasm/.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. @@ -163,6 +165,8 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv interface. * `--save` writes the reassembled library. A saved file is also accepted as input. * `--stages` limits the output to some stages. +* `--compute-hashes FILE` instead writes only the compute programs whose code has one of the SHA-256 digests listed + in `FILE` (`fspx_code_sha256`), with every state they are used with. A digest no compute program has is an error. The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest diff --git a/tests/test_shader_library.py b/tests/test_shader_library.py index 6d4e88d1f4..bcdbb91af2 100644 --- a/tests/test_shader_library.py +++ b/tests/test_shader_library.py @@ -388,6 +388,129 @@ def test_compute_missing_state_removes_stale_state_and_skips_none_blob(self): self.assertIn("fspx_code_sha256", meta) self.assertNotIn("fspx_state_sha256", meta) + def two_state_library(self): + """Program 0 with three state blobs, two of them the same bytes, and once without a state; program 1 with one + of those blobs; program 2 in a graphics pipeline. Returns (library, the two distinct states, program 0).""" + first, second = kind0(), kind0(threads=(32, 1, 1)) + code = prog(3) + compute = [(0, NONE, 0, NONE), (1, NONE, 0, NONE), (2, NONE, 0, NONE), (NONE, NONE, 0, NONE), + (1, NONE, 1, NONE)] + lib = build([(NONE, NONE, {0: (2, 3)})], compute, [first, second, first, layout_blob(2, D_PS)], + [code, prog(4), prog(5)]) + return lib, (first, second), code + + # The entries of that library's compute programs: program 0, its second state (blob 1) and program 1. + TWO_STATE_NAMES = [sl.program_name(0, {"cs"}), sl.program_name(0, {"cs"}) + "_state_1", sl.program_name(1, {"cs"})] + + def test_program_with_two_states_gets_an_entry_for_each(self): + lib, (first, second), code = self.two_state_library() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + out = os.path.join(tmp, "out") + # A further state is an output like any other: --save must not name it. + names = self.TWO_STATE_NAMES + self.assert_save_overlap(src, out, os.path.join(out, "fspx", names[1] + ".state"), "--stages", "cs") + self.assertFalse(os.path.exists(out)) + rc, text = self.run_main(src, "--out", out, "--stages", "cs") + self.assertEqual(rc, 0) + self.assertIn("3 written", text) + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + index = json.load(f) + self.assertEqual([(e["file"], e["program"], e["threads"]) for e in index], + [(names[0] + ".dxbc", 0, [8, 8, 1]), (names[1] + ".dxbc", 0, [32, 1, 1]), + (names[2] + ".dxbc", 1, [32, 1, 1])]) + self.assertEqual(sorted(os.listdir(os.path.join(out, "fspx"))), + sorted(n + ext for n in names for ext in (".code", ".json", ".state"))) + for name, state in zip(names, (first, second, second)): + with open(os.path.join(out, "fspx", name + ".state"), "rb") as f: + self.assertEqual(f.read(), state) + for name in names[:2]: + with open(os.path.join(out, "fspx", name + ".code"), "rb") as f: + self.assertEqual(f.read(), code) + # Both entries of program 0 have its code key, and each its own state key. + metas = [shader_meta.collect(os.path.join(out, "disasm", n + ".s"), n, [[]], [[]]) for n in names[:2]] + self.assertEqual({m["fspx_code_sha256"] for m in metas}, {hashlib.sha256(code).hexdigest()}) + self.assertEqual([m["fspx_state_sha256"] for m in metas], + [hashlib.sha256(first).hexdigest(), hashlib.sha256(second).hexdigest()]) + # Every record names the entry with its state; the one without a state names the program. + with open(os.path.join(out, "library.json"), encoding="utf-8") as f: + self.assertEqual([c["program"] for c in json.load(f)["compute"]], + [names[0], names[1], names[0], names[0], names[2]]) + + def test_compute_hashes_select_programs_by_their_code(self): + lib, (first, second), code = self.two_state_library() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + hashes = os.path.join(tmp, "hashes.txt") + with open(hashes, "w", encoding="utf-8", newline="\n") as f: + f.write("\n " + hashlib.sha256(code).hexdigest().upper() + "\n\n") + out = os.path.join(tmp, "out") + names = self.TWO_STATE_NAMES[:2] + self.assert_save_overlap(src, out, os.path.join(out, "fspx", names[1] + ".code"), + "--compute-hashes", hashes) + self.assertFalse(os.path.exists(out)) + rc, text = self.run_main(src, "--out", out, "--compute-hashes", hashes) + self.assertEqual(rc, 0) + self.assertIn("2 written", text) + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + self.assertEqual([e["file"] for e in json.load(f)], [n + ".dxbc" for n in names]) + self.assertEqual(sorted(os.listdir(os.path.join(out, "fspx"))), + sorted(n + ext for n in names for ext in (".code", ".json", ".state"))) + for name, state in zip(names, (first, second)): + with open(os.path.join(out, "fspx", name + ".state"), "rb") as f: + self.assertEqual(f.read(), state) + # The tables are the library's, whatever was selected. + with open(os.path.join(out, "library.json"), encoding="utf-8") as f: + summary = json.load(f) + self.assertEqual([c["program"] for c in summary["compute"]], + [names[0], names[1], names[0], names[0], self.TWO_STATE_NAMES[2]]) + self.assertEqual(summary["graphics"][0]["stages"], {"ps": sl.program_name(2, {"ps"})}) + + def test_compute_hashes_are_checked_before_anything_is_written(self): + lib, _, code = self.two_state_library() + digest = hashlib.sha256(code).hexdigest() + pixel = hashlib.sha256(sl.program(lib, sl.parse(lib), 2)).hexdigest() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + out = os.path.join(tmp, "out") + listed = os.path.join(tmp, "hashes.txt") + + def usage_error(text, *args): + with open(listed, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + err = io.StringIO() + with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as caught: + self.run_main(src, *args) + self.assertEqual(caught.exception.code, 2) + return err.getvalue() + + self.assertIn("not allowed with", usage_error(digest, "--out", out, "--stages", "cs", + "--compute-hashes", listed)) + self.assertIn("--compute-hashes needs --out", usage_error(digest, "--save", os.path.join(tmp, "l.bin"), + "--compute-hashes", listed)) + for text in ("", "\n", digest[:-1], digest + " not-a-digest", "0x" + digest): + with self.subTest(text=text): + self.assertIn("cannot read --compute-hashes", usage_error(text, "--out", out, + "--compute-hashes", listed)) + self.assertIn("cannot read --compute-hashes", + usage_error(digest, "--out", out, "--compute-hashes", os.path.join(tmp, "missing.txt"))) + # A digest no compute program has, here an unknown one and a pixel program's. + for text in (digest + "\n" + "0" * 64, pixel): + with self.subTest(text=text): + with open(listed, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + with self.assertRaises(sl.LibraryError) as caught: + self.run_main(src, "--out", out, "--compute-hashes", listed) + self.assertIn("match no compute program", str(caught.exception)) + self.assertFalse(os.path.exists(out)) + self.assertFalse(os.path.exists(os.path.join(tmp, "l.bin"))) + def test_same_code_with_distinct_states_gets_distinct_state_keys(self): code = prog(0x44556677) s_a, s_b = kind0(threads=(32, 1, 1)), kind0(threads=(64, 1, 1)) diff --git a/tools/shader_library.py b/tools/shader_library.py index 233e6ba565..5545ab1f6e 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -20,17 +20,24 @@ and tools/rdna2spirv.py reads (fspx/.code, fspx/.json, index.json). A compute program also gets its record's state blob as fspx/.state, as fspx_unpack.py writes kind 0: the runtime finds a program the executable passes to Xbox device slot 67 by the SHA-256 of both (docs/fspx.md, "Build and run-time lookup"). In the 1.0.2.1 -library every compute program has exactly one state blob (2,684 programs, 2,693 records). +library every compute program has exactly one state blob (2,684 programs, 2,693 records). A program that compute +records use with different state blobs is written once per distinct state, so that each pair of keys has its entry: +the first state under the program's name, each further one as _state_. Usage: - python -I shader_library.py --out DIR [--stages cs,ps,vs,ms] [--disasm] - [--mcpu gfx1013] [--jobs N] + python -I shader_library.py --out DIR [--stages cs,ps,vs,ms | --compute-hashes FILE] + [--disasm] [--mcpu gfx1013] [--jobs N] python -I shader_library.py --save library.bin # the reassembled file, nothing else DIR/library.json gets the header, both pipeline tables (stage -> program name) and the per-program stage. Programs are named lib__. The output is game data and must stay in the user's work folder. + +--compute-hashes FILE writes only the compute programs whose code has one of the SHA-256 digests listed in FILE (the +fspx_code_sha256 of the translation index; whitespace-separated), with every state they are used with. A digest no +compute program has is an error. """ import argparse +import hashlib import json import mmap import os @@ -258,13 +265,48 @@ def program_name(i: int, stages) -> str: return f"lib_{st}_{i:05d}" +def compute_variants(b: bytes, lib: dict, names: dict): + """({program: {state bytes: name}}, {(program, state blob index): name}) over the compute records. + + The run time finds a slot-67 program by its code and its state, so a program that records use with different + state blobs needs an entry for each. The first state met keeps the program's name and each further distinct one + gets _state_; records whose blobs hold the same bytes share a name, and a record without a + state names the program itself.""" + variants, by_record = {}, {} + for rec in lib["compute"]: + i, state_id = rec["program"], rec["state"] + if i is None: + continue + states = variants.setdefault(i, {}) + if state_id is None: + by_record[i, None] = names[i] + continue + state = blob(b, lib, state_id) + if state not in states: + states[state] = names[i] if not states else f"{names[i]}_state_{state_id}" + by_record[i, state_id] = states[state] + return variants, by_record + + +def read_hashes(path: str) -> set: + """The SHA-256 digests of a --compute-hashes file, lower case. ValueError when it has none or another word.""" + with open(path, encoding="utf-8") as f: + hashes = set(f.read().lower().split()) + if not hashes or not all(re.fullmatch(r"[0-9a-f]{64}", h) for h in hashes): + raise ValueError("expected one or more SHA-256 digests of 64 hex digits") + return hashes + + def main(argv=None) -> int: ap = argparse.ArgumentParser(description="Unpack the pipeline library stored in shaders.rpf.") ap.add_argument("src", help="shaders.rpf, or a library file written with --save") ap.add_argument("--out", help="output folder (library.json, index.json, fspx/, disasm/)") ap.add_argument("--save", help="write the reassembled library file here (must not overlap --out paths)") - ap.add_argument("--stages", default="cs,ps,vs,ms", - help="stages whose programs to write (default cs,ps,vs,ms; 'all' adds the unidentified slot)") + select = ap.add_mutually_exclusive_group() + select.add_argument("--stages", default="cs,ps,vs,ms", + help="stages whose programs to write (default cs,ps,vs,ms; 'all' adds the unidentified slot)") + select.add_argument("--compute-hashes", metavar="FILE", + help="write only the compute programs whose code has one of the SHA-256 digests in FILE") ap.add_argument("--disasm", action="store_true", help="also write disasm/.s (needs llvm-mc, see LLVM_MC)") ap.add_argument("--mcpu", default="gfx1013", help="llvm-mc CPU for --disasm (default gfx1013)") ap.add_argument("--carve", help="a tools/shader_carve.py output folder: name each program's source shader by the " @@ -277,6 +319,14 @@ def main(argv=None) -> int: ap.error("--jobs must be at least 1") if not a.out and not a.save: ap.error("give --out, --save or both") + hashes = None + if a.compute_hashes: + if not a.out: + ap.error("--compute-hashes needs --out") + try: + hashes = read_hashes(a.compute_hashes) + except (OSError, ValueError) as error: + ap.error(f"cannot read --compute-hashes {a.compute_hashes}: {getattr(error, 'strerror', None) or error}") with open(a.src, "rb") as f: head = f.read(4) f.seek(0) @@ -302,8 +352,25 @@ def main(argv=None) -> int: summary_path = os.path.join(a.out, "library.json") index_path = os.path.join(a.out, "index.json") names = {i: program_name(i, lib["stage"].get(i)) for i in range(lib["header"]["programs"])} + variants, compute_names = compute_variants(b, lib, names) want = None if a.stages == "all" else set(a.stages.split(",")) + if hashes is not None: + want = {"cs"} selected = [i for i in names if want is None or lib["stage"].get(i, set()) & want] + if hashes is not None: + code_hash = {i: hashlib.sha256(program(b, lib, i)).hexdigest() for i in selected} + selected = [i for i in selected if code_hash[i] in hashes] + missing = hashes - {code_hash[i] for i in selected} + if missing: + raise LibraryError(f"{len(missing)} of the {len(hashes)} --compute-hashes digests match no compute " + f"program of the library, first {min(missing)}") + + def selected_programs(): + """(program, name, state bytes or None): one per program, and one more per further state of a compute one.""" + for i in selected: + for state, name in (variants.get(i) or {None: names[i]}).items(): + yield i, name, state + carve_errors = [] sources = carve_digests(a.carve, errors=carve_errors) if a.carve else None @@ -321,8 +388,7 @@ def extraction_paths(): yield from (fspx_dir, summary_path, index_path) if disasm_dir: yield disasm_dir - for i in selected: - name = names[i] + for i, name, _ in selected_programs(): yield os.path.join(fspx_dir, name + ".code") yield os.path.join(fspx_dir, name + ".json") # Extraction writes the compute state or removes a stale sidecar at this path. @@ -345,20 +411,16 @@ def extraction_paths(): if a.save: with open(a.save, "wb") as f: f.write(b) - cs_state = {c["program"]: c["state"] for c in lib["compute"] - if c["program"] is not None and c["state"] is not None} index, written, work = [], 0, [] - for i in selected: + for i, name, state in selected_programs(): stages = lib["stage"].get(i) st = "+".join(sorted(stages)) if stages else "unused" code = program(b, lib, i) start, end = code_range(code) meta = {"program": i, "stage": st, "offset": lib["programs"][i][0], "size": len(code), "code": {"start": start, "end": end, "prologue": start == fspx_unpack.PROLOGUE_SIZE}} - state = blob(b, lib, cs_state[i]) if i in cs_state else None if state is not None: meta.update(fspx_unpack.decode_kind0(state)) - name = names[i] entry = {"file": name + ".dxbc", "stage": st, "program": i} digests = sorted(lib["digest"].get(i, ())) meta["digest"] = [d.hex() for d in digests] @@ -412,8 +474,8 @@ def named(stages): "layout": lib["layout"], "graphics": [{"hash": g["hash"], "state": g["state"], "input_layout": g["input_layout"], "stages": named(g["stages"])} for g in lib["graphics"]], - "compute": [{"hash": c["hash"], "state": c["state"], "program": names.get(c["program"])} - for c in lib["compute"]], + "compute": [{"hash": c["hash"], "state": c["state"], + "program": compute_names.get((c["program"], c["state"]))} for c in lib["compute"]], } with open(summary_path, "w", encoding="utf-8", newline="\n") as f: json.dump(summary, f, indent=1) From 4e1ca11a650afd3f187adba55a7938a74b32f009 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 23:35:37 +0100 Subject: [PATCH 12/18] fix: shader_disasm prints the v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 words llvm-mc rejects, so the FSR4 FSPX programs translate The FidelityFX upscaler programs hold 89 such words in 8 programs (docs/fspx.md); the translator already models the form but the listing could not carry it, so the programs were refused as a fall-through into undecodable words. --- docs/fspx.md | 9 + tests/semantic/test_alu_dot4_i8.py | 4 +- .../semantic/test_fspx_dot4_op_sel_disasm.py | 157 ++++++++++++++++++ tools/shader_disasm.py | 56 +++++++ 4 files changed, 224 insertions(+), 2 deletions(-) create mode 100644 tests/semantic/test_fspx_dot4_op_sel_disasm.py diff --git a/docs/fspx.md b/docs/fspx.md index a603545e93..12025a239b 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -149,6 +149,15 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. `op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`. + - `tools/shader_disasm.py` (so `fspx_unpack.py --disasm` and `make_game.py`) prints such a word as + `v_dot4_i32_i8 vD, a, b, c op_sel:[0,1,0] op_sel_hi:[1,0,1]` with its real encoding. A dword pair that llvm-mc + rejected, with exactly opcode 0x16, `op_sel` 2, `op_sel_hi` 5, no `clamp` and no `neg`, is decoded with the two + fields at their defaults and then given the fields and the encoding back, so the translator reads it and its + encoding check against the blob passes. Any other `op_sel`/`op_sel_hi` value, `clamp` or `neg` is still + undecodable (only this one was measured). A pair llvm-mc accepted, such as a literal followed by an instruction, + is never touched. `tests/semantic/test_fspx_dot4_op_sel_disasm.py` checks it with llvm-mc (the 5 measured + operand sets, and the forms that stay refused); the 89 words of the real programs are not re-run here, because + that needs the package's DLL. ## Kind 7: records diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py index 23c73bdaa0..ffefcbbd48 100644 --- a/tests/semantic/test_alu_dot4_i8.py +++ b/tests/semantic/test_alu_dot4_i8.py @@ -15,8 +15,8 @@ op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words (0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit -ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can -carry it. +ops. `ref_op_sel` reproduces them. A listing carries the form since tools/shader_disasm.py prints it +(tests/semantic/test_fspx_dot4_op_sel_disasm.py). neg_lo and neg_hi. llvm-mc accepts them on v_dot4_i32_i8 for gfx1036 (not on v_dot4c_i32_i8), and the hardware does not ignore them: on the same GPU, 5 operand sets with 8 forms each gave the words of `ref_neg`, 9 of which are in diff --git a/tests/semantic/test_fspx_dot4_op_sel_disasm.py b/tests/semantic/test_fspx_dot4_op_sel_disasm.py new file mode 100644 index 0000000000..7ff52527f4 --- /dev/null +++ b/tests/semantic/test_fspx_dot4_op_sel_disasm.py @@ -0,0 +1,157 @@ +"""The FidelityFX upscaler's programs (docs/fspx.md) hold 89 v_dot4_i32_i8 words with op_sel 2 and op_sel_hi 5, which +llvm-mc does not decode: it rejects the first dword, reads the second as another instruction, and the translator then +refuses the program ("fall-through into undecodable words"), so 9 of the 29 programs had no pipeline and the DLL's +next pipeline call faulted. tools/shader_disasm.py now prints such a word as the instruction it is, with its +op_sel/op_sel_hi fields and its real encoding, so the translator reads it and checks it against the blob. + +Each case assembles a small program with llvm-mc, turns one v_dot4_i32_i8 into the op_sel 2 / op_sel_hi 5 form by +setting those fields in its two dwords, disassembles the bytes with shader_disasm, and translates the listing in the +FSPX layout (disasm/, fspx/.code and .json). The expected words are the ones measured on gfx1036 +(MEASURED_OP_SEL in test_alu_dot4_i8.py). They need llvm-mc with the AMDGPU target (LLVM_MC, or llvm-mc on PATH) and +skip without it. No GPU and no game files. + + python -I tests/semantic/test_fspx_dot4_op_sel_disasm.py +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.dont_write_bytecode = True +sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import shader_disasm # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +from test_alu_dot4_i8 import MEASURED_OP_SEL, ref # noqa: E402 + +MCPU = "gfx1030" # fspx_unpack.py's default: LLVM decodes v_dot4_i32_i8 for it and not for gfx1013 +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 2) << 14 + w1 = w1 & ~(3 << 27) | (op_sel_hi & 3) << 27 + return struct.pack("<2I", w0, w1) + + +def program(a, b, addend, middle): + """Code bytes of: v8 = the v_dot4_i32_i8 given by `middle` (its two dwords), v9 = the plain v_dot4_i32_i8 on the + same registers, both written to mrt0. Returns (code, byte offset of the first dot4).""" + head = b"".join(assemble(line) for line in ( + f"v_mov_b32_e32 v1, 0x{a:08x}", f"v_mov_b32_e32 v2, 0x{b:08x}", f"v_mov_b32_e32 v3, 0x{addend:08x}")) + tail = b"".join(assemble(line) for line in ( + "v_dot4_i32_i8 v9, v1, v2, v3", "exp mrt0 v8, v9, v8, v9 done vm", "s_endpgm")) + return head + middle + tail, len(head) + + +def translate_fspx(name, listing, code): + """SPIR-V assembly for a listing in the FSPX layout, with the code bytes it was disassembled from beside it.""" + with tempfile.TemporaryDirectory() as tmp: + for d in ("disasm", "fspx"): + os.mkdir(os.path.join(tmp, d)) + with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(os.path.join(tmp, "fspx", name + ".code"), "wb") as f: + f.write(code) + with open(os.path.join(tmp, "fspx", name + ".json"), "w", encoding="utf-8") as f: + json.dump({}, f) + src = os.path.join(tmp, "disasm", name + ".s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(listing) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(src) + + +def listing_of(name, code): + asm, bad, err = shader_disasm.disasm(code, MCPU) + return f"; {name} code 0x0..0x{len(code):x} (fspx), {MCPU}, {bad} invalid words\n" + asm, bad + + +@unittest.skipUnless(llvm_decodes_v_dot4(), "needs llvm-mc with the AMDGPU target that decodes v_dot4_i32_i8") +class Dot4OpSelListing(unittest.TestCase): + def plain_pair(self): + return assemble("v_dot4_i32_i8 v8, v1, v2, v3") + + def test_the_listing_carries_the_op_sel_word_and_the_program_runs(self): + for a, b, addend, measured in MEASURED_OP_SEL: + with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): + middle = with_op_sel(self.plain_pair(), 2, 5) + code, at = program(a, b, addend, middle) + listing, bad = listing_of("ps_fspx_dot4_op_sel", code) + self.assertEqual(bad, 0, listing) + lines = [ln for ln in listing.splitlines() if "v_dot4_i32_i8" in ln] + self.assertEqual(len(lines), 2, listing) + self.assertIn("v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", lines[0]) + self.assertIn("encoding: [" + ",".join(f"0x{x:02x}" for x in middle) + "]", lines[0]) + self.assertNotIn("op_sel", lines[1]) # the plain instruction next to it stays plain + words = support_words(translate_fspx("ps_fspx_dot4_op_sel", listing, code)) + self.assertEqual(words, [measured, ref(a, b, addend), measured, ref(a, b, addend)]) + + def test_other_op_sel_values_stay_undecodable(self): + # Only op_sel 2 / op_sel_hi 5 was measured on hardware; anything else is still rejected, never guessed. + for op_sel, op_sel_hi in ((1, 5), (4, 5), (2, 7), (0, 5), (2, 4)): + with self.subTest(op_sel=op_sel, op_sel_hi=op_sel_hi): + code, _ = program(1, 1, 0, with_op_sel(self.plain_pair(), op_sel, op_sel_hi)) + listing, bad = listing_of("ps_fspx_dot4_other", code) + self.assertNotIn("op_sel:[0,1,0] op_sel_hi:[1,0,1]", listing) + with self.assertRaises(rdna2spirv.Unsupported): # undecodable, or printed without a dropped field + translate_fspx("ps_fspx_dot4_other", listing, code) + + def test_a_clamp_or_neg_bit_on_the_word_stays_undecodable(self): + for name, shift, dword in (("clamp", 15, 0), ("neg_hi", 8, 0), ("neg_lo", 29, 1)): + with self.subTest(field=name): + middle = list(struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5))) + middle[dword] |= 1 << shift + code, _ = program(1, 1, 0, struct.pack("<2I", *middle)) + listing, bad = listing_of("ps_fspx_dot4_mods", code) + self.assertGreaterEqual(bad, 1) + self.assertNotIn("op_sel:[0,1,0]", listing) + + def test_data_that_looks_like_the_word_is_left_alone(self): + # The same two dwords as a 32-bit literal and the instruction after it decode with no invalid word, so they + # are not touched: only a word llvm-mc rejected is read as v_dot4_i32_i8. + pair = struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5)) + code = (assemble("v_mov_b32_e32 v4, 0x%08x" % pair[0]) + assemble("v_fmac_legacy_f32 v7, v1, v2") + + assemble("s_endpgm")) + self.assertEqual(struct.unpack_from("<2I", code, 4), pair) + listing, bad = listing_of("ps_fspx_dot4_literal", code) + self.assertEqual(bad, 0, listing) + self.assertNotIn("op_sel", listing) + + +def support_words(spv): + out = si.run_fragment(spv) + return list(out["%out_mrt0"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index 67a10ec13d..09d0246352 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -30,6 +30,7 @@ TRIPLE = "amdgcn--amdpal" ENDPGM = b"\x00\x00\x81\xbf" +DOT4_I8_OPCODE = 0x16 # VOP3P v_dot4_i32_i8 PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with FAILED = [] # (path, first stderr line) for shaders that produced no disassembly @@ -97,6 +98,9 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True fixed = with_vopc_dpp(code, mcpu, err) if fixed: return fixed + fixed = with_dot4_op_sel(code, mcpu, bad, err) + if fixed: + return fixed return asm, bad, err @@ -184,6 +188,58 @@ def with_vopc_dpp(code: bytes, mcpu: str, err: str): return None +def dot4_op_sel_words(code: bytes, offsets) -> dict: + """{offset: (word0, word1)} of the dword pairs at `offsets` that are v_dot4_i32_i8 with op_sel 2 and op_sel_hi 5, + no clamp and no neg: the form 89 words of the FidelityFX upscaler's programs take (docs/fspx.md). llvm-mc has no + decoding for it, and a plain v_dot4_i32_i8 has op_sel 0 and op_sel_hi 7. Only this combination is recognised: + its result was measured on hardware (tests/semantic/test_alu_dot4_i8.py), the other op_sel values were not.""" + found = {} + for at in sorted(offsets): + if at % 4 or at + 8 > len(code): + continue + w0, w1 = struct.unpack_from("<2I", code, at) + if (w0 >> 23 == 0x198 and (w0 >> 16) & 0x7F == DOT4_I8_OPCODE and (w0 >> 8) & 7 == 0 # VOP3P, neg_hi + and (w0 >> 11) & 7 == 2 and (w0 >> 14) & 1 == 1 and (w0 >> 15) & 1 == 0 # op_sel, hi[2], clamp + and (w1 >> 27) & 3 == 1 and (w1 >> 29) & 7 == 0): # op_sel_hi[1:0], neg_lo + found[at] = (w0, w1) + return found + + +def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str): + """The listing of `code` with each rejected v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 word printed as the instruction + it is, or None when there is none. llvm-mc rejects the pair, so it is decoded with the two fields at their + defaults (op_sel 0, op_sel_hi 7), and each such line gets the real fields and the real encoding back: the + translator then reads the instruction and checks its encoding against the blob. A word that is not printed as + v_dot4_i32_i8 at an instruction boundary was not an instruction (it sits in a literal or in data), so it is + left as it was and the pass runs again without it.""" + words = dot4_op_sel_words(code, invalid_offsets(err)) + while words and bad: + patched = bytearray(code) + for at, (w0, w1) in words.items(): + struct.pack_into("<2I", patched, at, w0 & ~(7 << 11), w1 | (2 << 27)) + asm, bad2, err2 = run_mc(bytes(patched), mcpu) + if not asm.strip(): + return None + invalid, pos, hit, lines = invalid_offsets(err2), 0, set(), [] + for line in asm.split("\n"): + enc = ENCODING.search(line) + if not enc: + lines.append(line) + continue + while pos in invalid: + pos += 4 + if pos in words and line.lstrip("\t").startswith("v_dot4_i32_i8 "): + hit.add(pos) + w0, w1 = words[pos] + original = ",".join(f"0x{b:02x}" for b in struct.pack("<2I", w0, w1)) + line = line[:enc.start()].rstrip() + " op_sel:[0,1,0] op_sel_hi:[1,0,1]" + line = f"{line:<40}; encoding: [{original}]" + lines.append(line) + pos += len(enc.group(1).split(",")) + if hit == set(words): + return "\n".join(lines), bad2, err2 + words = {at: w for at, w in words.items() if at in hit} + return None MAX_DATA_DWORDS = 1 << 16 From cc3aef810a2bf3b611dfb6d40bdc1c0bfc8e337b Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:02:58 -0500 Subject: [PATCH 13/18] test_vcc_tuple_fallback: widened scalar load with an SGPR offset, buffer store through a vcc resource luizwidmer/palmetto repairs these words outside the translator with tools/widen_smem_decode.py (the console's 112-SGPR file is wider than llvm-mc's 106). Here restore_vcc_tuples (#674) already decodes them from the blob; these cases pin the two forms its tests did not cover: s_buffer_load_dwordx8 into s[100:107] with an SGPR soffset and an immediate offset, and buffer_store_dword with its resource in s[104:107]. Encodings built from the field layout. Ported from luizwidmer/palmetto (GPL-3.0): the forms, from its docs/boot_frontier.md. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_vcc_tuple_fallback.py | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 9b614f3812..3aa66c9def 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -139,6 +139,39 @@ 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_load_with_register_offset_into_vcc(self): + # The widened scalar load with an SGPR soffset and an immediate offset (the form luizwidmer/palmetto's + # docs/boot_frontier.md measured in an FSPX program, built here from the field layout, not copied): + # s_buffer_load_dwordx8 [s100..s105,vcc_lo,vcc_hi], s[4:7], s12 offset:0x40 reads BASE + 0x40 + s12. + load = "02 19 2c f4 40 00 00 18" + program = [SET_SGPR_V[0], SET_SGPR_V[1], ("s_mov_b32 s6, 0x100", "ff 03 86 be 00 01 00 00"), SET_SGPR_V[3], + ("s_mov_b32 s12, 32", "a0 03 8c be"), + (None, load), 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 + 0x60 + 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_buffer_store_with_resource_in_vcc(self): + # buffer_store_dword v11, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen: a store through the widened resource too. + store = "00 10 70 e0 01 0b 1a 80" + program = SET_SGPR_V + [ + (None, LOAD_X4_VCC), WAIT, + ("v_mov_b32_e32 v1, 4", "84 02 02 7e"), + ("v_mov_b32_e32 v11, 0x5a5a1234", "ff 02 16 7e 34 12 5a 5a"), + (None, store), WAIT_V, + ("s_endpgm", "00 00 81 bf"), + ] + memory = {BASE + 4 * i: w for i, w in enumerate([OUT, 0, 16, 0x30000000])} + for variant in PROGRAM_VARIANTS: + with self.subTest(printed_as=variant): + mem = run(translate(program, variant), memory) + self.assertEqual(mem.get(OUT + 4), 0x5A5A1234) + 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 From d4b2afe0ec046b4cb3d22ad042430cb14cb07c76 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:05:29 -0500 Subject: [PATCH 14/18] rdna2spirv: a v_dot4_i32_i8 printed with default op_sel takes the stored fields llvm-mc decodes a VOP3P v_dot4_i32_i8 whose op_sel_hi is not [1,1,1] (op_sel bit 1 clear) but prints and re-encodes it with op_sel 0 / op_sel_hi 7, so translate() refused it as a dropped field. When those two fields are the only difference between the stored and the printed bytes, they are now read from the blob, in check_printed_encodings and in both re-anchoring paths, and the v_dot4_i32_i8 rule applies them as measured on gfx1036 (a non-default S2 half stays refused). Any other difference is still refused. Ported from luizwidmer/palmetto (GPL-3.0): its restore_vop3p_dot4. Its console_dot4_word (the op_sel 2 / op_sel_hi 5 words llvm-mc rejects) is not ported: #1317 prints those in shader_disasm.py. Test: tests/semantic/test_dot4_printed_op_sel.py, hand-built words. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- tests/semantic/test_dot4_printed_op_sel.py | 117 +++++++++++++++++++++ tools/rdna2spirv.py | 48 +++++++++ 3 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 tests/semantic/test_dot4_printed_op_sel.py diff --git a/docs/design.md b/docs/design.md index 396b29df40..a7fccf352d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -411,7 +411,7 @@ How the generated SPIR-V expects the runtime to work: | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | -| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). | +| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. A word `llvm-mc` does decode but prints with the default fields (op_sel_hi other than `[1,1,1]` with op_sel bit 1 clear: it re-encodes op_sel 0 / op_sel_hi 7, so the text names the wrong halves) takes the stored op_sel and op_sel_hi from the blob, in a clean listing (`check_printed_encodings`) and when re-anchoring, only when those two fields are the whole difference (`dot4_op_sel_fields`); anything else is still refused as a dropped field. Found in an FSPX program by luizwidmer/palmetto (GPL-3.0, ported); the fields are applied by the rule measured above, checked by `tests/semantic/test_dot4_printed_op_sel.py` (hand-built words); not re-counted over the corpus. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). | | Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | | Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | | LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win), `cs_w32_partial_permute.asm` (a 20-thread wave32: a launched lane whose source lane was never launched gets 0, and a send to a missing lane is lost; the same words from a raw 20-thread `hw_oracle` kernel on `gfx1036`) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | diff --git a/tests/semantic/test_dot4_printed_op_sel.py b/tests/semantic/test_dot4_printed_op_sel.py new file mode 100644 index 0000000000..85b90feef6 --- /dev/null +++ b/tests/semantic/test_dot4_printed_op_sel.py @@ -0,0 +1,117 @@ +"""A v_dot4_i32_i8 whose op_sel/op_sel_hi llvm-mc printed as the defaults takes the stored fields. + +llvm-mc decodes a VOP3P v_dot4_i32_i8 with op_sel_hi other than [1,1,1] but prints and re-encodes it with op_sel 0 and +op_sel_hi 7, so the listing names halves the instruction does not read. translate() used to refuse it ("a field the +disassembler dropped"); it now reads the two fields from the blob when they are the only difference +(rdna2spirv.dot4_op_sel_fields), and the v_dot4_i32_i8 rule applies them as measured on gfx1036 +(tests/semantic/test_alu_dot4_i8.py). Ported from luizwidmer/palmetto (GPL-3.0). Hand-built listing and blob, the +encodings assembled from the VOP3P field layout; no game data. + + python -I tests/semantic/test_dot4_printed_op_sel.py -v +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +from support import mrt0_words, rdna2spirv, translate_listing # noqa: E402 + +NAME = "ps_dot4_printed_op_sel" +CODE_START = 0x100 +A, B, C = 0x80FF7F01, 0x12F0FE7F, 0x00001000 + + +def dot4(op_sel=0, op_sel_hi=7, dst=0, srcs=(1, 2, 3)): + """VOP3P v_dot4_i32_i8 (opcode 0x16) vdst, v[srcs] with the given op_sel and op_sel_hi.""" + w0 = 0xCC000000 | (0x16 << 16) | ((op_sel_hi >> 2) & 1) << 14 | (op_sel & 7) << 11 | dst + w1 = (op_sel_hi & 3) << 27 | (256 + srcs[2]) << 18 | (256 + srcs[1]) << 9 | (256 + srcs[0]) + return struct.pack("<2I", w0, w1).hex(" ") + + +def v_mov(reg, value): + return (f"v_mov_b32_e32 v{reg}, 0x{value:x}", f"ff {2 * reg:02x} 02 7e " + struct.pack("> off) & 0xFF + return v - 256 if v & 0x80 else v + total = addend + for k in range(4): + half = (op_sel if k < 2 else op_sel_hi) + xo = 16 * ((half >> 0) & 1) + 8 * (k & 1) + yo = 16 * ((half >> 1) & 1) + 8 * (k & 1) + total += byte(a, xo) * byte(b, yo) + return total & 0xFFFFFFFF + + +def translate(stored_dot4, reanchor=False): + printed = SETUP + [PRINTED] + TAIL + stored = SETUP + [("", stored_dot4)] + TAIL + code = b"".join(bytes.fromhex(enc) for _, enc in stored) + data = listing(printed, CODE_START + len(code)) + blob = bytes(CODE_START) + code + if reanchor: # a listing with an undecodable word after the code goes through the re-anchoring path + data += b"; warning: invalid instruction encoding\n" + blob += b"\xff" * 4 + return translate_listing(NAME, data, fssm=blob) + + +class Dot4PrintedOpSelTest(unittest.TestCase): + def test_reference_is_the_plain_dot_product_for_the_defaults(self): + sb = [lambda x, k=k: (((x >> 8 * k) & 0xFF) ^ 0x80) - 0x80 for k in range(4)] + self.assertEqual(ref(A, B, C), (sum(f(A) * f(B) for f in sb) + C) & 0xFFFFFFFF) + + def test_default_fields_translate_as_printed(self): + self.assertEqual(mrt0_words(translate(dot4())), [ref(A, B, C)] * 4) + + def test_stored_op_sel_hi_is_read_from_the_blob(self): + # op_sel_hi [1,0,1]: byte pairs 2..3 of S1 come from its low half. llvm-mc decodes it and prints [1,1,1]. + for reanchor in (False, True): + with self.subTest(reanchor=reanchor): + got = mrt0_words(translate(dot4(op_sel_hi=5), reanchor)) + self.assertEqual(got, [ref(A, B, C, op_sel_hi=5)] * 4) + self.assertNotEqual(ref(A, B, C, op_sel_hi=5), ref(A, B, C)) + + def test_stored_op_sel_on_source_0_is_read_from_the_blob(self): + got = mrt0_words(translate(dot4(op_sel=1, op_sel_hi=6))) + self.assertEqual(got, [ref(A, B, C, op_sel=1, op_sel_hi=6)] * 4) + + def test_a_non_default_s2_half_stays_refused(self): + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(dot4(op_sel_hi=3)) + self.assertIn("op_sel", str(cm.exception)) + + def test_another_difference_is_still_a_dropped_field(self): + # The stored word names v4 as S2, the printed one v3: not an op_sel difference. + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(dot4(op_sel_hi=5, srcs=(1, 2, 4))) + self.assertIn("dropped", str(cm.exception)) + + def test_fields_helper(self): + printed = bytes.fromhex(dot4()) + self.assertEqual(rdna2spirv.dot4_op_sel_fields(bytes.fromhex(dot4(op_sel_hi=5)), printed, + "v_dot4_i32_i8"), (0, 5)) + self.assertIsNone(rdna2spirv.dot4_op_sel_fields(printed, printed, "v_dot4_i32_i8")) + self.assertIsNone(rdna2spirv.dot4_op_sel_fields(bytes.fromhex(dot4(op_sel_hi=5)), printed, + "v_dot2_i32_i16")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 0548ba0b05..0f4855ba87 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17274,6 +17274,48 @@ def restore_mix_inline_literal(ins, raw, literal): ins["enc"] = raw.hex() +def dot4_op_sel_fields(raw, printed, op): + """(op_sel, op_sel_hi) of a v_dot4_i32_i8 whose stored op_sel fields llvm-mc printed as the defaults, else None. + + llvm-mc decodes a VOP3P v_dot4_i32_i8 (opcode 0x16) whose op_sel_hi is not [1,1,1] (while op_sel bit 1 is clear; + with it set the word is rejected and tools/shader_disasm.py prints it, docs/fspx.md) but prints and re-encodes it + with op_sel 0 and op_sel_hi 7, so its text names halves the instruction does not read. The fields are op_sel (word + 0 bits 13:11) and op_sel_hi (word 1 bits 28:27 for sources 0 and 1, word 0 bit 14 for source 2). Accepted only when + the stored 8 bytes with just those two fields set to the defaults are the printed ones, so every other bit + (opcode, operands, neg, clamp) is what the text says. From luizwidmer/palmetto (GPL-3.0), which found such a + word in an FSPX program (op_sel_hi[1] clear, the rest of the word as printed).""" + if base_op(op) != "v_dot4_i32_i8" or len(raw) != 8 or len(printed) != 8 or raw[3] != 0xCC: + return None + w0, w1 = struct.unpack("<2I", raw) + if (w0 >> 16) & 0x7F != 0x16: + return None + op_sel = (w0 >> 11) & 7 + op_sel_hi = ((w1 >> 27) & 3) | (((w0 >> 14) & 1) << 2) + if (op_sel, op_sel_hi) == (0, 7): + return None + if struct.pack("<2I", (w0 & ~(7 << 11)) | (1 << 14), w1 | (3 << 27)) != printed: + return None + return op_sel, op_sel_hi + + +def restore_dot4_op_sel(ins, raw): + """Give ``ins`` the op_sel/op_sel_hi dot4_op_sel_fields reads from the stored bytes, and those bytes as its + encoding; False (``ins`` untouched) when it does not apply. The v_dot4_i32_i8 rule applies the fields as measured + on gfx1036 (docs/design.md, "Signed-byte dot products") and refuses a non-default S2 half.""" + fields = dot4_op_sel_fields(raw, bytes.fromhex(ins["enc"]), ins["op"]) + if fields is None: + return False + op_sel, op_sel_hi = fields + mods = [m for m in ins.get("mods", []) if not m.startswith(("op_sel:", "op_sel_hi:"))] + if op_sel: + mods.append("op_sel:[%s]" % ",".join(str((op_sel >> k) & 1) for k in range(3))) + if op_sel_hi != 7: + mods.append("op_sel_hi:[%s]" % ",".join(str((op_sel_hi >> k) & 1) for k in range(3))) + ins["mods"] = mods + ins["enc"] = raw.hex() + return True + + def restore_vcc_tuples(insns, blob, code_start, code_end, wave32=True): """Decode from the blob the instructions llvm-mc rejects because a scalar tuple runs into vcc. @@ -17581,6 +17623,8 @@ def check_printed_encodings(path, info): restore_mix_inline_literal(ins, raw12, literal) shift += 4 continue + if restore_dot4_op_sel(ins, raw): + continue raise Unsupported(f"{ins['op']} at 0x{ins['pc']:x}: the blob holds {raw.hex()}, LLVM printed " f"{enc.hex()} (a field the disassembler dropped)") @@ -17680,6 +17724,8 @@ def translate(path): if literal is not None: restore_mix_inline_literal(ins, blob[pos:pos + 12], literal) enc = blob[pos:pos + 12] + elif restore_dot4_op_sel(ins, window): + pass elif pos + len(enc) > len(blob): raise Unsupported("undecodable words (cannot re-anchor)") else: @@ -17703,6 +17749,8 @@ def translate(path): restore_mix_inline_literal(ins, blob[at:at + 12], literal) enc = blob[at:at + 12] # the 12 bytes the decoder read: the next one starts after them break + if restore_dot4_op_sel(ins, blob[at:at + len(enc)]): + break at += 4 skipped += 4 if skipped > 4096 or at >= len(blob): From 65362a4ffaf4ed1893bd1d94ee7ff0f155cdb7d2 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:14:06 -0500 Subject: [PATCH 15/18] s_bitreplicate_b64_b32 of a lane-mask half into data: test and contract-table sentence #998 added the rule (a 32-bit EXEC/VCC half as S0, read through Gen.wave_mask) without a test or a design.md entry. test_lane_mask_bitreplicate_flbit.py now runs it on every lane of a wave64 in the CPU interpreter, from exec_lo/exec_hi and from a compare's vcc_lo/vcc_hi, against the ISA pseudocode. design.md says it is interpreter-checked only, not measured on hardware. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- .../test_lane_mask_bitreplicate_flbit.py | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index a7fccf352d..4a85a897b3 100644 --- a/docs/design.md +++ b/docs/design.md @@ -454,7 +454,7 @@ How the generated SPIR-V expects the runtime to work: | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | | 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210), except under `s_flbit_i32_b64`, which reads the wave's whole mask as real bits (`wave_mask`, as `s_ff1_i32_b64` does): 63 minus the last active lane (the 1.0.2.1 pipeline library reads EXEC this way; wave64 run of EXEC and VCC masks in `tests/semantic/test_lane_mask_bitreplicate_flbit.py`). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | | `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by the unit test `ValuBfeMeasuredOnRdna2.test_translator_gives_the_gfx1036_words` in `tests/test_int_hw_probe.py`. | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. An EXEC or VCC destination of `s_bitreplicate_b64_b32` gives lane L bit L // 2 of S0 (EXEC since 6ecd922d9; VCC, which the 1.0.2.1 pipeline library writes from a constant, checked on every lane of a wave64 by `tests/semantic/test_lane_mask_bitreplicate_flbit.py`). Any other lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | +| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. An EXEC or VCC destination of `s_bitreplicate_b64_b32` gives lane L bit L // 2 of S0 (EXEC since 6ecd922d9; VCC, which the 1.0.2.1 pipeline library writes from a constant, checked on every lane of a wave64 by `tests/semantic/test_lane_mask_bitreplicate_flbit.py`). A 32-bit lane-mask source (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`) of `s_bitreplicate_b64_b32` into a scalar (non-EXEC/VCC) destination reads that half of the wave's mask as data (`Gen.wave_mask`, as `s_ff1_i32_b64` reads one) and replicates it as any scalar (#998, for 6 pipeline-library programs of 1.0.2.1). Confirmed only by the CPU interpreter on every lane of a wave64 (`test_lane_mask_bitreplicate_flbit.py`: EXEC halves and a compare's VCC halves, synthetic lines) and by the ISA pseudocode above; not measured on hardware. Any other lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | | 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| | Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). **A computed value written to EXEC** (`s_lshl_b32`, `s_add_u32`, `s_bfm_b32`, and every other SALU result that reaches `exec_lo`/`exec_hi` through `Gen.dst`) takes each lane's bit too: until 2026-11-24 the generic path tested the value for non-zero, so `s_lshl_b32 exec_lo, 1, s5` ran all 32 lanes of that half (SHADER-1264; `Gen.exec_bit`). The words are the GPU's, recorded in `runtime/test/shaders/cs_w32_exec_computed.asm` and `cs_w64_exec_computed.asm` (RTX 5070), and `tests/semantic/test_exec_computed.py` replays them through the CPU interpreter. A value that already holds this lane's bit of a mask (0 or ~0) gives the same answer. | | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | diff --git a/tests/semantic/test_lane_mask_bitreplicate_flbit.py b/tests/semantic/test_lane_mask_bitreplicate_flbit.py index 66743bd2cc..ecc55775b2 100644 --- a/tests/semantic/test_lane_mask_bitreplicate_flbit.py +++ b/tests/semantic/test_lane_mask_bitreplicate_flbit.py @@ -4,6 +4,8 @@ RDNA2 ISA, SOP1: - s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i], i in 0..31; SCC is not written. Into VCC, lane L's bit is S0 bit L // 2. + Of a 32-bit lane-mask source (exec_lo/exec_hi, vcc_lo/vcc_hi) into scalar data, S0 is that half of the wave's + mask, read as data (Gen.wave_mask), then replicated as any scalar. - s_flbit_i32_b64: the zeros above the first 1 from bit 63, -1 when S0 is 0. Of EXEC that is 63 minus the wave's last active lane. Synthetic programs only. @@ -60,6 +62,36 @@ def test_flbit_of_vcc(self): "s_endpgm"]) self.assertEqual(mem[OUT_AT], flbit_model((1 << n) - 1)) + def bitreplicate_of(self, setup, src): + mem = run(lane_index() + setup + [f"s_bitreplicate_b64_b32 s[10:11], {src}", "s_mov_b64 exec, -1", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + "v_mov_b32_e32 v22, s11", f"v_mov_b32_e32 v21, {OUT_AT}", + "buffer_store_dword v20, v21, s[0:3], 0 offen", + "buffer_store_dword v22, v21, s[0:3], 0 offen offset:4", "s_endpgm"]) + return mem[OUT_AT] | mem[OUT_AT + 4] << 32 + + def test_bitreplicate_of_exec_half_into_data(self): + # Every lane that runs the instruction reads the same 32 mask bits; each becomes two bits of s[10:11]. + for mask in (h.ALL64, 0x00000000FFFFFFFF, 0xFFFFFFFF00000000, 0x8000000180000001, 0x0F0F0F0F12345678): + for half, src in ((0, "exec_lo"), (1, "exec_hi")): + with self.subTest(exec=hex(mask), src=src): + word = (mask >> (32 * half)) & 0xFFFFFFFF + got = self.bitreplicate_of([f"s_mov_b32 exec_lo, {mask & 0xFFFFFFFF:#x}", + f"s_mov_b32 exec_hi, {mask >> 32:#x}"], src) + self.assertEqual(got, bitreplicate_model(word)) + + def test_bitreplicate_of_a_compare_into_data(self): + # VCC from a compare: lanes l < n. Its low and high halves replicated as data. + for n in (0, 1, 17, 32, 45, 64): + for half, src in ((0, "vcc_lo"), (1, "vcc_hi")): + with self.subTest(n=n, src=src): + got = self.bitreplicate_of([f"v_cmp_gt_u32_e32 vcc, {n}, v1"], src) + self.assertEqual(got, bitreplicate_model((((1 << n) - 1) >> (32 * half)) & 0xFFFFFFFF)) + + +def bitreplicate_model(word): + return sum(3 << (2 * i) for i in range(32) if (word >> i) & 1) + if __name__ == "__main__": unittest.main() From a39b3e4f8a0da61e4de5050d0ec6f621ee34b274 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:04:56 -0500 Subject: [PATCH 16/18] runtime tests: build and pass on the merged Xbox device proxy dxgi_swapchain_count_test: main's failed-resize case passes the diagnostics argument #984 added to VulkanSwapchain. xs_proxy_mock_test follows the merge's choices: slot 81 is GetFrameStatisticsX (no frame events slot 102 in the env mode), slot 73 refuses an IID it does not know as main's did, and console queue slots the presenter does not route stay with the queue proxy (S_OK tail) instead of E_NOTIMPL. Co-Authored-By: Claude Opus 5.5 --- runtime/test/dxgi_swapchain_count_test.cpp | 3 +- runtime/test/xs_proxy_mock_test.cpp | 52 +++++++++------------- 2 files changed, 23 insertions(+), 32 deletions(-) diff --git a/runtime/test/dxgi_swapchain_count_test.cpp b/runtime/test/dxgi_swapchain_count_test.cpp index 10d975357b..fbbca182ac 100644 --- a/runtime/test/dxgi_swapchain_count_test.cpp +++ b/runtime/test/dxgi_swapchain_count_test.cpp @@ -378,7 +378,8 @@ int run_failed_resize(const char* label, std::uint32_t requested, std::uint32_t std::mutex mutex; leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast(1), reinterpret_cast(2), get_device_proc, - reinterpret_cast(3), reinterpret_cast(4), 0, mutex); + reinterpret_cast(3), reinterpret_cast(4), 0, mutex, + /*diagnostics=*/nullptr); if (!swapchain.create(reinterpret_cast(static_cast(1)), 64, 64, VK_FORMAT_B8G8R8A8_UNORM, requested)) return fail("VulkanSwapchain::create"); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index f49bf243b7..7d2b77c796 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -15,7 +15,6 @@ // patching this executable's own import table before the first proxy table is built (one process each). // Every device, queue, fence and resource here is a mock that records the calls it gets. No game data, no Xbox DLLs. #include "../shims/d3d12_xs_device.h" -#include "../src/d3d12_xs_frame_events.h" #include #include @@ -1573,16 +1572,11 @@ int check_xbox_slots() { EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, 0)) == E_POINTER); EXPECT(mock->calls[80] == 0 && xs::device_slot_hits(80) == 3); - // 81 GetFrameEventsX(frame_token, flags, &num_events, events): sets *num_events = 0 and returns S_OK without - // reaching the mock's table (slot 81 is past ID3D12Device11's 80 slots). - std::uint32_t num_events = 6; - leonida::d3d12_xs::XboxFrameEvent events[6] = {}; - EXPECT(hr_of(raw(device, 81, token, 0x11100u, word(&num_events), word(events))) == S_OK && num_events == 0); - EXPECT(hr_of(raw(device, 81, token, 0x11100u, word(&num_events), 0)) == S_OK && num_events == 0); - EXPECT(hr_of(raw(device, 81, token, 0x11100u, 0, word(events))) == E_POINTER); - num_events = 6; - EXPECT(hr_of(raw(device, 81, token, 0x11100u, word(&num_events), 0)) == E_POINTER); - EXPECT(mock->calls[81] == 0 && xs::device_slot_hits(81) == 4); + // 81 GetFrameStatisticsX with no presenter attached: S_FALSE and no statistics, never the PC slot 81 + // (check_presentation_wiring covers an attached presenter). + UINT stats_count = 7; + EXPECT(hr_of(raw(device, 81, token, 0x1a, word(&stats_count), 0)) == S_FALSE && stats_count == 0); + EXPECT(mock->calls[81] == 0 && xs::device_slot_hits(81) == 1); // 48 CreateCommandQueueX(desc, riid, out): the queue proxy, created through the PC slot 8 path (filtered desc copy). void* queue = nullptr; @@ -1633,16 +1627,14 @@ int check_xbox_slots() { // output on failure, so an invalid call would clear this pointer. EXPECT(release(list) == 0); - // An IID the PC does not know (the console's own list IID; this one is made up for the test) still gets a list: - // the console list proxy, not a failure from the PC device. + // An IID that is neither a PC list IID nor the measured console one (made up for the test) goes to the PC device + // as asked, once, and its refusal comes back (main's slot 73; check_console_command_list has the console IID). // {8d2c4f61-3a5e-4b7c-9e10-2f6a8b4c3d51} constexpr GUID kConsoleListIid{0x8d2c4f61, 0x3a5e, 0x4b7c, {0x9e, 0x10, 0x2f, 0x6a, 0x8b, 0x4c, 0x3d, 0x51}}; void* unknown_list = nullptr; - EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&kConsoleListIid), word(&unknown_list))) == - S_OK); - EXPECT(xs::is_list_proxy(unknown_list) && mock->calls[12] == 3 && mock->calls[73] == 0); - EXPECT(IsEqualIID(*reinterpret_cast(mock->args[12][4]), list_iid)); - EXPECT(release(unknown_list) == 0); + EXPECT(FAILED(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&kConsoleListIid), + word(&unknown_list))))); + EXPECT(!unknown_list && mock->calls[12] == 3 && mock->calls[73] == 0); // A PC list IID the proxy answers is returned as asked. const IID list1_iid = __uuidof(ID3D12GraphicsCommandList1); void* list1 = nullptr; @@ -1949,7 +1941,6 @@ int run_env_slots(bool valid, bool on_slot70 = false, bool on_slot74 = false) { const char* schedule_event = valid ? "97" : "2"; const char* wait_event = on_slot74 ? "74" : valid ? "98" : "2"; - const char* frame_events = valid ? "102" : "2"; const char* queue_x = valid ? "99" : "2"; const char* list_x = valid ? "100" : "2"; const char* frame_statistics = valid ? "101" : "2"; @@ -1984,10 +1975,6 @@ int run_env_slots(bool valid, bool on_slot70 = false, bool on_slot74 = false) { EXPECT(hr_of(raw(device, 96, 0, 16667, 1, 0)) == S_OK && mock->calls[96] == 0); EXPECT(hr_of(raw(device, 97, 0, 0, 0, 0)) == S_OK && mock->calls[97] == 0); EXPECT(hr_of(raw(device, 98, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[98] == 0); - std::uint32_t ev_count = 6; - leonida::d3d12_xs::XboxFrameEvent ev_buf[6] = {}; - EXPECT(hr_of(raw(device, 102, token, 0x11100u, word(&ev_count), word(ev_buf))) == S_OK && ev_count == 0 && - mock->calls[102] == 0); void* queue = nullptr; EXPECT(hr_of(raw(device, 99, word(kXboxQueueDesc), word(&kQueueIid), word(&queue))) == S_OK); EXPECT(xs::is_queue_proxy(queue) && mock->calls[99] == 0); @@ -2005,7 +1992,7 @@ int run_env_slots(bool valid, bool on_slot70 = false, bool on_slot74 = false) { EXPECT(release(allocator) == 0); // The presenter answers frame statistics at 101 only (81 is not routed, so the mock refuses it); PresentX - // stays at 30, SuspendX answers at 33, and ResumeX, asked for 30, is unrouted, so 32 is refused. + // stays at 30, SuspendX answers at 33, and ResumeX, asked for 30, is unrouted, so 32 never reaches it. EnvPresenter env{}; xs::PresentationHandler h{}; h.context = &env; @@ -2031,7 +2018,8 @@ int run_env_slots(bool valid, bool on_slot70 = false, bool on_slot74 = false) { EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == E_NOTIMPL && env.stats == 1); EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == S_OK && env.present == 1); EXPECT(hr_of(raw(queue, 33)) == S_OK && env.suspend == 1); - EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && env.resume == 0); + raw(queue, 32); // a console queue slot: answered by the queue proxy, never by the presenter's ResumeX + EXPECT(env.resume == 0); EXPECT(xs::set_presentation_handler(device, nullptr)); EXPECT(release(queue) == 0); } else { @@ -3570,17 +3558,19 @@ int check_presentation_wiring() { UINT count = 3; EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == S_FALSE && count == 0 && p.stats_calls == 1); - // Queue slot 30 routes to PresentX while attached. SuspendX and ResumeX have no default route, so 31/32 are refused - // and never reach the presenter (the env mode, run_env_slots, routes them). + // Queue slot 30 routes to PresentX while attached. SuspendX and ResumeX have no default route, so 31/32 stay with + // the queue proxy's console slots and never reach the presenter (the env mode, run_env_slots, routes them). EXPECT(hr_of(raw(queue, 30, 1, 0x1000, 0x2000)) == S_OK && p.present_calls == 1 && p.last_planes == 1); - EXPECT(hr_of(raw(queue, 31, 0)) == E_NOTIMPL && p.suspend_calls == 0); - EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && p.resume_calls == 0); + raw(queue, 31, 0); + raw(queue, 32); + EXPECT(p.suspend_calls == 0 && p.resume_calls == 0); - // Detaching restores default E_NOTIMPL refusal on beyond-PC queue slots. + // Detaching: GetFrameStatisticsX no longer reaches the presenter (queue slot 30 goes back to the queue proxy's + // own PresentX, which check_xbox_queue_slots and the boot runs cover). EXPECT(xs::set_presentation_handler(device, nullptr)); UINT none = 7; // unattached GetFrameStatisticsX: no statistics yet, never the PC slot 81 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&none), 0)) == S_FALSE && none == 0 && p.stats_calls == 1); - EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == E_NOTIMPL && p.present_calls == 1); + EXPECT(p.present_calls == 1); EXPECT(release(queue) == 0); EXPECT(release(device) == 0 && mock->refs == 0); From 898bea520881e2e9ec857bbfd54c7c9a133693b8 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:04:56 -0500 Subject: [PATCH 17/18] rdna2spirv: remove widen_wave64_valu_masks, unused after the merge The merge kept main's widen_wave64_masks for wave64 lane masks; #984's variant had no caller left. Co-Authored-By: Claude Opus 5.5 --- tools/rdna2spirv.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 1a0038a9a3..fcd5b2b282 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17174,28 +17174,6 @@ def vertex_input_locations(sig): }) -def widen_wave64_valu_masks(insns): - """Older llvm-mc listings use wave32 spellings for wave-size-dependent VALU predicates. - A wave64 compare or carry writes two SGPRs. CNDMASK and carry-in read both. - Scalar data operands (including explicit vcc_lo and exec_lo) keep their original width. - """ - for ins in insns: - op, args = base_op(ins["op"]), ins["args"] - if op.startswith("v_cmp_") and len(args) == 3: - masks = (args[0],) - elif op in VOP3_TWO_DESTS and len(args) >= 4: - masks = (args[1], args[4]) if op.endswith("_ci_u32") and len(args) == 5 else (args[1],) - elif op == "v_cndmask_b32" and len(args) == 4: - masks = (args[3],) - else: - continue - for arg in masks: - if arg["k"] == "sgpr": - arg["n"] = 2 - elif arg.get("t") in ("vcc_lo", "exec_lo"): - arg["t"] = arg["t"][:-3] - - def same_encoding(raw, printed, op, operand_count): """True if the bytes in the blob are the instruction LLVM printed. Exact match, except for fields the hardware ignores that LLVM re-encodes with its default: VOP3P op_sel_hi[2] (bit 14) on two-source packed From 70985db6a5910fa4defe41faa589d013c3d4d339 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:04:57 -0500 Subject: [PATCH 18/18] semantic tests: model OpPhi, check the emulated wave64 swizzles These failed on #984's head as well. The loop guard (spirv_loop_guard.py) puts OpPhi into every loop, which the branch interpreter of test_control_flow_branches did not model; it now evaluates a block's phis together from the predecessor. spirv_mini_interp now models OpSwitch, so it runs the emulated wave64 scheduler that the ds_swizzle and permlane16 tests expected it to reject: they now compare the 64 lanes with their reference models. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_control_flow_branches.py | 20 ++++++++++++- tests/semantic/test_ds_swizzle_b32.py | 30 +++++++++++--------- tests/semantic/test_valu_permlane16.py | 17 ++++++----- 3 files changed, 46 insertions(+), 21 deletions(-) diff --git a/tests/semantic/test_control_flow_branches.py b/tests/semantic/test_control_flow_branches.py index 4193a8073f..d5e712c353 100644 --- a/tests/semantic/test_control_flow_branches.py +++ b/tests/semantic/test_control_flow_branches.py @@ -409,12 +409,30 @@ def deref(p): ip = 0 steps = 0 + current = previous = None # the block being run and the one that branched to it, for OpPhi while ip < len(self.insns): steps += 1 if steps > max_steps: raise BranchExecutionLimitError(f"Step limit {max_steps} exceeded: possible infinite loop") res, op, a, _ = self.insns[ip] - if op in _IGNORED or op == "OpLabel": + if op == "OpLabel": + previous, current = current, res + ip += 1 + continue + if op == "OpPhi": + # The block's phis read their incoming values together (tools/spirv_loop_guard.py adds them). + chosen = {} + while ip < len(self.insns) and self.insns[ip][1] == "OpPhi": + phi_res, _, phi_args, _ = self.insns[ip] + pairs = list(zip(phi_args[1::2], phi_args[2::2])) + incoming = next((v for v, parent in pairs if parent == previous), None) + if incoming is None: + raise UnsupportedConstruct(f"OpPhi {phi_res} has no value for block {previous}") + chosen[phi_res] = val(incoming) + ip += 1 + values.update(chosen) + continue + if op in _IGNORED: ip += 1 continue if op in ("OpReturn", "OpFunctionEnd"): diff --git a/tests/semantic/test_ds_swizzle_b32.py b/tests/semantic/test_ds_swizzle_b32.py index 929e74acab..90767b6025 100644 --- a/tests/semantic/test_ds_swizzle_b32.py +++ b/tests/semantic/test_ds_swizzle_b32.py @@ -760,14 +760,15 @@ class EmulationAndParsingTests(unittest.TestCase): """Structural SPIR-V checks for `--wave64-emulate`; unparsed offsets raise Unsupported.""" def test_wave64_emulate_lowers_all_five_modes_via_x_buf_without_subgroup_ops(self): + # The last field is the 16-bit offset the swizzle() form assembles to, for the reference model. cases = [ - ("quad", "swizzle(QUAD_PERM,3,2,1,0)", r"%cfffffffc\b"), - ("bitmask", 'swizzle(BITMASK_PERM,"10p0i")', r"%cffffffe5\b"), - ("swap", "swizzle(SWAP,16)", r"OpBitwiseXor %uint %\w+ %c10\b"), - ("reverse", "swizzle(REVERSE,32)", r"OpBitwiseXor %uint %\w+ %c1f\b"), - ("broadcast", "swizzle(BROADCAST,16,5)", r"%cfffffff0\b"), + ("quad", "swizzle(QUAD_PERM,3,2,1,0)", r"%cfffffffc\b", 0x801B), + ("bitmask", 'swizzle(BITMASK_PERM,"10p0i")', r"%cffffffe5\b", 0x0605), + ("swap", "swizzle(SWAP,16)", r"OpBitwiseXor %uint %\w+ %c10\b", 0x401F), + ("reverse", "swizzle(REVERSE,32)", r"OpBitwiseXor %uint %\w+ %c1f\b", 0x7C1F), + ("broadcast", "swizzle(BROADCAST,16,5)", r"%cfffffff0\b", 0x00B0), ] - for label, mod_str, expected_pat in cases: + for label, mod_str, expected_pat, offset16 in cases: with self.subTest(mode=label): lines = [ "s_mov_b64 exec, -1", @@ -784,13 +785,16 @@ def test_wave64_emulate_lowers_all_five_modes_via_x_buf_without_subgroup_ops(sel self.assertIn("%x_buf = OpVariable", spv) self.assertGreaterEqual(spv.count("OpControlBarrier"), 2) self.assertRegex(spv, expected_pat) - # spirv_mini_interp.py deliberately rejects the Workgroup-memory round loop. - with self.assertRaises(si.UnsupportedConstruct): - si.run_workgroup( - spv, 64, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, - push_constants=VSHARP + [0] * 28, memory={}, - ) + # spirv_mini_interp.py runs the Workgroup-memory round loop since it models OpSwitch: the 64 lanes + # match the reference model. + mem = _Heap() + si.run_workgroup( + spv, 64, 32, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, + push_constants=VSHARP + [0] * 28, memory=mem, + ) + want = ref_swizzle([100 + i for i in range(64)], [0] * 64, offset16, (1 << 64) - 1) + self.assertEqual([mem.get(4 * k) for k in range(64)], want) # Wave32 shaders are unaffected by WAVE64_EMULATE = True. w32_lines = [ diff --git a/tests/semantic/test_valu_permlane16.py b/tests/semantic/test_valu_permlane16.py index 413635ce70..f317a63bc6 100644 --- a/tests/semantic/test_valu_permlane16.py +++ b/tests/semantic/test_valu_permlane16.py @@ -685,13 +685,16 @@ def test_wave64_emulate_lowers_permlane_through_x_buf_without_subgroup_ops(self) self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b") self.assertIn("OpBitwiseAnd %uint %", spv) self.assertIn("%cfffffff0", spv) - # spirv_mini_interp.py deliberately rejects the emulated Workgroup/loop scheduler. - with self.assertRaises(si.UnsupportedConstruct): - si.run_workgroup( - spv, 64, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, - push_constants=VSHARP + [0] * 28, memory={}, - ) + # spirv_mini_interp.py runs the emulated Workgroup/loop scheduler since it models OpSwitch: the 64 lanes + # match the reference model. + mem = _Heap() + si.run_workgroup( + spv, 64, 32, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, + push_constants=VSHARP + [0] * 28, memory=mem, + ) + want = ref_permlane(spv is spv_x16, [100 + i for i in range(64)], [0] * 64, ID_S1, ID_S2, (1 << 64) - 1) + self.assertEqual([mem.get(4 * k) for k in range(64)], want) # v_permlanex16_b32 XORs the masked half base with 16 (%c10); v_permlane16_b32 does not. xor16_pat = r"OpBitwiseAnd %uint %\w+ %cfffffff0\n\s*%\w+ = OpBitwiseXor %uint %\w+ %c10\b"