perf(shader): cut per-instruction allocations and map lookups in IR #404
No reviewers
Labels
No labels
accessibility
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
question
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/lobomfz--VIctory-xmem!404
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-404"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@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 mergingLatest 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
ir.rsoptimization subject.cargo xtask policyon 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 = identicalacross allshaders/*anddescriptors/*benchmarks), and explicitly resolves unreachable-block stale SSA values after CFG rewrites:RegSetdedup (effects_into): replaces per-instructionr/w/seenVecallocations and linear scans ineffects()acrossir::build()andunspill()with caller-reused scratch buffers and direct bitmask membership tracking viaRegSet.peekablenext-offset iteration inir::build(): replaces thenext_offsetslookupVecandbinary_searchcalls with a monotonic block index cursor,peekableleader iteration, and O(1) fallthrough lookup (leaders.get(b + 1)).unspill()setup whenVICTORY_WHY_UNSPILLis unset and nov_writelane_b32/v_readlane_b32instructions exist (retaining full instruction scanning andWHY-UNSPILLdiagnostic logging whenVICTORY_WHY_UNSPILLis set), and skips fixed-point iteration inremove_trivial_phis_steps()when all blocks have emptyphis.prune_unreachable): afterlink()/ CFG edge edits (build,thread_edges,without_early_outs,without_skips) and as a guard at entry torename(),prune_unreachablerunsreverse_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, remapsExit::JumpandExit::Branchtargets (leavingExit::End/Exit::Indirectunchanged), and recomputeslink()/reverse_postorder()beforesplit_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 trippedremove_trivial_phis_steps()onmainor remained dangling under the no-phi fast exit); unreachable blocks are now removed cleanly rather than preserving invalid unreachable SSA programs.Value-indexed tables inwithout_skips()andcopy_through_phis(): replaces SipHashHashMap<Value, Value>andHashSet<Value>with denseVec<Value>andVec<bool>tables indexed byValue.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, andthread_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) viatools/benchmark-suitecomparing the branch's actual parent1152b9cvs3b07683(perf/ir-build-unspill-alloc):1152b9c(ms)3b07683(ms)shaders/structurise_guard_runsidenticaldescriptors/shader_resource_trackingidenticalshaders/guest_load_clusters_extendedidenticalshaders/guest_load_clustersidenticalshaders/uniform_guest_loadsidenticalshaders/uniform_smem_and_wide_loadsidenticalshaders/translate_corpusidenticaldescriptors/copy_span_indexidenticalshaders/node_probe_emitidenticalshaders/gpu_execute,descriptors/d3d12x_heap_and_copy--cpu-onlyAll 9 supported benchmarks produce 100%
identicalequivalence digests with zero regressions.Validation & Reproducible Commands
victory-shader): 299 passed, 0 failed, 2 ignored (on macOS; Windows D3D12 emit tests are Windows-only):tools/benchmark-suite):Known Limitations
crates/victory-shader/src/ir.rsis modified; orthogonal passes inemit/bitcode/opt.rs(#399) andstructure.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
b581f7e0a8086158953a64068ba29305d5450d68into the existing branch without rewriting history. New head:a39ca27f3947e162653747d7564762811381e4c2. Review split candidates staged independently: CFG fix31e7e781fbcf5b3a19620ac0ebd14b68a478169a, performance-only22ffc9974358305a9670b2ccc3c93e428fa09033. 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. Addedpruning_remaps_both_branch_targets_past_a_dead_blockto 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)
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.
@Kal0s-design on GitHub · 2026-12-04 02:10 UTC · original
Tested this natively on Windows 11 (MSVC), PR head
3f52e6bagainst main1152b9c.cargo test -p victory-shader --libgives 420 passed, 1 failed, 4 ignored on the PR and 419/1/4 on main. The one failure isemit::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-targetsshows 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.
effects()from main next toeffects_intoand 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 inbuildcould push a read the old code wouldn't. It never happened.ir::build,without_skips,operand_readsandemitcall 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.without_skipsin both modes, andoperand_reads. 199,971 gave the same result on both sides. The other 29 differ, main panics inwithout_skipsand the PR returnsSome.The panic on main is an index out of bounds in
find()inremove_trivial_phis_steps. Whenwithout_skipsdrops a skip, some blocks can become unreachable.renamenever visits those blocks, so their reads keep value numbers from the old program, and main trips over them because it runsfind()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 ofrename(without_early_outs, thread_edges too). Nothing in the test corpus hits this, only the random programs. Either dropping unreachable blocks beforerenameor 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, anddecodeguarantees that by rejecting branches into the middle of an instruction.RegSetcovers everyReg, so the dedup keeps exactly what the oldseenscan kept.copyandliveare never iterated, so the move to flat tables can't change any order. The flat tables only differ from the maps onNONEvalues, which rename's debug asserts already rule out. One small thing, the unspill early return also skips theVICTORY_WHY_UNSPILL"effects unknown" line, which only matters when debugging.I didn't measure timing.
AI-assisted: yes
@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_UNSPILLdiagnostic edge case in fuzzing! Pushed commit3b07683resolving both and updated the PR description:prune_unreachableincrates/victory-shader/src/ir.rs):prune_unreachable(&mut blocks)usingreverse_postorder()(zero-allocation fast path when all blocks are reachable; otherwise builds an order-preserving remap, retains reachable blocks, updatesExit::Jumpand bothExit::Branchtargets leavingExit::End/Exit::Indirectuntouched, and callslink(blocks)).link()and beforesplit_irreducible()acrossbuild,thread_edges,without_early_outs, andwithout_skips, plus a reachability guard at entry torename()beforereverse_postorder()andliveness().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).VICTORY_WHY_UNSPILLdiagnostics (unspill):v_writelane_b32/no-v_readlane_b32fast exit tocrate::envs::var_os("VICTORY_WHY_UNSPILL").is_none(), so settingVICTORY_WHY_UNSPILLpreserves the full instruction scan and"effects unknown"diagnostic reporting.Verification on
3b07683crates/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, andthread_edges_prunes_orphaned_join_and_keeps_valid_ssa(fullcargo test --offline -p victory-shader:299 passed; 0 failed; 2 ignoredon macOS, valid shader corpus unchanged).45591b0vs3b07683, 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 workloadsidenticalwith zero regressions. (SyncingPROGRESS.mdon#322next.)@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; onmainthis is a latent panic (remove_trivial_phis_stepstripping over stale out-of-range values). That deserves its own PR and its own changelog line.Three things in
prune_unreachable/without_skipsworth fixing as you split:crates/victory-shader/src/ir.rs:1358-1401relies ondebug_assert_ne!(remap[*t], usize::MAX). In release, a kept block pointing at a pruned one becomesExit::Jump(usize::MAX)and the nextblocks[t]panics far from the cause. Make it a hardexpect, orfilter_mapthe unknown targets.build(ir.rs:252) andrename(ir.rs:714), andthread_edges/without_skips/without_early_outsprune, thensplit_irreducible, thenrenameprunes again — each call paying areverse_postorderplus a fulllink()on the shader-compile hot path you are trying to shorten. Theorder.len() == blocks.len()fast path still pays for the traversal.without_skips'deep && phi.value != NONE && !live[...](ir.rs:1140) is not the olddeep && !live.contains(&phi.value): a phi whose value isNONEused to be skipped in deep mode and now is not. I could not construct such a phi frombuild, but the predicate changed rather than being preserved. Adebug_assert_ne!(phi.value, NONE)atir.rs:1131would state the assumption.The perf half (
effects_intobuffers,peekableleader walk, denseValuetables, theunspillearly exit) is fine and worth having on its own.42 behind;
ir.rsuntouched onmainsince the merge base. Reviewed at head3b07683(your local ref was stale at3f52e6b).@tommiehansen on GitHub · 2026-12-04 12:21 UTC · original
Updated the PR #404 benchmark table to isolate
3b07683directly against its true parent1152b9c(replacing the earlier45591b0comparison, which preceded1152b9cby 14 commits) and clarified thatprune_unreachable()avoids remapping allocations on the all-reachable fast path whilereverse_postorder()still allocates its traversal buffers: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)identicaldigests with zero regressions.@Kal0s-design on GitHub · 2026-12-04 13:45 UTC · original
Re-checked at
3b07683against the same base (1152b9c), natively on Windows 11 with MSVC, not Wine.cargo test -p victory-shader --lib -- --test-threads=2gives 424 passed, 1 failed, 4 ignored. The 4 new tests pass. The one failure is stillemit::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::Indirectis thes_setpc_b64handover (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 andretainkeeps 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 touchphi.args, but every caller clears phis before it runs (ir.rs:789, 968, 1207, and build creates none), andrenamecreates them fresh from the relinked preds (ir.rs:739). So there are never phi args from a pruned pred to fix up. The callers inemit/mod.rsrebuild structure, io and resources from the new program (theformclosure at emit/mod.rs:667, and emit/mod.rs:795-798 afterthread_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
1152b9cand on3b07683.build, and I don't think it can, sincedecodeonly 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.wave64_tests::a_far_early_out_is_left_out_and_the_gate_counts_the_lanes_of_both_halves. On main,without_early_outsandwithout_skipsleave 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.
As a negative control I commented out the
not_takenremap 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_edgesgot 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
shader: cut per-instruction allocations and map lookups in irto perf(shader): cut per-instruction allocations and map lookups in IR@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 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!
Pull request closed