Skip to content

Recompiler: fold 64-bit ints, bitcast selects and commutative CSE in direct DXIL - #1906

Open
Decodere wants to merge 1 commit into
xcl-dev:mainfrom
Decodere:dxil-opt-post-phi
Open

Decodere wants to merge 1 commit into
xcl-dev:mainfrom
Decodere:dxil-opt-post-phi

Conversation

@Decodere

@Decodere Decodere commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Extends the direct-DXIL optimizer (gpu::dxil::module::opt) to fold post-phi value redundancies that remain after initial lowering and trivial-phi elimination: 64-bit integer window/pack arithmetic, finite constant BitCasts, zero-duplication bitcast(select(...)) folding around VGPR float updates, nested same-condition Select chains, commutative integer ops and compares before dominator CSE, and expanded flag-neutral intrinsic DCE. Part of #1269.

Because the DXIL validator verifies that shader feature flags match the emitted instructions, f64 instructions stay untouched, BitCast constant folding excludes NaN and Inf in both directions, and Shader::infer_type_features clears Feature::Int64Ops after optimization when no surviving instruction uses i64 so folding away all 64-bit ops never fails Flags must match usage. Control-flow terminator folding is intentionally left out of this PR to keep scope focused and avoid overlap with #1818.

What is in it

  • crates/xcl/src/gpu/dxil/module/opt.rs:
    • Separate XCL_DXIL_NO_OPT=fold from cse for independent bisecting (XCL_DXIL_NO_OPT=phi,fold,cse,dce or all).
    • Enable 64-bit integer constant/identity folding and DCE (i64 arithmetic, shifts, LShr(ZExt) and LShr(Or(ZExt, Shl(ZExt))) window-high patterns, Trunc(ZExt|SExt), i1 select/compare identities, and ZExt(i1) compares).
    • Fold finite constant BitCast (i32 <-> f32, i16 <-> f16, excluding NaN and Inf symmetrically), reuse dominating BitCasts from CSE, collapse nested same-condition Select chains, and push BitCast through Select only when the Select has no surviving non-bitcast uses (accounting for bypassed same-condition inner selects, so no Select is duplicated) with scoped CSE alias registration.
    • Canonicalize commutative integer binops (Add/Mul/And/Or/Xor) and integer Cmp predicates before dominator CSE, and expand flag-neutral ReadNone dx.op.* DCE.
  • crates/xcl/src/gpu/dxil/shader.rs: clear Feature::Int64Ops in infer_type_features() when no surviving instruction uses i64.
  • crates/xcl/src/gpu/dxil/core_tests.rs: add opt_folds_i64_bitcast_selects_and_commutative_cse covering i64 window-high + Int64Ops cleanup, finite vs +Inf constant BitCasts, bitcast(select), nested selects, commutative CSE, zext(i1) compares, multi-window RDNA2 loop folding, DXC validation, and RTX 4060 GPU execution + HLSL parity.
  • Cache invalidation for direct-DXIL entries is handled automatically by XCL_DIRECT_DXIL_SOURCE_ID (Recompiler: direct DXIL cache entries change when its sources do #1947), so no manual TRANSLATOR_VERSION bump is needed.

Tested

  • Hardware / toolchain: NVIDIA GeForce RTX 4060 (8 GB, 32-lane waves, driver 621.14), Intel Core i5-11400F, 32 GB RAM, Windows 11 Home build 26200, Rust 1.100.0 (0ef1bc386), DXC 1.9.2609.5 (01b62ad4), release build.
  • cargo test --release -p xcl --lib gpu::dxil -- --test-threads=4: 113 passed, 0 failed, 3 ignored, 0 skipped (including fuzz, geometry, MSAA, directed rounding, dx.op.discard block-CSE invalidation, and the new optimization test).
  • cargo build --release --workspace + cargo test --release --workspace -- --test-threads=4: 1112 passed, 0 failed, 46 ignored across 20 test binaries.
  • SKIPPED GPU/runtime tests on this adapter (27 lines):
    • 20 no wave64 subcases across gpu::recomp::lower::tests (4), gpu::recomp::lower_dxil::tests (14), and gpu::recomp::tests (2)
    • 3 intentional per-lane #1426 refusals (V_MUL_F16, V_PK_MUL_F16, V_CVT_F16_F32) in gpu::recomp::lower_dxil::tests
    • shaders::tests::pso_measurement_compiles_an_exact_synthetic_record: cannot disable the driver cache (Windows Developer Mode is required)
    • heap_window_out_of_memory_falls_back_to_the_switch_form: no heap windows
    • 2 D3D12 debug-layer tests (test_title_draws_with_a_root_signature_under_the_debug_layer, uploads_start_from_each_subresources_state: no d3d12SDKLayers.dll)
  • Direct-DXIL validated corpus comparison (origin/main 689f2db4 vs this PR on a 300-record seed-1 retail shader pack sample, 252/252 = 100.0% translated across 22 CS, 4 GS, 98 MS, 97 PS, 31 VS):
    • Validator errors: 0, panics: 0, timeouts: 0 (also 0 errors across 977/977 translated programs in a 1,000-record --max-bytes 65536 validated sweep, and 0 errors across 13/13 in a 20-record --validate check with XCL_DXIL_NO_OPT=fold).
    • Total DXIL size: 12,208,376 -> 11,811,244 B (-397,132 B, -3.25%; 252/252 shrank, 0 unchanged, 0 grew; per-shader median -3.35%, range -0.46% to -7.82%).
    • Total LLVM instructions: 1,683,483 -> 1,576,845 (-106,638, -6.33%); bitcast: 191,134 -> 136,196 (-54,938, -28.74%); select: 265,081 -> 258,991 (-6,090, -2.30%); i64 ops: 79,848 -> 49,251 (-30,597, -38.32%).
    • Translation wall time for the 252-program sweep: 2.1 s (main) vs 1.9 s (PR).
  • Cold RTX 4060 CreateComputePipelineState check on 15 unique-hash retail direct-DXIL compute shaders (28–37 KB, alternating main/PR order, verified cold vs 0.5–1.1 ms warm 2nd calls):
    • 15/15 compiled cleanly with 0 driver errors.
    • Total DXIL bytes: 497,560 -> 480,904 B (-3.35%).
    • Total cold PSO compile time: 3,037.9 ms -> 3,123.3 ms (+2.81%; 7 faster / 8 slower, median +1.70%, range -12.57% to +21.83%, within single-shot driver variance).

Regression run
scripts/smoke.ps1 on origin/main (3da2abb81606df622610e009f0430de99aa9881c) and on this PR's head commit (5ca498afcb7dd97accc91427e1e0f5b3a1bcb577):

xcl-smoke v1
commit: 3da2abb81606df622610e009f0430de99aa9881c
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1582 (PresentX 1582)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14666 MB
xcl-smoke v1
commit: 5ca498afcb7dd97accc91427e1e0f5b3a1bcb577
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1568 (PresentX 1568)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14664 MB

Not tested

  • AMD and Intel GPUs, native wave64 hardware, and heap-window hardware paths (skipped above).
  • Live in-game retail smoke with XCL_DIRECT_DXIL=1 enabled (the default smoke run above exercises the default HLSL runtime path; direct-DXIL coverage was verified via corpus DXC validation, cold RTX 4060 PSO creation, and direct-DXIL GPU execution parity tests).
  • Debug-profile full workspace test run (the full suite ran in --release).

AI use

  • Google Antigravity (Gemini 4 Neon) — implemented the optimization pass, tests, benchmarks, and PR description; every line of the diff, test output, benchmark run, and smoke check was verified on local RTX 4060 hardware.
  • Google Antigravity (Gemini 4 Carbon) — audited the diff, validator invariants, and live upstream PR collisions.

@upipibi

upipibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

A second NVIDIA generation: RTX 3070 8 GB (Ampere, 32-lane waves, split wave64), driver 616.56, Windows 11, debug, 9ea9ad1 merged onto main 689f2db (clean).

AI-assisted (Claude Code). Synthetic tests only.

@Melow-code Melow-code 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.

Fold logic is correct on the edges we checked: masks saturate at w=64 (the old AShr had a wrong shift count, fixed by the precalculated sx), free_bitcast excludes NaN/Inf both ways, bc_only pre-pass properly distinguishes bitcast-uses from other select arms, and the Int64Ops removal is paired with the DCE keep-list change.

Three points for the author to confirm:

  1. The BitCast alias key placed back in the CSE table in-place — a core test would pin this.
  2. Value id ordering as total order for canonicalize — harmless for CSE, worth noting.
  3. The new ReadNone DCE-able intrinsics (threadId, groupId, flattenedThreadIdInGroup) should get a validator run on a shader that uses them only in that context.

@Decodere

Copy link
Copy Markdown
Contributor Author

Thanks @upipibi for the RTX 3070 verification and @ruipedro-pinheiro for the thorough review! Confirming all three points on 9ea9ad1:

  1. BitCast alias_key in the scoped CSE table (module/opt.rs:151-162, 674-677): Confirmed sound — when bitcast(select(...)) rewrites an instruction at index i, inserting alias_key = (Op::Cast(BitCast, s, to), to) mapped to repl[i].unwrap_or(Value::Inst(i)) (which dominates the subtree) and pushing the prior entry onto undo ensures dominated free_bitcast/CSE lookups reuse the rewritten value while Step::Leave cleanly restores the parent scope.
  2. Value ordering in canonicalize_commutative (module/opt.rs:187-204): Confirmed — Value: Ord provides a deterministic total order per module, applied after operand resolution purely to normalize commutative BinOp/Cmp keys for dominator CSE.
  3. DCE of threadId / groupId / flattenedThreadIdInGroup (module/opt.rs:413): Confirmed flag-neutral — Shader::infer_type_features (shader.rs:212-233) sets no Feature flags or PSV0/signature entries for them, Module::write_bitcode (module.rs:819-865) omits declarations of unreferenced dx.op.* intrinsics, and compute_init / setup_lanes_compute (kernel.rs:563, lanes.rs:142,176) already emit unused groupId / threadIdInGroup / flattenedThreadIdInGroup calls that DCE cleanly with 0 DXC validator errors across the 252-program and 977-program --direct --validate sweeps.

Leaving 9ea9ad1 untouched for now so the existing RTX 3070 test report and smoke blocks stay current; happy to push a dedicated unit test pinning points 1 & 3 if a maintainer would like one before merge.

AI use: Google Antigravity (Gemini 4 Neon) checked the line citations against 9ea9ad1 and drafted this confirmation.

anoyarou pushed a commit to anoyarou/xcl that referenced this pull request Nov 25, 2026
…direct DXIL (xcl-dev#1906)

Extend `gpu::dxil::module::opt` to fold remaining post-phi redundancies in
direct-DXIL shaders without colliding with CFG-level folding or violating DXC
validator shader-flag invariants:

- Enable 64-bit integer constant/identity folding and DCE (`i64` arithmetic,
  shifts, `LShr(ZExt)` / `LShr(Or(ZExt, Shl(ZExt)))` window-high patterns,
  `Trunc(ZExt|SExt)`, and `i1` / `ZExt(i1)` compares) and clear
  `Feature::Int64Ops` in `Shader::infer_type_features` when no surviving
  instruction uses `i64`.
- Fold finite constant `BitCast` (`i32 <-> f32`, `i16 <-> f16`, excluding NaN
  and Inf in both directions), reuse dominating `BitCast`s from CSE, collapse
  nested same-condition `Select` chains, and push `BitCast` through `Select`
  only when the `Select` has no surviving non-bitcast uses (preventing select
  duplication).
- Canonicalize commutative integer binops (`Add`/`Mul`/`And`/`Or`/`Xor`) and
  integer `Cmp` predicates before dominator CSE, separate `XCL_DXIL_NO_OPT=fold`
  from `cse`, and expand flag-neutral `ReadNone` intrinsic DCE.
- Bump `dxil::kernel::TRANSLATOR_VERSION` (7 -> 8) and add validator + RTX 4060
  GPU execution parity tests.

On a 252-program validated direct-DXIL corpus sample (100% across CS/GS/MS/PS/VS):
-3.25% DXIL bytes (-397 KB, 252/252 shrank), -6.33% instructions, -28.74%
bitcasts, -2.30% selects, -38.32% i64 ops, 0 validator errors (and 0 errors
across 977 programs in a 1,000-record sample).

Assisted-by: Google Antigravity (Gemini 4 Neon)
@anes66

anes66 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

CPU-only integer optimizer checks on exact head d73513ab35dd9b57a8c5c72b52478723988b9597: no mismatch found in the tested cases. Companion tests are at 02a2e7e, directly on that head; additions are confined to module/opt.rs's existing #[cfg(test)] module.

Tested

  • Windows 10 Pro 19045, Ryzen 7 9800X3D, Rust 1.100.0 MSVC, debug. No GPU, DXC, or retail input used.
  • 2824 integer folds, widths 1/8/16/32/64, including zero, the sign boundary, all-ones and a mixed-bit pattern. Live sink operands after Module::optimize must equal independently calculated 128-bit CPU arithmetic reduced to the target width. Covers add/subtract/multiply, bitwise operations, defined shifts, unsigned divide/remainder with nonzero divisors.
  • 150 truncation/sign-extension/zero-extension cases across those widths, including negative source values.
  • 64 CSE pairs with opaque nonconstant operands: five commutative operations, subtraction's preserved direction, and all ten reversed signed/unsigned integer predicates, widths 8/16/32/64. One-bit subtraction is intentionally excluded from the directional check because it is commutative modulo 2.
  • cargo test --locked -p xcl --lib gpu::dxil::module::opt::tests:: -- --nocapture --test-threads=1: 4 passed / 0 failed / 0 ignored, no skips (three new tests and the existing discard/CSE test).
  • Three temporary negative controls each failed its corresponding new test: logical instead of arithmetic right shift (i8 0x80 >> 1: 64 instead of 192); zero instead of sign extension (i1 1 -> i8: 1 instead of 255); treating subtraction as commutative. All runtime edits were restored before the final passing run and commit; the published patch adds tests only.

Not tested
Full workspace/GPU suite, validator or serialized bitcode equivalence, float/bitcast-select optimizations, performance, release, retail execution or integration onto newer main. This checks optimized integer IR, not complete shader correctness. No competing upstream PR.

AI use
Codex (GPT-6; exact variant unavailable) wrote the tests and temporary controls, ran CPU validation and prepared this report.

CPU validator follow-up

1176dcc is a separate test-only commit on top of the companion above. Four serialized compute shaders cover a predeclared-but-unused i64 feature, constant i64 arithmetic, the high half of a zero-extended i32, and live i64 multiplication/high extraction. All pass SDK validator 1.9.2602.17; disassembly shows Int64Ops only for the live case. The test creates no D3D12 device and performs no dispatch.

  • cargo test --locked -p xcl --lib cpu_integer_folding_keeps_validator_feature_flags_consistent -- --nocapture --test-threads=1: 1/0/0, no skips.
  • The four optimizer CPU tests above were rerun: 4/0/0, no skips.
  • Both temporary controls are rejected by the validator: retaining a stale flag (declared=1048592, actual=16) and removing a required live flag (declared=16, actual=1048592). Both edits were restored before the final run and commit.

This adds validator coverage only for those four serialized feature cases; the other limits above still apply. No GPU, retail execution or performance check. Codex (GPT-6; exact variant unavailable) prepared and ran this follow-up.

@raylitebull

Copy link
Copy Markdown
Member

Diff audit passed across opt.rs, shader.rs, kernel.rs, and core_tests.rs (bc_only pre-pass, free_bitcast infinity/NaN guards, Int64Ops cleanup, and zext/LShr identities all look solid).

Remaining before merge:

  1. Rebase onto main — #1950 bumped TRANSLATOR_VERSION to 8, and #1947 just landed automatic XCL_DIRECT_DXIL_SOURCE_ID hashing for gpu/dxil sources, so you can drop the manual TRANSLATOR_VERSION bump in kernel.rs.
  2. Let Build and test (Windows, no GPU) run cleanly.
  3. One independent AMD GPU run on the rebased head (current reports on d73513a are NVIDIA + CPU only).

@Decodere

Copy link
Copy Markdown
Contributor Author

@raylitebull Done — rebased cleanly onto main (ae0518c2) at c640e80d and dropped the manual TRANSLATOR_VERSION bump in kernel.rs (relying on #1947's XCL_DIRECT_DXIL_SOURCE_ID). Re-ran gpu::dxil (110 passed, 0 failed), full RTX 4060 release workspace suite (1,087 passed, 0 failed, 46 ignored), and paired 60s scripts/smoke.ps1 (1,568 -> 1,544 frames, 0 crashes/removals); PR description updated. Ready for CI whenever convenient!

AI use: Google Antigravity (Gemini 4 Neon).

@raylitebull

Copy link
Copy Markdown
Member

Rebased head c640e80 (XCL_DIRECT_DXIL_SOURCE_ID via #1947, manual TRANSLATOR_VERSION bump dropped) now passes Build and test (Windows, no GPU) and PR description.

Remaining before merge: one independent AMD GPU run confirming opt_folds_i64_bitcast_selects_and_commutative_cse and gpu::dxil on c640e80 (current reports cover RTX 4060, RTX 3070 on 9ea9ad1, and CPU on d73513a).

@JJAutoCompare

Copy link
Copy Markdown

Tested

Independent Intel Arc A770 verification of clean PR head c640e80d9fdc021109fa745f5854d1c1f13e8470. Windows 11 Enterprise Evaluation 25H2 (26200.9974), Ryzen 7 3800X, Arc A770 driver 32.0.101.9175, Rust/Cargo 1.100.0 (x86_64-pc-windows-msvc), and DXC/DXIL 1.9.2609.5.

  • Prebuilt outside the GPU lock with cargo test --locked -p xcl --lib --no-run (exit 0). The test profile was unoptimized with CARGO_BUILD_JOBS=2, CARGO_INCREMENTAL=0, CARGO_PROFILE_DEV_DEBUG=0, and CARGO_PROFILE_TEST_DEBUG=0. The build used the designated target directory and dedicated TEMP/TMP.
  • Ran the resulting test executable with XCL_ADAPTER=A770 and XCL_DXC_DIR pointing to the verified DXC/DXIL directory. The Arc lock was acquired and released around the test command.
& 'L:/XclTooling/Invoke-ArcTest.ps1' -Test {
    & 'L:\XclTooling\pr1844-71f2ceb-t3-737e5ee5\target\debug\build\xcl\97fdf2b9ff8e1482\out\xcl-97fdf2b9ff8e1482.exe' gpu::dxil::core_tests::opt_folds_i64_bitcast_selects_and_commutative_cse --exact --nocapture --test-threads=1
}
  • 1 passed, 0 failed, 0 ignored, 0 explicit skips (1,063 filtered out, 1.52 s, exit 0). The checked-in DXIL validation and disassembly assertions passed for the synthetic shader and four-window loop. Both wave32 GPU comparisons ran. The synthetic shader returned the expected alternating 4.0f32 bit pattern and zero across all 32 lanes. The one-window loop's direct DXIL and HLSL/DXC outputs matched in VGPRs 2 and 3 for each of the 32 lanes.

Not tested

Full gpu::dxil or workspace suites, wave64, AMD or NVIDIA on this machine, release, retail smoke, and performance.

AI use

T3 Code through the Codex harness (gpt-6.2-sol, high reasoning effort) ran the checked-in test and wrote this report.

…direct DXIL

Extend `gpu::dxil::module::opt` to fold remaining post-phi redundancies in
direct-DXIL shaders without colliding with CFG-level folding or violating DXC
validator shader-flag invariants:

- Enable 64-bit integer constant/identity folding and DCE (`i64` arithmetic,
  shifts, `LShr(ZExt)` / `LShr(Or(ZExt, Shl(ZExt)))` window-high patterns,
  `Trunc(ZExt|SExt)`, and `i1` / `ZExt(i1)` compares) and clear
  `Feature::Int64Ops` in `Shader::infer_type_features` when no surviving
  instruction uses `i64`.
- Fold finite constant `BitCast` (`i32 <-> f32`, `i16 <-> f16`, excluding NaN
  and Inf in both directions), reuse dominating `BitCast`s from CSE, collapse
  nested same-condition `Select` chains, and push `BitCast` through `Select`
  only when the `Select` has no surviving non-bitcast uses (preventing select
  duplication).
- Canonicalize commutative integer binops (`Add`/`Mul`/`And`/`Or`/`Xor`) and
  integer `Cmp` predicates before dominator CSE, separate `XCL_DXIL_NO_OPT=fold`
  from `cse`, and expand flag-neutral `ReadNone` intrinsic DCE.
- Add validator + RTX 4060 GPU execution parity tests (direct-DXIL cache
  invalidation is automatic via `XCL_DIRECT_DXIL_SOURCE_ID`).

On a 252-program validated direct-DXIL corpus sample (100% across CS/GS/MS/PS/VS):
-3.25% DXIL bytes (-397 KB, 252/252 shrank), -6.33% instructions, -28.74%
bitcasts, -2.30% selects, -38.32% i64 ops, 0 validator errors (and 0 errors
across 977 programs in a 1,000-record sample).

Assisted-by: Google Antigravity (Gemini 4 Neon)
@Decodere

Copy link
Copy Markdown
Contributor Author

Rebased cleanly onto main (3da2abb8) at 5ca498af to resolve the core_tests.rs end-of-file test conflict from #1922; module/opt.rs and shader.rs are unchanged from c640e80d.

Re-verified locally on RTX 4060 (release): gpu::dxil (113 passed, 0 failed), full workspace (1,112 passed, 0 failed, 46 ignored), and paired 60 s scripts/smoke.ps1 (1,582 -> 1,568 frames, 0 crashes/removals). Ready for CI and the remaining independent AMD GPU check.

AI use: Google Antigravity (Gemini 4 Neon & Gemini 4 Carbon).

@DavidM1911

Copy link
Copy Markdown
Contributor

Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

Thanks!

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.

7 participants