From 9088f734f44c407a6d4e5b8d5de2b0162460fa59 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 02:51:36 +0100 Subject: [PATCH 1/4] startup: add a compute stage to gfx2hlsl with the offen buffer store ComputePipeline translates one gfx1013 compute program with the root and resource model of the graphics stages. COMPUTE_PGM_RSRC2 and the thread group size come from the caller and follow compute_store_aot's entry layout (#1608): root parameters from s4, one SGPR per enabled group-ID axis after the user SGPRs, and v0-v2 as SV_GroupThreadID. TG_SIZE_EN stays refused, and a numeric read of a user SGPR the root does not place is refused. The output is a cs HLSL main with numthreads and a version 2 manifest (stage cs, group, uav table ). The one store lowered is buffer_store_dword[x2-4] in the offen form through a fixed root-table descriptor, to a RWByteAddressBuffer. The fixture translates two source-built programs (all axes; X and Z only), compiles them with DXC and dispatches them on a plain D3D12 device, comparing all 320 words. Swapped group axes and a dropped store must mismatch. Refs #1412 Co-Authored-By: Claude Fable 5.2 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 16 ++ docs/experiments.md | 34 +++ tests/startup_gfx2hlsl_compute_check.py | 273 ++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 138 +++++++++++- 6 files changed, 462 insertions(+), 2 deletions(-) create mode 100644 tests/startup_gfx2hlsl_compute_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 3d3ff1750a..e82b6b435d 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -88,6 +88,7 @@ jobs: (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "binary", "llvm-mc-15"], {}), @@ -221,6 +222,7 @@ jobs: tests/startup_flat_param_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_gfx2hlsl_mad_check.py \ + tests/startup_gfx2hlsl_compute_check.py \ tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 4ab50f4b80..72c04f6ecb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,6 +149,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_load_mip_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_operand_count_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 17aa9d3505..5a753396a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2594,6 +2594,22 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_mad_dispatch_${adapter} startup_gfx2hlsl_mad_preserve_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). + add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_compute_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS swapped-axes dropped-store) + add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl 64-bit VOP3 shifts: binary round-trip, overlap, guards and WARP/hardware draws (Refs #1723). add_test(NAME startup_gfx2hlsl_shift64_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index ec41c366f4..03e7cfccd8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12061,6 +12061,40 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mad_' -V python -B tests/startup_gfx2hlsl_mad_check.py binary llvm-mc-15 ``` +## Compute stage in the startup translator + +`gfx2hlsl.ComputePipeline` translates one gfx1013 compute program with the root and resource model of +the graphics stages. The caller passes `COMPUTE_PGM_RSRC2` and the thread group size, which are pipeline +register state. Root parameters start at s4. Each group-ID axis enabled by `TGID_X/Y/Z_EN` gets the next +SGPR after the user SGPRs, with no gap for an omitted axis (`SV_GroupID`), and v0-v2 hold +`SV_GroupThreadID` up to `TIDIG_COMP_CNT`. This is the layout `compute_store_aot` uses (#1608). +`TG_SIZE_EN` stays refused. A numeric read of a user SGPR that the root signature does not place, +including s0-s3, is refused because its value is unknown. + +The output is a `cs` HLSL main with `[numthreads]` and a version 2 manifest. The manifest has +`stage cs` and `group` lines, plus one `uav table ` line for each store +target. The only store lowered is `buffer_store_dword[x2|x3|x4]` in the `offen` form: a per-lane byte VGPR, plus +the scalar offset and the immediate, through a descriptor at a fixed root-table offset. It writes a +`RWByteAddressBuffer`. Other forms are refused: `off`, `idxen`, the cache-policy flags, a store +through a modified descriptor, and a descriptor that is also loaded. +The runtime has no slot-67 path yet, so no translated compute program runs in the stand-in. + +`startup_gfx2hlsl_compute_check.py` translates two source-built programs. Case A enables all three +group-ID axes and v0-v2, with group size 2x3x4 and 3x2x2 groups. Case B enables X and Z only, so Z +is s8, with group size 5x2x1 and 4x1x3 groups, and stores two words at an immediate offset. Each thread +reads a read buffer at its own index and stores to its own destination. DXC compiles the HLSL for +`cs_6_0`, and a plain D3D12 device dispatches it with a root SRV, a root UAV and the root constants. +All 320 words are compared, including the sentinels. The two controls swap the X and Y group IDs, or +drop the store, and each must mismatch. + +On Windows 11 (26300), all 320 words matched in both cases on WARP (10.0.26100.10068) and on an +RTX 5090 (32.0.16.2135), with the debug layer on. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_' -V +python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 +``` + ## Startup translator: refusal census The startup shader translator normally stops a pipeline at its first refusal. Fixing that refusal can expose gaps that were previously hidden, as documented in the [issue #1723 census](https://github.com/R0Y00/Xbox2Windows/issues/1723). diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py new file mode 100644 index 0000000000..3f465abd57 --- /dev/null +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -0,0 +1,273 @@ +"""Compute stage of tools/startup/gfx2hlsl.py: entry registers, numthreads and the offen buffer store (#1412). + + (no arguments) translation controls, pure Python + binary reassemble the fixture sources and compare them with the words below + dispatch + translate, compile with DXC cs_6_0, dispatch and compare every word + control + the same dispatch with a mutated translation, which must mismatch + +The fixtures are source-built gfx1013 compute programs. The root signature puts two root constants (key, stride) +in s4-s5 and a descriptor table in s6; the table holds a read buffer at byte 0 and a writable buffer at byte 16. +COMPUTE_PGM_RSRC2 and the thread group size are pipeline register state, given here as the runtime would give them. +Each thread names its group and local IDs only by the registers that state gives them, computes its own index, +reads the read buffer at that index and stores to its own destination: + +- case A enables all three group-ID axes and v0-v2, with group size 2x3x4 and 3x2x2 groups, and stores one word; +- case B enables X and Z only (Y omitted, so Z is s8), v0-v1, group size 5x2x1 and 4x1x3 groups, and stores two + words at an immediate offset of 8 bytes. + +The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet): root SRV t0 (read buffer), root +UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's r0, u0 and entry cbuffer. +All 320 words are compared, so a word outside the written records must keep the sentinel. The controls swap the +X and Y group IDs at entry or drop the store; either must change the readback. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +SENTINEL = 0xc5c5c5c5 +WORDS = 320 +MASK = 0xffffffff +KEY, STRIDE = 0x01234567, 0x9e3779b9 +TGID_X, TGID_Y, TGID_Z, TG_SIZE_EN = 1 << 7, 1 << 8, 1 << 9, 1 << 10 +USER7 = 7 << 1 # s0-s3, two root constants, one table + + +def tidig(components): + return (components - 1) << 11 + + +SOURCE_A = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_mad_u32_u24 v3, v1, 2, v0 +v_mad_u32_u24 v3, v2, 6, v3 +s_mul_i32 s20, s8, 3 +s_add_u32 s20, s20, s7 +s_mul_i32 s21, s9, 6 +s_add_u32 s20, s20, s21 +s_mul_i32 s20, s20, 24 +v_add_nc_u32 v3, s20, v3 +v_lshlrev_b32 v4, 2, v3 +buffer_load_dword v5, v4, s[12:15], 0 offen +v_mul_lo_u32 v6, v3, s5 +v_add_nc_u32 v6, s4, v6 +s_waitcnt vmcnt(0) +v_mul_lo_u32 v5, v5, 33 +v_xor_b32 v5, v5, v6 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_A = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '030043d501050104' '030043d5020d0d04' '08831493' '14071480' + '09861593' '14151480' '14981493' '1406064a' '82060834' '001030e004050380' '060069d5030b0000' '040c0c4a' + '703f8cbf' '050069d505430100' '050d0a3a' '001070e004050480' '000081bf') + +SOURCE_B = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_mad_u32_u24 v3, v1, 5, v0 +s_lshl_b32 s20, s8, 2 +s_add_u32 s20, s20, s7 +s_mul_i32 s20, s20, 10 +v_add_nc_u32 v3, s20, v3 +v_lshlrev_b32 v4, 3, v3 +v_lshlrev_b32 v7, 2, v3 +buffer_load_dword v5, v7, s[12:15], 0 offen +v_mul_lo_u32 v6, v3, s5 +v_add_nc_u32 v6, s4, v6 +s_waitcnt vmcnt(0) +v_xor_b32 v5, v5, v6 +v_xor_b32 v6, 0x5a000000, v3 +buffer_store_dwordx2 v[5:6], v4, s[16:19], 0 offen offset:8 +s_endpgm +""" +WORDS_B = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '030043d5010b0104' '0882148f' '14071480' '148a1493' + '1406064a' '83060834' '82060e34' '001030e007050380' '060069d5030b0000' '040c0c4a' '703f8cbf' '050d0a3a' + 'ff060c3a0000005a' '081074e004050480' '000081bf') + +CASES = { + # name: (source, words, rsrc2, group size, group counts) + 'A': (SOURCE_A, WORDS_A, USER7 | TGID_X | TGID_Y | TGID_Z | tidig(3), (2, 3, 4), (3, 2, 2)), + 'B': (SOURCE_B, WORDS_B, USER7 | TGID_X | TGID_Z | tidig(2), (5, 2, 1), (4, 1, 3)), +} + + +def root_blob(): + """RTS0: param 0 = two root constants (b0), param 1 = a descriptor table with no ranges.""" + params_at, constants_at = 24, 24 + 2 * 12 + table_at = constants_at + 12 + rts0 = (struct.pack('<6I', 2, 2, params_at, 0, table_at + 8, 0) + + struct.pack('<3I', 1, 0, constants_at) + struct.pack('<3I', 0, 0, table_at) + + struct.pack('<3I', 0, 0, 2) + struct.pack('<2I', 0, table_at + 8)) + part = b'RTS0' + struct.pack(' user: + raise Unsupported('root signature needs s4-s%d, COMPUTE_PGM_RSRC2 gives %d user SGPRs' % (root_end - 1, user)) + for n in list(range(4)) + list(range(root_end, user)): + self.sym[n] = ('unknown user sgpr',) + self.entry = [] + for axis, n in sorted(groups.items()): + self.used_s.add(n) + self.entry.append('s%d = gid.%s;' % (n, 'xyz'[axis])) + for i in range(threads): + self.used_v.add(i) + self.entry.append('v%d = tid.%s;' % (i, 'xyz'[i])) + # ---- operand helpers --------------------------------------------------------------------- def S(self, n): """Runtime expression of scalar register n (uint).""" @@ -1528,6 +1548,57 @@ def op_buffer_load_dwordx3(self, ops, mods): def op_buffer_load_dwordx4(self, ops, mods): self.op_buffer_load_dword(ops, mods, 4) + def op_buffer_store_dword(self, ops, mods, count=1): + # Compute-stage store in the offen form: per-lane byte VGPR plus the scalar offset and the 12-bit immediate, + # through a descriptor read from a fixed root-table slot, to a RWByteAddressBuffer (manifest `uav` line). + # Like the loads, this assumes a raw descriptor (no swizzle or stride) and that the runtime sizes the view + # to the descriptor's range, so an out-of-range store is dropped on both sides. + if self.kind != 'cs': + raise Unsupported('buffer store in the %s stage' % self.kind) + offset = 0 + for m in mods: + if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): + offset += int(m[7:], 0) + elif m != 'offen': + raise Unsupported('buffer store modifier %s' % m) + if len(ops) != 4 or 'offen' not in mods: + raise Unsupported('buffer store without the offen address form') + src, vaddr = reg_range(ops[0]), reg_range(ops[1]) + if not src or src[0] != 'v' or src[2] - src[1] != count - 1 or src[2] > 255: + raise Unsupported('buffer store data %s' % ops[0]) + if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: + raise Unsupported('buffer store vaddr %s for offen' % ops[1]) + key = self.descriptor(ops[2]) + if key[0][0] != 'table' or key[1] is None: + raise Unsupported('buffer store through %s' % (key,)) + if key in self.pipe.modified: + raise Unsupported('buffer store through a modified descriptor') + terms = [self.u(ops[1])] + if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): + offset += int(ops[3], 0) + else: + sreg = reg_range(ops[3]) + if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: + raise Unsupported('buffer soffset %s' % ops[3]) + terms.append(self.S(sreg[1])) + uav = self.pipe.uav(key) + words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] + data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) + # shortcut: Store* needs a multiple of four, so a misaligned address is rounded down (dword buffer access is + # assumed to ignore the low two bits); refuse misaligned addresses instead if a program depends on them. + self.emit('a = (%s + %d) & 0xfffffffcu;' % (' + '.join(terms), offset)) + store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else count, data) + self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) + + def op_buffer_store_dwordx2(self, ops, mods): + self.op_buffer_store_dword(ops, mods, 2) + + def op_buffer_store_dwordx3(self, ops, mods): + self.op_buffer_store_dword(ops, mods, 3) + + def op_buffer_store_dwordx4(self, ops, mods): + self.op_buffer_store_dword(ops, mods, 4) + def tbuffer(self, ops, mods, count): dst = reg_range(ops[0]) formats = [m for m in mods if m.startswith('format:')] @@ -2627,6 +2698,69 @@ def manifest(self): return '\n'.join(lines) + '\n' +class ComputePipeline(Pipeline): + """One compute program with the root and resource model of Pipeline. COMPUTE_PGM_RSRC2 and the thread group + size are pipeline register state the caller supplies; their meaning follows compute_store_aot (#1608).""" + + def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals=None, decoded=None): + from compute_store_aot import checked_group, entry_registers + try: + self.entry = entry_registers(rsrc2) # (user SGPRs, {axis: group-ID SGPR}, thread-ID VGPRs) + self.group = checked_group(group) + except ValueError as reason: + raise Unsupported(str(reason)) from None + self.root = parse_root(root_blob) + self.vs_fetch, self.packed_position_vgpr, self.rtv_formats = None, None, () + self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap + self.uses_sampler_heap = False + self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] + self.notes, self.modified = set(), set() + self.cs = Stage(self, 'cs', cs_code, refusals=refusals, decoded=decoded) + + def resource(self, key, kind): + if key in self.uavs: + raise Unsupported('descriptor %s used for a load and a store' % (key,)) + return super().resource(key, kind) + + def uav(self, key): + if key in self.resources: + raise Unsupported('descriptor %s used for a load and a store' % (key,)) + return 'u%d' % self.uavs.setdefault(key, len(self.uavs)) + + def common(self): + out = [line for line in super().common() if self.uds or not line.startswith('cbuffer entry')] + return out + ['RWByteAddressBuffer u%d : register(u%d);' % (i, i) for i in sorted(self.uavs.values())] + + def hlsl_cs(self): + s = self.cs + if s.exports: + raise Unsupported('export in a compute program') + body = s.body() + return '\n'.join(self.common() + ['[numthreads(%d, %d, %d)]' % self.group, + 'void main(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID) {'] + + s.declarations() + [' ' + line for line in s.entry] + body + ['}']) + '\n' + + def manifest(self): + # Version 2: `stage cs`, `group` and `uav` lines, which a graphics-only reader must not take for a draw. + lines = ['x2w-manifest 2', 'stage cs', 'group %d %d %d' % self.group, 'ud %d' % len(self.uds)] + lines += ['udsrc %d %s' % (i, ' '.join(str(x) for x in source)) for i, source in enumerate(self.uds)] + for (source, off), r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): + if source[0] == 'table': + where = 'table %d %d' % (source[1], off or 0) + elif source[0] == 'root': + where = 'root %d' % source[1] + else: + raise Unsupported('resource through %s' % (source,)) + lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) + lines += ['uav %d table %d %d' % (i, key[0][1], key[1]) for key, i in sorted(self.uavs.items(), key=lambda kv: kv[1])] + for key, i in self.samplers.items(): + comparison = key[0] == 'cmp' + lines.append('%s %d %s' % ('smpc' if comparison else 'smp', i, ' '.join('0x%x' % w for w in key[comparison:]))) + if self.uses_sampler_heap: + lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) + return '\n'.join(lines) + '\n' + + def fnv(data, h=1469598103934665603): for b in data: h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff From 0236bbcb5bc6fce4483b1c475f7f8c62fa1c0f32 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 04:04:58 +0100 Subject: [PATCH 2/4] startup: tighten the gfx2hlsl compute store and entry from review - Store descriptor: all four words must still be the words the s_load returned. A moved, overwritten or modified word refuses the store. A modification is now recorded for the descriptor the word belongs to (load offset + 4 * (dword & ~3)), not for the load's first descriptor. Translating every locally cached graphics request gave identical output. - Compute: a scalar instruction inside a block s_cbranch_execz skips is refused. The wave runs that block when any lane is active. - Compute: an implicit-LOD image_sample is refused instead of sampling level 0. - An immediate store offset that is not a multiple of 4 is refused. The run-time part is rounded down as in #2059. - Graphics stages keep the unknown-op refusal text for buffer stores. - Root parameters from s4 are documented as an inference, not as #1608. - Fixture: case C stores x4 and, under a compare-set exec, x3. New controls drop case B's immediate offset and case C's exec predicate. Refs #1412 Co-Authored-By: Claude Fable 5.2 --- CMakeLists.txt | 2 +- docs/experiments.md | 58 +++++++--- tests/startup_gfx2hlsl_compute_check.py | 148 +++++++++++++++++++++--- tools/startup/gfx2hlsl.py | 69 ++++++++--- 4 files changed, 227 insertions(+), 50 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5a753396a6..3431f1002e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2602,7 +2602,7 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" dispatch "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - foreach(control IN ITEMS swapped-axes dropped-store) + foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 03e7cfccd8..47daaeeea5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12065,30 +12065,54 @@ python -B tests/startup_gfx2hlsl_mad_check.py binary llvm-mc-15 `gfx2hlsl.ComputePipeline` translates one gfx1013 compute program with the root and resource model of the graphics stages. The caller passes `COMPUTE_PGM_RSRC2` and the thread group size, which are pipeline -register state. Root parameters start at s4. Each group-ID axis enabled by `TGID_X/Y/Z_EN` gets the next -SGPR after the user SGPRs, with no gap for an omitted axis (`SV_GroupID`), and v0-v2 hold -`SV_GroupThreadID` up to `TIDIG_COMP_CNT`. This is the layout `compute_store_aot` uses (#1608). -`TG_SIZE_EN` stays refused. A numeric read of a user SGPR that the root signature does not place, -including s0-s3, is refused because its value is unknown. +register state. Each group-ID axis enabled by `TGID_X/Y/Z_EN` gets the next SGPR after the user +SGPRs, with no gap for an omitted axis (`SV_GroupID`). v0-v2 hold `SV_GroupThreadID` up to +`TIDIG_COMP_CNT`. This is how `compute_store_aot` decodes `COMPUTE_PGM_RSRC2` (#1608). +`TG_SIZE_EN` stays refused. + +Root parameters are placed from s4, which is an inference, like the graphics stages' s8. #1608 defines no +root placement. The only in-repo evidence is the local compute-record scan above, whose table bindings +used s4 or s5. A numeric read of a user SGPR that the root signature does not place, including s0-s3, +is refused because its value is unknown. + +Inside a block that `s_cbranch_execz` skips, a scalar instruction is refused. The wave runs that block +when any lane is active, while the one-lane model would skip it for an inactive lane. An image sample +with implicit LOD is also refused, because a compute lane has no derivatives. The output is a `cs` HLSL main with `[numthreads]` and a version 2 manifest. The manifest has `stage cs` and `group` lines, plus one `uav table ` line for each store target. The only store lowered is `buffer_store_dword[x2|x3|x4]` in the `offen` form: a per-lane byte VGPR, plus the scalar offset and the immediate, through a descriptor at a fixed root-table offset. It writes a -`RWByteAddressBuffer`. Other forms are refused: `off`, `idxen`, the cache-policy flags, a store -through a modified descriptor, and a descriptor that is also loaded. +`RWByteAddressBuffer`. All four descriptor words must still be the words the `s_load` returned. Refused: +- the `off` and `idxen` forms, and the cache-policy flags; +- an immediate offset that is not a multiple of 4; +- a descriptor word that was moved, overwritten or modified; +- a descriptor that is also loaded. + +As in #2059, the run-time part of the address is rounded down to a multiple of 4. That rounding, and the +handling of out-of-range stores, are assumptions, not measurements. The runtime has no slot-67 path yet, so no translated compute program runs in the stand-in. -`startup_gfx2hlsl_compute_check.py` translates two source-built programs. Case A enables all three -group-ID axes and v0-v2, with group size 2x3x4 and 3x2x2 groups. Case B enables X and Z only, so Z -is s8, with group size 5x2x1 and 4x1x3 groups, and stores two words at an immediate offset. Each thread -reads a read buffer at its own index and stores to its own destination. DXC compiles the HLSL for -`cs_6_0`, and a plain D3D12 device dispatches it with a root SRV, a root UAV and the root constants. -All 320 words are compared, including the sentinels. The two controls swap the X and Y group IDs, or -drop the store, and each must mismatch. - -On Windows 11 (26300), all 320 words matched in both cases on WARP (10.0.26100.10068) and on an -RTX 5090 (32.0.16.2135), with the debug layer on. +`startup_gfx2hlsl_compute_check.py` translates three source-built programs: +- Case A enables all three group-ID axes and v0-v2, with group size 2x3x4 and 3x2x2 groups, and stores one word. +- Case B enables X and Z only, so Z is s8, with group size 5x2x1 and 4x1x3 groups. It stores two words at an + immediate offset. +- Case C enables Y only, with group size 8x1x1 and 1x5x1 groups. It stores four words from every lane, then + three words under an exec mask set from a compare. + +Each thread reads a read buffer at its own index and stores to its own destination. DXC compiles the HLSL +for `cs_6_0`, and a plain D3D12 device dispatches it. The root signature is the test runner's (a root SRV, +a root UAV and the root constants), so the manifest's table lines and the descriptor fetch are not exercised +on the GPU. All 320 words are compared, including the sentinels. Four controls must each mismatch: swapping +the X and Y group IDs, dropping the store, dropping case B's immediate offset, and dropping case C's exec +predicate. The pure-Python controls refuse every reviewed input that was previously accepted: a modified +descriptor word, an execz-skipped scalar write, an implicit-LOD sample and a misaligned immediate offset. + +Translating every cached graphics request before and after the descriptor-tracking change gave identical +output and refusals. The local check covered 925 requests, 123 of which translate. + +On Windows 11 (26300), all 320 words matched in every case on WARP (10.0.26100.10068) and on an RTX 5090 +(32.0.16.2135), with the debug layer on. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_' -V diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 3f465abd57..44122847dd 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -4,7 +4,7 @@ binary reassemble the fixture sources and compare them with the words below dispatch translate, compile with DXC cs_6_0, dispatch and compare every word - control + control the same dispatch with a mutated translation, which must mismatch The fixtures are source-built gfx1013 compute programs. The root signature puts two root constants (key, stride) @@ -15,12 +15,16 @@ - case A enables all three group-ID axes and v0-v2, with group size 2x3x4 and 3x2x2 groups, and stores one word; - case B enables X and Z only (Y omitted, so Z is s8), v0-v1, group size 5x2x1 and 4x1x3 groups, and stores two - words at an immediate offset of 8 bytes. - -The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet): root SRV t0 (read buffer), root -UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's r0, u0 and entry cbuffer. -All 320 words are compared, so a word outside the written records must keep the sentinel. The controls swap the -X and Y group IDs at entry or drop the store; either must change the readback. + words at an immediate offset of 8 bytes; +- case C enables Y only (s7), v0 only, group size 8x1x1 and 1x5x1 groups, stores four words with every lane, then + three words at offset 16 under an exec mask set from a compare (lanes with tid.x < 6), and restores exec. + +The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet). The root signature is the runner's: +root SRV t0 (read buffer), root UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's +r0, u0 and entry cbuffer. The manifest's table lines and the descriptor fetch are therefore not exercised on the GPU. +All 320 words are compared, so a word outside the written records must keep the sentinel. The controls swap the X +and Y group IDs at entry, drop the store, drop case B's immediate offset, or drop case C's exec predicate; each must +change the readback. """ import struct import subprocess @@ -98,13 +102,71 @@ def tidig(components): '1406064a' '83060834' '82060e34' '001030e007050380' '060069d5030b0000' '040c0c4a' '703f8cbf' '050d0a3a' 'ff060c3a0000005a' '081074e004050480' '000081bf') +SOURCE_C = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v7, 2, v3 +buffer_load_dword v8, v7, s[12:15], 0 offen +v_mul_u32_u24 v4, 28, v3 +v_mov_b32 v9, v3 +v_mul_lo_u32 v10, v3, s5 +v_add_nc_u32 v10, s4, v10 +s_waitcnt vmcnt(0) +v_xor_b32 v11, v8, v10 +buffer_store_dwordx4 v[8:11], v4, s[16:19], 0 offen +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_mov_b32 exec_lo, vcc_lo +buffer_store_dwordx3 v[8:10], v4, s[16:19], 0 offen offset:16 +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_C = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060e34' '001030e007080380' + '9c060816' '0303127e' '0a0069d5030b0000' '0414144a' '703f8cbf' '0815163a' '001078e004080480' '7e0395be' + '8600887d' '6a03febe' '10107ce004080480' '1503febe' '000081bf') + CASES = { # name: (source, words, rsrc2, group size, group counts) 'A': (SOURCE_A, WORDS_A, USER7 | TGID_X | TGID_Y | TGID_Z | tidig(3), (2, 3, 4), (3, 2, 2)), 'B': (SOURCE_B, WORDS_B, USER7 | TGID_X | TGID_Z | tidig(2), (5, 2, 1), (4, 1, 3)), + 'C': (SOURCE_C, WORDS_C, USER7 | TGID_Y | tidig(1), (8, 1, 1), (1, 5, 1)), +} + +# Single instructions the controls splice into case A before its store, recorded from llvm-mc 15. +STORE_A = WORDS_A.index(bytes.fromhex('001070e004050480')) +SPLICE = { + 's_mov_b32 s18, 0': '800392be', + 's_or_b32 s17, s17, 0x40000': '11ff118800000400', + 's_and_b32 s18, s18, 0xffff': '12ff1287ffff0000', + 's_mov_b32 s18, 4': '840392be', + 'v_cmp_gt_u32 vcc_lo, 1, v0': '8100887d', + 's_and_saveexec_b32 s0, vcc_lo': '6a3c80be', + 's_cbranch_execz 1': '010088bf', + 's_add_u32 s20, s7, 1': '07811480', + 's_or_b32 exec_lo, exec_lo, s0': '7e007e88', + 'v_mov_b32 v5, s20': '14020a7e', + 's_mov_b32 s21, exec_lo': '7e0395be', + 's_mov_b32 exec_lo, vcc_lo': '6a03febe', + 's_mov_b32 exec_lo, s21': '1503febe', + 's_mov_b64 s[20:21], 0': '800494be', + 's_mov_b64 s[22:23], 0': '800496be', + 's_load_dwordx8 s[24:31], s[10:11], 0x40': '05060cf4400000fa', + 'image_sample v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D': '080f80f0000ca600', + 'image_sample_lz v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D': '080f9cf0000ca600', + 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', + 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:6': '061070e004050480', } +def splice(*lines, at=STORE_A): + return WORDS_A[:at] + b''.join(bytes.fromhex(SPLICE[line]) for line in lines) + WORDS_A[at:] + + def root_blob(): """RTS0: param 0 = two root constants (b0), param 1 = a descriptor table with no ranges.""" params_at, constants_at = 24, 24 + 2 * 12 @@ -132,6 +194,12 @@ def expected(name): if name == 'A': i = (gx + 3 * gy + 6 * gz) * 24 + tx + 2 * ty + 6 * tz out[i] = ((input_word(i) * 33) & MASK) ^ ((KEY + i * STRIDE) & MASK) + elif name == 'C': + i = gy * 8 + tx + record = [input_word(i), i, (KEY + i * STRIDE) & MASK] + out[7 * i:7 * i + 4] = record + [record[0] ^ record[2]] + if tx < 6: + out[7 * i + 4:7 * i + 7] = record else: i = (gx + 4 * gz) * 10 + tx + 5 * ty out[2 + 2 * i] = input_word(i) ^ ((KEY + i * STRIDE) & MASK) @@ -197,12 +265,50 @@ def check_controls(): ('005070e004050480', 'modifier glc'), # glc offen ('001070e004050380', 'used for a load and a store')): # store through the read descriptor refused(fragment, lambda w=word: translate('A', code=patch(WORDS_A, store, w)).hlsl_cs()) - refused('buffer store in the ps stage', lambda: G.Stage.op_buffer_store_dword( - type('P', (), {'kind': 'ps'})(), ['v5', 'v4', 's[16:19]', '0'], ['offen'])) + # Graphics stages keep the unknown-op refusal text, so refusal census buckets do not move. + for count, text in ((1, 'buffer_store_dword'), (4, 'buffer_store_dwordx4')): + try: + G.Stage.op_buffer_store_dword(type('P', (), {'kind': 'ps'})(), ['v5', 'v4', 's[16:19]', '0'], ['offen'], count) + except G.Unsupported as reason: + assert str(reason) == text, str(reason) + else: + raise AssertionError('graphics store accepted') # A register soffset is added to the address. hlsl = translate('A', code=patch(WORDS_A, store, '001070e004050414')).hlsl_cs() assert ' a = (v4 + s20 + 0) & 0xfffffffcu;' in hlsl.splitlines(), hlsl - print('compute entry, numthreads, manifest, offen store forms and 9 refusals pass') + # An immediate offset that is not a multiple of 4 is refused, not rounded down. + refused('unaligned immediate offset 6', lambda: translate( + 'A', code=patch(WORDS_A, store, SPLICE['buffer_store_dword v5, v4, s[16:19], 0 offen offset:6'])).hlsl_cs()) + # Descriptor words: a word that is overwritten, moved or modified before the store refuses it, including a word + # that is not the first of its s_load and a constant move. Each input below was accepted before. + for lines in (['s_mov_b32 s18, 0'], ['s_or_b32 s17, s17, 0x40000'], ['s_and_b32 s18, s18, 0xffff'], + ['buffer_store_dword v5, v4, s[16:19], 0 offen', 's_mov_b32 s18, 4']): + refused('modified descriptor', lambda lines=lines: translate('A', code=splice(*lines)).hlsl_cs()) + # The modification is recorded for the descriptor the word belongs to (byte 16 of the x8 load), not for the + # load's first descriptor: loads through the read descriptor at byte 0 are unaffected. + refusals = [] + pipe = G.ComputePipeline(splice('s_and_b32 s18, s18, 0xffff'), root_blob(), CASES['A'][2], (2, 3, 4), refusals=refusals) + assert pipe.modified == {(('table', 1), 16)}, pipe.modified + assert [G.normalize_refusal(r) for r, _ in refusals] == ['buffer store through a modified descriptor'], refusals + # A scalar write in a block s_cbranch_execz skips: the wave runs it when any lane is active, so a per-lane skip + # would store 0 for inactive lanes. Refused with exec from a plain move and in the saveexec form. + for lines in (['s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_mov_b32 exec_lo, vcc_lo', + 's_cbranch_execz 1', 's_add_u32 s20, s7, 1', 's_mov_b32 exec_lo, s21', 'v_mov_b32 v5, s20'], + ['v_cmp_gt_u32 vcc_lo, 1, v0', 's_and_saveexec_b32 s0, vcc_lo', 's_cbranch_execz 1', + 's_add_u32 s20, s7, 1', 's_or_b32 exec_lo, exec_lo, s0', 'v_mov_b32 v5, s20']): + refused('s_add_u32 inside a block s_cbranch_execz skips', lambda lines=lines: translate( + 'A', code=splice(*lines)).hlsl_cs()) + # The same block without the branch translates: the scalar write then runs for every lane. + translate('A', code=splice('s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_mov_b32 exec_lo, vcc_lo', + 's_add_u32 s20, s7, 1', 's_mov_b32 exec_lo, s21', 'v_mov_b32 v5, s20')).hlsl_cs() + # An implicit-LOD sample has no derivatives in a compute lane; the level-zero form translates. + load = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40') + sample = 'image_sample v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D' + refused('image_sample with implicit LOD', lambda: translate('A', code=splice(*load, sample)).hlsl_cs()) + lz = translate('A', code=splice(*load, sample.replace('image_sample', 'image_sample_lz'))).hlsl_cs() + assert '.SampleLevel(' in lz, lz + print('compute entry, numthreads, manifest, offen store forms and the store, descriptor, execz and sample ' + 'refusals pass') def assemble(llvm_mc, source): @@ -214,15 +320,25 @@ def check_binary(llvm_mc): for name, (source, words, *_rest) in CASES.items(): built = assemble(llvm_mc, source) assert built == words, '%s: assembled %s, recorded %s' % (name, built.hex(), words.hex()) + for line, words in SPLICE.items(): + built = assemble(llvm_mc, line + '\n').hex() + assert built == words, '%s: assembled %s, recorded %s' % (line, built, words) print('fixture words match llvm-mc') +# control -> (case, text the translation must contain once, replacement) +CONTROLS = { + 'swapped-axes': ('A', ' s7 = gid.x;\n s8 = gid.y;\n', ' s7 = gid.y;\n s8 = gid.x;\n'), + 'dropped-store': ('A', ' u0.Store(a, v5);\n', ''), + 'b-offset': ('B', ' a = (v4 + 8) & 0xfffffffcu;\n', ' a = (v4 + 0) & 0xfffffffcu;\n'), + 'c-unpredicated': ('C', 'if (exec & 1) u0.Store3(', 'u0.Store3('), +} + + def mutate(hlsl, control): - if control == 'swapped-axes': - assert ' s7 = gid.x;\n s8 = gid.y;\n' in hlsl - return hlsl.replace(' s7 = gid.x;\n s8 = gid.y;\n', ' s7 = gid.y;\n s8 = gid.x;\n') - assert control == 'dropped-store' and hlsl.count('u0.Store(') == 1 - return hlsl.replace(' u0.Store(a, v5);\n', '') + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) def run_case(name, dxc, runner, adapter, directory, control=None): @@ -244,7 +360,7 @@ def check_dispatch(dxc, runner, adapter, control=None): out = HERE.parent / 'out' out.mkdir(exist_ok=True) with tempfile.TemporaryDirectory(dir=out) as tmp: - for name in (('A',) if control else CASES): + for name in ((CONTROLS[control][0],) if control else CASES): run = run_case(name, dxc, runner, adapter, Path(tmp), control) print(run.stdout, end='') if run.returncode == 77: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index fbeaf146b4..9a8fa61fe0 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -396,6 +396,16 @@ def reg_range(tok): return None +# Scalar instructions with no scalar or exec effect, allowed inside a compute block s_cbranch_execz skips. +SKIPPABLE_SCALAR = ('s_waitcnt', 's_nop', 's_inst_prefetch', 's_clause', 's_cbranch_', 's_branch') + + +def desc_key(sym): + """Resource key of the descriptor a ('desc', source, load offset, dword) word belongs to: the key descriptor() + gives its first word, so a write into a later descriptor of a wide load marks that descriptor.""" + return sym[1], None if sym[2] is None else sym[2] + 4 * (sym[3] & ~3) + + def smem_offset(tok): """The SMEM offset operand as a token: 'off' (no offset operand) is the literal 0, anything else unchanged.""" return '0' if tok == 'off' else tok @@ -461,7 +471,9 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): # ---- entry state --------------------------------------------------------------------- def setup_entry(self): root = self.pipe.root - # Compute root parameters start at s4 (s0-s3 are not modelled); graphics stages start at s8. + # Graphics root parameters start at s8. For compute, s4 is an inference, not a documented layout: the only + # in-repo evidence is a local compute-record scan whose table bindings used s4 or s5 (docs/experiments.md). + # s0-s3 are not modelled. reg = 4 if self.kind == 'cs' else 8 for index, p in enumerate(root['params']): if p['type'] == 0: @@ -492,9 +504,10 @@ def setup_entry(self): self.sym[reg] = ('const', 0) # primitive mask: only ever moved to m0 def setup_compute_entry(self, root_end): - """Entry registers of a compute wave (compute_store_aot.entry_registers): the user SGPRs, then one SGPR per - enabled group-ID axis (SV_GroupID), and v0..v2 holding SV_GroupThreadID. User SGPRs the root signature does - not place (s0-s3 and any past the root's span) have no known value, so any numeric read of them is refused.""" + """Entry registers of a compute wave as compute_store_aot.entry_registers (#1608) gives them: the user SGPRs, + then one SGPR per enabled group-ID axis (SV_GroupID), and v0..v2 holding SV_GroupThreadID. Where the root + parameters sit inside the user SGPRs (from s4) is this translator's inference. User SGPRs the root does not + place (s0-s3 and any past the root's span) have no known value, so any numeric read of them is refused.""" user, groups, threads = self.pipe.entry if root_end > user: raise Unsupported('root signature needs s4-s%d, COMPUTE_PGM_RSRC2 gives %d user SGPRs' % (root_end - 1, user)) @@ -707,9 +720,13 @@ def const_words(self, tok): # ---- instruction translation ------------------------------------------------------------- def translate(self): targets = set() + skipped = [] # compute: (branch, target) of each s_cbranch_execz for off, n, name, asm in self.ins: if name.startswith('s_cbranch') or name == 's_branch': - targets.add(int(parse(asm)[1][0].split('_')[1], 16)) + target = int(parse(asm)[1][0].split('_')[1], 16) + targets.add(target) + if name == 's_cbranch_execz' and self.kind == 'cs': + skipped.append((off, target)) self.blocks = [] # (offset, [lines], terminator) self.uniform_v = set() self.varying_s = set() @@ -723,6 +740,12 @@ def translate(self): self.lines, start = [], off self.pc = off try: + if any(branch < off < target or target <= off < branch for branch, target in skipped) and ( + name.startswith(('s_', 'v_readlane', 'v_readfirstlane', 'v_writelane')) + and not name.startswith(SKIPPABLE_SCALAR)): + # The wave runs this block when any lane is active, so its scalar state changes for every + # lane; the one-lane model would skip it for an inactive lane. + raise Unsupported('%s inside a block s_cbranch_execz skips per lane' % name) term = self.one(name, asm) except Unsupported as reason: if refusals is None: @@ -1089,7 +1112,10 @@ def src_sym(t): self.varying_s.add(d + 1) elif own and own[0] in ('desc', 'ptr', 'ptrhi') and any(s == own for s in syms): if own[0] == 'desc': - self.pipe.modified.add((own[1], own[2])) + self.pipe.modified.add(desc_key(own)) + # The word keeps its descriptor identity for loads; an exact-word check (unmodified_descriptor) + # sees the mark. + self.sym[d] = own[:4] + ('modified',) else: self.sym[d] = ('descnum',) return None @@ -1551,10 +1577,10 @@ def op_buffer_load_dwordx4(self, ops, mods): def op_buffer_store_dword(self, ops, mods, count=1): # Compute-stage store in the offen form: per-lane byte VGPR plus the scalar offset and the 12-bit immediate, # through a descriptor read from a fixed root-table slot, to a RWByteAddressBuffer (manifest `uav` line). - # Like the loads, this assumes a raw descriptor (no swizzle or stride) and that the runtime sizes the view - # to the descriptor's range, so an out-of-range store is dropped on both sides. + # Like the loads, this assumes a raw descriptor (no swizzle or stride). Out-of-range stores: assumes a future + # runtime sizes the view to the descriptor's range so both sides drop them; nothing binds or checks that yet. if self.kind != 'cs': - raise Unsupported('buffer store in the %s stage' % self.kind) + raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal offset = 0 for m in mods: if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): @@ -1568,11 +1594,16 @@ def op_buffer_store_dword(self, ops, mods, count=1): raise Unsupported('buffer store data %s' % ops[0]) if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: raise Unsupported('buffer store vaddr %s for offen' % ops[1]) - key = self.descriptor(ops[2]) - if key[0][0] != 'table' or key[1] is None: - raise Unsupported('buffer store through %s' % (key,)) - if key in self.pipe.modified: + # All four words must still be the loaded words of one descriptor at a fixed table offset: a moved, + # overwritten or modified word (stride, num_records) would change what the store does. + rsrc = reg_range(ops[2]) + first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == 3 else None + if not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or first[3] % 4: + raise Unsupported('buffer store through %s holding %s' % (ops[2], first)) + if (any(self.sym.get(rsrc[1] + k) != first[:3] + (first[3] + k,) for k in range(4)) + or desc_key(first) in self.pipe.modified): raise Unsupported('buffer store through a modified descriptor') + key = desc_key(first) terms = [self.u(ops[1])] if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): offset += int(ops[3], 0) @@ -1581,11 +1612,13 @@ def op_buffer_store_dword(self, ops, mods, count=1): if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: raise Unsupported('buffer soffset %s' % ops[3]) terms.append(self.S(sreg[1])) + if offset % 4: + raise Unsupported('buffer store at unaligned immediate offset %d' % offset) uav = self.pipe.uav(key) words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) - # shortcut: Store* needs a multiple of four, so a misaligned address is rounded down (dword buffer access is - # assumed to ignore the low two bits); refuse misaligned addresses instead if a program depends on them. + # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: + # an assumption that a dword access ignores the low two address bits, not a measurement. self.emit('a = (%s + %d) & 0xfffffffcu;' % (' + '.join(terms), offset)) store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else count, data) self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) @@ -1723,6 +1756,9 @@ def image(self, ops, mods, how): uv = 'float3(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) else: uv = 'float2(%s, %s)' % (self.f(cs[0]), self.f(cs[1])) + if how == 'sample' and self.kind == 'cs': + # A compute lane has no pixel quad to supply derivatives; level 0 would be a guess. + raise Unsupported('image_sample with implicit LOD in a compute program') if how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'lz' or not self.exec_known or self.kind != 'ps' or len(self.blocks) > 0: @@ -2700,7 +2736,8 @@ def manifest(self): class ComputePipeline(Pipeline): """One compute program with the root and resource model of Pipeline. COMPUTE_PGM_RSRC2 and the thread group - size are pipeline register state the caller supplies; their meaning follows compute_store_aot (#1608).""" + size are pipeline register state the caller supplies; COMPUTE_PGM_RSRC2 is decoded as compute_store_aot does + (#1608). Root parameters from s4 are an inference (see Stage.setup_entry).""" def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals=None, decoded=None): from compute_store_aot import checked_group, entry_registers From 94b042bac51961db9be4fd5218b3ab0eb92d9c01 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 04:40:30 +0100 Subject: [PATCH 3/4] test: pin the unguarded out-of-range compute store in gfx2hlsl A store whose immediate offset puts it past the descriptor's range still translates to a plain RWByteAddressBuffer Store with no range check, and the manifest carries no size: num_records and stride are not read, and dropping such a store is left to a runtime that sizes the view. The control pins that stated behaviour, so changing the policy has to update it (review nit on #2182). Co-Authored-By: Claude Fable 5.2 --- tests/startup_gfx2hlsl_compute_check.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 44122847dd..890783405a 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -160,6 +160,7 @@ def tidig(components): 'image_sample_lz v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D': '080f9cf0000ca600', 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:6': '061070e004050480', + 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:4092': 'fc1f70e004050480', } @@ -279,6 +280,16 @@ def check_controls(): # An immediate offset that is not a multiple of 4 is refused, not rounded down. refused('unaligned immediate offset 6', lambda: translate( 'A', code=patch(WORDS_A, store, SPLICE['buffer_store_dword v5, v4, s[16:19], 0 offen offset:6'])).hlsl_cs()) + # Past the range: today the translation carries no range check (num_records and stride are not read) and the + # manifest no size, so an out-of-range store reaches the UAV unguarded and only a runtime that sizes the view + # to the descriptor's range drops it. Pinned so a change of that policy has to update this control. + far = translate('A', code=patch(WORDS_A, store, SPLICE['buffer_store_dword v5, v4, s[16:19], 0 offen offset:4092'])) + lines = far.hlsl_cs().splitlines() + at = lines.index(' a = (v4 + 4092) & 0xfffffffcu;') + assert lines[at + 1] == ' u0.Store(a, v5);', lines[at:at + 2] + body = far.hlsl_cs().split('void main(', 1)[1] + assert not any(word in body for word in ('GetDimensions', 'min(', 'if (a')), body + assert far.manifest().splitlines()[-1] == 'uav 0 table 1 16', far.manifest() # Descriptor words: a word that is overwritten, moved or modified before the store refuses it, including a word # that is not the first of its s_load and a constant move. Each input below was accepted before. for lines in (['s_mov_b32 s18, 0'], ['s_or_b32 s17, s17, 0x40000'], ['s_and_b32 s18, s18, 0xffff'], From 5633dcd0ff9aa43efe2d678274eb584bf290c798 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 06:26:07 +0100 Subject: [PATCH 4/4] startup: let a bare stage reach the image refusals before the compute D16 guard The compute D16 guard added in 0a523d0e reads self.kind at the top of Stage.image. Checks that build a bare Stage to reach the operand-only refusals (tests/startup_image_sample_l_check.py and others) have no kind, so the Linux Python job failed with AttributeError. Read kind with a default; the guard is unchanged for a compute stage. Co-Authored-By: Claude Fable 5.2 --- tools/startup/gfx2hlsl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 839dec1cae..f855af54be 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1800,7 +1800,7 @@ def op_tbuffer_load_format_xyzw(self, ops, mods): self.tbuffer(ops, mods, 4) def image(self, ops, mods, how): - if self.kind == 'cs' and 'd16' in mods: + if getattr(self, 'kind', None) == 'cs' and 'd16' in mods: raise Unsupported('compute d16 image load requires validated SRV formats') dst = reg_range(ops[0]) dim = [m for m in mods if m.startswith('dim:')][0][4:]