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 @@ -359,6 +359,7 @@ jobs:
tests/startup_gfx2hlsl_sdwa_cvt_check.py \
tests/startup_gfx2hlsl_sdwa_cndmask_check.py \
tests/startup_gfx2hlsl_sop2_complement_check.py \
tests/startup_gfx2hlsl_s_nor_nand_check.py \
tests/startup_gfx2hlsl_pack_absdiff_check.py \
tests/startup_gfx2hlsl_sopk_accum_check.py \
tests/startup_gfx2hlsl_bfm_b64_check.py \
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ python3 -m venv out/pe-env
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_recompute_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_nor_nand_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_absdiff_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cvt_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cndmask_check.py
Expand Down
9 changes: 9 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3576,6 +3576,15 @@ if(EXISTS "${INTAKE_PYTHON}")
# 32-bit scalar complement logic: s_nand_b32, s_nor_b32 and s_xnor_b32 against an integer reference (#1919).
add_test(NAME startup_gfx2hlsl_sop2_complement COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sop2_complement_check.py")
# s_nand_b32 and s_nor_b32 of lane masks into exec_lo or an SGPR: CPU lines and D3D12 UAV readback (#1723).
add_test(NAME startup_gfx2hlsl_s_nor_nand COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_nor_nand_check.py")
foreach(adapter IN ITEMS warp hardware)
add_test(NAME startup_gfx2hlsl_s_nor_nand_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_nor_nand_check.py" dispatch "${DXC_EXECUTABLE}"
"$<TARGET_FILE:offscreen_check>" ${adapter})
set_tests_properties(startup_gfx2hlsl_s_nor_nand_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
# s_waitcnt_depctr is a hazard delay without architectural effect: the translation is unchanged by it (#2413).
add_test(NAME startup_gfx2hlsl_waitcnt_depctr COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_waitcnt_depctr_check.py")
Expand Down
2 changes: 1 addition & 1 deletion docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -8287,7 +8287,7 @@ when every source is a mask, because bit i of the complement depends only on bit
lowers to `(~(a op b)) & 1` into an SGPR, checked on all 32 lanes of the edge words. Guest SCC reads the whole
32-bit result, which the per-lane projection cannot show, so SCC is not emitted and a program that can read it
before the next SCC write is refused, through joins and back edges. A mask mixed with a plain word or a constant
and a vcc_lo or exec_lo destination stay refused, as does a mask source whose last write does not dominate a
and a vcc_lo destination (or an exec_lo destination of s_xnor_b32) stay refused. s_nand_b32 and s_nor_b32 also accept exec_lo as the destination when every source is a mask and the stage is proven wave32 (compute with at most 32 threads per group; pixel and vertex stages, whose wave size is unknown, the slot 57 mesh stage and any wave64 compute group keep refusing it, because a write to exec_lo leaves lanes 32..63 unchanged): the lane's new EXEC bit is the same per-lane value, including for a lane that was inactive. `startup_gfx2hlsl_s_nor_nand` and its `_dispatch_warp`/`_dispatch_hardware` variants check those forms by D3D12 UAV readback against an integer reference. A mask source is also refused whose last write does not dominate a
branch target crossed since, or which a block on a path to that target writes again. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sop2_complement$' -V`; with
LLVM 15, `tests/startup_gfx2hlsl_sop2_complement_check.py binary <llvm-mc>` and `decode <libLLVM>` round-trip
the same words.
Expand Down
138 changes: 138 additions & 0 deletions tests/startup_gfx2hlsl_s_nor_nand_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"""s_nor_b32 and s_nand_b32 of lane masks into exec_lo or an SGPR in tools/startup/gfx2hlsl.py (Part of #1723).

With every source a lane mask, the lane's bit of ~(a op b) is exact. The emitted lines are run on the integer
evaluator of the sibling check, and with `dispatch <dxc> <offscreen_check> <adapter>` also as a D3D12 compute
shader whose UAV readback is compared with an integer reference (bit = ~(a | b) & 1 for NOR, ~(a & b) & 1 for
NAND, over every pair of source bits). Forms with SCC readers, mixed mask and word sources, vcc_lo, exec_hi and
XNOR into exec_lo stay refused; the sibling check (startup_gfx2hlsl_sop2_complement_check.py) pins those.
"""
import struct
import subprocess
import sys
import tempfile
from pathlib import Path
from types import SimpleNamespace

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import startup_gfx2hlsl_sop2_complement_check as C # noqa: E402

REFERENCES = {
's_nor_b32': lambda a, b: ~(a | b) & 1,
's_nand_b32': lambda a, b: ~(a & b) & 1,
}
DESTINATIONS = ('exec_lo', 's3')
BIT_PAIRS = ((0, 0), (0, 1), (1, 0), (1, 1))


def lowered(name, dest):
stage = C.Probe()
stage.masks.update((1, 2))
stage.one(name, '%s %s, s1, s2' % (name, dest))
return stage


def cpu_checks():
for name, reference in REFERENCES.items():
for dest in DESTINATIONS:
stage = lowered(name, dest)
key = 'exec' if dest == 'exec_lo' else dest
wrong = []
for a, b in BIT_PAIRS:
out = C.run_lines(stage.lines, {key: 0, 's1': a, 's2': b, 'scc': C.SCC_UNSET})
if out[key] != reference(a, b):
wrong.append((a, b, out[key]))
C.check('%s into %s matches the reference on every bit pair' % (name, dest), not wrong, str(wrong))
C.check('NOR and NAND references differ', REFERENCES['s_nor_b32'](0, 1) != REFERENCES['s_nand_b32'](0, 1))


def accepts(name, dest, kind, group):
stage = C.Probe()
stage.kind, stage.pipe = kind, SimpleNamespace(group=group)
stage.masks.update((1, 2))
try:
stage.one(name, '%s %s, s1, s2' % (name, dest))
except C.G.Unsupported:
return False
return True


def stage_checks():
"""exec_lo leaves lanes 32..63 alone, so a wave64 stage must keep refusing it (a wave64 wave would keep stale
upper lanes active while the low lanes are rewritten). Only compute with at most 32 threads per group is proven
wave32; the wave size of a pixel or vertex stage is unknown. An SGPR destination is exact per lane in every stage."""
for name in REFERENCES:
for kind, group, want in (('ps', None, False), ('cs', (32, 1, 1), True), ('cs', (8, 4, 1), True),
('cs', (64, 1, 1), False), ('cs', (8, 8, 1), False),
('ms', None, False), ('vs', None, False)):
C.check('%s into exec_lo in a %s stage%s is %s' % (name, kind, ' of %s threads' % (group,) if group else '',
'accepted' if want else 'refused'),
accepts(name, 'exec_lo', kind, group) == want)
C.check('%s into s3 stays accepted in a wave64 mesh stage' % name, accepts(name, 's3', 'ms', None))


def dispatch(dxc, runner, adapter, name, dest, directory):
stage = lowered(name, dest)
key = 'exec' if dest == 'exec_lo' else dest
fill = tuple(((i + 1) * 0x9e3779b1 & 0xffffffff) | 1 for i in range(8))
lines = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {']
for i, (a, b) in enumerate(BIT_PAIRS):
lines.extend((
' {',
f' uint s1 = data.Load({4 * 2 * i}) ^ {fill[2 * i] ^ a:#010x}u;',
f' uint s2 = data.Load({4 * (2 * i + 1)}) ^ {fill[2 * i + 1] ^ b:#010x}u;',
' uint s3 = 0; uint exec = 0; bool scc = true;',
))
lines.extend(' ' + line for line in stage.lines)
lines.append(f' data.Store({4 * (8 + i)}, {key});')
lines.append(' }')
lines.append('}')
stem = '%s_%s' % (name, dest)
src, cso, output = (directory / (stem + suffix) for suffix in ('.hlsl', '.cso', '.bin'))
src.write_text('\n'.join(lines) + '\n', encoding='ascii')
compiled = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)],
stderr=subprocess.PIPE, text=True)
if compiled.returncode or compiled.stderr:
raise AssertionError(compiled.stderr or 'DXC exited with %d' % compiled.returncode)
run = subprocess.run([runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * 16), str(output)],
capture_output=True, text=True)
print(run.stdout, end='')
if run.returncode == 77:
sys.exit(77)
if run.returncode or run.stderr:
raise AssertionError(run.stderr or 'raw UAV dump exited with %d' % run.returncode)
actual = struct.unpack('<16I', output.read_bytes())
assert actual[:8] == fill, '%s: operand region changed' % stem
return actual[8:12]


def check_dispatch(dxc, runner, adapter):
runner = str(Path(runner).resolve())
out = HERE.parent / 'out'
out.mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(dir=out) as tmp:
for name, reference in REFERENCES.items():
for dest in DESTINATIONS:
got = dispatch(dxc, runner, adapter, name, dest, Path(tmp))
want = tuple(reference(a, b) for a, b in BIT_PAIRS)
C.check('%s into %s on the GPU: got %s, want %s' % (name, dest, got, want), got == want)
if C.failures:
sys.exit(1)


def main():
cpu_checks()
stage_checks()
if C.failures:
print('FAILED: %s' % ', '.join(C.failures))
sys.exit(1)
print('startup_gfx2hlsl_s_nor_nand_check: ok')


if __name__ == '__main__':
if len(sys.argv) == 1:
main()
elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch':
check_dispatch(*sys.argv[2:])
else:
sys.exit(__doc__)
64 changes: 54 additions & 10 deletions tests/startup_gfx2hlsl_sop2_complement_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
Lane masks: vcc_lo, exec_lo or an SGPR holding a compare mask is the whole wave's mask, of which the translator keeps
one lane's bit. Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask and an
SGPR destination the lane's bit of the result is exact: the form is accepted and checked here on every lane of the
edge words. SCC is set when any bit of the complemented 32-bit result is, which the other lanes decide (the bit of an
idle lane is set); the per-lane projection cannot show that, so SCC is not emitted and a program that can read it
before the next SCC write is refused (through branches too). A mask and a plain word mixed, a constant source, and a
vcc_lo or exec_lo destination stay refused. The mask mark follows program order, so a mark is a proof at a branch
edge words. NAND and NOR also accept exec_lo as the destination and can reactivate a lane. SCC is set when any bit
of the complemented 32-bit result is set. SCC is not emitted for these forms and a program that can read it before
the next SCC write is refused (through branches too). A mask mixed with a plain word or constant, a VCC destination,
and XNOR into exec_lo stay refused. The mask mark follows program order, so a mark is a proof at a branch
target only if the register's last write dominates the target and no block on a path from that write to the target
writes the register again; otherwise the complement is refused until the register is written again. Mutations: the
join rule disabled and the SCC read scan disabled must each accept a refused program.
Expand Down Expand Up @@ -53,6 +53,7 @@
import struct
import sys
from pathlib import Path
from types import SimpleNamespace

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent / 'tools'))
Expand Down Expand Up @@ -119,7 +120,10 @@ def code(name, form):


class Probe(G.Stage):
"""A Stage with no pipeline: enough state for decoded instructions to be translated."""
"""A Stage with no pipeline: enough state for decoded instructions to be translated. It is a compute stage of
one 32-lane group (proven wave32) unless a test sets `kind` and `pipe.group`."""
kind = 'cs'
pipe = SimpleNamespace(group=(32, 1, 1))

def __init__(self):
self.lines, self.sym = [], {}
Expand Down Expand Up @@ -278,13 +282,45 @@ def lane_mask_controls():
check('%s: %d all-mask forms give the lane bit of the reference on 32 lanes x %d pairs, SCC not written'
% (name, len(forms), len(SPECIAL) ** 2), not wrong, str(wrong[:2]))

# 2. Still refused: a constant or plain-word source next to a mask, a mask destination, a high-half mask name.
for name in ('s_nand_b32', 's_nor_b32'):
reference = OPS[name][1]
# PR #2030 covered exec_lo, s1, s2 and all four source-bit pairs.
for operands, left, right in (('exec_lo, s1, s2', 's1', 's2'),
('exec_lo, exec_lo, vcc_lo', 'exec', 'vcc')):
stage = Probe()
stage.masks.update((1, 2))
stage.one(name, '%s %s' % (name, operands))
expected = ['exec = (~(%s %s %s)) & 1;' % (left, operator[name], right)]
check('%s %s emits a one-bit EXEC write and invalidates the EXEC proof' % (name, operands),
stage.lines == expected and not stage.exec_known and stage.masks == {1, 2}
and stage.scc_effect == 'a lane-mask complement', str(stage.lines))
if stage.lines != expected:
continue
wrong = []
for a in (0, 1):
for b in (0, 1):
env = {'exec': 0, left: a, right: b, 'scc': SCC_UNSET}
out = run_lines(stage.lines, env)
if (out['exec'], out['scc']) != (reference(a, b) & 1, SCC_UNSET):
wrong.append((a, b, out))
check('%s %s gives the lane bit even for inactive lanes' % (name, operands), not wrong, str(wrong))

# 2. Still refused: mixed sources and destinations outside the supported forms.
for name in OPS:
wrong = []
for operands in ('s3, s1, s9', 's3, s9, vcc_lo', 's3, s1, -1', 's3, 0, vcc_lo', 'vcc_lo, s1, s2',
'exec_lo, s1, s2', 's3, s1, vcc_hi', 'm0, s1, s2'):
# PR #2030 covered the vcc_lo constants, exec_hi constants and s3 with a mask and -1.
refused = ('s3, s1, s9', 's3, s9, vcc_lo', 's3, s1, -1', 's3, 0, vcc_lo', 'vcc_lo, s1, s2',
'vcc_lo, 1, 0', 'vcc, s1, s2', 'exec_hi, 0, 0', 'exec, s1, s2', 's[4:5], s1, s2',
'exec_lo, s1, s9', 'exec_lo, vcc_lo, 0', 'exec_lo, s[1:2], s2',
's3, s1, vcc_hi', 'm0, s1, s2')
cases = [(operands, {1, 2}) for operands in refused]
# PR #2030 covered exec_lo with two plain SGPRs.
cases.append(('exec_lo, s1, s2', set()))
if name == 's_xnor_b32':
cases.append(('exec_lo, s1, s2', {1, 2}))
for operands, masks in cases:
stage = Probe()
stage.masks.update((1, 2))
stage.masks.update(masks)
try:
stage.one(name, '%s %s' % (name, operands))
wrong.append((operands, stage.lines))
Expand All @@ -295,6 +331,10 @@ def lane_mask_controls():

# 3. Whole programs. SCC after the complement is not the guest's: a read before the next SCC write is refused.
masks = ('v_cmp_eq_f32_e64 s5, 0, v1', 'v_cmp_lt_f32_e64 s4, 0, v2')
for name in ('s_nand_b32', 's_nor_b32'):
got = text_refusal(*masks, '%s exec_lo, s5, s4' % name, 's_cselect_b32 s6, 1, 0', 's_endpgm')
check('%s into exec_lo refuses a later SCC read' % name,
got == 'scc from a lane-mask complement in s_cselect_b32', got)
for name in OPS:
complement = '%s s4, s5, s4' % name
line = 's4 = (~(s5 %s s4)) & 1;' % operator[name]
Expand Down Expand Up @@ -331,6 +371,10 @@ def lane_mask_controls():
got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)]
check('a mask that another path into the branch target changes is refused (skipped write, loop body write)',
got == [joined, joined], str(got))
for name in ('s_nand_b32', 's_nor_b32'):
got = text_refusal(*skip, '%s exec_lo, s5, s4' % name, 's_endpgm')
check('%s into exec_lo refuses a joined mask source' % name,
got == '%s on a lane mask joined at a branch target' % name, got)
lines = run_text(*arms)
check('a mask written before the split and on no arm crosses the join', 's4 = (~(s5 & s4)) & 1;' in lines, str(lines))
lines = run_text(*skip, *masks, 's_nand_b32 s6, s5, s4', 's_endpgm')
Expand Down Expand Up @@ -628,7 +672,7 @@ def controls():
check('%s: %d numeric forms emit the %s lines complemented, same mask and EXEC bookkeeping'
% (name, len(VALUE_FORMS), sibling), not wrong, str(wrong[:2]))

# 5b. Refused: a lane mask next to a plain word, or as the destination (lane_mask_controls has the accepted forms).
# 5b. Decoded forms with a lane mask and a plain word (lane_mask_controls covers all-mask forms).
for name in OPS:
accepted = []
for form in MASK_FORMS:
Expand Down
Loading
Loading