From c60704bfe2cfc4e8aba95ad05a4173a87774364d Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <241957358+Ammmae0x@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:35:59 +0200 Subject: [PATCH 1/2] compute: classify remaining scalar ops in direct SCC liveness Refs #3224, #2935 uses_scc_after() treated every SOPK op except s_movk_i32 as uncertain and missed SCC writers (s_bfe_i32, s_addk_i32, all twelve s_cmpk_*) and readers (s_addc_u32, s_subb_u32), so programs that kill or preserve SCC through those ops were refused as if SCC were still live at a symbolic descriptor field. The overwrite list now names the three writers, a new preserves_sopk list names s_mulk_i32, the four counter waits and the mode writes, and the readers join reads_scc. Unimplemented scalar ops stay uncertain and SOPP ops keep their fallthrough behavior. tests/native_scc_liveness_check.py pins the classification without Windows: its no-arg mode checks all 199 scalar ops in the ISA tables against the census, runs a Python replica of the backward walk over 53 straight-line and branching programs, and kills 25 of 25 single-condition mutants. controls and hardware modes compile and replay the pass, refusal and boundary programs on Windows. --- docs/experiments.md | 13 + .../experiments/native-direct-scc-liveness.md | 73 ++ src/gfx1013_direct_compute.inl | 33 +- .../python-linux/native-scc-liveness.txt | 1 + tests/cmake/native_scc_liveness.cmake | 11 + tests/native_scc_liveness_check.py | 778 ++++++++++++++++++ 6 files changed, 906 insertions(+), 3 deletions(-) create mode 100644 docs/experiments/native-direct-scc-liveness.md create mode 100644 tests/checks/python-linux/native-scc-liveness.txt create mode 100644 tests/cmake/native_scc_liveness.cmake create mode 100644 tests/native_scc_liveness_check.py diff --git a/docs/experiments.md b/docs/experiments.md index aed53ffb69..b63f666ff6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -93,6 +93,19 @@ derived from that descriptor's clamped stride, and the raw OOB selector. The compute fixture reads back all four store widths across two workgroups. [Experiment and reproduction commands](experiments/native-bytewin-store.md) +## Scalar SCC liveness in direct compute + +`uses_scc_after()` in `src/gfx1013_direct_compute.inl` decides whether the +SCC value leaving a symbolic descriptor field is still live. A field +extraction refuses with "numeric SCC from a symbolic descriptor field" when +SCC is live after it and no stride metadata was bound for that SRV; when SCC +is dead at the field, the extraction compiles. The classification now names +the remaining lowered scalar ops explicitly: `s_bfe_i32`, `s_addk_i32` and +all twelve `s_cmpk_*` comparisons overwrite SCC, `s_mulk_i32`, the counter +waits and the accepted mode writes preserve it, and `s_addc_u32`/`s_subb_u32` +read it. +[Experiment and reproduction commands](experiments/native-direct-scc-liveness.md) + ## Sub-DWORD global loads in direct compute `global_load_ubyte`, `global_load_sbyte`, `global_load_ushort` and `global_load_sshort` lower in the diff --git a/docs/experiments/native-direct-scc-liveness.md b/docs/experiments/native-direct-scc-liveness.md new file mode 100644 index 0000000000..cb03256e81 --- /dev/null +++ b/docs/experiments/native-direct-scc-liveness.md @@ -0,0 +1,73 @@ +# Scalar SCC liveness in direct compute + +`uses_scc_after()` in `src/gfx1013_direct_compute.inl` is the backward walk +that decides whether the SCC value leaving a symbolic descriptor field is +still live. A field extraction refuses with "numeric SCC from a symbolic +descriptor field" when SCC is live after it and no stride metadata was bound +for that SRV; when SCC is dead at the field, the extraction compiles and SCC +is simply the value the next writer produces. + +The walk previously treated every SOPK op except `s_movk_i32` as uncertain, +so a program that kills SCC with `s_bfe_i32`, `s_addk_i32` or any of the +twelve `s_cmpk_*` comparisons, or that preserves SCC through `s_mulk_i32`, +a counter wait (`s_waitcnt_vscnt`, `s_waitcnt_vmcnt`, `s_waitcnt_expcnt`, +`s_waitcnt_lgkmcnt`), or an accepted mode write (`s_setreg_b32`, +`s_setreg_imm32_b32`, `s_round_mode`, `s_denorm_mode`) and then kills it +with `s_and_b32`, was refused as if SCC were still live. The classification +now names those ops explicitly: the three overwriters join the overwrite +list, the SOPK preservers join a new `preserves_sopk` list, and +`s_addc_u32`/`s_subb_u32` join the readers (they consume SCC through +`read(128)` in `arithmetic()`). + +Two classifications are deliberately conservative. `s_setreg_b32` is listed +as a preserver even though `consume_half_mode()` never accepts it in +compute: any program containing it still refuses at lowering, with +"unsupported binary16 rounding or denormal mode" when its MODE field +touches binary16 bits, so the liveness entry cannot admit a translation. +`s_wqm_b32`/`s_wqm_b64` stay in the `mask_scc` overwrite list although +`arithmetic()` does not lower them; they were overwriters before this change +and no program reaches them. Scalar ops DirectCompute does not lower at all +(`s_getpc_b64`, `s_setpc_b64`, `s_swappc_b64`, `s_rfe_b64`, +`s_movrels_b32`/`s_movrels_b64`, `s_movreld_b32`/`s_movreld_b64`, +`s_mov_fed_b32`, `s_movrelsd_2_b32`, `s_version`, `s_getreg_b32`, +`s_call_b64`, `s_subvector_loop_begin`, `s_subvector_loop_end`) stay +uncertain. SOPP ops are not listed anywhere: the uncertain test never +matches them, so the lowered ones (`s_nop`, `s_waitcnt`, +`s_waitcnt_depctr`, `s_clause`, `s_inst_prefetch`, `s_setprio`, +`s_barrier`, `s_branch`, the `s_cbranch_vccz`/`s_cbranch_vccnz` and +`s_cbranch_execz`/`s_cbranch_execnz` branches, `s_round_mode`, +`s_denorm_mode`) fall through to the successor edges and preserve SCC the +same way, while the unlowered ones still refuse at lowering. + +The [source-built fixture](../../tests/native_scc_liveness_check.py) pins +the classification three ways without Windows. Its no-arg mode parses +`uses_scc_after()` out of the translator source and checks all 199 scalar +ops in the ISA tables against the census, runs a Python replica of the +backward walk over 53 straight-line and branching programs (including a +diamond where only one arm overwrites SCC, a branch over a reader, and +loops with and without a reader), and kills 25 of 25 single-condition +mutants of the new and modified conditions. The `controls` mode compiles 8 +pass programs and 21 refusal programs against a root whose descriptor slot +has no stride metadata: the pass programs compile, every refusal program +fails with the exact "numeric SCC from a symbolic descriptor field" +substring, and the direct read compiles once the stride is bound. The +`hardware` mode replays one shader with stride 0 and stride 4 and checks +all 16 output words and guards in both groups, covering signed and +unsigned imm16 sign-extension and boundary values for `s_bfe_i32`, +`s_addk_i32` and `s_cmpk_*`, and proving `s_mulk_i32` and +`s_waitcnt_vscnt null, 0` carry both SCC 0 and SCC 1 into `s_cselect_b32`. + +Windows verification is pending; the Linux results above are the no-arg +audit only. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_scc_liveness_(controls|hardware)$' -V +``` + +```bash +python3 -B tests/native_scc_liveness_check.py +``` + +The instruction behavior follows the +[AMD RDNA 2 ISA, revision 1.0](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture). diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index f9046ce6df..9228045121 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -3329,6 +3329,7 @@ struct DirectCompute { const auto n = inst.name; const bool reads_scc = n == "s_cselect_b32" || n == "s_cselect_b64" || n == "s_cmov_b32" || n == "s_cmov_b64" || n == "s_cmovk_i32" || + n == "s_addc_u32" || n == "s_subb_u32" || std::find(inst.src.begin(), inst.src.end(), 253u) != inst.src.end(); // These scalar mask operations set SCC from their entire // result and do not consume the incoming SCC. An explicit @@ -3345,7 +3346,7 @@ struct DirectCompute { const bool overwrites = mask_scc || n == "s_abs_i32" || n == "s_bcnt0_i32_b32" || n == "s_bcnt1_i32_b32" || n == "s_bcnt0_i32_b64" || n == "s_bcnt1_i32_b64" || - inst.enc == Encoding::Sopc || n == "s_bfe_u32" || n == "s_and_b32" || + inst.enc == Encoding::Sopc || n == "s_bfe_u32" || n == "s_bfe_i32" || n == "s_and_b32" || n == "s_or_b32" || n == "s_max_u32" || n == "s_min_u32" || n == "s_min_i32" || n == "s_max_i32" || n == "s_absdiff_i32" || n == "s_add_u32" || n == "s_sub_u32" || n == "s_add_i32" || n == "s_sub_i32" || n == "s_and_saveexec_b32" || @@ -3358,7 +3359,15 @@ struct DirectCompute { n == "s_lshr_b32" || n == "s_lshl_b32" || n == "s_ashr_i32" || n == "s_lshl_b64" || n == "s_lshr_b64" || n == "s_ashr_i64" || n == "s_xor_b32" || n == "s_bfe_u64" || n == "s_bfe_i64" || - n == "s_lshl1_add_u32" || n == "s_lshl2_add_u32" || n == "s_lshl3_add_u32" || n == "s_lshl4_add_u32"; + n == "s_lshl1_add_u32" || n == "s_lshl2_add_u32" || n == "s_lshl3_add_u32" || n == "s_lshl4_add_u32" || + // SOPK comparisons and the signed add write SCC from the + // comparison result or the signed overflow, respectively, + // and do not consume the incoming SCC (arithmetic()). + n == "s_addk_i32" || + n == "s_cmpk_eq_i32" || n == "s_cmpk_lg_i32" || n == "s_cmpk_gt_i32" || + n == "s_cmpk_ge_i32" || n == "s_cmpk_lt_i32" || n == "s_cmpk_le_i32" || + n == "s_cmpk_eq_u32" || n == "s_cmpk_lg_u32" || n == "s_cmpk_gt_u32" || + n == "s_cmpk_ge_u32" || n == "s_cmpk_lt_u32" || n == "s_cmpk_le_u32"; const bool preserves_pair = n == "s_mul_i32" || n == "s_mul_hi_i32" || n == "s_mul_hi_u32" || n == "s_bfm_b32" || n == "s_bfm_b64" || n == "s_pack_ll_b32_b16" || n == "s_pack_lh_b32_b16" || n == "s_pack_hh_b32_b16"; @@ -3371,7 +3380,25 @@ struct DirectCompute { n == "s_sext_i32_i8" || n == "s_sext_i32_i16" || n == "s_bitset0_b32" || n == "s_bitset0_b64" || n == "s_bitset1_b32" || n == "s_bitset1_b64" || n == "s_bitreplicate_b64_b32"; - const bool uncertain_scalar = (inst.enc == Encoding::Sopk && n != "s_movk_i32") || + // SOPK operations that write only their destination (or, for + // the counter waits and the accepted mode writes, nothing + // at all) and never read or write SCC. s_mulk_i32 and + // s_movk_i32 only write the destination in arithmetic(); + // the waits are handled as no-ops in lower() and the mode + // writes as no-ops in consume_half_mode(). A setreg or mode + // write that consume_half_mode() does not accept still + // refuses at lowering, so classifying it here cannot admit + // a translation. SOPP operations are not listed: the + // uncertain test below never matches them, so the lowered + // ones (s_nop, s_waitcnt, s_waitcnt_depctr, s_clause, + // s_inst_prefetch, s_setprio, s_barrier, s_round_mode, + // s_denorm_mode and the branches) fall through to the + // successor edges and preserve SCC the same way. + const bool preserves_sopk = n == "s_movk_i32" || n == "s_mulk_i32" || + n == "s_setreg_b32" || n == "s_setreg_imm32_b32" || + n == "s_waitcnt_vscnt" || n == "s_waitcnt_vmcnt" || + n == "s_waitcnt_expcnt" || n == "s_waitcnt_lgkmcnt"; + const bool uncertain_scalar = (inst.enc == Encoding::Sopk && !overwrites && !preserves_sopk) || (inst.enc == Encoding::Sop2 && !overwrites && !preserves_pair) || (inst.enc == Encoding::Sop1 && !overwrites && !preserves_sop1); if (reads_scc || uncertain_scalar || (inst.branch() && (inst.op == 4 || inst.op == 5))) { diff --git a/tests/checks/python-linux/native-scc-liveness.txt b/tests/checks/python-linux/native-scc-liveness.txt new file mode 100644 index 0000000000..c6841bc803 --- /dev/null +++ b/tests/checks/python-linux/native-scc-liveness.txt @@ -0,0 +1 @@ +tests/native_scc_liveness_check.py diff --git a/tests/cmake/native_scc_liveness.cmake b/tests/cmake/native_scc_liveness.cmake new file mode 100644 index 0000000000..76a5908566 --- /dev/null +++ b/tests/cmake/native_scc_liveness.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_scc_liveness_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_scc_liveness_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_scc_liveness_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_scc_liveness_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_scc_liveness_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_scc_liveness_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/native_scc_liveness_check.py b/tests/native_scc_liveness_check.py new file mode 100644 index 0000000000..1859aeb6f3 --- /dev/null +++ b/tests/native_scc_liveness_check.py @@ -0,0 +1,778 @@ +"""Direct compute SCC liveness classification for scalar ops (#3224, #2935). + +Issue #3224's census still lists the "numeric SCC from a symbolic +descriptor field" refusal after #3227 and #3301. uses_scc_after() in +src/gfx1013_direct_compute.inl treated every SOPK op except s_movk_i32 as +uncertain and missed SCC writers (s_bfe_i32, s_addk_i32, all s_cmpk_*) and +SCC readers (s_addc_u32, s_subb_u32), so programs that kill or preserve SCC +through those ops were refused as if SCC were still live at a symbolic +descriptor field. + +No-arg mode (Linux CI) parses uses_scc_after() out of the translator +source and checks it three independent ways: the parsed classification sets +must equal the census below, a Python replica of the backward CFG walk must +agree with the parsed classification on a battery of straight-line and +branching programs, and an exhaustive mutation audit must kill every +single-condition mutant of the new/modified classification. It also runs +native_direct_container_check's scc_overwrite_names parser check so an edit +here never silently breaks native_direct_container. + +controls mode compiles pass and refusal programs with compile_dxil against +a root whose descriptor slot has no stride metadata, so a live SCC at the +field refuses and a dead SCC compiles. hardware mode replays one shader +with stride 0 and stride 4 and checks every output and guard word. +""" + +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) + +from native_compute_clear_check import write_request +from native_direct_container_check import check_scc_writer_mutant, scc_overwrite_names +from native_scalar_lds_check import scalar, sop1, vmove +import disasm_rdna2 + +ROOT = Path(__file__).resolve().parents[1] +INL = ROOT / "src" / "gfx1013_direct_compute.inl" +TABLES = ROOT / "src" / "gfx1013_isa_tables.inl" + +SCC_REFUSAL = "numeric SCC from a symbolic descriptor field" +SENTINEL = 0x69696969 +GUARD_WORDS, OUTPUT_WORDS = 8, 2064 +ENDPGM = 0xBF810000 +SA = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 6 << 1) +ROOT_SIG = ('DescriptorTable(SRV(t0,numDescriptors={srv}),' + 'UAV(u0,numDescriptors={uav},offset={srv})),' + 'RootConstants(num32BitConstants=1,b0)') + +# Census of uses_scc_after() as fixed. These sets are the expected values +# the no-arg audit compares the parsed C++ against; they were read off +# arithmetic()/lower()/consume_half_mode() in the same file, not invented. +EXPECTED_READS = { + "s_cselect_b32", "s_cselect_b64", "s_cmov_b32", "s_cmov_b64", + "s_cmovk_i32", "s_addc_u32", "s_subb_u32", +} +# mask_scc: scalar mask ops that set SCC from their whole result. +EXPECTED_MASK_SCC = { + "s_andn2_b64", "s_and_b64", "s_or_b64", "s_xor_b64", "s_orn2_b64", + "s_nand_b64", "s_nor_b64", "s_xnor_b64", "s_not_b64", "s_wqm_b32", + "s_wqm_b64", "s_quadmask_b32", "s_quadmask_b64", "s_and_saveexec_b64", + "s_or_saveexec_b64", "s_xor_saveexec_b64", "s_andn2_saveexec_b64", + "s_orn2_saveexec_b64", "s_nand_saveexec_b64", "s_nor_saveexec_b64", + "s_xnor_saveexec_b64", "s_andn1_saveexec_b64", "s_orn1_saveexec_b64", + "s_andn1_wrexec_b64", "s_andn2_wrexec_b64", +} +# Names in the overwrites expression besides mask_scc and the SOPC blanket. +EXPECTED_OVERWRITES_EXTRA = { + "s_abs_i32", "s_bcnt0_i32_b32", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", + "s_bcnt1_i32_b64", "s_bfe_u32", "s_bfe_i32", "s_and_b32", "s_or_b32", + "s_max_u32", "s_min_u32", "s_min_i32", "s_max_i32", "s_absdiff_i32", + "s_add_u32", "s_sub_u32", "s_add_i32", "s_sub_i32", + "s_and_saveexec_b32", "s_or_saveexec_b32", "s_xor_saveexec_b32", + "s_andn2_saveexec_b32", "s_orn2_saveexec_b32", "s_nand_saveexec_b32", + "s_nor_saveexec_b32", "s_xnor_saveexec_b32", "s_andn1_saveexec_b32", + "s_orn1_saveexec_b32", "s_andn1_wrexec_b32", "s_andn2_wrexec_b32", + "s_andn2_b32", "s_orn2_b32", "s_nor_b32", "s_nand_b32", "s_xnor_b32", + "s_not_b32", "s_lshr_b32", "s_lshl_b32", "s_ashr_i32", "s_lshl_b64", + "s_lshr_b64", "s_ashr_i64", "s_xor_b32", "s_bfe_u64", "s_bfe_i64", + "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", + "s_lshl4_add_u32", "s_addk_i32", + "s_cmpk_eq_i32", "s_cmpk_lg_i32", "s_cmpk_gt_i32", "s_cmpk_ge_i32", + "s_cmpk_lt_i32", "s_cmpk_le_i32", "s_cmpk_eq_u32", "s_cmpk_lg_u32", + "s_cmpk_gt_u32", "s_cmpk_ge_u32", "s_cmpk_lt_u32", "s_cmpk_le_u32", +} +EXPECTED_PRESERVES_PAIR = { + "s_mul_i32", "s_mul_hi_i32", "s_mul_hi_u32", "s_bfm_b32", "s_bfm_b64", + "s_pack_ll_b32_b16", "s_pack_lh_b32_b16", "s_pack_hh_b32_b16", +} +EXPECTED_PRESERVES_SOP1 = { + "s_mov_b32", "s_mov_b64", "s_brev_b32", "s_brev_b64", + "s_ff0_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b32", "s_ff1_i32_b64", + "s_flbit_i32_b32", "s_flbit_i32_b64", "s_flbit_i32", "s_flbit_i32_i64", + "s_sext_i32_i8", "s_sext_i32_i16", "s_bitset0_b32", "s_bitset0_b64", + "s_bitset1_b32", "s_bitset1_b64", "s_bitreplicate_b64_b32", +} +EXPECTED_PRESERVES_SOPK = { + "s_movk_i32", "s_mulk_i32", "s_setreg_b32", "s_setreg_imm32_b32", + "s_waitcnt_vscnt", "s_waitcnt_vmcnt", "s_waitcnt_expcnt", + "s_waitcnt_lgkmcnt", +} +# Scalar ops DirectCompute does not lower; they must stay uncertain so a +# program containing one is still refused rather than misclassified. +EXPECTED_UNCERTAIN_SOP1 = { + "s_getpc_b64", "s_setpc_b64", "s_swappc_b64", "s_rfe_b64", + "s_movrels_b32", "s_movrels_b64", "s_movreld_b32", "s_movreld_b64", + "s_mov_fed_b32", "s_movrelsd_2_b32", +} +EXPECTED_UNCERTAIN_SOPK = { + "s_version", "s_getreg_b32", "s_call_b64", "s_subvector_loop_begin", + "s_subvector_loop_end", +} +# SOPP ops lowered in lower()/consume_half_mode() (no-ops, waits, branches); +# the uncertain test never matches SOPP, so they fall through to the +# successor edges and preserve SCC. Every other SOPP op refuses at lowering. +LOWERED_SOPP = { + "s_nop", "s_branch", "s_cbranch_vccz", "s_cbranch_vccnz", + "s_cbranch_execz", "s_cbranch_execnz", "s_barrier", "s_waitcnt", + "s_setprio", "s_inst_prefetch", "s_clause", "s_waitcnt_depctr", + "s_round_mode", "s_denorm_mode", +} +NEW_OVERWRITES = ["s_bfe_i32", "s_addk_i32"] + [ + "s_cmpk_eq_i32", "s_cmpk_lg_i32", "s_cmpk_gt_i32", "s_cmpk_ge_i32", + "s_cmpk_lt_i32", "s_cmpk_le_i32", "s_cmpk_eq_u32", "s_cmpk_lg_u32", + "s_cmpk_gt_u32", "s_cmpk_ge_u32", "s_cmpk_lt_u32", "s_cmpk_le_u32", +] +CMPK_OPS = NEW_OVERWRITES[2:] +NEW_READS = ["s_addc_u32", "s_subb_u32"] + + +def vop2(op, dst, src0, src1): + return (op << 25) | ((dst & 255) << 17) | ((src1 & 255) << 9) | (src0 & 511) + + +def sopk(op, sdst, simm): + return 0xB0000000 | (op << 23) | (sdst << 16) | (simm & 0xFFFF) + + +def sopp(op, simm): + return 0xBF800000 | (op << 16) | (simm & 0xFFFF) + + +def smov(reg, value): + return [sop1(3, reg, 255), value & 0xFFFFFFFF] + + +def movk(reg, value): + return [sopk(0, reg, value)] + + +def store(slot, reg): + return [vmove(10, reg), 0xE0701000 | (4 * slot), 0x80080A08] + + +def field(): + # s_bfe_u32 s25, s17, 0xe0010: the 14-bit stride field of the SRV descriptor. + return [scalar(0x27, 25, 17, 255), 0xE0010] + + +def prologue(): + return [sop1(3, 20, 4), sop1(3, 21, 128), + 0xF408040A, 0xFA000020, # input SRV in s[16:19] + 0xF408080A, 0xFA000040, # output UAV in s[32:35] + 0xBF8CC07F] + field() + + +def group_base(): + return [scalar(0x1E, 7, 6, 134), vmove(8, 7), sop1(3, 126, 129)] + + +def cselect(dst): + return [scalar(0x0A, dst, 129, 128)] + + +def f16_filler(): + # v_add_f16 v3, v1, v2 with 1.0 and 2.0: makes half_binary true so the + # mode writes in consume_half_mode() are accepted. + return [vmove(1, 255), 0x3C00, vmove(2, 255), 0x4000, vop2(0x32, 3, 257, 258)] + + +def diamond(arm_a, arm_b): + """Two arms selected on VCC, joined after. Branch simms are derived from + the arm lengths so the targets land on the first arm-B word and the join.""" + return ([sop1(3, 106, 129), sopp(6, len(arm_a) + 1)] + arm_a + + [sopp(2, len(arm_b))] + arm_b) + + +# --------------------------------------------------------------------------- +# No-arg audit: parse uses_scc_after() and compare it against the census. +# --------------------------------------------------------------------------- + +def names_in(source, start_marker, end_marker): + start = source.index(start_marker) + end = source.index(end_marker, start) + return set(re.findall(r'n == "([^"]+)"', source[start:end])) + + +def parse_classification(source): + block_start = source.index("bool uses_scc_after") + block_end = source.index("void prepare_descriptor_strides", block_start) + block = source[block_start:block_end] + parsed = { + "block": block, + "reads": names_in(block, "const bool reads_scc = ", "const bool mask_scc = "), + "mask_scc": names_in(block, "const bool mask_scc = ", "const bool overwrites = "), + "overwrites": scc_overwrite_names(source), + "preserves_pair": names_in(block, "const bool preserves_pair = ", "const bool preserves_sop1 = "), + "preserves_sop1": names_in(block, "const bool preserves_sop1 = ", "const bool preserves_sopk = "), + "preserves_sopk": names_in(block, "const bool preserves_sopk = ", "const bool uncertain_scalar = "), + } + parsed["overwrites"] |= parsed["mask_scc"] + guards = {} + for enc, clause in re.findall( + r"\(inst\.enc == Encoding::(\w+) && ([^)]*)\)", block): + guards[enc] = {flag[1:] for flag in clause.split() if flag.startswith("!")} + parsed["uncertain_guards"] = guards + return parsed + + +def isa_names(tables_source): + """Every (name, encoding, opcode index) in the five SOP tables.""" + found = [] + for enc, array in (("Sopp", "sopp_names"), ("Sop1", "sop1_names"), + ("Sop2", "sop2_names"), ("Sopc", "sopc_names"), + ("Sopk", "sopk_names")): + start = tables_source.index(f"constexpr const char* {array}[] = {{") + end = tables_source.index("};", start) + entries = re.findall(r'"([^"]+)"|nullptr', tables_source[start:end]) + for index, name in enumerate(entries): + if name: + found.append((name, enc, index)) + return found + + +def expected_class(name, enc, op): + if name == "s_endpgm": + return "endpgm" + if name in EXPECTED_READS: + return "read" + if enc == "Sopc" or name in EXPECTED_MASK_SCC or name in EXPECTED_OVERWRITES_EXTRA: + return "overwrite" + if enc == "Sop2" and name in EXPECTED_PRESERVES_PAIR: + return "preserve" + if enc == "Sop1" and name in EXPECTED_PRESERVES_SOP1: + return "preserve" + if enc == "Sopk" and name in EXPECTED_PRESERVES_SOPK: + return "preserve" + if enc == "Sopp" and op in (4, 5): + return "branch-scc" + if enc in ("Sopk", "Sop2", "Sop1"): + return "uncertain" + return "fallthrough" + + +def parsed_traits(name, enc, op, srcs, parsed): + """The two facts the C++ walk uses: whether the instruction seeds + liveness (reads_scc || uncertain_scalar || SCC branch) and whether it + stops propagation (overwrites || s_endpgm). The uncertain term follows + the guard text as parsed, so a mutant that drops an exclusion really + makes its ops live again.""" + reads = name in parsed["reads"] or 253 in srcs + overwrites = enc == "Sopc" or name in parsed["overwrites"] + preserves = ((enc == "Sop2" and name in parsed["preserves_pair"]) or + (enc == "Sop1" and name in parsed["preserves_sop1"]) or + (enc == "Sopk" and name in parsed["preserves_sopk"])) + guard = parsed["uncertain_guards"].get(enc) + uncertain = False + if guard is not None: + uncertain = True + if "overwrites" in guard and overwrites: + uncertain = False + if "preserves_pair" in guard and preserves: + uncertain = False + if "preserves_sop1" in guard and preserves: + uncertain = False + if "preserves_sopk" in guard and preserves: + uncertain = False + live_seed = reads or uncertain or (enc == "Sopp" and op in (4, 5)) + stops = overwrites or name == "s_endpgm" + return live_seed, stops, preserves + + +def parsed_class(name, enc, op, srcs, parsed): + if name == "s_endpgm": + return "endpgm" + live_seed, stops, preserves = parsed_traits(name, enc, op, srcs, parsed) + if live_seed: + if name in parsed["reads"] or 253 in srcs: + return "read" + if enc == "Sopp" and op in (4, 5): + return "branch-scc" + return "uncertain" + if stops: + return "overwrite" + if preserves: + return "preserve" + return "fallthrough" + + +def compare_census(parsed, tables_source): + """The parsed classification must equal the census for every scalar op.""" + assert parsed["reads"] == EXPECTED_READS, parsed["reads"] ^ EXPECTED_READS + assert parsed["mask_scc"] == EXPECTED_MASK_SCC, parsed["mask_scc"] ^ EXPECTED_MASK_SCC + assert parsed["overwrites"] == EXPECTED_MASK_SCC | EXPECTED_OVERWRITES_EXTRA, ( + parsed["overwrites"] ^ (EXPECTED_MASK_SCC | EXPECTED_OVERWRITES_EXTRA)) + assert parsed["preserves_pair"] == EXPECTED_PRESERVES_PAIR, ( + parsed["preserves_pair"] ^ EXPECTED_PRESERVES_PAIR) + assert parsed["preserves_sop1"] == EXPECTED_PRESERVES_SOP1, ( + parsed["preserves_sop1"] ^ EXPECTED_PRESERVES_SOP1) + assert parsed["preserves_sopk"] == EXPECTED_PRESERVES_SOPK, ( + parsed["preserves_sopk"] ^ EXPECTED_PRESERVES_SOPK) + assert "(inst.enc == Encoding::Sopk && !overwrites && !preserves_sopk)" in parsed["block"], ( + "the Sopk uncertain clause must exclude overwriters and preservers") + assert "inst.enc == Encoding::Sopc" in parsed["block"], "SOPC must stay a blanket overwriter" + assert "Sopp" not in parsed["block"].split("const bool uncertain_scalar")[1].split(";")[0], ( + "the uncertain test must never match SOPP") + ops = isa_names(tables_source) + seen = {} + for name, enc, op in ops: + assert name not in seen, f"{name} listed in both {seen[name]} and {enc}" + seen[name] = enc + got = parsed_class(name, enc, op, (), parsed) + want = expected_class(name, enc, op) + assert got == want, f"{name} ({enc} {op}): parsed={got}, expected={want}" + assert {n for n, e, _ in ops if e == "Sop1" and expected_class(n, e, _) == "uncertain"} == EXPECTED_UNCERTAIN_SOP1 + assert {n for n, e, _ in ops if e == "Sopk" and expected_class(n, e, _) == "uncertain"} == EXPECTED_UNCERTAIN_SOPK + assert {n for n, e, _ in ops if e == "Sop2" and expected_class(n, e, _) == "uncertain"} == set() + sopp = {n for n, e, _ in ops if e == "Sopp"} + assert sopp == LOWERED_SOPP | { + "s_cbranch_scc0", "s_cbranch_scc1", "s_endpgm", "s_wakeup", "s_setkill", + "s_sethalt", "s_sleep", "s_sendmsg", "s_sendmsghalt", "s_trap", + "s_icache_inv", "s_incperflevel", "s_decperflevel", "s_ttracedata", + "s_cbranch_cdbgsys", "s_cbranch_cdbguser", "s_cbranch_cdbgsys_or_user", + "s_cbranch_cdbgsys_and_user", "s_endpgm_saved", + "s_endpgm_ordered_ps_done", "s_code_end", "s_wait_idle", + "s_ttracedata_imm"}, sopp + return len(ops) + + +def is_branch(inst): + return inst["enc"] == "Sopp" and inst["op"] in (2, 4, 5, 6, 7, 8, 9) + + +def ins(name, enc, op=None, target=None, srcs=()): + return {"name": name, "enc": enc, "op": op, "target": target, "srcs": tuple(srcs)} + + +def scc_live_after(program, traits): + """Replica of the backward walk in uses_scc_after(). Returns the live + flags; live[field + 1] is whether SCC is live after the field at index 0.""" + count = len(program) + live = [False] * count + predecessors = [[] for _ in range(count)] + pending = [] + for j, inst in enumerate(program): + live_seed, stops, _ = traits(inst) + if live_seed: + live[j] = True + pending.append(j) + continue + if stops: + continue + if is_branch(inst): + predecessors[inst["target"]].append(j) + if not is_branch(inst) or inst["op"] != 2: + if j + 1 < count: + predecessors[j + 1].append(j) + while pending: + j = pending.pop() + for pred in predecessors[j]: + if live[pred]: + continue + live[pred] = True + pending.append(pred) + return live + + +def battery_programs(): + f = ins("s_bfe_u32", "Sop2") + end = ins("s_endpgm", "Sopp", op=1) + csel = ins("s_cselect_b32", "Sop2") + and32 = ins("s_and_b32", "Sop2") + vmov = ins("v_mov_b32", "Vop1") + mov_vcc = ins("s_mov_b32", "Sop1") + cases = [ + ("overwrite then read", [f, and32, csel, end], False), + ("s_bfe_i32 kills SCC", [f, ins("s_bfe_i32", "Sop2"), csel, end], False), + ("s_addk_i32 kills SCC", [f, ins("s_addk_i32", "Sopk"), csel, end], False), + ("s_mulk_i32 then overwrite", [f, ins("s_mulk_i32", "Sopk"), and32, csel, end], False), + ("s_mulk_i32 then read", [f, ins("s_mulk_i32", "Sopk"), csel, end], True), + ("waitcnt then overwrite", [f, ins("s_waitcnt_vscnt", "Sopk"), and32, csel, end], False), + ("waitcnt then read", [f, ins("s_waitcnt_vscnt", "Sopk"), csel, end], True), + ("round_mode then overwrite", [f, ins("s_round_mode", "Sopp", op=36), and32, csel, end], False), + ("round_mode then read", [f, ins("s_round_mode", "Sopp", op=36), csel, end], True), + ("direct read", [f, csel, end], True), + ("explicit src_scc read", [f, ins("s_mov_b32", "Sop1", srcs=(253,)), end], True), + ("s_addc_u32 reads SCC", [f, ins("s_addc_u32", "Sop2"), end], True), + ("s_subb_u32 reads SCC", [f, ins("s_subb_u32", "Sop2"), end], True), + ("s_nop then overwrite", [f, ins("s_nop", "Sopp", op=0), and32, csel, end], False), + ("branch over reader", [f, ins("s_branch", "Sopp", op=2, target=3), csel, vmov, end], False), + ("diamond both overwrite", [f, mov_vcc, ins("s_cbranch_vccz", "Sopp", op=6, target=5), + ins("s_cmpk_eq_i32", "Sopk"), + ins("s_branch", "Sopp", op=2, target=6), + ins("s_bfe_i32", "Sop2"), csel, vmov, end], False), + ("diamond one overwrite", [f, mov_vcc, ins("s_cbranch_vccz", "Sopp", op=6, target=5), + ins("s_cmpk_eq_i32", "Sopk"), + ins("s_branch", "Sopp", op=2, target=7), + ins("s_movk_i32", "Sopk"), ins("s_mulk_i32", "Sopk"), + csel, vmov, end], True), + ("diamond overwrite on taken arm", [f, mov_vcc, ins("s_cbranch_vccz", "Sopp", op=6, target=6), + ins("s_movk_i32", "Sopk"), ins("s_mulk_i32", "Sopk"), + ins("s_branch", "Sopp", op=2, target=7), + ins("s_bfe_i32", "Sop2"), csel, vmov, end], True), + ("loop without read", [f, ins("s_mulk_i32", "Sopk"), + ins("s_cbranch_vccz", "Sopp", op=6, target=1), end], False), + ("loop with read", [f, ins("s_mulk_i32", "Sopk"), csel, + ins("s_cbranch_vccz", "Sopp", op=6, target=1), end], True), + ("setreg_imm32 then overwrite", [f, ins("s_setreg_imm32_b32", "Sopk"), and32, csel, end], False), + ("setreg_imm32 then read", [f, ins("s_setreg_imm32_b32", "Sopk"), csel, end], True), + ("denorm_mode then overwrite", [f, ins("s_denorm_mode", "Sopp", op=37), and32, csel, end], False), + ("unimplemented SOP1 stays uncertain", [f, ins("s_getpc_b64", "Sop1"), and32, csel, end], True), + ("unimplemented SOPK stays uncertain", [f, ins("s_version", "Sopk"), and32, csel, end], True), + ("SOP1 preservers then end", [f, ins("s_mov_b32", "Sop1"), ins("s_brev_b32", "Sop1"), vmov, end], False), + ("existing s_bfe_u32 kills SCC", [f, ins("s_bfe_u32", "Sop2"), csel, end], False), + ("s_cbranch_scc1 reads SCC", [f, ins("s_cbranch_scc1", "Sopp", op=5, target=3), vmov, end], True), + ("SOPC compare kills SCC", [f, ins("s_cmp_eq_i32", "Sopc"), csel, end], False), + ("s_cmov_b32 reads SCC", [f, ins("s_cmov_b32", "Sop1"), end], True), + ("s_quadmask_b32 kills SCC", [f, ins("s_quadmask_b32", "Sop1"), csel, end], False), + ] + # One battery case per mutated condition, so every mutant must flip one. + for name in CMPK_OPS: + cases.append((f"{name} kills SCC", [f, ins(name, "Sopk"), csel, end], False)) + for name in ("s_waitcnt_vmcnt", "s_waitcnt_expcnt", "s_waitcnt_lgkmcnt"): + cases.append((f"{name} then overwrite", [f, ins(name, "Sopk"), and32, csel, end], False)) + cases.append((f"{name} then read", [f, ins(name, "Sopk"), csel, end], True)) + cases.append(("s_setreg_b32 then overwrite", [f, ins("s_setreg_b32", "Sopk"), and32, csel, end], False)) + cases.append(("s_setreg_b32 then read", [f, ins("s_setreg_b32", "Sopk"), csel, end], True)) + cases.append(("s_movk_i32 then overwrite", [f, ins("s_movk_i32", "Sopk"), and32, csel, end], False)) + cases.append(("s_movk_i32 then read", [f, ins("s_movk_i32", "Sopk"), csel, end], True)) + return cases + + +def run_battery(traits): + results = {} + for label, program, want in battery_programs(): + got = scc_live_after(program, traits)[1] + assert got == want, f"{label}: live={got}, expected={want}" + results[label] = got + return results + + +def expected_traits(inst): + cls = expected_class(inst["name"], inst["enc"], inst["op"]) + if inst["name"] in EXPECTED_READS or 253 in inst["srcs"]: + cls = "read" + return cls in ("read", "uncertain", "branch-scc"), cls in ("overwrite", "endpgm"), False + + +def mutation_audit(source, tables_source): + """Delete/replace every new/modified classification condition once; each + mutant must break the census comparison, and every mutant except the + reader additions must also flip at least one battery program (readers + stay live as uncertain, so their flip is the census itself).""" + base = parse_classification(source) + base_results = run_battery(lambda inst: parsed_traits( + inst["name"], inst["enc"], inst["op"], inst["srcs"], base)) + mutants = [] + for name in NEW_OVERWRITES: + mutants.append((f"drop {name} from overwrites", f'n == "{name}"', True)) + for name in sorted(EXPECTED_PRESERVES_SOPK): + mutants.append((f"drop {name} from preserves_sopk", f'n == "{name}"', True)) + for name in NEW_READS: + mutants.append((f"drop {name} from reads_scc", f'n == "{name}"', False)) + mutants.append(("drop !overwrites from the Sopk uncertain clause", + "!overwrites && !preserves_sopk", True)) + killed = 0 + for label, needle, expect_flip in mutants: + block = base["block"] + assert needle in block, label + if needle.startswith("!overwrites"): + mutant_block = block.replace(needle, "!preserves_sopk", 1) + else: + mutant_block = block.replace(needle, 'n == "s_endpgm"', 1) + mutant_source = source.replace(block, mutant_block, 1) + mutant = parse_classification(mutant_source) + try: + compare_census(mutant, tables_source) + except AssertionError: + killed += 1 + else: + raise AssertionError(f"mutation survived the census: {label}") + if expect_flip: + mutant_results = { + label: scc_live_after(program, lambda inst: parsed_traits( + inst["name"], inst["enc"], inst["op"], inst["srcs"], mutant))[1] + for label, program, _want in battery_programs()} + assert any(mutant_results[label2] != base_results[label2] + for label2 in base_results), f"mutation flipped nothing: {label}" + assert killed == len(mutants), (killed, len(mutants)) + return killed, len(mutants) + + +# --------------------------------------------------------------------------- +# Controls / hardware programs. +# --------------------------------------------------------------------------- + +CMPK_CASES = ( + ("eq", 3, "i32", 10, 10), ("lg", 4, "i32", 10, 5), ("gt", 5, "i32", 10, 5), + ("ge", 6, "i32", 10, 10), ("lt", 7, "i32", 10, 5), ("le", 8, "i32", 10, 10), + ("eq", 9, "u32", 0xFFFFFFFF, 0xFFFF), ("lg", 10, "u32", 0xFFFFFFFF, 0), + ("gt", 11, "u32", 0xFFFFFFFF, 0), ("ge", 12, "u32", 0xFFFFFFFF, 0xFFFF), + ("lt", 13, "u32", 0xFFFFFFFF, 0), ("le", 14, "u32", 0xFFFFFFFF, 0xFFFF), +) + + +def pass_programs(): + base = prologue() + group_base() + programs = [] + programs.append(("bfe-i32", base + smov(22, 0x80) + smov(23, 0x00080000) + + [scalar(40, 24, 22, 23)] + cselect(27) + [vmove(0, 27), ENDPGM])) + programs.append(("addk", base + smov(24, 0x7FFFFFFF) + [sopk(15, 24, 1)] + cselect(27) + + smov(24, 5) + [sopk(15, 24, 3)] + cselect(28) + + [vmove(0, 27), vmove(1, 28), ENDPGM])) + cmpk_words = list(base) + for _cmp, op, kind, preset, simm in CMPK_CASES: + cmpk_words += movk(24, preset) if kind == "i32" else smov(24, preset) + cmpk_words += [sopk(op, 24, simm)] + cselect(27) + cmpk_words += [vmove(0, 27), ENDPGM] + programs.append(("cmpk", cmpk_words)) + programs.append(("preservers", base + movk(24, 6) + [sopk(16, 24, 7)] + + [sopk(23, 125, 0), sopk(24, 125, 0), sopk(25, 125, 0), sopk(26, 125, 0)] + + [scalar(14, 24, 24, 24)] + cselect(27) + [vmove(0, 27), ENDPGM])) + programs.append(("mode", base + [sopp(36, 0), sopp(37, 0xF), sopk(21, 0, 0x0881), 0] + + [scalar(14, 24, 24, 24)] + cselect(27) + [vmove(0, 27)] + + f16_filler() + [ENDPGM])) + programs.append(("nop", base + [sopp(0, 0)] + [scalar(14, 24, 24, 24)] + cselect(27) + + [vmove(0, 27), ENDPGM])) + programs.append(("branch-over-reader", base + [sopp(2, 1)] + cselect(27) + + [vmove(0, 27), ENDPGM])) + programs.append(("diamond-both-overwrite", base + + diamond(movk(24, 10) + [sopk(3, 24, 10)], + smov(22, 0x80) + smov(23, 0x00080000) + [scalar(40, 24, 22, 23)]) + + cselect(27) + [vmove(0, 27), ENDPGM])) + return programs + + +def refusal_programs(): + base = prologue() + group_base() + programs = [] + programs.append(("cselect", base + cselect(27) + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) + programs.append(("src-scc", base + [sop1(3, 26, 253)] + [vmove(0, 26), ENDPGM], SCC_REFUSAL)) + programs.append(("mulk", base + movk(24, 6) + [sopk(16, 24, 7)] + cselect(27) + + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) + for op, name in ((23, "waitcnt-vscnt"), (24, "waitcnt-vmcnt"), + (25, "waitcnt-expcnt"), (26, "waitcnt-lgkmcnt")): + programs.append((name, base + [sopk(op, 125, 0)] + cselect(27) + + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) + programs.append(("round-mode", base + [sopp(36, 0)] + cselect(27) + [vmove(0, 27)] + + f16_filler() + [ENDPGM], SCC_REFUSAL)) + programs.append(("denorm-mode", base + [sopp(37, 0xF)] + cselect(27) + [vmove(0, 27)] + + f16_filler() + [ENDPGM], SCC_REFUSAL)) + programs.append(("setreg-imm32", base + [sopk(21, 0, 0x0881), 0] + cselect(27) + + [vmove(0, 27)] + f16_filler() + [ENDPGM], SCC_REFUSAL)) + programs.append(("nop", base + [sopp(0, 0)] + cselect(27) + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) + programs.append(("waitcnt", base + [0xBF8CC07F] + cselect(27) + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) + programs.append(("waitcnt-depctr", base + [sopp(35, 0)] + cselect(27) + + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) + programs.append(("barrier", base + [sopp(10, 0)] + cselect(27) + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) + programs.append(("addc", base + smov(22, 1) + smov(23, 2) + [scalar(4, 24, 22, 23)] + + [vmove(0, 24), ENDPGM], SCC_REFUSAL)) + programs.append(("subb", base + smov(22, 1) + smov(23, 2) + [scalar(5, 24, 22, 23)] + + [vmove(0, 24), ENDPGM], SCC_REFUSAL)) + programs.append(("cbranch-scc1", base + [sopp(5, 1), vmove(0, 27), ENDPGM], SCC_REFUSAL)) + programs.append(("diamond-one-overwrite", base + + diamond([sopk(3, 24, 10)], movk(24, 6) + [sopk(16, 24, 7)]) + + cselect(27) + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) + programs.append(("setreg-b32", base + [sopk(19, 0, 0x981)] + + [scalar(14, 24, 24, 24)] + cselect(27) + [vmove(0, 27)] + + f16_filler() + [ENDPGM], "unsupported binary16 rounding or denormal mode")) + programs.append(("round-mode-1", base + [sopp(36, 1)] + + [scalar(14, 24, 24, 24)] + cselect(27) + [vmove(0, 27)] + + f16_filler() + [ENDPGM], "unsupported compute control instruction s_round_mode")) + programs.append(("denorm-mode-0c", base + [sopp(37, 0xC)] + + [scalar(14, 24, 24, 24)] + cselect(27) + [vmove(0, 27)] + + f16_filler() + [ENDPGM], "unsupported compute control instruction s_denorm_mode")) + return programs + + +def hardware_program(): + words = prologue() + group_base() + # s_bfe_i32: 0x80 with width 8 -> -128 (SCC 1), then 0 -> 0 (SCC 0). + words += smov(22, 0x80) + smov(23, 0x00080000) + [scalar(40, 24, 22, 23)] + cselect(27) + words += store(0, 24) + store(1, 27) + words += smov(22, 0) + smov(23, 0x00080000) + [scalar(40, 24, 22, 23)] + cselect(27) + words += store(2, 24) + store(3, 27) + # s_addk_i32: 0x7fffffff + 1 overflows (SCC 1), 5 + 3 does not (SCC 0). + words += smov(24, 0x7FFFFFFF) + [sopk(15, 24, 1)] + cselect(27) + store(4, 24) + store(5, 27) + words += smov(24, 5) + [sopk(15, 24, 3)] + cselect(27) + store(6, 24) + store(7, 27) + # s_cmpk_*: 10 == 10, 10 < 5 (signed), 0xffffffff < 0xffff (unsigned), + # -1 >= -1 (signed, simm sign-extended). + words += movk(24, 10) + [sopk(3, 24, 10)] + cselect(27) + store(8, 27) + words += movk(24, 10) + [sopk(7, 24, 5)] + cselect(27) + store(9, 27) + words += smov(24, 0xFFFFFFFF) + [sopk(13, 24, 0xFFFF)] + cselect(27) + store(10, 27) + words += movk(24, 0xFFFF) + [sopk(6, 24, 0xFFFF)] + cselect(27) + store(11, 27) + # Preservers: re-extract the stride field so the SCC entering the op is + # the field's SCC, then prove s_mulk_i32 and s_waitcnt_vscnt carry both + # the 0 and the 1 into s_cselect_b32 (stride 0 and stride 4 runs). + words += field() + movk(24, 6) + [sopk(16, 24, 7)] + cselect(27) + store(12, 24) + store(13, 27) + words += field() + [sopk(23, 125, 0)] + cselect(27) + store(14, 27) + words += store(15, 25) + return words + [ENDPGM] + + +def disasm(words): + return disasm_rdna2.disassemble_binary( + struct.pack(f"<{len(words)}I", *words), "scc-liveness") + + +def assert_branch_target(rows, branch_asm, target_asm): + branch = next(row for row in rows if row["assembly"].startswith(branch_asm)) + label = branch["assembly"].split()[-1] + target = next(row for row in rows if row["assembly"].startswith(target_asm)) + assert label == f"label_0x{target['offset']:x}", (branch["assembly"], target["assembly"]) + + +def encodings(): + needles = { + "bfe-i32": ["s_bfe_i32 s24, s22, s23", "s_cselect_b32 s27, 1, 0"], + "addk": ["s_addk_i32 s24, 0x1", "s_addk_i32 s24, 0x3"], + "preservers": ["s_mulk_i32 s24, 0x7", "s_waitcnt_vscnt null, 0x0", + "s_waitcnt_vmcnt null, 0x0", "s_waitcnt_expcnt null, 0x0", + "s_waitcnt_lgkmcnt null, 0x0", "s_and_b32 s24, s24, s24"], + "mode": ["s_round_mode 0x0", "s_denorm_mode 15", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0", + "v_add_f16_e32 v3, v1, v2"], + "nop": ["s_nop 0"], + "setreg-b32": ["s_setreg_b32 hwreg(HW_REG_MODE, 6, 2), s0"], + "addc": ["s_addc_u32 s24, s22, s23"], + "subb": ["s_subb_u32 s24, s22, s23"], + } + for label, words in pass_programs() + [(label, words) for label, words, _ in refusal_programs()]: + rows = disasm(words) + asm = [row["assembly"] for row in rows] + text = "\n".join(asm) + assert asm[-1] == "s_endpgm", (label, asm[-1]) + assert "s_bfe_u32 s25, s17, 0xe0010" in text, label + for needle in needles.get(label, ()): + assert needle in text, (label, needle) + if label == "cmpk": + for cmp, _op, kind, _preset, _simm in CMPK_CASES: + assert f"s_cmpk_{cmp}_{kind} s24" in text, (label, cmp, kind) + for label, words in (("diamond-both-overwrite", dict(pass_programs())["diamond-both-overwrite"]), + ("diamond-one-overwrite", dict( + (label, words) for label, words, _ in refusal_programs())["diamond-one-overwrite"])): + rows = disasm(words) + assert_branch_target(rows, "s_cbranch_vccz", "s_movk_i32 s24, 0x6" if label.endswith("one-overwrite") + else "s_mov_b32 s22, 0x80") + assert_branch_target(rows, "s_branch", "s_cselect_b32 s27, 1, 0") + rows = disasm(dict(pass_programs())["branch-over-reader"]) + assert_branch_target(rows, "s_branch", "v_mov_b32_e32 v0, s27") + rows = disasm(hardware_program()) + asm = [row["assembly"] for row in rows] + text = "\n".join(asm) + assert asm.count("s_bfe_u32 s25, s17, 0xe0010") == 3, asm + for slot in range(16): + needle = "buffer_store_dword v10, v8, s[32:35], 0 offen" + if slot: + needle += f" offset:{4 * slot}" + assert needle in text, slot + print(f"encodings: {len(pass_programs()) + len(refusal_programs())} controls programs " + "and the hardware program disassemble as written, with branch targets pinned") + + +def audit(): + source = INL.read_text(encoding="utf-8") + tables_source = TABLES.read_text(encoding="utf-8") + parsed = parse_classification(source) + count = compare_census(parsed, tables_source) + run_battery(lambda inst: parsed_traits( + inst["name"], inst["enc"], inst["op"], inst["srcs"], parsed)) + run_battery(expected_traits) + killed, total = mutation_audit(source, tables_source) + check_scc_writer_mutant() + encodings() + print(f"audit: {count} scalar ops in the ISA tables match the census; " + f"{len(battery_programs())} CFG programs agree between the parsed " + f"classification, the census and the hand-computed expectations; " + f"mutation audit killed {killed}/{total}; " + "native_direct_container scc_overwrite_names still parses") + return 0 + + +def compile_one(cli, sdk, work, root, words, label, error=None): + marker = write_request(work / "requests", words, root, SA) + output = work / f"{label}.cso" + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + if error is None: + assert result.returncode == 0 and output.is_file(), (label, result.stdout, result.stderr) + else: + assert result.returncode and error in result.stderr, (label, result.stdout, result.stderr) + assert not output.exists(), label + + +def controls(cli, sdk, work, root1, root2): + # root1 has no stride metadata for the descriptor slot, so a live SCC at + # the field must refuse and a dead SCC must compile. root2 binds the + # stride, so the direct read compiles there as the positive control. + (work / "requests").mkdir(exist_ok=True) + (work / "cache").mkdir(exist_ok=True) + passes = pass_programs() + refusals = refusal_programs() + for label, words in passes: + compile_one(cli, sdk, work, root1, words, "pass-" + label) + for label, words, error in refusals: + compile_one(cli, sdk, work, root1, words, "refuse-" + label, error) + compile_one(cli, sdk, work, root2, prologue() + group_base() + cselect(27) + + [vmove(0, 27), ENDPGM], "pass-stride-bound-read") + print(f"controls: {len(passes)} pass programs compiled, {len(refusals)} refusal " + "programs refused with the pinned message, and the direct read compiled " + "once the stride was bound") + return 0 + + +def hardware(replay, sdk, work, root2): + (work / "requests").mkdir(exist_ok=True) + (work / "cache").mkdir(exist_ok=True) + marker = write_request(work / "requests", hardware_program(), root2, SA) + readback = work / "readback.bin" + metadata = work / "stride.txt" + for stride in (0, 4): + metadata.write_text(str(stride), encoding="ascii") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", readback, + "--direct", metadata], capture_output=True, text=True) + if result.returncode == 77: + print(result.stderr.strip()) + return 77 + assert result.returncode == 0, result.stdout + result.stderr + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + start = GUARD_WORDS + group * 16 + expected[start:start + 16] = [ + 0xFFFFFF80, 1, 0, 0, 0x80000000, 1, 8, 0, + 1, 0, 0, 1, 42, int(stride != 0), int(stride != 0), stride] + actual = list(struct.unpack(f"<{OUTPUT_WORDS}I", readback.read_bytes())) + assert actual == expected, next( + (i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b) + print(f"hardware: stride {stride}: 16 output words and all guards match in both groups") + return 0 + + +def root_bytes(work, dxc, srv_count): + source = work / f"root{srv_count}.hlsl" + root = work / f"root{srv_count}.bin" + source.write_text(f'#define RS "{ROOT_SIG.format(srv=srv_count, uav=3 - srv_count)}"\n', + encoding="ascii") + subprocess.run([dxc, "-T", "rootsig_1_1", "-E", "RS", source, "-Fo", root], check=True) + return root.read_bytes() + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + dxc = Path(sdk) / "dxc.exe" + root1 = root_bytes(work, dxc, 1) + root2 = root_bytes(work, dxc, 2) + if mode == "controls": + return controls(tool, sdk, work, root1, root2) + if mode == "hardware": + return hardware(tool, sdk, work, root2) + raise SystemExit(f"unknown mode {mode}") + + +if __name__ == "__main__": + sys.exit(audit() if len(sys.argv) == 1 else main(*sys.argv[1:])) From f4d347b1ace35394f5350d40b60480829929e938 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <241957358+Ammmae0x@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:54:53 +0200 Subject: [PATCH 2/2] compute: fix SCC liveness fixture ordering and unbound SGPRs Windows dev verification of c60704bf compiled the C++ cleanly but caught three fixture bugs in tests/native_scc_liveness_check.py: - The field was extracted in prologue(), before group_base(), whose s_lshl_b32 overwrites SCC, so all 15 SCC refusals returned rc=0. The field now comes after the group base and the SGPR initializations (new base_words() helper), so the field's SCC is the one the tested instruction sees. - s24 and s27 were read unbound in several controls programs. The base now initializes them (movk(24, 1) + movk(27, 0); movk(24, 6) for the one-arm-overwrite diamond), and the stride-bound positive control uses the same base. - hardware_program() stored s25 numerically, but the stride field value is symbolic. Slot 15 now re-extracts the field and proves the mode writes (s_round_mode 0, s_denorm_mode 0xf, s_setreg_imm32_b32) preserve its SCC into s_cselect_b32. The no-arg audit now also pins the base initializations and the pass/refusal split itself: between the field and the first SCC reader, every pass program has an overwriter (except the branch-over-reader, which passes by skipping the reader) and every SCC refusal program has none (except the diamond that refuses on its preserving arm, and the three mode refusals, which refuse on the mode op). Linux: no-arg audit passes (199 scalar ops, 53 CFG programs, 25/25 mutants killed), run_checks_parallel 277/277, form/docs/bidi pass (187 files/738 links, 2728 files), py_compile and diff --check clean, merge-tree exits 0. Refs #3224, #2935 --- .../experiments/native-direct-scc-liveness.md | 40 ++++++--- tests/native_scc_liveness_check.py | 88 +++++++++++++++---- 2 files changed, 102 insertions(+), 26 deletions(-) diff --git a/docs/experiments/native-direct-scc-liveness.md b/docs/experiments/native-direct-scc-liveness.md index cb03256e81..78292e1f2e 100644 --- a/docs/experiments/native-direct-scc-liveness.md +++ b/docs/experiments/native-direct-scc-liveness.md @@ -46,19 +46,37 @@ ops in the ISA tables against the census, runs a Python replica of the backward walk over 53 straight-line and branching programs (including a diamond where only one arm overwrites SCC, a branch over a reader, and loops with and without a reader), and kills 25 of 25 single-condition -mutants of the new and modified conditions. The `controls` mode compiles 8 -pass programs and 21 refusal programs against a root whose descriptor slot -has no stride metadata: the pass programs compile, every refusal program -fails with the exact "numeric SCC from a symbolic descriptor field" -substring, and the direct read compiles once the stride is bound. The -`hardware` mode replays one shader with stride 0 and stride 4 and checks -all 16 output words and guards in both groups, covering signed and -unsigned imm16 sign-extension and boundary values for `s_bfe_i32`, -`s_addk_i32` and `s_cmpk_*`, and proving `s_mulk_i32` and +mutants of the new and modified conditions. It also disassembles every +controls program and the hardware program and pins their exact encodings: +every controls program starts from the same base (the descriptor loads, the +group base, `s_movk_i32 s24, 1` and `s_movk_i32 s27, 0`, then the field +extraction), so the field's SCC is the one the tested instruction sees and +no SGPR is read unbound. The field must come after the group base because +the base starts with `s_lshl_b32`, an SCC overwriter. The no-arg mode +further pins the pass/refusal split itself: between the field and the first +SCC reader, every pass program has an overwriter (except the +branch-over-reader, which passes by skipping the reader) and every SCC +refusal program has none (except the diamond that refuses on its preserving +arm, and the three mode refusals, which refuse on the mode op). The +`controls` mode compiles 8 pass programs and 21 refusal programs against +a root whose descriptor slot has no stride metadata: the pass programs +compile, every refusal program fails with the exact "numeric SCC from a +symbolic descriptor field" substring, and the direct read compiles once the +stride is bound. The `hardware` mode replays one shader with stride 0 and +stride 4 and checks all 16 output words and guards in both groups, +covering signed and unsigned imm16 sign-extension and boundary values for +`s_bfe_i32`, `s_addk_i32` and `s_cmpk_*`, and proving `s_mulk_i32` and `s_waitcnt_vscnt null, 0` carry both SCC 0 and SCC 1 into `s_cselect_b32`. +Slot 15 proves the same for the mode writes (`s_round_mode 0`, +`s_denorm_mode 0xf`, `s_setreg_imm32_b32`) after a fresh field extraction; +the stride field value itself is symbolic, so it cannot be stored +numerically and is never read as a value. -Windows verification is pending; the Linux results above are the no-arg -audit only. +Windows verification is pending on the current head. The first dev run +compiled the C++ cleanly and caught three fixture bugs in the check (the +field extracted before the group base, unbound SGPR reads in the controls +programs, and a numeric store of the symbolic field value in the hardware +program); those are fixed in this commit and re-verification is pending. ```powershell cmake --build --preset dev --target compile_dxil native_store_replay diff --git a/tests/native_scc_liveness_check.py b/tests/native_scc_liveness_check.py index 1859aeb6f3..01a7259dac 100644 --- a/tests/native_scc_liveness_check.py +++ b/tests/native_scc_liveness_check.py @@ -164,13 +164,22 @@ def prologue(): return [sop1(3, 20, 4), sop1(3, 21, 128), 0xF408040A, 0xFA000020, # input SRV in s[16:19] 0xF408080A, 0xFA000040, # output UAV in s[32:35] - 0xBF8CC07F] + field() + 0xBF8CC07F] def group_base(): return [scalar(0x1E, 7, 6, 134), vmove(8, 7), sop1(3, 126, 129)] +def base_words(s24_init=1): + # The field extraction must come AFTER the group base and AFTER the SGPR + # initializations. group_base() starts with s_lshl_b32, an SCC overwriter, + # so extracting the field before it would kill the field's SCC before the + # tested instruction ever sees it. s24 and s27 are initialized here so no + # later read of either is an unbound numeric SGPR. + return prologue() + group_base() + movk(24, s24_init) + movk(27, 0) + field() + + def cselect(dst): return [scalar(0x0A, dst, 129, 128)] @@ -517,7 +526,7 @@ def mutation_audit(source, tables_source): def pass_programs(): - base = prologue() + group_base() + base = base_words() programs = [] programs.append(("bfe-i32", base + smov(22, 0x80) + smov(23, 0x00080000) + [scalar(40, 24, 22, 23)] + cselect(27) + [vmove(0, 27), ENDPGM])) @@ -548,7 +557,7 @@ def pass_programs(): def refusal_programs(): - base = prologue() + group_base() + base = base_words() programs = [] programs.append(("cselect", base + cselect(27) + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) programs.append(("src-scc", base + [sop1(3, 26, 253)] + [vmove(0, 26), ENDPGM], SCC_REFUSAL)) @@ -574,7 +583,7 @@ def refusal_programs(): programs.append(("subb", base + smov(22, 1) + smov(23, 2) + [scalar(5, 24, 22, 23)] + [vmove(0, 24), ENDPGM], SCC_REFUSAL)) programs.append(("cbranch-scc1", base + [sopp(5, 1), vmove(0, 27), ENDPGM], SCC_REFUSAL)) - programs.append(("diamond-one-overwrite", base + programs.append(("diamond-one-overwrite", base_words(6) + diamond([sopk(3, 24, 10)], movk(24, 6) + [sopk(16, 24, 7)]) + cselect(27) + [vmove(0, 27), ENDPGM], SCC_REFUSAL)) programs.append(("setreg-b32", base + [sopk(19, 0, 0x981)] @@ -590,7 +599,7 @@ def refusal_programs(): def hardware_program(): - words = prologue() + group_base() + words = prologue() + group_base() + field() # s_bfe_i32: 0x80 with width 8 -> -128 (SCC 1), then 0 -> 0 (SCC 0). words += smov(22, 0x80) + smov(23, 0x00080000) + [scalar(40, 24, 22, 23)] + cselect(27) words += store(0, 24) + store(1, 27) @@ -610,7 +619,13 @@ def hardware_program(): # the 0 and the 1 into s_cselect_b32 (stride 0 and stride 4 runs). words += field() + movk(24, 6) + [sopk(16, 24, 7)] + cselect(27) + store(12, 24) + store(13, 27) words += field() + [sopk(23, 125, 0)] + cselect(27) + store(14, 27) - words += store(15, 25) + # The stride field value is symbolic, so s25 cannot be stored numerically. + # Instead, re-extract the field and prove the mode writes (s_round_mode 0, + # s_denorm_mode 0xf, s_setreg_imm32_b32) preserve its SCC into s_cselect_b32. + # The f16 filler at the end makes half_binary true so the mode writes are + # accepted. + words += field() + [sopp(36, 0), sopp(37, 0xF), sopk(21, 0, 0x0881), 0] + cselect(27) + store(15, 27) + words += f16_filler() return words + [ENDPGM] @@ -620,13 +635,27 @@ def disasm(words): def assert_branch_target(rows, branch_asm, target_asm): - branch = next(row for row in rows if row["assembly"].startswith(branch_asm)) + # The target is always after the branch, so search forward from it: an + # identical instruction can also appear before the branch (the diamond + # base initializes s24 to the same value arm B writes). + branch_idx = next(i for i, row in enumerate(rows) if row["assembly"].startswith(branch_asm)) + branch = rows[branch_idx] label = branch["assembly"].split()[-1] - target = next(row for row in rows if row["assembly"].startswith(target_asm)) + target = next(row for row in rows[branch_idx + 1:] if row["assembly"].startswith(target_asm)) assert label == f"label_0x{target['offset']:x}", (branch["assembly"], target["assembly"]) -def encodings(): +def first_reader_index(asm, field_idx, parsed): + """Index of the first SCC reader after the field extraction, or None.""" + for i in range(field_idx + 1, len(asm)): + op = asm[i].split()[0] + if (op in parsed["reads"] or "src_scc" in asm[i] + or op in ("s_cbranch_scc0", "s_cbranch_scc1")): + return i + return None + + +def encodings(parsed): needles = { "bfe-i32": ["s_bfe_i32 s24, s22, s23", "s_cselect_b32 s27, 1, 0"], "addk": ["s_addk_i32 s24, 0x1", "s_addk_i32 s24, 0x3"], @@ -641,17 +670,41 @@ def encodings(): "addc": ["s_addc_u32 s24, s22, s23"], "subb": ["s_subb_u32 s24, s22, s23"], } - for label, words in pass_programs() + [(label, words) for label, words, _ in refusal_programs()]: + # A pass program compiles only because an overwriter kills the field's SCC + # before the first reader; a refusal program has no overwriter in that + # window. branch-over-reader passes by skipping the reader entirely, and + # diamond-one-overwrite refuses on the preserving arm, so both are checked + # by the branch-target assertions and the CFG battery instead. The three + # mode refusals refuse on the mode op, not on SCC. + programs = ([(label, words, True) for label, words in pass_programs()] + + [(label, words, False) for label, words, _ in refusal_programs()]) + for label, words, is_pass in programs: rows = disasm(words) asm = [row["assembly"] for row in rows] text = "\n".join(asm) assert asm[-1] == "s_endpgm", (label, asm[-1]) assert "s_bfe_u32 s25, s17, 0xe0010" in text, label + assert "s_movk_i32 s27, 0x0" in text, label + assert ("s_movk_i32 s24, 0x6" if label == "diamond-one-overwrite" + else "s_movk_i32 s24, 0x1") in text, label for needle in needles.get(label, ()): assert needle in text, (label, needle) if label == "cmpk": for cmp, _op, kind, _preset, _simm in CMPK_CASES: assert f"s_cmpk_{cmp}_{kind} s24" in text, (label, cmp, kind) + field_idx = asm.index("s_bfe_u32 s25, s17, 0xe0010") + reader_idx = first_reader_index(asm, field_idx, parsed) + assert reader_idx is not None, label + window = [asm[i].split()[0] for i in range(field_idx + 1, reader_idx)] + if is_pass: + if label == "branch-over-reader": + # It passes by skipping the reader, not by killing SCC. + assert not any(op in parsed["overwrites"] for op in window), (label, window) + else: + assert any(op in parsed["overwrites"] for op in window), (label, window) + elif label not in ("diamond-one-overwrite", "setreg-b32", + "round-mode-1", "denorm-mode-0c"): + assert not any(op in parsed["overwrites"] for op in window), (label, window) for label, words in (("diamond-both-overwrite", dict(pass_programs())["diamond-both-overwrite"]), ("diamond-one-overwrite", dict( (label, words) for label, words, _ in refusal_programs())["diamond-one-overwrite"])): @@ -664,14 +717,19 @@ def encodings(): rows = disasm(hardware_program()) asm = [row["assembly"] for row in rows] text = "\n".join(asm) - assert asm.count("s_bfe_u32 s25, s17, 0xe0010") == 3, asm + assert asm.count("s_bfe_u32 s25, s17, 0xe0010") == 4, asm + for needle in ("s_round_mode 0x0", "s_denorm_mode 15", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0", + "v_add_f16_e32 v3, v1, v2"): + assert needle in text, needle for slot in range(16): needle = "buffer_store_dword v10, v8, s[32:35], 0 offen" if slot: needle += f" offset:{4 * slot}" assert needle in text, slot print(f"encodings: {len(pass_programs()) + len(refusal_programs())} controls programs " - "and the hardware program disassemble as written, with branch targets pinned") + "and the hardware program disassemble as written, with branch targets pinned " + "and the pass/refusal split pinned to the overwriter window") def audit(): @@ -684,7 +742,7 @@ def audit(): run_battery(expected_traits) killed, total = mutation_audit(source, tables_source) check_scc_writer_mutant() - encodings() + encodings(parsed) print(f"audit: {count} scalar ops in the ISA tables match the census; " f"{len(battery_programs())} CFG programs agree between the parsed " f"classification, the census and the hand-computed expectations; " @@ -717,7 +775,7 @@ def controls(cli, sdk, work, root1, root2): compile_one(cli, sdk, work, root1, words, "pass-" + label) for label, words, error in refusals: compile_one(cli, sdk, work, root1, words, "refuse-" + label, error) - compile_one(cli, sdk, work, root2, prologue() + group_base() + cselect(27) + compile_one(cli, sdk, work, root2, base_words() + cselect(27) + [vmove(0, 27), ENDPGM], "pass-stride-bound-read") print(f"controls: {len(passes)} pass programs compiled, {len(refusals)} refusal " "programs refused with the pinned message, and the direct read compiled " @@ -744,7 +802,7 @@ def hardware(replay, sdk, work, root2): start = GUARD_WORDS + group * 16 expected[start:start + 16] = [ 0xFFFFFF80, 1, 0, 0, 0x80000000, 1, 8, 0, - 1, 0, 0, 1, 42, int(stride != 0), int(stride != 0), stride] + 1, 0, 0, 1, 42, int(stride != 0), int(stride != 0), int(stride != 0)] actual = list(struct.unpack(f"<{OUTPUT_WORDS}I", readback.read_bytes())) assert actual == expected, next( (i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b)