upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRain156 <77776581+Rain156@users.noreply.github.com>2026-11-24 21:11:46 +0800
committerRain156 <77776581+Rain156@users.noreply.github.com>2026-11-24 21:11:46 +0800
commit8e2f3f618f464d56a7bb17a41f071e31ff2d5bfb (patch)
tree0cec5641c61cec919e4b554cecf61ea26a2242e1
parentb398993940227956a19f7e5a381624b642d17c15 (diff)
parent33f4a5aedeb48e27b004efe5d6ae306130d55cdd (diff)
Integrate the storage-image translation rules from #213
The corresponding runtime views are assembled with the other first-run rendering dependencies.
-rw-r--r--docs/design.md4
-rw-r--r--docs/testing.md24
-rw-r--r--tests/test_image_load_typed.py180
-rw-r--r--tests/test_spirv_metal_set0.py2
-rw-r--r--tests/test_spirv_metal_set0_aliases.py2
-rw-r--r--tests/test_spirv_metal_set0_extra.py39
-rw-r--r--tools/rdna2spirv.py315
7 files changed, 437 insertions, 129 deletions
diff --git a/docs/design.md b/docs/design.md
index 39b71b409..127bf8874 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -325,7 +325,7 @@ How the generated SPIR-V expects the runtime to work:
325| `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. | 325| `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. |
326| `v_div_fmas_f32`, `v_div_fmas_f64` | Scaled FMA for IEEE-754 division (VOP3): `D = fma(S0, S1, S2)` when `VCC[lane] == 0`; when `VCC[lane] == 1`, `D = (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2)` where `(bias, S)` is `(127, 64)` for f32 and `(1023, 128)` for f64 (`OpCapability Float64`, no `Int64`), i.e. `\|S2\| >= 2.0` scales up and `\|S2\| < 2.0` scales down. Scale-up uses `fma(S0, S1, S2) * 2^S` (any non-zero cancellation residual against `\|S2\| >= 2.0` stays well above normal minimum). Scale-down pre-scales `S0`/`S1` only when `\|S0*S1\|` can overflow (`\|S0\| >= 2^S` and `\|S1\| >= 1`, symmetric, or both `>= 2^(S/2)`), with a raw-bit sticky value `copysign(min_normal, S2)` whenever `0 < \|S2\| < 2^(Emin + S)` so half-ULP tie-breaking stays exact; otherwise it post-scales `fma(S0, S1, S2) * 2^-S`, with a TwoSum + product-error half-ULP tie adjustment in f64 when `\|fma\|` falls in `[2^-947, 2^-894)` so f64 subnormal outputs single-round. For f32 under the game MODE (`denorm32=0`), subnormal inputs and intermediate products are kept while subnormal outputs flush to signed zero before (and after) output modifiers; for f64 (`denorm16_64=3`), subnormals are kept throughout. VOP3 input (`abs`/`neg`) and output (`mul:2`/`mul:4`/`div:2`, then `clamp`) modifiers apply via `clamp_mods` / `clamp_mods_f64`. **Until 2026-11-22 the translator scaled unconditionally by `2^32` (f32) / `2^64` (f64) whenever `VCC[lane] == 1`, omitting the `exp(S2) > bias` branch and using half the hardware exponent shift.** **Hardware-verified on RDNA2** (`gfx1036`, AMD Radeon Graphics, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64, game MODE `ieee=0`/`dx10_clamp=1`/`denorm32=0`/`denorm16_64=3`): 150/150 f32 and 153/153 f64 stress cases match bit-for-bit, including the `\|S2\| = 2.0` vs `nextbelow(2.0)` threshold, scale-down overflow prevention, sticky-bit tie-breaking, f32 output denormal flushing, and f64 subnormal single rounding. Checked bit-for-bit on the CPU (`spirv_mini_interp` for f32, SSA `%double` evaluator for f64) and assembled with `tools/spirv_asm.py` (plus `spirv-val` when present) by `tests/semantic/test_alu_div_fmas.py`; not run on the shader corpus. | 326| `v_div_fmas_f32`, `v_div_fmas_f64` | Scaled FMA for IEEE-754 division (VOP3): `D = fma(S0, S1, S2)` when `VCC[lane] == 0`; when `VCC[lane] == 1`, `D = (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2)` where `(bias, S)` is `(127, 64)` for f32 and `(1023, 128)` for f64 (`OpCapability Float64`, no `Int64`), i.e. `\|S2\| >= 2.0` scales up and `\|S2\| < 2.0` scales down. Scale-up uses `fma(S0, S1, S2) * 2^S` (any non-zero cancellation residual against `\|S2\| >= 2.0` stays well above normal minimum). Scale-down pre-scales `S0`/`S1` only when `\|S0*S1\|` can overflow (`\|S0\| >= 2^S` and `\|S1\| >= 1`, symmetric, or both `>= 2^(S/2)`), with a raw-bit sticky value `copysign(min_normal, S2)` whenever `0 < \|S2\| < 2^(Emin + S)` so half-ULP tie-breaking stays exact; otherwise it post-scales `fma(S0, S1, S2) * 2^-S`, with a TwoSum + product-error half-ULP tie adjustment in f64 when `\|fma\|` falls in `[2^-947, 2^-894)` so f64 subnormal outputs single-round. For f32 under the game MODE (`denorm32=0`), subnormal inputs and intermediate products are kept while subnormal outputs flush to signed zero before (and after) output modifiers; for f64 (`denorm16_64=3`), subnormals are kept throughout. VOP3 input (`abs`/`neg`) and output (`mul:2`/`mul:4`/`div:2`, then `clamp`) modifiers apply via `clamp_mods` / `clamp_mods_f64`. **Until 2026-11-22 the translator scaled unconditionally by `2^32` (f32) / `2^64` (f64) whenever `VCC[lane] == 1`, omitting the `exp(S2) > bias` branch and using half the hardware exponent shift.** **Hardware-verified on RDNA2** (`gfx1036`, AMD Radeon Graphics, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64, game MODE `ieee=0`/`dx10_clamp=1`/`denorm32=0`/`denorm16_64=3`): 150/150 f32 and 153/153 f64 stress cases match bit-for-bit, including the `\|S2\| = 2.0` vs `nextbelow(2.0)` threshold, scale-down overflow prevention, sticky-bit tie-breaking, f32 output denormal flushing, and f64 subnormal single rounding. Checked bit-for-bit on the CPU (`spirv_mini_interp` for f32, SSA `%double` evaluator for f64) and assembled with `tools/spirv_asm.py` (plus `spirv-val` when present) by `tests/semantic/test_alu_div_fmas.py`; not run on the shader corpus. |
327| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | 327| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). |
328| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10–10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); every other `image_load` keeps the sampled path and needs no storage feature (SHADER-151). `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) is `Unsupported`. A cube has no storage view of its own: it is bound as a six-layer 2D array, so a coherent `image_load` on `dim:SQ_RSRC_IMG_CUBE` is supported (bindings 11/12/13, the third coordinate is the face). Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | 328| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10-10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class for those 2D views, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); other loads in the corpus keep the sampled path and need no storage feature (SHADER-151). The D3D-78 row below describes the storage-only and tagged atomic readback exceptions. `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) or on a dimension without storage views (cube) is `Unsupported`. Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. |
329| 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. | 329| 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. |
330| 2D `image_sample_l` | The T# FORMAT selects the sampled image type, and every type uses the LOD following the two coordinates. Vulkan requires the sampled type and signedness to match the view. The unit test `test_2d_lod_samples_use_matching_typed_views` in `tests/test_image_load_typed.py` checks the R32 UINT, SINT and FLOAT descriptor branches, the float fallback on a lookup miss and the LOD register with full-width and D16 results. [Vulkan sampling validation](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-input-validation) | 330| 2D `image_sample_l` | The T# FORMAT selects the sampled image type, and every type uses the LOD following the two coordinates. Vulkan requires the sampled type and signedness to match the view. The unit test `test_2d_lod_samples_use_matching_typed_views` in `tests/test_image_load_typed.py` checks the R32 UINT, SINT and FLOAT descriptor branches, the float fallback on a lookup miss and the LOD register with full-width and D16 results. [Vulkan sampling validation](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-input-validation) |
331| `image_sample_l` / `image_sample_lz` in every dimension | The T# FORMAT rule applies to a 2D-array, 3D, cube and 1D image too: the sample reads the uint/sint alias of that dimension's sampled binding (3, 6 and 5; a cube uses its 6-layer 2D-array view) and keeps the float view for a float format, the same `image_read_typed` dispatch `image_load` uses. Confirmed by `tests/semantic/test_sample_typed_dims.py` (the alias and sampled-image type each dimension emits, that a float format still samples the float view, and `spirv-val --target-env vulkan1.2`) and `runtime/src/vulkan_bindless.h` (`sampled_binding`). The format rule itself is the 2D row above; a GPU readback on a non-2D integer texture is not measured yet. | 331| `image_sample_l` / `image_sample_lz` in every dimension | The T# FORMAT rule applies to a 2D-array, 3D, cube and 1D image too: the sample reads the uint/sint alias of that dimension's sampled binding (3, 6 and 5; a cube uses its 6-layer 2D-array view) and keeps the float view for a float format, the same `image_read_typed` dispatch `image_load` uses. Confirmed by `tests/semantic/test_sample_typed_dims.py` (the alias and sampled-image type each dimension emits, that a float format still samples the float view, and `spirv-val --target-env vulkan1.2`) and `runtime/src/vulkan_bindless.h` (`sampled_binding`). The format rule itself is the 2D row above; a GPU readback on a non-2D integer texture is not measured yet. |
@@ -428,6 +428,8 @@ How the generated SPIR-V expects the runtime to work:
428| Typed image stores | `image_store` (2D, 2D array, 3D, cube) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. A cube storage image is bound as a six-layer 2D array (bindings 11/12/13 for float/uint/sint, `OpTypeImage ... 2D 0 1 0 2 Unknown`, `%v3int` coordinates (x, y, face)); `tfe` and `lwe` are refused. CPU-checked by `tests/semantic/test_image_cube_store_glc.py`; **not GPU-verified**: no GPU fixture covers a cube store yet. | 428| Typed image stores | `image_store` (2D, 2D array, 3D, cube) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. A cube storage image is bound as a six-layer 2D array (bindings 11/12/13 for float/uint/sint, `OpTypeImage ... 2D 0 1 0 2 Unknown`, `%v3int` coordinates (x, y, face)); `tfe` and `lwe` are refused. CPU-checked by `tests/semantic/test_image_cube_store_glc.py`; **not GPU-verified**: no GPU fixture covers a cube store yet. |
429| Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D<min16uint>` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. | 429| Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D<min16uint>` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. |
430| Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | 430| Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
431| 1D and 3D texture UAVs (D3D-78) | Storage bindings are 17–19 for 1D and 26–28 for 1D arrays (SPIR-V `1D`, arrayed), leaving multisample SRV bindings 20–25 unchanged. 1D arrays are storage-only: `image_load` and `image_store` use `(x, layer)` relative to the view. Ordinary 1D and 3D loads use sampled aliases; `image_load ... glc` in either dimension, or any `image_load` on a 1D array, reads the Unknown-format storage view. A layer-created 3D UAV sets reserved bit 31 of T# word 4; word 7 tagged with `0xd7800000` (mask `0xff800000`) holds `WSize - 1` in bits [21:11] and `FirstWSlice` in bits [10:0], including for whole-mip UAVs. Vulkan rebases/checks Z for storage operations. The typed sampled aliases below use the tag to rebase Z and return zero outside the range or for nonzero UAV LOD; an untagged SRV keeps its original coordinates and LOD. For non-`glc` `image_load` on a tagged R32_UINT T# whose SGPR group also feeds volume atomics in the shader, the read uses their formatted storage view (binding 7) so it can observe the atomic result in the same dispatch. Other sampled loads retain the visibility rule below. 3D atomics run only in active lanes with a resolved R32_UINT UAV; `glc` returns the old value and inactive lanes keep their destination. `cs_texture_uav.asm` and `d3d12_texture_uav_test` check coherent and sampled reads, dynamic `image_load_mip`, an untouched base mip, and active/inactive add and compare-and-swap with `glc` on an RTX 4090. |
432| Packed RGB9E5 UAV backing (#1287 and D3D-78) | Emulated RGB9E5 still encodes the logical shared-exponent FORMAT in the T#. A sampled view reads E5B9G9R9; a raw storage view uses R32_UINT, with any selected W range applied only to that storage view. On 1D-family and 3D UAVs, bit 22 of the synthetic word 7 marks this backing (tag mask `0xff800000`, lower 22 W bits unchanged). The translator does not implement re-packing for generic `image_store` or unpacking for formatless storage loads: these operations respectively suppress writes or take the fallback, not a view of the wrong numeric type. R32_UINT atomics require a logical R32_UINT volume UAV. The packed bit does not affect slicing or untagged SRVs; `d3d12_r9g9b9e5_uav_test` checks raw stores and sampled readback with the real set 0. |
431| 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 unit test `test_volume_mip_fetch_uses_xyz_level_and_descriptor_type` in `tests/test_image_load_typed.py` checks the four address registers and the RGBA32 format selection on the translated module. 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) | 433| 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 unit test `test_volume_mip_fetch_uses_xyz_level_and_descriptor_type` in `tests/test_image_load_typed.py` checks the four address registers and the RGBA32 format selection on the translated module. 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) |
432| 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. On the CPU, the unit tests `test_explicit_lod_gather_fetches_four_taps_from_each_typed_view` and `test_2d_gather_picks_the_sampled_type_and_selected_component` in `tests/test_image_load_typed.py` check the typed views at binding 0, the selected component, the shared mip footprint and the d16 packing. | 434| 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. On the CPU, the unit tests `test_explicit_lod_gather_fetches_four_taps_from_each_typed_view` and `test_2d_gather_picks_the_sampled_type_and_selected_component` in `tests/test_image_load_typed.py` check the typed views at binding 0, the selected component, the shared mip footprint and the d16 packing. |
433| Dynamic sampled descriptor indices | Set 0 bindings 0 (2D), 3 (2D array and cube), 5 (1D) and 6 (3D), including their integer sampled aliases, use runtime T# hash results for sampling, gather, texel fetch and image queries. Binding 1 uses runtime S# hash results for sampling, gather and LOD queries. Explicit-LOD gather emulation takes its sampler state directly from S# words and uses sampled-image fetches. Literal descriptor words and the zero-on-miss fallback still go through the runtime lookup. Emit `SampledImageArrayDynamicIndexing` and record `shaderSampledImageArrayDynamicIndexing` in the shader index whenever such an array is indexed. A storage-only shader can declare sampled arrays without indexing them. The hash table is one storage buffer containing an array of words. T# and S# operands are scalar across an RDNA2 wave (AMD RDNA 2 ISA, MIMG fields SRSRC/SSAMP). The Vulkan contract requires the resulting index to be dynamically uniform in the subgroup or invocation group, and in the invocation group when the effective subgroup size is one. If wave and Vulkan execution mappings break that uniformity, the affected accesses need separate non-uniform indexing support. Confirmed by the synthetic `sampled_dynamic_index.asm` regression (`test_sample_with_literal_sampler_still_indexes_both_arrays_dynamically` and `test_fetch_and_query_paths` in `tests/semantic/test_sampled_dynamic_index.py`), `spirv-val`, and the declaration-only GPU positive control in [#2806](https://github.com/ItsNotRexed/Leonida/pull/2806#issuecomment-7083836498). [Vulkan VUID 10128](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-SampledImageArrayDynamicIndexing-10128) and [runtime VUIDs 10135 and 10142](https://docs.vulkan.org/refpages/latest/refpages/source/RuntimeSpirv.html#VUID-RuntimeSpirv-SampledImageArrayNonUniformIndexing-10135). | 435| Dynamic sampled descriptor indices | Set 0 bindings 0 (2D), 3 (2D array and cube), 5 (1D) and 6 (3D), including their integer sampled aliases, use runtime T# hash results for sampling, gather, texel fetch and image queries. Binding 1 uses runtime S# hash results for sampling, gather and LOD queries. Explicit-LOD gather emulation takes its sampler state directly from S# words and uses sampled-image fetches. Literal descriptor words and the zero-on-miss fallback still go through the runtime lookup. Emit `SampledImageArrayDynamicIndexing` and record `shaderSampledImageArrayDynamicIndexing` in the shader index whenever such an array is indexed. A storage-only shader can declare sampled arrays without indexing them. The hash table is one storage buffer containing an array of words. T# and S# operands are scalar across an RDNA2 wave (AMD RDNA 2 ISA, MIMG fields SRSRC/SSAMP). The Vulkan contract requires the resulting index to be dynamically uniform in the subgroup or invocation group, and in the invocation group when the effective subgroup size is one. If wave and Vulkan execution mappings break that uniformity, the affected accesses need separate non-uniform indexing support. Confirmed by the synthetic `sampled_dynamic_index.asm` regression (`test_sample_with_literal_sampler_still_indexes_both_arrays_dynamically` and `test_fetch_and_query_paths` in `tests/semantic/test_sampled_dynamic_index.py`), `spirv-val`, and the declaration-only GPU positive control in [#2806](https://github.com/ItsNotRexed/Leonida/pull/2806#issuecomment-7083836498). [Vulkan VUID 10128](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-SampledImageArrayDynamicIndexing-10128) and [runtime VUIDs 10135 and 10142](https://docs.vulkan.org/refpages/latest/refpages/source/RuntimeSpirv.html#VUID-RuntimeSpirv-SampledImageArrayNonUniformIndexing-10135). |
diff --git a/docs/testing.md b/docs/testing.md
index ad6fdc539..765f22b3b 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -180,7 +180,29 @@ python -I runtime/test/shaders/build.py <out-dir> vs_ids ps_mullit
180python -I runtime/test/shaders/mullit_readback.py <out-dir> <harness-directory> 180python -I runtime/test/shaders/mullit_readback.py <out-dir> <harness-directory>
181``` 181```
182 182
183For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). 183For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with
184validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is
185installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal
186the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems").
187
188On Windows, `run_gpu_tests.py` assembles and translates the D3D-78 fixture and runs the UAV readback and WARP
189comparison from the same build folder. Use `--filter cs_texture_uav` to run only this case:
190
191```powershell
192$env:LEONIDA_VK_VALIDATION = "1"
193python -I scripts/run_gpu_tests.py --build runtime/build --filter cs_texture_uav
194```
195
196Use the actual configuration subfolder for the executables with a multi-config generator. The native Windows
197case reports SKIP without WARP or a sufficiently capable Vulkan device; failed translation, a missing test
198executable on Windows, and readback mismatches fail the runner. Devices without sliced 3D views still run the 1D,
199array and whole-mip cases and check that partial views are refused.
200
201CTest runs the same D3D-78 descriptor creation, copy, range/refusal and clear checks with `--descriptors-only`.
202That mode requires Vulkan, but not a translated shader or WARP. The GPU runner still exercises dispatch and readback.
203
204Use `--filter cs_imgload_mip` to check 2D `image_load_mip` on FLOAT (UNORM), UINT and SINT sampled views with
205both full-width and D16 loads; mip 0 contains decoy data and mip 1 holds the expected texels.
184 206
185`vk_compute_test`, `vk_bindless_test` and `vk_image_fuzz` read `LEONIDA_VK_VALIDATION` too (`vk_compute_test` 207`vk_compute_test`, `vk_bindless_test` and `vk_image_fuzz` read `LEONIDA_VK_VALIDATION` too (`vk_compute_test`
186through `runtime/test/vk_validation.h`): each validation message goes to stderr and a validation error makes the 208through `runtime/test/vk_validation.h`): each validation message goes to stderr and a validation error makes the
diff --git a/tests/test_image_load_typed.py b/tests/test_image_load_typed.py
index 2b7908435..a9ca28a1e 100644
--- a/tests/test_image_load_typed.py
+++ b/tests/test_image_load_typed.py
@@ -5,11 +5,13 @@ no GPU, LLVM or game files; SPIRV-Tools only for the optional validation test).
5 5
6The image's numeric type lives in the T# (word 1 FORMAT [28:20]), so the translator branches on it at run time. 6The image's numeric type lives in the T# (word 1 FORMAT [28:20]), so the translator branches on it at run time.
7UINT and SINT formats are fetched through uint and sint aliases of the dimension's sampled array (same set and 7UINT and SINT formats are fetched through uint and sint aliases of the dimension's sampled array (same set and
8binding), everything else and a lookup miss (index 0, the RGBA8_UNORM fallback) through the float array. Nothing 8binding), everything else and a lookup miss (index 0, the RGBA8_UNORM fallback) through the float array. Ordinary
9reads a storage image, so a shader that only loads declares no StorageImageReadWithoutFormat (which Intel Xe-LP 9sampled-image loads need neither StorageImageReadWithoutFormat (which Intel Xe-LP lacks, #619) nor
10lacks, #619) and no StorageImageWriteWithoutFormat. These tests translate small pixel shaders and check the SPIR-V: 10StorageImageWriteWithoutFormat. These tests translate small pixel shaders and check the SPIR-V:
11the capabilities, which binding and component type each fetch reads, and, with a small evaluator of the code that 11the capabilities, which binding and component type each fetch reads, and, with a small evaluator of the code that
12picks the branch, the branch taken for all 512 FORMAT values with a hit and with a miss. 12picks the branch, the branch taken for all 512 FORMAT values with a hit and with a miss. Coherent `glc`
13loads and storage-only 1D-array loads take the explicit storage-image path (D3D-78); the normal typed
14sampled path needs neither formatless storage-image capability.
13runtime/test/shaders/cs_imgload.asm checks the result on a GPU (vk_store_test load). 15runtime/test/shaders/cs_imgload.asm checks the result on a GPU (vk_store_test load).
14""" 16"""
15import itertools 17import itertools
@@ -99,8 +101,9 @@ class Module:
99 assert (op, ptr[1]) == ("OpAccessChain", "%vgpr"), (op, ptr) 101 assert (op, ptr[1]) == ("OpAccessChain", "%vgpr"), (op, ptr)
100 return self.value(ptr[2], 0, 0) 102 return self.value(ptr[2], 0, 0)
101 103
102 def value(self, x, word1, index): 104 def value(self, x, word1, index, regs=None):
103 """Evaluate the uint/bool id x given the T#'s word 1 and the bindless index of the lookup.""" 105 """Evaluate the format selection or volume guard, optionally supplying a test's SGPR/VGPR words."""
106 get = lambda y: self.value(y, word1, index, regs)
104 if x in ("%true", "%false"): 107 if x in ("%true", "%false"):
105 return x == "%true" 108 return x == "%true"
106 op, a = self.defs[x] 109 op, a = self.defs[x]
@@ -113,20 +116,31 @@ class Module:
113 if op == "OpLoad": 116 if op == "OpLoad":
114 ptr_op, p = self.defs[a[1]] 117 ptr_op, p = self.defs[a[1]]
115 assert ptr_op == "OpAccessChain", ptr_op 118 assert ptr_op == "OpAccessChain", ptr_op
116 if p[1] == "%vgpr" and self.vgprs is not None: 119 if p[1] in ("%sgpr", "%vgpr"):
117 return self.vgprs[self.value(p[2], word1, index)] 120 r = get(p[2])
118 if p[1] == "%sgpr": 121 if regs is not None:
119 assert self.value(p[2], word1, index) == 1, "only T# word 1 is read" 122 return regs[p[1], r]
123 if p[1] == "%vgpr" and self.vgprs is not None:
124 return self.vgprs[r]
125 assert (p[1], r) == ("%sgpr", 1), "only T# word 1 is read"
120 return word1 126 return word1
121 var_op, v = self.defs[p[1]] 127 var_op, v = self.defs[p[1]]
122 assert var_op == "OpVariable" and v[1] == "Private", (var_op, v) 128 assert var_op == "OpVariable" and v[1] == "Private", (var_op, v)
123 words = self.defs[v[2]][1][1:] # OpConstantComposite %fmt_mask_arr <words> 129 words = self.defs[v[2]][1][1:] # OpConstantComposite %fmt_mask_arr <words>
124 return self.value(words[self.value(p[2], word1, index)], word1, index) 130 return get(words[get(p[2])])
125 if op == "OpGroupNonUniformBroadcastFirst": # desc_lookup makes the descriptor word uniform: one invocation 131 if op == "OpGroupNonUniformBroadcastFirst": # One invocation: return the value (a[1] is the scope).
126 return self.value(a[2], word1, index) # here, so the value itself (a[1] is the Subgroup scope) 132 return get(a[2])
127 if op == "OpGroupNonUniformShuffle": # the same for a wave32 pixel shader's half (SHADER-731, #4225) 133 if op == "OpGroupNonUniformShuffle": # One invocation; subgroup shuffle returns its input.
128 return self.value(a[2], word1, index) 134 return get(a[2])
129 u = [self.value(y, word1, index) for y in a[1:]] 135 if op == "OpCompositeExtract":
136 return get(a[1])[int(a[2])]
137 if op == "OpCompositeInsert":
138 result = list(get(a[2]))
139 result[int(a[3])] = get(a[1])
140 return tuple(result)
141 u = [get(y) for y in a[1:]]
142 if op == "OpCompositeConstruct":
143 return tuple(u)
130 if op == "OpBitcast": 144 if op == "OpBitcast":
131 return u[0] 145 return u[0]
132 if op == "OpBitFieldUExtract": 146 if op == "OpBitFieldUExtract":
@@ -137,8 +151,20 @@ class Module:
137 return u[0] & u[1] 151 return u[0] & u[1]
138 if op == "OpINotEqual": 152 if op == "OpINotEqual":
139 return u[0] != u[1] 153 return u[0] != u[1]
154 if op == "OpIEqual":
155 return u[0] == u[1]
156 if op == "OpIAdd":
157 return (u[0] + u[1]) & 0xffffffff
158 if op == "OpULessThanEqual":
159 return u[0] <= u[1]
160 if op == "OpSelect":
161 return u[1] if u[0] else u[2]
140 if op == "OpLogicalAnd": 162 if op == "OpLogicalAnd":
141 return u[0] and u[1] 163 return u[0] and u[1]
164 if op == "OpLogicalOr":
165 return u[0] or u[1]
166 if op == "OpLogicalNot":
167 return not u[0]
142 raise AssertionError(f"unexpected {op} in the branch condition") 168 raise AssertionError(f"unexpected {op} in the branch condition")
143 169
144 def branch(self, word1, index): 170 def branch(self, word1, index):
@@ -173,9 +199,15 @@ class LoadOnlyShaders(unittest.TestCase):
173 self.assertEqual((m.binding[var], image[1]), (6, "3D")) 199 self.assertEqual((m.binding[var], image[1]), (6, "3D"))
174 _, _, xyz, mask, lod = m.defs[rid][1] 200 _, _, xyz, mask, lod = m.defs[rid][1]
175 self.assertEqual(mask, "Lod") 201 self.assertEqual(mask, "Lod")
176 op, coords = m.defs[xyz] 202 # The sampled alias rebases only tagged UAVs; an ordinary SRV must use its original XYZ/LOD.
203 op, adjusted = m.defs[xyz]
204 self.assertEqual((op, adjusted[0], adjusted[3]), ("OpCompositeInsert", "%v3int", "2"))
205 op, coords = m.defs[adjusted[2]]
177 self.assertEqual((op, coords[0]), ("OpCompositeConstruct", "%v3int")) 206 self.assertEqual((op, coords[0]), ("OpCompositeConstruct", "%v3int"))
178 self.assertEqual([m.integer_coord_vgpr(v) for v in [*coords[1:], lod]], [4, 5, 6, 7]) 207 self.assertEqual([m.integer_coord_vgpr(v) for v in [*coords[1:], lod]], [4, 5, 6, 7])
208 regs = {("%vgpr", r): val for r, val in zip(range(4, 8), (11, 17, 23, 3))}
209 regs.update({("%sgpr", 4): 0, ("%sgpr", 7): 0})
210 self.assertEqual((m.value(xyz, 0, 1, regs), m.value(lod, 0, 1, regs)), ((11, 17, 23), 3))
179 for fmt, kind in ((75, "uint"), (76, "sint"), (77, "float")): # RGBA32 formats 211 for fmt, kind in ((75, "uint"), (76, "sint"), (77, "float")): # RGBA32 formats
180 self.assertEqual(m.branch(fmt << 20, 1), kind) 212 self.assertEqual(m.branch(fmt << 20, 1), kind)
181 self.assertEqual(m.branch(fmt << 20, 0), "float") 213 self.assertEqual(m.branch(fmt << 20, 0), "float")
@@ -512,15 +544,125 @@ class StoreAndLoad(unittest.TestCase):
512 self.assertEqual(set(m.binding.values()), {0, 1, 2, 8, 9, 10}) 544 self.assertEqual(set(m.binding.values()), {0, 1, 2, 8, 9, 10})
513 545
514 546
547def uav_array_load():
548 return translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2",
549 "image_load v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_1D_ARRAY unorm",
550 "s_waitcnt vmcnt(0)"])
551
552
553def volume_mip_load():
554 return translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", "v_mov_b32 v6, 3", "v_mov_b32 v7, 1",
555 "image_load_mip v[0:3], v[4:7], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_3D unorm",
556 "s_waitcnt vmcnt(0)"])
557
558
559def mixed_d16_mip_loads():
560 return translate(["image_load_mip v0, v[4:6], s[8:15] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16",
561 "image_load_mip v3, v[8:11], s[16:23] dmask:0x9 dim:SQ_RSRC_IMG_3D unorm d16",
562 "s_waitcnt vmcnt(0)"])
563
564
565class TextureUavLoads(unittest.TestCase):
566 def test_1d_array_load_uses_only_storage_bindings_and_the_read_feature(self):
567 m = Module(uav_array_load())
568 self.assertEqual(m.caps & STORAGE_IMAGE_CAPS, {"StorageImageReadWithoutFormat", "Image1D"})
569 self.assertEqual(set(m.binding.values()), {0, 1, 2, 26, 27, 28})
570 self.assertFalse(m.fetches())
571 reads = {}
572 for _, op, args in m.order:
573 if op == "OpImageRead":
574 _, load = m.defs[args[1]]
575 _, chain = m.defs[load[1]]
576 reads[m.binding[chain[1]]] = m.defs[load[0]][1]
577 self.assertEqual(reads, {26: ["%float", "1D", "0", "1", "0", "2", "Unknown"],
578 27: ["%uint", "1D", "0", "1", "0", "2", "Unknown"],
579 28: ["%int", "1D", "0", "1", "0", "2", "Unknown"]})
580
581 def test_coherent_volume_load_and_1d_array_load_share_storage_dispatch(self):
582 m = Module(translate([
583 "image_load v0, v[4:6], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc dlc",
584 "image_load v3, v[4:5], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm",
585 "s_waitcnt vmcnt(0)",
586 ]))
587 self.assertEqual(m.caps & STORAGE_IMAGE_CAPS, {"StorageImageReadWithoutFormat", "Image1D"})
588 self.assertFalse(m.fetches())
589 self.assertEqual({b for v, b in m.binding.items() if v.startswith("%stv")}, {14, 15, 16, 26, 27, 28})
590 self.assertTrue(all(f"OpDecorate {v} Coherent" in m.text for v in m.binding if v.startswith("%stv")))
591
592 def test_volume_mip_load_rebases_each_sampled_alias_without_storage(self):
593 m = Module(volume_mip_load())
594 self.assertFalse(m.caps & STORAGE_IMAGE_CAPS)
595 fetches = m.fetches()
596 self.assertEqual({image[0] for _, _, image in fetches}, {"%int", "%uint", "%float"})
597 for rid, var, _ in fetches:
598 self.assertEqual(m.binding[var], 6)
599 self.assertEqual(m.defs[m.defs[rid][1][2]][0], "OpCompositeInsert")
600 self.assertTrue(any(op == "OpPhi" and rid in args for _, op, args in m.order))
601
602 def test_volume_atomic_load_accepts_a_descriptor_register_list(self):
603 t = "[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]"
604 m = Module(translate([
605 f"image_atomic_add v0, v[4:6], {t} dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc",
606 f"image_load v3, v[4:6], {t} dmask:0x1 dim:SQ_RSRC_IMG_3D unorm",
607 "s_waitcnt vmcnt(0)",
608 ]))
609 self.assertIn("OpAtomicIAdd", m.text)
610 self.assertIn("OpImageRead", m.text)
611 self.assertEqual(m.binding["%simages3d"], 7)
612 self.assertFalse(m.caps & STORAGE_IMAGE_CAPS)
613
614 def test_mixed_d16_mips_keep_2d_lod_and_only_rebase_tagged_3d(self):
615 m = Module(mixed_d16_mip_loads())
616 self.assertFalse(m.caps & STORAGE_IMAGE_CAPS)
617 self.assertNotIn("OpImageRead", m.text)
618 self.assertEqual(set(m.binding.values()), {0, 1, 2, 6})
619 guards, last = {}, None
620 for rid, op, args in m.order:
621 if op == "OpBranchConditional":
622 last = args[0]
623 elif op == "OpImageFetch":
624 guards[rid] = last
625 regs = {("%vgpr", r): value for r, value in {4: 3, 5: 4, 6: 2, 8: 5, 9: 6, 10: 0, 11: 0}.items()}
626 types = {0: set(), 6: set()}
627 flag, tag = 0x80000000, 0xd7800000 | (1 << 11) | 3 # WSize=2, FirstWSlice=3
628 for rid, var, image in m.fetches():
629 binding = m.binding[var]
630 types[binding].add(image[0])
631 _, (_, _, coords, operand, lod) = m.defs[rid]
632 self.assertEqual(operand, "Lod")
633 if binding == 0:
634 self.assertEqual(m.value(coords, 0, 1, regs), (3, 4))
635 self.assertEqual(m.value(lod, 0, 1, regs), 2)
636 continue
637 for t4, t7, z, level, expected in (
638 (flag, tag, 1, 0, 4), (flag, tag, 2, 0, None), (flag, tag, 0xffffffff, 0, None),
639 (flag, tag, 0, 1, None), (0, tag, 2, 1, 2), (flag, 0, 2, 1, 2), (0, 0, 2, 1, 2),
640 (flag, tag | 0x00400000, 1, 0, 4), (flag, tag | 0x00400000, 2, 0, None),
641 ):
642 with self.subTest(ty=image[0], t4=t4, t7=t7, z=z, level=level):
643 regs.update({("%sgpr", 20): t4, ("%sgpr", 23): t7, ("%vgpr", 10): z, ("%vgpr", 11): level})
644 self.assertEqual(m.value(guards[rid], 0, 1, regs), expected is not None)
645 if expected is not None:
646 self.assertEqual(m.value(coords, 0, 1, regs), (5, 6, expected))
647 self.assertEqual(m.value(lod, 0, 1, regs), level)
648 self.assertEqual(types, {0: {"%float", "%uint", "%int"}, 6: {"%float", "%uint", "%int"}})
649
650
515@unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val") 651@unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val")
516class Validation(unittest.TestCase): 652class Validation(unittest.TestCase):
517 def test_spirv_val_accepts_every_dimension(self): 653 def test_spirv_val_accepts_every_dimension(self):
654 shaders = {dim: load_shader(dim) for dim in DIMS}
655 shaders.update({"1D_ARRAY": uav_array_load(), "3D_MIP": volume_mip_load(), "MIXED_D16_MIP": mixed_d16_mip_loads()})
656 shaders["GATHER_D16"] = translate([
657 "image_gather4_lz v[0:1], v[4:5], s[0:7], s[8:11] dmask:0x2 dim:SQ_RSRC_IMG_2D d16",
658 "s_waitcnt vmcnt(0)",
659 ])
518 with tempfile.TemporaryDirectory() as tmp: 660 with tempfile.TemporaryDirectory() as tmp:
519 for dim in DIMS: 661 for dim, text in shaders.items():
520 with self.subTest(dim=dim): 662 with self.subTest(dim=dim):
521 sa, sv = os.path.join(tmp, f"{dim}.spvasm"), os.path.join(tmp, f"{dim}.spv") 663 sa, sv = os.path.join(tmp, f"{dim}.spvasm"), os.path.join(tmp, f"{dim}.spv")
522 with open(sa, "w", encoding="utf-8") as f: 664 with open(sa, "w", encoding="utf-8") as f:
523 f.write(load_shader(dim)) 665 f.write(text)
524 result = rdna2spirv.assemble_spirv(sa, sv) 666 result = rdna2spirv.assemble_spirv(sa, sv)
525 self.assertEqual(result.returncode, 0, result.stderr + result.stdout) 667 self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
526 668
diff --git a/tests/test_spirv_metal_set0.py b/tests/test_spirv_metal_set0.py
index 099298c15..46839df05 100644
--- a/tests/test_spirv_metal_set0.py
+++ b/tests/test_spirv_metal_set0.py
@@ -37,7 +37,7 @@ MODULE = """\
37def test_capacities_match_vulkan_bindless(): 37def test_capacities_match_vulkan_bindless():
38 counts = m.capacities() 38 counts = m.capacities()
39 assert counts[:5] == [4096, 1024, 1, 1024, 1024] 39 assert counts[:5] == [4096, 1024, 1, 1024, 1024]
40 assert len(counts) == 26 40 assert counts[26:] == [256, 256, 256] # storage-only Texture1DArray UAVs
41 41
42 42
43def test_metal_ids_are_running_sums(): 43def test_metal_ids_are_running_sums():
diff --git a/tests/test_spirv_metal_set0_aliases.py b/tests/test_spirv_metal_set0_aliases.py
index 379360930..0775197b0 100644
--- a/tests/test_spirv_metal_set0_aliases.py
+++ b/tests/test_spirv_metal_set0_aliases.py
@@ -83,7 +83,7 @@ class TestFileHygiene(unittest.TestCase):
83 with warnings.catch_warnings(): 83 with warnings.catch_warnings():
84 warnings.simplefilter("error", ResourceWarning) 84 warnings.simplefilter("error", ResourceWarning)
85 counts = m.capacities() 85 counts = m.capacities()
86 self.assertEqual(len(counts), 26) 86 self.assertEqual(len(counts), 29)
87 self.assertEqual(m.capacities(good_hdr), [16, 8]) 87 self.assertEqual(m.capacities(good_hdr), [16, 8])
88 with self.assertRaises(SystemExit): 88 with self.assertRaises(SystemExit):
89 m.capacities(bad_hdr) 89 m.capacities(bad_hdr)
diff --git a/tests/test_spirv_metal_set0_extra.py b/tests/test_spirv_metal_set0_extra.py
index 5f8b63c62..eb31eb06b 100644
--- a/tests/test_spirv_metal_set0_extra.py
+++ b/tests/test_spirv_metal_set0_extra.py
@@ -1,7 +1,7 @@
1"""Expanded stdlib-only unit tests for tools/spirv_metal_set0.py. 1"""Expanded stdlib-only unit tests for tools/spirv_metal_set0.py.
2 2
3Covers bindless capacity parsing from vulkan_bindless.h and custom headers, 3Covers bindless capacity parsing from vulkan_bindless.h and custom headers,
4metal_ids() layout math, rewrite() across all 26 bindings, non-set-0 / 4metal_ids() layout math, rewrite() across all set-0 bindings, non-set-0 /
5push-constant / non-runtime-array / pre-sized / raw-ID / error branches, 5push-constant / non-runtime-array / pre-sized / raw-ID / error branches,
6synthetic SPIR-V binary word header/magic/endianness/bounds handling, 6synthetic SPIR-V binary word header/magic/endianness/bounds handling,
7out-of-place vs in-place CLI execution via mocked spirv-dis/spirv-as, 7out-of-place vs in-place CLI execution via mocked spirv-dis/spirv-as,
@@ -376,17 +376,17 @@ def _make_fake_spirv_tools(dis_name="spirv-dis", asm_name="spirv-as"):
376 376
377 377
378class TestCapacities(unittest.TestCase): 378class TestCapacities(unittest.TestCase):
379 def test_default_bindless_header_all_26_entries_and_cross_check(self): 379 def test_default_bindless_header_all_entries_and_cross_check(self):
380 counts = m.capacities() 380 counts = m.capacities()
381 expected = [4096, 1024, 1, 1024, 1024] + [256] * 21 381 expected = [4096, 1024, 1, 1024, 1024] + [256] * 24
382 self.assertEqual(counts, expected) 382 self.assertEqual(counts, expected)
383 self.assertEqual(len(counts), 26) 383 self.assertEqual(len(counts), 29)
384 self.assertEqual(sum(counts), 12545) 384 self.assertEqual(sum(counts), 13313)
385 385
386 with open(m.BINDLESS_H, encoding="utf-8") as f: 386 with open(m.BINDLESS_H, encoding="utf-8") as f:
387 hdr = f.read() 387 hdr = f.read()
388 self.assertIn("inline constexpr std::uint32_t binding_count = 26;", hdr) 388 self.assertIn("inline constexpr std::uint32_t binding_count = 29;", hdr)
389 self.assertIn("inline constexpr std::array<Binding, 26> bindings =", hdr) 389 self.assertIn("inline constexpr std::array<Binding, 29> bindings =", hdr)
390 390
391 def test_custom_header_parsing_variants(self): 391 def test_custom_header_parsing_variants(self):
392 cases = [ 392 cases = [
@@ -465,12 +465,13 @@ class TestMetalIds(unittest.TestCase):
465 def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self): 465 def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self):
466 counts = m.capacities() 466 counts = m.capacities()
467 ids = m.metal_ids(counts) 467 ids = m.metal_ids(counts)
468 self.assertEqual(len(ids), 26) 468 self.assertEqual(len(ids), 29)
469 self.assertEqual(ids[0], 0) 469 self.assertEqual(ids[0], 0)
470 self.assertEqual(ids[:6], [0, 4096, 5120, 5121, 6145, 7169]) 470 self.assertEqual(ids[:6], [0, 4096, 5120, 5121, 6145, 7169])
471 self.assertEqual(ids[8], 7937) 471 self.assertEqual(ids[8], 7937)
472 self.assertEqual(ids[20], 11009) 472 self.assertEqual(ids[20], 11009)
473 self.assertEqual(ids[25], 12289) 473 self.assertEqual(ids[25], 12289)
474 self.assertEqual(ids[26:], [12545, 12801, 13057])
474 for b in range(len(counts) - 1): 475 for b in range(len(counts) - 1):
475 self.assertEqual(ids[b + 1], ids[b] + counts[b]) 476 self.assertEqual(ids[b + 1], ids[b] + counts[b])
476 self.assertEqual(ids[-1] + counts[-1], sum(counts)) 477 self.assertEqual(ids[-1] + counts[-1], sum(counts))
@@ -480,11 +481,11 @@ class TestMetalIds(unittest.TestCase):
480 if b > 0: 481 if b > 0:
481 self.assertGreater(ids[b], ids[b - 1] + counts[b - 1] - 1) 482 self.assertGreater(ids[b], ids[b - 1] + counts[b - 1] - 1)
482 seen_total += counts[b] 483 seen_total += counts[b]
483 self.assertEqual(seen_total, 12545) 484 self.assertEqual(seen_total, 13313)
484 485
485 486
486class TestRewrite(unittest.TestCase): 487class TestRewrite(unittest.TestCase):
487 def test_all_26_vulkan_bindless_bindings(self): 488 def test_all_vulkan_bindless_bindings(self):
488 counts = m.capacities() 489 counts = m.capacities()
489 ids = m.metal_ids(counts) 490 ids = m.metal_ids(counts)
490 lines = [ 491 lines = [
@@ -492,7 +493,7 @@ class TestRewrite(unittest.TestCase):
492 " OpCapability RuntimeDescriptorArray", 493 " OpCapability RuntimeDescriptorArray",
493 " OpMemoryModel Logical GLSL450", 494 " OpMemoryModel Logical GLSL450",
494 ] 495 ]
495 for b in range(26): 496 for b in range(len(counts)):
496 lines.append(f" OpDecorate %v{b} DescriptorSet 0") 497 lines.append(f" OpDecorate %v{b} DescriptorSet 0")
497 lines.append(f" OpDecorate %v{b} Binding {b}") 498 lines.append(f" OpDecorate %v{b} Binding {b}")
498 lines.extend([ 499 lines.extend([
@@ -504,13 +505,13 @@ class TestRewrite(unittest.TestCase):
504 " %map = OpTypeStruct %rt_map", 505 " %map = OpTypeStruct %rt_map",
505 " %ptr_map = OpTypePointer StorageBuffer %map", 506 " %ptr_map = OpTypePointer StorageBuffer %map",
506 ]) 507 ])
507 for b in range(26): 508 for b in range(len(counts)):
508 if b == 2: 509 if b == 2:
509 continue 510 continue
510 elem = "%smp" if b == 1 else "%img2d" 511 elem = "%smp" if b == 1 else "%img2d"
511 lines.append(f" %rt_b{b} = OpTypeRuntimeArray {elem}") 512 lines.append(f" %rt_b{b} = OpTypeRuntimeArray {elem}")
512 lines.append(f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}") 513 lines.append(f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}")
513 for b in range(26): 514 for b in range(len(counts)):
514 if b == 2: 515 if b == 2:
515 lines.append(" %v2 = OpVariable %ptr_map StorageBuffer") 516 lines.append(" %v2 = OpVariable %ptr_map StorageBuffer")
516 else: 517 else:
@@ -519,7 +520,7 @@ class TestRewrite(unittest.TestCase):
519 out = m.rewrite("\n".join(lines) + "\n", counts) 520 out = m.rewrite("\n".join(lines) + "\n", counts)
520 out_lines = out.splitlines() 521 out_lines = out.splitlines()
521 522
522 for b in range(26): 523 for b in range(len(counts)):
523 self.assertIn(f" OpDecorate %v{b} Binding {ids[b]}", out_lines) 524 self.assertIn(f" OpDecorate %v{b} Binding {ids[b]}", out_lines)
524 if b == 2: 525 if b == 2:
525 self.assertIn(" %v2 = OpVariable %ptr_map StorageBuffer", out_lines) 526 self.assertIn(" %v2 = OpVariable %ptr_map StorageBuffer", out_lines)
@@ -690,7 +691,7 @@ OpDecorate %orphan Binding 1
690 self.assertEqual(m.rewrite(plain, [4]), plain) 691 self.assertEqual(m.rewrite(plain, [4]), plain)
691 692
692 def test_out_of_bounds_set0_binding_raises_system_exit(self): 693 def test_out_of_bounds_set0_binding_raises_system_exit(self):
693 for b, counts in ((2, [10, 20]), (26, m.capacities()), (100, m.capacities())): 694 for b, counts in ((2, [10, 20]), (29, m.capacities()), (100, m.capacities())):
694 with self.subTest(binding=b, count_len=len(counts)): 695 with self.subTest(binding=b, count_len=len(counts)):
695 text = f"OpDecorate %bad DescriptorSet 0\nOpDecorate %bad Binding {b}\n" 696 text = f"OpDecorate %bad DescriptorSet 0\nOpDecorate %bad Binding {b}\n"
696 with self.assertRaises(SystemExit) as ctx: 697 with self.assertRaises(SystemExit) as ctx:
@@ -731,14 +732,14 @@ class TestMainAndCli(unittest.TestCase):
731 code = m.main(argv) 732 code = m.main(argv)
732 return code, out.getvalue(), err.getvalue() 733 return code, out.getvalue(), err.getvalue()
733 734
734 def test_print_layout_outputs_26_formatted_ranges_without_subprocess(self): 735 def test_print_layout_outputs_all_formatted_ranges_without_subprocess(self):
735 with mock.patch.object(m.subprocess, "run") as run_mock: 736 with mock.patch.object(m.subprocess, "run") as run_mock:
736 code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"]) 737 code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"])
737 run_mock.assert_not_called() 738 run_mock.assert_not_called()
738 self.assertEqual(code, 0) 739 self.assertEqual(code, 0)
739 self.assertEqual(err, "") 740 self.assertEqual(err, "")
740 lines = out.splitlines() 741 lines = out.splitlines()
741 self.assertEqual(len(lines), 26) 742 self.assertEqual(len(lines), 29)
742 self.assertEqual(lines[0], "binding 0: 4096 descriptors at IDs 0..4095") 743 self.assertEqual(lines[0], "binding 0: 4096 descriptors at IDs 0..4095")
743 self.assertEqual(lines[1], "binding 1: 1024 descriptors at IDs 4096..5119") 744 self.assertEqual(lines[1], "binding 1: 1024 descriptors at IDs 4096..5119")
744 self.assertEqual(lines[2], "binding 2: 1 descriptors at IDs 5120..5120") 745 self.assertEqual(lines[2], "binding 2: 1 descriptors at IDs 5120..5120")
@@ -801,7 +802,7 @@ class TestMainAndCli(unittest.TestCase):
801 ) 802 )
802 self.assertEqual(r_layout.returncode, 0, r_layout.stderr) 803 self.assertEqual(r_layout.returncode, 0, r_layout.stderr)
803 self.assertEqual(r_layout.stderr, "") 804 self.assertEqual(r_layout.stderr, "")
804 self.assertEqual(len(r_layout.stdout.splitlines()), 26) 805 self.assertEqual(len(r_layout.stdout.splitlines()), 29)
805 self.assertEqual(r_layout.stdout.splitlines()[0], "binding 0: 4096 descriptors at IDs 0..4095") 806 self.assertEqual(r_layout.stdout.splitlines()[0], "binding 0: 4096 descriptors at IDs 0..4095")
806 807
807 for args in ([], ["only_one.spv"], ["a.spv", "b.spv", "c.spv"]): 808 for args in ([], ["only_one.spv"], ["a.spv", "b.spv", "c.spv"]):
@@ -1025,7 +1026,7 @@ class TestMainAndCli(unittest.TestCase):
1025 runpy.run_path(TOOL_PATH, run_name="__main__") 1026 runpy.run_path(TOOL_PATH, run_name="__main__")
1026 self.assertEqual(ctx.exception.code, 0) 1027 self.assertEqual(ctx.exception.code, 0)
1027 self.assertEqual(err_stream.getvalue(), "") 1028 self.assertEqual(err_stream.getvalue(), "")
1028 self.assertEqual(len(out_stream.getvalue().splitlines()), 26) 1029 self.assertEqual(len(out_stream.getvalue().splitlines()), 29)
1029 1030
1030 err_stream = io.StringIO() 1031 err_stream = io.StringIO()
1031 with warnings.catch_warnings(): 1032 with warnings.catch_warnings():
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 2c80928e4..cc7d149c8 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -297,9 +297,11 @@ class Gen:
297 self.uses_store_views = set() # image_store dims used (index into STORE_DIMS) 297 self.uses_store_views = set() # image_store dims used (index into STORE_DIMS)
298 self.uses_int_sampler = False # 2D typed sampled-image types for sampling and gathering 298 self.uses_int_sampler = False # 2D typed sampled-image types for sampling and gathering
299 self.uses_int_fetch = set() # typed image_load dims (index into STORE_DIMS): uint/sint sampled aliases 299 self.uses_int_fetch = set() # typed image_load dims (index into STORE_DIMS): uint/sint sampled aliases
300 self.uses_d16_image = False # a d16 image result is narrowed: needs the normalized / 32-bit-float tables 300 self.uses_d16_image = False # d16 normalized/f32 conversion masks
301 self.uses_fmt_size = False # %fmt_size_tab: byte size of each 7-bit buffer FORMAT code (0 = not in FORMATS) 301 self.uses_fmt_size = False # buffer FORMAT -> size table
302 self.reads_store_views = False # a coherent image_load reads a storage view (StorageImageReadWithoutFormat) 302 self.uses_store_reads = set() # formatless reads for coherent/storage-only dimensions
303 self.atomic_volume_tsharps = set() # SGPR descriptor groups also used for 3D atomics
304 self.reads_store_views = False # reserved for compatibility with main
303 self.coherent_images = False # a glc image_load/image_store: the storage views are decorated Coherent 305 self.coherent_images = False # a glc image_load/image_store: the storage views are decorated Coherent
304 self.writes_depth = False 306 self.writes_depth = False
305 self.uses_smul = False 307 self.uses_smul = False
@@ -13268,6 +13270,9 @@ class Gen:
13268 a16 = "a16" in mods 13270 a16 = "a16" in mods
13269 d16 = "d16" in mods 13271 d16 = "d16" in mods
13270 dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") 13272 dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D")
13273 storage_only = dim == "dim:SQ_RSRC_IMG_1D_ARRAY"
13274 if storage_only and (op != "image_load" or d16):
13275 raise Unsupported(op + " 1D_ARRAY")
13271 kinds = {"dim:SQ_RSRC_IMG_2D": ("img2d", "%images", "simg2d", 2, "_ptr_UC_img"), 13276 kinds = {"dim:SQ_RSRC_IMG_2D": ("img2d", "%images", "simg2d", 2, "_ptr_UC_img"),
13272 "dim:SQ_RSRC_IMG_2D_ARRAY": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), 13277 "dim:SQ_RSRC_IMG_2D_ARRAY": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"),
13273 # Cube: the shader already did face selection (v_cube*), and cube_coords maps (s, t, face) onto a 13278 # Cube: the shader already did face selection (v_cube*), and cube_coords maps (s, t, face) onto a
@@ -13275,17 +13280,20 @@ class Gen:
13275 "dim:SQ_RSRC_IMG_CUBE": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), 13280 "dim:SQ_RSRC_IMG_CUBE": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"),
13276 "dim:SQ_RSRC_IMG_1D": ("img1d", "%images_1d", "simg1d", 1, "_ptr_UC_img1"), 13281 "dim:SQ_RSRC_IMG_1D": ("img1d", "%images_1d", "simg1d", 1, "_ptr_UC_img1"),
13277 "dim:SQ_RSRC_IMG_3D": ("img3d", "%images_3d", "simg3d", -3, "_ptr_UC_img3")} 13282 "dim:SQ_RSRC_IMG_3D": ("img3d", "%images_3d", "simg3d", -3, "_ptr_UC_img3")}
13278 if dim not in kinds: 13283 if not storage_only and dim not in kinds:
13279 raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) 13284 raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1])
13280 itype, iarr, stype, ncoord, iptr = kinds[dim] 13285 if storage_only:
13281 is3d = ncoord == -3 # 3D: three real coordinates (and 3-component gradients) 13286 ncoord, is3d = 2, False
13282 if is3d: 13287 else:
13283 ncoord = 3 13288 itype, iarr, stype, ncoord, iptr = kinds[dim]
13284 self.uses_tex_3d = True 13289 is3d = ncoord == -3 # 3D: three real coordinates (and 3-component gradients)
13285 elif ncoord == 3: 13290 if is3d:
13286 self.uses_tex_array = True 13291 ncoord = 3
13287 if ncoord == 1: 13292 self.uses_tex_3d = True
13288 self.uses_tex_1d = True 13293 elif ncoord == 3:
13294 self.uses_tex_array = True
13295 if ncoord == 1:
13296 self.uses_tex_1d = True
13289 if is3d and op in ("image_sample_d", "image_sample_d_cl") and ("tfe" in mods or "lwe" in mods): 13297 if is3d and op in ("image_sample_d", "image_sample_d_cl") and ("tfe" in mods or "lwe" in mods):
13290 raise Unsupported(op + " 3D gradient status") 13298 raise Unsupported(op + " 3D gradient status")
13291 grad_width = 3 if is3d else min(ncoord, 2) # an array layer has no derivative 13299 grad_width = 3 if is3d else min(ncoord, 2) # an array layer has no derivative
@@ -13309,7 +13317,7 @@ class Gen:
13309 raise Unsupported(op + " needs scalar 2D depth comparison") 13317 raise Unsupported(op + " needs scalar 2D depth comparison")
13310 img_idx = self.desc_lookup_sgpr(a[2], 8) 13318 img_idx = self.desc_lookup_sgpr(a[2], 8)
13311 img = None # a coherent image_load reads the storage view, not this sampled one 13319 img = None # a coherent image_load reads the storage view, not this sampled one
13312 if not coherent: 13320 if not (coherent or storage_only):
13313 ip, img = self.tmp(), self.tmp() 13321 ip, img = self.tmp(), self.tmp()
13314 self.dynamic_sampled_access(ip, f"%{iptr}", iarr, img_idx) 13322 self.dynamic_sampled_access(ip, f"%{iptr}", iarr, img_idx)
13315 self.emit(f"{img} = OpLoad %{itype} {ip}") 13323 self.emit(f"{img} = OpLoad %{itype} {ip}")
@@ -13358,10 +13366,10 @@ class Gen:
13358 iv = self.tmp() 13366 iv = self.tmp()
13359 self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if ncoord == 2 else '%v3int'} {' '.join(ints)}") 13367 self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if ncoord == 2 else '%v3int'} {' '.join(ints)}")
13360 if coherent: 13368 if coherent:
13361 self.image_load_coherent(view_dim, self.sgpr_word(a[2], 1), iv, img_idx, dmask, vdata, d16) 13369 self.image_load_coherent(view_dim, a[2], iv, img_idx, dmask, vdata, d16)
13362 return 13370 return
13363 self.image_load_typed(view_dim, self.sgpr_word(a[2], 1), iv, img, img_idx, 13371 self.image_load_typed(view_dim, a[2], iv, img, img_idx, dmask, vdata,
13364 dmask, vdata, self.cu(0), d16) 13372 lod=self.cu(0), d16=d16)
13365 return 13373 return
13366 else: 13374 else:
13367 smp_idx = self.desc_lookup_sgpr(a[3], 4) 13375 smp_idx = self.desc_lookup_sgpr(a[3], 4)
@@ -13726,13 +13734,15 @@ class Gen:
13726 IMG_ATOMICS_EXTRA = ("image_atomic_swap", "image_atomic_inc", "image_atomic_dec", 13734 IMG_ATOMICS_EXTRA = ("image_atomic_swap", "image_atomic_inc", "image_atomic_dec",
13727 "image_atomic_fmin", "image_atomic_fmax", "image_atomic_fcmpswap") 13735 "image_atomic_fmin", "image_atomic_fmax", "image_atomic_fcmpswap")
13728 13736
13729 # image_store views: dim -> (index, SPIR-V Dim, arrayed, coordinate count). Bindings 8 + 3 * index + class, 13737 # image_store views: dim -> (index, SPIR-V Dim, arrayed, coordinate count). Class 0 = float, 1 = uint, 2 = sint
13730 # class 0 = float, 1 = uint, 2 = sint (Vulkan needs the shader's component type to match the image format). 13738 # (Vulkan needs the shader's component type to match the image format).
13731 STORE_DIMS = {"dim:SQ_RSRC_IMG_2D": (0, "2D", 0, 2), "dim:SQ_RSRC_IMG_2D_ARRAY": (1, "2D", 1, 3), 13739 STORE_DIMS = {"dim:SQ_RSRC_IMG_2D": (0, "2D", 0, 2), "dim:SQ_RSRC_IMG_2D_ARRAY": (1, "2D", 1, 3),
13732 "dim:SQ_RSRC_IMG_3D": (2, "3D", 0, 3), "dim:SQ_RSRC_IMG_1D": (3, "1D", 0, 1)} 13740 "dim:SQ_RSRC_IMG_3D": (2, "3D", 0, 3), "dim:SQ_RSRC_IMG_1D": (3, "1D", 0, 1),
13741 "dim:SQ_RSRC_IMG_1D_ARRAY": (4, "1D", 1, 2)}
13733 # The sampled array of each STORE_DIMS index: its binding in set 0 (assemble declares %images, %images_arr, 13742 # The sampled array of each STORE_DIMS index: its binding in set 0 (assemble declares %images, %images_arr,
13734 # %images_3d and %images_1d there). Typed image_load reads UINT/SINT images through uint/sint aliases of it. 13743 # %images_3d and %images_1d there). Typed image_load reads UINT/SINT images through uint/sint aliases of it.
13735 SAMPLED_BINDINGS = {0: 0, 1: 3, 2: 6, 3: 5} 13744 SAMPLED_BINDINGS = {0: 0, 1: 3, 2: 6, 3: 5}
13745 R32_UINT = next(code for code, name in GFX10_FORMATS.items() if name == "GFX10_FORMAT_32_UINT")
13736 INT_FORMATS = None # (uint mask words, sint mask words) over the 512 GFX10 formats 13746 INT_FORMATS = None # (uint mask words, sint mask words) over the 512 GFX10 formats
13737 13747
13738 @classmethod 13748 @classmethod
@@ -13813,14 +13823,114 @@ class Gen:
13813 self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}") 13823 self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}")
13814 return half 13824 return half
13815 13825
13816 def image_load_typed(self, dim, t1, iv, img, idx, dmask, vdata, lod, d16=False): 13826 @staticmethod
13817 def fetch(image, _cls, ty): 13827 def tsharp_regs(tsharp):
13828 """The same descriptor register group can be printed as a range or a list."""
13829 if tsharp["k"] == "slist":
13830 return tuple(tsharp["r"][:8])
13831 if tsharp["k"] == "sgpr":
13832 return tuple(range(tsharp["r"], tsharp["r"] + 8))
13833 return ()
13834
13835 def synthetic_uav(self, tsharp):
13836 """Decode the private volume/packed UAV tag (gfx10_descriptors.h), not ordinary hardware metadata."""
13837 t4 = self.sgpr_word(tsharp, 4)
13838 t7 = self.sgpr_word(tsharp, 7)
13839 flag, flag_set, tag, tag_set, uav = (self.tmp() for _ in range(5))
13840 self.emit(f"{flag} = OpBitwiseAnd %uint {t4} {self.cu(0x80000000)}")
13841 self.emit(f"{flag_set} = OpINotEqual %bool {flag} {self.cu(0)}")
13842 self.emit(f"{tag} = OpBitwiseAnd %uint {t7} {self.cu(0xff800000)}")
13843 self.emit(f"{tag_set} = OpIEqual %bool {tag} {self.cu(0xd7800000)}")
13844 self.emit(f"{uav} = OpLogicalAnd %bool {flag_set} {tag_set}")
13845 return uav, t7
13846
13847 def packed_uav(self, tsharp):
13848 uav, t7 = self.synthetic_uav(tsharp)
13849 return self.emit_land(uav, self.emit_ne0(self.emit_and(t7, 0x00400000)))
13850
13851 def image_fetch(self, img, coords, lod, ty, volume=None):
13852 """Vulkan applies Z slicing to storage views only. Rebase all sampled aliases of a volume UAV."""
13853 if volume is None:
13818 res = self.tmp() 13854 res = self.tmp()
13819 self.emit(f"{res} = OpImageFetch {ty} {image} {iv} Lod {lod}") 13855 self.emit(f"{res} = OpImageFetch {ty} {img} {coords} Lod {lod}")
13820 return res 13856 return res
13857 uav, t7 = volume
13858 offset, last, z, relative, absolute, coord = (self.tmp() for _ in range(6))
13859 self.emit(f"{offset} = OpBitFieldUExtract %uint {t7} {self.cu(0)} {self.cu(11)}")
13860 self.emit(f"{last} = OpBitFieldUExtract %uint {t7} {self.cu(11)} {self.cu(11)}")
13861 self.emit(f"{z} = OpCompositeExtract %int {coords} 2")
13862 self.emit(f"{relative} = OpBitcast %uint {z}")
13863 self.emit(f"{absolute} = OpIAdd %int {z} {self.as_int(offset)}")
13864 self.emit(f"{coord} = OpSelect %int {uav} {absolute} {z}")
13865 in_slice, not_uav, valid = (self.tmp() for _ in range(3))
13866 self.emit(f"{in_slice} = OpULessThanEqual %bool {relative} {last}")
13867 in_view = in_slice
13868 if lod != self.cu(0):
13869 base_mip, in_view = self.tmp(), self.tmp()
13870 self.emit(f"{base_mip} = OpIEqual %bool {lod} {self.as_int(self.cu(0))}")
13871 self.emit(f"{in_view} = OpLogicalAnd %bool {in_slice} {base_mip}")
13872 self.emit(f"{not_uav} = OpLogicalNot %bool {uav}")
13873 self.emit(f"{valid} = OpLogicalOr %bool {not_uav} {in_view}")
13874 body, miss, end = (self.tmp() + s for s in ("_fetch", "_oob", "_end"))
13875 adjusted, texel, zero, result = (self.tmp() for _ in range(4))
13876 self.emit(f"OpSelectionMerge {end} None")
13877 self.emit(f"OpBranchConditional {valid} {body} {miss}")
13878 self.emit(f"{body} = OpLabel")
13879 self.emit(f"{adjusted} = OpCompositeInsert %v3int {coord} {coords} 2")
13880 self.emit(f"{texel} = OpImageFetch {ty} {img} {adjusted} Lod {lod}")
13881 self.emit(f"OpBranch {end}")
13882 self.emit(f"{miss} = OpLabel")
13883 scalar = {"%v4float": "%f0", "%v4uint_st": self.cu(0), "%v4int_st": None}[ty]
13884 if scalar is None:
13885 scalar = self.as_int(self.cu(0))
13886 self.emit(f"{zero} = OpCompositeConstruct {ty} {' '.join([scalar] * 4)}")
13887 self.emit(f"OpBranch {end}")
13888 self.emit(f"{end} = OpLabel")
13889 self.emit(f"{result} = OpPhi {ty} {texel} {body} {zero} {miss}")
13890 return result
13891
13892 def image_load_typed(self, dim, tsharp, iv, img, idx, dmask, vdata, *, lod, d16=False):
13893 """Supply the fetch to the shared typed-image dispatch used by both loads and gathers."""
13894 t1 = self.sgpr_word(tsharp, 1)
13895 di = self.STORE_DIMS[dim][0]
13896 volume = self.synthetic_uav(tsharp) if di == 2 else None
13897 atomic_read = (volume is not None and self.tsharp_regs(tsharp) in self.atomic_volume_tsharps and
13898 lod == self.cu(0))
13899 if img is None:
13900 return self.image_load_storage(dim, tsharp, iv, idx, dmask, vdata, d16)
13901
13902 def fetch(image, cls, ty):
13903 if cls != 1 or not atomic_read:
13904 return self.image_fetch(image, iv, lod, ty, volume)
13905 # Read a tagged logical R32_UINT volume UAV through the same formatted storage view as its atomics.
13906 # Other uint descriptors (notably SRVs) must use the sampled alias, not a potentially shorter array.
13907 self.uses_storage3d = True
13908 fmt, r32, coherent = self.tmp(), self.tmp(), self.tmp()
13909 self.emit(f"{fmt} = OpBitFieldUExtract %uint {t1} {self.cu(20)} {self.cu(9)}")
13910 self.emit(f"{r32} = OpIEqual %bool {fmt} {self.cu(self.R32_UINT)}")
13911 self.emit(f"{coherent} = OpLogicalAnd %bool {r32} {volume[0]}")
13912 storage, sampled, fetch_done, end = (
13913 self.tmp() + suffix for suffix in ("_storage", "_sampled", "_fetch_done", "_read_end"))
13914 self.emit(f"OpSelectionMerge {end} None")
13915 self.emit(f"OpBranchConditional {coherent} {storage} {sampled}")
13916 self.emit(f"{storage} = OpLabel")
13917 ip, im, raw, result = (self.tmp() for _ in range(4))
13918 self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}")
13919 self.emit(f"{im} = OpLoad %simg3d_u {ip}")
13920 self.emit(f"{raw} = OpImageRead {ty} {im} {iv}")
13921 self.emit(f"OpBranch {end}")
13922 self.emit(f"{sampled} = OpLabel")
13923 texel = self.image_fetch(image, iv, lod, ty, volume)
13924 self.emit(f"OpBranch {fetch_done}")
13925 self.emit(f"{fetch_done} = OpLabel")
13926 self.emit(f"OpBranch {end}")
13927 self.emit(f"{end} = OpLabel")
13928 self.emit(f"{result} = OpPhi {ty} {raw} {storage} {texel} {fetch_done}")
13929 return result
13930
13821 self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch) 13931 self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch)
13822 13932
13823 def image_load_coherent(self, dim, t1, iv, idx, dmask, vdata, d16): 13933 def image_load_coherent(self, dim, tsharp, iv, idx, dmask, vdata, d16):
13824 """image_load with glc: a coherent read. On GFX10 a device-scope load is glc + dlc and a device-scope store 13934 """image_load with glc: a coherent read. On GFX10 a device-scope load is glc + dlc and a device-scope store
13825 glc (Mesa ac_get_hw_cache_flags maps ACCESS_COHERENT to exactly these bits); the POPS pixel shaders read and 13935 glc (Mesa ac_get_hw_cache_flags maps ACCESS_COHERENT to exactly these bits); the POPS pixel shaders read and
13826 write their ordered images that way. Through the sampled array (image_load_typed) the read could not see 13936 write their ordered images that way. Through the sampled array (image_load_typed) the read could not see
@@ -13828,10 +13938,25 @@ class Gen:
13828 sections only makes Coherent memory visible (Vulkan memory model, fragment shader interlock). So the read 13938 sections only makes Coherent memory visible (Vulkan memory model, fragment shader interlock). So the read
13829 goes through the storage view the stores write (OpImageRead, StorageImageReadWithoutFormat), and the 13939 goes through the storage view the stores write (OpImageRead, StorageImageReadWithoutFormat), and the
13830 storage views are decorated Coherent (assemble).""" 13940 storage views are decorated Coherent (assemble)."""
13831 di = self.STORE_DIMS[dim][0]
13832 self.uses_store_views.add(di)
13833 self.reads_store_views = True
13834 self.coherent_images = True 13941 self.coherent_images = True
13942 self.image_load_storage(dim, tsharp, iv, idx, dmask, vdata, d16)
13943
13944 def image_load_storage(self, dim, tsharp, iv, idx, dmask, vdata, d16):
13945 di = self.STORE_DIMS[dim][0]
13946 self.uses_store_reads.add(di)
13947 if di >= 2:
13948 # Packed RGB9E5 has no float storage view. Untagged 3D SRVs may also have an index beyond
13949 # the shorter storage arrays; the coherent operation needs a UAV, not a sampled descriptor.
13950 unsupported = self.packed_uav(tsharp)
13951 if di == 2:
13952 tagged, _ = self.synthetic_uav(tsharp)
13953 untagged, reject = self.tmp(), self.tmp()
13954 self.emit(f"{untagged} = OpLogicalNot %bool {tagged}")
13955 self.emit(f"{reject} = OpLogicalOr %bool {untagged} {unsupported}")
13956 unsupported = reject
13957 safe = self.tmp()
13958 self.emit(f"{safe} = OpSelect %uint {unsupported} {self.cu(0)} {idx}")
13959 idx = safe
13835 13960
13836 def view(cls): 13961 def view(cls):
13837 ip, im = self.tmp(), self.tmp() 13962 ip, im = self.tmp(), self.tmp()
@@ -13843,7 +13968,7 @@ class Gen:
13843 res = self.tmp() 13968 res = self.tmp()
13844 self.emit(f"{res} = OpImageRead {ty} {image} {iv}") 13969 self.emit(f"{res} = OpImageRead {ty} {image} {iv}")
13845 return res 13970 return res
13846 self.image_read_typed(dim, t1, None, idx, dmask, vdata, d16, read, view) 13971 self.image_read_typed(dim, self.sgpr_word(tsharp, 1), None, idx, dmask, vdata, d16, read, view)
13847 13972
13848 def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read, view=None): 13973 def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read, view=None):
13849 """Read an image using the component type selected by FORMAT in T# word 1. 13974 """Read an image using the component type selected by FORMAT in T# word 1.
@@ -13908,29 +14033,25 @@ class Gen:
13908 self.emit(f"{w} = OpBitwiseOr %uint {xs[i]} {hi}") 14033 self.emit(f"{w} = OpBitwiseOr %uint {xs[i]} {hi}")
13909 self.dst(dest, w) 14034 self.dst(dest, w)
13910 14035
13911 def read_integer(cls, ty): 14036 def read_view(cls, ty):
13912 im = view(cls) 14037 texel = read(view(cls), cls, ty)
13913 b = self.tmp() 14038 b = self.tmp()
13914 r = read(im, cls, ty) 14039 self.emit(f"{b} = OpBitcast %v4uint_st {texel}")
13915 self.emit(f"{b} = OpBitcast %v4uint_st {r}")
13916 write(b, cls) 14040 write(b, cls)
13917 14041
13918 self.emit(f"OpSelectionMerge {L['e2']} None") 14042 self.emit(f"OpSelectionMerge {L['e2']} None")
13919 self.emit(f"OpBranchConditional {use_s} {L['s']} {L['rest']}") 14043 self.emit(f"OpBranchConditional {use_s} {L['s']} {L['rest']}")
13920 self.emit(f"{L['s']} = OpLabel") 14044 self.emit(f"{L['s']} = OpLabel")
13921 read_integer(2, "%v4int_st") 14045 read_view(2, "%v4int_st")
13922 self.emit(f"OpBranch {L['e2']}") 14046 self.emit(f"OpBranch {L['e2']}")
13923 self.emit(f"{L['rest']} = OpLabel") 14047 self.emit(f"{L['rest']} = OpLabel")
13924 self.emit(f"OpSelectionMerge {L['e3']} None") 14048 self.emit(f"OpSelectionMerge {L['e3']} None")
13925 self.emit(f"OpBranchConditional {use_u} {L['u']} {L['f']}") 14049 self.emit(f"OpBranchConditional {use_u} {L['u']} {L['f']}")
13926 self.emit(f"{L['u']} = OpLabel") 14050 self.emit(f"{L['u']} = OpLabel")
13927 read_integer(1, "%v4uint_st") 14051 read_view(1, "%v4uint_st")
13928 self.emit(f"OpBranch {L['e3']}") 14052 self.emit(f"OpBranch {L['e3']}")
13929 self.emit(f"{L['f']} = OpLabel") 14053 self.emit(f"{L['f']} = OpLabel")
13930 res = read(view(0), 0, "%v4float") 14054 read_view(0, "%v4float")
13931 b = self.tmp()
13932 self.emit(f"{b} = OpBitcast %v4uint_st {res}")
13933 write(b, 0)
13934 self.emit(f"OpBranch {L['e3']}") 14055 self.emit(f"OpBranch {L['e3']}")
13935 self.emit(f"{L['e3']} = OpLabel") 14056 self.emit(f"{L['e3']} = OpLabel")
13936 self.emit(f"OpBranch {L['e2']}") 14057 self.emit(f"OpBranch {L['e2']}")
@@ -14022,6 +14143,11 @@ class Gen:
14022 self.emit(f"{v4u} = OpCompositeConstruct %v4uint_st {' '.join(uv)}") 14143 self.emit(f"{v4u} = OpCompositeConstruct %v4uint_st {' '.join(uv)}")
14023 self.emit(f"{v4s} = OpCompositeConstruct %v4int_st {' '.join(sv)}") 14144 self.emit(f"{v4s} = OpCompositeConstruct %v4int_st {' '.join(sv)}")
14024 act = self.active_b() 14145 act = self.active_b()
14146 if di >= 2: # no writes to the shared fallback or to R32_UINT-backed logical RGB9E5
14147 found, unpacked = self.tmp(), self.tmp()
14148 self.emit(f"{found} = OpINotEqual %bool {idx} {self.cu(0)}")
14149 self.emit(f"{unpacked} = OpLogicalNot %bool {self.packed_uav(a[2])}")
14150 act = self.emit_land(act, self.emit_land(found, unpacked))
14025 L = {k: self.tmp() + "_" + k for k in ("do", "end", "s", "rest", "e2", "u", "f", "e3")} 14151 L = {k: self.tmp() + "_" + k for k in ("do", "end", "s", "rest", "e2", "u", "f", "e3")}
14026 14152
14027 def write(cls, texel): 14153 def write(cls, texel):
@@ -14090,7 +14216,7 @@ class Gen:
14090 vals[i] = kept 14216 vals[i] = kept
14091 return vals + [lv] 14217 return vals + [lv]
14092 14218
14093 def emit_image_atomic_extra(self, op, ptr_ty, arr_var, idx, iv, vdata, mods): 14219 def emit_image_atomic_extra(self, op, ptr_ty, arr_var, idx, iv, vdata, mods, *, volume_active=None):
14094 """Lower 32-bit image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap} on an r32ui storage image (2D or 3D). 14220 """Lower 32-bit image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap} on an r32ui storage image (2D or 3D).
14095 Inactive lanes skip the op and preserve vdata. CAS loops use OpAtomicLoad (valid on Image pointers) + 14221 Inactive lanes skip the op and preserve vdata. CAS loops use OpAtomicLoad (valid on Image pointers) +
14096 OpAtomicCompareExchange, requiring no shader float atomic extension.""" 14222 OpAtomicCompareExchange, requiring no shader float atomic extension."""
@@ -14099,7 +14225,7 @@ class Gen:
14099 raise Unsupported(op + " operands") 14225 raise Unsupported(op + " operands")
14100 val = self.load_reg("vgpr", vdata["r"]) 14226 val = self.load_reg("vgpr", vdata["r"])
14101 cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_fcmpswap" else None 14227 cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_fcmpswap" else None
14102 act = self.active_b() 14228 act = self.active_b() if volume_active is None else volume_active
14103 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" 14229 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end"
14104 self.emit(f"OpSelectionMerge {lbl_end} None") 14230 self.emit(f"OpSelectionMerge {lbl_end} None")
14105 self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") 14231 self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}")
@@ -14205,31 +14331,42 @@ class Gen:
14205 if op == "image_store": 14331 if op == "image_store":
14206 self.image_store(a, mods, dim) 14332 self.image_store(a, mods, dim)
14207 return 14333 return
14208 if op == "image_load_mip" and "glc" in mods: 14334 if op == "image_load_mip":
14209 # A coherent read of one mip: image_load_coherent reads a storage view, which has one level. 14335 if "glc" in mods:
14210 raise Unsupported("image_load_mip glc") 14336 raise Unsupported("image_load_mip glc") # the coherent storage view has only one mip
14211 if op == "image_load_mip" and dim == "dim:SQ_RSRC_IMG_3D" and "a16" not in mods: 14337 # x, y[, z], mip. All sampled aliases fetch that LOD; only a tagged volume UAV restricts it to zero.
14212 # x, y, z, mip from a 3D sampled image (binding 6) 14338 is3d = dim == "dim:SQ_RSRC_IMG_3D"
14213 if "d16" in mods and ("tfe" in mods or "lwe" in mods): 14339 ncoord = 3 if is3d else 2
14340 packed = "a16" in mods
14341 status = "tfe" in mods or "lwe" in mods
14342 if (not is3d and dim != "dim:SQ_RSRC_IMG_2D") or (packed and (is3d or status)):
14343 raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1])
14344 if is3d and status and "d16" in mods:
14214 raise Unsupported("image_load_mip d16 status") 14345 raise Unsupported("image_load_mip d16 status")
14215 vdata, addr = a[0], self.addr_regs(a[1]) 14346 vdata, addr = a[0], self.addr_regs(a[1])
14216 if len(addr) < 4: 14347 words = 2 if packed else ncoord + 1
14348 if len(addr) < words:
14217 raise Unsupported("image_load_mip coords") 14349 raise Unsupported("image_load_mip coords")
14218 idx = self.desc_lookup_sgpr(a[2], 8) 14350 idx = self.desc_lookup_sgpr(a[2], 8)
14219 self.uses_tex_3d = True
14220 ip, img, iv = self.tmp(), self.tmp(), self.tmp() 14351 ip, img, iv = self.tmp(), self.tmp(), self.tmp()
14221 self.dynamic_sampled_access(ip, "%_ptr_UC_img3", "%images_3d", idx) 14352 if is3d:
14222 self.emit(f"{img} = OpLoad %img3d {ip}") 14353 self.uses_tex_3d = True
14223 xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:4]] 14354 self.dynamic_sampled_access(ip, "%_ptr_UC_img3", "%images_3d", idx)
14224 self.emit(f"{iv} = OpCompositeConstruct %v3int {xs[0]} {xs[1]} {xs[2]}") 14355 self.emit(f"{img} = OpLoad %img3d {ip}")
14356 else:
14357 self.dynamic_sampled_access(ip, "%_ptr_UC_img", "%images", idx)
14358 self.emit(f"{img} = OpLoad %img2d {ip}")
14359 raw = [self.load_reg("vgpr", r) for r in addr[:words]]
14360 if packed:
14361 raw = self.unpack_image_a16_uints(raw)
14362 *coords, lod = [self.as_int(c) for c in raw[:ncoord + 1]]
14363 self.emit(f"{iv} = OpCompositeConstruct %v{ncoord}int {' '.join(coords)}")
14225 dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") 14364 dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1")
14226 self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, idx, int(dm.split(":")[1], 0), 14365 self.image_load_typed(dim, a[2], iv, img, idx, int(dm.split(":")[1], 0), vdata,
14227 vdata, xs[3], d16="d16" in mods) 14366 lod=lod, d16="d16" in mods)
14228 return 14367 return
14229 packed_mip = op == "image_load_mip" and "tfe" not in mods and "lwe" not in mods
14230 if ((dim != "dim:SQ_RSRC_IMG_2D" and not (is3d_atomic or array_query)) 14368 if ((dim != "dim:SQ_RSRC_IMG_2D" and not (is3d_atomic or array_query))
14231 or ("a16" in mods and not (is_atomic or packed_mip)) 14369 or ("a16" in mods and not is_atomic) or "d16" in mods):
14232 or ("d16" in mods and op != "image_load_mip")):
14233 raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) 14370 raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1])
14234 vdata, addr = a[0], self.addr_regs(a[1]) 14371 vdata, addr = a[0], self.addr_regs(a[1])
14235 idx = self.desc_lookup_sgpr(a[2], 8) 14372 idx = self.desc_lookup_sgpr(a[2], 8)
@@ -14250,23 +14387,31 @@ class Gen:
14250 return [self.as_int(c) for c in raw[:nc]] 14387 return [self.as_int(c) for c in raw[:nc]]
14251 14388
14252 if is_atomic: 14389 if is_atomic:
14253 # 2D (binding 4) or 3D (binding 7) r32ui storage image atomics. 14390 # 2D (binding 4) or 3D (binding 7) r32ui atomics. For tagged volumes, only a
14254 # Guard OpAccessChain / OpImageTexelPointer / OpAtomic* inside `if (active)` so inactive lanes never 14391 # real R32_UINT UAV with a nonzero descriptor and an active lane may write.
14255 # execute spurious RMWs or dereference uninitialized descriptors/coordinates.
14256 if is3d_atomic: 14392 if is3d_atomic:
14257 self.uses_storage3d = True 14393 self.uses_storage3d = True
14258 coords = atomic_coords(3) 14394 coords = atomic_coords(3)
14259 iv = self.tmp() 14395 iv = self.tmp()
14260 self.emit(f"{iv} = OpCompositeConstruct %v3int {coords[0]} {coords[1]} {coords[2]}") 14396 self.emit(f"{iv} = OpCompositeConstruct %v3int {coords[0]} {coords[1]} {coords[2]}")
14261 ptr_ty, arr_var = "%_ptr_UC_simg3", "%simages3d" 14397 ptr_ty, arr_var = "%_ptr_UC_simg3", "%simages3d"
14398 found, fmt, r32 = (self.tmp() for _ in range(3))
14399 self.emit(f"{found} = OpINotEqual %bool {idx} {self.cu(0)}")
14400 t1 = self.sgpr_word(a[2], 1)
14401 self.emit(f"{fmt} = OpBitFieldUExtract %uint {t1} {self.cu(20)} {self.cu(9)}")
14402 self.emit(f"{r32} = OpIEqual %bool {fmt} {self.cu(self.R32_UINT)}")
14403 uav, _ = self.synthetic_uav(a[2])
14404 run = self.emit_land(self.active_b(), self.emit_land(found, self.emit_land(r32, uav)))
14262 else: 14405 else:
14263 self.uses_storage = True 14406 self.uses_storage = True
14264 coords = atomic_coords(2) 14407 coords = atomic_coords(2)
14265 iv = self.tmp() 14408 iv = self.tmp()
14266 self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}") 14409 self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}")
14267 ptr_ty, arr_var = "%_ptr_UC_simg", "%simages" 14410 ptr_ty, arr_var = "%_ptr_UC_simg", "%simages"
14411 run = self.active_b()
14268 if op in self.IMG_ATOMICS_EXTRA: 14412 if op in self.IMG_ATOMICS_EXTRA:
14269 self.emit_image_atomic_extra(op, ptr_ty, arr_var, idx, iv, vdata, mods) 14413 self.emit_image_atomic_extra(op, ptr_ty, arr_var, idx, iv, vdata, mods,
14414 volume_active=run)
14270 return 14415 return
14271 if op == "image_atomic_cmpswap": 14416 if op == "image_atomic_cmpswap":
14272 if vdata["k"] != "vgpr" or vdata.get("n", 1) != 2: 14417 if vdata["k"] != "vgpr" or vdata.get("n", 1) != 2:
@@ -14278,7 +14423,7 @@ class Gen:
14278 # is handled separately. 14423 # is handled separately.
14279 val = self.load_reg("vgpr", vdata["r"]) 14424 val = self.load_reg("vgpr", vdata["r"])
14280 cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_cmpswap" else None 14425 cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_cmpswap" else None
14281 act = self.active_b() 14426 act = run
14282 do, end = self.tmp() + "_do", self.tmp() + "_end" 14427 do, end = self.tmp() + "_do", self.tmp() + "_end"
14283 self.emit(f"OpSelectionMerge {end} None") 14428 self.emit(f"OpSelectionMerge {end} None")
14284 self.emit(f"OpBranchConditional {act} {do} {end}") 14429 self.emit(f"OpBranchConditional {act} {do} {end}")
@@ -14318,19 +14463,6 @@ class Gen:
14318 self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, u) 14463 self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, u)
14319 out += 1 14464 out += 1
14320 return 14465 return
14321 # image_load_mip: x, y, mip, with the same typed SRV as image_load.
14322 packed = "a16" in mods
14323 if len(addr) < (2 if packed else 3):
14324 raise Unsupported("image_load_mip coords")
14325 if packed:
14326 words = [self.load_reg("vgpr", r) for r in addr[:2]]
14327 xs = [self.as_int(c) for c in self.unpack_image_a16_uints(words)[:3]]
14328 else:
14329 xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:3]]
14330 iv = self.tmp()
14331 self.emit(f"{iv} = OpCompositeConstruct %v2int {xs[0]} {xs[1]}")
14332 self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, idx, dmask, vdata, xs[2], d16="d16" in mods)
14333
14334 14466
14335 def interp_pair_src(self, op, a, ins): 14467 def interp_pair_src(self, op, a, ins):
14336 """SHADER-177: the VGPR source of a v_interp_p1/p2 is the barycentric coordinate that op interpolates 14468 """SHADER-177: the VGPR source of a v_interp_p1/p2 is the barycentric coordinate that op interpolates
@@ -15359,6 +15491,7 @@ def insert_late_constants(gen, out, written):
15359 15491
15360 15492
15361def assemble(gen): 15493def assemble(gen):
15494 store_dims = gen.uses_store_views | gen.uses_store_reads
15362 vs = gen.stage == "vs" 15495 vs = gen.stage == "vs"
15363 cs = gen.stage == "cs" 15496 cs = gen.stage == "cs"
15364 ms = gen.stage == "ms" 15497 ms = gen.stage == "ms"
@@ -15411,11 +15544,12 @@ def assemble(gen):
15411 [f"%ms_out_f16h{n}_{h}" for n in ms_halves for h in (0, 1)])) if ms else []) + ( 15544 [f"%ms_out_f16h{n}_{h}" for n in ms_halves for h in (0, 1)])) if ms else []) + (
15412 ["%x_buf"] if gen.emulate or gen.bar_rounds and not gen.bar_counts_in_lds() else []) + ( 15545 ["%x_buf"] if gen.emulate or gen.bar_rounds and not gen.bar_counts_in_lds() else []) + (
15413 ([("%gs_in_pos" if sv == 1 else f"%gs_in{r}") for r, sv in gen.gs["in"]] + 15546 ([("%gs_in_pos" if sv == 1 else f"%gs_in{r}") for r, sv in gen.gs["in"]] +
15414 [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + (["%fmt_uint_mask", "%fmt_sint_mask"] if gen.uses_store_views or gen.uses_int_fetch else []) + \ 15547 [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + (
15415 (["%fmt_norm_mask", "%fmt_f32_mask"] if gen.uses_d16_image else []) + \ 15548 ["%fmt_uint_mask", "%fmt_sint_mask"] if store_dims or gen.uses_int_fetch else []) + (
15549 ["%fmt_norm_mask", "%fmt_f32_mask"] if gen.uses_d16_image else []) + \
15416 (["%fmt_size_tab"] if gen.uses_fmt_size else []) + \ 15550 (["%fmt_size_tab"] if gen.uses_fmt_size else []) + \
15417 (["%fmt_desc_tab", "%fmt_norm_rep_tab"] if gen.uses_fmt_tables else []) + \ 15551 (["%fmt_desc_tab", "%fmt_norm_rep_tab"] if gen.uses_fmt_tables else []) + \
15418 [f"%stv{c}_{d}" for d in sorted(gen.uses_store_views) for c in range(3)] + \ 15552 [f"%stv{c}_{d}" for d in sorted(store_dims) for c in range(3)] + \
15419 [f"%itx{c}_{d}" for d in sorted(gen.uses_int_fetch) for c in (1, 2)] 15553 [f"%itx{c}_{d}" for d in sorted(gen.uses_int_fetch) for c in (1, 2)]
15420 psb = gen.uses_psb 15554 psb = gen.uses_psb
15421 tex = gen.uses_tex 15555 tex = gen.uses_tex
@@ -15490,10 +15624,10 @@ def assemble(gen):
15490 caps.append("StorageImageArrayDynamicIndexing") 15624 caps.append("StorageImageArrayDynamicIndexing")
15491 if gen.uses_store_views: 15625 if gen.uses_store_views:
15492 caps.append("StorageImageWriteWithoutFormat") # shaderStorageImageWriteWithoutFormat 15626 caps.append("StorageImageWriteWithoutFormat") # shaderStorageImageWriteWithoutFormat
15493 if gen.reads_store_views: 15627 if gen.uses_store_reads:
15494 caps.append("StorageImageReadWithoutFormat") # shaderStorageImageReadWithoutFormat: coherent image_load 15628 caps.append("StorageImageReadWithoutFormat") # shaderStorageImageReadWithoutFormat
15495 if 3 in gen.uses_store_views: 15629 if store_dims.intersection((3, 4)):
15496 caps.append("Image1D") 15630 caps.append("Image1D")
15497 if vs: 15631 if vs:
15498 caps.append("DrawParameters") # BaseVertex / BaseInstance (shaderDrawParameters), see the seeding of v0 / v3 15632 caps.append("DrawParameters") # BaseVertex / BaseInstance (shaderDrawParameters), see the seeding of v0 / v3
15499 if gsx: 15633 if gsx:
@@ -15744,7 +15878,7 @@ def assemble(gen):
15744 types.append(f"{fn_type} = OpTypeFunction %uint " + " ".join(["%uint"] * arity)) 15878 types.append(f"{fn_type} = OpTypeFunction %uint " + " ".join(["%uint"] * arity))
15745 # dedupe_types keeps the first uvec4 it meets: when the typed-image types follow, declare the ballot type after 15879 # dedupe_types keeps the first uvec4 it meets: when the typed-image types follow, declare the ballot type after
15746 # them, so a shader that gains a ballot keeps the name %v4uint_st (SHADER-1016). 15880 # them, so a shader that gains a ballot keeps the name %v4uint_st (SHADER-1016).
15747 st_types = gen.uses_store_views or gen.uses_int_fetch or gen.uses_d16_image 15881 st_types = bool(store_dims or gen.uses_int_fetch or gen.uses_d16_image)
15748 if gen.uses_ballot and not st_types: 15882 if gen.uses_ballot and not st_types:
15749 types.append("%v4uint_bal = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 15883 types.append("%v4uint_bal = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4
15750 if gen.uses_bvh and not any(t.startswith("%v3float = ") for t in types): 15884 if gen.uses_bvh and not any(t.startswith("%v3float = ") for t in types):
@@ -15783,7 +15917,7 @@ def assemble(gen):
15783 sizes = [Gen.FORMATS[c][0] if c in Gen.FORMATS else 0 for c in range(128)] 15917 sizes = [Gen.FORMATS[c][0] if c in Gen.FORMATS else 0 for c in range(128)]
15784 types += [f"%fmt_size_arr = OpTypeArray %uint {gen.cu(128)}", 15918 types += [f"%fmt_size_arr = OpTypeArray %uint {gen.cu(128)}",
15785 "%_ptr_Private_fmt_size = OpTypePointer Private %fmt_size_arr"] 15919 "%_ptr_Private_fmt_size = OpTypePointer Private %fmt_size_arr"]
15786 if not (gen.uses_store_views or gen.uses_int_fetch or gen.uses_d16_image): 15920 if not (store_dims or gen.uses_int_fetch or gen.uses_d16_image):
15787 types += ["%_ptr_Private_uint = OpTypePointer Private %uint"] 15921 types += ["%_ptr_Private_uint = OpTypePointer Private %uint"]
15788 types += ["%fmt_size_init = OpConstantComposite %fmt_size_arr " + " ".join(gen.cu(v) for v in sizes)] 15922 types += ["%fmt_size_init = OpConstantComposite %fmt_size_arr " + " ".join(gen.cu(v) for v in sizes)]
15789 gvars += ["%fmt_size_tab = OpVariable %_ptr_Private_fmt_size Private %fmt_size_init"] 15923 gvars += ["%fmt_size_tab = OpVariable %_ptr_Private_fmt_size Private %fmt_size_init"]
@@ -15801,7 +15935,7 @@ def assemble(gen):
15801 " ".join(gen.lconsts[v] for v in Gen.fmt_norm_reps())) 15935 " ".join(gen.lconsts[v] for v in Gen.fmt_norm_reps()))
15802 gvars += ["%fmt_desc_tab = OpVariable %_ptr_Private_fmt_desc Private %fmt_desc_init", 15936 gvars += ["%fmt_desc_tab = OpVariable %_ptr_Private_fmt_desc Private %fmt_desc_init",
15803 "%fmt_norm_rep_tab = OpVariable %_ptr_Private_fmt_rep Private %fmt_norm_rep_init"] 15937 "%fmt_norm_rep_tab = OpVariable %_ptr_Private_fmt_rep Private %fmt_norm_rep_init"]
15804 if gen.uses_store_views or gen.uses_int_fetch or gen.uses_d16_image: 15938 if store_dims or gen.uses_int_fetch or gen.uses_d16_image:
15805 u, si = Gen.int_format_masks() 15939 u, si = Gen.int_format_masks()
15806 types += ["%v4uint_st = OpTypeVector %uint 4", "%v4int_st = OpTypeVector %int 4", 15940 types += ["%v4uint_st = OpTypeVector %uint 4", "%v4int_st = OpTypeVector %int 4",
15807 *(["%v4uint_bal = OpTypeVector %uint 4"] if gen.uses_ballot else []), 15941 *(["%v4uint_bal = OpTypeVector %uint 4"] if gen.uses_ballot else []),
@@ -15829,14 +15963,16 @@ def assemble(gen):
15829 dec += [f"OpDecorate %itx{cls}_{di} DescriptorSet 0", 15963 dec += [f"OpDecorate %itx{cls}_{di} DescriptorSet 0",
15830 f"OpDecorate %itx{cls}_{di} Binding {Gen.SAMPLED_BINDINGS[di]}"] 15964 f"OpDecorate %itx{cls}_{di} Binding {Gen.SAMPLED_BINDINGS[di]}"]
15831 gvars += [f"%itx{cls}_{di} = OpVariable %_ptr_UC_rt_itx{cls}_{di} UniformConstant"] 15965 gvars += [f"%itx{cls}_{di} = OpVariable %_ptr_UC_rt_itx{cls}_{di} UniformConstant"]
15832 for di in sorted(gen.uses_store_views): 15966 for di in sorted(store_dims):
15833 _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di) 15967 _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di)
15968 # Keep the runtime's multisample SRV bindings (20–25); 1D-array storage follows them.
15969 base = 26 if di == 4 else 8 + 3 * di
15834 for cls, st in enumerate(("%float", "%uint", "%int")): 15970 for cls, st in enumerate(("%float", "%uint", "%int")):
15835 types += [f"%stimg{cls}_{di} = OpTypeImage {st} {sdim} 0 {arr} 0 2 Unknown", 15971 types += [f"%stimg{cls}_{di} = OpTypeImage {st} {sdim} 0 {arr} 0 2 Unknown",
15836 f"%rt_stv{cls}_{di} = OpTypeRuntimeArray %stimg{cls}_{di}", 15972 f"%rt_stv{cls}_{di} = OpTypeRuntimeArray %stimg{cls}_{di}",
15837 f"%_ptr_UC_rt_stv{cls}_{di} = OpTypePointer UniformConstant %rt_stv{cls}_{di}", 15973 f"%_ptr_UC_rt_stv{cls}_{di} = OpTypePointer UniformConstant %rt_stv{cls}_{di}",
15838 f"%_ptr_UC_stv{cls}_{di} = OpTypePointer UniformConstant %stimg{cls}_{di}"] 15974 f"%_ptr_UC_stv{cls}_{di} = OpTypePointer UniformConstant %stimg{cls}_{di}"]
15839 dec += [f"OpDecorate %stv{cls}_{di} DescriptorSet 0", f"OpDecorate %stv{cls}_{di} Binding {8 + 3 * di + cls}"] 15975 dec += [f"OpDecorate %stv{cls}_{di} DescriptorSet 0", f"OpDecorate %stv{cls}_{di} Binding {base + cls}"]
15840 if gen.coherent_images: 15976 if gen.coherent_images:
15841 dec.append(f"OpDecorate %stv{cls}_{di} Coherent") 15977 dec.append(f"OpDecorate %stv{cls}_{di} Coherent")
15842 gvars += [f"%stv{cls}_{di} = OpVariable %_ptr_UC_rt_stv{cls}_{di} UniformConstant"] 15978 gvars += [f"%stv{cls}_{di} = OpVariable %_ptr_UC_rt_stv{cls}_{di} UniformConstant"]
@@ -17478,6 +17614,11 @@ def translate(path):
17478 check_printed_encodings(path, info) 17614 check_printed_encodings(path, info)
17479 g = Gen(stage, hoist_reg_ptrs=True, cache_active=True) 17615 g = Gen(stage, hoist_reg_ptrs=True, cache_active=True)
17480 g.exec_static_true = not any(writes_exec(i) for i in insns) 17616 g.exec_static_true = not any(writes_exec(i) for i in insns)
17617 g.atomic_volume_tsharps = {g.tsharp_regs(i["args"][2]) for i in insns
17618 if base_op(i["op"]) in (*Gen.IMG_ATOMICS, *Gen.IMG_ATOMICS_EXTRA,
17619 "image_atomic_cmpswap")
17620 and "dim:SQ_RSRC_IMG_3D" in i["mods"]
17621 and len(i["args"]) >= 3 and i["args"][2]["k"] in ("sgpr", "slist")}
17481 if stage in ("vs", "ms"): # --f16-interp-fallback places the decoded halves clear of every param 17622 if stage in ("vs", "ms"): # --f16-interp-fallback places the decoded halves clear of every param
17482 g.param_max = max((int(t[5:]) for i in insns if base_op(i["op"]) == "exp" for t in 17623 g.param_max = max((int(t[5:]) for i in insns if base_op(i["op"]) == "exp" for t in
17483 (i["args"][0].get("t", ""),) if t.startswith("param") and t[5:].isdigit()), default=-1) 17624 (i["args"][0].get("t", ""),) if t.startswith("param") and t[5:].isdigit()), default=-1)