From 1b2720ba47531ac70cdeac93486b2cac8b63ff01 Mon Sep 17 00:00:00 2001 From: BubsMcgee Date: Wed, 25 Nov 2026 15:29:55 -0500 Subject: [PATCH] rdna2spirv: translate image_get_lod on a cube (IMAGE-GET-LOD-CUBE) A cube binds as the 6-layer 2D-array view cube_coords already builds for image_sample: the query takes the projected s - 1 and t - 1 (the 2D-array u and v) and does not read the third word (8 * slice + face). a16 packs the three coordinates differently, so a16 cube stays Unsupported. No corpus shader uses cube image_get_lod (705 in the 26,503-shader set: 702 2D, 3 2D array), so no title output changes; a 2,651-shader shard translates to byte-identical .spv before and after. Confirmed by the RDNA2 ISA MIMG GET_LOD form and the existing cube sample mapping (docs/design.md). Tests: tests/semantic/test_image_get_lod_cube.py 5/5 (shape, source VGPRs, face word unread, refusals, spirv-val); full tests/semantic 6,317 tests pass. AI-assisted. --- docs/design.md | 2 +- tests/semantic/test_image_get_lod_cube.py | 91 +++++++++++++++++++++++ tools/rdna2spirv.py | 24 +++++- 3 files changed, 112 insertions(+), 5 deletions(-) create mode 100644 tests/semantic/test_image_get_lod_cube.py diff --git a/docs/design.md b/docs/design.md index eecb1cb844..e18085652f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -454,7 +454,7 @@ How the generated SPIR-V expects the runtime to work: | Descriptor hash-table probe loop (`%desc_lookup_fn`) | `Gen.desc_probe` marks its FNV-1a probe loop `OpLoopMerge %dl_end %dl_cont DontUnroll` and breaks straight to `%dl_end` on a match (`OpBranch %dl_end`) instead of clobbering `%dl_k` to fall through `%dl_next`. Keeping `%dl_idx` on a single-exit loop-header phi caused Mesa ANV 26.1.6 (Intel UHD Graphics 630, CFL GT2) to hoist the post-loop binding-table-index addition (`add bti, idx, 2`) into `B0` before the probe loop in `ps_table_fetch` (observed in `INTEL_DEBUG=wm` across SIMD8, SIMD16 and SIMD32: every `fetch-sint` and `fetch-uint` pixel read slot 0's magenta fallback `0x3f800000`). Breaking directly to `%dl_end` with `DontUnroll` keeps one compact rolled loop (avoiding 8× unroll bloat) while giving `%dl_end` a post-loop exit phi so the addition stays after the loop. Confirmed on Intel UHD 630 / Mesa ANV 26.1.6 (`ps_table_fetch` 4096/4096 exact, full suite `185/241`, 0 failed), NVIDIA GTX 1050 Ti / 555.58.02 (`180/241`, 0 failed) and Mesa llvmpipe 26.1.6 (`ps_table_fetch` 4096/4096 exact); CPU-checked by `test_desc_probe_breaks_directly_with_dont_unroll` in `tests/test_desc_cache.py` (`spirv-as`, `tools/spirv_asm.py` and `spirv-val`). | | 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) | | Dynamic storage image descriptor indices | The runtime T# hash result indexes the r32ui arrays (bindings 4 and 7) used by `OpImageTexelPointer` for image atomics and the typed storage arrays (bindings 8 through 19) used by `OpImageWrite` for stores and `OpImageRead` for coherent loads. Literal T# words still go through the hash table. Emit `StorageImageArrayDynamicIndexing` and record `shaderStorageImageArrayDynamicIndexing` in the shader index when a storage array is accessed this way. Plain typed loads use sampled aliases and follow the sampled indexing rule. The same Vulkan dynamic-uniformity contract applies to storage indices. Confirmed by [Vulkan VUID 10130](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-StorageImageArrayDynamicIndexing-10130), the synthetic `storage_dynamic_index.asm` regression (`test_literal_storage_descriptor_and_mixed_sampled_load`, `test_storage_aliases_in_every_dimension` and `test_atomic_texel_pointers_use_storage_indices` in `tests/semantic/test_sampled_dynamic_index.py`) and `spirv-val`. | -| 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 skips the access entirely (`OpAccessChain`, `OpImageTexelPointer`, `OpAtomic*`, and any `glc` write-back sit inside `if (active)`), leaving memory and `vdata` untouched. Two-VGPR `dmask:0x3` forms of the nine standard ops currently still operate on the low 32-bit dword as before; true 64-bit image atomics remain separate follow-up work. `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; `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). `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: 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 skips the access entirely (`OpAccessChain`, `OpImageTexelPointer`, `OpAtomic*`, and any `glc` write-back sit inside `if (active)`), leaving memory and `vdata` untouched. Two-VGPR `dmask:0x3` forms of the nine standard ops currently still operate on the low 32-bit dword as before; true 64-bit image atomics remain separate follow-up work. `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; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D, 2D array and cube, the slice or face ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). A cube is the 6-layer 2D-array view of the `cube_coords` mapping: the query takes the projected s - 1 and t - 1 and does not read the third word (8 * slice + face), and `a16` cube stays refused because a16 packs the three coordinates differently. Confirmed by `tests/semantic/test_image_get_lod_cube.py` and a corpus count (705 `image_get_lod` in the 26,503-shader set, all 2D or 2D array, so no title frame changes; a 2,651-shader shard translated unchanged before and after). 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). `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: 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_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | The six remaining 32-bit MIMG image atomics on 2D (binding 4) and 3D (binding 7) `r32ui` storage images (including `a16` packed coordinates and optional `glc` return), guarded by `active_b` so inactive lanes skip memory access and preserve `vdata`. `image_atomic_swap` emits `OpAtomicExchange`; `inc`/`dec`/`fmin`/`fmax`/`fcmpswap` emit `OpAtomicLoad` (valid on `OpImageTexelPointer` `Image` pointers) followed by a Device-scope `OpAtomicCompareExchange` CAS loop (`inc`: `(M >= D) ? 0 : M + 1`; `dec`: `(M == 0 \|\| M > D) ? D : M - 1`; `fmin`/`fmax`: GLSL.std.450 `NMin`/`NMax`, no float-atomic extension required; `fcmpswap`: integer IEEE-754 binary32 ordered equality on raw 32-bit words — equal iff neither is NaN and `(cur == cmp) \|\| (both ±0.0)`, preserving subnormals even on Vulkan drivers reporting `shaderDenormPreserveFloat32 = false`, exiting without writing on mismatch or NaN; native RDNA2 subnormal behavior under denormal flush is unmeasured). Source: AMD RDNA2 ISA MIMG `IMAGE_ATOMIC_*`. CPU-checked structurally (including `spirv_mini_interp.check_structure` CFG validation) by `tests/semantic/test_image_atomics_32.py` (all 6 ops on 2D and 3D images, `a16`, `glc` and non-`glc`, no `AtomicFloat` capability, rejected widths/coords/dims). GPU-checked by `runtime/test/shaders/cs_imgatomic_ext.asm` through `vk_store_test words` (GPU-IMG-ATOMIC-EXT): all six ops on the 2D image and the volume, inc/dec on both sides of their wrap and with a D that is negative as a signed number, fmin/fmax with a NaN in the data register, fcmpswap with an equal and an unequal comparand, +0 against -0 and a NaN, `glc` and non-`glc` returns, inactive lanes held on a trap texel, and inc/dec/fmin/fmax from all 64 threads on one texel (the CAS loops under contention); every word exact on a Radeon 610M (`gfx1036`, RDNA2, RADV Mesa 26.2.6) and an RTX 4070 Ti (NVIDIA 620.70.06), natively and under `LEONIDA_W64_EMULATE=1`. Each of five planted translator faults (a signed inc/dec compare, fmin and fmax exchanged, fcmpswap without the +0/-0 rule, no inactive-lane guard, no `glc` return from swap) fails it on both. Not covered: NaN or denormal texels for fmin/fmax and fcmpswap, and +0 against -0 for fmin/fmax, where `NMin`/`NMax` and native RDNA2 may differ (native behaviour unmeasured). | | 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. `v_{add,sub,subrev}_co_ci_u32_sdwa` print the carry-out before the sources, so the selects belong to operands 2 and 3; **until 2026-11-24 they went to operands 1 and 2**, which left src1 unselected and put src1's select on src0 (CPU-checked by `tests/semantic/test_sdwa_carry.py`; not measured on RDNA2). **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, of which 556 also fall in the first group, so the groups add up to 21,204; 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. | diff --git a/tests/semantic/test_image_get_lod_cube.py b/tests/semantic/test_image_get_lod_cube.py new file mode 100644 index 0000000000..76bd42ef6f --- /dev/null +++ b/tests/semantic/test_image_get_lod_cube.py @@ -0,0 +1,91 @@ +"""image_get_lod on a cube: the query reads the 6-layer 2D-array view a cube binds as. + +Standard library only (spirv-as and spirv-val are used when they are on PATH); no GPU, no LLVM, no game files. + +The translator maps a cube sample onto the 2D-array view of the six faces (`cube_coords`): the hardware cube s and t +are the projected sc, tc / |cubema| + 1.5, and the third address word is 8 * slice + face. `image_get_lod` refused +every dimension but 2D and 2D array; on a cube it now subtracts one from s and t (the array view's u and v) and asks +OpImageQueryLod on the cube's %simg2da view. The face word takes no part in the LOD, so it is not read, and `a16` +cube stays refused because a16 packs the three coordinates differently. + +No corpus shader uses cube `image_get_lod` (705 in the 26 503-shader set: 702 2D and 3 2D array), so this closes a +form rather than fixing a title frame. The rule is the RDNA2 ISA MIMG GET_LOD dimension form and the existing cube +sample mapping (docs/design.md); the emitted module validates for Vulkan 1.2. +""" +import os +import re +import shutil +import subprocess +import tempfile +import unittest + +import support + +DESC = "s[0:7], s[8:11]" +CUBE = "dim:SQ_RSRC_IMG_CUBE" +EPILOGUE = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] + + +def translate(instruction): + return support.translate_lines("ps_get_lod_cube", [instruction, *EPILOGUE]) + + +def source_vgpr(spv, value): + """The VGPR index the id `value` was loaded from (through bitcasts), or None.""" + consts = {k: int(v) for k, v in re.findall(r"^\s*(%\w+) = OpConstant %uint (\d+)", spv, re.M)} + for _ in range(8): + m = re.search(rf"^\s*{re.escape(value)} = (\w+) (?:%\w+ )?(%\w+)", spv, re.M) + if not m: + return None + op, src = m.groups() + if op == "OpLoad": + m2 = re.search(rf"^\s*{re.escape(src)} = OpAccessChain %\S+ %vgpr (%\w+)", spv, re.M) + return consts.get(m2.group(1)) if m2 else None + value = src + return None + + +class GetLodCube(unittest.TestCase): + def one(self): + return translate(f"image_get_lod v[0:1], v[4:6], {DESC} dmask:0x3 {CUBE}") + + def test_cube_query_uses_the_six_layer_2d_array_view(self): + spv = self.one() + self.assertIn("%img2da = OpTypeImage %float 2D 0 1 0 1 Unknown", spv) + self.assertIn("%simg2da", spv) + self.assertIn("OpImageQueryLod %v2float", spv) + + def test_s_and_t_shift_by_one_and_the_face_word_is_not_read(self): + spv = self.one() + subs = re.findall(r"(%\w+) = OpFSub %float (%\w+) %f1$", spv, re.M) + self.assertEqual(len(subs), 2) + self.assertEqual([source_vgpr(spv, src) for _, src in subs], [4, 5]) # the projected s and t, not the face + uv = re.search(r"(%\w+) = OpCompositeConstruct %v2float (%\w+) (%\w+)$", spv, re.M) + self.assertIsNotNone(uv) + self.assertEqual(list(uv.groups()[1:]), [sid for sid, _ in subs]) + lod = re.search(r"OpImageQueryLod %v2float %\w+ (%\w+)$", spv, re.M) + self.assertEqual(lod.group(1), uv.group(1)) + # v6 holds 8 * slice + face; the query does not need it + self.assertNotIn("%reg_v6", spv) + + def test_a16_cube_stays_refused(self): + with self.assertRaises(support.rdna2spirv.Unsupported): + translate(f"image_get_lod v[0:1], v[4:5], {DESC} dmask:0x3 {CUBE} a16") + + def test_a_cube_with_too_few_address_registers_is_refused(self): + with self.assertRaises(support.rdna2spirv.Unsupported): + translate(f"image_get_lod v[0:1], v[4:5], {DESC} dmask:0x3 {CUBE}") + + @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val on PATH") + def test_module_validates(self): + spv = self.one() + with tempfile.TemporaryDirectory() as tmp: + a, b = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") + with open(a, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + subprocess.run(["spirv-as", "--target-env", "vulkan1.2", a, "-o", b], check=True) + subprocess.run(["spirv-val", "--target-env", "vulkan1.2", b], check=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index fa3c1aadf9..fb730bd225 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -3243,15 +3243,20 @@ def current_label_placeholder(self): return self.block_label def image_get_lod(self, a, mods): - """image_get_lod vD, vaddr, T#, S#: (clamped lod, unclamped lod) like OpImageQueryLod (2D, 2D array). For - arrays the query takes only the 2D coordinate; the layer doesn't affect the LOD.""" + """image_get_lod vD, vaddr, T#, S#: (clamped lod, unclamped lod) like OpImageQueryLod (2D, 2D array, + cube). For arrays the query takes only the 2D coordinate; the layer doesn't affect the LOD. A cube is the + same 6-layer 2D-array view image_sample uses (cube_coords): the projected s and t are the texture + coordinates, and the 8 * slice + face word takes no part in the LOD.""" dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") - if dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY") or self.stage != "ps": + cube = dim == "dim:SQ_RSRC_IMG_CUBE" + if dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY", "dim:SQ_RSRC_IMG_CUBE") or self.stage != "ps": raise Unsupported("image_get_lod form") a16 = "a16" in mods if a16 and ("tfe" in mods or "lwe" in mods): raise Unsupported("image_get_lod form") - arr = dim.endswith("_ARRAY") + if a16 and cube: + raise Unsupported("image_get_lod a16 cube") # a16 packs the cube's three coordinates differently + arr = dim.endswith("_ARRAY") or cube if arr: self.uses_tex_array = True dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x3") @@ -3275,6 +3280,17 @@ def image_get_lod(self, a, mods): packed = self.load_reg("vgpr", addr[0]) uv = self.tmp() self.emit(f"{uv} = OpExtInst %v2float %glsl UnpackHalf2x16 {packed}") + elif cube: + if len(addr) < 3: + raise Unsupported("image_get_lod cube coords") + # The hardware cube s and t are sc, tc / |cubema| + 1.5, i.e. the 2D-array view's u and v plus + # one; the third word (8 * slice + face) takes no part in the LOD, so it is not read. + f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]] + s, t = self.tmp(), self.tmp() + self.emit(f"{s} = OpFSub %float {f[0]} %f1") + self.emit(f"{t} = OpFSub %float {f[1]} %f1") + uv = self.tmp() + self.emit(f"{uv} = OpCompositeConstruct %v2float {s} {t}") else: f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]] uv = self.tmp()