diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 167c7ac722..183ba4d966 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -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 \ diff --git a/AGENTS.md b/AGENTS.md index 90800c9151..3210ebbaf7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/CMakeLists.txt b/CMakeLists.txt index f9be7c7068..a8ae78b0e5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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}" + "$" ${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") diff --git a/docs/experiments.md b/docs/experiments.md index 00b5edb884..76276958b8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -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 ` and `decode ` round-trip the same words. diff --git a/tests/startup_gfx2hlsl_s_nor_nand_check.py b/tests/startup_gfx2hlsl_s_nor_nand_check.py new file mode 100644 index 0000000000..c5ad04c475 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_nor_nand_check.py @@ -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 ` 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__) diff --git a/tests/startup_gfx2hlsl_sop2_complement_check.py b/tests/startup_gfx2hlsl_sop2_complement_check.py index 6a4394bb9d..bf7755e104 100644 --- a/tests/startup_gfx2hlsl_sop2_complement_check.py +++ b/tests/startup_gfx2hlsl_sop2_complement_check.py @@ -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. @@ -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')) @@ -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 = [], {} @@ -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)) @@ -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] @@ -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') @@ -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: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 348fca197a..e09d4212dd 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4686,13 +4686,22 @@ def low(tok): if base in ('s_mul_hi_u32', 's_mul_hi_i32') else self.is_lane_mask(dname)) # Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask the lane's - # bit of the result is exact. Only an SGPR destination is taken; a mixed mask and plain word is not. + # bit of the result is exact for SGPR destinations and for NAND/NOR into exec_lo. def mask_source(tok): r = reg_range(tok) return tok in ('vcc', 'vcc_lo', 'exec', 'exec_lo') or bool( r and r[0] == 's' and r[1] == r[2] and r[1] in self.masks) - lane_complement = (word_complement and bool(dst) and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105 - and all(mask_source(t) for t in srcs)) + sgpr_dest = bool(dst) and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105 + # A write to exec_lo leaves lanes 32..63 alone, so it is exact only where the wave is proven wave32: + # compute with at most 32 threads per group (as the b32 waterfall close requires). The wave size of a + # pixel or vertex stage is unknown here (see require_spill_lanes_apart) and the slot 57 mesh stage is + # wave64, so those keep refusing it. + group = getattr(getattr(self, 'pipe', None), 'group', None) + wave32_stage = (getattr(self, 'kind', None) == 'cs' and group is not None + and group[0] * group[1] * group[2] <= 32) + exec_dest = dname == 'exec_lo' and base in ('s_nand_b32', 's_nor_b32') and wave32_stage + lane_complement = (word_complement and (sgpr_dest or exec_dest) + and all(mask_source(t) for t in (ops[1:] if exec_dest else srcs))) if not lane_complement and (mask_dest or any(self.is_lane_mask(t) for t in srcs)): raise Unsupported('%s on a lane mask' % base) if lane_complement and any(reg_range(t) and reg_range(t)[1] in getattr(self, 'join_masks', ()) @@ -4828,6 +4837,12 @@ def src_sym(t): self.used_s.add(reg_range(srcs[absorbed])[1]) values = [t if i == absorbed else self.u(t) for i, t in enumerate(srcs)] expr = text.format(*values) + if lane_complement: + # Guest SCC depends on the whole complemented word. Refuse a program that can read it. + scc = None + self.scc_effect = 'a lane-mask complement' + if self.tracks_uniformity(): + self.scc_uniform = False if base == 's_add_u32' and getattr(self, 'pc', None) in self.address_carry_pairs: for tok in srcs: self.reject_lane_mask_data(base, tok) @@ -4933,17 +4948,11 @@ def known(tok): high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) salu_align4 = not pair and not is_mask and self.salu_align4(base, srcs) - self.set_s(d, expr, scc=None if lane_complement else scc, align4=salu_align4) + self.set_s(d, expr, scc=scc, align4=salu_align4) if base == 's_mov_b32' and srcs[0] in FLOATS and not is_mask: # Keep the runtime SGPR assignment intact while letting const_words() read inline float patterns # such as 0x40000000 (OPAQUE_BLACK, encoded as inline 244 / '2.0'). self.__dict__.setdefault('float_const_s', {})[d] = fbits(FLOATS[srcs[0]]) - if lane_complement: - # The guest SCC is (the whole complemented word != 0), which the bits of every other lane decide (an - # idle lane's bit is set). It is not emitted: translate() refuses a program that can read it. - self.scc_effect = 'a lane-mask complement' - if self.tracks_uniformity(): - self.scc_uniform = False if hasattr(self, 'heap_index'): self.mark_heap_index(base, d, srcs, syms) if is_mask: