Skip to content
Closed
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
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3402,6 +3402,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")
Comment thread
tedin7 marked this conversation as resolved.
Resolved
# Startup shader translator: symbols that are not constants (descriptors, pointers, pairs) at a branch join.
add_test(NAME startup_gfx2hlsl_join_symbols_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_join_symbols_check.py")
Expand Down
3 changes: 3 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -13675,10 +13675,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`.
Expand Down
72 changes: 72 additions & 0 deletions tests/startup_gfx2hlsl_sload_const_offset_check.py
Original file line number Diff line number Diff line change
@@ -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)
23 changes: 23 additions & 0 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1946,6 +1946,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))
Expand Down Expand Up @@ -2159,6 +2162,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
Comment thread
tedin7 marked this conversation as resolved.
Resolved
return None

def op_s_load_dwordx4(self, ops, mods, count=4):
imm = smem_mods(mods)
if len(ops) != 3:
Expand All @@ -2176,6 +2191,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:
Comment thread
tedin7 marked this conversation as resolved.
Resolved
# 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:
Expand Down
Loading