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 1/3] 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): From 33c80b58bbbe78f4dc7aa0f87850047fe548ed36 Mon Sep 17 00:00:00 2001 From: Flyander <48117641+Flyander@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:45:04 +0100 Subject: [PATCH 2/3] fix(translator): query typed image store bounds --- docs/design.md | 2 +- runtime/test/vk_store_test.cpp | 26 +++++-- tests/semantic/test_image_store_bounds.py | 92 +++++++++++++++++------ tools/rdna2spirv.py | 39 ++++++---- 4 files changed, 112 insertions(+), 47 deletions(-) diff --git a/docs/design.md b/docs/design.md index 0eef406f19..856af4e1ec 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`. **`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. | +| 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 shader queries the selected float/uint/sint storage view and writes through that same view, then 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/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 5612a7119f..8a4243f60f 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp @@ -207,11 +207,12 @@ int main(int argc, char** argv) { CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); std::memcpy(tbp, table.data(), table.size() * 4); - const uint32_t W = 8; + const uint32_t W = 8, FLOAT_VIEW_MIPS = 4; VkImage img[3]; VkImageView view[3]; for (int k = 0; k < 3; k++) { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; + ii.mipLevels = k == 0 ? FLOAT_VIEW_MIPS : 1; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; @@ -226,6 +227,14 @@ int main(int argc, char** argv) { vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; CHECK(vkCreateImageView(dev, &vi, nullptr, &view[k])); } + // A 1x1 float-view fallback in the slots for integer images catches a bounds query through the wrong class. + VkImageView float_small_view; + { + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = img[0]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = vkf[0]; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, FLOAT_VIEW_MIPS - 1, 1, 0, 1}; + CHECK(vkCreateImageView(dev, &vi, nullptr, &float_small_view)); + } VkImage wide; VkImageView wide_view; { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; @@ -265,9 +274,9 @@ int main(int argc, char** argv) { // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays. // Five elements each: index 0 stands for the runtime's fallback, image k is at index k + 1 and the 16x4 image at // index 4. Binding 0 holds each image's view in its own format (typed image_load reads the uint and sint ones - // through integer aliases); every element of a storage array holds the image of its class, so all of them are - // valid descriptors. Bindings 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image - // and the volume, in every element. + // through integer aliases). The float storage array deliberately uses a 1x1 view at indices 2 and 3 while the + // corresponding uint/sint views remain 8x8; an integer image_store must query its selected typed view. Bindings + // 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image and the volume, in every element. constexpr uint32_t N = 5; VkDescriptorSetLayoutBinding b[8]{}; b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; @@ -307,7 +316,10 @@ int main(int argc, char** argv) { wr[1].dstBinding = 1; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = &smpi; wr[2].dstBinding = 2; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tbi; for (int k = 0; k < 3; k++) { - for (uint32_t e = 0; e < N; e++) dii[k][e] = {VK_NULL_HANDLE, view[k], VK_IMAGE_LAYOUT_GENERAL}; + for (uint32_t e = 0; e < N; e++) { + VkImageView storage_view = k == 0 && (e == 2 || e == 3) ? float_small_view : view[k]; + dii[k][e] = {VK_NULL_HANDLE, storage_view, VK_IMAGE_LAYOUT_GENERAL}; + } wr[3 + k].dstBinding = 8 + k; wr[3 + k].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; wr[3 + k].pImageInfo = dii[k]; wr[3 + k].descriptorCount = N; } @@ -387,7 +399,7 @@ int main(int argc, char** argv) { ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].srcQueueFamilyIndex = ib[k].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, k == 0 ? FLOAT_VIEW_MIPS : 1, 0, 1}; if (filled && k > 0) { // filled by a copy first ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; } diff --git a/tests/semantic/test_image_store_bounds.py b/tests/semantic/test_image_store_bounds.py index bf45c66fcf..75d7577dbf 100644 --- a/tests/semantic/test_image_store_bounds.py +++ b/tests/semantic/test_image_store_bounds.py @@ -38,7 +38,7 @@ def parse(spv): class ImageStoreBoundsTests(unittest.TestCase): - def test_every_write_is_behind_a_size_test(self): + def test_every_write_is_guarded_by_its_typed_view_size(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", @@ -47,29 +47,75 @@ def test_every_write_is_behind_a_size_test(self): 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 + writes = [a[0] for _r, o, a in lines if o == "OpImageWrite"] + self.assertEqual(len(writes), 3) # one for each typed storage view 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") + self.assertEqual(len(sizes), 3) # integer views may not share the float view's extent + + blocks, current = {}, None + for r, op, args in lines: + if op == "OpLabel": + current = r + blocks[current] = [] + elif current is not None: + blocks[current].append((r, op, args)) + + def dependencies(root): + seen, todo = set(), [root] + while todo: + value = todo.pop() + if value in seen: + continue + seen.add(value) + if value in defs: + todo.extend(arg for arg in defs[value][1] if arg.startswith("%")) + return seen + + matched_queries = set() + for image in writes: + self.assertEqual(defs[image][0], "OpLoad") + write_type, write_pointer = defs[image][1][:2] + self.assertEqual(defs[write_pointer][0], "OpAccessChain") + write_index = defs[write_pointer][1][-1] + matching = [] + for query in sizes: + query_image = defs[query][1][1] + self.assertEqual(defs[query_image][0], "OpLoad") + query_type, query_pointer = defs[query_image][1][:2] + if query_type == write_type: + self.assertEqual(defs[query_pointer][0], "OpAccessChain") + self.assertEqual(defs[query_pointer][1][-1], write_index) + matching.append(query) + self.assertEqual(len(matching), 1, "each write must query its own typed descriptor") + query = matching[0] + matched_queries.add(query) + + guarded = False + for i, (_r, op, args) in enumerate(lines): + if op != "OpBranchConditional" or query not in dependencies(args[0]): + continue + true_block, false_block = blocks.get(args[1], []), blocks.get(args[2], []) + if not any(o == "OpImageWrite" and a[0] == image for _d, o, a in true_block): + continue + self.assertFalse(any(o == "OpImageWrite" and a[0] == image for _d, o, a in false_block)) + self.assertIn("%active", dependencies(args[0])) + tests = [v for v in dependencies(args[0]) if v in defs and defs[v][0] == "OpULessThan"] + self.assertEqual(len(tests), n) + for ax in range(n): + if n == 1: + size_component = query + else: + extracts = [r for r, (o, a) in defs.items() + if o == "OpCompositeExtract" and a[1:] == [query, str(ax)]] + self.assertEqual(len(extracts), 1) + size_component = extracts[0] + self.assertTrue(any(defs[v][1][2] == size_component for v in tests), + f"axis {ax}: coordinate < typed-view size missing") + self.assertLess(next(j for j, (r, _o, _a) in enumerate(lines) if r == query), i) + guarded = True + break + self.assertTrue(guarded, "OpImageWrite is not guarded by its typed-view size") + self.assertEqual(matched_queries, set(sizes)) if __name__ == "__main__": diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 73a3245dae..ff5709c925 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -11383,30 +11383,37 @@ 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): ip, img = self.tmp(), self.tmp() self.emit(f"{ip} = OpAccessChain %_ptr_UC_stv{cls}_{di} %stv{cls}_{di} {idx}") self.emit(f"{img} = OpLoad %stimg{cls}_{di} {ip}") + # Other numeric-class bindings can hold a 1x1 fallback, so query the same typed view that receives + # this write rather than assuming the float view has its dimensions. + qs = self.tmp() + self.emit(f"{qs} = OpImageQuerySize {'%int' if nc == 1 else '%v2int' if nc == 2 else '%v3int'} {img}") + in_bounds = act + for ax in range(nc): + lt, both = self.tmp(), self.tmp() + if nc == 1: + c, z = coords[0], qs + else: + c, z = self.tmp(), self.tmp() + 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 {in_bounds} {lt}") + in_bounds = both + + store_do, store_end = self.tmp() + "_store", self.tmp() + "_store_end" + self.emit(f"OpSelectionMerge {store_end} None") + self.emit(f"OpBranchConditional {in_bounds} {store_do} {store_end}") + self.emit(f"{store_do} = OpLabel") self.emit(f"OpImageWrite {img} {iv} {texel}") + self.emit(f"OpBranch {store_end}") + self.emit(f"{store_end} = OpLabel") self.emit(f"OpSelectionMerge {L['end']} None") self.emit(f"OpBranchConditional {act} {L['do']} {L['end']}") From 1b7fc6c495b7cc1030bc9bd18473888898565a57 Mon Sep 17 00:00:00 2001 From: Flyander <48117641+Flyander@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:00:21 +0100 Subject: [PATCH 3/3] test(runtime): reuse 1x1 mip for image bounds fixture --- runtime/test/vk_store_test.cpp | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 8a4243f60f..d33b070043 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp @@ -207,12 +207,11 @@ int main(int argc, char** argv) { CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); std::memcpy(tbp, table.data(), table.size() * 4); - const uint32_t W = 8, FLOAT_VIEW_MIPS = 4; + const uint32_t W = 8; VkImage img[3]; VkImageView view[3]; for (int k = 0; k < 3; k++) { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; - ii.mipLevels = k == 0 ? FLOAT_VIEW_MIPS : 1; ii.arrayLayers = 1; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; @@ -227,20 +226,12 @@ int main(int argc, char** argv) { vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; CHECK(vkCreateImageView(dev, &vi, nullptr, &view[k])); } - // A 1x1 float-view fallback in the slots for integer images catches a bounds query through the wrong class. - VkImageView float_small_view; - { - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = img[0]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = vkf[0]; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, FLOAT_VIEW_MIPS - 1, 1, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &float_small_view)); - } VkImage wide; VkImageView wide_view; { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[0]; ii.extent = {WIDE_W, WIDE_H, 1}; ii.mipLevels = WIDE_MIPS; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; - ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT; CHECK(vkCreateImage(dev, &ii, nullptr, &wide)); VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, wide, &mr); VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; @@ -252,6 +243,14 @@ int main(int argc, char** argv) { vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, WIDE_MIPS, 0, 1}; CHECK(vkCreateImageView(dev, &vi, nullptr, &wide_view)); } + // A 1x1 float-view fallback in the slots for integer images catches a bounds query through the wrong class. + VkImageView float_small_view; + { + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = wide; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = vkf[0]; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, WIDE_MIPS - 1, 1, 0, 1}; + CHECK(vkCreateImageView(dev, &vi, nullptr, &float_small_view)); + } VkImage vol; VkImageView vol_view; { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; @@ -399,7 +398,7 @@ int main(int argc, char** argv) { ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].srcQueueFamilyIndex = ib[k].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, k == 0 ? FLOAT_VIEW_MIPS : 1, 0, 1}; + ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; if (filled && k > 0) { // filled by a copy first ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; }