From eb931ba9d3f432673eb56762db1fca9b207c95b6 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 02:01:21 +0100 Subject: [PATCH] startup: s_load with a constant register offset reaches the heap descriptor (#1723) Fold only in shaders without branches, sign-extend s_movk_i32, and document the accepted form. --- CMakeLists.txt | 3 + docs/experiments.md | 3 + ...artup_gfx2hlsl_sload_const_offset_check.py | 72 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 23 ++++++ 4 files changed, 101 insertions(+) create mode 100644 tests/startup_gfx2hlsl_sload_const_offset_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 884ff147f5..2c340cd5a0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3284,6 +3284,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: scalar constants are dropped at a branch join that another path writes (loop counters). add_test(NAME startup_gfx2hlsl_loop_constants COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_loop_constants_check.py") + # Startup shader translator: s_load with a register offset holding a known constant reaches the heap descriptor (#1723). + add_test(NAME startup_gfx2hlsl_sload_const_offset COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_const_offset_check.py") # Startup shader translator: uniform sources of v_readfirstlane_b32 in straight-line code and entry blocks (#1723). add_test(NAME startup_gfx2hlsl_readfirstlane_uniform COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index d2ed94c46d..cb9a211f35 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13342,10 +13342,13 @@ python -B tools/startup/gfx2hlsl.py --refusals out/startup/shader_cache | a literal (`0x4`, `16`) | byte offset into the buffer, `rN.Load(0x00000004u + 4 * i)` | byte offset from the pointer | | `off` | the literal 0 | the literal 0 | | `m0` | register byte offset, `rN.Load(m0 + 4 * i)` | refused (`s_load with a register offset through ...`), except for the run-time sampler heap index | +| `s0`..`s105` holding a constant (`s_mov_b32`/`s_movk_i32` before the load) | not changed | that constant as a literal byte offset, plus any `offset:` modifier; the total is 0..0xfffff | | anything else (`null`, `OFF`, `offset`, ...) | refused (`operand '...'`) | refused | `off` names no offset at all, so it is translated exactly as the literal 0: the same emitted HLSL, the same descriptor offset for a table load, and the same fixed-word marking of an `s_buffer_load` result. Before this change, `s_buffer_load_dword s0, s[4:7], off` was refused with `operand 'off'`, and the `s_load` form with the misleading register-offset message. `tests/startup_gfx2hlsl_smem_offset_check.py` drives each load handler on a scalar symbol state with no machine code. It compares the `off` form of `s_buffer_load_dword`, `_dwordx2` and `_dwordx4`, of `s_load_dword` and `_dwordx2` from a root buffer and of `s_load_dwordx8` from a descriptor table with the literal 0, keeps the literal and `m0` behaviour above, and requires five other operand spellings to be refused by both kinds of load. With the `off` handling removed in-process, both `off` forms must be refused again. Test: `startup_gfx2hlsl_smem_offset`. Not covered here: whether the full set of locally refused shaders now translates, which needs local inputs. +**Constant register offsets for `s_load_dword*`.** An SGPR that holds a known constant (`s_movk_i32 s9, 0x40` before the load) is translated as the literal offset, which reaches descriptors in a bindless heap. Limits: the proof is used only in shaders without branches, because symbols are not merged at control-flow joins; `s_movk_i32` sign-extends its 16-bit immediate, so `0x8000` and above become negative and stay refused; the run-time sampler heap index is unchanged; an SGPR with an unknown value, `m0`, and a total above 0xfffff stay refused. Measured on CPU only (Linux translation); Windows, D3D12 and GPU behavior are not measured. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sload_const_offset$' -V` or `python3 -B tests/startup_gfx2hlsl_sload_const_offset_check.py`. [Part of #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) + ### Scalar writes to and symbolic tracking of `m0` `Stage.scalar()` in [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) previously returned `None` whenever `dname == 'm0'`, dropping every scalar ALU write (and its `SCC` update) to `m0` even though `Stage.u('m0')` and `Stage.op_s_buffer_load_dword()` read `m0` as a runtime `uint` variable. In addition, `scalar_select()`, `op_s_bfm_b32()`, `op_s_and_saveexec_b64()` and `op_s_andn2_wrexec_b64()` subscripted `reg_range(ops[0])` directly, raising `TypeError` on `m0`, and 64-bit scalar operations (`*_b64`, where `decode_s_reg64(124)` prints `m0`) silently vanished or raised `TypeError`. diff --git a/tests/startup_gfx2hlsl_sload_const_offset_check.py b/tests/startup_gfx2hlsl_sload_const_offset_check.py new file mode 100644 index 0000000000..4a7e42bc4b --- /dev/null +++ b/tests/startup_gfx2hlsl_sload_const_offset_check.py @@ -0,0 +1,72 @@ +"""Check s_load with a register offset that holds a known constant (#1723). + +usage: startup_gfx2hlsl_sload_const_offset_check.py + +A title loads a descriptor from the resource heap with the byte offset in a scalar register that an earlier +s_movk filled. The translator must read that register as the literal offset (plus any offset: modifier), so +the result equals the literal form. An unknown register, m0, and the sampler heap keep their old handling. +""" +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +class Pipe: + sampler_heap = False + + def resource(self, key, kind): + return 'r0' + + +def run(symbols, op, operands, mods=(), branches=False): + s = G.Stage.__new__(G.Stage) + s.pipe, s.sym, s.lines = Pipe(), dict(symbols), [] + s.used_s, s.used_v, s.uniform_v, s.exec_known = set(), set(), set(), True + s.has_branches, s.masks = branches, set() + try: + if hasattr(s, 'op_' + op): + getattr(s, 'op_' + op)(operands.split(', '), list(mods)) + else: + s.one(op, '%s %s' % (op, operands)) + except G.Unsupported as error: + return str(error) + return s.sym + + +HEAP = {4: ('ptr', ('resheap',)), 9: ('const', 0x40), 10: ('ud', 0)} +want = [('desc', ('resheap',), 0x40, i) for i in range(8)] + +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s9') +check('constant register offset reaches the heap descriptor', + isinstance(got, dict) and [got[16 + i] for i in range(8)] == want, repr(got)) +literal = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], 0x40') +check('same as the literal offset', isinstance(got, dict) and isinstance(literal, dict) + and [got[16 + i] for i in range(8)] == [literal[16 + i] for i in range(8)]) +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s9', ['offset:0x20']) +check('offset: modifier adds to the register', isinstance(got, dict) and got[16] == ('desc', ('resheap',), 0x60, 0), repr(got)) +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s10') +check('unknown register still refused', got == "s_load with a register offset through ('resheap',)", repr(got)) +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], m0') +check('m0 still refused', got == "s_load with a register offset through ('resheap',)", repr(got)) + +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s9', branches=True) +check('constant offset in a shader with branches is refused', got == "s_load with a register offset through ('resheap',)", repr(got)) +got = run({}, 's_movk_i32', 's9, 0x8000') +check('s_movk_i32 sign-extends its 16-bit immediate', isinstance(got, dict) and got[9] == ('const', 0xffff8000), repr(got)) +got = run({4: ('ptr', ('resheap',)), 9: ('const', 0xffff8000)}, 's_load_dwordx8', 's[16:23], s[4:5], s9') +check('a negative movk offset is refused', got == "s_load with a register offset through ('resheap',)", repr(got)) +got = run({}, 's_movk_i32', 's9, 0x7fff') +check('positive movk immediate unchanged', isinstance(got, dict) and got[9] == ('const', 0x7fff), repr(got)) + +print('s_load constant offset checks: %d failed' % len(failures)) +sys.exit(1 if failures else 0) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1c45b6733a..b98cf81001 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1697,6 +1697,9 @@ def src_sym(t): for t in srcs) and base.split('_')[1] in ('mov', 'and', 'or', 'xor', 'andn2', 'orn2', 'nand', 'nor', 'xnor', 'not', 'cselect') if base in ('s_mov_b32', 's_mov_b64', 's_movk_i32') and re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', srcs[0]) and srcs[0] not in FLOATS: value = int(srcs[0], 0) + if base == 's_movk_i32' and 0x8000 <= value <= 0xffff: + value -= 0x10000 # the 16-bit immediate is sign-extended into the SGPR + values = ['0x%08xu' % (value & 0xffffffff)] + list(values[1:]) self.set_s(d, values[0], ('const', value & 0xffffffff)) if pair: self.set_s(d + 1, '0x%08xu' % ((value >> 32) & 0xffffffff), ('const', (value >> 32) & 0xffffffff)) @@ -1909,6 +1912,18 @@ def smem_soffset(self, tok, record_use=True): self.used_s = saved raise Unsupported('operand %r' % tok) + def const_soffset(self, tok): + """The constant held by an SMEM offset register s0..s105, or None (m0 and unknown values).""" + r = reg_range(tok) + # Symbols are not merged at control-flow joins, so a constant proves the runtime value only without branches. + if getattr(self, 'has_branches', True): + return None + if r and r[0] == 's' and r[1] == r[2] and r[1] <= 105: + value = self.is_const(r[1]) + if value is not None and 0 <= value <= 0xfffff: + return value + return None + def op_s_load_dwordx4(self, ops, mods, count=4): imm = smem_mods(mods) if len(ops) != 3: @@ -1926,6 +1941,14 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load through s%d holding %s' % (base[1], p)) # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. token = smem_offset(ops[2]) + known = self.const_soffset(token) if p[1] != ('smpheap',) else None + if known is not None: + # A register offset that holds a known constant (s_movk before the load) is that literal byte + # offset; the modifier adds to it. This reaches descriptors in a bindless heap (#1723). + total = known + (imm or 0) + if total > 0xfffff: + raise Unsupported('SMEM register offset %#x' % total) + token, imm = str(total), None if re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', token): off = int(token, 0) if off < 0 or off > 0xfffff: