diff --git a/docs/design.md b/docs/design.md index 7bff52e7f9..52bd373031 100644 --- a/docs/design.md +++ b/docs/design.md @@ -302,7 +302,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**. | | `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`) and `tests/semantic/test_scalar_mem_smem.py` (both halves and the resulting addresses); **not GPU-verified**: the synthetic `runtime/test/shaders/cs_smem_vcc_base.asm` reads back eight seeded words through the pair in the standard GPU runner. | | 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. Hardware applies src0 float modifiers (`neg`/`abs`) after the invalid-lane zero selection, so `-src0` on an invalid lane yields `-0.0f` (`0x80000000`) and `\|src0\|` yields `+0.0f` (HW-DPP-NEG-INVALID-LANE, measured on RDNA3 (gfx1101) RX 7800 XT, RDNA2 not measured; tested by `tests/semantic/test_dpp_bound_ctrl_modifiers.py`). 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. For native FI=0, the source-lane ballot bit also selects the shuffle index: an absent or EXEC-off source is redirected to the current subgroup lane before `OpGroupNonUniformShuffle`, because masking an undefined shuffle result afterwards is not sufficient; FI=1 is unchanged. CPU-checked by `tests/semantic/test_dpp_eager_subgroup.py::test_fi0_shuffle_index_is_ballot_safe` with a hand-written `quad_perm` case whose active lane 6 reads absent lane 7 in a seven-invocation wave; **not GPU-verified**. 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 | 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. Hardware applies src0 float modifiers (`neg`/`abs`) after the invalid-lane zero selection, so `-src0` on an invalid lane yields `-0.0f` (`0x80000000`) and `\|src0\|` yields `+0.0f` (HW-DPP-NEG-INVALID-LANE, measured on RDNA3 (gfx1101) RX 7800 XT, RDNA2 not measured; tested by `tests/semantic/test_dpp_bound_ctrl_modifiers.py`). 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. For native FI=0, the source-lane ballot bit also selects the shuffle index: an absent or EXEC-off source is redirected to the current subgroup lane before `OpGroupNonUniformShuffle`, because masking an undefined shuffle result afterwards is not sufficient; FI=1 is unchanged. CPU-checked by `tests/semantic/test_dpp_eager_subgroup.py::test_fi0_shuffle_index_is_ballot_safe` with a hand-written `quad_perm` case whose active lane 6 reads absent lane 7 in a seven-invocation wave; **not GPU-verified**. 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. In a pixel shader (not under `--wave64-emulate`), `quad_perm` reads its quad through quad operations instead: `OpGroupNonUniformQuadSwap` for `[1,0,3,2]`, `[2,3,0,1]` and `[3,2,1,0]`, otherwise one `OpGroupNonUniformQuadBroadcast` per lane read and a select on the lane's selector, and with `fi` 0 the source lane's EXEC bit goes through the same quad read instead of a ballot. Without `MaximallyReconvergesKHR`, Vulkan lets helper invocations count as inactive for every group operation other than quad and derivative ones, so a shuffle or ballot could miss the helper next to a triangle edge (SHADER-PS-DPP-QUAD-OPS). CPU-checked by `tests/semantic/test_dpp_quad_ops_ps.py` in `tests/semantic/spirv_wave_interp.py` with helper lanes (`helpers=`); **not GPU-verified**. 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 is refused (`DPP compare with lanes DPP leaves unwritten`), because what such a lane writes is measured only on RDNA3, not on RDNA2. On RDNA3 (gfx1101, RX 7800 XT, `tools/hw_oracle`, wave32 and wave64; [measurement](https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7161289307)) a lane DPP leaves unwritten does not keep its bit: `v_cmp` writes 0 to its VCC bit and `v_cmpx` turns it off in EXEC. That holds for an invalid source with `bound_ctrl` 0, and for a lane `row_mask` or `bank_mask` turns off, even with `bound_ctrl` 1. Translating these forms on RDNA2 (gfx1013) would need the same measurement there. `v_cmpx` in DPP form takes the same lane selection and the same forms, and writes EXEC as the plain `v_cmpx` does (a lane that was off stays off); it prints no destination, so its src0 is the first operand (SHADER-VOPCX-DPP). 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. `v_cmpx` in DPP form is in 78 of the 18,837 graphics programs of the pipeline library (all pixel shaders, 113 instructions), all `v_cmpx_gt_f32_dpp vN, -vM quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1`, a compare against the lane two above or below in its quad. **Not measured on RDNA2 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. The RDNA3 measurement above also ran the translated forms (`bound_ctrl` 1, masks 0xF): an invalid source lane gets the compare of a 0 source, as the rule says. 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` and, for `v_cmpx`, `cs_dpp_cmpx.asm` (RTX 4070 Laptop, native wave32 and `--wave64-emulate`). | | 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. | diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index a2eb436fc9..da7d40a236 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py @@ -25,8 +25,13 @@ lane number giving that lane's integer value, e.g. {"VertexIndex": lambda lane: first + lane}). PushConstant words can be seeded (default zero). - run_wave(text, wave=32, push_constants=None, max_steps=2_000_000, builtins=None) -> - {"outputs": [ {output_name: tuple_of_words} or None (lane killed) for each lane ], +`helpers` names lanes that run as a fragment shader's helper invocations. They take part in quad operations, but +every other group operation leaves them out, the strict reading of Vulkan's "Helper Invocations" without +MaximallyReconvergesKHR: a shuffle or broadcast from one is undefined, a ballot does not see it, and any other +group operation they reach raises UnsupportedConstruct. Their outputs are discarded (None). + + run_wave(text, wave=32, push_constants=None, max_steps=2_000_000, builtins=None, helpers=()) -> + {"outputs": [ {output_name: tuple_of_words} or None (lane killed or a helper) for each lane ], "steps": instructions executed (summed over invocations)} """ import math @@ -321,9 +326,10 @@ def _copy(v): class _Wave: - def __init__(self, mod, wave, push_constants, max_steps, builtins=None, inputs=None, memory=None): + def __init__(self, mod, wave, push_constants, max_steps, builtins=None, inputs=None, memory=None, helpers=()): self.m = mod self.wave = wave + self.helpers = frozenset(helpers) self.pcw = list(push_constants or []) self.max_steps = max_steps self.steps = 0 @@ -397,8 +403,8 @@ def run(self): raise UnsupportedConstruct(f"invocations left the function through {sorted(rest)}") out = [] for lane in self.lanes: - if lane.index in self.killed: - out.append(None) + if lane.index in self.killed or lane.index in self.helpers: + out.append(None) # a helper invocation's outputs are discarded continue words = {} for vid, box in lane.outputs.items(): @@ -576,6 +582,16 @@ def collective(self, res, op, a, members): raise UnsupportedConstruct(f"{op} with a scope other than Subgroup") L = self.lanes width = self.wave + if not op.startswith("OpGroupNonUniformQuad") and self.helpers.intersection(members): + # Without MaximallyReconvergesKHR, helper invocations may be treated as inactive for group operations + # other than quad and derivative ones (Vulkan, "Helper Invocations"): the strict reading leaves them out. + if op not in ("OpGroupNonUniformShuffle", "OpGroupNonUniformBroadcast", "OpGroupNonUniformBallot"): + raise UnsupportedConstruct(f"{op} with helper invocations") + for i in self.helpers.intersection(members): + L[i].values[res] = _Poison(f"{op[17:]} in a helper invocation") + members = [i for i in members if i not in self.helpers] + if not members: + return def ballot_bits(v): if not (isinstance(v, tuple) and len(v) == 4): @@ -1011,9 +1027,11 @@ def __init__(self, name): self.name = name -def run_wave(text, wave=32, push_constants=None, max_steps=2_000_000, builtins=None, inputs=None, memory=None): +def run_wave(text, wave=32, push_constants=None, max_steps=2_000_000, builtins=None, inputs=None, memory=None, + helpers=()): if wave not in (32, 64): raise ValueError("wave must be 32 or 64") - w = _Wave(_Module(text), wave, push_constants, max_steps, builtins, inputs=inputs, memory=memory) + w = _Wave(_Module(text), wave, push_constants, max_steps, builtins, inputs=inputs, memory=memory, + helpers=helpers) outputs = w.run() return {"outputs": outputs, "steps": w.steps, "memory": w.memory} diff --git a/tests/semantic/test_dpp_quad_ops_ps.py b/tests/semantic/test_dpp_quad_ops_ps.py new file mode 100644 index 0000000000..69e431f215 --- /dev/null +++ b/tests/semantic/test_dpp_quad_ops_ps.py @@ -0,0 +1,137 @@ +"""quad_perm DPP in a pixel shader reads its quad through quad operations (SHADER-PS-DPP-QUAD-OPS). + +Without MaximallyReconvergesKHR, Vulkan ("Helper Invocations") lets an implementation treat helper invocations as +inactive for group operations other than quad and derivative ones. The translator used to lower every quad_perm to +OpGroupNonUniformShuffle (and, with fi:0, the source lane's EXEC bit to a ballot), so a pixel next to a triangle edge +could read an undefined value from its helper neighbour. In fragment shaders it now uses OpGroupNonUniformQuadSwap +for the three swaps and OpGroupNonUniformQuadBroadcast, one per lane read, for every other selector. + +The values are checked by running the translated program in tests/semantic/spirv_wave_interp.py, whose `helpers` +option takes the strict reading: a shuffle from a helper is undefined and a ballot does not see it. + +Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. +""" +import os +import re +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 test_dpp_eager_subgroup import conditional_subgroup_ops # noqa: E402 + +SWAPS = {(1, 0, 3, 2): 0, (2, 3, 0, 1): 1, (3, 2, 1, 0): 2} +SELECTORS = [(1, 0, 3, 2), (2, 3, 0, 1), (3, 2, 1, 0), # the three swaps + (0, 0, 0, 0), (1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3), # broadcasts + (1, 1, 3, 3), (2, 3, 2, 3), (0, 0, 2, 2), (0, 1, 0, 1), # pair and half broadcasts + (3, 1, 2, 0)] # all four lanes, no pattern + + +def form(sel, fi, bound=1): + return f"quad_perm:[{','.join(map(str, sel))}] row_mask:0xf bank_mask:0xf bound_ctrl:{bound} fi:{fi}" + + +def dpp_ps(dpp, exec_off=None): + """A pixel shader: v6 = 100, then v6 = v0 (the lane) + 10 through DPP `dpp`, with lane `exec_off` off in EXEC + for the DPP; mrt0.x exports v6's bits.""" + lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", "v_mov_b32 v1, 10", "v_mov_b32 v6, 100", "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"v_add_nc_u32_dpp v6, v0, v1 {dpp}", "s_mov_b32 exec_lo, s10", + "exp mrt0 v6, v6, v6, v6 done vm", "s_endpgm"] + return support.translate_lines("ps_dpp_quad", lines) + + +def reference(sel, fi, bound=1, exec_off=None, wave=32): + """v6 per lane after dpp_ps(form(sel, fi, bound), exec_off): the RDNA2 DPP rules for quad_perm + (docs/design.md, Gen.dpp_insn). A helper invocation is an ordinary active lane to the hardware.""" + out = [] + for lane in range(wave): + src = (lane & ~3) | sel[lane & 3] + valid = fi or src != exec_off + if lane == exec_off or (not valid and not bound): + out.append(100) # not written: keeps its old value + else: + out.append((src if valid else 0) + 10) + return out + + +def lanes(spv, helpers=()): + return [o and o["%out_mrt0"][0] for o in wi.run_wave(spv, wave=32, helpers=helpers)["outputs"]] + + +class PixelShaderQuadPerm(unittest.TestCase): + def test_no_shuffle_or_ballot(self): + for sel in SELECTORS: + for fi in (0, 1): + with self.subTest(sel=sel, fi=fi): + spv = dpp_ps(form(sel, fi)) + self.assertNotIn("OpGroupNonUniformShuffle", spv) + self.assertNotIn("OpGroupNonUniformBallot", spv) + self.assertIn("OpCapability GroupNonUniformQuad", spv) + self.assertEqual(conditional_subgroup_ops(spv), []) + + def test_swaps_and_broadcasts(self): + for sel in SELECTORS: + with self.subTest(sel=sel): + spv = dpp_ps(form(sel, 1)) + swaps = re.findall(r"OpGroupNonUniformQuadSwap %uint %c3 %\w+ %c(\d+)", spv) + reads = re.findall(r"OpGroupNonUniformQuadBroadcast %uint %c3 %\w+ %c(\d+)", spv) + if sel in SWAPS: + self.assertEqual((swaps, reads), ([str(SWAPS[sel])], [])) + else: + self.assertEqual((swaps, sorted(reads)), ([], [str(k) for k in sorted(set(sel))])) + + def test_identity_reads_no_neighbour(self): + spv = dpp_ps(form((0, 1, 2, 3), 1)) + self.assertNotIn("OpGroupNonUniformQuad", spv) + self.assertEqual(lanes(spv), reference((0, 1, 2, 3), 1)) + + def test_values(self): + for sel in SELECTORS: + for fi, bound in ((1, 1), (0, 1), (0, 0)): + for exec_off in (None, 5): + with self.subTest(sel=sel, fi=fi, bound=bound, exec_off=exec_off): + spv = dpp_ps(form(sel, fi, bound), exec_off) + self.assertEqual(lanes(spv), reference(sel, fi, bound, exec_off)) + + def test_helper_neighbours_are_read(self): + # Lanes 2, 5 and 12 run as helper invocations. Their neighbours read their v0 as hardware does; with a + # shuffle (fi:1) or a ballot of EXEC (fi:0) they read an undefined value or miss the bit. + helpers = (2, 5, 12) + for sel in SELECTORS: + for fi in (0, 1): + with self.subTest(sel=sel, fi=fi): + want = [None if lane in helpers else v for lane, v in enumerate(reference(sel, fi))] + self.assertEqual(lanes(dpp_ps(form(sel, fi)), helpers=helpers), want) + + +class OtherStagesKeepTheShuffle(unittest.TestCase): + def test_vertex_shader(self): + # Quad operations are guaranteed in fragment and compute shaders only (quadOperationsInAllStages). + lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", "v_mov_b32 v1, 10", "v_mov_b32 v6, 100", + f"v_add_nc_u32_dpp v6, v0, v1 {form((1, 0, 3, 2), 1)}", "v_mov_b32 v5, 0", + "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v5, v5, v5", "s_endpgm"] + spv = support.translate_lines("vs_dpp_quad", lines) + self.assertIn("OpGroupNonUniformShuffle", spv) + self.assertNotIn("OpGroupNonUniformQuad", spv) + + +class HelperModel(unittest.TestCase): + """The interpreter's helpers option itself: a shuffle that reads a helper lane gives an undefined value.""" + + def test_shuffle_from_a_helper_is_undefined(self): + lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", "v_mov_b32 v1, 10", "v_mov_b32 v6, 100", + f"v_add_nc_u32_dpp v6, v0, v1 {form((1, 0, 3, 2), 1)}", "v_mov_b32 v5, 0", + "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v5, v5, v5", "s_endpgm"] + spv = support.translate_lines("vs_dpp_quad", lines) + with self.assertRaisesRegex(wi.UnsupportedConstruct, "undefined"): + wi.run_wave(spv, wave=32, helpers=(2,), + builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_translate.py b/tests/test_translate.py index 24299f6d13..4e96310a3d 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -111,7 +111,14 @@ def test_dpp_controls_translate_and_validate(case, make_shader): shader = make_shader(program("v_mov_b32 v0, v0\n" + DPP_CASES[case])) spvasm = shader.translate() shader.validate(spvasm) - assert "OpGroupNonUniformShuffle" in spvasm + # make_shader builds a pixel shader: quad_perm reads its quad through quad operations, which helper + # invocations take part in (SHADER-PS-DPP-QUAD-OPS); the identity selector reads no other lane. + if "quad_perm:[0,1,2,3]" in DPP_CASES[case]: + assert "OpGroupNonUniformShuffle" not in spvasm and "OpGroupNonUniformQuad" not in spvasm + elif "quad_perm" in DPP_CASES[case]: + assert "OpGroupNonUniformQuadSwap" in spvasm and "OpGroupNonUniformShuffle" not in spvasm + else: + assert "OpGroupNonUniformShuffle" in spvasm @pytest.mark.parametrize("mods", [[], ["row_share:20"], ["row_shl:0"], ["row_shl:1", "row_shr:2"]]) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index b10de728ec..8c358423e4 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7757,6 +7757,20 @@ def selectors(key, count, limit): self.emit(f"{both} = OpLogicalAnd %bool {in_bounds} {active}") active = both src_ok = active + elif quad is not None and self.stage == "ps": + # A pixel shader reads its quad neighbours through quad operations (SHADER-PS-DPP-QUAD-OPS). Without + # MaximallyReconvergesKHR, Vulkan lets helper invocations count as inactive for every group operation + # other than the quad and derivative ones, so a shuffle could miss the helper next to a triangle edge. + # A quad is four consecutive subgroup lanes from a multiple of 4: the lane & ~3 of quad_perm. + shuffled = self.quad_perm_read(src_val, quad, perm) if src.get("k") == "vgpr" else src_val + if fi: + src_ok = "%true" + else: + bit = self.tmp() + self.emit(f"{bit} = OpSelect %uint {self.active_b()} {self.cu(1)} {self.cu(0)}") + read = self.tmp() + self.emit(f"{read} = OpINotEqual %bool {self.quad_perm_read(bit, quad, perm)} {self.cu(0)}") + src_ok = read else: sgl = self.subgroup_lane() sg_group = self.tmp() @@ -7843,6 +7857,34 @@ def selectors(key, count, limit): finally: self.dpp_guard = previous + QUAD_SWAPS = {(1, 0, 3, 2): 0, (2, 3, 0, 1): 1, (3, 2, 1, 0): 2} # OpGroupNonUniformQuadSwap Direction + + def quad_perm_read(self, value, quad, perm): + """value (a %uint) of the lane quad_perm selects in this lane's quad, through quad operations: a swap for + the three swaps, else one QuadBroadcast per lane read (the Index must be a constant) and a select on this + lane's `perm`. Each result is stored eagerly, so every lane runs it (SHADER-529).""" + quad = tuple(quad) + if quad == (0, 1, 2, 3): + return value + self.uses_subgroup = self.uses_quad = True + if quad in self.QUAD_SWAPS: + r = self.tmp() + self.emit(f"{r} = OpGroupNonUniformQuadSwap %uint {self.cu(3)} {value} {self.cu(self.QUAD_SWAPS[quad])}") + return self.eager("%uint", r) + reads = {} + for k in sorted(set(quad)): + r = self.tmp() + self.emit(f"{r} = OpGroupNonUniformQuadBroadcast %uint {self.cu(3)} {value} {self.cu(k)}") + reads[k] = self.eager("%uint", r) + *rest, last = reads + out = reads[last] + for k in rest: + is_k, sel = self.tmp(), self.tmp() + self.emit(f"{is_k} = OpIEqual %bool {perm} {self.cu(k)}") + self.emit(f"{sel} = OpSelect %uint {is_k} {reads[k]} {out}") + out = sel + return out + def permute_known_selector(self, src0, src1, selector): """Emit only the selected bytes of V_PERM_B32 when S2 is known.""" if selector == 0x03020100: