diff --git a/docs/design.md b/docs/design.md index 3f2d522517..c34aea8496 100644 --- a/docs/design.md +++ b/docs/design.md @@ -277,6 +277,7 @@ How the generated SPIR-V expects the runtime to work: | Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | | Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. | | DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | +| DPP on a VOPC compare | A VOPC compare whose src0 field is a DPP marker (250 for DPP16, 233/234 for DPP8) takes src0 through the DPP lane selection of the row above and writes VCC: a lane's bit is `compare(src0 of the selected lane, its own src1)`, with 0 for src0 when the selected lane is out of its row or inactive (`bound_ctrl` 1, or DPP8 with `fi` 0). The second word has the layout of a VOP2's DPP word. `llvm-mc` has no decoding for it on gfx10 (LLVM 21.1.8 rejects the first word for `gfx1013`; LLVM defines the form from GFX11 on), so `tools/shader_disasm.py` prints it: it decodes the pair with the first word turned into `v_max_f32` into `v0`, which takes the same second word, and gives the line the compare's name, a `vcc_lo` destination and the real encoding back (`with_vopc_dpp`); `tools/rdna2_decode.py` decodes it directly. **Only the forms where every lane writes its bit are translated**: `row_mask` and `bank_mask` 0xF and either `bound_ctrl` 1 or DPP8. Any other form, and `v_cmpx`, is refused (`DPP compare with lanes that keep their mask bit`), because what a lane DPP leaves unwritten does to its VCC bit is not measured. Found in 3 of the 2,684 pipeline-library compute programs of 1.0.2.1: 4 `v_cmp_gt_f32` each, with `quad_perm:[1,0,3,2]`, `quad_perm:[2,3,0,1]`, `row_ror:8` (all `bound_ctrl:1`, masks 0xF) and `dpp8:[4,5,6,7,0,1,2,3]`, beside `v_min/max_f32_dpp` and `v_mov_b32_dpp` on the same lanes. **Not measured on hardware**: the rule follows from the encoding, from LLVM's GFX11 definition of the same form and from the VOP2 DPP rules measured in the row above; the sweep that measured those (`tools/crosslane_fuzz.py --dpp-sweep --oracle hw`) does not cover compares. Lane values are checked in `tests/semantic/test_dpp_compare.py` (the SPIR-V interpreter) and on a GPU with `runtime/test/shaders/cs_dpp_cmp.asm`. | | EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. | | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | | Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index fe0d98bcee..013b287173 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -125,7 +125,9 @@ def not_found_message(build, missing): ("cs_dpp_ops", [100, 10, 11, 12, 13, 14, 15, 16]), ("cs_dpp_bound", [10, 10, 11, 12, 13, 14, 15, 16]), ("cs_dpp_bank", [0xffffffff, 0xfffffffe, 0xfffffffd, 0xfffffffc, 7, 7, 7, 7]), - ("cs_dpp_fi", [1, 2, 3, 0x7777, 5, 6, 7, 0x7777])] + ("cs_dpp_fi", [1, 2, 3, 0x7777, 5, 6, 7, 0x7777]), + # a VOPC compare with a DPP src0: 1 for the pair compare, 2 for the dpp8 one (cs_dpp_cmp.asm header) + ("cs_dpp_cmp", [3, 2, 3, 2, 1, 0, 1, 0])] WAVE32_DUMPS += tuple(n for n, _ in CS_DPP) WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP) CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), diff --git a/runtime/test/shaders/cs_dpp_cmp.asm b/runtime/test/shaders/cs_dpp_cmp.asm new file mode 100644 index 0000000000..867c6a81ac --- /dev/null +++ b/runtime/test/shaders/cs_dpp_cmp.asm @@ -0,0 +1,22 @@ +; DPP on a VOPC compare: src0 is read from the permuted lane, src1 from the lane itself, and the result goes to VCC. +; v1 = float(lane). The first compare takes src0 from the other lane of each pair (quad_perm [1,0,3,2]), so +; "neighbour > self" is true on even lanes. The second takes it from the other half of each 8 lanes (dpp8), so it +; is true on lanes 0-3. out = (first ? 1 : 0) + (second ? 2 : 0). +; Run: vk_compute_test cs_dpp_cmp.spv 1 dump -> out[0..7] = 3 2 3 2 1 0 1 0 +; llvm-mc assembles neither compare for gfx1013 ("dpp variant of this instruction is not supported"), so the GPU +; test takes this file's text as its listing; tools/shader_disasm.py prints the same lines for the encoded words. +; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here +; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_cvt_f32_u32 v1, v0 +v_mov_b32 v3, 0 +v_mov_b32 v4, 1 +v_mov_b32 v5, 2 +v_cmp_gt_f32_dpp vcc_lo, v1, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1 +v_cndmask_b32 v6, v3, v4, vcc_lo +v_cmp_gt_f32_dpp vcc_lo, v1, v1 dpp8:[4,5,6,7,0,1,2,3] +v_cndmask_b32 v7, v3, v5, vcc_lo +v_add_nc_u32 v6, v6, v7 +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v6, v2, s[0:3], 0 offen +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 80b380d9e3..14c0fcfa4c 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -94,10 +94,23 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2, group_ return struct.pack(" None: """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" with open(asm_path, encoding="utf-8") as source: raw = source.read() + if any(ln.strip() == TEXT_ONLY_MARK for ln in raw.splitlines()): + # The source holds an instruction llvm-mc has no gfx1013 encoding for. The translator reads straight-line + # code from its text alone (tests/semantic/regen_fixtures.py writes such listings), so the lines go through + # as they are. + lines = [f"; {name} code 0x0..0x0 (synthetic), gfx1013, 0 invalid words"] + lines += ["\t" + ln.strip() for ln in raw.splitlines() if ln.strip() and not ln.lstrip().startswith(";")] + with open(s_path, "w", encoding="utf-8", newline="\n") as f: + f.write("\n".join(lines) + "\n") + return cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] for ln in raw.splitlines(): s = ln.strip() @@ -1162,7 +1175,7 @@ def run_suite(a, work: str) -> int: results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) elif name in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", - "cs_dpp_bound", "cs_dpp_w64", + "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64", "cs_w64_mask_detect", "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", @@ -1223,6 +1236,7 @@ def run_suite(a, work: str) -> int: "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16], "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], + "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0], "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] # without it @@ -1297,7 +1311,7 @@ def run_suite(a, work: str) -> int: "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", - "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_w32_andn2_exec", + "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", "cs_w32_exec_computed") and not emulated and not partial if partial and not emulated: cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") diff --git a/tests/semantic/fixtures/disasm/cs_dpp_cmp.s b/tests/semantic/fixtures/disasm/cs_dpp_cmp.s new file mode 100644 index 0000000000..64d4e8fa83 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_dpp_cmp.s @@ -0,0 +1,14 @@ +; cs_dpp_cmp test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_dpp_cmp.asm + v_mbcnt_lo_u32_b32 v0, -1, 0 + v_cvt_f32_u32 v1, v0 + v_mov_b32 v3, 0 + v_mov_b32 v4, 1 + v_mov_b32 v5, 2 + v_cmp_gt_f32_dpp vcc_lo, v1, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1 + v_cndmask_b32 v6, v3, v4, vcc_lo + v_cmp_gt_f32_dpp vcc_lo, v1, v1 dpp8:[4,5,6,7,0,1,2,3] + v_cndmask_b32 v7, v3, v5, vcc_lo + v_add_nc_u32 v6, v6, v7 + v_lshlrev_b32 v2, 2, v0 + buffer_store_dword v6, v2, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/test_dpp_compare.py b/tests/semantic/test_dpp_compare.py new file mode 100644 index 0000000000..c6f429fb5e --- /dev/null +++ b/tests/semantic/test_dpp_compare.py @@ -0,0 +1,230 @@ +"""A VOPC compare in DPP form reads src0 through the DPP lane selection (SHADER-VOPC-DPP). + +Three pipeline-library compute programs of 1.0.2.1 hold `v_cmp_gt_f32` with a DPP16 or DPP8 src0 (7 words each), +beside `v_min/max_f32_dpp` and `v_mov_b32_dpp` in a lane-pair reduction. `Gen.dpp_insn` took only a VGPR +destination, so the programs were refused ("DPP destination"). + +The rule (docs/design.md, "DPP on a VOPC compare"): the bit a lane writes is compare(src0 of the selected lane, its +own src1), with 0 for src0 when the selected lane is out of its row or inactive. Only the forms where every lane +writes are translated: all rows and banks enabled and either `bound_ctrl:1` or DPP8. A form that leaves a lane +unwritten is refused, because what that lane's mask bit becomes is not measured. + +The values come from running the translated module in tests/semantic/spirv_wave_interp.py. + +Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. +""" +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import support # noqa: E402 (puts tools/ on the path) +import spirv_wave_interp as wi # noqa: E402 +from rdna2spirv import Unsupported # noqa: E402 + +# Every lane writes with each of these: all rows and banks, and bound_ctrl:1 or DPP8. +WRITTEN_FORMS = [ + "quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1", # the three forms the programs use + "quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1", + "row_ror:8 row_mask:0xf bank_mask:0xf bound_ctrl:1", + "dpp8:[4,5,6,7,0,1,2,3]", + "row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1", # lane 0 of a row has no source: reads 0 + "row_shl:3 row_mask:0xf bank_mask:0xf bound_ctrl:1", + "row_mirror row_mask:0xf bank_mask:0xf bound_ctrl:1", + "dpp8:[7,6,5,4,3,2,1,0] fi:1", # fi:1 reads an inactive source lane too +] + +# A lane that DPP does not write: a row or bank switched off, or an invalid source without bound_ctrl. +UNWRITTEN_FORMS = [ + "quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "quad_perm:[1,0,3,2] row_mask:0x5 bank_mask:0xf bound_ctrl:1", + "quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xa bound_ctrl:1", + "row_shr:1 row_mask:0xf bank_mask:0xf", +] + +COMPARES = { + "v_cmp_gt_f32_dpp": ("v1", lambda a, b: a > b), # v1 = float(lane) + "v_cmp_lt_u32_dpp": ("v0", lambda a, b: a < b), # v0 = lane + "v_cmp_eq_u32_dpp": ("v0", lambda a, b: a == b), +} + + +def compare_vs(op, form, exec_off=None): + """A vertex shader: VCC = `op`(DPP(src), src) with lane `exec_off` off in EXEC for the compare; param0.x + exports 1 where the lane's VCC bit is set and 0 where it is clear.""" + src = COMPARES[op][0] + lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", "v_cvt_f32_u32 v1, v0", "v_mov_b32 v3, 0", "v_mov_b32 v4, 1", + "s_mov_b32 s10, exec_lo"] + if exec_off is not None: + lines.append(f"v_cmpx_ne_u32_e32 {exec_off}, v0") + lines += [f"{op} vcc_lo, {src}, {src} {form}", "s_mov_b32 exec_lo, s10", "v_cndmask_b32 v6, v3, v4, vcc_lo", + "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v5, v5, v5", "s_endpgm"] + return support.translate_lines("vs_dpp_compare", lines) + + +def compare_reference(op, form, exec_off=None, wave=32): + """The VCC bit per lane after compare_vs: an inactive lane's bit is 0, as for a plain compare.""" + mods = form.split() + fi = any(m == "fi:1" for m in mods) + relation = COMPARES[op][1] + active = [lane != exec_off for lane in range(wave)] + out = [] + for lane in range(wave): + loc, ok = lane & 15, True + if mods[0].startswith("dpp8:"): + src = (lane & ~7) | [int(x) for x in mods[0][6:-1].split(",")][lane & 7] + elif mods[0].startswith("quad_perm:"): + src = (lane & ~3) | [int(x) for x in mods[0][11:-1].split(",")][lane & 3] + else: + kind, _, n = mods[0].partition(":") + n = int(n or 0) + if kind == "row_shr": + ok, s = loc >= n, loc - n + elif kind == "row_shl": + ok, s = loc + n < 16, loc + n + elif kind == "row_ror": + s = (loc - n) & 15 + else: # row_mirror + s = 15 - loc + src = (lane & ~15) | (s & 15) + valid = ok and (active[src] or fi) + out.append(int(active[lane] and relation(src if valid else 0, lane))) + return out + + +def run(op, form, exec_off=None): + res = wi.run_wave(compare_vs(op, form, exec_off), wave=32, + builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) + return [o["%out_param0"][0] for o in res["outputs"]] + + +class DppCompare(unittest.TestCase): + def test_values(self): + for op in COMPARES: + for form in WRITTEN_FORMS: + for exec_off in (None, 5, 16): + with self.subTest(op=op, form=form, exec_off=exec_off): + self.assertEqual(run(op, form, exec_off), compare_reference(op, form, exec_off)) + + def test_reference_by_hand(self): + # Pairs swapped: an even lane compares its odd neighbour against itself, an odd lane the lane below it. + pair = "quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1" + self.assertEqual(compare_reference("v_cmp_gt_f32_dpp", pair)[:8], [1, 0, 1, 0, 1, 0, 1, 0]) + # Halves of eight swapped: lanes 0-3 see lanes 4-7. + self.assertEqual(compare_reference("v_cmp_gt_f32_dpp", "dpp8:[4,5,6,7,0,1,2,3]")[:8], [1, 1, 1, 1, 0, 0, 0, 0]) + # Lane 4's source, lane 5, is inactive and reads 0, so "0 > 4" is false; lane 5 is inactive and writes 0. + self.assertEqual(compare_reference("v_cmp_gt_f32_dpp", pair, exec_off=5)[:8], [1, 0, 1, 0, 0, 0, 1, 0]) + # The game's reduction step compares against runtime/test/shaders/cs_dpp_cmp.asm's expected 3 2 3 2 1 0 1 0. + first = compare_reference("v_cmp_gt_f32_dpp", pair)[:8] + second = compare_reference("v_cmp_gt_f32_dpp", "dpp8:[4,5,6,7,0,1,2,3]")[:8] + self.assertEqual([a + 2 * b for a, b in zip(first, second)], [3, 2, 3, 2, 1, 0, 1, 0]) + + def test_a_form_that_leaves_a_lane_unwritten_is_refused(self): + for form in UNWRITTEN_FORMS: + with self.subTest(form=form): + with self.assertRaisesRegex(Unsupported, "DPP compare with lanes that keep their mask bit"): + compare_vs("v_cmp_gt_f32_dpp", form) + + def test_cmpx_is_refused(self): + lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", + "v_cmpx_gt_u32_dpp v0, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1", + "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done", "s_endpgm"] + with self.assertRaises(Unsupported): + support.translate_lines("vs_dpp_cmpx", lines) + + +def vopc(opcode, src0, vsrc1): + return 0x3E << 25 | opcode << 17 | vsrc1 << 9 | src0 + + +def dpp16_word(src0_reg, ctrl, bound=0, fi=0, bank_mask=0xF, row_mask=0xF): + return row_mask << 28 | bank_mask << 24 | bound << 19 | fi << 18 | ctrl << 8 | src0_reg + + +def dpp8_word(src0_reg, lanes): + return sum(lane << (8 + 3 * i) for i, lane in enumerate(lanes)) | src0_reg + + +GT_F32, LT_U32 = 0x04, 0xC1 # VOPC opcodes (tools/rdna2_tables.py) +S_ENDPGM = 0xBF810000 +# (first word, second word, the line both printers give) +PAIRS = [ + (vopc(GT_F32, 250, 2), dpp16_word(1, 0xB1, bound=1), + "v_cmp_gt_f32_dpp vcc_lo, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1"), + (vopc(GT_F32, 250, 9), dpp16_word(9, 0x128, bound=1), + "v_cmp_gt_f32_dpp vcc_lo, v9, v9 row_ror:8 row_mask:0xf bank_mask:0xf bound_ctrl:1"), + (vopc(LT_U32, 250, 3), dpp16_word(4, 0x111, bank_mask=0xA, row_mask=0x5), + "v_cmp_lt_u32_dpp vcc_lo, v4, v3 row_shr:1 row_mask:0x5 bank_mask:0xa"), + (vopc(GT_F32, 233, 20), dpp8_word(20, [4, 5, 6, 7, 0, 1, 2, 3]), + "v_cmp_gt_f32_dpp vcc_lo, v20, v20 dpp8:[4,5,6,7,0,1,2,3]"), + (vopc(GT_F32, 234, 6), dpp8_word(5, [7, 6, 5, 4, 3, 2, 1, 0]), + "v_cmp_gt_f32_dpp vcc_lo, v5, v6 dpp8:[7,6,5,4,3,2,1,0] fi:1"), +] + + +def text_of(line): + return " ".join(line.split(";", 1)[0].split()) + + +class DppCompareDecode(unittest.TestCase): + """The two printers of the pair: tools/rdna2_decode.py, and tools/shader_disasm.py over llvm-mc.""" + + def test_opcodes_are_the_tables(self): + import rdna2_decode + self.assertEqual(rdna2_decode.T.VOPC[GT_F32][0], "v_cmp_gt_f32") + self.assertEqual(rdna2_decode.T.VOPC[LT_U32][0], "v_cmp_lt_u32") + + def test_python_decoder(self): + import rdna2_decode + import struct + for w0, w1, want in PAIRS: + with self.subTest(want=want): + asm, bad = rdna2_decode.disasm_bytes(struct.pack("<3I", w0, w1, S_ENDPGM), mcpu="gfx1013", wave32=True) + lines = [text_of(line) for line in asm.splitlines() if "encoding" in line] + self.assertEqual((lines, bad), ([want, "s_endpgm"], 0)) + + def test_a_decoded_line_translates(self): + # What the disassembler prints is what the translator takes: the two forms it accepts, from PAIRS. + for _, _, line in (PAIRS[0], PAIRS[3]): + with self.subTest(line=line): + lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", line, "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done", + "s_endpgm"] + self.assertIn("OpGroupNonUniformShuffle", support.translate_lines("vs_dpp_compare_line", lines)) + + def test_llvm_mc_listing(self): + import struct + import shader_disasm + probe = struct.pack(" 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: + # A compare with a DPP src0. llvm-mc has no decoding for it on gfx10 (it rejects the word), but 1.0.2.1's + # pipeline library holds it; the second word has the layout of a VOP2's (docs/design.md, "DPP on a + # VOPC compare"). The result goes to VCC, as for the plain _e32 compare. + if not need(8): + return None, 4 + w1 = struct.unpack_from("> 20) & 1), bool((w1 >> 21) & 1) + s1["neg"], s1["abs"] = bool((w1 >> 22) & 1), bool((w1 >> 23) & 1) + mods.append(_format_dpp16_ctrl((w1 >> 8) & 0x1FF)) + 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: + mods.append(f"dpp8:[{','.join(str((w1 >> (8 + 3 * i)) & 7) for i in range(8))}]") + if src0 == 234: + mods.append("fi:1") + args = [s0, s1] if name.startswith("v_cmpx_") else [_vcc_operand(wave32), 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 920e858ae8..5f5d190741 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7247,7 +7247,18 @@ 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: + # A VOPC compare in DPP form (docs/design.md, "DPP on a VOPC compare"): src0 comes through the same lane + # selection and the result is a mask bit, not a VGPR. Only the forms where every lane writes its bit are + # taken: what a lane that DPP leaves unwritten does to its VCC bit is not measured. + compare = base_op(ins["op"]).startswith("v_cmp") + if compare: + if base_op(ins["op"]).startswith("v_cmpx"): + raise Unsupported("DPP on v_cmpx") + if len(args) != 3: + raise Unsupported("DPP compare operands") + if row_mask != 0xF or bank_mask != 0xF or not (dpp8 is not None or bound): + raise Unsupported("DPP compare with lanes that keep their mask bit") + 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") @@ -7426,6 +7437,10 @@ def selectors(key, count, limit): write = self.tmp() self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}") args[1] = {"k": "ssa", "v": src0} + if compare: + # Every lane is enabled and an invalid source reads 0 (checked above), so the compare's own EXEC guard + # is the only one: the mask write is the plain compare's. + return self._insn({**ins, "args": args}) previous = self.dpp_guard self.dpp_guard = write try: diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index a119e74aaf..67a10ec13d 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -14,6 +14,7 @@ """ import argparse import os +import re import struct import subprocess import sys @@ -91,6 +92,16 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True if backend == "python": asm, bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32) return asm, bad, "" + asm, bad, err = run_mc(code, mcpu) + if bad and asm.strip(): + fixed = with_vopc_dpp(code, mcpu, err) + if fixed: + return fixed + return asm, bad, err + + +def run_mc(code: bytes, mcpu: str): + """One llvm-mc pass over `code`: (listing, invalid word count, stderr), or ("", count, reason) when it failed.""" text = " ".join(f"0x{b:02x}" for b in code) try: p = subprocess.run(MC + ["--disassemble", f"-triple={TRIPLE}", f"-mcpu={mcpu}", "-show-encoding"], @@ -104,6 +115,75 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True return p.stdout, bad, p.stderr +ENCODING = re.compile(r"; encoding: \[([^\]]*)\]") +INVALID_AT = re.compile(r":1:(\d+): warning: invalid instruction encoding") +VOPC = 0x3E # bits 31..25 of a VOPC word +DPP_SRC0 = (250, 233, 234) # the src0 field of a DPP16, DPP8 and DPP8-with-fi word +STAND_IN = 0x10 # VOP2 v_max_f32: takes the same DPP second word, and llvm-mc decodes it +STAND_IN_TEXT = "v_max_f32_dpp v0, " + + +def invalid_offsets(err: str) -> set: + """Byte offsets llvm-mc rejected: its warning names the column of the word in the one line of 5-character + "0xNN " tokens it was given.""" + return {(int(col) - 1) // 5 for col in INVALID_AT.findall(err)} + + +def vopc_dpp_words(code: bytes, offsets) -> dict: + """{offset: (compare name, word0, word1)} of the rejected words at `offsets` that are a VOPC compare whose src0 + field is a DPP marker. The name is the decoder's (rdna2_decode's VOPC table).""" + found = {} + for at in sorted(offsets): + if at % 4 or at + 8 > len(code): + continue + w0, w1 = struct.unpack_from("<2I", code, at) + entry = rdna2_decode.T.VOPC.get((w0 >> 17) & 0xFF) + if w0 >> 25 == VOPC and w0 & 0x1FF in DPP_SRC0 and entry: + found[at] = (entry[0], w0, w1) + return found + + +def with_vopc_dpp(code: bytes, mcpu: str, err: str): + """The listing of `code` with each rejected VOPC compare in DPP form printed as the instruction it is, or None + when there is none (docs/design.md, "DPP on a VOPC compare"). llvm-mc has no decoding for the pair on gfx10, so + it is decoded with the first word turned into a VOP2 that takes the same DPP second word (v_max_f32 into v0), + which gives llvm-mc's own text for the two sources and the DPP controls; each such line then gets the compare's + name, its VCC destination and the real encoding back, so the translator reads the instruction and checks its + encoding against the blob. A word that does not come out as that stand-in at an instruction boundary was not an + instruction (it sits in a literal or in data): it is left as it was and the pass runs again without it.""" + words = vopc_dpp_words(code, invalid_offsets(err)) + while words: + patched = bytearray(code) + for at, (_, w0, _) in words.items(): + struct.pack_into("