Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,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, kind`. The last word is 0 in an empty slot; otherwise bit 31 marks it occupied and bits 0..5 / 8..11 name the sampled / storage arrays the index is bound in (docs/d3d12_vulkan.md section 5.1, "Images and samplers (T# dimension)" below). A module reads it only when its index entry says `"descriptor_table": "tagged"`; `--descriptor-table plain` leaves the word unread and gives byte-identical modules to the translator before the marker (checked with a 5-instruction pixel shader: old and plain output are the same bytes). The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot by default. With `--descriptor-hash=fnv1a_fmix32` the shader applies MurmurHash3 fmix32 before masking the slot. Every translated module then records `"descriptor_hash": "fnv1a_fmix32"` in its index entry. An absent key means `fnv1a`. The runtime and shader must select the same hash. 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: one shared function, `%fmt_dec(format, element, component)`, 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). Then four functions, one per output component, held 565 instructions and no branch, and that module was 56,763 bytes; every load called all four. 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 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. Since 2026-11-27 the component is the function's last parameter (154 instructions), and a load calls it once per register it writes, with the component that register's DST_SEL picks (DST_SEL − 4; a register whose DST_SEL is 0, 1 or reserved discards the call's value): `buffer_load_format_x` makes one call, not four. The values are the same by construction (the four components' channel width and offset are computed as before and the parameter selects one), checked against the previous translator by the mini interpreter on 22,528 loads (`_x` … `_xyzw` and `d16_x` … `d16_xyzw`, all 128 codes, random DST_SEL, byte alignments and out-of-range records) and on an RTX 4070 Laptop (621.40) by the typed-load GPU tests; `tests/semantic/test_buffer_format_decode_one.py` counts the calls. The function takes the format code, the element's four dwords as a `v4uint` and the component, so its 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. 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). |
Expand Down
11 changes: 11 additions & 0 deletions tests/semantic/fixtures/typed_load_runtime_x.asm
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
; buffer_load_format_x with the V# in s[0:3] (push constants): its FORMAT and DST_SEL are known only at run time.
; The registers the load does not write keep their sentinels.
v_mov_b32 v2, 0xA5A5A5A5
v_mov_b32 v3, 0x5A5A5A5A
v_mov_b32 v4, 0x13579BDF
v_mov_b32 v5, 0x2468ACE0
v_mov_b32 v1, 0
buffer_load_format_x v2, v1, s[0:3], 0 offen
s_waitcnt vmcnt(0)
exp mrt0 v2, v3, v4, v5 done vm
s_endpgm
11 changes: 11 additions & 0 deletions tests/semantic/fixtures/typed_load_runtime_xy.asm
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
; buffer_load_format_xy with the V# in s[0:3] (push constants): its FORMAT and DST_SEL are known only at run time.
; The registers the load does not write keep their sentinels.
v_mov_b32 v2, 0xA5A5A5A5
v_mov_b32 v3, 0x5A5A5A5A
v_mov_b32 v4, 0x13579BDF
v_mov_b32 v5, 0x2468ACE0
v_mov_b32 v1, 0
buffer_load_format_xy v[2:3], v1, s[0:3], 0 offen
s_waitcnt vmcnt(0)
exp mrt0 v2, v3, v4, v5 done vm
s_endpgm
11 changes: 11 additions & 0 deletions tests/semantic/fixtures/typed_load_runtime_xyzw.asm
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
; buffer_load_format_xyzw with the V# in s[0:3] (push constants): its FORMAT and DST_SEL are known only at run time.
; The registers the load does not write keep their sentinels.
v_mov_b32 v2, 0xA5A5A5A5
v_mov_b32 v3, 0x5A5A5A5A
v_mov_b32 v4, 0x13579BDF
v_mov_b32 v5, 0x2468ACE0
v_mov_b32 v1, 0
buffer_load_format_xyzw v[2:5], v1, s[0:3], 0 offen
s_waitcnt vmcnt(0)
exp mrt0 v2, v3, v4, v5 done vm
s_endpgm
22 changes: 21 additions & 1 deletion tests/semantic/spirv_mini_interp.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,26 @@ def bits_f32(b):
return _F32(b & MASK)


_HEX_FLOAT = re.compile(r"([+-]?)0[xX]([0-9a-fA-F]*)\.?([0-9a-fA-F]*)[pP]([+-]?\d+)")


def f32_literal(tok):
"""The value of a 32-bit OpConstant %float literal as spirv-as reads it: a decimal, or a hex-float, where exponent
+128 is the SPIRV-Tools spelling of an infinity (0x1p+128) or a NaN with its payload (0x1.8p+128, the quiet NaN),
as rdna2spirv.float_literal writes them."""
m = _HEX_FLOAT.fullmatch(tok)
if m is None:
return f32(float(tok))
sign, ipart, fpart, exp = m.groups()
sig = int(ipart + fpart or "0", 16)
top = sig.bit_length() - 1
if sig and int(exp) - 4 * len(fpart) + top == 128:
frac = sig & ((1 << top) - 1)
mant = frac << (23 - top) if top <= 23 else frac >> (top - 23)
return bits_f32((0x80000000 if sign == "-" else 0) | 0x7F800000 | mant)
return f32(float.fromhex(tok))


def half_to_float(h):
# Bit-level f16 -> f32 (sign, exponent, fraction; every result is exact in binary32). struct's '<e' is not
# used because its NaN result depends on the Python version: before 3.14 it drops the payload and returns
Expand Down Expand Up @@ -624,7 +644,7 @@ def walk(type_id, indices):
elif op == "OpConstant":
k = types.t[a[0]]
if k[0] == "float":
constants[res] = values[res] = f32(float(a[1])) if k[1] == 32 else float(a[1])
constants[res] = values[res] = f32_literal(a[1]) if k[1] == 32 else float(a[1])
elif k[0] == "int":
constants[res] = values[res] = int(a[1]) & ((1 << k[1]) - 1)
id_type[res] = a[0]
Expand Down
15 changes: 14 additions & 1 deletion tests/semantic/spirv_wave_interp.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,9 +309,22 @@ def bits(self, type_id):


def _float_literal_bits(text):
"""The bits of an OpConstant %float literal: a decimal, or the SPIRV-Tools hex-float spelling (an infinity or a NaN
with its payload at exponent +128) that tools/rdna2spirv.py's float_literal writes."""
import re
import struct
try:
return struct.unpack("<I", struct.pack("<f", float(text)))[0]
m = re.fullmatch(r"([+-]?)0[xX]([0-9a-fA-F]*)\.?([0-9a-fA-F]*)[pP]([+-]?\d+)", text)
if m is None:
return struct.unpack("<I", struct.pack("<f", float(text)))[0]
sign, ipart, fpart, exp = m.groups()
sig = int(ipart + fpart or "0", 16)
top = sig.bit_length() - 1
if sig and int(exp) - 4 * len(fpart) + top == 128:
frac = sig & ((1 << top) - 1)
mant = frac << (23 - top) if top <= 23 else frac >> (top - 23)
return (0x80000000 if sign == "-" else 0) | 0x7F800000 | mant
return struct.unpack("<I", struct.pack("<f", float.fromhex(text)))[0]
except (OverflowError, ValueError):
raise UnsupportedConstruct(f"float literal {text!r}") from None

Expand Down
7 changes: 4 additions & 3 deletions tests/semantic/test_alu_sincos.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,18 +724,19 @@ def test_negative_control_spirv_opcode_sabotage(self):
self.assertNotEqual(sabotaged_cos_out, expected_cos)

def test_negative_control_turn_scaling_sabotage(self):
# Sabotaging the 2*pi scaling factor (1086918619 -> 1.0 = 1065353216) fails the check
# Sabotaging the 2*pi scaling factor (the float constant 0x40c90fdb -> 1.0) fails the check
spv = translate_ps([
f"v_mov_b32 v1, {H_QUARTER:#x}",
"v_sin_f16 v0, v1",
"exp mrt0 v0, v0, v0, v0 done vm",
"s_endpgm",
])
self.assertIn("1086918619", spv)
two_pi = "%fc40c90fdb = OpConstant %float 6.2831854820251465"
self.assertIn(two_pi, spv)
expected = H_ONE
self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0] & 0xFFFF, expected)

sabotaged = spv.replace("1086918619", "1065353216")
sabotaged = spv.replace(two_pi, "%fc40c90fdb = OpConstant %float 1.0")
sabotaged_out = si.run_fragment(sabotaged)["%out_mrt0"][0] & 0xFFFF
self.assertNotEqual(sabotaged_out, expected)

Expand Down
Loading
Loading