Skip to content

D3D12-SHADER-OPT-CHAINS-CANONICAL: a chain with its steps the other way round is in order (-8 % translate CPU, -0.34 % DXIL instructions) - #2800

Open
bobcatchris wants to merge 3 commits into
ProjectLeonida:mainfrom
bobcatchris:perf/d3d12-shader-chains-canonical
Open

bobcatchris wants to merge 3 commits into
ProjectLeonida:mainfrom
bobcatchris:perf/d3d12-shader-chains-canonical

Conversation

@bobcatchris

@bobcatchris bobcatchris commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

What

Module::optimise (leonida-shader/src/emit/bitcode/opt.rs) runs merge, prune, guards and chains for up to four rounds and stops early when none of them changes anything. In a full-archive leonida translate on current main, 10,291 of 25,689 emitted programs (40 %) run all four rounds, and rounds 3 and 4 are 44 % of the time the optimiser takes. I traced those rounds (live instructions, dead instructions, blocks, and which pass said "changed") and they are a loop, not progress: from round 2 on merge and chains both report a change every round while the counts do not move. With the limit raised to 16, 10,236 programs still say "changed" in the last round.

The cause is in chains. It rewrites a conjunction of lane conditions into (((t1 & t2) & t3) & ...), terms in the order they were made, and leaves a chain that is in that form (canonical). canonical only accepted a step written and(lower, term). key() treats an integer and as commutative, so a chain written and(term, lower) was never canonical: chains built and(lower, term) as new instructions, the reuse pass of merge put the instruction that was there back, and the next round did the same. I found it by printing the plans of a small program per round: the same root and the same terms every round, with the prefix and there with its operands the other way round.

canonical now accepts a step with its two operands either way round. That is one match arm.

Claim: D3D12-SHADER-OPT-CHAINS-CANONICAL (coordination issue #2570, #2570 (comment)). No open pull request edits chains (checked the diffs of the ones that touch opt.rs: #2750, #2698, #2687, #2681, #2569).

The DXIL is not identical to main's, and why

I claimed an identical-DXIL bar in the claim; this is not that, so here is what changes. Full archive, 25,689 programs, hash of the DXIL of each (a scratch patch writing the hashes; not in this pull request):

  • 10,089 programs differ; 15,600 are identical.
  • All of it is in arith: -341,356 instructions (-0.84 % of arith, -0.34 % of all instructions). Every other kind (select, phi, calls, loads, stores, casts, extracts, handles) and the block count are equal, from the census (LEONIDA_SHADER_CENSUS) of both builds.
  • By size: 7,315 programs smaller (up to 7.7 %), 2,767 the same size with a different hash (operands the other way round), 7 larger by 4 bytes each. Total DXIL 979,120,356 -> 977,096,524 bytes (-0.21 %).
  • Why main has those extra instructions: its last round ends on a chains rewrite and no merge follows, so the rewrite's duplicates of existing ands are written out. I checked that: main with one merge added after the last round gives the same arith count (40,370,778) as this branch and the same DXIL in 25,548 programs (total bytes within 8 of this branch's).
  • Both builds are deterministic (two runs of each gave the same hashes).

Not rewriting a chain is always sound (it leaves the lowering's own form), so the new output is main's with duplicate ands absent and some operands in the other order; I did not run a GPU test on it.

leonida translate --validate (Windows SDK 10.0.26100 dxil.dll) on both builds: the same counts (14,220 of 14,247 vertex and pixel programs, 2,677 of 2,677 compute, 8,673 of 8,765 mesh) and the same table of reasons for the rest (compared line by line, counts included), so nothing new is refused.

Measured

Full-archive leonida translate, release build with mimalloc, 16 threads, Ryzen 7 7800X3D, main at 2878a39 as the baseline (the same tree with the one arm taken out), four alternating runs of each:

wall user CPU
main 37.1 / 36.3 / 36.5 / 36.7 s 477.1 / 476.5 / 477.3 / 478.0 s
this branch 35.6 / 33.0 / 33.3 / 33.2 s 436.4 / 436.1 / 439.2 / 435.7 s

Means: wall 36.65 -> 33.78 s (-7.8 %), user CPU 477.2 -> 436.9 s (-8.5 %).

Tests

  • New a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is: the term first at the root, below it, and both; chains() finds nothing to rewrite, still nothing after optimise(CHAINS | REUSE | DEAD) has merged them, and a second run leaves the instructions as they were. Negative control: taking the new arm out makes it fail on the first assertion.
  • New a_chain_with_its_terms_out_of_order_is_still_rewritten: the control for the other direction (it passes with and without the arm).
  • cargo test -p leonida-shader (debug): 402 passed, 0 failed, 5 ignored.
  • rustfmt --edition 2024 --check opt.rs: no diff in the lines this changes (the file's other diffs were there before). cargo clippy -p leonida-shader --no-deps --all-targets -- -D warnings reports errors in other files of the crate and two in opt.rs (lines 1318 and 1778, from the commit that added chains), none in the lines this changes.
  • check_no_game_data.py on the changed file: clean.

AI-assisted: Claude Sonnet 5.5

…ay round is in order

`chains` rewrites a conjunction of lane conditions into `(((t1 & t2) & t3) & ...)`
with the terms in the order they were made, and leaves a chain alone when it is
that already (`canonical`). `canonical` only accepted a step written
`and(lower, term)`. `key` has an integer `and` the same whichever way round its
operands are, so a chain written `and(term, lower)` was never canonical: `chains`
built `and(lower, term)` as new instructions, the reuse pass of `merge` put the
instruction that was there back, and the next round did the same, until the
limit of four rounds. Both passes said "changed" every round, so `optimise` never
stopped early on those modules, and its last round ended on a `chains` rewrite
that no `merge` followed, which left the rewrite's duplicates in the DXIL.

`canonical` now accepts a step with its two operands either way round.

Full-archive `leonida translate` (25,689 emitted programs): 10,291 programs ran all
four rounds before (rounds 3 and 4 were 44 % of the optimiser's time); the DXIL of
10,089 programs changes, all of it in `arith` (-341,356 instructions, -0.84 % of
arith, -0.34 % of all; every other kind of instruction and the block count are
equal), 7,315 smaller, 2,767 of the same size, 7 larger by 4 bytes. The old code
with one `merge` added after its last round gives the same arith count. The
validator (`--validate`) reports the same table of reasons and the same counts
before and after. Wall -7.8 %, user CPU -8.5 % over four alternating runs each.

Tests: a chain with the term first at the root, below it, and both is left as it
is (fails without the change), and a chain with its terms out of order is still
rewritten.

AI-assisted: Claude Sonnet 5.5
Co-authored-by: Cursor <cursoragent@cursor.com>
@OreoFR

OreoFR commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Verified by OreoFR on macOS 27.2.1, Apple M5, Rust (rustup), head 9e39fbb58, main d4fabd3fe. CPU only, no game files.

MEASURED

  • cargo test --release -p leonida-shader: main 242 passed, 0 failed, 2 ignored; main + this PR (merge-tree) 244 passed, 0 failed, 2 ignored. The two extra tests are the new ones.
  • Red, on main + this PR with only the added arm removed (Op::Bin(Bin::And, x, y) if x == want => cur = y,), tests matching a_chain_with: 1 failed, 1 passed.
    • a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is fails, at opt.rs:1853 (assert!(!m.chains(), "no chain here is out of order")).
    • a_chain_with_its_terms_out_of_order_is_still_rewritten passes, as a control should.
  • So the new test pins the fix, and the control shows that out-of-order chains are still rewritten.

READ IN CODE

  • The fix is the one arm in canonical. It walks the chain from the root using whichever operand of and is not the expected term. That matches key() treating an integer and as commutative, so chains and the reuse pass now agree on what "in order" means.
  • The new test covers the three shapes (swapped at the root and below, at the root only, below only). It also checks that a second optimise(CHAINS | REUSE | DEAD) leaves the same instructions, which is the fixed point that was missing.

ASSUMED

  • The archive figures (DXIL changes in 10,089 of 25,689 programs, all in arith, -0.34 % instructions, -8 % translation CPU) are from your run and are not reproduced here: they need the game's archive. The DXIL is not byte-identical to main, so an in-game check on the translated output is what would cover the behavior change.

AI-assisted: Claude Code

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified the Rust arm (this is d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs, not the Python translator — so the semantic suite cannot discriminate it): cargo test --locked -p leonida-shader --lib is 402 passed / 0 failed / 5 ignored, and removing the new match arm makes a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is fail at opt.rs:1853, while the out-of-order control test still passes. So the new arm is pinned in both directions.

The change is semantically safe as far as I can tell: only i1 and nodes (plus pure xor) are replaced, leaves — including effectful loads/calls — keep their instructions and positions, and a store/atomic/barrier is not an i1 and step, so nothing with side effects is reordered. The term order is irrelevant to AND, and the terms are sorted by definition site and deduped, with a term-with-its-complement refused (:1242-1261); the only hash-ordered collection is the pre-existing by_block map, which does not decide which chains collapse.

One residual, performance only but worth closing: born[p] = (rank, 0) for every phi in a block (:1202) and a stable sort_by_key (:1249) mean same-block phis tie, so their order follows the DFS — which reverses when the chain is rebuilt. With three i1 phis from one block in a chain, canonical rejects the rebuilt chain and chains() rewrites again next call (temporary test: first call true, second call true; with three distinct comparisons the second is false). A total tie-break — (born, base) or a per-phi birth index — finishes the loop fix this PR is after.

(The Python semantic suite is irrelevant here: 553 files / 6,720 tests pass, but it never loads leonida-shader. The archive hash change is not reproducible here either — no work folder with disassembly on this machine — and the PR does not claim identical output anyway.)

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2800 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS. The fix is one line and the pull request brings its own control: the out-of-order chain is still rewritten.

Head 9e39fbb5, base the current main 88a9f133, merge base 2878a391, 1 commit, 1 file, +86/−1: d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs.

1. The change

chains() asks whether the chain it is looking at is already in canonical order, and the answer walked the chain's steps like this:

match m.insts[i as usize].op {
    Op::Bin(Bin::And, x, y) if y == want => cur = x,
    _ => return false,
}

That only accepts a step written as x & want — the term second. An integer and is the same value whichever way round its operands are, so want & x is the same chain; the old answer said "not canonical" for it. The pull request adds the other way:

    Op::Bin(Bin::And, x, y) if y == want => cur = x,
    Op::Bin(Bin::And, x, y) if x == want => cur = y,

The comment in the pull request describes the consequence: the reuse pass would put the instruction that is there back in place of the rewrite, and the next round would plan the same rewrite again, "up to the round limit".

2. Red and green, and the discrimination

cargo test -p leonida-shader (Linux, pinned toolchain) on the pull request's branch:

test result: ok. 241 passed; 0 failed; 2 ignored

With only that one line put back (the pull request's tests kept):

test emit::bitcode::opt::tests::a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is ... FAILED
  panicked at crates/leonida-shader/src/emit/bitcode/opt.rs:1853:9
test result: FAILED. 240 passed; 1 failed; 2 ignored

So the new test looks at the code it is about.

3. The control is in the pull request

a_chain_with_its_terms_out_of_order_is_still_rewritten is the negative control, and it is the part I like most about this pull request:

let low = m.bin(b, Bin::And, c2, a);      // c2 & a  — the terms are in the wrong order
let chain = m.bin(b, Bin::And, low, c1);
assert!(m.chains(), "`c2 & a` then `& c1` is not `(a & c1) & c2`");
assert!(!m.chains(), "and the rewrite is in order");

The first assertion is that the pass finds work, the second that a second call finds none — so the fix cannot be "the pass stopped rewriting anything". With the fix reverted, the other test fails and this one still passes, which is what a control should do.

4. The claim about the reuse pass

The pull request says the chain "would be rebuilt each round for the reuse pass to put back, and say that it had changed something every time, up to the limit of rounds". The new test checks the end of that: m.optimise(CHAINS | REUSE | DEAD) merges the three chains, and a second optimise leaves the instructions identical (assert_eq!(ops(&m), merged)).

I did not measure the round count or the CPU saving on a real shader corpus — the pull request's title quotes "-8 % translate CPU, -0.34 % DXIL instructions", and that needs the game's shaders, which are not in the repository and which I do not have.

5. It does not collide with #2872

Both pull requests change chains() in opt.rs (#2872 makes the block grouping deterministic, this one makes the canonical test accept a commutative step). I merged both onto today's main and ran the crate:

test result: ok. 249 passed; 0 failed; 2 ignored

No conflict, and neither pull request's test breaks the other's.

6. What I did not check

  • The translation of a real shader. Everything above is the crate's unit tests over hand-built modules. I did not translate a game shader, so I did not measure the CPU or the instruction count the pull request's title quotes.
  • The other crates in the workspace — leonida-gpu, leonida-hle and leonida-loader do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows Linux: build leonida.exe and run it under Proton or Wine #2577"), so I ran leonida-shader on its own.
  • Whether Bin::And is always commutative in this IR. The fix assumes an integer and; the pass works on i1/i32 values, and and on those is commutative. I did not look for a use of Bin::And on a non-integer type, where the reasoning would not hold.
  • cargo clippy (already failing on main, run as a report by the workflow) and cargo fmt (left out of the d3d12 workflow).

AI-assisted: MiniMax M3.1 Flash.

@bobcatchris

Copy link
Copy Markdown
Contributor Author

@KelboLive Addressed the same-block phi tie-break residual in b6ebcedd4 (after merging main, no rebase/force-push):

  • Assigned distinct birth positions (rank, k) for each phi (0..phis.len()) and (rank, phis.len() + k) for body instructions in chains(), giving every instruction in reachable blocks a strict total birth order.
  • Added a_chain_of_three_phis_in_the_same_block_settles_in_one_pass pinning that a 3-phi chain in one block rewrites once and settles (chains() returns false on the second call).
  • Verified locally on Windows (Rust 1.98.1): cargo test --locked -p leonida-shader --lib bitcode::opt (21 passed, 0 failed) and python -I scripts/check_no_game_data.py (clean).

AI-assisted: Gemini 4 Neon (including an independent read-only reviewer pass).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants