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
1 change: 1 addition & 0 deletions .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ jobs:
tests/startup_translator_check.py \
tests/startup_gfx2hlsl_smem_offset_check.py \
tests/startup_gfx2hlsl_scalar_m0_check.py \
tests/startup_gfx2hlsl_swap_check.py \
tests/startup_triage_run_check.py \
tests/startup_run_ps1_check.py \
tests/startup_flat_param_check.py \
Expand Down
4 changes: 4 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2324,6 +2324,10 @@ if(EXISTS "${INTAKE_PYTHON}")
# Startup shader translator: the SMEM offset 'off' is the literal 0; m0 and other operands keep their handling (#1674).
add_test(NAME startup_gfx2hlsl_smem_offset COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_smem_offset_check.py")
# v_swap_b32 exchanges two VGPRs in the translator (#1723); compiles the emitted HLSL with DXC and FXC.
add_test(NAME startup_gfx2hlsl_swap COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_swap_check.py" compile "${DXC_EXECUTABLE}"
$<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>)
add_test(NAME startup_triage_run COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_triage_run_check.py")
add_test(NAME startup_run_ps1 COMMAND "${INTAKE_PYTHON}" -B
Expand Down
10 changes: 10 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -11194,6 +11194,16 @@ old lowering used as y. Full-width loads still accept cache-policy flags. Plain
patched 2D `a16` instruction carrying an unexpected NSA extension are refused, and that the runtime
and offline cache keys use the same revision. The check verifies translation on the CPU.

## Startup translator: v_swap_b32

The VOP1 `v_swap_b32 vdst, vsrc` exchanges two VGPRs. The translator refused it with `Unsupported: v_swap_b32`; in the offline shader-archive census of #1723, 2 of the 1,171 pixel and vertex program pairs stop there. The handler (`op_v_swap_b32` in `tools/startup/gfx2hlsl.py`) emits `{ uint swap_tmp = vA; vA = vB; vB = swap_tmp; }`, guarded by `if (exec & 1)` when the exec mask is not known, emits nothing when both registers are the same, and drops the proven-uniform status of both registers. The instruction has no output or source modifier and no VOP3 form (LLVM 19 rejects `v_swap_b32_e64` for gfx1010 and gfx1030); two single VGPR operands (`v0`..`v255`) are required, so a scalar, constant, register range, out-of-range VGPR, modifier or wrong operand count is refused, and the SDWA, DPP16 and VOP3A spellings stay refused by the decoder. The operation follows the [AMD RDNA 2 ISA](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) (VOP1 opcode 101).

The fixture (`tests/startup_gfx2hlsl_swap_check.py`) is synthetic only: it builds the instruction words from the public VOP1 field layout and checks them against the bytes LLVM 19 assembles (`02 cb 02 7e` for `v_swap_b32 v1, v2`). It checks the emitted exchange, the exec guard, the same-register case, a later read of the swapped register, the uniform status, nine operand refusals, a modifier, and the SDWA, DPP16 and VOP3A spellings. On Windows (`compile` mode, registered in CTest), it also compiles a full translated pixel shader containing two sequential swaps and an exec-guarded swap with DXC (`ps_6_0`) and FXC (`ps_5_1`) cleanly with no warnings. Not measured: no WARP or hardware draw runs through this check. The pixel path lowers the same instruction in `tools/pixel_aot.py`.

```powershell
ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_swap$' -V
```

## Startup translator: pixel depth export

The startup translator emits `SV_Depth` for an uncompressed `exp mrtz vN, off, off, off` in a straight-line pixel shader that still uses its entry execution mask. Color exports in the same shader keep their `SV_Target` outputs. Additional MRTZ channels, packed exports, multiple depth exports, branches and changes to the execution mask before the depth export are refused.
Expand Down
189 changes: 189 additions & 0 deletions tests/startup_gfx2hlsl_swap_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"""v_swap_b32 in tools/startup/gfx2hlsl.py (found by the offline shader census in #1723).

usage: startup_gfx2hlsl_swap_check.py

The VOP1 `v_swap_b32 vdst, vsrc` exchanges two VGPRs. The translator refused it with
`Unsupported: v_swap_b32`; 2 of the 1,171 pixel and vertex program pairs of the census stop there.

The instruction words are **constructed here** from the public VOP1 field layout (AMD RDNA 2 ISA, VOP1:
[8:0] SRC0, [16:9] OP, [24:17] VDST, [31:25] 0b0111111) with OP = 101 for V_SWAP_B32, and are also checked
against the bytes LLVM 19 assembles for `v_swap_b32 v1, v2` (02 cb 02 7e, gfx1010 and gfx1030).
"""
import os
import struct
import subprocess
import sys
import tempfile
from pathlib import Path

here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, here)
sys.path.insert(0, os.path.join(here, '..', 'tools'))
sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup'))
import gfx2hlsl as G # noqa: E402
from startup_flat_param_check import VS_WORDS, root_blob # noqa: E402

failures = []


def check(label, condition, detail=''):
print(f"{label}: {'ok' if condition else 'MISMATCH'}")
if not condition:
failures.append(label)
if detail:
print(' ' + detail)


V_SWAP_B32 = 101
VOP1_PREFIX = 0b0111111


def encode_vop1(op, vdst, src0):
"""A VOP1 word; src0 uses the 9-bit source field (VGPRs from 256)."""
return struct.pack('<I', (VOP1_PREFIX << 25) | ((vdst & 0xff) << 17) | ((op & 0xff) << 9) | (src0 & 0x1ff))


class Pipeline:
def __init__(self):
self.resources, self.notes, self.modified, self.sampler_heap = {}, set(), set(), False


class Stage(G.Stage):
"""A Stage with no pipeline: enough state for a decoded instruction to be translated."""

def __init__(self, exec_known=True):
self.lines, self.sym = [], {}
self.used_s, self.used_v, self.uniform_v = set(), set(), set()
self.exec_known = exec_known
self.exports = {}
self.pipe = Pipeline()


def translate(code, exec_known=True):
stage = Stage(exec_known)
for _offset, _size, name, asm in G.decode(code):
stage.one(name, asm)
return stage


def refused(code):
try:
translate(code)
except G.Unsupported as error:
return str(error)
return None


def main():
word = encode_vop1(V_SWAP_B32, 1, 256 + 2)
check('encoding matches the bytes LLVM assembles', word == bytes([0x02, 0xcb, 0x02, 0x7e]), repr(word))

stage = translate(word)
check('swap exchanges the two registers through a temporary',
stage.lines == ['{ uint swap_tmp = v1; v1 = v2; v2 = swap_tmp; }'], repr(stage.lines))
check('both registers are written', {1, 2} <= stage.used_v)

stage = translate(encode_vop1(V_SWAP_B32, 255, 256), exec_known=False)
check('an unknown exec mask guards the whole exchange',
stage.lines == ['if (exec & 1) { uint swap_tmp = v255; v255 = v0; v0 = swap_tmp; }'], repr(stage.lines))

stage = translate(encode_vop1(V_SWAP_B32, 3, 256 + 3))
check('swapping a register with itself emits nothing', stage.lines == [], repr(stage.lines))

# Chained with an arithmetic use: the swapped values are what later instructions read.
code = encode_vop1(V_SWAP_B32, 7, 256 + 8) + struct.pack('<I', (0b0111111 << 25) | (9 << 17) | (1 << 9) | (256 + 7))
stage = translate(code)
check('a later read sees the swapped register',
stage.lines == ['{ uint swap_tmp = v7; v7 = v8; v8 = swap_tmp; }', 'v9 = v7;'], repr(stage.lines))

# A swap invalidates the proven-uniform status of both registers.
stage = Stage()
stage.uniform_v.update({4, 5, 6})
for _o, _s, name, asm in G.decode(encode_vop1(V_SWAP_B32, 4, 256 + 5)):
stage.one(name, asm)
check('uniform status is dropped for both swapped registers', stage.uniform_v == {6}, repr(stage.uniform_v))

# Refusals: a scalar or constant source cannot be encoded by the hardware, so a hand-written line
# must not be accepted either; modifiers, register ranges, out-of-range VGPRs and extra operands are refused.
for label, asm in (('scalar source', 'v_swap_b32 v1, s2'), ('constant source', 'v_swap_b32 v1, 0'),
('scalar destination', 'v_swap_b32 s1, v2'), ('missing source', 'v_swap_b32 v1'),
('third operand', 'v_swap_b32 v1, v2, v3'),
('destination register range', 'v_swap_b32 v[1:2], v3'),
('source register range', 'v_swap_b32 v1, v[2:3]'),
('out-of-range destination VGPR', 'v_swap_b32 v256, v1'),
('out-of-range source VGPR', 'v_swap_b32 v1, v256')):
stage = Stage()
try:
stage.one('v_swap_b32', asm)
ok = False
except G.Unsupported:
ok = True
check('%s is refused' % label, ok and stage.lines == [], asm)
stage = Stage()
try:
stage.one('v_swap_b32', 'v_swap_b32 v1, v2 clamp')
ok = False
except G.Unsupported:
ok = True
check('a modifier is refused', ok and stage.lines == [])

# The SDWA, DPP16 and VOP3A spellings are not swaps the translator may run.
sdwa = struct.pack('<II', (VOP1_PREFIX << 25) | (1 << 17) | (V_SWAP_B32 << 9) | 249, 2 | (6 << 8) | (6 << 16) | (6 << 24))
reason = refused(sdwa)
check('the SDWA spelling is refused', reason is not None, repr(reason))

dpp = struct.pack('<II', (VOP1_PREFIX << 25) | (1 << 17) | (V_SWAP_B32 << 9) | 250, 0)
reason = refused(dpp)
check('the DPP16 spelling is refused', reason is not None, repr(reason))

vop3 = struct.pack('<II', (0b110101 << 26) | ((0x180 + V_SWAP_B32) << 16) | 1, 256 + 2)
reason = refused(vop3)
check('the VOP3A spelling is refused', reason is not None, repr(reason))

# Full pipeline translation with two sequential swaps and an exec-guarded swap.
ps_hlsl = pipeline_hlsl_ps()
check('pipeline HLSL contains two unguarded swaps and an exec-guarded swap',
'{ uint swap_tmp = v0; v0 = v1; v1 = swap_tmp; }' in ps_hlsl and
'{ uint swap_tmp = v2; v2 = v3; v3 = swap_tmp; }' in ps_hlsl and
'if (exec & 1) { uint swap_tmp = v1; v1 = v2; v2 = swap_tmp; }' in ps_hlsl,
ps_hlsl)

if len(sys.argv) > 1:
if sys.argv[1] != 'compile' or len(sys.argv) not in (3, 4):
raise SystemExit('usage: startup_gfx2hlsl_swap_check.py [compile <dxc> [fxc]]')
check_compile(ps_hlsl, sys.argv[2], sys.argv[3] if len(sys.argv) == 4 else None)

if failures:
print('\nFAILED: ' + ', '.join(failures))
sys.exit(1)
print('PASS')


def pipeline_hlsl_ps():
prolog = bytes.fromhex('0203fcbe' '020002c8' '020106c8' '02020ac8' '02030ec8')
swaps = encode_vop1(V_SWAP_B32, 0, 256 + 1) + encode_vop1(V_SWAP_B32, 2, 256 + 3)
saveexec = struct.pack('<I', (0b101111101 << 23) | (0 << 16) | (0x24 << 8) | 106)
guarded = encode_vop1(V_SWAP_B32, 1, 256 + 2)
epilog = bytes.fromhex('0f1800f800010203' '000081bf')
return G.Pipeline(VS_WORDS, prolog + swaps + saveexec + guarded + epilog, root_blob()).hlsl_ps()


def check_compile(ps_hlsl, dxc, fxc=None):
compilers = [('dxc', dxc, 'ps_6_0')] + ([('fxc', fxc, 'ps_5_1')] if fxc else [])
with tempfile.TemporaryDirectory() as tmp:
directory = Path(tmp)
src = directory / 'swap_ps.hlsl'
src.write_text(ps_hlsl, encoding='ascii')
for kind, compiler, profile in compilers:
out = directory / ('swap_ps_%s.cso' % kind)
if kind == 'fxc':
args = [compiler, '/nologo', '/T', profile, '/E', 'main', '/Fo', str(out), str(src)]
else:
args = [compiler, '-T', profile, '-E', 'main', '-Fo', str(out), str(src)]
run = subprocess.run(args, capture_output=True, text=True)
ok = run.returncode == 0 and out.is_file() and out.stat().st_size > 0 and not run.stderr.strip()
check('%s (%s) compiles emitted swap HLSL cleanly' % (kind, profile), ok,
'rc=%d stdout=%r stderr=%r' % (run.returncode, run.stdout, run.stderr))


main()
18 changes: 18 additions & 0 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1269,6 +1269,24 @@ def op_v_readfirstlane_b32(self, ops, mods):
def op_v_mov_b32(self, ops, mods):
self.set_v(reg_range(ops[0])[1], self.u(ops[1]))

def op_v_swap_b32(self, ops, mods):
# VOP1 only: VDST and SRC0 are both VGPRs and exchange values. It has no output or source modifier
# and no VOP3, SDWA or DPP form here, so anything extra is refused instead of dropped.
if mods or len(ops) != 2:
raise Unsupported('v_swap_b32 with %d operands and modifiers %s' % (len(ops), mods))
dst, src = reg_range(ops[0]), reg_range(ops[1])
if (not dst or not src or dst[0] != 'v' or src[0] != 'v' or
dst[1] != dst[2] or src[1] != src[2] or
not (0 <= dst[1] <= 255 and 0 <= src[1] <= 255)):
raise Unsupported('v_swap_b32 needs two VGPRs, got %s and %s' % (ops[0], ops[1]))
a, b = dst[1], src[1]
for n in (a, b):
self.uniform_v.discard(n)
self.used_v.add(n)
if a != b:
swap = '{ uint swap_tmp = v%d; v%d = v%d; v%d = swap_tmp; }' % (a, a, b, b)
self.emit(swap if self.exec_known else 'if (exec & 1) %s' % swap)

def op_v_cndmask_b32(self, ops, mods):
# The select takes no output modifier: a clamp or mul on it would change the value, so a
# modifier that reaches here is refused rather than dropped from the emitted text.
Expand Down