diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index ce1a5f7bef..c32175c52c 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -4179,7 +4179,7 @@ store, load, mesh, geometry and BVH tests; this layer is the other half. | Vertex fetch | PSO input layout + ISG1 signature; location = D3D input register; format from `DXGI_FORMAT`; instance step rate from the layout. The fetch subroutine is already replaced by Vulkan inputs. | | PS system inputs | `FragCoord` (xy/z/w), `FrontFacing`, barycentrics; enable `fragmentShaderBarycentric` and `fragmentShaderPixelInterlock` when the index entry asks. | | Mesh/geometry stages | `VK_EXT_mesh_shader`; the index's max vertices/primitives size the SPIR-V output arrays and are checked against the device's mesh properties; geometry stage for the 195 voxelize shaders; `DispatchMesh` → `vkCmdDrawMeshTasksEXT`. | -| POPS collision | The runtime puts 0 (no collision, bit 31 clear) in the POPS collision SGPR; the translator uses fragment-shader interlock for ordering. **Open:** the exact SGPR location is a translator/driver detail not named in the current contract. | +| POPS collision | The translator seeds the POPS collision SGPR itself at entry (`0x00010000`: no overlap, wave id 1, collision id 0; `docs/design.md`, "POPS"), so whatever the push constants hold at that SGPR's dword does not matter; ordering comes from fragment-shader interlock. The SGPR is the one the program's wave id extract reads (after the user SGPRs and the primitive mask). | | Wave size | The PSO asks for the size the shader was translated for (`requiredSubgroupSize` 64 or 32, section 3.2 "Subgroup size") where the stage is in `requiredSubgroupSizeStages`; a shader translated with `--wave64-emulate` asks for nothing. A size the device cannot give is named in the log. | | Code-embedded data | The whole FSSM blob is in the arena; `s_getpc_b64` becomes `code_base + next-instruction offset`. | diff --git a/docs/design.md b/docs/design.md index 8e185c5d65..75fec69090 100644 --- a/docs/design.md +++ b/docs/design.md @@ -352,7 +352,7 @@ How the generated SPIR-V expects the runtime to work: | Packed integer dot products (`v_dot2_i32_i16`, `v_dot2_u32_u16`, `v_dot4_u32_u8`, `v_dot8_i32_i4`, `v_dot8_u32_u4`) and `v_pk_fmac_f16` | RDNA2 ISA: `v_dot2_i32_i16`/`u16` (2×16-bit), `v_dot4_u32_u8` (4×8-bit unsigned), and `v_dot8_i32_i4`/`u4` (8×4-bit) extract each element with `OpBitFieldSExtract`/`OpBitFieldUExtract`, sum the elementwise products with `S2` wrapping at 32 bits, and saturate to `[INT32_MIN, INT32_MAX]` / `[0, UINT32_MAX]` under VOP3P `clamp` (signed carry tracking handles the `v_dot2_i32_i16` `(-32768)^2 + (-32768)^2 + S2` overflow/cancellation edge). The hardware default `op_sel:[0,0,0]` and `op_sel_hi:[1,1,1]` (whether omitted or written explicitly) is accepted; any other `op_sel`/`op_sel_hi` (such as `op_sel_hi:[0,0,0]` or `[0,1,1]`, which select the low half for lane 1 on `v_dot2_*`), `neg_lo`/`neg_hi`, DPP/SDWA forms, and source `neg`/`abs` raise `Unsupported`. (`v_dot4_i32_i8` and `v_dot4c_i32_i8` are covered separately in the Signed-byte dot products row, #1754.) `v_pk_fmac_f16` (VOP2) unpacks `src0`, `vsrc1` and `vdst` as `f16x2` (`Gen.src_h`, so inline float constants apply in the low half with `+0.0` high), computes `fma(src0[k], vsrc1[k], vdst[k])` per half with single f16 rounding (`Gen.fma_f16_odd`, SHADER-55), and packs with `Gen.f16_pack2`; any modifier outside `_dpp` or non-VGPR `vdst` raises `Unsupported`, and `v_pk_fmac_f16` marks `vdst` as read before write in `read_before_write_vgprs` and `reg_reads_writes`. Until 2026-11-22 all six ops raised `Unsupported`. **Hardware-confirmed on RDNA2:** on `gfx1036` (Ryzen 9 7950X3D iGPU, `tools/hw_oracle`, @aslan2142), all 60 integer dot-product sets (plain, swapped/SGPR sources, and `clamp`) match bit-for-bit, all measured `op_sel`/`neg_*` variants are refused, and all 22 `v_pk_fmac_f16` default-MODE (`0x000003C0`: round-to-nearest-even, f16 denormals kept, IEEE and DX10_CLAMP on) words match in both source orders (all 34 non-NaN halves bit-exact; the 10 NaN halves yield quiet f16 NaN, as SPIR-V does not preserve NaN payload bits or sign); independently confirmed on `gfx1035` (Radeon 680M, `tools/hw_oracle`, @Youssefrah16) across 18 cases × wave32/wave64 (36/36 bit-exact). Pinned by `tests/semantic/test_alu_dot_pk_fmac.py` (all 82 `gfx1036` measured tables plus hand-written `.asm` fixture, boundary/clamp cases, default/non-default `op_sel`/`op_sel_hi`, `read_before_write_vgprs`/`reg_reads_writes`, DPP, seeded sweeps, and rejected forms). Non-default f16 MODEs (denormal flush, RTZ) are not modelled on `v_pk_fmac_f16` while the translator has no MODE input. | | `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. | | `v_div_fmas_f32`, `v_div_fmas_f64` | Scaled FMA for IEEE-754 division (VOP3): `D = fma(S0, S1, S2)` when `VCC[lane] == 0`; when `VCC[lane] == 1`, `D = (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2)` where `(bias, S)` is `(127, 64)` for f32 and `(1023, 128)` for f64 (`OpCapability Float64`, no `Int64`), i.e. `\|S2\| >= 2.0` scales up and `\|S2\| < 2.0` scales down. Scale-up uses `fma(S0, S1, S2) * 2^S` (any non-zero cancellation residual against `\|S2\| >= 2.0` stays well above normal minimum). Scale-down pre-scales `S0`/`S1` only when `\|S0*S1\|` can overflow (`\|S0\| >= 2^S` and `\|S1\| >= 1`, symmetric, or both `>= 2^(S/2)`), with a raw-bit sticky value `copysign(min_normal, S2)` whenever `0 < \|S2\| < 2^(Emin + S)` so half-ULP tie-breaking stays exact; otherwise it post-scales `fma(S0, S1, S2) * 2^-S`, with a TwoSum + product-error half-ULP tie adjustment in f64 when `\|fma\|` falls in `[2^-947, 2^-894)` so f64 subnormal outputs single-round. For f32 under the game MODE (`denorm32=0`), subnormal inputs and intermediate products are kept while subnormal outputs flush to signed zero before (and after) output modifiers; for f64 (`denorm16_64=3`), subnormals are kept throughout. VOP3 input (`abs`/`neg`) and output (`mul:2`/`mul:4`/`div:2`, then `clamp`) modifiers apply via `clamp_mods` / `clamp_mods_f64`. **Until 2026-11-22 the translator scaled unconditionally by `2^32` (f32) / `2^64` (f64) whenever `VCC[lane] == 1`, omitting the `exp(S2) > bias` branch and using half the hardware exponent shift.** **Hardware-verified on RDNA2** (`gfx1036`, AMD Radeon Graphics, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64, game MODE `ieee=0`/`dx10_clamp=1`/`denorm32=0`/`denorm16_64=3`): 150/150 f32 and 153/153 f64 stress cases match bit-for-bit, including the `\|S2\| = 2.0` vs `nextbelow(2.0)` threshold, scale-down overflow prevention, sticky-bit tie-breaking, f32 output denormal flushing, and f64 subnormal single rounding. Checked bit-for-bit on the CPU (`spirv_mini_interp` for f32, SSA `%double` evaluator for f64) and assembled with `tools/spirv_asm.py` (plus `spirv-val` when present) by `tests/semantic/test_alu_div_fmas.py`; not run on the shader corpus. | -| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | +| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and the translator seeds the **collision word**. The hardware puts it in the SGPR after the user SGPRs and the primitive mask (collision wave id in bits 0-9, this wave's id in bits 16-25, overlap in bit 31; Mesa's `pops_collision_wave_id`), and the program takes the wave id out with `s_bfe_u32 ..., 0x000a0010`. The source of that extract, when the program reads its entry value (`shader_meta`'s `user_sgpr_reads`), is set at entry to `0x00010000` (no overlap, wave id 1, collision id 0). The overlap test before the wait loop skips the loop whenever a lane is on in EXEC. A wave that reaches the loop with EXEC all off (on a device with 32-wide subgroups, either half of a wave64 program) leaves after one round: `wave_id + ~collision_id` is 0, below `0 + ~collision_id`. **Until 2026-11-25** the word was what the push constants held at that SGPR's dword, usually 0: wave id == collision id, the test was `0xffffffff < 0xffffffff`, and such a wave ran the loop until the loop guard (65,536 rounds). A program whose extract is not found keeps the old behaviour; the corpus's 10 POPS shaders all extract the word from the same SGPR. CPU-checked by `tests/semantic/test_pops_collision_seed.py` (subgroups of 64 and of 32 lanes, with and without the seed) on `runtime/test/shaders/ps_pops_wait_loop.asm`, which check.py also runs on the GPU: on an RTX 4070 SUPER (Windows 11) 4096 of 4096 pixels as expected, and with the seed taken out every pixel's x is `0x00010000`, the loop guard's 65,536 rounds. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`); vk_harness reports a device without it as unsupported (exit 77). | | Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10-10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class for those 2D views, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); other loads in the corpus keep the sampled path and need no storage feature (SHADER-151). The D3D-78 row below describes the storage-only and tagged atomic readback exceptions. `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) or on a dimension without storage views (cube) is `Unsupported`. Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | | 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. | | 2D `image_sample_l` | The T# FORMAT selects the sampled image type, and every type uses the LOD following the two coordinates. Vulkan requires the sampled type and signedness to match the view. The unit test `test_2d_lod_samples_use_matching_typed_views` in `tests/test_image_load_typed.py` checks the R32 UINT, SINT and FLOAT descriptor branches, the float fallback on a lookup miss and the LOD register with full-width and D16 results. [Vulkan sampling validation](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-input-validation) | diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 39a3179a46..16c304e8ff 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -837,6 +837,8 @@ def salu_ext_test(tools, spirv, env=None): "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000), # far branches: s_getpc/s_add|s_sub/s_addc|s_subb/s_setpc forward, backward loops, conditional (.asm header) "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000b), + # POPS wait loop: rounds with EXEC off (1, not the loop guard) and on (0) (.asm header) + "ps_pops_wait_loop": (0x00000001, 0x00000000, 0x3f800000, 0x3f800000), # 16-bit float v_cmp, all 16 predicates, e32 and e64 with swapped operands (.asm headers) "ps_vcmp_f16": (0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba), "ps_vcmp_f16_e64": (0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9), diff --git a/runtime/test/shaders/ps_pops_wait_loop.asm b/runtime/test/shaders/ps_pops_wait_loop.asm new file mode 100644 index 0000000000..b582a85434 --- /dev/null +++ b/runtime/test/shaders/ps_pops_wait_loop.asm @@ -0,0 +1,61 @@ +; POPS (primitive-ordered pixel shading) wait loop (docs/design.md "POPS"): the entry of an ordered section as console +; pixel programs write it, wave64. The hardware puts the collision word in the SGPR after the user SGPRs and the +; primitive mask (s18 here): collision wave id in bits 0-9, this wave's id in bits 16-25, overlap in bit 31. The +; program extracts the ids, computes s5 = wave_id + ~collision_id, skips the loop when the overlap bit is clear (or +; its turn has come) for a lane in EXEC, and otherwise waits until s5 < src_pops_exiting_wave_id + ~collision_id. +; The translator orders the section with fragment-shader interlock, reads src_pops_exiting_wave_id as 0 and seeds the +; collision word with 0x00010000 (no overlap, wave id 1, collision id 0), so a wave that enters the loop leaves it +; after one round: s5 = 1 + 0xffffffff = 0 < 0 + 0xffffffff. +; x: rounds of the loop with EXEC all off at s_cbranch_vccnz (the vote fails, the wave falls into the loop): 1. +; A collision word with wave id == collision id (0, what the push constants hold for s18) gives s5 = 0xffffffff, +; never below 0xffffffff: the loop ran until the loop guard (65536 rounds, x = 0x00010000). +; y: rounds with EXEC all on: the overlap test holds for every lane, the branch skips the loop: 0. +; z, w: 1.0, so a pixel that is written shows it. +; Each s_cbranch_vccnz skips the 5 dwords of its loop; each s_cbranch_scc0 -5 goes back to the loop's s_sleep. +; Expected mrt0 bits: 0x00000001, 0x00000000, 0x3f800000, 0x3f800000 +s_mov_b64 s[20:21], exec +s_mov_b32 s12, 0 +s_mov_b32 s13, 0 +s_mov_b64 exec, 0 +s_bfe_u32 s2, s18, 0xa0000 +s_bfe_u32 s5, s18, 0xa0010 +s_not_b32 s4, s2 +s_lshr_b32 s0, s18, 31 +s_add_i32 s5, s5, s4 +s_cmp_eq_u32 s0, 0 +s_cselect_b64 s[0:1], exec, 0 +s_add_i32 s2, src_pops_exiting_wave_id, s4 +s_cmp_gt_u32 s2, s5 +s_cselect_b64 s[2:3], exec, 0 +s_or_b64 s[0:1], s[0:1], s[2:3] +s_and_b64 vcc, exec, s[0:1] +s_cbranch_vccnz 5 +s_sleep 0xffff +s_add_i32 s12, s12, 1 +s_add_i32 s0, src_pops_exiting_wave_id, s4 +s_cmp_lt_u32 s5, s0 +s_cbranch_scc0 -5 +s_mov_b64 exec, s[20:21] +s_bfe_u32 s2, s18, 0xa0000 +s_bfe_u32 s5, s18, 0xa0010 +s_not_b32 s4, s2 +s_lshr_b32 s0, s18, 31 +s_add_i32 s5, s5, s4 +s_cmp_eq_u32 s0, 0 +s_cselect_b64 s[0:1], exec, 0 +s_add_i32 s2, src_pops_exiting_wave_id, s4 +s_cmp_gt_u32 s2, s5 +s_cselect_b64 s[2:3], exec, 0 +s_or_b64 s[0:1], s[0:1], s[2:3] +s_and_b64 vcc, exec, s[0:1] +s_cbranch_vccnz 5 +s_sleep 0xffff +s_add_i32 s13, s13, 1 +s_add_i32 s0, src_pops_exiting_wave_id, s4 +s_cmp_lt_u32 s5, s0 +s_cbranch_scc0 -5 +v_mov_b32_e32 v0, s12 +v_mov_b32_e32 v1, s13 +v_mov_b32_e32 v2, 1.0 +exp mrt0 v0, v1, v2, v2 done vm +s_endpgm diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp index cd374e8b6f..cf7139861a 100644 --- a/runtime/test/vk_harness.cpp +++ b/runtime/test/vk_harness.cpp @@ -309,12 +309,14 @@ int main(int argc, char** argv) { // (llvmpipe and other software devices), so the suite reports it as unsupported instead. 77 is the existing // "this device cannot run the test" code (runtime/test/shaders/check.py, scripts/run_gpu_tests.py). const std::vector fs_code = read_spv(argv[2]); - bool needs_barycentric = false, needs_float64 = false; + bool needs_barycentric = false, needs_float64 = false, needs_interlock = false; for (std::size_t i = 5; i + 1 < fs_code.size();) { // instructions follow the 5-word SPIR-V header const uint32_t words = fs_code[i] >> 16, op = fs_code[i] & 0xffffu; if (!words) break; if (op == 17 && fs_code[i + 1] == 5284) // OpCapability FragmentBarycentricKHR needs_barycentric = true; + if (op == 17 && fs_code[i + 1] == 5378) // OpCapability FragmentShaderPixelInterlockEXT (POPS) + needs_interlock = true; if (op == 17 && fs_code[i + 1] == 10) // OpCapability Float64 (v_add_f64 and friends) needs_float64 = true; i += words; @@ -324,6 +326,19 @@ int main(int argc, char** argv) { argv[2], VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); return 77; } + // The same for a pixel shader with an ordered section (POPS), which runs under fragment-shader interlock. + if (needs_interlock) { + VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT have_lock{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have_lock}; + const bool ext = has(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); + if (ext) vkGetPhysicalDeviceFeatures2(pd, &query); + if (!ext || !have_lock.fragmentShaderPixelInterlock) { + std::fprintf(stderr, "unsupported: %s uses fragment-shader interlock and the device has no " + "fragmentShaderPixelInterlock\n", argv[2]); + return 77; + } + } // OpFmaKHR (rdna2spirv.py --fma khr) needs VK_KHR_shader_fma; a module of ANY stage that needs it is refused // (argv[1] is the vertex shader, or the mesh shader run as compute under VKH_MESH_COMPUTE). leonida::vk_test::ShaderFma fma; diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index f87290ec65..05062dcd22 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -1546,6 +1546,7 @@ def run_suite(a, work: str) -> int: # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000), "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000B), # far branches (.asm header) + "ps_pops_wait_loop": (0x00000001, 0x00000000, 0x3F800000, 0x3F800000), # POPS wait loop (.asm header) "ps_vcmp_f16": (0x48A12080, 0x4CE9B1A2, 0x4BA72C98, 0x4FEFBDBA), # 16-bit float v_cmp e32 (.asm header) "ps_vcmp_f16_e64": (0x44C11100, 0x4CF171C1, 0x47C71D18, 0x4FF77DD9), # same, e64 with swapped operands "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header) diff --git a/tests/semantic/fixtures/disasm/ps_pops_wait_loop.s b/tests/semantic/fixtures/disasm/ps_pops_wait_loop.s new file mode 100644 index 0000000000..3892151543 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_pops_wait_loop.s @@ -0,0 +1,47 @@ +; ps_pops_wait_loop llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding output for runtime/test/shaders/ps_pops_wait_loop.asm (the branches need the instruction encodings; test_pops_collision_seed.py checks this listing against the .asm) + s_mov_b64 s[20:21], exec ; encoding: [0x7e,0x04,0x94,0xbe] + s_mov_b32 s12, 0 ; encoding: [0x80,0x03,0x8c,0xbe] + s_mov_b32 s13, 0 ; encoding: [0x80,0x03,0x8d,0xbe] + s_mov_b64 exec, 0 ; encoding: [0x80,0x04,0xfe,0xbe] + s_bfe_u32 s2, s18, 0xa0000 ; encoding: [0x12,0xff,0x82,0x93,0x00,0x00,0x0a,0x00] + s_bfe_u32 s5, s18, 0xa0010 ; encoding: [0x12,0xff,0x85,0x93,0x10,0x00,0x0a,0x00] + s_not_b32 s4, s2 ; encoding: [0x02,0x07,0x84,0xbe] + s_lshr_b32 s0, s18, 31 ; encoding: [0x12,0x9f,0x00,0x90] + s_add_i32 s5, s5, s4 ; encoding: [0x05,0x04,0x05,0x81] + s_cmp_eq_u32 s0, 0 ; encoding: [0x00,0x80,0x06,0xbf] + s_cselect_b64 s[0:1], exec, 0 ; encoding: [0x7e,0x80,0x80,0x85] + s_add_i32 s2, src_pops_exiting_wave_id, s4 ; encoding: [0xef,0x04,0x02,0x81] + s_cmp_gt_u32 s2, s5 ; encoding: [0x02,0x05,0x08,0xbf] + s_cselect_b64 s[2:3], exec, 0 ; encoding: [0x7e,0x80,0x82,0x85] + s_or_b64 s[0:1], s[0:1], s[2:3] ; encoding: [0x00,0x02,0x80,0x88] + s_and_b64 vcc, exec, s[0:1] ; encoding: [0x7e,0x00,0xea,0x87] + s_cbranch_vccnz 5 ; encoding: [0x05,0x00,0x87,0xbf] + s_sleep 0xffff ; encoding: [0xff,0xff,0x8e,0xbf] + s_add_i32 s12, s12, 1 ; encoding: [0x0c,0x81,0x0c,0x81] + s_add_i32 s0, src_pops_exiting_wave_id, s4 ; encoding: [0xef,0x04,0x00,0x81] + s_cmp_lt_u32 s5, s0 ; encoding: [0x05,0x00,0x0a,0xbf] + s_cbranch_scc0 -5 ; encoding: [0xfb,0xff,0x84,0xbf] + s_mov_b64 exec, s[20:21] ; encoding: [0x14,0x04,0xfe,0xbe] + s_bfe_u32 s2, s18, 0xa0000 ; encoding: [0x12,0xff,0x82,0x93,0x00,0x00,0x0a,0x00] + s_bfe_u32 s5, s18, 0xa0010 ; encoding: [0x12,0xff,0x85,0x93,0x10,0x00,0x0a,0x00] + s_not_b32 s4, s2 ; encoding: [0x02,0x07,0x84,0xbe] + s_lshr_b32 s0, s18, 31 ; encoding: [0x12,0x9f,0x00,0x90] + s_add_i32 s5, s5, s4 ; encoding: [0x05,0x04,0x05,0x81] + s_cmp_eq_u32 s0, 0 ; encoding: [0x00,0x80,0x06,0xbf] + s_cselect_b64 s[0:1], exec, 0 ; encoding: [0x7e,0x80,0x80,0x85] + s_add_i32 s2, src_pops_exiting_wave_id, s4 ; encoding: [0xef,0x04,0x02,0x81] + s_cmp_gt_u32 s2, s5 ; encoding: [0x02,0x05,0x08,0xbf] + s_cselect_b64 s[2:3], exec, 0 ; encoding: [0x7e,0x80,0x82,0x85] + s_or_b64 s[0:1], s[0:1], s[2:3] ; encoding: [0x00,0x02,0x80,0x88] + s_and_b64 vcc, exec, s[0:1] ; encoding: [0x7e,0x00,0xea,0x87] + s_cbranch_vccnz 5 ; encoding: [0x05,0x00,0x87,0xbf] + s_sleep 0xffff ; encoding: [0xff,0xff,0x8e,0xbf] + s_add_i32 s13, s13, 1 ; encoding: [0x0d,0x81,0x0d,0x81] + s_add_i32 s0, src_pops_exiting_wave_id, s4 ; encoding: [0xef,0x04,0x00,0x81] + s_cmp_lt_u32 s5, s0 ; encoding: [0x05,0x00,0x0a,0xbf] + s_cbranch_scc0 -5 ; encoding: [0xfb,0xff,0x84,0xbf] + v_mov_b32_e32 v0, s12 ; encoding: [0x0c,0x02,0x00,0x7e] + v_mov_b32_e32 v1, s13 ; encoding: [0x0d,0x02,0x02,0x7e] + v_mov_b32_e32 v2, 1.0 ; encoding: [0xf2,0x02,0x04,0x7e] + exp mrt0, v0, v1, v2, v2 done vm ; encoding: [0x0f,0x18,0x00,0xf8,0x00,0x01,0x02,0x02] + s_endpgm ; encoding: [0x00,0x00,0x81,0xbf] diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index a2eb436fc9..be0ee9198a 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py @@ -25,6 +25,9 @@ lane number giving that lane's integer value, e.g. {"VertexIndex": lambda lane: first + lane}). PushConstant words can be seeded (default zero). +A fragment-shader interlock (OpBeginInvocationInterlockEXT / OpEndInvocationInterlockEXT) runs as a no-op: it orders +invocations of other primitives at the same pixel, and a run here has none. + 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 ], "steps": instructions executed (summed over invocations)} @@ -677,6 +680,10 @@ def ballot_bits(v): # -- per-invocation instructions ----------------------------------------------------------------------------- def eval(self, lane, res, op, a): m = self.m + if op in ("OpBeginInvocationInterlockEXT", "OpEndInvocationInterlockEXT"): + # The interlock orders fragment invocations of other primitives at the same pixel; one subgroup run + # here has none, so it orders nothing. + return None if op == "OpVariable": cls, pointee = m.ptr_types[a[0]] if cls != "Function": diff --git a/tests/semantic/test_pops_collision_seed.py b/tests/semantic/test_pops_collision_seed.py new file mode 100644 index 0000000000..b764df0c1b --- /dev/null +++ b/tests/semantic/test_pops_collision_seed.py @@ -0,0 +1,200 @@ +"""POPS: the collision word a pixel shader's ordered section reads is seeded so its wait loop ends at once. + +The hardware gives a pixel shader with an ordered section (POPS) its collision word in the SGPR after the user SGPRs +and the primitive mask: collision wave id in bits 0-9, this wave's id in bits 16-25, overlap in bit 31. Console code +waits in a loop until wave_id + ~collision_id is below src_pops_exiting_wave_id + ~collision_id (unsigned). The +translator orders the section with fragment-shader interlock instead (docs/design.md "POPS"), reads the exiting id as 0 +and seeds the word with POPS_COLLISION_SEED (wave id 1, collision id 0, no overlap). The overlap test before the loop +skips it for a wave with a lane in EXEC; a wave (here: a host subgroup) with EXEC all off falls into it. With the +word the push constants held (0: wave id == collision id) the test 0xffffffff < 0xffffffff never held, and the loop +ran until the loop guard (65,536 rounds by default) in every such subgroup. On a device with 32-wide subgroups one +half of a wave64 pixel program is such a subgroup whenever its lanes are all off. + +The shader is runtime/test/shaders/ps_pops_wait_loop.asm (also run on the GPU by check.py and run_gpu_tests.py); its +listing tests/semantic/fixtures/disasm/ps_pops_wait_loop.s is llvm-mc output, for the branch encodings. The runs here +use spirv_wave_interp.run_wave, whole subgroups of 64 and of 32 lanes. The idea comes from Marvisak/VIctory 7ac1f54. +""" +import os +import re +import unittest +from unittest.mock import patch + +import support +import rdna2spirv +import shader_ir +from spirv_wave_interp import run_wave +from test_loop_ballot_barrier import _resolve_labels + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +NAME = "ps_pops_wait_loop" +FIXTURE = os.path.join(HERE, "fixtures", "disasm", NAME + ".s") +ASM = os.path.join(ROOT, "runtime", "test", "shaders", NAME + ".asm") +LIMIT = 40 # a small loop guard, so a loop that never ends on its own costs 40 rounds here +WORD_SGPR = 18 # the collision word's SGPR in the fixture and below + + +def header_words(): + with open(ASM, encoding="utf-8") as f: + m = re.search(r"Expected mrt0 bits: (.*)", f.read()) + return tuple(int(x, 16) for x in m.group(1).split(",")) + + +def translate_fixture(seed=True): + """The fixture listing, translated with LIMIT as the loop guard; without the seed when `seed` is False (the + translator before the change: the word stays as the push constants give it).""" + with open(FIXTURE, "rb") as f: + data = f.read() + with patch.object(rdna2spirv, "LOOP_LIMIT", LIMIT): + if seed: + return support.translate_listing(NAME, data) + with patch.object(rdna2spirv, "pops_collision_sgpr", lambda insns, reads: None): + return support.translate_listing(NAME, data) + + +def mrt0(text, wave, word=0): + """{mrt0 words} over the lanes of one subgroup run, with `word` in push-constant dword WORD_SGPR.""" + run = run_wave(text, wave=wave, push_constants=[0] * WORD_SGPR + [word] + [0] * (31 - WORD_SGPR)) + return {tuple(out["%out_mrt0"]) if out else None for out in run["outputs"]} + + +PROLOGUE = [ + "s_bfe_u32 s2, s18, 0xa0000", + "s_bfe_u32 s5, s18, 0xa0010", + "s_not_b32 s4, s2", + "s_lshr_b32 s0, s18, 31", + "s_add_i32 s5, s5, s4", + "s_cmp_eq_u32 s0, 0", + "s_cselect_b64 s[0:1], exec, 0", + "s_add_i32 s2, src_pops_exiting_wave_id, s4", + "s_cmp_gt_u32 s2, s5", + "s_cselect_b64 s[2:3], exec, 0", + "s_or_b64 s[0:1], s[0:1], s[2:3]", + "s_and_b64 vcc, exec, s[0:1]", + "s_cbranch_vccnz body", + "wait:", + "s_sleep 0xffff", + "s_add_i32 s12, s12, 1", + "s_add_i32 s0, src_pops_exiting_wave_id, s4", + "s_cmp_lt_u32 s5, s0", + "s_cbranch_scc0 wait", + "body:", +] + + +def lanes_on(*predicate): + """Instructions that leave EXEC on in the lanes `predicate` (ending in a v_cmpx on the lane number in v1) + names.""" + return ["v_mbcnt_lo_u32_b32 v1, -1, 0", "v_mbcnt_hi_u32_b32 v1, -1, v1", *predicate] + + +def translate_program(exec_lines, seed=True): + """A pixel program: EXEC set by `exec_lines`, the ordered-section entry counting wait-loop rounds in s12, EXEC + back on, the count exported.""" + items = ["s_mov_b32 s12, 0", "s_mov_b64 s[20:21], exec", *exec_lines, *PROLOGUE, + "s_mov_b64 exec, s[20:21]", "v_mov_b32_e32 v4, s12", "exp mrt0 v4, v4, v4, v4 done vm", "s_endpgm"] + text = "; pops\n" + "".join(f"\t{t} ; encoding: [{','.join(['0x00'] * size)}]\n" + for t, size in _resolve_labels(items)) + with patch.object(rdna2spirv, "LOOP_LIMIT", LIMIT): + if seed: + return support.translate_listing("ps_pops_rounds", text.encode("utf-8")) + with patch.object(rdna2spirv, "pops_collision_sgpr", lambda insns, reads: None): + return support.translate_listing("ps_pops_rounds", text.encode("utf-8")) + + +def rounds(text, wave): + """{wait-loop rounds} over the lanes of one subgroup run (push constants all 0, as before the seed).""" + return {out["%out_mrt0"][0] for out in run_wave(text, wave=wave)["outputs"] if out} + + +class Fixture(unittest.TestCase): + def test_listing_is_the_asm(self): + """The listing has the `; encoding:` comments the branches need (regen_fixtures.py writes none), so it is + llvm-mc output; its mnemonics must be those of the .asm, in order.""" + def mnemonics(lines): + return [re.sub(r"_e32$", "", ln.split()[0]) for ln in lines] + with open(ASM, encoding="utf-8") as f: + asm = [ln.strip() for ln in f if ln.strip() and not ln.lstrip().startswith(";")] + with open(FIXTURE, encoding="utf-8") as f: + listing = [ln.strip() for ln in f.read().splitlines()[1:] if ln.strip()] + self.assertEqual(mnemonics(listing), mnemonics(asm)) + + def test_the_three_tables_agree(self): + """The .asm header, check.py's PIXEL_BITS and scripts/run_gpu_tests.py state the same four words.""" + import sys + sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) + import check + with open(os.path.join(ROOT, "scripts", "run_gpu_tests.py"), encoding="utf-8") as f: + m = re.search(r'"%s": \(([^)]*)\)' % NAME, f.read()) + self.assertEqual(check.PIXEL_BITS[NAME], header_words()) + self.assertEqual(tuple(int(x, 16) for x in m.group(1).split(",")), header_words()) + + def test_words(self): + """One round with EXEC off, none with EXEC on, whatever the push constants hold at the word's dword.""" + text = translate_fixture() + for wave in (64, 32): + for word in (0, 0x80000000, 0x03ff03ff): + with self.subTest(wave=wave, word=hex(word)): + self.assertEqual(mrt0(text, wave, word), {header_words()}) + + def test_without_the_seed_the_loop_runs_to_the_guard(self): + """The translator before the change: with 0 in the word, EXEC off ran the loop until the guard.""" + text = translate_fixture(seed=False) + for wave in (64, 32): + with self.subTest(wave=wave): + self.assertEqual(mrt0(text, wave), {(LIMIT,) + header_words()[1:]}) + + +class Rounds(unittest.TestCase): + """Rounds of the wait loop by which lanes are on at the ordered section's entry, in a wave64 program run as + 64-wide subgroups and as 32-wide ones (a device whose subgroups are narrower than the program's waves).""" + def test_every_lane_on_skips_the_loop(self): + for wave in (64, 32): + self.assertEqual(rounds(translate_program([]), wave), {0}) + + def test_a_lane_on_in_each_subgroup_skips_the_loop(self): + exec_lines = lanes_on("v_and_b32_e32 v1, 31, v1", "v_cmpx_gt_u32_e32 8, v1") # lanes 0-7 and 32-39 + for wave in (64, 32): + self.assertEqual(rounds(translate_program(exec_lines), wave), {0}) + + def test_every_lane_off_leaves_after_one_round(self): + for wave in (64, 32): + self.assertEqual(rounds(translate_program(["s_mov_b64 exec, 0"]), wave), {1}) + self.assertEqual(rounds(translate_program(["s_mov_b64 exec, 0"], seed=False), wave), {LIMIT}) + + def test_a_half_with_every_lane_off(self): + """Lanes 41-63 on: one 64-lane subgroup skips the loop. A 32-lane subgroup runs the low half (lanes 0-31, + all off), which falls into it and leaves after one round; before the seed it stayed until the guard.""" + exec_lines = lanes_on("v_cmpx_lt_u32_e32 40, v1") + self.assertEqual(rounds(translate_program(exec_lines), 64), {0}) + self.assertEqual(rounds(translate_program(exec_lines), 32), {1}) + self.assertEqual(rounds(translate_program(exec_lines, seed=False), 32), {LIMIT}) + + +class WhichSgpr(unittest.TestCase): + """pops_collision_sgpr: the source of the s_bfe_u32 that takes out the wave id, when its entry value is read.""" + def insns(self, *lines): + return [shader_ir.parse_line("\t" + ln) for ln in lines] + + def test_the_wave_id_extract_names_the_sgpr(self): + insns = self.insns("s_bfe_u32 s2, s18, 0xa0000", "s_bfe_u32 s5, s18, 0xa0010") + self.assertEqual(rdna2spirv.pops_collision_sgpr(insns, {18}), 18) + + def test_a_written_sgpr_is_not_the_word(self): + insns = self.insns("s_mov_b32 s18, 7", "s_bfe_u32 s5, s18, 0xa0010") + self.assertIsNone(rdna2spirv.pops_collision_sgpr(insns, set())) + + def test_another_field_is_not_the_wave_id(self): + insns = self.insns("s_bfe_u32 s2, s18, 0xa0000", "s_bfe_u32 s1, s18, 0x2001c") + self.assertIsNone(rdna2spirv.pops_collision_sgpr(insns, {18})) + + def test_the_seed_needs_an_ordered_section(self): + """The same extract in a program that never reads src_pops_exiting_wave_id gets no seed.""" + text = support.translate_lines("ps_no_pops", ["s_bfe_u32 s5, s18, 0xa0010", "v_mov_b32_e32 v4, s5", + "exp mrt0 v4, v4, v4, v4 done vm", "s_endpgm"]) + self.assertNotIn("%pops_word", text) + self.assertIn("%pops_word", translate_fixture()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index bf51eabc61..799031b72b 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -216,6 +216,34 @@ def user_data_dword(stage, sgpr): return None return sgpr - (MS_ROOT_SGPR - GRAPHICS_ROOT_DWORD) + +# POPS: the hardware gives a pixel shader with an ordered section its collision word in the SGPR after its user +# SGPRs and the primitive mask (Mesa's pops_collision_wave_id argument, GFX9-10.3): the collision wave id in bits +# 0-9, this wave's id in bits 16-25, the overlap flag in bit 31. The program takes the wave id out with s_bfe_u32 +# and this field (offset 16, width 10). +POPS_WAVE_ID_FIELD = 0x000A0010 +# What the translator puts in that SGPR at entry: no overlap, wave id 1, collision id 0. The program's wait loop +# leaves once wave_id + ~collision_id is below src_pops_exiting_wave_id + ~collision_id, unsigned. With the exiting +# id read as 0 (Gen.src_u) that is 0 < 0xFFFFFFFF, true at the first test. A word with wave id == collision id +# (0, what the push constants usually hold) gives 0xFFFFFFFF < 0xFFFFFFFF, never true: a wave that reaches the loop +# runs it to the loop guard. The overlap test before the loop skips it whenever a lane is on, so only a subgroup +# with EXEC all off there entered it. +POPS_COLLISION_SEED = 1 << 16 + + +def pops_collision_sgpr(insns, entry_reads): + """The SGPR a pixel shader's POPS collision word arrives in: the source of the s_bfe_u32 that takes out the + word's wave id (POPS_WAVE_ID_FIELD), when the program reads that SGPR's entry value (`entry_reads`, from + shader_meta's user_sgpr_reads). None when no such read is found: the word is then left as the push constants + give it, as before.""" + for ins in insns: + a = ins["args"] + if (base_op(ins["op"]) == "s_bfe_u32" and len(a) == 3 and a[1]["k"] == "sgpr" and a[1].get("n", 1) == 1 + and a[2]["k"] == "imm" and a[2]["v"] & 0xFFFFFFFF == POPS_WAVE_ID_FIELD + and a[1]["r"] in entry_reads): + return a[1]["r"] + return None + # v_pipeflush (GFX10 VOP1) only flushes the VALU pipeline: no register, memory or EXEC effect to translate. # s_icache_inv invalidates the instruction cache; s_ttracedata / s_ttracedata_imm send thread-trace data; # s_code_end pads the end of a code object; s_version records the ISA version. None of them has a register, memory, @@ -332,6 +360,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.uses_minlod = False self.uses_img_offset = False self.uses_pops = False + self.pops_word_sgpr = None # PS: the SGPR the POPS collision word arrives in (pops_collision_sgpr) self.round_mode = False # the program writes MODE.FP_ROUND[3:2] (f16/f64 rounding): kept in %mode_r16 self.uses_fhalf = False # %fhalf_g (0.5) constant self.uses_f64 = False @@ -532,7 +561,8 @@ def src_u(self, a): elif k == "special" and a["t"] == "src_pops_exiting_wave_id": # POPS (primitive-ordered pixel shading): the hardware wait loop compares this against the # collision word. Ordering comes from fragment-shader interlock around the whole shader instead - # (see assemble), so the id reads as 0 and the runtime puts 0 (no collision) in the collision SGPR. + # (see assemble), so the id reads as 0 and the collision word is seeded at entry with + # POPS_COLLISION_SEED, which ends the wait loop at its first test. v = self.cu(0) self.uses_pops = True elif k == "imm": @@ -5544,6 +5574,13 @@ def bar_counts_in_lds(self, lds_used=None): used = self.uses_lds if lds_used is None else lds_used return self.bar_rounds and used and 4 * self.lds_dwords + 12 > 16384 + def note_pops_word(self, insns): + """PS: the SGPR the POPS collision word arrives in (pops_collision_sgpr), seeded at entry. Called once + build_meta, whose user_sgpr_reads says which entry values the program reads, is known.""" + if self.stage == "ps": + reads = {r["sgpr"] for r in (self.build_meta or {}).get("user_sgpr_reads", ())} + self.pops_word_sgpr = pops_collision_sgpr(insns, reads) + def fit_shared_memory(self): """SHADER-309: a compute shader's Workgroup memory, the LDS array plus %x_buf, must fit in MAX_SHARED_BYTES (#1721: RADV dies on a module 4 bytes over 64 KiB; the device's own limit is the runtime's check). Called before any code is generated. The LDS array is a @@ -15825,6 +15862,8 @@ def assemble(gen): iface += ["%frag_coord"] + (["%front_facing"] if "front" in gen.frag_inputs.values() else []) + (["%bary"] if bary else []) for i in range(USER_SGPRS): # index constants for the user-data copy at entry gen.cu(i) + if gen.uses_pops and gen.pops_word_sgpr is not None: + gen.cu(POPS_COLLISION_SEED) # SPIR-V module layout: every OpCapability, then every OpExtension, then imports. caps = ["Shader"] + (["Int64", "PhysicalStorageBufferAddresses"] if psb else []) + \ (["RuntimeDescriptorArray"] if tex else []) + (["GroupNonUniform", "GroupNonUniformShuffle"] if sg else []) + \ @@ -16413,6 +16452,11 @@ def assemble(gen): f"%ud{i} = OpLoad %uint %ud{i}p", f"%ud{i}s = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(i)}", f"OpStore %ud{i}s %ud{i}"] + if gen.uses_pops and gen.pops_word_sgpr is not None: + # The POPS collision word is the hardware's, not user data: whatever the push constants hold at its dword + # (often 0, wave id == collision id) would keep a wave that enters the wait loop in it until the loop guard. + fn += [f"%pops_word = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(gen.pops_word_sgpr)}", + f"OpStore %pops_word {gen.cu(POPS_COLLISION_SEED)}"] if vs: # The hardware's VS input VGPRs are zero-based: v0 is the vertex id without the draw's base vertex and v3 # the instance id without its first instance (Mesa: ac.vertex_id = load_vertex_id_zero_base, the base in @@ -18333,6 +18377,7 @@ def translate(path): halves_analysis(g, [insns], [[]]) g.build_meta = _shader_meta.collect(path, info["name"], [insns], [[]], user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) + g.note_pops_word(insns) g.fit_shared_memory() end = next((k for k, ins in enumerate(insns) if base_op(ins["op"]) == "s_endpgm"), len(insns)) g.exec_changes = any(g.may_write_exec(ins) for ins in insns[:end]) @@ -18403,6 +18448,7 @@ def target(ins): halves_analysis(g, blocks, succ) g.build_meta = _shader_meta.collect(path, info["name"], blocks, succ, user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) + g.note_pops_word(insns) g.bar_rounds = needs_barrier_rounds(g, blocks, succ) folds, fold_chain, absorbed = {}, {}, set()