From 5dd8051cb6dfef93b1191dcbb8e290f56314dfe3 Mon Sep 17 00:00:00 2001 From: Vonsek <45567075+Vonsek@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:47:56 +0100 Subject: [PATCH] fix(translator): drop image_store writes outside the image (EGEN-IMGSTORE-OOB) RDNA2 (gfx1036, tools/hw_oracle) leaves memory unchanged for an image_store at x/y past the edge, at -1 or at the row pitch. OpImageWrite out of range is undefined in Vulkan, so every write is now behind an unsigned coordinate < OpImageQuerySize test per axis (1D, 2D, 2D array, 3D). --- docs/design.md | 2 +- tests/semantic/test_image_store_bounds.py | 76 +++++++++++++++++++++++ tools/rdna2spirv.py | 17 +++++ 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 tests/semantic/test_image_store_bounds.py diff --git a/docs/design.md b/docs/design.md index d32503f1a8..0eef406f19 100644 --- a/docs/design.md +++ b/docs/design.md @@ -383,7 +383,7 @@ How the generated SPIR-V expects the runtime to work: | 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The synthetic translator tests check the four address registers and the RGBA32 format selection. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) | | Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. \| AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. | | Half-precision coordinates for LOD queries | For `image_get_lod a16` on 2D and 2D-array images, the low and high halves of the first address VGPR supply U and V. The array layer is excluded from `OpImageQueryLod`; the selected clamped and raw LOD outputs are f32. `tests/semantic/fixtures/get_lod_a16.asm` assembles for gfx1030 and checks the query operands and output components through `tests/test_image_load_typed.py`. [AMD RDNA2 ISA, MIMG](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) | -| Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off leaves memory alone: cmpswap is skipped, the others run with the operand that changes nothing. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (1) and the level count in VGPRs 0..3 (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). The translator still differs in the first three: it writes 1 for the 2D depth word and the full layer count for a 2D array, and `OpImageQuerySizeLod` past the last level is undefined. `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: resinfo's depth word on hardware (1 is what the T#'s DEPTH field says for a 2D image), the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. | +| Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off leaves memory alone: cmpswap is skipped, the others run with the operand that changes nothing. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (1) and the level count in VGPRs 0..3 (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). The translator still differs in the first three: it writes 1 for the 2D depth word and the full layer count for a 2D array, and `OpImageQuerySizeLod` past the last level is undefined. `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: resinfo's depth word on hardware (1 is what the T#'s DEPTH field says for a 2D image), the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. **`image_store` out of range** (EGEN-IMGSTORE-OOB): a store whose coordinate is outside the image (any axis, unsigned, so -1 is out; 1D, 2D, 2D array and 3D) is not performed: the translation tests `coordinate < OpImageQuerySize` per axis together with EXEC before the `OpImageWrite`, which is undefined out of range in Vulkan (the runtime does not enable robustImageAccess). Measured on gfx1036 (RDNA2, Windows driver 32.0.21045.16010) with `tools/hw_oracle`, a linear 4x4 R32_UINT T#: image_store at x = width, x = -1, y = height, y = -1, x = the row pitch and x = 1000 left every seeded word of the image, its row padding and the bytes after it unchanged (the in-range control stored). `image_load` out of range returned 0 on the same GPU for x = width, x = -1, y = height and x = pitch; the translator's `OpImageFetch`/`OpImageRead` path is not guarded yet. CPU-checked by `tests/semantic/test_image_store_bounds.py`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. | | Hand-written short assembler forms | `llvm-mc` accepts `v_add_co_ci_u32 vD, src0, src1` (also `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with the carry out and in left to VCC, and a modifier list shorter than the operands (`op_sel_hi:[0,0]`, `neg_lo:[1,0]` on a three-source op), whose missing entries are 0; it prints them as `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo` and `[0,0,0]`. The GPU runner assembles through `llvm-mc -show-encoding`, so it sees the printed form; `tests/semantic/regen_fixtures.py` copies the `.asm` text as written, so the translator takes the source spelling too (it used to raise `IndexError` for these: the carry forms, `v_pk_fma_f16`, `v_fma_mix_*`). A probe of 42,000 operand and modifier variations of 302 ALU mnemonics, in the source spelling and as `llvm-mc` prints them, found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_short_asm_forms.py`. | | SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. A byte or word destination with PRESERVE reads its incoming VGPR on first use. The synthetic `sdwa_bary_input.asm` checks this with two raw fragment weights, following the [LLVM SDWA destination rules](https://llvm.org/docs/AMDGPUModifierSyntax.html#dst-unused). VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. **Measured natively on RDNA2** (gfx1036 iGPU, `tools/hw_oracle`, the game's MODE): all 172 distinct SDWA forms of the 26,503 listings (79,307 instructions: opcode, operand kinds, sels, `sext`, neg/abs, `dst_unused`, omod), 12 operand words per source, 21,204 cases. 18,885 give the translator's word. The rest are: a 16-bit result with `dst_sel:DWORD`, where the hardware zeroes the high half and the translator keeps it (1,888, #2187); a NaN result, where the hardware keeps the input's sign and payload (826 counting those also in the first group, as in the f16 transcendentals row); `div:2` on -0, which gives +0 (1, as in the output-modifier rows); and 160 cases whose translation is undefined in SPIR-V (`FClamp`/`FDiv`/`Sqrt` on NaN, zero or negative operands). `tests/semantic/test_alu_sdwa_hw.py` replays 624 of the matching words, up to four per form. | | VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). | diff --git a/tests/semantic/test_image_store_bounds.py b/tests/semantic/test_image_store_bounds.py new file mode 100644 index 0000000000..bf45c66fcf --- /dev/null +++ b/tests/semantic/test_image_store_bounds.py @@ -0,0 +1,76 @@ +"""image_store with a texel coordinate outside the image: RDNA2 drops the write, so the translation must too. + +Measured natively on gfx1036 (RDNA2) with tools/hw_oracle on a linear 4x4 R32_UINT T#: image_store at x = width, x = -1, +y = height, y = -1, x = the row pitch and x = 1000 left every seeded word of the image, its row padding and the bytes +after it unchanged. An OpImageWrite outside the image is undefined in Vulkan (the runtime does not enable +robustImageAccess), so every write must sit behind a branch on "coordinate < OpImageQuerySize" per axis, unsigned so +that -1 is out too, together with the EXEC test. + +Standard library only; no GPU, no LLVM, no game files. +""" +import os +import re +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) + +from test_image_atomics_32 import check_cfg, translate_cs # noqa: E402 + +LINE = re.compile(r"^\s*(?:(%\w+) = )?(Op\w+)(.*)$") +DIMS = {"SQ_RSRC_IMG_1D": ("v4", 1), "SQ_RSRC_IMG_2D": ("v[4:5]", 2), + "SQ_RSRC_IMG_2D_ARRAY": ("v[4:6]", 3), "SQ_RSRC_IMG_3D": ("v[4:6]", 3)} + + +def parse(spv): + out, body = [], False + for raw in spv.splitlines(): + m = LINE.match(raw) + if not m: + continue + res, op, rest = m.groups() + body = body or op == "OpFunction" + if body: + out.append((res, op, rest.split())) + return out + + +class ImageStoreBoundsTests(unittest.TestCase): + def test_every_write_is_behind_a_size_test(self): + for dim, (addr, n) in DIMS.items(): + with self.subTest(dim=dim): + spv = translate_cs(["v_mov_b32_e32 v4, 1", "v_mov_b32_e32 v5, 2", "v_mov_b32_e32 v6, 3", + "v_mov_b32_e32 v8, 7", + f"image_store v8, {addr}, s[4:11] dmask:0x1 dim:{dim} unorm", "s_waitcnt vmcnt(0)"]) + check_cfg(spv) + lines = parse(spv) + defs = {r: (o, a) for r, o, a in lines if r} + writes = [i for i, (_r, o, _a) in enumerate(lines) if o == "OpImageWrite"] + self.assertEqual(len(writes), 3) # the sint, uint and float views + sizes = [r for r, (o, _a) in defs.items() if o == "OpImageQuerySize"] + self.assertEqual(len(sizes), 1, "no OpImageQuerySize before the writes") + # the outermost guard: the first conditional branch after the size query + q = next(i for i, (r, _o, _a) in enumerate(lines) if r == sizes[0]) + first = next(i for i in range(q, len(lines)) if lines[i][1] == "OpBranchConditional") + seen, todo = set(), [lines[first][2][0]] + while todo: + v = todo.pop() + if v in seen or v not in defs: + continue + seen.add(v) + todo += defs[v][1] + self.assertIn("%active", seen) + if n == 1: + tests = [v for v in seen if defs[v][0] == "OpULessThan" and defs[v][1][2] == sizes[0]] + self.assertTrue(tests, "1D: coordinate < size missing") + else: + for ax in range(n): + tests = [v for v in seen if defs[v][0] == "OpULessThan" + and defs[defs[v][1][2]] == ("OpCompositeExtract", ["%int", sizes[0], str(ax)])] + self.assertTrue(tests, f"axis {ax}: coordinate < size (unsigned) missing") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 001b98668c..73a3245dae 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -11383,6 +11383,23 @@ def image_store(self, a, mods, dim): self.emit(f"{v4u} = OpCompositeConstruct %v4uint_st {' '.join(uv)}") self.emit(f"{v4s} = OpCompositeConstruct %v4int_st {' '.join(sv)}") act = self.active_b() + # RDNA2 drops a store whose coordinate is outside the image (gfx1036, tools/hw_oracle: x = width, -1, y = height, + # -1, the row pitch and 1000 left every word unchanged); an out-of-range OpImageWrite is undefined in Vulkan. + self.uses_query = True + qp, qi, qs = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{qp} = OpAccessChain %_ptr_UC_stv0_{di} %stv0_{di} {idx}") + self.emit(f"{qi} = OpLoad %stimg0_{di} {qp}") + self.emit(f"{qs} = OpImageQuerySize {'%int' if nc == 1 else '%v2int' if nc == 2 else '%v3int'} {qi}") + for ax in range(nc): + c, z, lt, both = self.tmp(), self.tmp(), self.tmp(), self.tmp() + if nc == 1: + c, z = coords[0], qs + else: + self.emit(f"{c} = OpCompositeExtract %int {iv} {ax}") + self.emit(f"{z} = OpCompositeExtract %int {qs} {ax}") + self.emit(f"{lt} = OpULessThan %bool {c} {z}") + self.emit(f"{both} = OpLogicalAnd %bool {act} {lt}") + act = both L = {k: self.tmp() + "_" + k for k in ("do", "end", "s", "rest", "e2", "u", "f", "e3")} def write(cls, texel):