From c774f25f09eaac0168a8655005e0b9d36cfc88f6 Mon Sep 17 00:00:00 2001 From: BACONMANXDGOD <167630566+BACONMANXDGOD@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:32:20 -0600 Subject: [PATCH] rdna2spirv: barrier rounds for wave32 compute shaders whose s_barrier isn't in uniform control flow (SHADER-91) On RDNA every s_barrier counts against the same workgroup barrier and a wave that has ended no longer counts; SPIR-V needs every OpControlBarrier reached by the whole workgroup in uniform control flow. A native wave32 compute shader whose s_barrier sits anywhere but a top-level block of the structured tree now runs in rounds, the emulated wave64 loop without its cross-lane part: s_barrier ends a segment, each invocation runs until its next s_barrier or the end, and the workgroup meets at one OpControlBarrier at the end of the round. A per-round count of the invocations not done (three Workgroup words) ends the loop. Native wave64 cs and ms are unchanged. Intel Arrow Lake Xe-LPG iGPU (32.0.101.8132): cs_barrier_divergent and the new cs_barrier_early_end and cs_barrier_loop lose the device with the plain translation and pass with barrier rounds; all three pass on an RTX 5070 Ti (617.42) either way. docs/design.md's Workgroup barriers row describes it. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- runtime/test/shaders/check.py | 9 +- runtime/test/shaders/cs_barrier_early_end.asm | 22 +++ runtime/test/shaders/cs_barrier_loop.asm | 37 +++++ scripts/run_gpu_tests.py | 12 +- tests/test_translate.py | 49 +++++++ tools/rdna2spirv.py | 136 +++++++++++++++++- 7 files changed, 254 insertions(+), 13 deletions(-) create mode 100644 runtime/test/shaders/cs_barrier_early_end.asm create mode 100644 runtime/test/shaders/cs_barrier_loop.asm diff --git a/docs/design.md b/docs/design.md index 52ed0ce517..cc511745b5 100644 --- a/docs/design.md +++ b/docs/design.md @@ -273,7 +273,7 @@ How the generated SPIR-V expects the runtime to work: | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | 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**. This was checked against what all 2,689 CS read before writing: 2,281 match exactly, and the rest overshoot only through loop-carried registers in the straight-line check. 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. | -| 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. **On the native path it is not proven:** the barrier stays where `s_barrier` is, and in the 1.0.2.1 corpus it sits inside a selection or loop construct in 43 of the 55 wave32 cs shaders with `s_barrier` (always native) and in every ms and most wave64 cs shaders when they run natively (AMD). Branches are scalar, so whole waves take the same path. No hang has been seen: `cs_barrier_divergent.asm` (two barrier sites in different branches), an early end of the other waves and a per-wave loop count all pass on NVIDIA RTX 4070 Ti (drivers 610.88 and 621.24) and RTX 5090 (Linux 595.99). SHADER-91 tracks this; a barrier-only round scheduler (the emulated loop without its cross-lane part) is the fix if a hang shows up. | +| 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. 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. | | 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), 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) and `tests/semantic/test_ds_permute.py`. 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. | | `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`. **Not GPU-verified.** | | 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), 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) and `tests/semantic/test_ds_permute.py`. In wave64 the permute runs as two wave32s (RDNA ISA §10.4.4): each half reads lanes of its own half, and a source lane that is off in EXEC reads 0. 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). 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/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 917a9eb54c..a2d0cccf67 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -76,7 +76,8 @@ def not_found_message(build, missing): CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800] CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c] WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", - "cs_barrier_divergent", "cs_w32_lds_u8_d16", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const") + "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", + "cs_w32_partial_scmp", "cs_exec_const") # Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is # narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const") @@ -101,7 +102,11 @@ def not_found_message(build, missing): ("cs_w32_partial_scmp", [0, 1, 1, 0, 1, 1, 1, 1]), # a 20-thread wave32: s_cmp mask, -1 ("cs_wqm_w64_half", [11, 14, 0, 1, 6, 8, 12, 2]), # SHADER-91: two s_barrier sites in wave-uniform branches meet like one barrier; wave 0 reads wave 3 - ("cs_barrier_divergent", [127, 126, 125, 124, 123, 122, 121, 120])] + ("cs_barrier_divergent", [127, 126, 125, 124, 123, 122, 121, 120]), + # SHADER-91: waves that end without an s_barrier don't hold the barrier of the ones still running + ("cs_barrier_early_end", [127, 126, 125, 124, 123, 122, 121, 120]), + # SHADER-91: a barrier in a loop with a per-wave trip count; the k-th one waits for the waves still running + ("cs_barrier_loop", [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE])] # num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement. # The SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm header): one thread too. # Never run cs_smem_sload_neg with a translator that zero-extends the s_load immediate: it reads 4 GiB past the heap. diff --git a/runtime/test/shaders/cs_barrier_early_end.asm b/runtime/test/shaders/cs_barrier_early_end.asm new file mode 100644 index 0000000000..9144134d00 --- /dev/null +++ b/runtime/test/shaders/cs_barrier_early_end.asm @@ -0,0 +1,22 @@ +; group: 128,1,1 +; SHADER-91: a wave that has ended no longer counts at s_barrier. Wave32, 128 threads = 4 waves. Every thread +; writes its id to LDS[id]; waves 1-3 then end without an s_barrier, and wave 0 waits at one. On RDNA the barrier +; releases once the other waves have ended, and wave 0 reads what wave 3 wrote: out[i] = LDS[127 - i] = 127 - i. +; Translated, the s_barrier sits in a branch that only wave 0 takes: Intel's driver loses the device on that +; (an OpControlBarrier outside uniform control flow); barrier rounds keep the barrier at the top level. +; Run: vk_compute_test cs_barrier_early_end.spv 1 dump +; Expect: out[0..7] = 127 126 125 124 123 122 121 120 +v_lshlrev_b32_e32 v2, 2, v0 +ds_write_b32 v2, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s5, v0 +s_lshr_b32 s5, s5, 5 +s_cmp_lg_u32 s5, 0 +s_cbranch_scc1 9 +s_barrier +v_sub_nc_u32_e32 v3, 0x1fc, v2 +ds_read_b32 v4, v3 +s_waitcnt lgkmcnt(0) +v_cmpx_gt_u32_e32 8, v0 +buffer_store_dword v4, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_barrier_loop.asm b/runtime/test/shaders/cs_barrier_loop.asm new file mode 100644 index 0000000000..29826d6190 --- /dev/null +++ b/runtime/test/shaders/cs_barrier_loop.asm @@ -0,0 +1,37 @@ +; group: 128,1,1 +; SHADER-91: s_barrier in a loop whose trip count differs per wave. Wave32, 128 threads = 4 waves; wave w runs +; w + 1 iterations. Iteration k adds 1 to LDS[k] from each of the wave's 32 lanes, waits at s_barrier, then +; reads LDS[k] and stores it to out[4 * (3 - w) + k]. On RDNA every s_barrier counts against the same barrier +; and a wave that has ended no longer counts, so the k-th barrier releases once every wave still running has +; added to LDS[k]: LDS[k] = 32 * (4 - k) when read. Wave 3 stores out[0..3] and wave 2 out[4..6]; out[7] would +; be wave 2's fourth iteration, which it doesn't run, so it keeps the sentinel 0xeeeeeeee. +; Run: vk_compute_test cs_barrier_loop.spv 1 dump +; Expect: out[0..7] = 128 96 64 32 128 96 64 4008636142 +v_lshlrev_b32_e32 v2, 2, v0 +v_mov_b32_e32 v3, 0 +v_cmpx_gt_u32_e32 4, v0 +ds_write_b32 v2, v3 +s_mov_b32 exec_lo, -1 +s_waitcnt lgkmcnt(0) +s_barrier +v_readfirstlane_b32 s5, v0 +s_lshr_b32 s5, s5, 5 +s_add_u32 s6, s5, 1 +s_sub_u32 s9, 3, s5 +s_lshl_b32 s9, s9, 4 +s_mov_b32 s7, 0 +v_mov_b32_e32 v5, 1 +v_mov_b32_e32 v1, s7 +ds_add_u32 v1, v5 +s_waitcnt lgkmcnt(0) +s_barrier +ds_read_b32 v4, v1 +s_waitcnt lgkmcnt(0) +s_add_u32 s10, s9, s7 +v_mov_b32_e32 v6, s10 +buffer_store_dword v4, v6, s[0:3], 0 offen +s_add_u32 s7, s7, 4 +s_sub_u32 s6, s6, 1 +s_cmp_lg_u32 s6, 0 +s_cbranch_scc1 -16 +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 63ecc38180..71e386c10a 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -708,7 +708,8 @@ def run_suite(a, work: str) -> int: "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", - "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp"): + "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_barrier_early_end", + "cs_barrier_loop"): cs_dump_wants = { "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800], # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone @@ -755,6 +756,10 @@ def run_suite(a, work: str) -> int: "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm) "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120], + # SHADER-91: other waves end without s_barrier (cs_barrier_early_end.asm); a loop whose trip count + # differs per wave (cs_barrier_loop.asm) + "cs_barrier_early_end": [127, 126, 125, 124, 123, 122, 121, 120], + "cs_barrier_loop": [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE], } want = cs_dump_wants[name] # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / @@ -767,8 +772,9 @@ def run_suite(a, work: str) -> int: emulated = w64_emulated() partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp") wave64 = name not in ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", - "cs_w32_permute", "cs_barrier_divergent", "cs_w32_lds_u8_d16", "cs_bpermute32", - "cs_w32_partial_scmp", "cs_exec_const") and not emulated and not partial + "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", + "cs_w32_lds_u8_d16", "cs_bpermute32", "cs_w32_partial_scmp", + "cs_exec_const") and not emulated and not partial if partial and not emulated: cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") diff --git a/tests/test_translate.py b/tests/test_translate.py index 37b99058ea..e7cae15f4e 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -650,6 +650,55 @@ def test_wave64_emulate_uses_no_subgroup_ops(path, make_shader, monkeypatch): assert "%x_buf" in emulated and emulated.count("OpControlBarrier") >= 2 +# SHADER-91: a native wave32 compute shader whose s_barrier isn't in a top-level block runs in barrier rounds. +BARRIER_SAMPLES = ("cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop") + + +@pytest.mark.parametrize("stem", BARRIER_SAMPLES) +def test_nested_barrier_runs_in_barrier_rounds(stem, make_shader): + """No OpControlBarrier is left among the blocks (the cases of the switch over %pc): s_barrier ends a segment + there. The only two are before the round loop and at its end, where the whole workgroup is.""" + with open(os.path.join(ROOT, "runtime", "test", "shaders", stem + ".asm"), encoding="utf-8") as f: + shader = make_shader(f.read(), stem) + asm = shader.translate() + shader.validate(asm) + assert rdna2spirv.translate.last_gen.control_flow == "barrier rounds" + blocks = asm[asm.index("OpSwitch %pcv"):asm.index("%sw_default = OpLabel")] + assert "OpControlBarrier" not in blocks and "OpStore %x_bar %true" in blocks + assert asm.count("OpControlBarrier") == 2 + head, tail = asm.index("OpLoopMerge %loop_exit %loop_cont"), asm.index("%loop_cont = OpLabel") + assert asm.index("OpControlBarrier") < head and asm.rindex("OpControlBarrier") > tail + assert "OpAtomicIAdd" in asm[tail - 2000:tail] and "%x_buf = OpVariable" in asm + + +def test_top_level_barrier_keeps_the_plain_translation(make_shader): + """A barrier in a block every invocation runs (the top level of the structured tree) stays one OpControlBarrier + in place: no rounds for a shader that doesn't need them.""" + shader = make_shader("v_lshlrev_b32_e32 v2, 2, v0\nds_write_b32 v2, v0\ns_waitcnt lgkmcnt(0)\ns_barrier\n" + "v_readfirstlane_b32 s5, v0\ns_cmp_lg_u32 s5, 0\ns_cbranch_scc1 2\n" # skips the 2-dword read + "ds_read_b32 v4, v2\ns_endpgm\n", "cs_barrier_top") + asm = shader.translate() + shader.validate(asm) + assert rdna2spirv.translate.last_gen.control_flow == "structured" + assert asm.count("OpControlBarrier") == 1 and "%x_bar" not in asm and "%x_buf" not in asm + + +def test_barrier_rounds_are_wave32_compute_only(make_shader, monkeypatch): + """Native wave64 (AMD's 64-wide subgroups) keeps the barrier where s_barrier is; under --wave64-emulate the + emulated round loop already holds the only barrier.""" + with open(os.path.join(ROOT, "runtime", "test", "shaders", "cs_barrier_divergent.asm"), encoding="utf-8") as f: + src = f.read() + shader = make_shader("s_mov_b64 exec, -1\n" + src, "cs_barrier_divergent_w64") # a 64-bit EXEC write: wave64 + asm = shader.translate() + gen = rdna2spirv.translate.last_gen + assert gen.wave64 and not gen.bar_rounds and gen.control_flow == "structured" + assert asm.count("OpControlBarrier") == 2 and "%x_bar" not in asm + monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", True) + shader.translate() + gen = rdna2spirv.translate.last_gen + assert gen.emulate and not gen.bar_rounds and gen.control_flow == "emulated wave64 rounds" + + # SHADER-36: image_gather4_l(_o) runs every texel of its 2x2 footprint through the S#'s CLAMP_X/CLAMP_Y. def _gather_l(s_word0, dynamic=False, s_word1=0): return program( diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 76ccdf0402..f84dcd720f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -153,6 +153,7 @@ def __init__(self, stage): self.x_gen = 0 # emulate: bumped at every label (control flow inside a block): forgets x_tok self.x_mcache = {} # emulate: wave_mask key -> (lo, hi) already exchanged in this block self.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves + self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) self.uses_storage3d = False self.uses_heap = False self.uses_codebase = False @@ -3190,7 +3191,7 @@ def f64(sv): # Workgroup execution barrier; AMD orders LDS through s_waitcnt before it, so include workgroup memory. if self.stage not in ("cs", "ms"): raise Unsupported("s_barrier outside compute") - if self.emulate: + if self.emulate or self.bar_rounds: # The wave waits in the scheduler until every wave not done waits too (assemble). self.emit("OpStore %x_bar %true") self.x_split() @@ -6442,12 +6443,16 @@ def assemble(gen): if x_missing: for v in (x_missing - 1, gen.x_lanes + x_threads): gen.cu(v) + if gen.bar_rounds: + sx, sy, _ = gen.cs["size"] + for v in (0, 1, 2, 3, 0x108, sx, sx * sy): + gen.cu(v) model = "Vertex" if vs else "GLCompute" if cs else "MeshEXT" if ms else "Geometry" if gsx else "Fragment" ms_blk = ms and (gen.uses_clip or gen.uses_cull) iface = list(gen.outputs) + list(gen.inputs) + (["%vertex_index", "%instance_index"] if vs else []) + (["%wg_id", "%local_id"] if cs else []) + (["%lds"] if gen.uses_lds else []) + ( (["%wg_id", "%num_wg", "%local_index", "%ms_counts", ("%ms_out_vtx" if ms_blk else "%ms_out_pos"), "%ms_prim_idx", "%ms_cull"] + [f"%ms_out_param{n}" for n in sorted(gen.ms_params)]) if ms else []) + ( - ["%x_buf"] if gen.emulate else []) + ( + ["%x_buf"] if gen.emulate or gen.bar_rounds else []) + ( ([("%gs_in_pos" if sv == 1 else f"%gs_in{r}") for r, sv in gen.gs["in"]] + [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + ((["%fmt_uint_mask", "%fmt_sint_mask"] + [f"%stv{c}_{d}" for d in sorted(gen.uses_store_views) for c in range(3)]) if gen.uses_store_views else []) @@ -6796,6 +6801,11 @@ def assemble(gen): types += [f"%x_arr = OpTypeArray %uint {gen.cu(x_sink + 1)}", "%_ptr_WG_x_arr = OpTypePointer Workgroup %x_arr", "%_ptr_WG_uint_x = OpTypePointer Workgroup %uint"] gvars += ["%x_buf = OpVariable %_ptr_WG_x_arr Workgroup"] + elif gen.bar_rounds: + # Barrier rounds: one count of the invocations not done per round, 3 slots by round mod 3 (bar_scheduler). + types += [f"%x_arr = OpTypeArray %uint {gen.cu(3)}", + "%_ptr_WG_x_arr = OpTypePointer Workgroup %x_arr", "%_ptr_WG_uint_x = OpTypePointer Workgroup %uint"] + gvars += ["%x_buf = OpVariable %_ptr_WG_x_arr Workgroup"] if cs: types += ["%v3uint = OpTypeVector %uint 3", "%_ptr_Input_v3u = OpTypePointer Input %v3uint"] gvars += ["%wg_id = OpVariable %_ptr_Input_v3u Input", "%local_id = OpVariable %_ptr_Input_v3u Input"] @@ -6882,6 +6892,10 @@ def assemble(gen): fn += [f"{var} = OpVariable {ptr} Function" for var, ptr in gen.x_spills] if gen.uses_perm: fn.append("%x_perm = OpVariable %_ptr_Function_uint Function %c0") + elif gen.bar_rounds: + fn += ["%x_it = OpVariable %_ptr_Function_uint Function %c0", + "%x_bar = OpVariable %_ptr_Function_bool Function %false"] + fn += [f"{var} = OpVariable {ptr} Function" for var, ptr in gen.x_spills] # User data: s0..s31 are loaded at entry from a push-constant block (the driver's user-SGPR setup). if gen.uses_heap: gen.consts.setdefault(1, "%c1") @@ -6974,10 +6988,13 @@ def assemble(gen): # Spill pointers last: a spilled value's type may be declared anywhere above. types += [f"{ptr} = OpTypePointer Function {t}" for t, ptr in gen.x_ptr_types.items()] out = hdr + dec + types + gvars + (gen.desc_fn or []) + (gen.fmt_fn or []) + fn - tree = cfg_structure.structure(gen.succ) if gen.blocks and STRUCTURED and not gen.emulate else None + tree = (cfg_structure.structure(gen.succ) if gen.blocks and STRUCTURED and not gen.emulate and not gen.bar_rounds + else None) gen.control_flow = "structured" if tree is not None else "dispatch loop" if gen.blocks else "straight line" if gen.emulate: gen.control_flow = "emulated wave64 rounds" + elif gen.bar_rounds: + gen.control_flow = "barrier rounds" if tree is not None: # Real loops and conditionals (cfg_structure): the blocks nested by dominance, each behind a test of %pc, # and every natural loop as a loop that repeats while %pc names its header. @@ -7020,6 +7037,14 @@ def place(items): body += blines body.append("OpBranch %sw_merge") body += x_scheduler_tail(gen) + elif gen.bar_rounds: + lines = bar_scheduler(gen) + body = [] + for i, blines in sorted(list(enumerate(gen.blocks)) + list(gen.x_segs.items())): + body.append(f"%blk{i} = OpLabel") + body += blines + body.append("OpBranch %sw_merge") + body += bar_scheduler_tail(gen) elif gen.blocks: # Dispatch loop: any CFG (forward/backward branches) in structured SPIR-V form. Used for the irreducible # graphs cfg_structure refuses (a loop with two entries), and with --dispatch-loop. @@ -7749,6 +7774,7 @@ def target(ins): g.build_meta = _shader_meta.collect(path, info["name"], blocks, succ, user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) + g.bar_rounds = needs_barrier_rounds(g, blocks, succ) g.x_seg = len(blocks) + 1 # emulate: continuation segments are numbered after "done" (len(blocks)) for n, blk in enumerate(blocks): g.body = [] @@ -7819,10 +7845,35 @@ def target(ins): _DEF = re.compile(r"(%\w+) = (Op\w+)(?: (%\w+))?") +def needs_barrier_rounds(g, blocks, succ): + """SHADER-91: whether a native wave32 compute shader has to run in barrier rounds (bar_scheduler). On RDNA every + s_barrier counts against the same workgroup barrier, so waves on different paths meet at different s_barrier + sites. SPIR-V requires an OpControlBarrier to be reached by the whole workgroup in uniform control flow, and an + Intel GPU hangs (device lost) when it isn't (cs_barrier_divergent.asm). A barrier is only certain to be + uniform in a block at the top level of the structured tree, which every invocation runs; one under a guard + or in a loop, or anywhere in the dispatch loop, may be reached by some waves and not others.""" + if g.stage != "cs" or g.emulate or g.wave64: + return False # emulated: already rounds; native wave64 cs and ms run on AMD only + with_barrier = set() + for n, blk in enumerate(blocks): + for ins in blk: + op = base_op(ins["op"]) + if op == "s_endpgm" or op in BRANCHES: + break + if op == "s_barrier": + with_barrier.add(n) + break + if not with_barrier: + return False + tree = cfg_structure.structure(succ) if STRUCTURED else None + top = {it[1] for it in tree if it[0] == "block"} if tree is not None else set() + return not with_barrier <= top + + def x_spill(g, parts): - """Emulated wave64: the segments of one block run in different rounds, i.e. in different cases of the - scheduler's switch and different loop iterations, so an SSA value defined in one and used in a later one - can't be referenced directly. It goes through a Function variable: stored at the end of the segment that + """Emulated wave64 and barrier rounds: the segments of one block run in different rounds, i.e. in different + cases of the scheduler's switch and different loop iterations, so an SSA value defined in one and used in a + later one can't be referenced directly. It goes through a Function variable: stored at the end of the segment that defines it and loaded, under a new id, at the top of each later segment that uses it.""" defs, out = {}, [] for k, part in enumerate(parts): @@ -7836,7 +7887,8 @@ def x_spill(g, parts): seg, typ, var = defs[ref] if var is None: if typ is None or typ.startswith("%_ptr"): - raise Unsupported("wave64 emulation: a pointer lives across a round") + mode = "barrier rounds" if g.bar_rounds else "wave64 emulation" + raise Unsupported(f"{mode}: a pointer lives across a round") ptr = {"%uint": "%_ptr_Function_uint", "%bool": "%_ptr_Function_bool"}.get(typ) if ptr is None: ptr = g.x_ptr_types.setdefault(typ, f"%_ptr_Function_x_{typ[1:]}") @@ -7958,6 +8010,76 @@ def x_scheduler_tail(gen): "%loop_exit = OpLabel"] +def bar_scheduler(gen): + """Barrier rounds (SHADER-91): a native wave32 compute shader whose s_barrier isn't in uniform control flow + (needs_barrier_rounds). The emulated wave64 loop without its cross-lane part: s_barrier ends a segment, and + the code after it is a continuation segment (x_split). In a round each invocation that isn't done runs its + blocks, through the switch over %pc, until it reaches an s_barrier or the end; then the whole workgroup meets + at one OpControlBarrier, at the end of the round loop, in uniform control flow. After the inner loop every + invocation is done or waits, so the barrier always releases the waiting ones, and a wave that has ended + doesn't hold the others back (RDNA's rule). Cross-lane operations stay subgroup operations: a wave runs one + segment at a time, as in the dispatch loop. The round's count of invocations not done ends the loop at 0. + + %x_buf holds 3 counts, by round mod 3: round r adds to its own slot before the barrier and reads it after, + and invocation 0 clears the slot of round r + 1, last read in round r - 2 (before the barrier of r - 1). + The first two lines are the Function variables %pc and %done, as for the dispatch loop.""" + c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 + sx, sy, _ = gen.cs["size"] + return ["%pc = OpVariable %_ptr_Function_uint Function %c0", + "%done = OpVariable %_ptr_Function_bool Function %false", + "%xb_lid = OpLoad %v3uint %local_id", "%xb_lx = OpCompositeExtract %uint %xb_lid 0", + "%xb_ly = OpCompositeExtract %uint %xb_lid 1", "%xb_lz = OpCompositeExtract %uint %xb_lid 2", + f"%xb_ly2 = OpIMul %uint %xb_ly {c(sx)}", f"%xb_lz2 = OpIMul %uint %xb_lz {c(sx * sy)}", + "%xb_lxy = OpIAdd %uint %xb_lx %xb_ly2", "%xb_li = OpIAdd %uint %xb_lxy %xb_lz2", + f"%xb_first = OpIEqual %bool %xb_li {c(0)}", + # Workgroup memory starts undefined: invocation 0 clears round 0's count before the first round. + "OpSelectionMerge %xb_z_end None", "OpBranchConditional %xb_first %xb_z %xb_z_end", "%xb_z = OpLabel", + f"%xb_zp = OpAccessChain %_ptr_WG_uint_x %x_buf {c(0)}", f"OpStore %xb_zp {c(0)}", + "OpBranch %xb_z_end", "%xb_z_end = OpLabel", + f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}", + "OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", + "OpBranch %xb_round", "%xb_round = OpLabel", + "%xb_itv = OpLoad %uint %x_it", f"%xb_s = OpUMod %uint %xb_itv {c(3)}", + f"%xb_n1 = OpIAdd %uint %xb_itv {c(1)}", f"%xb_sn = OpUMod %uint %xb_n1 {c(3)}", + "OpSelectionMerge %xb_r_end None", "OpBranchConditional %xb_first %xb_r %xb_r_end", "%xb_r = OpLabel", + "%xb_rp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_sn", f"OpStore %xb_rp {c(0)}", + "OpBranch %xb_r_end", "%xb_r_end = OpLabel", + "%xb_d = OpLoad %bool %done", + "OpSelectionMerge %xb_ran None", "OpBranchConditional %xb_d %xb_ran %xb_run", "%xb_run = OpLabel", + # The invocation's blocks, until an s_barrier (%x_bar) or the end (%done). + "OpBranch %xb_in_head", "%xb_in_head = OpLabel", "OpLoopMerge %xb_in_merge %xb_in_cont None", + "OpBranch %dispatch", "%dispatch = OpLabel", + "%pcv = OpLoad %uint %pc", "OpSelectionMerge %sw_merge None", + "OpSwitch %pcv %sw_default " + " ".join(f"{i} %blk{i}" for i in + sorted(list(range(len(gen.blocks))) + list(gen.x_segs)))] + + +def bar_scheduler_tail(gen): + """Barrier rounds: the end of a round, after the switch (see bar_scheduler).""" + c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 + return ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", + "%sw_merge = OpLabel", "OpBranch %xb_in_cont", "%xb_in_cont = OpLabel", + "%xb_d1 = OpLoad %bool %done", "%xb_b1 = OpLoad %bool %x_bar", + "%xb_stop = OpLogicalOr %bool %xb_d1 %xb_b1", + "OpBranchConditional %xb_stop %xb_in_merge %xb_in_head", "%xb_in_merge = OpLabel", + # Not done: count this invocation in the round's slot. + "%xb_d2 = OpLoad %bool %done", + "OpSelectionMerge %xb_c_end None", "OpBranchConditional %xb_d2 %xb_c_end %xb_c", "%xb_c = OpLabel", + "%xb_cp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_s", + f"%xb_ca = OpAtomicIAdd %uint %xb_cp {c(2)} {c(0)} {c(1)}", + "OpBranch %xb_c_end", "%xb_c_end = OpLabel", + "OpBranch %xb_ran", "%xb_ran = OpLabel", + "OpBranch %loop_cont", "%loop_cont = OpLabel", + # s_barrier's own barrier (workgroup, acquire-release, workgroup memory), now in uniform control flow; + # it also orders the count, read below. + f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}", + "%xb_lp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_s", "%xb_left = OpLoad %uint %xb_lp", + "OpStore %x_bar %false", + f"%xb_it1 = OpIAdd %uint %xb_itv {c(1)}", "OpStore %x_it %xb_it1", + f"%xb_fin = OpIEqual %bool %xb_left {c(0)}", "OpBranchConditional %xb_fin %loop_exit %loop_head", + "%loop_exit = OpLabel"] + + BRANCHES = {"s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", "s_cbranch_execz", "s_cbranch_execnz"}