diff --git a/docs/design.md b/docs/design.md index 6a82596ebf..beee7d671d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -318,6 +318,7 @@ How the generated SPIR-V expects the runtime to work: | Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 \|\| M > DATA) ? DATA : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** \|\| M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** | | `global_atomic_csub`, `buffer_atomic_csub` (GFX10.3) | `tmp = M; M = (DATA > tmp) ? 0 : tmp - DATA`, unsigned: a subtract clamped at 0 that never wraps; with `glc` the old M comes back. Measured on gfx1036 by @Vonsek (#3193): 162/162 (memory, data) pairs over both forms. Same `OpAtomicCompareExchange` loop as `inc`/`dec` (`Gen.atomic_inc_dec_cas`), so exact under contention; operands, inactive lanes, buffer bounds and `glc` as `inc`/`dec`. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_atomic_csub.py` (a 9×9 value grid, no `glc`, buffer bounds, 32 lanes on one dword against 32 sequential subtracts, seeded values). The translation is not GPU-verified. | | Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88) and, with the same eight words, on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel), so the `vdst` preservation, the sign/zero extension, the ushort load across a dword and the element-size end check are GPU-checked on AMD too. `tools/hw_oracle` was not used for this; the Vulkan path above is what the translator runs. Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** Measured on an AMD Radeon RX 7900 XTX (`gfx1100`, driver 26.10.1) by running the instructions as a raw compute kernel (`tools/hw_oracle`, wave32, seeded synthetic bytes): the four loads zero-/sign-extend at byte offsets 0..7, the ushort at byte offset 3 merges byte 0 of the next dword, and with `NUM_RECORDS` = 8 the end check uses the element size (a ubyte at 7 reads where one at 8 returns 0, a ushort at 6 reads 0x5eee where one at 7 returns 0, an sshort at 7 returns 0 where an sbyte at 7 reads). `buffer_load_format_x` with `FORMAT` code 5 and `tbuffer_load_format_x format:[BUF_FMT_8_UINT]` return that byte zero-extended with the same 1-byte end check (at `NUM_RECORDS` 8, offset 7 reads 0x5e and 8 returns 0), and a V# whose `DST_SEL`s are 1/2/3/4 returns the integer 1 in all four components, not the fetched byte. The inactive-lane clause rests on the NVIDIA run. **Not GPU-verified.** | +| MUBUF loads to LDS (`lds` modifier) | `buffer_load_dword`, `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` with `lds` fetch into LDS instead of a VGPR (RDNA2 ISA 8.1.9 "Memory Buffer Load to LDS": only these five forms; `tfe` is illegal with `lds`, `buffer_load_dwordxN` and `buffer_load_format_*` stay refused). The LDS address is `LDS_BASE + M0[15:0] + inst_offset + TIDinWave*4` bytes: `M0[15:0]` is a byte offset, `inst_offset` the `offset:N` byte offset, and `TIDinWave` is added on the LDS path even when the V#'s ADD_TID_ENABLE is clear (the ISA figure; the VDATA field names the M#, only M0 exists, and is ignored). The buffer read is `buffer_address`'s with the element size (4 or 1/2 bytes), so an out-of-range read supplies 0, which the lane writes to LDS; sub-dword loads store the zero/sign-extended dword. The write runs in active lanes only and is dropped outside the wave's LDS allocation (`lds_access` bound = RSRC2 LDS_SIZE for CS). CS/MS only. The python decoder prints all four operands (VDATA first); llvm-mc omits VDATA on the `lds` forms, so a three-operand listing is read as vaddr, srsrc, soffset. CPU-checked by `tests/semantic/test_buffer_load_lds.py` (per-lane slots, `offset:` and M0[15:0], the 3-operand form, extensions, OOB -> 0, inactive lanes, the LDS bound) and GPU-checked by `runtime/test/shaders/cs_buf_lds.asm` in `scripts/run_gpu_tests.py` (buffer_load_dword `lds` fills LDS, `s_barrier`, `ds_read_b32` reads it back, `buffer_store` to the output). **Not GPU-verified** until that run reports. | | 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. GPU-checked by `runtime/test/shaders/cs_global_mem_ext.asm` for two of the ten ops (one lane, `saddr` addressing, on a Radeon 610M (gfx1036, RADV, Mesa 26.2.6) and an RTX 4070 Ti (NVIDIA 620.70.06), Linux): `global_store_short` at byte 3 of a dword changes only its two bytes, across both dwords, and `global_load_sbyte_d16_hi` sign-extends a byte into the high half of `vdst` and keeps the low half. **Not GPU-verified:** the other eight ops and an inactive lane. | | Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). | | Pipeline-library scalar operands | A scalar load may use VCC as a 64-bit pointer. In wave32 programs using that operand, scalar pair moves and XORs preserve both address words. Read its low and high data words, gathering a native wave's mask bits when a half is mask-valued. An emulated wave64 mask-valued pointer is refused. Where LLVM rejects a scalar, image or buffer tuple ending in VCC, recover the tuple from its original bytes before following branches. Hand-built memory and decoder cases in `test_library_compute_forms.py` and `test_vcc_tuple_fallback.py`. | diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 987a4eb530..0ba66a7cdc 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -110,7 +110,7 @@ def not_found_message(build, missing): "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", - "cs_w32_exec_computed") + "cs_w32_exec_computed", "cs_buf_lds") # 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. They run with # 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may @@ -118,7 +118,7 @@ def not_found_message(build, missing): WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi", - "cs_w32_exec_computed") + "cs_w32_exec_computed", "cs_buf_lds") CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), @@ -212,7 +212,12 @@ def not_found_message(build, missing): ("cs_barrier_loop", [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE]), # SHADER-21 part 2: a mask copied to a VGPR with v_mov_b32 respects EXEC (inactive lanes keep the old VGPR) ("cs_mask_vgpr_exec", [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF])] + 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF]), + # MUBUF loads with `lds` (RDNA2 ISA 8.1.9): LDS[64+4t] = 0x5EED0000+t, [192+4t] = 0x80+t, + # [320+4t] = sign-extended 0x80+t; the last word of each lane's four is lane t^1's dword slot. + # Only lanes 0-1 store, so the console dump's out[0..7] is the whole check (cs_buf_lds.asm header) + ("cs_buf_lds", [0x5EED0000, 0x00000080, 0xFFFFFF80, 0x5EED0001, + 0x5EED0001, 0x00000081, 0xFFFFFF81, 0x5EED0000])] # 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_buf_lds.asm b/runtime/test/shaders/cs_buf_lds.asm new file mode 100644 index 0000000000..2fa8c8bfac --- /dev/null +++ b/runtime/test/shaders/cs_buf_lds.asm @@ -0,0 +1,53 @@ +; MUBUF loads with the `lds` modifier (RDNA2 ISA 8.1.9 "Memory Buffer Load to LDS"; docs/design.md). Lane t of the +; 32-thread group seeds heap dword t at 0x400 + 4t with 0x5EED0000 + t and byte 0x80 + t at 0x480 + t, then: +; m0 = 64: buffer_load_dword v1, s[0:3], s8 offen lds -> LDS[64 + 4t] = 0x5EED0000 + t +; m0 = 192: buffer_load_ubyte v1, s[0:3], s8 offen lds -> LDS[192 + 4t] = 0x00000080 + t (zero-extended) +; m0 = 320: buffer_load_sbyte v1, s[0:3], s8 offen lds -> LDS[320 + 4t] = 0xFFFFFF80 + t (sign-extended) +; (s8 = 0x400 is the SOFFSET; the ubyte/sbyte vaddr adds 0x80 so the address is 0x480 + t. LDS_ADDR = M0[15:0] + +; TIDinWave*4; TIDinWave is added on the LDS path even though the V#'s ADD_TID_ENABLE is clear.) After +; s_waitcnt + s_barrier each lane ds_read_b32 its own three slots and lane t^1's dword slot back. Lanes 0 and 1 +; then store four words each through the output V# s[0:3] (EXEC is cut to them; the console dump judges out[0..7]): +; out[0..3] = lane 0: 0x5EED0000, 0x00000080, 0xFFFFFF80, 0x5EED0001 (lane 1's slot) +; out[4..7] = lane 1: 0x5EED0001, 0x00000081, 0xFFFFFF81, 0x5EED0000 (lane 0's slot) +; group: 32,1,1 +; Run: vk_compute_test cs_buf_lds.spv 1 dump -> out[0..7] = 0x5EED0000 0x80 0xFFFFFF80 0x5EED0001 0x5EED0001 0x81 0xFFFFFF81 0x5EED0000 +; mattr: +wavefrontsize32,-wavefrontsize64 +v_lshlrev_b32_e32 v10, 2, v0 +v_add_nc_u32_e32 v10, 0x400, v10 +v_add_nc_u32_e32 v11, 0x5eed0000, v0 +buffer_store_dword v11, v10, s[0:3], 0 offen +v_add_nc_u32_e32 v12, 0x480, v0 +v_add_nc_u32_e32 v13, 0x80, v0 +buffer_store_byte v13, v12, s[0:3], 0 offen +s_waitcnt vmcnt(0) +s_mov_b32 s8, 0x400 +v_lshlrev_b32_e32 v1, 2, v0 +s_mov_b32 m0, 64 +buffer_load_dword v1, s[0:3], s8 offen lds +v_add_nc_u32_e32 v1, 0x80, v0 +s_mov_b32 m0, 192 +buffer_load_ubyte v1, s[0:3], s8 offen lds +s_mov_b32 m0, 320 +buffer_load_sbyte v1, s[0:3], s8 offen lds +s_waitcnt vmcnt(0) +s_barrier +v_lshlrev_b32_e32 v20, 2, v0 +v_add_nc_u32_e32 v21, 64, v20 +ds_read_b32 v22, v21 +v_add_nc_u32_e32 v23, 192, v20 +ds_read_b32 v24, v23 +v_add_nc_u32_e32 v25, 320, v20 +ds_read_b32 v26, v25 +v_xor_b32_e32 v27, 1, v0 +v_lshlrev_b32_e32 v27, 2, v27 +v_add_nc_u32_e32 v27, 64, v27 +ds_read_b32 v28, v27 +s_waitcnt lgkmcnt(0) +v_lshrrev_b32_e32 v31, 1, v0 +v_cmpx_eq_u32_e32 0, v31 +v_lshlrev_b32_e32 v30, 4, v0 +buffer_store_dword v22, v30, s[0:3], 0 offen +buffer_store_dword v24, v30, s[0:3], 0 offen offset:4 +buffer_store_dword v26, v30, s[0:3], 0 offen offset:8 +buffer_store_dword v28, v30, s[0:3], 0 offen offset:12 +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 60e9687830..55f7502dc3 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -1213,7 +1213,7 @@ def run_suite(a, work: str) -> int: "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", - "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): + "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed", "cs_buf_lds"): cs_dump_wants = { "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone @@ -1332,6 +1332,10 @@ def run_suite(a, work: str) -> int: # inactive lanes keep the old VGPR (cs_mask_vgpr_exec.asm) "cs_mask_vgpr_exec": [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF], + # MUBUF loads with `lds` (RDNA2 ISA 8.1.9, cs_buf_lds.asm): only lanes 0-1 store, four words + # each; the last word of a lane's four is lane t^1's dword slot + "cs_buf_lds": [0x5EED0000, 0x00000080, 0xFFFFFF80, 0x5EED0001, + 0x5EED0001, 0x00000081, 0xFFFFFF81, 0x5EED0000], } want = cs_dump_wants[name] # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / @@ -1354,7 +1358,7 @@ def run_suite(a, work: str) -> int: "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_w32_andn2_exec", - "cs_w32_exec_computed") and not emulated and not partial + "cs_w32_exec_computed", "cs_buf_lds") and not emulated and not partial if partial: cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) diff --git a/tests/semantic/test_buffer_load_lds.py b/tests/semantic/test_buffer_load_lds.py new file mode 100644 index 0000000000..6c91804ed8 --- /dev/null +++ b/tests/semantic/test_buffer_load_lds.py @@ -0,0 +1,215 @@ +"""Semantic tests for MUBUF loads with the `lds` modifier (RDNA2 ISA 8.1.9 "Memory Buffer Load to LDS"). + +Covers buffer_load_dword / buffer_load_{u,s}byte / buffer_load_{u,s}hort with `lds`: the fetched value is +written to LDS at LDS_BASE + M0[15:0] + inst_offset + TIDinWave*4 (bytes) instead of a VGPR, sub-dword loads +store the zero/sign-extended dword, an out-of-range buffer read writes 0, inactive lanes write nothing, and an +address outside the wave's LDS allocation drops the write. The three-operand llvm-mc spelling (no VDATA) and +the rejected forms (dwordxN, tfe, format loads) are checked too. + +Standard library only; no GPU, no LLVM, no game files. +""" +import struct +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from support import rdna2spirv, translate_lines # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +# RSRC2 0x40088: 4 user SGPRs, workgroup id in s4, LDS_SIZE = 8 x 512 bytes = 4 KiB (1024 dwords). +FSSM = bytearray(0x148) +struct.pack_into(" OUT + lane*4 + slot*4 (slot a Python int).""" + return ["v_lshlrev_b32_e32 v30, 2, v0", + f"v_add_nc_u32_e32 v30, {OUT + slot * 4:#x}, v30", + f"global_store_dword v30, {reg}, s[0:1]"] + + +def read_lds(byte_vreg, out_reg): + """ds_read_b32 the dword at VGPR byte address `byte_vreg` into out_reg.""" + return [f"ds_read_b32 {out_reg}, {byte_vreg}", "s_waitcnt lgkmcnt(0)"] + + +def lane_slot(m0, extra=0): + """VGPR v20 = m0 + lane*4 + extra: this lane's LDS dword address for a load lds with offset:extra.""" + return [f"v_lshlrev_b32_e32 v20, 2, v0", + f"v_add_nc_u32_e32 v20, {m0 + extra:#x}, v20"] + + +def run(body, memory=None, nlanes=8): + spv = translate_lines("cs_buflds", list(body) + ["s_endpgm"], fssm=FSSM) + mem = dict(MEMORY if memory is None else memory) + si.run_workgroup(spv, nlanes, 32, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=[0] * 36, memory=mem) + return mem + + +class BufferLoadLdsTests(unittest.TestCase): + def test_dword_writes_lds_per_lane(self): + # m0 = 64: lane i's load of buffer dword i lands at LDS byte 64 + 4*i; ds_read_addtid reads it back. + body = vsharp() + [ + "v_lshlrev_b32_e32 v1, 2, v0", # v1 = lane * 4: the buffer byte offset + "s_mov_b32 m0, 64", + "buffer_load_dword v9, v1, s[4:7], 0 offen lds", + "s_waitcnt vmcnt(0)", + "s_barrier", + "ds_read_addtid_b32 v2 offset:0", # LDS[64 + lane*4] + "s_waitcnt lgkmcnt(0)", + ] + store_out("v2", 0) + mem = run(body) + for lane in range(8): + self.assertEqual(mem.get(OUT + lane * 4), MEMORY[BASE + lane * 4], f"lane {lane}") + + def test_inst_offset_and_m0_high_bits(self): + # offset:16 adds 16 to both the buffer and the LDS address; M0's high bits are ignored. + body = vsharp() + [ + "v_lshlrev_b32_e32 v1, 2, v0", + "s_mov_b32 m0, 0x12340040", # M0[15:0] = 0x40 + "buffer_load_dword v9, v1, s[4:7], 0 offen offset:16 lds", + "s_waitcnt vmcnt(0)", + "s_barrier", + ] + lane_slot(0x40, 16) + read_lds("v20", "v2") + store_out("v2", 1) + mem = run(body) + for lane in range(8): + self.assertEqual(mem.get(OUT + 4 + lane * 4), MEMORY[BASE + 16 + lane * 4], f"lane {lane}") + + def test_llvm_mc_three_operand_form(self): + # llvm-mc prints no VDATA operand for the lds forms: vaddr, srsrc, soffset. + body = vsharp() + [ + "v_lshlrev_b32_e32 v1, 2, v0", + "s_mov_b32 m0, 64", + "buffer_load_dword v1, s[4:7], 0 offen lds", + "s_waitcnt vmcnt(0)", + "s_barrier", + ] + lane_slot(64) + read_lds("v20", "v2") + store_out("v2", 2) + mem = run(body) + for lane in range(8): + self.assertEqual(mem.get(OUT + 8 + lane * 4), MEMORY[BASE + lane * 4], f"lane {lane}") + + def test_subdword_loads_store_extended_dwords(self): + # Byte offset 5 of the input dword: ubyte 0x45, sbyte 0x45; ushort at 6: 0x4746, sshort positive. + cases = [("buffer_load_ubyte", 5, 0x45), ("buffer_load_sbyte", 5, 0x45), + ("buffer_load_ushort", 6, 0x4746), ("buffer_load_sshort", 6, 0x4746)] + for slot, (op, off, want) in enumerate(cases): + with self.subTest(op=op): + body = vsharp() + [ + f"v_mov_b32_e32 v1, {off}", + "s_mov_b32 m0, 64", + f"{op} v9, v1, s[4:7], 0 offen lds", + "s_waitcnt vmcnt(0)", + "s_barrier", + ] + lane_slot(64) + read_lds("v20", "v2") + store_out("v2", slot) + mem = run(body, nlanes=1) + self.assertEqual(mem.get(OUT + slot * 4), want) + + def test_subdword_sign_extension(self): + # BASE dword = 0x0145807F (bytes 7F 80 45 01), BASE+4 = 0x123480FF (bytes FF 80 34 12). + mem_in = dict(MEMORY) + mem_in[BASE] = 0x0145807F + mem_in[BASE + 4] = 0x123480FF + cases = [("buffer_load_ubyte", 1, 0x80), ("buffer_load_sbyte", 1, 0xFFFFFF80), + ("buffer_load_ushort", 1, 0x4580), ("buffer_load_sshort", 1, 0x4580), + ("buffer_load_ushort", 4, 0x80FF), ("buffer_load_sshort", 4, 0xFFFF80FF), + ("buffer_load_ubyte", 4, 0xFF), ("buffer_load_sbyte", 4, 0xFFFFFFFF)] + for slot, (op, off, want) in enumerate(cases): + with self.subTest(op=op, off=off): + body = vsharp() + [ + f"v_mov_b32_e32 v1, {off}", + "s_mov_b32 m0, 64", + f"{op} v9, v1, s[4:7], 0 offen lds", + "s_waitcnt vmcnt(0)", + "s_barrier", + ] + lane_slot(64) + read_lds("v20", "v2") + store_out("v2", slot) + mem = run(body, memory=mem_in, nlanes=1) + self.assertEqual(mem.get(OUT + slot * 4), want) + + def test_out_of_range_buffer_read_writes_zero(self): + # num_records 8: a dword load at byte offset 8 ends at 12 > 8 -> the lane writes 0 to LDS. + body = vsharp(num_records=8) + [ + "v_mov_b32_e32 v1, 8", + "s_mov_b32 m0, 64", + "buffer_load_dword v9, v1, s[4:7], 0 offen lds", + "s_waitcnt vmcnt(0)", + "s_barrier", + ] + lane_slot(64) + read_lds("v20", "v2") + store_out("v2", 0) + mem = run(body, nlanes=1) + self.assertEqual(mem.get(OUT), 0) + + def test_inactive_lane_writes_nothing(self): + # Lane 0 only is active for the load; lane 1's LDS slot keeps the sentinel ds_write left. + body = vsharp() + [ + # sentinel 0xdeadbeef at every lane's slot (m0 = 64) + "v_lshlrev_b32_e32 v10, 2, v0", + "v_add_nc_u32_e32 v10, 64, v10", + "v_mov_b32_e32 v11, 0xdeadbeef", + "ds_write_b32 v10, v11", + "s_waitcnt lgkmcnt(0)", + "v_lshlrev_b32_e32 v1, 2, v0", + "s_mov_b32 m0, 64", + "v_cmp_eq_u32_e32 vcc_lo, 0, v0", # only lane 0 passes + "s_and_saveexec_b32 s8, vcc_lo", + "buffer_load_dword v9, v1, s[4:7], 0 offen lds", + "s_mov_b32 exec_lo, s8", + "s_waitcnt vmcnt(0)", + "s_barrier", + ] + lane_slot(64) + read_lds("v20", "v2") + store_out("v2", 0) + mem = run(body, nlanes=2) + self.assertEqual(mem.get(OUT), MEMORY[BASE]) # lane 0 loaded + self.assertEqual(mem.get(OUT + 4), 0xDEADBEEF) # lane 1 kept the sentinel + + def test_lds_address_outside_allocation_is_dropped(self): + # M0[15:0] = 0xFFF0: every lane's LDS dword index is past the 4 KiB allocation, so the write is + # dropped and cannot wrap onto dword 1020 (byte 4080), which holds a sentinel. + body = vsharp() + [ + "v_mov_b32_e32 v10, 4080", + "v_mov_b32_e32 v11, 0x12345678", + "ds_write_b32 v10, v11", + "s_waitcnt lgkmcnt(0)", + "v_lshlrev_b32_e32 v1, 2, v0", + "s_mov_b32 m0, 0xFFF0", + "buffer_load_dword v9, v1, s[4:7], 0 offen lds", + "s_waitcnt vmcnt(0)", + "s_barrier", + "v_mov_b32_e32 v20, 4080", + ] + read_lds("v20", "v2") + store_out("v2", 0) + mem = run(body, nlanes=1) + self.assertEqual(mem.get(OUT), 0x12345678) + + def test_rejected_forms(self): + for line in ("buffer_load_dwordx2 v9, v1, s[4:7], 0 offen lds", + "buffer_load_dword v9, v1, s[4:7], 0 offen tfe lds", + "buffer_load_format_x v9, v1, s[4:7], 0 offen lds", + "buffer_load_ubyte v9, v1, s[4:7], 0 offen tfe lds"): + with self.subTest(line=line): + with self.assertRaises(rdna2spirv.Unsupported): + translate_lines("cs_buflds", vsharp() + ["v_mov_b32_e32 v1, 0", "s_mov_b32 m0, 64", line, + "s_endpgm"], fssm=FSSM) + + def test_spirv_stores_to_workgroup_memory(self): + spv = translate_lines("cs_buflds", vsharp() + [ + "v_mov_b32_e32 v1, 0", "s_mov_b32 m0, 64", + "buffer_load_dword v9, v1, s[4:7], 0 offen lds", "s_endpgm"], fssm=FSSM) + self.assertIn("%lds", spv) + self.assertIn("Workgroup", spv) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_buffer_load_sub.py b/tests/semantic/test_buffer_load_sub.py index 6808d68b71..2391fb4137 100644 --- a/tests/semantic/test_buffer_load_sub.py +++ b/tests/semantic/test_buffer_load_sub.py @@ -156,8 +156,7 @@ def test_inactive_lane_preserves_vdst(self): self.assertEqual(mem.get(OUT + 4), 0xCAFEBABE) def test_rejected_sub_dword_forms(self): - for line in ("buffer_load_ushort v5, v1, s[4:7], 0 offen lds", - "buffer_load_ushort v5, v1, s[4:7], 0 offen tfe", + for line in ("buffer_load_ushort v5, v1, s[4:7], 0 offen tfe", "buffer_load_ushort v5, v1, s[4:7], 0 offen d16"): with self.subTest(line=line): with self.assertRaises(rdna2spirv.Unsupported): diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index b10de728ec..74a3c33dd9 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -2588,6 +2588,10 @@ def buffer_load(self, op, a, mods): Each dword is loaded only when it is in range per the V#'s OOB_SELECT (buffer_address; docs/design.md, Buffer bounds checking): for modes 0 and 3 dword i ends inside the stride / num_records, else it is 0 and memory is not read; modes 1 and 2 check the index / num_records once. Inactive lanes don't load.""" + if "lds" in mods: + if op != "buffer_load_dword": # ISA 8.1.9: the lds subset is dword, not dwordxN + raise Unsupported(op + " lds") + return self.buffer_load_lds(op, a, mods, 4, False) if any(m in mods for m in ("lds", "tfe")) or "format" in op: raise Unsupported(op + " form") n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) @@ -2640,7 +2644,10 @@ def buffer_load_sub(self, op, a, mods): """buffer_load_{u,s}byte / buffer_load_{u,s}short vD, vaddr, s[V#], soffset [offen|idxen] offset:N. Loads 1 or 2 bytes from V#.base + offsets, zero- or sign-extended to 32 bits. Out-of-bounds lanes (OOB_SELECT with element size 1 or 2) return 0 without reading memory; inactive lanes keep vD.""" - if any(m in mods for m in ("lds", "tfe", "d16")): + if "lds" in mods: + nbytes, signed = self.BUFFER_SUB[op] + return self.buffer_load_lds(op, a, mods, nbytes, signed) + if any(m in mods for m in ("tfe", "d16")): raise Unsupported(op + " form") nbytes, signed = self.BUFFER_SUB[op] vd = a[0] @@ -2655,6 +2662,16 @@ def buffer_load_sub(self, op, a, mods): self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") + val = self.buffer_sub_value(addr, step, nbytes, signed) + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + res = self.tmp() + self.emit(f"{res} = OpPhi %uint {val} {lbl_do} {self.cu(0)} {pre_label}") + self.dst(vd, res) + + def buffer_sub_value(self, addr, step, nbytes, signed): + """The uint id of the 1- or 2-byte value at the ulong address `addr` (buffer_load_sub's read, shared with + the lds forms), zero- or sign-extended to 32 bits. Emitted inside the caller's guarded block.""" alo, b3, b64, aligned, sh = (self.tmp() for _ in range(5)) self.emit(f"{alo} = OpUConvert %uint {addr}") self.emit(f"{b3} = OpBitwiseAnd %uint {alo} {self.cu(3)}") @@ -2681,11 +2698,64 @@ def buffer_load_sub(self, op, a, mods): self.emit(f"{crossed} = OpBitwiseOr %uint {lo_part} {hi_sh}") self.emit(f"{raw} = OpSelect %uint {cross} {crossed} {lo_part}") self.emit(f"{val} = {ext} %uint {raw} {self.cu(0)} {self.cu(16)}") + return val + + def buffer_load_lds(self, op, a, mods, nbytes, signed): + """buffer_load_{dword,ubyte,sbyte,ushort,sshort} ... lds (RDNA2 ISA 8.1.9 "Memory Buffer Load to LDS"): + the fetched data goes to LDS, not a VGPR. LDS_addr = LDS_BASE + M0[15:0] + inst_offset + TIDinWave*4 bytes + (the figure's formula; TIDinWave is added on the LDS path even when the V#'s ADD_TID_ENABLE is clear, and + inst_offset is the offset:N byte offset). The VDATA field names the M# (only M0 exists on RDNA2) and is + ignored. The buffer read is buffer_address's, bounds-checked the same way as the VGPR forms; an + out-of-range read supplies 0, which is what the lane writes to LDS. The LDS write runs in active lanes + only and is dropped outside the wave's LDS allocation (lds_access bound = RSRC2 LDS_SIZE for CS). The + python decoder prints all four operands (VDATA first); llvm-mc omits VDATA on the lds forms, so a + three-operand listing is vaddr, srsrc, soffset.""" + if self.stage not in ("cs", "ms") or "tfe" in mods: + raise Unsupported(op + " lds") + if len(a) == 3: + a = [None] + a + if len(a) != 4: + raise Unsupported(op + " operands") + self.uses_lds = True + addr, _, in_b, step = self.buffer_address(a, mods, elem=nbytes) + act = self.active_b() + cond = self.tmp() + self.emit(f"{cond} = OpLogicalAnd %bool {act} {in_b}") + lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" + pre = self.current_label_placeholder() + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") + self.emit(f"{lbl_do} = OpLabel") + if nbytes == 4: + ptr, host = self.tmp(), self.host_addr(addr) + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") + val = self.tmp() + self.emit(f"{val} = OpLoad %uint {self.buf_dword_ptr(ptr, host, step, 0)} Aligned 4") + else: + val = self.buffer_sub_value(addr, step, nbytes, signed) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") res = self.tmp() - self.emit(f"{res} = OpPhi %uint {val} {lbl_do} {self.cu(0)} {pre_label}") - self.dst(vd, res) + self.emit(f"{res} = OpPhi %uint {val} {lbl_do} {self.cu(0)} {pre}") # OOB read: 0, as the VGPR form gives + w_do, w_end = self.tmp() + "_wdo", self.tmp() + "_wend" + self.emit(f"OpSelectionMerge {w_end} None") + self.emit(f"OpBranchConditional {act} {w_do} {w_end}") + self.emit(f"{w_do} = OpLabel") + m0, off, lane_b, laddr = (self.tmp() for _ in range(4)) + self.emit(f"{m0} = OpLoad %uint %m0") + self.emit(f"{off} = OpBitwiseAnd %uint {m0} {self.cu(0xFFFF)}") + inst = next((int(m.split(":", 1)[1], 0) for m in mods if m.startswith("offset:")), 0) + if inst: + self.emit(f"{off} = OpIAdd %uint {off} {self.cu(inst)}") + self.emit(f"{lane_b} = OpShiftLeftLogical %uint {self.wave_lane()} {self.cu(2)}") + self.emit(f"{laddr} = OpIAdd %uint {off} {lane_b}") + + def store(p): + self.emit(f"OpStore {p} {res} Volatile") # as lds_store + return None + self.lds_access(laddr, 0, store, self.lds_declared if self.stage == "cs" else None) + self.emit(f"OpBranch {w_end}") + self.emit(f"{w_end} = OpLabel") # GFX10 buffer formats (from Mesa src/amd/registers/gfx10-rsrc.json, GFX10_FORMAT): # code: (bytes, kind, component bit widths from bit 0)