From 7bddb1bce2fa3f257a537f66aeb2a348bd162f16 Mon Sep 17 00:00:00 2001 From: SweatierKey <53280918+SweatierKey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:05:09 +0100 Subject: [PATCH 1/2] rdna2spirv: demand-driven %fmt_dec_dyn for 1/2/3-component buffer_load_format --- docs/design.md | 2 +- tests/semantic/test_format_decode_table.py | 88 ++++++++++++++ tests/test_rdna2spirv_decode.py | 13 +++ tools/rdna2spirv.py | 130 ++++++++++++++++----- 4 files changed, 205 insertions(+), 28 deletions(-) diff --git a/docs/design.md b/docs/design.md index 3f2d522517..c446e474c5 100644 --- a/docs/design.md +++ b/docs/design.md @@ -297,7 +297,7 @@ How the generated SPIR-V expects the runtime to work: | Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | | Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm, and, since 2026-11-22, the other GFX10 buffer codes 1–77 (every USCALED/SSCALED, 10_11_11 and 11_11_10 FLOAT, the 10_10_10_2 and 2_10_10_10 families, 8_8_8_8 and 16_16_16_16 SINT and SCALED; see *Typed buffer formats*). Others (code 0 and 78 up) give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | | Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). | -| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function per output component (`%fmt_dec_c0`…`%fmt_dec_c3`) reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Now the four functions hold 565 instructions and no branch, and that module is 56,763 bytes. The decode functions take the format code and the element's four dwords as a `v4uint`, so their function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared-per-component shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | +| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: `buffer_load_format_xyzw` calls one shared function per output component (`%fmt_dec_c0`…`%fmt_dec_c3`), while 1/2/3-component loads (`_x`, `_xy`, `_xyz`, and `_d16_x`/`_xy`/`_xyz`) call one shared dynamic-channel function `%fmt_dec_dyn(fmt, words, chan)` per output component using `chan = DST_SEL & 3` (decoding only 1, 2, or 3 channels instead of all 4, and omitting `%fmt_dec_c0`…`%fmt_dec_c3` when no 4-component load is present). Each function reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Now the four `%fmt_dec_c*` functions hold 565 instructions and no branch (56,763 bytes for a single `_xyzw`), and `%fmt_dec_dyn` holds a single branch-free component decode for `<4`-component loads. The decode functions take the format code and the element's four dwords as a `v4uint`, so their function types (`%fn_fmt_dec`, `%fn_fmt_dec_dyn`) have structures of their own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass `spirv-val`, and the 15,103 shaders without a run-time FORMAT come out byte for byte identical. The values are unchanged: every one of the 128 codes gives the same words as the branch search across `_xyzw`, `_xyz`, `_xy`, and `_x` (including all 8 `DST_SEL` values, in-bounds and out-of-bounds), checked by `tests/semantic/test_format_decode_table.py` and `tests/test_rdna2spirv_decode.py`, and GPU-checked on NVIDIA GeForce RTX 5070 Ti (driver 616.92, Windows 11) across all 7 format compute fixtures (`cs_buf_swizzle`, `cs_fmt_1010102`, `cs_fmt_int_narrow`, `cs_fmt_sint32`, `cs_fmt_all`, `cs_fmt_xy_xyz`, `cs_fmt_d16_xyz`: 816/816 readback words exact). The old translation was also confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | | 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | | `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | | Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). | diff --git a/tests/semantic/test_format_decode_table.py b/tests/semantic/test_format_decode_table.py index f868b7a4c3..ab36d651f6 100644 --- a/tests/semantic/test_format_decode_table.py +++ b/tests/semantic/test_format_decode_table.py @@ -120,6 +120,94 @@ def test_the_decode_is_small(self): # instructions and 306 branches in the module of a shader with one dynamic-format load. self.assertLess(count, 900, f"the decode is {count} instructions") + def test_narrow_loads_use_demand_driven_dynamic_channel_decode(self): + # 1/2/3-component dynamic-format loads decode only the N channels selected by DST_SEL via %fmt_dec_dyn + # and do not emit %fmt_dec_c0..c3 when no 4-component load is present. + for suffix, ncomp, dst in (("x", 1, "v2"), ("xy", 2, "v[2:3]"), ("xyz", 3, "v[2:4]")): + lines = [f"s_mov_b32 s0, {BASE:#x}", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100", + f"s_mov_b32 s3, {1 << 12 | 0x30000FAC:#x}", "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", "v_mov_b32 v4, 0", "v_mov_b32 v5, 0", + f"buffer_load_format_{suffix} {dst}, v1, s[0:3], 0 offen", + "exp mrt0 v2, v3, v4, v5 done vm", "s_endpgm"] + spv = support.translate_lines(f"ps_fmt_dyn_{suffix}", lines) + body = function_body(spv, "%fmt_dec_dyn") + self.assertTrue(body, f"%fmt_dec_dyn missing for buffer_load_format_{suffix}") + for line in body: + for op in BRANCHES: + self.assertNotIn(op, line, f"%fmt_dec_dyn branches: {line}") + for k in range(4): + self.assertNotIn(f"%fmt_dec_c{k} = OpFunction", spv) + main = function_body(spv, "%main") + calls = [ln for ln in main if "OpFunctionCall %uint %fmt_dec_dyn " in ln] + self.assertEqual(len(calls), ncomp, f"expected {ncomp} decode calls for _{suffix}") + + def test_narrow_loads_match_reference_across_all_formats_dst_sel_and_oob(self): + # Exhaustive check: every format code 0..max+1 with rotated DST_SEL (including 0, 1, reserved 2/3, 4..7) + # across buffer_load_format_x, _xy, and _xyz, plus OOB DST_SEL=1 vs channel selection. + def dst1_for(code): + entry = rdna2spirv.Gen.FORMATS.get(code) + if entry is None or entry[1] in ("uint", "sint", "u32", "i32"): + return 1 + return 0x3F800000 + + def expect_sel(ref4, code, sel, in_bounds): + if sel == 1: + return dst1_for(code) + if 4 <= sel <= 7: + return ref4[sel - 4] if in_bounds else 0 + return 0 + + # Build reusable shaders parameterized by V# word3 in push constants / s0..s3? Here translate once per + # (ncomp, dst_sel_word) with code in s3 via s_mov_b32 — fast because we test every code on _x with + # DST_SEL_X = (code % 8) and rotated multi-channel swizzles on _xy / _xyz. + mem = {BASE + 4 * i: w for i, w in enumerate(WORDS)} + # 1) All 128 codes on _xyz with swizzle (7, 5, 6) = W, Y, Z -> exercises channels 1, 2, 3 across every format + for code in range(max(rdna2spirv.Gen.FORMATS) + 2): + want4 = reference(code) + if want4 is None: + continue + sels = (7, 5, 6) + d3 = (code << 12) | 0x30000000 | sels[0] | (sels[1] << 3) | (sels[2] << 6) + lines = [f"s_mov_b32 s0, {BASE:#x}", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100", + f"s_mov_b32 s3, {d3:#x}", "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", "v_mov_b32 v4, 0", "v_mov_b32 v5, 0", + "buffer_load_format_xyz v[2:4], v1, s[0:3], 0 offen", + "exp mrt0 v2, v3, v4, v5 done vm", "s_endpgm"] + spv = support.translate_lines("ps_fmt_xyz_swiz", lines) + got = tuple(run_fragment(spv, memory=mem)["%out_mrt0"]) + expected = tuple(expect_sel(want4, code, s, True) for s in sels) + (0,) + self.assertEqual(got, expected, f"xyz format {code}") + + # 2) All 8 DST_SEL values (0..7) on _x in-bounds and out-of-bounds for both float (unorm 1) and uint (2) + for code in (1, 2, 76, 127): + want4 = reference(code) + for in_bounds in (True, False): + voff = "0" if in_bounds else "0x200" + for sel in range(8): + d3 = (code << 12) | 0x30000000 | sel + lines = [f"s_mov_b32 s0, {BASE:#x}", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100", + f"s_mov_b32 s3, {d3:#x}", f"v_mov_b32 v1, {voff}", + "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", "v_mov_b32 v4, 0", "v_mov_b32 v5, 0", + "buffer_load_format_x v2, v1, s[0:3], 0 offen", + "exp mrt0 v2, v3, v4, v5 done vm", "s_endpgm"] + spv = support.translate_lines("ps_fmt_x_sel", lines) + got = run_fragment(spv, memory=mem)["%out_mrt0"][0] + self.assertEqual(got, expect_sel(want4, code, sel, in_bounds), + f"x format={code} sel={sel} in_bounds={in_bounds}") + + def test_mixed_xyzw_and_x_emits_fmt_norm_bits_once(self): + # A shader containing both buffer_load_format_xyzw and buffer_load_format_x must emit %fmt_norm_bits once. + lines = [f"s_mov_b32 s0, {BASE:#x}", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100", + f"s_mov_b32 s3, {1 << 12 | 0x30000FAC:#x}", "v_mov_b32 v1, 0", + "buffer_load_format_xyzw v[2:5], v1, s[0:3], 0 offen", + "buffer_load_format_x v6, v1, s[0:3], 0 offen", + "v_add_f32 v2, v2, v6", + "exp mrt0 v2, v3, v4, v5 done vm", "s_endpgm"] + spv = support.translate_lines("ps_fmt_mixed", lines) + self.assertEqual(spv.count("%fmt_norm_bits = OpFunction"), 1) + self.assertEqual(spv.count("%fmt_dec_dyn = OpFunction"), 1) + self.assertEqual(spv.count("%fmt_dec_c0 = OpFunction"), 1) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_rdna2spirv_decode.py b/tests/test_rdna2spirv_decode.py index 43b08e5220..533d31f74e 100644 --- a/tests/test_rdna2spirv_decode.py +++ b/tests/test_rdna2spirv_decode.py @@ -246,6 +246,19 @@ def test_format_decode_call_builds_and_caches_function(self): self.assertEqual(len(comps2), 4) self.assertIs(self.gen.fmt_fn, first_fn) + def test_format_decode_dyn_call_builds_and_caches_function(self): + self.assertIsNone(self.gen.fmt_dyn_fn) + r1 = self.gen.format_decode_dyn_call("%fmt_var", "%wvec", "%chan0") + self.assertTrue(r1.startswith("%")) + self.assertIsNotNone(self.gen.fmt_dyn_fn) + first_fn = self.gen.fmt_dyn_fn + # Dynamic single-channel call does not build the 4-component %fmt_dec_c0..c3 functions. + self.assertIsNone(self.gen.fmt_fn) + + r2 = self.gen.format_decode_dyn_call("%fmt_var2", "%wvec", "%chan1") + self.assertTrue(r2.startswith("%")) + self.assertIs(self.gen.fmt_dyn_fn, first_fn) + def test_encode_format_saturation_and_boundary(self): fcomps = ["%f0", "%f1", "%f2", "%f3"] icomps = ["%i0", "%i1", "%i2", "%i3"] diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 920e858ae8..767c01e66b 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -395,6 +395,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it self.tbuffer_norm_fns: dict[int, list[str]] = {} # one exact quotient per used magnitude width self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it + self.fmt_dyn_fn = None # lines of the dynamic-channel format-decode function (%fmt_dec_dyn) for ncomp < 4 self.fmt_norm_fn = None # lines of the shared exact norm quotient for a run-time width (SHADER-849) self.fmt_enc_fn = None # lines of the format-encode and element-size functions, once a typed store needs them self.uses_fmt_tables = False # %fmt_desc_tab / %fmt_norm_rep_tab: a format's kind and channel widths @@ -3325,7 +3326,29 @@ def fmt_dec_component(self, k, params): o = self.tmp() self.emit(f"{o} = OpIAdd %uint {offsets[-1]} {widths[i - 1]}") offsets.append(o) - if k == 1: + if k is None: + chan = params[2] + # Dynamic output channel 0..3: eff = chan % ncomp for ncomp in {1, 2, 3, 4} (all widths are 0 when 0). + one, two, three = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{one} = OpIEqual %bool {ncomp} {self.cu(1)}") + self.emit(f"{two} = OpIEqual %bool {ncomp} {self.cu(2)}") + self.emit(f"{three} = OpIEqual %bool {ncomp} {self.cu(3)}") + c_mod2, c_is3, c_mod3 = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{c_mod2} = OpBitwiseAnd %uint {chan} {self.cu(1)}") + self.emit(f"{c_is3} = OpIEqual %bool {chan} {self.cu(3)}") + self.emit(f"{c_mod3} = OpSelect %uint {c_is3} {self.cu(0)} {chan}") + eff3, eff2, eff = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{eff3} = OpSelect %uint {three} {c_mod3} {chan}") + self.emit(f"{eff2} = OpSelect %uint {two} {c_mod2} {eff3}") + self.emit(f"{eff} = OpSelect %uint {one} {self.cu(0)} {eff2}") + wid, off = widths[0], offsets[0] + for i in (1, 2, 3): + eq, ws, os_ = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{eq} = OpIEqual %bool {eff} {self.cu(i)}") + self.emit(f"{ws} = OpSelect %uint {eq} {widths[i]} {wid}") + self.emit(f"{os_} = OpSelect %uint {eq} {offsets[i]} {off}") + wid, off = ws, os_ + elif k == 1: one, wid, off = self.tmp(), self.tmp(), self.tmp() self.emit(f"{one} = OpIEqual %bool {ncomp} {self.cu(1)}") self.emit(f"{wid} = OpSelect %uint {one} {widths[0]} {widths[1]}") @@ -3423,16 +3446,21 @@ def fmt_dec_component(self, k, params): res = sel return res - def fmt_dec_functions(self): - """The shared per-component decode functions (SHADER-849), one per output component.""" - if self.fmt_fn is None: + def _ensure_fmt_tables(self): + if not self.uses_fmt_tables: self.uses_fmt_tables = True # The tables are constants: register them here, while the constant section can still take them. for v in Gen.fmt_desc_table(): self.cu(v) for v in Gen.fmt_norm_reps(): self.cl(v) - fns = list(self.fmt_norm_function()) + self.fmt_norm_function() + + def fmt_dec_functions(self): + """The shared per-component decode functions (SHADER-849), one per output component.""" + if self.fmt_fn is None: + self._ensure_fmt_tables() + fns = [] for k in range(4): saved, self.body = self.body, [] params = [f"%fd{k}_fmt", f"%fd{k}_words"] @@ -3444,6 +3472,28 @@ def fmt_dec_functions(self): self.fmt_fn = fns return self.fmt_fn + def fmt_dec_dyn_function(self): + """Shared dynamic-channel decode function %fmt_dec_dyn(fmt, words, chan) for 1/2/3-component loads.""" + if self.fmt_dyn_fn is None: + self._ensure_fmt_tables() + saved, self.body = self.body, [] + params = ["%fdd_fmt", "%fdd_words", "%fdd_chan"] + res = self.fmt_dec_component(None, params) + lines, self.body = self.body, saved + self.fmt_dyn_fn = (["%fmt_dec_dyn = OpFunction %uint None %fn_fmt_dec_dyn"] + + [f"{params[0]} = OpFunctionParameter %uint", + f"{params[1]} = OpFunctionParameter %v4uint_fmt", + f"{params[2]} = OpFunctionParameter %uint"] + + ["%fmt_dec_dyn_entry = OpLabel"] + lines + [f"OpReturnValue {res}", "OpFunctionEnd"]) + return self.fmt_dyn_fn + + def format_decode_dyn_call(self, fmt, wvec, chan): + """One uint id: the single channel `chan` (0..3) decoded per the run-time FORMAT.""" + self.fmt_dec_dyn_function() + r = self.tmp() + self.emit(f"{r} = OpFunctionCall %uint %fmt_dec_dyn {fmt} {wvec} {chan}") + return r + def format_decode_call(self, fmt, words): """4 uint ids: the element decoded per the run-time FORMAT, through the shared per-component functions. @@ -3588,8 +3638,12 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): comps = self.decode_format(words, fixed_fmt, fixed=True) widths = self.FORMATS[fixed_fmt][2] d3 = self.cu(sum((4 + c) << (3 * c) for c in range(len(widths)))) - else: + elif ncomp == 4: comps = self.format_decode_call(fmt, words) + else: + comps = None + wvec = self.tmp() + self.emit(f"{wvec} = OpCompositeConstruct %v4uint_fmt " + " ".join(words[:4])) # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm/scaled) or integer 1 (UINT/SINT, INVALID or reserved; # SHADER-86, SHADER-429), 4..7 -> X..W. On an out-of-bounds MUBUF load `words` are 0 so `comps` decode to 0, # while DST_SEL=1 still produces 1.0f / 1 (MTBUF overrides `d3` above with 4..7 / 0, so OOB and INVALID stay 0). @@ -3616,25 +3670,44 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): dst1 = self.tmp() self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}") # In-bounds gate applies to components read from buffer memory, leaving DST_SEL=1 intact (SHADER-429). - bounded_comps = [] - for comp in comps: - cb = self.tmp() - self.emit(f"{cb} = OpSelect %uint {in_b} {comp} {self.cu(0)}") - bounded_comps.append(cb) outs = [] - for c in range(ncomp): - sel = self.tmp() - self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}") - r = self.cu(0) - for code_v, src in ((1, dst1), (4, bounded_comps[0]), (5, bounded_comps[1]), (6, bounded_comps[2]), (7, bounded_comps[3])): - e, s = self.tmp(), self.tmp() - self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}") - self.emit(f"{s} = OpSelect %uint {e} {src} {r}") - r = s - if d16: - outs.append(r) - else: - self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, r) + if comps is not None: + bounded_comps = [] + for comp in comps: + cb = self.tmp() + self.emit(f"{cb} = OpSelect %uint {in_b} {comp} {self.cu(0)}") + bounded_comps.append(cb) + for c in range(ncomp): + sel = self.tmp() + self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}") + r = self.cu(0) + for code_v, src in ((1, dst1), (4, bounded_comps[0]), (5, bounded_comps[1]), (6, bounded_comps[2]), (7, bounded_comps[3])): + e, s = self.tmp(), self.tmp() + self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}") + self.emit(f"{s} = OpSelect %uint {e} {src} {r}") + r = s + if d16: + outs.append(r) + else: + self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, r) + else: + # Demand-driven decode for 1/2/3-component dynamic-format loads: decode only the channel + # selected by each output's DST_SEL (4..7 -> channel 0..3) instead of all four channels. + for c in range(ncomp): + sel, chan = self.tmp(), self.tmp() + self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}") + self.emit(f"{chan} = OpBitwiseAnd %uint {sel} {self.cu(3)}") + dec = self.format_decode_dyn_call(fmt, wvec, chan) + cb, is_ch, is_1, r0, r = (self.tmp() for _ in range(5)) + self.emit(f"{cb} = OpSelect %uint {in_b} {dec} {self.cu(0)}") + self.emit(f"{is_ch} = OpUGreaterThanEqual %bool {sel} {self.cu(4)}") + self.emit(f"{is_1} = OpIEqual %bool {sel} {self.cu(1)}") + self.emit(f"{r0} = OpSelect %uint {is_1} {dst1} {self.cu(0)}") + self.emit(f"{r} = OpSelect %uint {is_ch} {cb} {r0}") + if d16: + outs.append(r) + else: + self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, r) if d16: # D16 packs two results per register, saturating integer formats according to signedness. def int_half(word): @@ -15720,13 +15793,16 @@ def assemble(gen): types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8)) if gen.tbuffer_norm_fns or gen.fmt_enc_fn: types.append("%fn_tbuffer_norm = OpTypeFunction %uint %uint") # also the element-size function's type - if gen.fmt_fn or gen.fmt_enc_fn: + if gen.fmt_fn or gen.fmt_dyn_fn or gen.fmt_enc_fn: types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 + if gen.fmt_fn or gen.fmt_dyn_fn: + types.append("%fn_fmt_norm = OpTypeFunction %uint %uint %uint") if gen.fmt_fn: # The decode function takes the format code and the element's four dwords as a v4uint: a type of its own # structure, so it never repeats another function type in the module (SPIR-V forbids that). types.append("%fn_fmt_dec = OpTypeFunction %uint %uint %v4uint_fmt") - types.append("%fn_fmt_norm = OpTypeFunction %uint %uint %uint") + if gen.fmt_dyn_fn: + types.append("%fn_fmt_dec_dyn = OpTypeFunction %uint %uint %v4uint_fmt %uint") if gen.fmt_enc_fn: types.append("%fn_fmt_encode = OpTypeFunction %v4uint_fmt " + " ".join(["%uint"] * 29)) for arity, fn_type in sorted(gen.x_round_fn_types.items()): @@ -16137,7 +16213,7 @@ def assemble(gen): fn.append(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {gen.cu(r)}") # Spill pointers last: a spilled value's type may be declared anywhere above. types += [f"{ptr} = OpTypePointer Function {t}" for t, ptr in gen.x_ptr_types.items()] - helpers = (gen.desc_fn or []) + (gen.fmt_fn or []) + (gen.fmt_enc_fn or []) + helpers = (gen.desc_fn or []) + (gen.fmt_norm_fn or []) + (gen.fmt_fn or []) + (gen.fmt_dyn_fn or []) + (gen.fmt_enc_fn or []) for function in gen.tbuffer_norm_fns.values(): helpers.extend(function) for function in gen.x_round_fns.values(): From 5c7a8bbd8b85274f72aa01eccc823c463cdff88a Mon Sep 17 00:00:00 2001 From: SweatierKey <53280918+SweatierKey@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:43:24 +0100 Subject: [PATCH 2/2] tests: set odd DST_SEL_Y in _x selector matrix to kill 3->4 bitfield width mutant --- tests/semantic/test_format_decode_table.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/semantic/test_format_decode_table.py b/tests/semantic/test_format_decode_table.py index ab36d651f6..dab835e1fc 100644 --- a/tests/semantic/test_format_decode_table.py +++ b/tests/semantic/test_format_decode_table.py @@ -178,13 +178,15 @@ def expect_sel(ref4, code, sel, in_bounds): expected = tuple(expect_sel(want4, code, s, True) for s in sels) + (0,) self.assertEqual(got, expected, f"xyz format {code}") - # 2) All 8 DST_SEL values (0..7) on _x in-bounds and out-of-bounds for both float (unorm 1) and uint (2) + # 2) All 8 DST_SEL values (0..7) on _x in-bounds and out-of-bounds for both float (unorm 1) and uint (2). + # Also set DST_SEL_Y = 5 (odd) so an over-wide 4-bit extract of DST_SEL_X would pull in bit 0 of DST_SEL_Y + # and corrupt selectors 0..3 (catching 3->4 field-width mutations on OpBitFieldUExtract). for code in (1, 2, 76, 127): want4 = reference(code) for in_bounds in (True, False): voff = "0" if in_bounds else "0x200" for sel in range(8): - d3 = (code << 12) | 0x30000000 | sel + d3 = (code << 12) | 0x30000000 | sel | (5 << 3) lines = [f"s_mov_b32 s0, {BASE:#x}", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100", f"s_mov_b32 s3, {d3:#x}", f"v_mov_b32 v1, {voff}", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", "v_mov_b32 v4, 0", "v_mov_b32 v5, 0",