From 0681b9d280ee1adac2d123fb47265da4d9e35444 Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:03:32 +0200 Subject: [PATCH 1/4] cfg_structure / rdna2spirv: unwrap tautological %pc guards in structured CFGs (ms_wave_info_s3 AMD LLPC crash) cfg_structure.structure() wraps post-dominating join blocks after a diamond or loop in a ('guard', g, ...) node even when %pc == g is tautologically true on every incoming path. wave64_emulate_opt._unwrap_known_pc_guards already unwraps these guards for --wave64-emulate, which is why ms_wave_info_s3 passed on 32-wide NVIDIA GPUs while crashing with 0xC0000005 on native wave64 AMD RDNA2 Windows (driver 24.10.24, LLPC) where blk2's OpControlBarrier stayed trapped inside a conditional OpBranchConditional. Move unwrap_known_pc_guards into tools/cfg_structure.py (reused by wave64_emulate_opt with zero duplication) and apply it in rdna2spirv.capped_tree() so both assemble() and needs_barrier_rounds() see post-dominating join blocks at top level. SHADER-STRUCTURED-PC-UNWRAP Co-Authored-By: Gemini 4 Neon --- docs/design.md | 2 +- tests/test_cfg_structure.py | 26 +++++++++++++++ tests/test_translate.py | 5 +++ tools/cfg_structure.py | 61 ++++++++++++++++++++++++++++++++++ tools/rdna2spirv.py | 2 ++ tools/wave64_emulate_opt.py | 66 ++----------------------------------- 6 files changed, 97 insertions(+), 65 deletions(-) diff --git a/docs/design.md b/docs/design.md index 1dd413b8bc..4b25f17477 100644 --- a/docs/design.md +++ b/docs/design.md @@ -291,7 +291,7 @@ How the generated SPIR-V expects the runtime to work: | DPP on a VOPC compare | A VOPC compare whose src0 field is a DPP marker (250 for DPP16, 233/234 for DPP8) takes src0 through the DPP lane selection of the row above and writes VCC: a lane's bit is `compare(src0 of the selected lane, its own src1)`, with 0 for src0 when the selected lane is out of its row or inactive (`bound_ctrl` 1, or DPP8 with `fi` 0). The second word has the layout of a VOP2's DPP word. `llvm-mc` has no decoding for it on gfx10 (LLVM 21.1.8 rejects the first word for `gfx1013`; LLVM defines the form from GFX11 on), so `tools/shader_disasm.py` prints it: it decodes the pair with the first word turned into `v_max_f32` into `v0`, which takes the same second word, and gives the line the compare's name, a `vcc_lo` destination and the real encoding back (`with_vopc_dpp`); `tools/rdna2_decode.py` decodes it directly. **Only the forms where every lane writes its bit are translated**: `row_mask` and `bank_mask` 0xF and either `bound_ctrl` 1 or DPP8. Any other form, and `v_cmpx`, is refused (`DPP compare with lanes that keep their mask bit`), because what a lane DPP leaves unwritten does to its VCC bit is not measured. Found in 3 of the 2,684 pipeline-library compute programs of 1.0.2.1: 4 `v_cmp_gt_f32` each, with `quad_perm:[1,0,3,2]`, `quad_perm:[2,3,0,1]`, `row_ror:8` (all `bound_ctrl:1`, masks 0xF) and `dpp8:[4,5,6,7,0,1,2,3]`, beside `v_min/max_f32_dpp` and `v_mov_b32_dpp` on the same lanes. **Not measured on hardware**: the rule follows from the encoding, from LLVM's GFX11 definition of the same form and from the VOP2 DPP rules measured in the row above; the sweep that measured those (`tools/crosslane_fuzz.py --dpp-sweep --oracle hw`) does not cover compares. Lane values are checked in `tests/semantic/test_dpp_compare.py` (the SPIR-V interpreter) and on a GPU with `runtime/test/shaders/cs_dpp_cmp.asm`. | | EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. | | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | -| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | +| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. `capped_tree()` also runs `cfg_structure.unwrap_known_pc_guards` (shared with `wave64_emulate_opt`) to unwrap tautological `("guard", g, ...)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths (e.g. post-dominating merge blocks after diamonds and loops); this keeps `ms_wave_info_s3`'s `s_barrier` in uniform top-level control flow (fixing an AMD Windows LLPC `0xC0000005` pipeline-creation crash on AMD Ryzen 5 7600 RDNA2 iGPU driver `24.10.24`, `4096/4096` exact on AMD RDNA2 and RTX 4070 SUPER) and avoids false `needs_barrier_rounds` triggers (`SHADER-STRUCTURED-PC-UNWRAP`). AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | | Loop guard | Each loop counts header visits per invocation and exits through its structured merge at `--loop-limit N` (default 65536, zero disables). Counters reset on entry, including nested EXEC retries and atomic loops. A PC-dispatch visit counts a dispatch iteration. Natural exits within the budget preserve their outputs. Five-star-recomp (b12a952) reported a story-load timeout when the shader input made its exit condition unreachable. | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | | Direct resource heap | In the matched Prop/Tree BatchCull compute signature the two explicit tables and scalar constant occupy s4–s6. Bind the resource heap's uint32 arena-relative byte address at s7 (push-constant byte 28). The program supplies a zero high word and scales the resource index by 32 bytes. Other stages and signatures consume different SGPRs. See [descriptor heaps and the bindless model](d3d12_vulkan.md#34-descriptor-heaps-and-the-bindless-model) for the evidence and graphics examples. | diff --git a/tests/test_cfg_structure.py b/tests/test_cfg_structure.py index d4fa490588..f6caa5bd80 100644 --- a/tests/test_cfg_structure.py +++ b/tests/test_cfg_structure.py @@ -146,10 +146,17 @@ def split_choose(b, _orig=orig, _ns=new_succ, _seed=seed, _v=visits): loops += '"loop"' in repr(tree).replace("'", '"') placed = blocks_in(tree) assert len(placed) == len(set(placed)), f"a block is placed twice: {succ}" + out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} + utree = S.unwrap_known_pc_guards(tree, out_pcs) + uplaced = blocks_in(utree) + assert len(uplaced) == len(set(uplaced)) and set(uplaced) == set(placed), ( + f"unwrap changed block set for {succ}: {placed} vs {uplaced}") for seed in range(6): want = walk(succ, chooser(succ, seed), 200) got = S.run(tree, chooser(succ, seed), 200) assert got == want, f"graph {succ} seed {seed}: tree ran {got}, graph runs {want}" + ugot = S.run(utree, chooser(succ, seed), 200) + assert ugot == want, f"unwrapped graph {succ} seed {seed}: tree ran {ugot}, graph runs {want}" assert structured > 5000 and refused > 1000 and loops > 2000, (structured, refused, loops) assert split_ok > 1000 and split_ok + split_cap == refused, (split_ok, split_cap, refused) return structured, refused, loops, split_ok, split_cap @@ -247,10 +254,29 @@ def test_deep_sequential_chains_stay_flat_and_iterative(): assert got == want +def test_unwrap_known_pc_guards(): + def unwrap(succ): + tree = S.structure(succ) + assert tree is not None + out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} + return S.unwrap_known_pc_guards(tree, out_pcs) + + # Single-arm if-then (ms_wave_info_s3 shape: 0 -> {2, 1}, 1 -> {2}, 2 -> []): join block 2 unwraps to top level. + assert unwrap([[2, 1], [2], []]) == [("block", 0), ("guard", 1, [("block", 1)]), ("block", 2)] + # Diamond (0 -> {1, 2}, 1 -> {3}, 2 -> {3}, 3 -> []): join block 3 unwraps to top level. + assert unwrap([[1, 2], [3], [3], []]) == [("block", 0), ("guard", 2, [("block", 2)]), + ("guard", 1, [("block", 1)]), ("block", 3)] + # Loop exit (0 -> {0, 1}, 1 -> []): block 1 unwraps to top level because exiting loop 0 proves pc == 1. + assert unwrap([[0, 1], []]) == [("loop", 0, [("block", 0)]), ("block", 1)] + # Early exit in arm 1 (0 -> {1, 2}, 1 -> [], 2 -> []): both arms MUST remain guarded (pc may be END). + assert unwrap([[1, 2], [], []]) == [("block", 0), ("guard", 2, [("block", 2)]), ("guard", 1, [("block", 1)])] + + if __name__ == "__main__": test_depth() test_shapes() test_deep_sequential_chains_stay_flat_and_iterative() + test_unwrap_known_pc_guards() structured, refused, loops, split_ok, split_cap = _check_random_graphs() print(f"ok: {structured} graphs structured and run, {refused} irreducible " f"({split_ok} split-structured, {split_cap} capped), {loops} with loops") diff --git a/tests/test_translate.py b/tests/test_translate.py index d151c36e28..f94996e1e6 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -1392,6 +1392,11 @@ def test_mesh_s3_wave_id_emits_local_index_shift_and_bfe(make_shader): asm = shader.translate() shader.validate(asm) assert "%wave = OpShiftRightLogical %uint %lidx %c6" in asm + # SHADER-STRUCTURED-PC-UNWRAP: blk2 post-dominates blk0/blk1 and carries s_barrier, so its tautological + # pc == 2 guard must be unwrapped (keeping OpControlBarrier in uniform top-level control flow for AMD LLPC). + blk2_pos = asm.index("%blk2 = OpLabel") + before_blk2 = asm[asm.index("%blk1 = OpLabel"):blk2_pos] + assert "OpBranchConditional" not in before_blk2, before_blk2 assert "%mwi = OpShiftLeftLogical %uint %wave %c18" in asm assert "OpStore %s3p %mwi" in asm assert "OpBitFieldUExtract %uint" in asm diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py index 3409d4dbf5..36eacf7f4f 100644 --- a/tools/cfg_structure.py +++ b/tools/cfg_structure.py @@ -347,3 +347,64 @@ def run(tree, choose, limit): else: stack.pop() return trace + + +def unwrap_known_pc_guards(tree, out_pcs, entry_pc=0): + """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths. + + `structure()` wraps post-dominating join blocks after a diamond or loop in `("guard", g, ...)`. When every + incoming path guarantees `%pc == g` (e.g. a merge block with `s_barrier` after a wave-divergent branch like + `ms_wave_info_s3`), unwrapping the tautological guard keeps `OpControlBarrier` in uniform top-level control + flow (avoiding an AMD Windows LLPC 0xC0000005 pipeline-creation crash in MeshEXT and preventing false + `needs_barrier_rounds` triggers) and avoids redundant `%pc` merge phis. + + `out_pcs[b]` is the finite set of `%pc` values block `b` may write (`{END}` when `b` terminates). + """ + root_out = [] + stack = [[collections.deque(tree), root_out, {entry_pc}, None]] + while stack: + frame = stack[-1] + q, dst, cur_pc, tag = frame + if not q: + if len(stack) > 1 and tag[0] == "guard" and len(cur_pc) == 1: + nxt_g = next(iter(cur_pc)) + skip_pc = tag[3] + parent_q = stack[-2][0] + if parent_q and parent_q[0][0] == "guard" and parent_q[0][1] == nxt_g and nxt_g not in skip_pc: + for child in reversed(parent_q.popleft()[2]): + q.appendleft(child) + continue + stack.pop() + if not stack: + break + parent = stack[-1] + if tag[0] == "guard": + _, g, child_dst, skip_pc = tag + parent[1].append(("guard", g, child_dst)) + parent[2] = skip_pc | cur_pc + else: + _, h, child_dst = tag + parent[1].append(("loop", h, child_dst)) + parent[2] = cur_pc - {h} + continue + it = q.popleft() + kind = it[0] + if kind == "block": + b = it[1] + dst.append(it) + frame[2] = set(out_pcs[b]) + elif kind == "guard": + g, gbody = it[1], it[2] + if cur_pc == {g}: + for child in reversed(gbody): + q.appendleft(child) + else: + child_dst = [] + skip_pc = set(cur_pc) + skip_pc.discard(g) + stack.append([collections.deque(gbody), child_dst, {g}, ("guard", g, child_dst, skip_pc)]) + else: + h, lbody = it[1], it[2] + child_dst = [] + stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)]) + return root_out diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index bb14c3d097..1e5e50f7c9 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -18342,6 +18342,8 @@ def capped_tree(succ): tree = cfg_structure.structure(succ) if STRUCTURED else None if tree is None: return None, None + out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))} + tree = cfg_structure.unwrap_known_pc_guards(tree, out_pcs) nesting = cfg_structure.depth(tree) if MAX_STRUCTURED_DEPTH and nesting > MAX_STRUCTURED_DEPTH: return None, nesting # too deep to validate cheaply: use the flat form diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index d6e1ad7d5b..d41f5575cb 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1105,70 +1105,8 @@ def _drop_tree_block(tree, b): def _unwrap_known_pc_guards(tree, out_pcs, entry_pc=0): - """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths. - - In `cfg_structure.structure`, every post-dominating join block `g` after a conditional diamond or loop is - still wrapped in `("guard", g, ...)`. Because `%pc` is a Function-scope variable in SPIR-V, LLVM/NVVM's - `SROA`/`Mem2Reg` promotes `%pc` at the same time as `%vgpr[0..255]` and `%sgpr[0..127]`, before `%pc == g` - can be constant-folded, forcing ~384 redundant Phi nodes at every spine guard merge block (and preventing - early block merging across convergent `OpControlBarrier`s). - - Tracks the exact finite set `cur_pc` of values `%pc` can hold before each item in `tree`: - - `("block", b)` overwrites `%pc` with `out_pcs[b]`. - - `("guard", g, gbody)`: if `cur_pc == {g}`, `%pc == g` is tautologically true on every path reaching - this item, so the guard unwraps in place; otherwise `gbody` is processed starting from `{g}` and its - exit `%pc` set merges with the skip path `cur_pc - {g}`. - - `("loop", h, lbody)`: `lbody` is processed starting from `cur_pc | {h}`; exiting the loop proves - `%pc != h`, leaving `pc_after_lbody - {h}`. - """ - root_out = [] - stack = [[collections.deque(tree), root_out, {entry_pc}, None]] - while stack: - frame = stack[-1] - q, dst, cur_pc, tag = frame - if not q: - if len(stack) > 1 and tag[0] == "guard" and len(cur_pc) == 1: - nxt_g = next(iter(cur_pc)) - skip_pc = tag[3] - parent_q = stack[-2][0] - if parent_q and parent_q[0][0] == "guard" and parent_q[0][1] == nxt_g and nxt_g not in skip_pc: - for child in reversed(parent_q.popleft()[2]): - q.appendleft(child) - continue - stack.pop() - if not stack: - break - parent = stack[-1] - if tag[0] == "guard": - _, g, child_dst, skip_pc = tag - parent[1].append(("guard", g, child_dst)) - parent[2] = skip_pc | cur_pc - else: - _, h, child_dst = tag - parent[1].append(("loop", h, child_dst)) - parent[2] = cur_pc - {h} - continue - it = q.popleft() - kind = it[0] - if kind == "block": - b = it[1] - dst.append(it) - frame[2] = set(out_pcs[b]) - elif kind == "guard": - g, gbody = it[1], it[2] - if cur_pc == {g}: - for child in reversed(gbody): - q.appendleft(child) - else: - child_dst = [] - skip_pc = set(cur_pc) - skip_pc.discard(g) - stack.append([collections.deque(gbody), child_dst, {g}, ("guard", g, child_dst, skip_pc)]) - else: - h, lbody = it[1], it[2] - child_dst = [] - stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)]) - return root_out + """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths.""" + return cfg_structure.unwrap_known_pc_guards(tree, out_pcs, entry_pc=entry_pc) def _region_has_cycle(region, succ): From 53ef382d7097290ecb1387f2400eaa7d134585b6 Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:36:04 +0200 Subject: [PATCH 2/4] cfg_structure: document why loop entry keeps cur_pc | {h} in unwrap_known_pc_guards Co-Authored-By: Gemini 4 Neon --- tools/cfg_structure.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py index 36eacf7f4f..68522ec8be 100644 --- a/tools/cfg_structure.py +++ b/tools/cfg_structure.py @@ -406,5 +406,7 @@ def unwrap_known_pc_guards(tree, out_pcs, entry_pc=0): else: h, lbody = it[1], it[2] child_dst = [] + # In a structure() tree lbody[0] is always ("block", h), which overwrites cur_pc with out_pcs[h]; + # keep cur_pc | {h} defensively so back-edge iterations stay sound even on non-structure() trees. stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)]) return root_out From 8e5cf5aef1942811bc6e377077b8dc8f388ff8fc Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:56:36 +0200 Subject: [PATCH 3/4] fix(rdna2spirv): include END in out_pcs for trailing conditional branches A conditional branch in the last basic block (no fallthrough block, so len(raw_edges[b]) == 1) emits OpSelect(%cond, tgt, len(blocks)) and can leave %pc at either tgt or cfg_structure.END. Compute exact per-block out_pcs in rdna2spirv._block_out_pcs (matching wave64_emulate_opt), pass it through capped_tree() into both cfg_structure.structure() (so single-target fall-off-the-end blocks also keep their dominated target guard) and unwrap_known_pc_guards(), and pass compact_out_pcs into cfg_structure.structure() in wave64_emulate_opt. Add unit and semantic regression tests covering both the loop back-edge repro reported in review and the non-loop dominated-target variant. Co-Authored-By: Gemini 4 Neon --- tests/semantic/test_structured_pc_unwrap.py | 137 ++++++++++++++++++++ tests/test_cfg_structure.py | 19 ++- tools/cfg_structure.py | 5 +- tools/rdna2spirv.py | 30 ++++- tools/wave64_emulate_opt.py | 17 ++- 5 files changed, 191 insertions(+), 17 deletions(-) create mode 100644 tests/semantic/test_structured_pc_unwrap.py diff --git a/tests/semantic/test_structured_pc_unwrap.py b/tests/semantic/test_structured_pc_unwrap.py new file mode 100644 index 0000000000..fc6eb90076 --- /dev/null +++ b/tests/semantic/test_structured_pc_unwrap.py @@ -0,0 +1,137 @@ +"""Semantic regression tests for structured %pc guard unwrapping (SHADER-STRUCTURED-PC-UNWRAP). + +Pure Python stdlib only (no llvm-mc, spirv-val, GPU, or game data). Verifies end-to-end translation +and execution of synthetic hand-written RDNA2 compute shaders where the last basic block ends in a +conditional branch with no trailing s_endpgm (fallthrough writes %pc = len(blocks) = END): + + 1. Loop whose back-edge is a conditional branch at the very end of the shader (succ = [[2, 1], [], [0]], + out_pcs[2] = {0, END}): exiting the loop leaves %pc in {1, END}, so guard 1 must stay and a + not-taken back-edge must terminate without executing block 1. + 2. Non-loop conditional branch at the very end of the shader whose single explicit target is + immediately dominated by it (succ = [[2], [], [1]], out_pcs[2] = {1, END}): both native + structured control flow and --wave64-emulate structured control flow must keep guard 1. + 3. Single-arm if-then join (0 -> {2, 1}, 1 -> {2}, 2 -> []) with s_barrier in block 2: block 2 + unwraps to top level so wave32 compute does not falsely fall back to barrier rounds. +""" +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +for _p in (HERE, TOOLS_DIR): + if _p not in sys.path: + sys.path.insert(0, _p) + +import rdna2spirv # noqa: E402 +from test_loop_ballot_barrier import VSHARP, _translate_cs, run_compute_workgroup # noqa: E402 + + +class StructuredPcUnwrapSemanticTest(unittest.TestCase): + def test_loop_last_block_cbranch_falloff_keeps_exit_guard(self): + """Loop back-edge in the last block with no s_endpgm after it: falling off the end must NOT run block 1.""" + prog = [ + "head:", + "s_cmp_eq_u32 s4, 0", + "s_cbranch_scc1 tail", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x1111", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_endpgm", + "tail:", + "s_mov_b32 s4, 1", + "s_cmp_eq_u32 s5, 1", + "s_cbranch_scc1 head", + ] + spv_struct, gen_struct = _translate_cs("cs_cbranch_falloff_loop", prog, threads=32, structured=True) + spv_disp, gen_disp = _translate_cs("cs_cbranch_falloff_loop_disp", prog, threads=32, structured=False) + self.assertEqual(gen_struct.control_flow, "structured") + self.assertEqual(gen_disp.control_flow, "dispatch loop") + self.assertEqual(gen_struct.succ, [[2, 1], [], [0]]) + self.assertEqual(gen_struct.out_pcs[2], frozenset({0, -1})) + tree, _ = rdna2spirv.capped_tree(gen_struct.succ, gen_struct.out_pcs) + self.assertEqual(tree, [ + ("loop", 0, [("block", 0), ("guard", 2, [("block", 2)])]), + ("guard", 1, [("block", 1)]), + ]) + + cases = [ + (1, 0, [0x1111] * 32), # B0 falls into B1 -> stores 0x1111 + (0, 1, [0x1111] * 32), # B0 -> B2 (s4=1, back-edge taken) -> B0 -> B1 -> stores 0x1111 + (0, 0, [0] * 32), # B0 -> B2 (back-edge not taken -> falls off end) -> no store + ] + for s4, s5, want in cases: + with self.subTest(s4=s4, s5=s5): + pc = VSHARP + [s4, s5] + mem_s = run_compute_workgroup(spv_struct, 32, 32, push_constants=pc) + mem_d = run_compute_workgroup(spv_disp, 32, 32, push_constants=pc) + got_s = [mem_s.get(4 * t, 0) for t in range(32)] + got_d = [mem_d.get(4 * t, 0) for t in range(32)] + self.assertEqual(got_d, want) + self.assertEqual(got_s, want) + + def test_nonloop_last_block_cbranch_falloff_keeps_dominated_target_guard(self): + """Last block ending in s_cbranch_scc1 to its single dominated target (no s_endpgm) must keep its guard.""" + prog = [ + "s_branch tail", + "do_store:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x2222", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_endpgm", + "tail:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 do_store", + ] + for mode, threads, sg_sz, emulate in ( + ("w32_structured", 32, 32, False), + ("w64_emulate", 64, 32, True), + ): + # Include a 64-bit exec op in the wave64 case so rdna2spirv classifies the shader as wave64 + # and exercises wave64_emulate_opt.plan_structured_emulation(). + mode_prog = (["s_mov_b64 s[10:11], exec"] + prog) if emulate else prog + spv, gen = _translate_cs(f"cs_cbranch_falloff_{mode}", mode_prog, threads=threads, emulate=emulate) + if emulate: + self.assertEqual(gen.control_flow, "emulated wave64 structured") + else: + self.assertEqual(gen.control_flow, "structured") + tree, _ = rdna2spirv.capped_tree(gen.succ, gen.out_pcs) + self.assertEqual(tree, [("block", 0), ("block", 2), ("guard", 1, [("block", 1)])]) + for s4, want_val in ((1, 0x2222), (0, 0)): + with self.subTest(mode=mode, s4=s4): + mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(threads)], [want_val] * threads) + + def test_postdominating_join_barrier_unwraps_to_top_level(self): + """A post-dominating merge block after a single-arm branch unwraps to top level (no false barrier rounds).""" + prog = [ + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 1", + "s_cmp_eq_u32 s4, 0", + "s_cbranch_scc1 join", + "v_mov_b32_e32 v1, 2", + "join:", + "ds_write_b32 v2, v1", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "ds_read_b32 v3, v2", + "s_waitcnt lgkmcnt(0)", + "buffer_store_dword v3, v2, s[0:3], 0 offen", + "s_endpgm", + ] + spv, gen = _translate_cs("cs_join_barrier_unwrap", prog, threads=64, lds_bytes=256, emulate=False) + self.assertFalse(gen.bar_rounds) + self.assertEqual(gen.control_flow, "structured") + tree, _ = rdna2spirv.capped_tree(gen.succ, gen.out_pcs) + self.assertEqual(tree, [("block", 0), ("guard", 1, [("block", 1)]), ("block", 2)]) + for s4, want_val in ((0, 1), (1, 2)): + with self.subTest(s4=s4): + mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [want_val] * 64) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cfg_structure.py b/tests/test_cfg_structure.py index f6caa5bd80..761bb21ee6 100644 --- a/tests/test_cfg_structure.py +++ b/tests/test_cfg_structure.py @@ -255,10 +255,11 @@ def test_deep_sequential_chains_stay_flat_and_iterative(): def test_unwrap_known_pc_guards(): - def unwrap(succ): - tree = S.structure(succ) + def unwrap(succ, out_pcs=None): + if out_pcs is None: + out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} + tree = S.structure(succ, out_pcs=out_pcs) assert tree is not None - out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} return S.unwrap_known_pc_guards(tree, out_pcs) # Single-arm if-then (ms_wave_info_s3 shape: 0 -> {2, 1}, 1 -> {2}, 2 -> []): join block 2 unwraps to top level. @@ -270,6 +271,18 @@ def unwrap(succ): assert unwrap([[0, 1], []]) == [("loop", 0, [("block", 0)]), ("block", 1)] # Early exit in arm 1 (0 -> {1, 2}, 1 -> [], 2 -> []): both arms MUST remain guarded (pc may be END). assert unwrap([[1, 2], [], []]) == [("block", 0), ("guard", 2, [("block", 2)]), ("guard", 1, [("block", 1)])] + # Conditional branch in the last block with no s_endpgm after it (fallthrough writes END): + # loop body block 2 has succ [0] but out_pcs {0, END}, so exiting loop 0 leaves pc in {1, END}; + # guard 1 MUST stay so falling off the end does not execute block 1. + assert unwrap([[2, 1], [], [0]], out_pcs={0: {2, 1}, 1: {S.END}, 2: {0, S.END}}) == [ + ("loop", 0, [("block", 0), ("guard", 2, [("block", 2)])]), + ("guard", 1, [("block", 1)]), + ] + # Non-loop conditional branch falling off the end whose single explicit target is immediately dominated by it: + # block 2 has succ [1] and out_pcs {1, END}, so structure() and unwrap MUST both keep guard 1. + assert unwrap([[2], [], [1]], out_pcs={0: {2}, 1: {S.END}, 2: {1, S.END}}) == [ + ("block", 0), ("block", 2), ("guard", 1, [("block", 1)]), + ] if __name__ == "__main__": diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py index 68522ec8be..9b7b412127 100644 --- a/tools/cfg_structure.py +++ b/tools/cfg_structure.py @@ -80,7 +80,7 @@ def _dominators(rpo, preds): return idom, pos -def structure(succ): +def structure(succ, out_pcs=None): rpo, back, preds = _order(succ) idom, pos = _dominators(rpo, preds) @@ -158,7 +158,8 @@ def member(x, region): out_list.append(("loop", x, lbody)) else: out_list.append(("block", x)) - if kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]]: + if (kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]] + and (out_pcs is None or set(out_pcs[x]) == {below[0][1]})): stack.append(("emit", out_list, parent_list, below[0], depth)) else: hoist = (parent_list is not None and below diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 1e5e50f7c9..202a95c37f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -398,6 +398,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): # single defining plain v_mov of it); valid I/J sources (SHADER-177) self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line self.succ = [] # per basic block: the blocks it can go to next (none = the program ends there) + self.out_pcs = None # per basic block: exact set of %pc values written (including cfg_structure.END) self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it self.tbuffer_norm_fns: dict[int, list[str]] = {} # one exact quotient per used magnitude width self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it @@ -16276,7 +16277,7 @@ def assemble(gen): helpers.extend(function) for function in gen.x_round_fns.values(): helpers.extend(function) - tree, nesting = (capped_tree(gen.succ) if gen.blocks and not gen.emulate and not gen.bar_rounds + tree, nesting = (capped_tree(gen.succ, gen.out_pcs) if gen.blocks and not gen.emulate and not gen.bar_rounds else (None, None)) if nesting is not None: gen.nesting = nesting @@ -18055,6 +18056,7 @@ def target(ins): g.cu(n) raw_edges = split_edges succ = [list(dict.fromkeys(e)) for e in raw_edges] + g.out_pcs = _block_out_pcs(blocks, raw_edges, succ) g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ) g.park_masks((blocks, succ)) halves_analysis(g, blocks, succ) @@ -18334,15 +18336,33 @@ def finish_module(g): return spirv_loop_guard.add_guards(text, LOOP_LIMIT) -def capped_tree(succ): +def _block_out_pcs(blocks, raw_edges, succ): + """Possible `%pc` values each basic block can store (`cfg_structure.END` when the block can end the shader). + A conditional branch with no fallthrough block (`len(raw_edges[b]) == 1`, i.e. the last block or a split clone + of it) emits `OpSelect %uint cond tgt len(blocks)` and therefore writes either `tgt` or `END`.""" + out_pcs = {} + for b, blk in enumerate(blocks): + pcs = set(succ[b]) + if not pcs: + pcs.add(cfg_structure.END) + elif len(raw_edges[b]) == 1: + last = next((i for i in blk if base_op(i["op"]) == "s_endpgm" or base_op(i["op"]) in BRANCHES), None) + if last is not None and base_op(last["op"]) in BRANCHES and base_op(last["op"]) != "s_branch": + pcs.add(cfg_structure.END) + out_pcs[b] = frozenset(pcs) + return out_pcs + + +def capped_tree(succ, out_pcs=None): """(tree, nesting): the structured tree for `succ` and its depth, or (None, None) under --dispatch-loop or when cfg_structure can't structure it; tree is None (nesting still the measured depth) when it nests deeper than MAX_STRUCTURED_DEPTH. assemble() emits exactly this tree, and needs_barrier_rounds() decides from the same one (SHADER-427 review): a barrier in a tree that falls back to the dispatch loop isn't at a structured top level.""" - tree = cfg_structure.structure(succ) if STRUCTURED else None + if out_pcs is None: + out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))} + tree = cfg_structure.structure(succ, out_pcs=out_pcs) if STRUCTURED else None if tree is None: return None, None - out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))} tree = cfg_structure.unwrap_known_pc_guards(tree, out_pcs) nesting = cfg_structure.depth(tree) if MAX_STRUCTURED_DEPTH and nesting > MAX_STRUCTURED_DEPTH: @@ -18370,7 +18390,7 @@ def needs_barrier_rounds(g, blocks, succ): break if not with_barrier: return False - tree, _ = capped_tree(succ) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop + tree, _ = capped_tree(succ, g.out_pcs) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop top = {it[1] for it in tree if it[0] == "block"} if tree is not None else set() return not with_barrier <= top diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index d41f5575cb..4b52127210 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1549,23 +1549,26 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb eff_succ[b] = nxt eff_succ_compact.append([eff_idx[s] for s in nxt]) - compact_tree = cfg_structure.structure(eff_succ_compact) - if compact_tree is None: - return None - tree = _map_tree_ids(compact_tree, eff_blocks) - out_pcs = {} for b in eff_blocks: tail = chain_of[b][-1] s = set(eff_succ[b]) if not s: - s.add(-1) + s.add(cfg_structure.END) elif tail not in folds and len(raw_edges[tail]) == 1: last = active_blocks[tail][-1] if active_blocks[tail] else None op = base_op(last["op"]) if last is not None else None if op in BRANCHES and op != "s_branch": - s.add(-1) + s.add(cfg_structure.END) out_pcs[b] = frozenset(s) + compact_out_pcs = { + eff_idx[b]: frozenset(eff_idx[p] if p != cfg_structure.END else cfg_structure.END for p in pcs) + for b, pcs in out_pcs.items() + } + compact_tree = cfg_structure.structure(eff_succ_compact, out_pcs=compact_out_pcs) + if compact_tree is None: + return None + tree = _map_tree_ids(compact_tree, eff_blocks) tree = _unwrap_known_pc_guards(tree, out_pcs, eff_blocks[0]) # Precompute per-superblock instruction summaries (for dirty transfer, sync-free check, s_barrier, s_endpgm). From 33431d6fe5482fdc87edb212f325f37386b4937a Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:06:01 +0200 Subject: [PATCH 4/4] fix(wave64_emulate_opt): refuse exec-fold regions containing a trailing conditional branch A block with len(raw_edges[u]) == 1 ending in a conditional branch (no fallthrough block, so falling through writes %pc = len(blocks) = END) cannot safely sit inside a folded s_cbranch_execz/nz region whose exit unconditionally sets %pc = skip. Reject such blocks during the region walk in find_local_exec_folds (matching the existing ot succ[u] check) and add semantic regression tests covering both s_cbranch_scc1 X and s_cbranch_scc1 skip in structured and --dispatch-loop --wave64-emulate modes. Co-Authored-By: Gemini 4 Neon --- tests/semantic/test_structured_pc_unwrap.py | 49 +++++++++++++++++++++ tools/wave64_emulate_opt.py | 3 +- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/tests/semantic/test_structured_pc_unwrap.py b/tests/semantic/test_structured_pc_unwrap.py index fc6eb90076..d8e42e6072 100644 --- a/tests/semantic/test_structured_pc_unwrap.py +++ b/tests/semantic/test_structured_pc_unwrap.py @@ -132,6 +132,55 @@ def test_postdominating_join_barrier_unwraps_to_top_level(self): mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4]) self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [want_val] * 64) + def test_wave64_emulate_exec_fold_refuses_last_block_cbranch_falloff(self): + """A wave64 s_cbranch_execz region containing a trailing conditional branch (no s_endpgm) must NOT be + folded into a region that unconditionally continues at `skip`: falling off the end must terminate.""" + prog_to_x = [ + "s_mov_b64 s[10:11], exec", + "s_cbranch_execz skip", + "s_branch last", + "X:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x3333", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_branch skip", + "skip:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x4444", + "buffer_store_dword v1, v2, s[0:3], 0 offen offset:256", + "s_endpgm", + "last:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 X", + ] + prog_to_skip = [ + "s_mov_b64 s[10:11], exec", + "s_cbranch_execz skip", + "s_branch last", + "skip:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x4444", + "buffer_store_dword v1, v2, s[0:3], 0 offen offset:256", + "s_endpgm", + "last:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 skip", + ] + for name, prog, want_taken_x, want_taken_skip in ( + ("branch_to_x", prog_to_x, 0x3333, 0x4444), + ("branch_to_skip", prog_to_skip, 0, 0x4444), + ): + for structured in (True, False): + spv, _ = _translate_cs( + f"cs_fold_falloff_{name}_{int(structured)}", + prog, threads=64, emulate=True, structured=structured, + ) + for s4, exp_x, exp_skip in ((0, 0, 0), (1, want_taken_x, want_taken_skip)): + with self.subTest(case=name, structured=structured, s4=s4): + mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [exp_x] * 64) + self.assertEqual([mem.get(256 + 4 * t, 0) for t in range(64)], [exp_skip] * 64) + if __name__ == "__main__": unittest.main() diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index 4b52127210..1ff464fd15 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1295,7 +1295,8 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr u = work.pop() if u == skip or u in region: continue - if u == b or u == 0 or not succ[u] or not blk_info[u][0]: + if (u == b or u == 0 or not succ[u] or not blk_info[u][0] + or (len(raw_edges[u]) == 1 and terms[u][0] == "br" and terms[u][1] != "s_branch")): ok = False break region.add(u)