perf(shader): eliminate per-block allocations and SipHash in bitcode::opt #399
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!399
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-399"
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:18 UTC · original
tommiehansen:perf/bitcode-opt-alloc-hash→main· +586 −150 · 1 files · 3 commits · merged 2026-12-05 17:28 UTCStandard benchmark — 2026-12-05
Reproducible CI result · head
6c77cd261757· Linux hosted CPU-only, Standard, four ABBA blocks (8 runs per arm).Baseline
b581f7e; candidate as pinned above. All measured shader outputs identical; structurise timing inconclusive. CPU translation, not GPU frame rate.Negative values indicate reduced CPU time. Synthetic workloads, not gameplay FPS.
What this does
eliminate per-block allocations and SipHash in bitcode::opt.
Checks
bitcode/opt.rsoptimization subject.expr_table_handles_collisions_lifo_removal_and_fast_clearand differential interpreter checks; 295 tests previously passed. Explicit before/after test and requested invariant/assertion follow-up pending.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 −21–29% in selected bitcode workloads; no GPU execution result.
Detailed implementation and historical validation
Summary
Eliminates per-instruction
Keyheap clones, SipHash lookups, and per-block trail/vector allocations insidevictory_shader::emit::bitcode::opt::mergewhile producing byte-for-byte identical DXIL (equivalence = identicalacross allshaders/*workloads, noTRANSLATOR_VERSIONchange).On Apple M5 (macOS), end-to-end shader translation throughput improves by 21.5%–29.1% across translation workloads (
shaders/translate_corpus-24.50%,shaders/guest_load_clusters-27.91%,shaders/guest_load_clusters_extended-29.09%,shaders/uniform_smem_and_wide_loads-24.88%,shaders/uniform_guest_loads-21.50%,shaders/node_probe_emit-12.62%).Changes (
crates/victory-shader/src/emit/bitcode/opt.rs)ExprTable<TRACK_USED>): ReplacesHashMap<Key, V>for both dominator-treeknownand block-localreadtables. ComputesFxhashes (key_hash) and value equality (key_eq,is_raw_srv) directly againstself.insts[i].opwithout cloningCall/Gep/BufferReadoperandVec<V>s, uses precomputedfunc_flags(dx.op.getDimensions,dx.op.rawBufferLoad.,dx.op.annotateHandle) instead of repeated string matching, performs LIFO backward-shift deletion onknown, and resets only occupied slots viausedindices onread::clear_fast().Facts): ReplacesFacts::bits: HashMap<V, bool>with a reusedVec<u8>indexed by instruction id (bits_activefast path skips lookups when no branch facts are active, and!compares.is_empty()guards compare lookups).Fxhasher (FxMap): SwitchesFacts::comparesandjoinsfrom SipHash toBuildHasherDefault<Fx>(matchingstructure.rs, zero new dependencies).MergeScratch: Replaces per-blockStep::Leave(Vec<Key>, Learned)allocations with three flat LIFO trailVecs (known_trail,bits_trail,cmp_trail), compactsBlock::bodyin place instead of allocatingVec::with_capacityper block, hoists & reusesjoins/join_key, and reuses all scratch buffers acrossoptimise()fixed-point rounds.pure_loadsempty check: Guardsself.pure_loads.contains(&i)inModule::class()with!self.pure_loads.is_empty().expr_table_handles_collisions_lifo_removal_and_fast_clearcovering hash collision chains,raw_srv/region namespace isolation, LIFO backward-shift deletion, andclear_fast()across capacity growth.Benchmarks (CPU-Only Synthetic Suite, Apple M5 macOS)
Paired A/B/B/A (
1152b9cvs454f72e,--offline --cpu-only --profile standard --blocks 4 --suite shaders, 8 runs/side) viatools/benchmark-suite:1152b9c(ms)454f72e(ms)shaders/guest_load_clustersidenticalshaders/guest_load_clusters_extendedidenticalshaders/uniform_smem_and_wide_loadsidenticalshaders/translate_corpusidenticalshaders/uniform_guest_loadsidenticalshaders/node_probe_emitidenticalshaders/structurise_guard_runsidenticalshaders/gpu_execute--cpu-onlyVerification & Reproducibility
victory-shader --lib):295 passed; 0 failed; 2 ignored(including 400-seed differential interpreter checkevery_pass_leaves_what_random_programs_storeacrossDEAD,FOLD,REUSE,FACTS,LOADS,ALL, plusexpr_table_handles_collisions_lifo_removal_and_fast_clear).rustfmt --edition 2024 --check crates/victory-shader/src/emit/bitcode/opt.rsclean.cargo check --offline -p victory-shader --lib --tests --examples --target x86_64-pc-windows-msvc --features blake3/pure,host,diagnosticsclean (guard_runsbench target has pre-existingpub(crate)ir::builderror onmain).Known Limitations
identical), so steady-state GPU execution of cached shaders is unchanged; wins apply to uncached/warm-start shader translation.Follow-up review fixes (2026-12-04)
Head:
526d8160499a1c6532b933dca6e6622653ee3b1e.Add debug assertions for missing expression-trail removal entries and document why the region participates in hashing only for raw SRVs. Existing byte-identical DXIL evidence is for the bitcode optimization path on the reported synthetic corpus, not proof of all real shaders.
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:6c77cd26175778eb3e94b3b6ce36b0904c5fc959.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.
Standard CI raw-artifact follow-up (2026-12-05)
All selected rows have identical output digests; corpus 95% CI −29.10% to −22.95%. 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.@Kal0s-design on GitHub · 2026-12-04 03:00 UTC · original
Tested this natively on Windows 11 (MSVC), victory-shader only, against the merge base
1152b9c.Tests
cargo test -p victory-shader --libgives 420 passed, 1 failed, 4 ignored. Main gives 419 / 1 / 4 on the same box, so the extra pass is the newexpr_table_handles_collisions_lifo_removal_and_fast_cleartest. The single failure issize_tests::a_reused_descriptor_register_read_only_behind_its_flag, which fails the same way on main here (WARP), so it has nothing to do with this PR.--all-targetsshows the same warnings as main and nothing new from opt.rs (theguard_runsbench E0603 is already there on main).Old vs new merge, call by call (local only, not pushed)
I copied main's
merge(theKey/HashMapversion withlearn,keyandraw_srv_key) into a test-only module and hookedoptimiseso everymergecall ran the old version and the new one on the same input. For each call I compared the returned changed flag and a full dump of types, consts, insts and blocks.rawBufferLoadthrough annotated handles (two SRVs and one UAV), which gets theDOM_LOADSpath some real traffic. 20000 seeds, with and without raw loads, over 9 pass sets (REUSE, LOADS, FACTS, FOLD|FACTS, DOM_LOADS, REUSE|LOADS|DOM_LOADS, MODULE, ALL, DEFAULT) came to about 755k merge calls with zero differences. Those runs hit about 48k dominated raw load reuses, 319k pure reuses and 99k block-local read reuses. Theknowntable grew to 256 slots with up to 120 live entries, so growth and unwinding with a live trail did happen.merge, and the diff caught it straight away. Swapping the backward-shift delete for a plain slot clear also failed, on theknown.len == 0debug assert at the end of the walk.DXIL
Hashed every module the suite emits on both sides. 840 modules (716 distinct), and the sorted hash lists match exactly between main and this branch.
Reading the code
key_eqlines up with the old derivedKeyequality for every variant. Bin operands only commute for integer Add/Mul/And/Or/Xor, Cast still includes the result type, Call/Gep/Load compare operand ids, and raw SRV entries stay in their own namespace keyed by region.key_hashhashes the same normalized operands, so equal keys get equal hashes. Floats are still compared by constant id, so -0.0 and NaN behave exactly as before.Op::GepandOp::Loadcarry no inbounds or alignment field, so the old key had nothing extra there either.getDimensionsandannotateHandleand the prefix forrawBufferLoad., same as the old string checks.key_eqnow reads the stored instruction's currentopinstead of a snapshot taken at insert time. That's fine today because the walk only rewrites the operands of the instruction it is on, but a future change that rewrites earlier instructions during the walk would quietly break lookups.I didn't do any timing on Windows.
AI-assisted: yes
@Luxuride on GitHub · 2026-12-04 12:20 UTC · original
This is the one to take from this batch: contained to one file, the equivalence argument holds, and 21–29% on the translator is a real number.
Three things I checked specifically, because they are what would silently corrupt dedup:
key_hashnormalises commutativeBinoperands exactly whenkey_eqaccepts the swap (crates/victory-shader/src/emit/bitcode/opt.rs:1004-1032vs:1065-1100), so equal keys cannot hash differently.remove's asymmetric predicate(!raw_srv || s.region == region)(opt.rs:277-281) is safe only becausekey_hashmixesregionin theraw_srvbranch only. That is a real footgun for the next reader: if anyone foldsregioninto the non-raw hash, every non-raw removal stops matching and the table leaks entries. Put that in a comment where the hash is built.clear_fast(opt.rs:189-199) is only ever called onTRACK_USED=truetables andgrow(opt.rs:201-224) rebuildsused, so no stale index survives a resize.Two small asks:
debug_asserton the miss path ofremove(opt.rs:269-272) — today a removal that fails to find its entry returns silently and leaveslentoo high, which only surfaces much later as an unnecessarygrow.42 behind, and
opt.rshas no commits onmainsince your merge base, so nothing was fixed underneath you.@tommiehansen on GitHub · 2026-12-05 10:19 UTC · original
Thanks @Luxuride for the removal/hash review. 526d816 adds the missing-removal debug assertion and explains why region is hashed only for raw SRVs. The updated description scopes DXIL equivalence to the measured bitcode path. Current-head Standard CPU comparison reports 24.56% lower corpus translation time with identical output.