perf(shader): cut per-instruction allocations and map lookups in IR #404

Closed
github-bot wants to merge 8 commits from github-bot/gh-404 into main AGit
Owner

@⁠tommiehansen on GitHub · 2026-12-04 00:38 UTC · original
tommiehansen:perf/ir-build-unspill-alloc → main · +495 −84 · 2 files · 8 commits · closed without merging

Latest CFG correctness verification

Exact-head audit at 481ed08: debug and release shader suites passed; deliberately omitting fallthrough remapping was detected by the new regression test. The mixed-corpus performance measurements in #547 apply to that separate split, not this combined revision.


What this does

cut per-instruction allocations and map lookups in IR.

Checks

  • N/A: intended behavior-preserving compiler optimization, not new runtime behavior; prior nine supported benchmark digests identical.
  • N/A: no new or changed runtime switch.
  • No unrelated cleanup: Single ir.rs optimization subject.
  • A test must exercise the change: 299 tests previously passed; establish targeted fail-before/performance sensitivity on current head.
  • Queue checked on 2026-12-04: #399/#402 optimize other compiler stages; #468 changes shader structure, verify integration.
  • Run cargo xtask policy on the final revision; no new game assets or build output intended.

Verified

Existing measurements and commands are retained below at their original revisions. No fresh compile, policy or hardware test is claimed by this metadata review.

Cost

CPU translation savings in original table; scratch memory changes, no GPU/FPS claim.


Detailed implementation and historical validation

Summary

Reduces per-instruction heap allocations, binary searches, and SipHash map/set overhead in crates/victory-shader/src/ir.rs, preserves unchanged IR/DXIL output on valid reachable shader programs (equivalence = identical across all shaders/* and descriptors/* benchmarks), and explicitly resolves unreachable-block stale SSA values after CFG rewrites:

  • Reusable effect buffers & O(1) RegSet dedup (effects_into): replaces per-instruction r/w/seen Vec allocations and linear scans in effects() across ir::build() and unspill() with caller-reused scratch buffers and direct bitmask membership tracking via RegSet.
  • Linear block cursor & peekable next-offset iteration in ir::build(): replaces the next_offsets lookup Vec and binary_search calls with a monotonic block index cursor, peekable leader iteration, and O(1) fallthrough lookup (leaders.get(b + 1)).
  • Empty-work fast-exits with diagnostics preserved: skips unspill() setup when VICTORY_WHY_UNSPILL is unset and no v_writelane_b32/v_readlane_b32 instructions exist (retaining full instruction scanning and WHY-UNSPILL diagnostic logging when VICTORY_WHY_UNSPILL is set), and skips fixed-point iteration in remove_trivial_phis_steps() when all blocks have empty phis.
  • Unreachable-block pruning before SSA renaming (prune_unreachable): after link() / CFG edge edits (build, thread_edges, without_early_outs, without_skips) and as a guard at entry to rename(), prune_unreachable runs reverse_postorder(): when all blocks are reachable it avoids remapping-table allocations (reverse_postorder() itself still allocates its traversal buffers); otherwise it retains only reachable blocks in original block order, remaps Exit::Jump and Exit::Branch targets (leaving Exit::End / Exit::Indirect unchanged), and recomputes link() / reverse_postorder() before split_irreducible, liveness, and SSA renaming. Intentional correctness fix: CFG passes (without_skips, without_early_outs, thread_edges) that leave unreachable blocks previously retained unvisited stale SSA values (which tripped remove_trivial_phis_steps() on main or remained dangling under the no-phi fast exit); unreachable blocks are now removed cleanly rather than preserving invalid unreachable SSA programs.
  • Flat Value-indexed tables in without_skips() and copy_through_phis(): replaces SipHash HashMap<Value, Value> and HashSet<Value> with dense Vec<Value> and Vec<bool> tables indexed by Value.
  • Tests: adds without_skips_flat_tables_and_fallthrough_leader_blocks, prune_unreachable_drops_dead_preds_and_stale_ssa_with_and_without_phis, without_early_outs_prunes_unreachable_early_exit, without_skips_prunes_unreachable_dead_branch_with_stale_values, and thread_edges_prunes_orphaned_join_and_keeps_valid_ssa.

Benchmark Results (CPU-only, Apple M5 macOS ARM64)

Paired A/B/B/A comparison (protocol v1, A-B-B-A-A-B-B-A-A-B-B-A-A-B-B-A, 4 paired blocks / 8 runs per side) via tools/benchmark-suite comparing the branch's actual parent 1152b9c vs 3b07683 (perf/ir-build-unspill-alloc):

Benchmark 1152b9c (ms) 3b07683 (ms) Change p-value 95% CI Equivalence Classification
shaders/structurise_guard_runs 9.430 5.842 −39.12% 0.0001 [−42.49%, −35.55%] identical Improvement
descriptors/shader_resource_tracking 1.138 0.777 −32.20% 0.0002 [−35.56%, −28.65%] identical Improvement
shaders/guest_load_clusters_extended 5.196 4.977 −4.49% 0.0076 [−6.63%, −2.29%] identical Improvement
shaders/guest_load_clusters 6.979 6.726 −4.16% 0.0088 [−6.25%, −2.02%] identical Improvement
shaders/uniform_guest_loads 1.453 1.406 −3.73% 0.0156 [−6.05%, −1.36%] identical Improvement
shaders/uniform_smem_and_wide_loads 4.173 4.042 −3.66% 0.0179 [−6.05%, −1.21%] identical Improvement
shaders/translate_corpus 2.636 2.480 −4.42% 0.1102 [−10.35%, +1.90%] identical Inconclusive
descriptors/copy_span_index 0.022 0.022 −0.26% 0.1977 [−0.76%, +0.24%] identical No significant difference
shaders/node_probe_emit 1.083 1.085 +0.14% 0.3993 [−0.32%, +0.61%] identical No significant difference
shaders/gpu_execute, descriptors/d3d12x_heap_and_copy - - - - - n/a Unsupported in --cpu-only

All 9 supported benchmarks produce 100% identical equivalence digests with zero regressions.

Validation & Reproducible Commands

  • Unit & regression tests (victory-shader): 299 passed, 0 failed, 2 ignored (on macOS; Windows D3D12 emit tests are Windows-only):
    cargo test --offline -p victory-shader
    
  • Benchmark comparison (tools/benchmark-suite):
    ./tools/benchmark-suite/run compare 1152b9c 3b07683 --offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors
    

Known Limitations

  • Paired timing numbers were measured in CPU-only mode on Apple M5 (macOS ARM64); Windows CI and physical AMD GPU gameplay/runtime timing require external validation.
  • Only crates/victory-shader/src/ir.rs is modified; orthogonal passes in emit/bitcode/opt.rs (#399) and structure.rs (#402) remain in separate PRs.

Follow-up review fixes (2026-12-04)

Head: f1dd4c8d147091f2f93cd7488068568774d3ec3b.

Preserve the old deep-mode behavior for a NONE phi and replace debug-only remapped-target checks with assertions in release as well. The requested independent unreachable-CFG bug-fix split and redundant traversal analysis remain open.

Pinned CI audit started for this revision. Final-head compilation, tests and policy results are pending; historical measurements have not been relabelled.

Queue refresh — 2026-12-05

Merged upstream main b581f7e0a8086158953a64068ba29305d5450d68 into the existing branch without rewriting history. New head: a39ca27f3947e162653747d7564762811381e4c2. Review split candidates staged independently: CFG fix 31e7e781fbcf5b3a19620ac0ebd14b68a478169a, performance-only 22ffc9974358305a9670b2ccc3c93e428fa09033. The CFG candidate reuses traversal order for SSA renaming. Original PR remains intact pending validation.

Fresh pinned CI audit is the verification record for this revision; previous tests apply to the previously stated heads. #528 remains a separate policy prerequisite, not a runtime dependency. No new gameplay or GPU timing claim.

Review follow-up

The isolated CFG fix is now #546 (298 shader tests passed), and the allocation-only change is #547 (295 passed). Each suite ignored two tests. The audit’s inherited launcher documentation failure is tracked in #528. These two slices touch the same IR source and should be reconciled if both are selected.

Post-review follow-up — 2026-12-05

Head: 4e460da651c98c782e761c9d6ddff1837dec39f1.

Applied the same conservative build-loop restoration as #547 after Kal0s-design's mixed-corpus regression report; the CFG correctness fix remains, with TRANSLATOR_VERSION 21 as in #546. The version must be reconciled with main when landing. Rerun the mixed-corpus timing and exact-output comparison on this head; all historical timings are revision-bound.

Fresh pinned debug/release CI started. The isolated review alternatives remain #545–547; do not merge overlapping original and split changes blindly.

Targeted branch-remap regression

Head: 481ed08485a37514d3367cb2bcf7f8ed85a0331c. Added pruning_remaps_both_branch_targets_past_a_dead_block to cover the fallthrough-remap gap identified by Kal0s-design. The test verifies both targets, predecessor lists and reachability after pruning. Production code is unchanged in this commit. Debug/release and deliberate missing-remap negative control pending.

Standard CI raw-artifact follow-up (2026-12-05)

Synthetic CPU workload Base (ms) Candidate (ms) Paired time change
Guard-run structurisation 18.0085 12.1986 −32.17%
Corpus translation 5.1780 4.8457 −6.34%

Both output digests identical; structurisation 95% CI −32.25% to −32.08%. Overlaps the split #547; do not add savings. Four complete ABBA blocks, eight runs per arm. Independently checked all 16 raw checkpoint revisions, per-run sample concatenation, medians and digests against results.json. The Python review gate incorrectly interprets rounds=8 (runs per arm) as eight ABBA blocks; its automatic verdict remains inconclusive pending a harness fix. The CIs above, where stated, are the Rust report's per-workload estimates. Generic software Vulkan control passed with identical SPIR-V, not activation of this PR. No physical GPU or gameplay FPS claim. Pinned CI/artifacts.

Superseded: #546 and #547 merged; current upstream retains the CFG/IR changes and regression tests. Closing the original combined PR rather than reintroducing duplicate code.

**@⁠tommiehansen** on GitHub · 2026-12-04 00:38 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/404) `tommiehansen:perf/ir-build-unspill-alloc` → `main` · +495 −84 · 2 files · 8 commits · closed without merging ## Latest CFG correctness verification [Exact-head audit](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47503802058/job/145623466290) at `481ed08`: debug and release shader suites passed; deliberately omitting fallthrough remapping was detected by the new regression test. The mixed-corpus performance measurements in #547 apply to that separate split, not this combined revision. --- ## What this does cut per-instruction allocations and map lookups in IR. ## Checks - N/A: intended behavior-preserving compiler optimization, not new runtime behavior; prior nine supported benchmark digests identical. - N/A: no new or changed runtime switch. - [x] No unrelated cleanup: Single `ir.rs` optimization subject. - [ ] A test must exercise the change: 299 tests previously passed; establish targeted fail-before/performance sensitivity on current head. - [x] Queue checked on 2026-12-04: #399/#402 optimize other compiler stages; #468 changes shader structure, verify integration. - [ ] Run `cargo xtask policy` on the final revision; no new game assets or build output intended. ## Verified Existing measurements and commands are retained below at their original revisions. No fresh compile, policy or hardware test is claimed by this metadata review. ## Cost CPU translation savings in original table; scratch memory changes, no GPU/FPS claim. --- ## Detailed implementation and historical validation ## Summary Reduces per-instruction heap allocations, binary searches, and SipHash map/set overhead in `crates/victory-shader/src/ir.rs`, preserves unchanged IR/DXIL output on valid reachable shader programs (`equivalence = identical` across all `shaders/*` and `descriptors/*` benchmarks), and explicitly resolves unreachable-block stale SSA values after CFG rewrites: - **Reusable effect buffers & O(1) `RegSet` dedup (`effects_into`)**: replaces per-instruction `r`/`w`/`seen` `Vec` allocations and linear scans in `effects()` across `ir::build()` and `unspill()` with caller-reused scratch buffers and direct bitmask membership tracking via `RegSet`. - **Linear block cursor & `peekable` next-offset iteration in `ir::build()`**: replaces the `next_offsets` lookup `Vec` and `binary_search` calls with a monotonic block index cursor, `peekable` leader iteration, and O(1) fallthrough lookup (`leaders.get(b + 1)`). - **Empty-work fast-exits with diagnostics preserved**: skips `unspill()` setup when `VICTORY_WHY_UNSPILL` is unset and no `v_writelane_b32`/`v_readlane_b32` instructions exist (retaining full instruction scanning and `WHY-UNSPILL` diagnostic logging when `VICTORY_WHY_UNSPILL` is set), and skips fixed-point iteration in `remove_trivial_phis_steps()` when all blocks have empty `phis`. - **Unreachable-block pruning before SSA renaming (`prune_unreachable`)**: after `link()` / CFG edge edits (`build`, `thread_edges`, `without_early_outs`, `without_skips`) and as a guard at entry to `rename()`, `prune_unreachable` runs `reverse_postorder()`: when all blocks are reachable it avoids remapping-table allocations (`reverse_postorder()` itself still allocates its traversal buffers); otherwise it retains only reachable blocks in original block order, remaps `Exit::Jump` and `Exit::Branch` targets (leaving `Exit::End` / `Exit::Indirect` unchanged), and recomputes `link()` / `reverse_postorder()` before `split_irreducible`, liveness, and SSA renaming. **Intentional correctness fix:** CFG passes (`without_skips`, `without_early_outs`, `thread_edges`) that leave unreachable blocks previously retained unvisited stale SSA values (which tripped `remove_trivial_phis_steps()` on `main` or remained dangling under the no-phi fast exit); unreachable blocks are now removed cleanly rather than preserving invalid unreachable SSA programs. - **Flat `Value`-indexed tables in `without_skips()` and `copy_through_phis()`**: replaces SipHash `HashMap<Value, Value>` and `HashSet<Value>` with dense `Vec<Value>` and `Vec<bool>` tables indexed by `Value`. - **Tests**: adds `without_skips_flat_tables_and_fallthrough_leader_blocks`, `prune_unreachable_drops_dead_preds_and_stale_ssa_with_and_without_phis`, `without_early_outs_prunes_unreachable_early_exit`, `without_skips_prunes_unreachable_dead_branch_with_stale_values`, and `thread_edges_prunes_orphaned_join_and_keeps_valid_ssa`. ## Benchmark Results (CPU-only, Apple M5 macOS ARM64) Paired A/B/B/A comparison (`protocol v1`, `A-B-B-A-A-B-B-A-A-B-B-A-A-B-B-A`, 4 paired blocks / 8 runs per side) via `tools/benchmark-suite` comparing the branch's actual parent **`1152b9c`** vs **`3b07683`** (`perf/ir-build-unspill-alloc`): | Benchmark | `1152b9c` (ms) | `3b07683` (ms) | Change | p-value | 95% CI | Equivalence | Classification | |---|---:|---:|---:|---:|---|---|---| | `shaders/structurise_guard_runs` | 9.430 | 5.842 | **−39.12%** | 0.0001 | [−42.49%, −35.55%] | `identical` | Improvement | | `descriptors/shader_resource_tracking` | 1.138 | 0.777 | **−32.20%** | 0.0002 | [−35.56%, −28.65%] | `identical` | Improvement | | `shaders/guest_load_clusters_extended` | 5.196 | 4.977 | **−4.49%** | 0.0076 | [−6.63%, −2.29%] | `identical` | Improvement | | `shaders/guest_load_clusters` | 6.979 | 6.726 | **−4.16%** | 0.0088 | [−6.25%, −2.02%] | `identical` | Improvement | | `shaders/uniform_guest_loads` | 1.453 | 1.406 | **−3.73%** | 0.0156 | [−6.05%, −1.36%] | `identical` | Improvement | | `shaders/uniform_smem_and_wide_loads` | 4.173 | 4.042 | **−3.66%** | 0.0179 | [−6.05%, −1.21%] | `identical` | Improvement | | `shaders/translate_corpus` | 2.636 | 2.480 | −4.42% | 0.1102 | [−10.35%, +1.90%] | `identical` | Inconclusive | | `descriptors/copy_span_index` | 0.022 | 0.022 | −0.26% | 0.1977 | [−0.76%, +0.24%] | `identical` | No significant difference | | `shaders/node_probe_emit` | 1.083 | 1.085 | +0.14% | 0.3993 | [−0.32%, +0.61%] | `identical` | No significant difference | | `shaders/gpu_execute`, `descriptors/d3d12x_heap_and_copy` | - | - | - | - | - | n/a | Unsupported in `--cpu-only` | All 9 supported benchmarks produce **100% `identical`** equivalence digests with zero regressions. ## Validation & Reproducible Commands - Unit & regression tests (`victory-shader`): **299 passed, 0 failed, 2 ignored** (on macOS; Windows D3D12 emit tests are Windows-only): ```sh cargo test --offline -p victory-shader ``` - Benchmark comparison (`tools/benchmark-suite`): ```sh ./tools/benchmark-suite/run compare 1152b9c 3b07683 --offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors ``` ## Known Limitations - Paired timing numbers were measured in CPU-only mode on Apple M5 (macOS ARM64); Windows CI and physical AMD GPU gameplay/runtime timing require external validation. - Only `crates/victory-shader/src/ir.rs` is modified; orthogonal passes in `emit/bitcode/opt.rs` (#399) and `structure.rs` (#402) remain in separate PRs. ### Follow-up review fixes (2026-12-04) Head: `f1dd4c8d147091f2f93cd7488068568774d3ec3b`. Preserve the old deep-mode behavior for a NONE phi and replace debug-only remapped-target checks with assertions in release as well. The requested independent unreachable-CFG bug-fix split and redundant traversal analysis remain open. Pinned [CI audit](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47438443784) started for this revision. Final-head compilation, tests and policy results are pending; historical measurements have not been relabelled. ### Queue refresh — 2026-12-05 Merged upstream main `b581f7e0a8086158953a64068ba29305d5450d68` into the existing branch without rewriting history. New head: `a39ca27f3947e162653747d7564762811381e4c2`. Review split candidates staged independently: CFG fix `31e7e781fbcf5b3a19620ac0ebd14b68a478169a`, performance-only `22ffc9974358305a9670b2ccc3c93e428fa09033`. The CFG candidate reuses traversal order for SSA renaming. Original PR remains intact pending validation. [Fresh pinned CI audit](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47466412636) is the verification record for this revision; previous tests apply to the previously stated heads. #528 remains a separate policy prerequisite, not a runtime dependency. No new gameplay or GPU timing claim. ### Review follow-up The isolated CFG fix is now #546 (298 shader tests passed), and the allocation-only change is #547 (295 passed). Each suite ignored two tests. The audit’s inherited launcher documentation failure is tracked in #528. These two slices touch the same IR source and should be reconciled if both are selected. ### Post-review follow-up — 2026-12-05 Head: `4e460da651c98c782e761c9d6ddff1837dec39f1`. Applied the same conservative build-loop restoration as #547 after Kal0s-design's mixed-corpus regression report; the CFG correctness fix remains, with TRANSLATOR_VERSION 21 as in #546. The version must be reconciled with main when landing. Rerun the mixed-corpus timing and exact-output comparison on this head; all historical timings are revision-bound. [Fresh pinned debug/release CI](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47499397549) started. The isolated review alternatives remain #545–547; do not merge overlapping original and split changes blindly. ### Targeted branch-remap regression Head: `481ed08485a37514d3367cb2bcf7f8ed85a0331c`. Added `pruning_remaps_both_branch_targets_past_a_dead_block` to cover the fallthrough-remap gap identified by Kal0s-design. The test verifies both targets, predecessor lists and reachability after pruning. Production code is unchanged in this commit. [Debug/release and deliberate missing-remap negative control](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47503802058) pending. ### Standard CI raw-artifact follow-up (2026-12-05) | Synthetic CPU workload | Base (ms) | Candidate (ms) | Paired time change | |---|---:|---:|---:| | Guard-run structurisation | 18.0085 | 12.1986 | −32.17% | | Corpus translation | 5.1780 | 4.8457 | −6.34% | Both output digests identical; structurisation 95% CI −32.25% to −32.08%. Overlaps the split #547; do not add savings. Four complete ABBA blocks, eight runs per arm. Independently checked all 16 raw checkpoint revisions, per-run sample concatenation, medians and digests against results.json. The Python review gate incorrectly interprets `rounds=8` (runs per arm) as eight ABBA blocks; its automatic verdict remains inconclusive pending a harness fix. The CIs above, where stated, are the Rust report's per-workload estimates. Generic software Vulkan control passed with identical SPIR-V, not activation of this PR. No physical GPU or gameplay FPS claim. [Pinned CI/artifacts](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47512649200/job/145651188656). **Superseded:** #546 and #547 merged; current upstream retains the CFG/IR changes and regression tests. Closing the original combined PR rather than reintroducing duplicate code.
- Reuse read/write effect scratch buffers across instructions with O(1) RegSet dedup via effects_into
- Replace next_offsets Vec and binary search in ir::build with a monotonic block cursor and peekable iterator
- Fast-exit unspill when no lane spill instructions exist and remove_trivial_phis_steps when no phis exist
- Replace HashMap/HashSet in without_skips and phi copy propagation with flat Value-indexed Vec tables
- Add unit test covering flat copy tables and fallthrough leader block edges
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-04 00:39:55 +00:00
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-04 02:10 UTC · original

Tested this natively on Windows 11 (MSVC), PR head 3f52e6b against main 1152b9c.

cargo test -p victory-shader --lib gives 420 passed, 1 failed, 4 ignored on the PR and 419/1/4 on main. The one failure is emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flag, which fails the same way on main here (WARP compute_pipeline), so it's not from this change. Clippy on -p victory-shader --all-targets shows the same warnings on both sides, nothing new.

I also checked the "no change in IR" claim, with local-only hooks that I've since removed.

  • For effects I put the old effects() from main next to effects_into and compared the exact read and write lists, order included, with the scratch buffers left dirty between calls. That covered 90,260 instructions from every program the lib tests build, plus about 1.25M runs over 365k randomly generated instructions (1,184 different opcodes). There were 0 mismatches. I also looked for a VGPR that shows up twice in the writes but not in the reads, since that's the one place the new merge in build could push a read the old code wouldn't. It never happened.
  • I hashed the Debug output of every ir::build, without_skips, operand_reads and emit call made during the lib tests. That's 1,193 builds (1,041 distinct inputs), 23 without_skips, 425 operand_reads and 110 emits (71 distinct programs). All of them are identical between main and the PR. The only extra entries on the PR side come from the new test.
  • I also generated 200k programs (pool instructions, branches to real instruction starts, writelane/readlane pairs) and ran them through build, without_skips in both modes, and operand_reads. 199,971 gave the same result on both sides. The other 29 differ, main panics in without_skips and the PR returns Some.

The panic on main is an index out of bounds in find() in remove_trivial_phis_steps. When without_skips drops a skip, some blocks can become unreachable. rename never visits those blocks, so their reads keep value numbers from the old program, and main trips over them because it runs find() over every read. The new early return when no block has phis skips that pass, so the PR hands back a Program whose unreachable blocks read values that don't exist. No panic is arguably better, but it is a behaviour change, and it hides those dangling values from whatever looks at the program next. The same early return applies to every caller of rename (without_early_outs, thread_edges too). Nothing in the test corpus hits this, only the random programs. Either dropping unreachable blocks before rename or just mentioning it in the PR would be fine with me. 157 other random programs panic the same way on both sides, which is pre-existing and unrelated.

From reading the code, the rest looks equivalent. The block cursor and the leaders.get(b + 1) check only match the old binary search if every leader is an instruction start, and decode guarantees that by rejecting branches into the middle of an instruction. RegSet covers every Reg, so the dedup keeps exactly what the old seen scan kept. copy and live are never iterated, so the move to flat tables can't change any order. The flat tables only differ from the maps on NONE values, which rename's debug asserts already rule out. One small thing, the unspill early return also skips the VICTORY_WHY_UNSPILL "effects unknown" line, which only matters when debugging.

I didn't measure timing.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-04 02:10 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/404#issuecomment-7398659649) Tested this natively on Windows 11 (MSVC), PR head 3f52e6b against main 1152b9c. `cargo test -p victory-shader --lib` gives 420 passed, 1 failed, 4 ignored on the PR and 419/1/4 on main. The one failure is `emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flag`, which fails the same way on main here (WARP compute_pipeline), so it's not from this change. Clippy on `-p victory-shader --all-targets` shows the same warnings on both sides, nothing new. I also checked the "no change in IR" claim, with local-only hooks that I've since removed. - For effects I put the old `effects()` from main next to `effects_into` and compared the exact read and write lists, order included, with the scratch buffers left dirty between calls. That covered 90,260 instructions from every program the lib tests build, plus about 1.25M runs over 365k randomly generated instructions (1,184 different opcodes). There were 0 mismatches. I also looked for a VGPR that shows up twice in the writes but not in the reads, since that's the one place the new merge in `build` could push a read the old code wouldn't. It never happened. - I hashed the Debug output of every `ir::build`, `without_skips`, `operand_reads` and `emit` call made during the lib tests. That's 1,193 builds (1,041 distinct inputs), 23 without_skips, 425 operand_reads and 110 emits (71 distinct programs). All of them are identical between main and the PR. The only extra entries on the PR side come from the new test. - I also generated 200k programs (pool instructions, branches to real instruction starts, writelane/readlane pairs) and ran them through build, `without_skips` in both modes, and `operand_reads`. 199,971 gave the same result on both sides. The other 29 differ, main panics in `without_skips` and the PR returns `Some`. The panic on main is an index out of bounds in `find()` in `remove_trivial_phis_steps`. When `without_skips` drops a skip, some blocks can become unreachable. `rename` never visits those blocks, so their reads keep value numbers from the old program, and main trips over them because it runs `find()` over every read. The new early return when no block has phis skips that pass, so the PR hands back a Program whose unreachable blocks read values that don't exist. No panic is arguably better, but it is a behaviour change, and it hides those dangling values from whatever looks at the program next. The same early return applies to every caller of `rename` (without_early_outs, thread_edges too). Nothing in the test corpus hits this, only the random programs. Either dropping unreachable blocks before `rename` or just mentioning it in the PR would be fine with me. 157 other random programs panic the same way on both sides, which is pre-existing and unrelated. From reading the code, the rest looks equivalent. The block cursor and the `leaders.get(b + 1)` check only match the old binary search if every leader is an instruction start, and `decode` guarantees that by rejecting branches into the middle of an instruction. `RegSet` covers every `Reg`, so the dedup keeps exactly what the old `seen` scan kept. `copy` and `live` are never iterated, so the move to flat tables can't change any order. The flat tables only differ from the maps on `NONE` values, which rename's debug asserts already rule out. One small thing, the unspill early return also skips the `VICTORY_WHY_UNSPILL` "effects unknown" line, which only matters when debugging. I didn't measure timing. AI-assisted: yes
Author
Owner

@⁠tommiehansen on GitHub · 2026-12-04 11:57 UTC · original

Thanks @⁠Kal0s-design for catching the unreachable-block stale-SSA masking and the VICTORY_WHY_UNSPILL diagnostic edge case in fuzzing! Pushed commit 3b07683 resolving both and updated the PR description:

  1. Prune unreachable blocks instead of masking stale SSA values (prune_unreachable in crates/victory-shader/src/ir.rs):
    • Added prune_unreachable(&mut blocks) using reverse_postorder() (zero-allocation fast path when all blocks are reachable; otherwise builds an order-preserving remap, retains reachable blocks, updates Exit::Jump and both Exit::Branch targets leaving Exit::End / Exit::Indirect untouched, and calls link(blocks)).
    • Called right after link() and before split_irreducible() across build, thread_edges, without_early_outs, and without_skips, plus a reachability guard at entry to rename() before reverse_postorder() and liveness().
    • Keeps the no-phi early return in remove_trivial_phis_steps() safe without hiding dangling SSA reads in unreachable blocks (and explicitly documents this unreachable-block removal as an intentional correctness fix rather than claiming byte-identical output for previously invalid programs with dead blocks).
  2. Preserve VICTORY_WHY_UNSPILL diagnostics (unspill):
    • Restricted the no-v_writelane_b32/no-v_readlane_b32 fast exit to crate::envs::var_os("VICTORY_WHY_UNSPILL").is_none(), so setting VICTORY_WHY_UNSPILL preserves the full instruction scan and "effects unknown" diagnostic reporting.

Verification on 3b07683

  • Added 4 focused tests in crates/victory-shader/src/ir.rs: prune_unreachable_drops_dead_preds_and_stale_ssa_with_and_without_phis, without_early_outs_prunes_unreachable_early_exit, without_skips_prunes_unreachable_dead_branch_with_stale_values, and thread_edges_prunes_orphaned_join_and_keeps_valid_ssa (full cargo test --offline -p victory-shader: 299 passed; 0 failed; 2 ignored on macOS, valid shader corpus unchanged).
  • Standard paired benchmark (45591b0 vs 3b07683, Apple M5 CPU-only, 4 A/B/B/A blocks): shaders/structurise_guard_runs −37.36% (p < 0.0001), descriptors/shader_resource_tracking −29.76% (p < 0.0001), shaders/uniform_smem_and_wide_loads −2.81% (p = 0.0013), all 9 comparable workloads identical with zero regressions. (Syncing PROGRESS.md on #322 next.)
**@⁠tommiehansen** on GitHub · 2026-12-04 11:57 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/404#issuecomment-7410780427) Thanks @⁠Kal0s-design for catching the unreachable-block stale-SSA masking and the `VICTORY_WHY_UNSPILL` diagnostic edge case in fuzzing! Pushed commit [`3b07683`](https://github.com/tommiehansen/VIctory-xmem/commit/3b07683) resolving both and updated the PR description: 1. **Prune unreachable blocks instead of masking stale SSA values (`prune_unreachable` in `crates/victory-shader/src/ir.rs`):** - Added `prune_unreachable(&mut blocks)` using `reverse_postorder()` (zero-allocation fast path when all blocks are reachable; otherwise builds an order-preserving remap, retains reachable blocks, updates `Exit::Jump` and both `Exit::Branch` targets leaving `Exit::End` / `Exit::Indirect` untouched, and calls `link(blocks)`). - Called right after `link()` and before `split_irreducible()` across `build`, `thread_edges`, `without_early_outs`, and `without_skips`, plus a reachability guard at entry to `rename()` before `reverse_postorder()` and `liveness()`. - Keeps the no-phi early return in `remove_trivial_phis_steps()` safe without hiding dangling SSA reads in unreachable blocks (and explicitly documents this unreachable-block removal as an intentional correctness fix rather than claiming byte-identical output for previously invalid programs with dead blocks). 2. **Preserve `VICTORY_WHY_UNSPILL` diagnostics (`unspill`):** - Restricted the no-`v_writelane_b32`/no-`v_readlane_b32` fast exit to `crate::envs::var_os("VICTORY_WHY_UNSPILL").is_none()`, so setting `VICTORY_WHY_UNSPILL` preserves the full instruction scan and `"effects unknown"` diagnostic reporting. ### Verification on `3b07683` - **Added 4 focused tests in `crates/victory-shader/src/ir.rs`:** `prune_unreachable_drops_dead_preds_and_stale_ssa_with_and_without_phis`, `without_early_outs_prunes_unreachable_early_exit`, `without_skips_prunes_unreachable_dead_branch_with_stale_values`, and `thread_edges_prunes_orphaned_join_and_keeps_valid_ssa` (full `cargo test --offline -p victory-shader`: `299 passed; 0 failed; 2 ignored` on macOS, valid shader corpus unchanged). - **Standard paired benchmark (`45591b0` vs `3b07683`, Apple M5 CPU-only, 4 A/B/B/A blocks):** `shaders/structurise_guard_runs` **−37.36%** (`p < 0.0001`), `descriptors/shader_resource_tracking` **−29.76%** (`p < 0.0001`), `shaders/uniform_smem_and_wide_loads` **−2.81%** (`p = 0.0013`), all 9 comparable workloads `identical` with zero regressions. (Syncing `PROGRESS.md` on `#322` next.)
Author
Owner

@⁠Luxuride on GitHub · 2026-12-04 12:20 UTC · original

Land the two commits as two PRs — the second is a bug fix users would want today, and it should not be carrying a behaviour change while the PR is titled as a perf change.

The split matters because commit 2 changes generated IR for any input with unreachable blocks. The body's "equivalence = identical across all shaders/*" only means the corpus never had one; on main this is a latent panic (remove_trivial_phis_steps tripping over stale out-of-range values). That deserves its own PR and its own changelog line.

Three things in prune_unreachable/without_skips worth fixing as you split:

  1. crates/victory-shader/src/ir.rs:1358-1401 relies on debug_assert_ne!(remap[*t], usize::MAX). In release, a kept block pointing at a pruned one becomes Exit::Jump(usize::MAX) and the next blocks[t] panics far from the cause. Make it a hard expect, or filter_map the unknown targets.
  2. It runs from both build (ir.rs:252) and rename (ir.rs:714), and thread_edges/without_skips/without_early_outs prune, then split_irreducible, then rename prunes again — each call paying a reverse_postorder plus a full link() on the shader-compile hot path you are trying to shorten. The order.len() == blocks.len() fast path still pays for the traversal.
  3. without_skips' deep && phi.value != NONE && !live[...] (ir.rs:1140) is not the old deep && !live.contains(&phi.value): a phi whose value is NONE used to be skipped in deep mode and now is not. I could not construct such a phi from build, but the predicate changed rather than being preserved. A debug_assert_ne!(phi.value, NONE) at ir.rs:1131 would state the assumption.

The perf half (effects_into buffers, peekable leader walk, dense Value tables, the unspill early exit) is fine and worth having on its own.

42 behind; ir.rs untouched on main since the merge base. Reviewed at head 3b07683 (your local ref was stale at 3f52e6b).

**@⁠Luxuride** on GitHub · 2026-12-04 12:20 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/404#issuecomment-7411296940) Land the two commits as two PRs — the second is a bug fix users would want today, and it should not be carrying a behaviour change while the PR is titled as a perf change. The split matters because commit 2 changes generated IR for any input with unreachable blocks. The body's "equivalence = identical across all `shaders/*`" only means the corpus never had one; on `main` this is a latent panic (`remove_trivial_phis_steps` tripping over stale out-of-range values). That deserves its own PR and its own changelog line. Three things in `prune_unreachable`/`without_skips` worth fixing as you split: 1. `crates/victory-shader/src/ir.rs:1358-1401` relies on `debug_assert_ne!(remap[*t], usize::MAX)`. In release, a kept block pointing at a pruned one becomes `Exit::Jump(usize::MAX)` and the next `blocks[t]` panics far from the cause. Make it a hard `expect`, or `filter_map` the unknown targets. 2. It runs from both `build` (`ir.rs:252`) and `rename` (`ir.rs:714`), and `thread_edges`/`without_skips`/`without_early_outs` prune, then `split_irreducible`, then `rename` prunes again — each call paying a `reverse_postorder` plus a full `link()` on the shader-compile hot path you are trying to shorten. The `order.len() == blocks.len()` fast path still pays for the traversal. 3. `without_skips`' `deep && phi.value != NONE && !live[...]` (`ir.rs:1140`) is not the old `deep && !live.contains(&phi.value)`: a phi whose value is `NONE` used to be skipped in deep mode and now is not. I could not construct such a phi from `build`, but the predicate changed rather than being preserved. A `debug_assert_ne!(phi.value, NONE)` at `ir.rs:1131` would state the assumption. The perf half (`effects_into` buffers, `peekable` leader walk, dense `Value` tables, the `unspill` early exit) is fine and worth having on its own. 42 behind; `ir.rs` untouched on `main` since the merge base. Reviewed at head `3b07683` (your local ref was stale at `3f52e6b`).
Author
Owner

@⁠tommiehansen on GitHub · 2026-12-04 12:21 UTC · original

Updated the PR #404 benchmark table to isolate 3b07683 directly against its true parent 1152b9c (replacing the earlier 45591b0 comparison, which preceded 1152b9c by 14 commits) and clarified that prune_unreachable() avoids remapping allocations on the all-reachable fast path while reverse_postorder() still allocates its traversal buffers:

./tools/benchmark-suite/run compare 1152b9c 3b07683 --offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors
  • shaders/structurise_guard_runs: −39.12% (9.430 → 5.842 ms, p = 0.0001, 95% CI [−42.49%, −35.55%])
  • descriptors/shader_resource_tracking: −32.20% (1.138 → 0.777 ms, p = 0.0002, 95% CI [−35.56%, −28.65%])
  • shaders/guest_load_clusters_extended: −4.49% (5.196 → 4.977 ms, p = 0.0076)
  • shaders/guest_load_clusters: −4.16% (6.979 → 6.726 ms, p = 0.0088)
  • shaders/uniform_guest_loads: −3.73% (1.453 → 1.406 ms, p = 0.0156)
  • shaders/uniform_smem_and_wide_loads: −3.66% (4.173 → 4.042 ms, p = 0.0179)
  • All 9 comparable workloads reported identical digests with zero regressions.
**@⁠tommiehansen** on GitHub · 2026-12-04 12:21 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/404#issuecomment-7411340998) Updated the PR #404 benchmark table to isolate `3b07683` directly against its true parent **`1152b9c`** (replacing the earlier `45591b0` comparison, which preceded `1152b9c` by 14 commits) and clarified that `prune_unreachable()` avoids remapping allocations on the all-reachable fast path while `reverse_postorder()` still allocates its traversal buffers: ```sh ./tools/benchmark-suite/run compare 1152b9c 3b07683 --offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors ``` - `shaders/structurise_guard_runs`: **−39.12%** (`9.430 → 5.842 ms`, `p = 0.0001`, 95% CI `[−42.49%, −35.55%]`) - `descriptors/shader_resource_tracking`: **−32.20%** (`1.138 → 0.777 ms`, `p = 0.0002`, 95% CI `[−35.56%, −28.65%]`) - `shaders/guest_load_clusters_extended`: **−4.49%** (`5.196 → 4.977 ms`, `p = 0.0076`) - `shaders/guest_load_clusters`: **−4.16%** (`6.979 → 6.726 ms`, `p = 0.0088`) - `shaders/uniform_guest_loads`: **−3.73%** (`1.453 → 1.406 ms`, `p = 0.0156`) - `shaders/uniform_smem_and_wide_loads`: **−3.66%** (`4.173 → 4.042 ms`, `p = 0.0179`) - All 9 comparable workloads reported `identical` digests with zero regressions.
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-04 13:45 UTC · original

Re-checked at 3b07683 against the same base (1152b9c), natively on Windows 11 with MSVC, not Wine.

cargo test -p victory-shader --lib -- --test-threads=2 gives 424 passed, 1 failed, 4 ignored. The 4 new tests pass. The one failure is still emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flag, the WARP one that fails the same way on main here.

Reading prune_unreachable (ir.rs:1358) I don't see a remap problem. Exit::Indirect is the s_setpc_b64 handover (ir.rs:82, 217) and carries no block index, so leaving it alone at ir.rs:1396 can't leave anything stale. The traversal starts at block 0 and retain keeps the order, so the entry stays at index 0. A reachable block's successors are reachable too, so the debug asserts hold. It doesn't touch phi.args, but every caller clears phis before it runs (ir.rs:789, 968, 1207, and build creates none), and rename creates them fresh from the relinked preds (ir.rs:739). So there are never phi args from a pruned pred to fix up. The callers in emit/mod.rs rebuild structure, io and resources from the new program (the form closure at emit/mod.rs:667, and emit/mod.rs:795-798 after thread_edges), so no block index crosses from one program to the other.

Same local-only hooks as last time, removed afterwards. I hashed the Debug output of every build, without_skips, without_early_outs, thread_edges, operand_reads and emit during the lib tests, on 1152b9c and on 3b07683.

  • All 1,041 distinct builds and 71 distinct emits (the DXIL bytes are part of that hash) are identical. Pruning never fires inside build, and I don't think it can, since decode only walks instructions reachable from offset 0 (gfx10/mod.rs:89-108). So the call at ir.rs:252 is a guard more than a behaviour change.
  • It does fire on a valid program in one existing test, wave64_tests::a_far_early_out_is_left_out_and_the_gate_counts_the_lanes_of_both_halves. On main, without_early_outs and without_skips leave the bypassed block in place (4 blocks, 1 unreachable). The PR drops it (3 blocks). With main's output pruned the same way afterwards, the programs hash identically. Lowered through the test's own path, the DXIL and the whole HostShader are byte-identical on both sides. Apart from that, the only extra entries on the PR side come from the 4 new tests.

I also ran 100k random programs on both sides through build, both without_skips modes and without_early_outs. Each result was checked for unreachable blocks and for reads or phi args that point at undefined values.

  • Build is identical in all 100k (as expected, given decode).
  • 165 results that panicked on main now come back fine (73 without_skips shallow, 92 deep).
  • 295 results where main returned a program with unreachable blocks (123 shallow, 124 deep, 48 without_early_outs) match the PR's output once main's is pruned.
  • No PR output has an unreachable block or a dangling value. Nothing that worked on main panics or changes on the PR.

As a negative control I commented out the not_taken remap at ir.rs:1394 and reran the random programs, the far early-out test and the 4 new tests. Those 5 tests are the only places pruning fires in the lib tests. The random run flagged it (17 cases went to new panics). The tests all still passed. A test where the dropped block sits before a branch's fallthrough would cover that line. Separately, retargeting the entry jump only when pruning fires changed the DXIL hash in the far early-out test and failed it, so the hashing does see real changes on that path.

The unspill fast exit (ir.rs:328) now uses crate::envs::var_os, same as the existing checks at ir.rs:352 and 417. That's cached per thread (envs.rs:10), so it costs a map lookup per build, not a real env read. From reading it, with the variable set the early return is skipped and the scan that prints "effects unknown" runs again. I didn't run it with the variable set.

thread_edges got the least coverage. The lib tests give it one distinct input besides the new test, and the random programs don't touch it.

Both points from my earlier comment look resolved to me.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-04 13:45 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/404#issuecomment-7413326151) Re-checked at 3b07683 against the same base (1152b9c), natively on Windows 11 with MSVC, not Wine. `cargo test -p victory-shader --lib -- --test-threads=2` gives 424 passed, 1 failed, 4 ignored. The 4 new tests pass. The one failure is still `emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flag`, the WARP one that fails the same way on main here. Reading `prune_unreachable` (ir.rs:1358) I don't see a remap problem. `Exit::Indirect` is the `s_setpc_b64` handover (ir.rs:82, 217) and carries no block index, so leaving it alone at ir.rs:1396 can't leave anything stale. The traversal starts at block 0 and `retain` keeps the order, so the entry stays at index 0. A reachable block's successors are reachable too, so the debug asserts hold. It doesn't touch `phi.args`, but every caller clears phis before it runs (ir.rs:789, 968, 1207, and build creates none), and `rename` creates them fresh from the relinked preds (ir.rs:739). So there are never phi args from a pruned pred to fix up. The callers in `emit/mod.rs` rebuild structure, io and resources from the new program (the `form` closure at emit/mod.rs:667, and emit/mod.rs:795-798 after `thread_edges`), so no block index crosses from one program to the other. Same local-only hooks as last time, removed afterwards. I hashed the Debug output of every build, without_skips, without_early_outs, thread_edges, operand_reads and emit during the lib tests, on 1152b9c and on 3b07683. - All 1,041 distinct builds and 71 distinct emits (the DXIL bytes are part of that hash) are identical. Pruning never fires inside `build`, and I don't think it can, since `decode` only walks instructions reachable from offset 0 (gfx10/mod.rs:89-108). So the call at ir.rs:252 is a guard more than a behaviour change. - It does fire on a valid program in one existing test, `wave64_tests::a_far_early_out_is_left_out_and_the_gate_counts_the_lanes_of_both_halves`. On main, `without_early_outs` and `without_skips` leave the bypassed block in place (4 blocks, 1 unreachable). The PR drops it (3 blocks). With main's output pruned the same way afterwards, the programs hash identically. Lowered through the test's own path, the DXIL and the whole HostShader are byte-identical on both sides. Apart from that, the only extra entries on the PR side come from the 4 new tests. I also ran 100k random programs on both sides through build, both without_skips modes and without_early_outs. Each result was checked for unreachable blocks and for reads or phi args that point at undefined values. - Build is identical in all 100k (as expected, given decode). - 165 results that panicked on main now come back fine (73 without_skips shallow, 92 deep). - 295 results where main returned a program with unreachable blocks (123 shallow, 124 deep, 48 without_early_outs) match the PR's output once main's is pruned. - No PR output has an unreachable block or a dangling value. Nothing that worked on main panics or changes on the PR. As a negative control I commented out the `not_taken` remap at ir.rs:1394 and reran the random programs, the far early-out test and the 4 new tests. Those 5 tests are the only places pruning fires in the lib tests. The random run flagged it (17 cases went to new panics). The tests all still passed. A test where the dropped block sits before a branch's fallthrough would cover that line. Separately, retargeting the entry jump only when pruning fires changed the DXIL hash in the far early-out test and failed it, so the hashing does see real changes on that path. The unspill fast exit (ir.rs:328) now uses `crate::envs::var_os`, same as the existing checks at ir.rs:352 and 417. That's cached per thread (envs.rs:10), so it costs a map lookup per build, not a real env read. From reading it, with the variable set the early return is skipped and the scan that prints "effects unknown" runs again. I didn't run it with the variable set. `thread_edges` got the least coverage. The lib tests give it one distinct input besides the new test, and the random programs don't touch it. Both points from my earlier comment look resolved to me. AI-assisted: yes
github-bot changed title from shader: cut per-instruction allocations and map lookups in ir to perf(shader): cut per-instruction allocations and map lookups in IR 2026-12-04 22:19:57 +00:00
Author
Owner

@⁠tommiehansen on GitHub · 2026-12-05 10:18 UTC · original

Thanks for the review. The independent correctness and performance alternatives are #546 and #547. The combined head 481ed08 restores the original build-loop allocation lifetime, bumps the translator cache version and adds a two-target remap regression. Debug/release and mutation-control CI passed. Prefer the smaller splits for review; their benchmark results are not attributed to this combined head.

**@⁠tommiehansen** on GitHub · 2026-12-05 10:18 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/404#issuecomment-7436355245) Thanks for the review. The independent correctness and performance alternatives are #546 and #547. The combined head [481ed08](https://github.com/tommiehansen/VIctory-xmem/commit/481ed08485a37514d3367cb2bcf7f8ed85a0331c) restores the original build-loop allocation lifetime, bumps the translator cache version and adds a two-target remap regression. [Debug/release and mutation-control CI](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47503802058/job/145623466290) passed. Prefer the smaller splits for review; their benchmark results are not attributed to this combined head.
github-bot closed this pull request 2026-12-05 22:39:46 +00:00
Author
Owner

@⁠tommiehansen on GitHub · 2026-12-05 22:33 UTC · original

The reviewed split PRs #546 and #547 are both merged now, including the CFG remap regression and the allocation-lifetime fix. I checked the original changes against current main; the relevant implementation and tests are present, with the newer traversal refinements preserved. Closing this combined PR as superseded to avoid duplicating the changes. Thanks for the reviews!

**@⁠tommiehansen** on GitHub · 2026-12-05 22:33 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/404#issuecomment-7446859797) The reviewed split PRs #546 and #547 are both merged now, including the CFG remap regression and the allocation-lifetime fix. I checked the original changes against current main; the relevant implementation and tests are present, with the newer traversal refinements preserved. Closing this combined PR as superseded to avoid duplicating the changes. Thanks for the reviews!

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.