From c9a480e374ab47242800f4fec985675bf853c15a Mon Sep 17 00:00:00 2001 From: Vincent Chu <259728795+vinceychu@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:20:51 -0500 Subject: [PATCH] rdna2spirv: --max-mesh-shared-memory checks a mesh shader's Workgroup memory (SHADER-MESH-SHARED-LIMIT) design.md listed mesh shaders against maxMeshSharedMemorySize as not covered. A MeshEXT module's Workgroup memory (the LDS array, the 4-byte %ms_counts and, under --wave64-emulate, %x_buf) can now be capped at translation with --max-mesh-shared-memory BYTES, refused with the needed and allowed byte counts. The default is 0 (no check), so every mesh shader that translated before still does; a --mesh-compute module keeps the compute cap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RAL8MMXUuNpQAVa1iiyAMP --- docs/d3d12_vulkan.md | 4 +- docs/design.md | 2 +- tests/semantic/fixtures/ms_shared_limit.asm | 6 + tests/semantic/test_ms_shared_memory_limit.py | 189 ++++++++++++++++++ tools/rdna2spirv.py | 33 ++- 5 files changed, 230 insertions(+), 4 deletions(-) create mode 100644 tests/semantic/fixtures/ms_shared_limit.asm create mode 100644 tests/semantic/test_ms_shared_memory_limit.py diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 45d4b4be47..438b9f7996 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2622,7 +2622,9 @@ Pipeline creation: - The index's `max_vertices`/`max_primitives` already size the SPIR-V mesh output arrays. Vulkan has no per-pipeline mesh output limit: check them against `VkPhysicalDeviceMeshShaderPropertiesEXT::maxMeshOutputVertices`/`maxMeshOutputPrimitives` and fail at pipeline - creation if the device is smaller. + creation if the device is smaller. Workgroup memory (`lds_bytes`) is checked against + `maxMeshSharedMemorySize` (and `maxMeshPayloadAndSharedMemorySize`) by `vulkan_mesh_limits.h`; pass the device's + value to `rdna2spirv.py --max-mesh-shared-memory` when translating for it (default 0: no check at translation; 28672 is the spec minimum). - Vertex input comes from the PSO input layout plus the shader's ISG1 signature. The translator's rule is **location = D3D input register**, not the semantic's HLSL slot. Match the layout element's semantic name/index to the ISG1 element to get the register, then create a `VkVertexInputAttributeDescription` with that location diff --git a/docs/design.md b/docs/design.md index 7bff52e7f9..455c8f3f0a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -432,7 +432,7 @@ How the generated SPIR-V expects the runtime to work: | Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. | | First active lane in a vertex shader (`v_readfirstlane_b32`, MoltenVK) | A native `v_readfirstlane_b32` is a ballot of the EXEC lanes, its lowest set bit, and a shuffle from that lane (lane 0 when no lane is on). **In a vertex shader the lowest bit is taken with `FindILsb` over the ballot's four words** (the lowest non-zero word wins), not with `OpGroupNonUniformBallotFindLSB`. The two give the same lane, because a ballot has no bit at or above the subgroup size. Other stages keep `BallotFindLSB`; the `--wave64-emulate` form already used `FindILsb` on its two mask words. Why: MoltenVK lowers `BallotFindLSB`, like the `SubgroupSize` built-in, to Metal's `threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for input declaration in a vertex function"), so every VS with a readfirstlane failed to compile there. **Confirmed on an Apple M4 (MoltenVK 1.4.2):** hand-written VS with `subgroupBallotFindLSB` or `gl_SubgroupSize` fail, and ballot, shuffle, broadcast-first, elect, votes, and ballot + `findLSB` + shuffle (32- and 64-lane forms) create. Corpus (1.0.2.1, translated from `4eb6155d`): 572 of the 2,236 VS contain `v_readfirstlane_b32`, and exactly those 572 modules change; all 2,236 stay `spirv-val`-valid. VS pipelines on the M4 go from 667 to 672 of 2,236 on main (the rest fail on the subgroup lane built-in, #1784), and from 1,662 to 2,233 with #1784's vertex-subgroup workaround (its flag is not on main) (the 571 `threads_per_simdgroup` failures are gone). `tests/semantic/test_vs_readfirstlane.py` runs it on the wave interpreter with the first EXEC lane in word 0 and word 1. | | Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. Under `--wave64-emulate`, `tools/wave64_emulate_opt.py` runs three exact CFG/dataflow passes to eliminate redundant scheduler rounds and global `OpSwitch` blow-up (#884): (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, no live-out scalars, and for each memory domain (`mem`/`lds`) either read-only accesses or an acyclic single write/atomic behind `if (%active)` (issuing any uniform `x_memory_order` split/barrier before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), and (3) structured emulation (`plan_structured_emulation`, `control_flow = "emulated wave64 structured"`) removes the global round-loop `OpSwitch` on multi-superblock reducible CFGs without non-uniform 32-bit half-mask SCC: single-wave workgroups (`<= 64` threads) run 100% inline structured SPIR-V with direct workgroup barriers (`0` `OpSwitch`, `0` `x_spill`, strictly monotone GEN/KILL 4-bit `dirty_in` memory ordering across blocks and loop back-edges), while multi-wave workgroups (`> 64` threads) emit post-dominating spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, `EXEC`-widening, and read-only loops) inline and isolate any remaining wave-divergent barrier regions into local mini-schedulers (or a tail scheduler from the first early `s_endpgm`, or the first `s_barrier` under a guard or in a loop, to the end: waves on different paths may meet at different `s_barrier` sites, which only the rounds model; the NGG mesh epilogue, `s_cbranch_vccnz` over an `s_barrier`, is the common case). Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (40/64/128/256-thread workgroup interpreter with strict uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, single-store WAR/RAW ordering, single-wave `inline_all` loop-carried WAR, monotone `dirty_in` regression after `x_round`, multi-wave `structured_hybrid` + local `mini_scheduler`, divergent `s_barrier` in the tail rounds, guarded `s_barrier` epilogue, `cs_w64x_saveexec_b64.s` fixture, and negative controls; **not yet GPU-verified** for the structured emulation pass). In addition, `wave64_emulate_opt.py` excludes lane-mask `s_flbit_i32_b32`/`s_flbit_i32` and mixed mask+data `s_cmp_eq_u64`/`s_cmp_lg_u64` from folded/sync-free blocks and `Gen.x_memory_order` skips `ds_nop` (matching `_x_memory_order_access`), pinned by `tests/semantic/test_wave64_emulate_barriers.py` (CPU workgroup interpreter only, not GPU-checked). (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), and (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no memory/LDS writes, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, and no live-out scalars behind `if (%active)` (issuing any uniform `x_memory_order` split before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), keeping all 64 lanes of each wave in the same scheduler round. Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (64-thread and 128-thread workgroup interpreter with uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, internal loop, `cs_w64x_saveexec_b64.s` fixture, RAW memory/scalar-load ordering, and negative controls for live-out scalars, stores, cross-lane ops, and EXEC-widening). `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | -| Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | +| Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Mesh shaders are covered the same way: a MeshEXT module's Workgroup memory — the LDS array (PSV0's shared size grown to the furthest `ds` offset, a power of two), the 4-byte `%ms_counts` and `%x_buf` of `--wave64-emulate` — is capped at translation by `--max-mesh-shared-memory` (default 0, no check, so nothing that translated before is refused: a 64 KiB LDS array plus `%ms_counts` is already 65,540 B; pass a device's `maxMeshSharedMemorySize`, 28,672 being the `VK_EXT_mesh_shader` minimum, to refuse at translation what it can't run, while the runtime checks `lds_bytes` against the device it runs on either way), and a module over it is refused (`Unsupported`) with the needed and allowed byte counts. A `--mesh-compute` module is GLCompute and keeps the compute cap (`--max-shared-memory`). Pinned by `tests/semantic/test_ms_shared_memory_limit.py` (under the cap, over it with the byte counts, the exact boundary, the wave64 exchange counted, mesh-compute on the compute cap, and the CLI flag end to end); CPU tests only, no GPU run. | | Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | | Wave64 emulation: cross-lane reads of missing lanes | With `--wave64-emulate`, a read of another lane's exchange slot (`ds_swizzle_b32`, `ds_bpermute_b32`, `ds_permute_b32`'s targets and data, `v_readlane_b32`, `v_readfirstlane_b32`, DPP and the other reads behind `Gen.x_round`) gives 0 when the source lane doesn't exist in a partial last wave (`Gen.x_lane_word`: `x_wbase + lane < threads`, else 0), as a source lane that isn't running reads 0 on the hardware. The prologue still zeroes those slots, but a read must not depend on it: RADV (Mesa 26.3.1, gfx1036 iGPU and RX 7900 XTX) compiled the store, barrier and load of an exchange behind a branch into `masked_swizzle_amd` with `fetch_inactive` (`RADV_DEBUG=shaders`), so in a 40-thread group lanes 32-39 of `ds_swizzle_b32 offset:swizzle(SWAP,8)` read the missing lanes' registers, garbage that changed between runs. Workgroups whose size is a multiple of 64 emit the same module as before. Confirmed by `runtime/test/shaders/cs_w64x_partial_swizzle.asm` (40 threads: SWAP 8, BROADCAST 16,15 and `ds_bpermute_b32` from lanes 40-47; its 8 words measured natively on gfx1036 through `tools/hw_oracle`): emulated at subgroup 32 (RADV, Mesa 26.3.1), words 2 and 3 wrong before in 20 of 20 runs on the gfx1036 iGPU and 19 of 20 on the RX 7900 XTX, and all 8 words right in 20 of 20 runs on both after; native wave64 and emulated at subgroup 64 right both times. `scripts/run_gpu_tests.py` runs the partial-wave fixtures emulated at subgroup 32, as `check.py` does, since at RADV's default of 64 this fixture passed before the change too; by `crosslane_fuzz.py --wave 64 --ext --dpp --no-maskdata --programs 1000 --seed 48315`, emulated: on the gfx1036 iGPU 993 match and 7 hyp_only (all 40-thread groups, lanes 32-39 reading a swizzle source of 40-47) before, 1000/1000 after, and on the RX 7900 XTX 995 match and 5 hyp_only before, 1000/1000 after; and by `tests/semantic/test_w64x_partial_swizzle.py` (fixture `w64x_partial_swizzle.asm`, 40 and 104 threads, the prologue's zero stores replaced by a poison word in the workgroup interpreter; both cases fail before the change). | diff --git a/tests/semantic/fixtures/ms_shared_limit.asm b/tests/semantic/fixtures/ms_shared_limit.asm new file mode 100644 index 0000000000..3e36e76226 --- /dev/null +++ b/tests/semantic/fixtures/ms_shared_limit.asm @@ -0,0 +1,6 @@ +; Mesh shader (NGG, wave64), PSV0: 128 threads, 64/64 outputs, triangles; the group-shared size is the DXBC's. +; One ds_write_b32 gives the shader an LDS array; the workgroup-memory limit tests size it through PSV0. +s_mov_b64 exec, -1 +v_lshlrev_b32_e32 v1, 2, v0 +ds_write_b32 v1, v0 +s_endpgm diff --git a/tests/semantic/test_ms_shared_memory_limit.py b/tests/semantic/test_ms_shared_memory_limit.py new file mode 100644 index 0000000000..c7f12ec0ab --- /dev/null +++ b/tests/semantic/test_ms_shared_memory_limit.py @@ -0,0 +1,189 @@ +"""A mesh shader's Workgroup memory fits in maxMeshSharedMemorySize (SHADER-MESH-SHARED-LIMIT). + +`rdna2spirv.MAX_MESH_SHARED_BYTES` (`--max-mesh-shared-memory`, default 0: no check; +28672 is the VK_EXT_mesh_shader minimum `maxMeshSharedMemorySize`) caps what a MeshEXT module declares in the Workgroup storage class: the LDS array +(PSV0's shared size grown to the furthest ds offset, a power of two), the 4-byte `%ms_counts` and, under +`--wave64-emulate`, `%x_buf` — the same total `lds_bytes` records for the runtime's device-limit check +(vk_pipeline_check / mesh_limit_refusal). Over the cap the shader is refused (`Unsupported`, with the byte +counts). A `--mesh-compute` module is GLCompute and runs as a compute shader, so it keeps the compute cap +(`MAX_SHARED_BYTES`, `--max-shared-memory`). There is no allocation to shrink to: the array is the program's need. + +The program is fixtures/ms_shared_limit.asm (hand-written, no game data) and the PSV0 part is written here; the +Workgroup bytes are counted from the emitted SPIR-V. The last test runs the tool's CLI end to end. +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path + +import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) + +rdna2spirv = support.rdna2spirv +FIXTURE = os.path.join(HERE, "fixtures", "ms_shared_limit.asm") +TOOL = os.path.join(support.ROOT, "tools", "rdna2spirv.py") + + +def mesh_dxbc(group_shared, threads=128): + """DXBC with one PSV0 part: the fields mesh_psv() reads (stage 13, 64/64 triangles, NumThreads, shared bytes).""" + r = bytearray(48) + struct.pack_into(" limit: + raise Unsupported(f"MS workgroup memory {wg} B (LDS {lds_b} B" + + (f" + wave64 exchange {gen.x_buf_bytes()} B" if gen.emulate else "") + + f" + %ms_counts 4 B) over {limit_name} {limit} B") if gen.frag_inputs or bary: dec += ["OpDecorate %frag_coord BuiltIn FragCoord"] gvars += ["%frag_coord = OpVariable %_ptr_Input_v4 Input"] @@ -19735,7 +19756,8 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): m["gs_input_locations"] = sorted(r for r, sv in g.gs["in"] if sv != 1) m["gs_output_locations"] = sorted(r for r, sv in g.gs["out"] if sv != 1) # Every Workgroup byte of a compute shader (LDS + %x_buf of the emulation or the barrier rounds; SHADER-309): the - # runtime compares it with the device's maxComputeSharedMemorySize. A mesh shader also has its 4-byte %ms_counts. + # runtime compares it with the device's maxComputeSharedMemorySize, and a mesh shader's (LDS + %ms_counts + %x_buf) + # with its maxMeshSharedMemorySize, both capped at translation by --max-shared-memory / --max-mesh-shared-memory. lds = (4 * g.lds_dwords if g.uses_lds else 0) + (g.x_buf_bytes() if g.cs or g.emulate else 0) + (4 if g.ms else 0) if lds: m["lds_bytes"] = lds @@ -20071,7 +20093,7 @@ def _out_inside_input(src, out): def main(): - global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, DESCRIPTOR_HASH, DESCRIPTOR_TABLE + global MAX_SHARED_BYTES, MAX_MESH_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, DESCRIPTOR_HASH, DESCRIPTOR_TABLE ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("--out", required=True) @@ -20133,6 +20155,12 @@ def main(): "(default %(default)s, the 64 KiB hard cap): over it the LDS array shrinks to the program's " "need, or the shader is refused (Unsupported). The device's own maxComputeSharedMemorySize " "(32768 on some drivers) is checked by the runtime against lds_bytes in index.json") + ap.add_argument("--max-mesh-shared-memory", type=int, default=MAX_MESH_SHARED_BYTES, metavar="BYTES", + help="cap on a mesh shader's workgroup memory, its LDS plus %%ms_counts and what " + "--wave64-emulate adds (default 0: no check; 28672 is the VK_EXT_mesh_shader minimum " + "maxMeshSharedMemorySize): over it the shader is refused (Unsupported). The device's own " + "maxMeshSharedMemorySize is checked by the runtime against lds_bytes in index.json; a " + "--mesh-compute module is compute and uses --max-shared-memory") ap.add_argument("--pc-tail-ubo", action="store_true", help="keep only s0..s31 (128 bytes) in push constants and read the heap base, code base and " "--mesh-compute output address from a uniform block at set 1, binding 0 (metadata: pc_tail), " @@ -20175,6 +20203,7 @@ def main(): if ancestor and not os.path.isdir(ancestor): ap.error(f"cannot create {a.out}: {ancestor} is a file, not a folder") MAX_SHARED_BYTES = a.max_shared_memory + MAX_MESH_SHARED_BYTES = a.max_mesh_shared_memory DESCRIPTOR_HASH = a.descriptor_hash DESCRIPTOR_TABLE = a.descriptor_table LOOP_LIMIT = a.loop_limit