Skip to content

dxil: guarded-value demand propagation and algebraic/bitcast folding in opt - #1972

Open
raylitebull wants to merge 1 commit into
xcl-dev:mainfrom
raylitebull:feat/dxil-opt-select-guard-prop
Open

raylitebull wants to merge 1 commit into
xcl-dev:mainfrom
raylitebull:feat/dxil-opt-select-guard-prop

Conversation

@raylitebull

@raylitebull raylitebull commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Adds guarded-value demand propagation (propagate_select_guards) and full-EXEC lane-bit folding (and(lshr(-1, s), 1) -> 1) inside crates/xcl/src/gpu/dxil/module/opt.rs to eliminate redundant select chains on lowered RDNA shader IR before DXIL serialization.

Part of #1269.

What is in it

  • crates/xcl/src/gpu/dxil/module/opt.rs (+588 / -63 across opt.rs + graphics_tests.rs, gated by XCL_DXIL_NO_OPT=guard):
    • propagate_select_guards (guard_eligible): propagates boolean/mask guard conditions backward to strictly lane-local, side-effect-free guarded instructions when all observed consumers use a single guarded operand (pre-seeding Op::Phi incoming operands as Demand::Any before the reverse-RPO walk, chasing nested select replacements transitively, and restricting dx.op.* intrinsics in guard_eligible to a strict lane-local math/bit/conversion allowlist op_code in 6..=42 | 44..=56 | 124..=132 so quad derivatives 83..=86, Eval* 87..=89, Wave*/Quad*, and implicit-LOD texture ops always receive Demand::Any).
    • known_lt_32 & full-EXEC lane-bit fold (and(lshr(-1, s), 1) -> 1) inside run_cse_simplify, while preserving local.clear() across dx.op.discard for wave/quad operations.
    • Unit tests (gpu::dxil::module::opt::tests): block_cse_invalidates_wave_and_quad_calls_across_discard, guard_demand_eliminates_chained_select_and_bitcast, loop_header_phi_preserves_latch_select_guard, full_exec_lanebit_folds_to_true, guarded_derivatives_and_cross_lane_ops_preserve_select_operands, and optimized_valu_chain_validates_with_dxil.
  • crates/xcl/src/gpu/dxil/graphics_tests.rs: add guarded_derivatives_read_neighbor_values (DXIL validation + disassembly check + fullscreen 8x8 quad-derivative draw test).
  • (Dropped overlapping simplify_op rules so this PR stays orthogonal to Recompiler: fold 64-bit ints, bitcast selects and commutative CSE in direct DXIL #1906, and relies on Recompiler: direct DXIL cache entries change when its sources do #1947 XCL_DIRECT_DXIL_SOURCE_ID instead of a manual TRANSLATOR_VERSION bump.)

Tested

  • Toolchain: Windows 11 x64, rustc 1.99.1 (58cf8f9c3 2026-10-13), DXC dxcompiler 1.8.2502.11 / dxil 1.8.2502.11, rebased cleanly onto 13c2a405 (528ca109).
  • cargo check --workspace --tests: passed (0 warnings in touched files).
  • cargo test -p xcl --lib gpu::dxil::module::opt::tests: 11 passed, 0 failed (dxil 1.8.2502.11 validated, including #2194 simplify_cfg tests and guarded_derivatives_and_cross_lane_ops_preserve_select_operands).

Regression run

  • Standalone scripts/smoke.ps1 pair and GPU guarded_derivatives_read_neighbor_values on 528ca109 vs 13c2a405 have not been run yet. AMD and NVIDIA reviewers are invited to test on 528ca109 vs 13c2a405 (including guarded_derivatives_read_neighbor_values, scripts/smoke.ps1, and XCL_DIRECT_DXIL=1) and post results in the comments.

Not tested

  • GPU guarded_derivatives_read_neighbor_values and 60 s scripts/smoke.ps1 pair on 528ca109, full cargo test --workspace suite on 528ca109, runtime GPU execution across AMD / NVIDIA / Intel hardware, and Linux/Wine/vkd3d-proton.

AI use

  • Antigravity assisted with implementation, rebase onto 13c2a405, cross-lane allowlist hardening, and DXIL/draw validation tests; the author reviewed the diff and test output.

@futurepro62

futurepro62 commented Nov 25, 2026 •

Copy link
Copy Markdown

Full-suite run, since this PR has no test report yet. Tested exact head c04f6c6 (on its base 80f4819).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 621.40, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.100.0 MSVC, DXC + dxil.dll 1.9.2602.17 (Windows SDK 10.0.26100), debug, D3D12 debug layer installed.
  • cargo build --workspace, then XCL_REQUIRE_GPU=mesh cargo test --workspace -- --test-threads=4 --skip heap_window_out_of_memory_falls_back_to_the_switch_form --skip gpu::recomp::lower_dxil::tests::f16_programs_on_the_gpu --skip gpu::recomp::lower_dxil::tests::f32_programs_on_the_gpu --skip gpu::recomp::lower_dxil::tests::integer_programs_on_the_gpu --skip gpu::recomp::lower_dxil::tests::f64_programs_on_the_gpu --skip gpu::recomp::lower_dxil::tests::const_and_null_mask_operands_agree_with_hlsl_on_the_gpu --skip gpu::dxil::fuzz_tests: 985 passed, 0 failed, 43 ignored. SKIPPED (no wave64): a_2d_or_3d_group_agrees_with_the_hlsl_path_on_the_gpu, a_per_lane_2d_or_3d_group_runs_on_the_gpu, coalesced_guarded_runs_agree_with_the_hlsl_path_on_the_gpu, cross_lane_reads_agree_with_the_hlsl_path_on_the_gpu, gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware, the_wave64_lowering_agrees_with_the_hlsl_path_on_the_gpu.
  • The new tests ran and passed: guard_demand_eliminates_chained_select_and_bitcast, full_exec_lanebit_and_zext_cmp_and_const_bitcast_fold, optimized_valu_chain_validates_with_dxil.
  • Same head on the AMD Radeon integrated GPU (iGPU) of the Ryzen 7 9800X3D (RDNA2, XCL_ADAPTER=radeon), cargo test --workspace -- --test-threads=4 --skip gpu::dxil::fuzz_tests::fuzz_validate_and_gpu_1: 995 passed, 0 failed, 45 ignored. SKIPPED: f16_programs_on_the_gpu (f16 arithmetic, wave32, per-lane form: refused (unsupported V_MUL_F16 (its gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426 semantics differ from the console's))), f16_programs_on_the_gpu (f16 arithmetic, wave64, per-lane form: refused (unsupported V_MUL_F16 (its gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426 semantics differ from the console's))), f16_programs_on_the_gpu (f16 packed, wave32, per-lane form: refused (unsupported V_PK_MUL_F16: VOP3 modifiers (its gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426 semantics differ from the console's))), f16_programs_on_the_gpu (f16 packed, wave64, per-lane form: refused (unsupported V_PK_MUL_F16: VOP3 modifiers (its gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426 semantics differ from the console's))), f32_programs_on_the_gpu (f32 conversions, wave32, per-lane form: refused (unsupported V_CVT_F16_F32 (its gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426 semantics differ from the console's))), f32_programs_on_the_gpu (f32 conversions, wave64, per-lane form: refused (unsupported V_CVT_F16_F32 (its gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426 semantics differ from the console's))), heap_window_out_of_memory_falls_back_to_the_switch_form (no heap windows).
  • --skip leaves out tests that fail on main 80f4819 too, not because of this PR. On NVIDIA: heap_window_out_of_memory_falls_back_to_the_switch_form (Tests: heap_window_out_of_memory_falls_back_to_the_switch_form fails under XCL_REQUIRE_GPU=mesh (opt-in skip counted as missing coverage) #1651), the four gpu::recomp::lower_dxil::tests::*_programs_on_the_gpu tests and const_and_null_mask_operands_agree_with_hlsl_on_the_gpu (follow-up on #1651) fail because runner::skip_test turns their skips into failures under XCL_REQUIRE_GPU=mesh, and gpu::dxil::fuzz_tests seeds 70, 545, 1019 and 1507 fail CreateComputePipelineState with E_OUTOFMEMORY on this card (drivers 616.64 and 621.40). On AMD: fuzz_validate_and_gpu_1 fails on seed 540 (res[833] 0x7 vs CPU 0x6). The AMD run does not set XCL_REQUIRE_GPU.

Not tested

  • a release build, a game (test run only).

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.

@WebIdentity1

WebIdentity1 commented Nov 25, 2026 •

Copy link
Copy Markdown

e3dfb2e: derivative repair verified on RTX 3090; small unit-test correction

Responding to the NVIDIA retest request: the runtime repair on exact e3dfb2e02ce639f3ca84ce130bbaef1dcc6a9493 produces all 256 correct derivative output components. Our earlier loop regression also remains correct for all 128 words. Credit to @philip-roy-jones for the derivative diagnosis/fixture and @raylitebull for the runtime repair.

One remaining failure is in the new unit test, not the GPU output. guarded_derivatives_and_cross_lane_ops_preserve_select_operands creates four identical selects, then asserts each derivative retains its original instruction ID. CSE legitimately shares the first select: opcode84 gets Inst(2) rather than its original Inst(6). The small test-only patch below checks Op::Select(c, two, nine) instead, retaining the exact predicate and both alternatives. The existing lane-local FAbs-fold check remains intact.

Tested — native Windows10 Home19045, Ryzen7800X3D, RTX3090 driver591.74 (32.0.15.9174), Rust/Cargo1.98.1MSVC, DXC/DXIL1.8.2502.11, debug. XCL_ADAPTER=3090, XCL_SPLIT_WAVE64=1; runner printed the actual adapter.

cargo test --locked -p xcl --lib -- guarded_derivatives guarded_value_keeps_its_loop_carried_use_on_gpu gpu::dxil::module::opt::tests --test-threads=1 --show-output
Snapshot Passed / failed / ignored / skipped Derivative wrong components
Author runtime and unit tests + diagnostics/earlier loop fixture 7 / 1 / 0 / 0 0/256; unit-ID assertion fails
Same + test-only correction below 8 / 0 / 0 / 0 0/256
Same corrected tests, only intrinsic-call eligibility restored to old ReadNone && !f64 catch-all 6 / 2 / 0 / 0 128/256; corrected unit test also rejects constant input

The negative control is a single-rule overlay on this head, not a parent checkout. It keeps the author's earlier loop repair, which passes in all snapshots. The pre-correction negative control also gave 6/2/0/0 and the same 128 wrong components. The first pixel is [0,0,0,0] with the old call rule and [7,7,7,7] with the repair.

Test-only diagnostics count the complete 8×8×4 readback and print the adapter; the draw's disassembly assertion was moved after readback so the negative control actually executes the shader. No assertion was removed. All four 319-file manifests match before/after and local snapshots; XCL rebuilt each time.

Not tested — full workspace, retail smoke, new AMD/Intel runs, compilation time or memory improvement. The six optimizer units include the existing chain-reduction check, but that is not a timing measurement. No runtime patch, commit/push or competing PR from this follow-up; required merge checks remain separate.

AI use — Codex (GPT-6) reviewed the new head, ran the comparison, diagnosed/corrected the unit-test identity assertion and prepared this report.

Test-only correction against e3dfb2e
diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs
index 48a6999..eeedad0 100644
--- a/crates/xcl/src/gpu/dxil/module/opt.rs
+++ b/crates/xcl/src/gpu/dxil/module/opt.rs
@@ -1045,7 +1045,7 @@ mod tests {
             let d = m.call(unary_f32, &[op_c, s]);
             let guarded = m.select(c, d, neg1);
             let _ = m.call(sink, &[guarded]);
-            deriv_calls.push((op_code, d, s));
+            deriv_calls.push((op_code, d));
         }
         // Contrast: a pure lane-local unary op (`FAbs` = 6) under the same outer guard
         // still propagates `Guard(c)` and bypasses its inner `select(c, 2.0, 9.0)`.
@@ -1058,13 +1058,17 @@ mod tests {
 
         m.optimize();
 
-        for (op_code, d, s) in deriv_calls {
+        for (op_code, d) in deriv_calls {
             let Value::Inst(di) = d else { unreachable!() };
             match &m.insts[di as usize].op {
-                Op::Call(_, args) => assert_eq!(
-                    args[1], s,
-                    "quad derivative opcode {op_code} must preserve select operand (not rewrite to constant 2.0)"
-                ),
+                Op::Call(_, args) => {
+                    // CSE may share the identical input selects; check the expression, not its ID.
+                    let Value::Inst(input) = args[1] else {
+                        panic!("quad derivative opcode {op_code} lost its select operand: {:?}", args[1]);
+                    };
+                    assert_eq!(Op::Select(c, two, nine), m.insts[input as usize].op,
+                        "quad derivative opcode {op_code} must preserve both input alternatives");
+                },
                 other => panic!("unexpected op for derivative {op_code}: {other:?}"),
             }
         }

Update: the author's repair at 6e1b44f2736825759c78194096f8afe64725c75c resolves this GPU reproducer. Tested that head with only the same 55-line GPU regression appended; none of my proposed optimizer changes were applied. The narrower phi-operand seeding passes, including the author's new loop test and the original guard-chain simplification test: 6 passed / 0 failed / 0 ignored, zero skips. All 128 GPU output words match; inactive/active carried values are [43, 8].

cargo test --locked -p xcl --lib -- guarded_value_keeps_its_loop_carried_use_on_gpu gpu::dxil::module::opt::tests --test-threads=1 --show-output

Same native Windows 10 19045 / Ryzen 7800X3D / RTX 3090 driver 591.74 / Rust 1.98.1 MSVC / DXC 1.8.2502.11, debug; XCL_ADAPTER=3090, XCL_REQUIRE_GPU=wave64,mesh, XCL_SPLIT_WAVE64=1, XCL_DIRECT_DXIL unset. All 311 source hashes matched before and after, and the build recompiled XCL. This closes the specific wrong-output finding below. No new full-suite, retail, AMD or performance result is claimed. AI use for this follow-up: Codex (GPT-6), source review, running the existing regression and report preparation.

Original reproducer, proposed patch and earlier results

Confirmed a wrong-output regression in propagate_select_guards at c04f6c6f81280a63389d01b101500448212694c9. A phi is initialized as Demand::Any, but its operands receive that demand only when the reverse walk reaches the loop header. By then the latch definition has already been visited, so the demand does not reach its inputs. A value shared with a guarded consumer can therefore lose its select even though the next iteration needs its inactive value.

The public synthetic loop forms v = select(active, 7, 42), uses v + 1 unconditionally through the header phi, and separately observes v * 3 only under active. After two iterations, inactive lanes must carry 43, not 8.

Tested — native Windows 10 19045, Ryzen 7 7800X3D, RTX 3090 driver 591.74, Rust 1.98.1 MSVC, DXC 1.8.2502.11, debug:

cargo test --locked -p xcl --lib -- guarded_value_keeps_its_loop_carried_use_on_gpu gpu::dxil::module::opt::tests --test-threads=1 --show-output
  • Parent 80f4819 + regression: 2 passed / 0 failed / 0 ignored, all 128 GPU output words correct.
  • Exact PR head + regression: 4 passed / 1 failed / 0 ignored. Existing optimizer checks pass, but the GPU test gets 32/128 words wrong: the inactive lanes carry 8 rather than 43.
  • PR head + the seven-line fix and regression below: 5 passed / 0 failed / 0 ignored, all 128 words correct. No skips in these focused runs. The original guard-chain test still gets one select and three bitcasts, retaining its intended simplification.

The fix seeds every non-eligible instruction's operands as unconditionally demanded before the reverse walk, including phi back-edge operands. It keeps the traversal linear and does not disable guarded-value optimization.

Full comparison: cargo build --locked --workspace passed on head+test and candidate. cargo test --locked --workspace --no-fail-fast -- --test-threads=4 --show-output returned 995 passed / 2 failed / 45 ignored on each, across 20 targets, with identical 26 SKIPPED messages (19 wave64 subcases, three refused per-lane subcases, two debug-layer checks, driver-cache-disable and heap-window checks).

The failure sets differ: head fails the new loop test plus the known gpu_clamp_and_omod_per_instruction; candidate fixes the loop but additionally hits d32s8_targets_take_their_own_size_of_video_memory at CommandList::Close (0x80004005). The unchanged candidate passes that depth test in isolation 1/0/0, no skip. That test is byte-identical across the pair and has previously failed on a separate main baseline in our #1834 comparison; its intermittent failure is not diagnosed here. The full suite is not green. All source snapshots matched 311-file SHA256 manifests before/after; source switches forced recompilation.

Candidate fix and GPU regression (62 added lines)
diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs
index 183b793..bcd6c7c 100644
--- a/crates/xcl/src/gpu/dxil/module/opt.rs
+++ b/crates/xcl/src/gpu/dxil/module/opt.rs
@@ -509,6 +509,13 @@ impl Module {
                 eligible[idx] = elig;
                 if !elig {
                     demand[idx] = Demand::Any;
+                    // Seed every unconditional use before the reverse walk. A phi's
+                    // back-edge operands may be defined in blocks visited before it.
+                    self.insts[idx].op.for_each_operand(|v| {
+                        if let Value::Inst(j) = resolve(repl, v) {
+                            demand[j as usize] = Demand::Any;
+                        }
+                    });
                 }
             }
         }
diff --git a/crates/xcl/src/gpu/dxil/tests.rs b/crates/xcl/src/gpu/dxil/tests.rs
index af8d2e9..f54d539 100644
--- a/crates/xcl/src/gpu/dxil/tests.rs
+++ b/crates/xcl/src/gpu/dxil/tests.rs
@@ -216,3 +216,58 @@ fn batched_replacements_match_one_at_a_time() {
         panic!("validator rejected the kernel:\n{e}");
     }
 }
+
+/// A guarded value also feeds the next iteration through an unconditional phi.
+/// A reverse pass must account for that back-edge use before rewriting its inputs.
+#[test]
+fn guarded_value_keeps_its_loop_carried_use_on_gpu() {
+    if runner::adapter().is_err() {
+        return runner::skip_test("no GPU");
+    }
+    let mut s = Shader::new(Stage::Compute, (6, 6));
+    let io = s.raw_uav(0, 0);
+    let res = s.raw_uav(1, 0);
+    let lane = s.thread_id_in_group(0);
+    let i32 = s.m.i32();
+    let (zero, one, two, three) = (s.m.i32c(0), s.m.i32c(1), s.m.i32c(2), s.m.i32c(3));
+    let (seven, old) = (s.m.i32c(7), s.m.i32c(42));
+    let off = s.m.bin(BinOp::Shl, lane, two);
+    let input = s.raw_load(io, off, 1)[0];
+    let active = s.m.cmp(Pred::Ne, input, zero);
+    let entry = s.m.current_block();
+    let header = s.m.new_block();
+    let body = s.m.new_block();
+    let exit = s.m.new_block();
+    s.m.br(header);
+    s.m.set_block(header);
+    let count = s.m.phi(i32);
+    let carried = s.m.phi(i32);
+    s.m.add_incoming(count, zero, entry);
+    s.m.add_incoming(carried, zero, entry);
+    let again = s.m.cmp(Pred::ULt, count, two);
+    s.m.cond_br(again, body, exit);
+    s.m.set_block(body);
+    let guarded = s.m.select(active, seven, old);
+    let next = s.m.bin(BinOp::Add, guarded, one);
+    let product = s.m.bin(BinOp::Mul, guarded, three);
+    let observed = s.m.select(active, product, zero);
+    s.raw_store(res, off, &[observed]);
+    let increment = s.m.bin(BinOp::Add, count, one);
+    s.m.br(header);
+    s.m.add_incoming(count, increment, body);
+    s.m.add_incoming(carried, next, body);
+    s.m.set_block(exit);
+    let row = s.m.i32c(64 * 4);
+    let final_off = s.m.bin(BinOp::Add, off, row);
+    s.raw_store(res, final_off, &[carried]);
+    let dxil = s.finish([64, 1, 1], None);
+    validate::validate(&dxil).expect("valid loop DXIL");
+    let state = runner::KernelState { sgpr: (0..128).map(|lane| lane % 2).collect(), ..Default::default() };
+    let got = runner::run(&dxil, &state, &[]).expect("GPU loop");
+    let want: Vec<u32> = (0..128).map(|i| match (i < 64, i % 2) {
+        (true, 0) => 0, (true, _) => 21, (false, 0) => 43, (false, _) => 8,
+    }).collect();
+    let wrong = got.raw[..128].iter().zip(&want).filter(|(a, b)| a != b).count();
+    println!("guarded loop: {wrong}/128 mismatches; carried lanes 0/1 = {:?}", &got.raw[64..66]);
+    assert_eq!(&got.raw[..128], &want);
+}

Not tested: retail shaders/gameplay/smoke, AMD/native wave64, or measured compile-time/memory benefit. This is a synthetic DXIL-loop correctness finding; no merge-readiness claim. No competing PR or source push.

AI use: Codex with GPT-6 Astra inspected the pass, wrote the candidate and synthetic GPU regression, ran the Windows comparisons, and drafted this report.

@raylitebull

Copy link
Copy Markdown
Member Author

Overlap note: full credit to #1906 (@Decodere), which already covers the shared simplify_op constant BitCast, nested same-condition Select, zext(i1) compare, and select(c, 1, 0) folding in module/opt.rs.

Once #1906 lands (or in our next update), we will trim #1972 down to only the independent propagate_select_guards pass and known_lt_32 bitmask rules, and address @WebIdentity1's loop-header phi Demand::Any latch-propagation catch.

@raylitebull
raylitebull force-pushed the feat/dxil-opt-select-guard-prop branch from c04f6c6 to 6e1b44f Compare November 25, 2026 00:48
@raylitebull

Copy link
Copy Markdown
Member Author

Thanks for catching and proving the loop-header phi case, @WebIdentity1!

Updated #1972 cleanly on top of 6567c5f in commit 6e1b44f (crates/xcl/src/gpu/dxil/module/opt.rs):

  1. Pre-seed Op::Phi incoming operands as Demand::Any before the reverse-RPO walk in propagate_select_guards so back-edge phi consumers visited after the loop latch cannot leave a Guard(c) requirement on a latch value.
  2. Transitive nested select(g, ...) chasing when repl[idx] replaces an eligible select(g, t, _).
  3. Added regression test loop_header_phi_preserves_latch_select_guard.

Verified locally with cargo check --workspace --tests, cargo test -p xcl --lib gpu::dxil::module::opt::tests (5 passed, 0 failed, dxil 1.8.2502.11 validated), and loop_entered_in_the_middle_is_split (1 passed, 0 failed).

@raylitebull
raylitebull force-pushed the feat/dxil-opt-select-guard-prop branch from 6e1b44f to 8d419c0 Compare November 25, 2026 01:12
@raylitebull

Copy link
Copy Markdown
Member Author

Trimmed and rebased #1972 cleanly onto aa9ab8a in commit 8d419c0:

  • Dropped the shared simplify_op constant BitCast/Select/zext(i1) rules that overlap with #1906 (thanks @Decodere!), keeping ONLY propagate_select_guards (with loop-header Op::Phi operand Demand::Any pre-seeding per @WebIdentity1's catch + transitive select chasing), known_lt_32 + full-EXEC lane-bit fold (and(lshr(-1, s), 1) -> 1), run_cse_simplify, and TRANSLATOR_VERSION 8 -> 9.
  • Verified with cargo check --workspace --tests and cargo test -p xcl --lib gpu::dxil::module::opt::tests (5 passed, 0 failed, dxil 1.8.2502.11 validated).

@Fran-co-F

Copy link
Copy Markdown

RADV numbers for the two ScreenProbes giants: the guard pass cuts ActivateProbes' driver build from 281 s to 105 s, and does not help ActivateRays, which still runs out of memory.

Setup: RX 9070 XT 16 GB (RDNA4), Mesa 26.3.1 RADV (ACO), Ryzen 7 9800X3D, 32 GB RAM, CachyOS. Wine 11.17, vkd3d-proton ec20719 (release, @0naku's two dxil-spirv patches). This PR's head 8d419c0 merged into my local tree (Wine fixes, local diagnostics, and the DXC optimizer patch from my comment on #1426, which runs after the translator in both arms), release, cross-built. Each program built alone: xcl shaders shaders.rpf --precompile --only cs --pipelines, with a local filter to one record hash. Settings: XCL_DIRECT_DXIL=all, the DXC optimizer pass list from #1426, cold (MESA_SHADER_CACHE_DISABLE=true, VKD3D_SHADER_CACHE_PATH=0, a new translation cache per arm), and a systemd scope with MemoryMax=26G, no swap. The control arm is the same binary with XCL_DXIL_NO_OPT=guard. One run per arm.

program XCL_DXIL_NO_OPT=guard this PR
CS_ScreenProbes_ActivateProbes (56c0cd3b82a00c6e) 281 s, 1.6 GB peak 105 s, 3.0 GB peak
CS_ScreenProbes_ActivateRays (95cc13288a27a96e) over 26 GB at 31 s over 26 GB at 30 s
  • On ActivateProbes, the pass shrinks the translated DXIL by 4.4 % (3 457 829 → 3 307 013 bytes), and the build takes less than half the time.
  • On ActivateRays, the pass changes the translated DXIL by 0.13 % (1 456 029 → 1 454 157 bytes). RADV still grows past 26 GB, as in Recompiler: nest the compact dispatch of big programs by default #2025's RADV numbers on the HLSL path.
  • Both arms ran the same DXC pass list after the translator, so the difference is this PR's pass.
  • Why it matters in the title: on this machine, ActivateProbes holds the single huge-compile slot for minutes during world load. The 15 xcl-pso workers wait in big_compile_turn, and the title's watchdog (+0x23cf683) ends the run.

Not tested: more than one run per arm, other programs, Windows.

AI use: Claude Code (Claude Opus 5.5) ran the builds on my machine and wrote this.

@philip-roy-jones

philip-roy-jones commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

RX 580 retest of the author’s fix at e3dfb2e02ce639f3ca84ce130bbaef1dcc6a9493

The 8×8 draw on the updated PR returned all 256 expected output components. At the author’s requested reference 94193f0c8a4a01bf6d3ca3cd2e3a608f0444eb84, copying only the new draw test gave the same result. The PR commit’s immediate Git parent is a1a2978. Author’s update

  • With XCL_DIRECT_DXIL=1, xcl-gpu run cargo test --locked -p xcl --lib guarded_derivatives -- --test-threads=1 --nocapture gave 1 passed, 1 failed, 0 ignored, 0 skipped on the PR. The GPU draw passed. The optimizer unit test failed for derivative opcode 84, comparing Inst(2) with Inst(6) after common subexpression elimination. On the reference with the draw fixture added, the same command filtered to guarded_derivatives_read_neighbor_values gave 1 passed, 0 failed, 0 ignored, 0 skipped. Windows CI failure
  • In a separate test-only experiment on e3dfb2e, the fixture constructed its identical input select once before the four derivative calls. With all original assertions in place, cargo test --locked -p xcl --lib guarded_derivatives_and_cross_lane_ops_preserve_select_operands -- --test-threads=1 --nocapture gave 1 passed, 0 failed, 0 ignored, 0 skipped.
  • On both clean trees I ran cargo build --locked --workspace -j 4 and xcl-gpu run cargo test --locked --workspace --no-fail-fast -- --test-threads=4 --show-output. The full suites used default backend selection. The failing optimizer unit test was the sole additional failure on the PR. Both suites had the same 65 explicit skips, included in their pass counts.
Clean checkout Passed Failed Ignored Explicit skips
Reference 94193f0 1034 109 46 65
PR e3dfb2e 1042 110 46 65

Both release builds exited early with 0xc0000409 during the 60-second retail smoke. Neither produced a final frame count. I used cargo build --release --locked -p xcl -j 4 and xcl-gpu run powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\smoke.ps1 -Game <folder> -Title Retail -Seconds 60 -Xcl <release-xcl.exe> with XCL_DIRECT_DXIL=1 and separate, initially empty data and DXIL-cache directories.

Generated smoke blocks for the reference and updated PR
xcl-smoke v1
commit: 94193f0c8a4a01bf6d3ca3cd2e3a608f0444eb84
gpu: Radeon RX 580 Series
title: Retail
seconds: 60
exit: 0xc0000409
frames shown: none logged (the run did not reach its end)
presents per 2 s (last 3): 39 57 8
device removals: 0
crashes: 0
peak commit: 11004 MB
xcl-smoke v1
commit: e3dfb2e02ce639f3ca84ce130bbaef1dcc6a9493
gpu: Radeon RX 580 Series
title: Retail
seconds: 60
exit: 0xc0000409
frames shown: none logged (the run did not reach its end)
presents per 2 s (last 3): 60 57 4
device removals: 0
crashes: 0
peak commit: 11002 MB

Radeon RX 580 (31.0.21925.1001), Ryzen 7 7700X, Windows 11 Pro 26200.9974, Rust 1.100.0 MSVC, DXC and validator 1.9.2609.5. OpenAI Codex, GPT-6.2 Astra at maximum reasoning effort, ran the retest and prepared these results.


RX 580 GPU readback at 8d419c0 — a pixel shader with alternating lane predicates returned [0, 0, 0, 0] at pixel (0, 0). The expected result is [7, 7, 7, 7]. The same draw matched the CPU expectation at all 64 pixels on the PR’s parent, on the PR with XCL_DXIL_NO_OPT=guard, and with a local change that preserves derivative inputs. Reviewed patch and regression test · Original measurement claim

The 8×8 draw uses XCL’s direct DXIL builder. On this head, a source search found explicit calls to Shader::deriv in builder tests only. For each axis, even pixels supply 2 and odd pixels supply 9. The shader evaluates the coarse and fine derivatives across the quad, then selects the derivative for even pixels and −1 for odd pixels. DXC’s validator accepted the shader in every run.

Tested

  • Windows 11 Pro 25H2 (26200.9974), Ryzen 7 7700X, Radeon RX 580 (31.0.21925.1001), Rust 1.100.0 MSVC, DXC and validator 1.9.2609.5. All GPU work went through the shared FIFO.
  • I appended guarded_derivatives_read_neighbor_values to the graphics tests. xcl-gpu run cargo test --locked -p xcl --lib guarded_derivatives_read_neighbor_values -- --test-threads=1 --nocapture gave 1 passed on parent aa9ab8a3e7b738ec48899e37805f6a7d2d22da53, 1 failed on head 8d419c01b1a0aba6e04c9dea8b9e7b795816e65e, 1 passed with the guard pass disabled on that head, and 1 passed with the local repair and the pass enabled. All four runs had 0 ignored and 0 skipped.
  • xcl-gpu run cargo test --locked --workspace --no-fail-fast -- --test-threads=4 --show-output (debug, default backend selection, sample variables unset) produced the counts below. The 97 failing test names and the 61 explicit skips matched across all three trees. Libtest includes those skips in its pass count.
Tree Passed Failed Ignored Explicit skips
Clean parent 985 97 46 61
Clean PR head 989 97 46 61
PR head with local repair and new draw test 990 97 46 61

With the repair, the existing five optimizer tests passed. The separate native-wave64 compute test gpu_divergence_through_exec also passed with XCL_DIRECT_DXIL=1. Both filtered runs had 0 failures, 0 ignored and 0 explicit skips.

Retail shader compilation

I translated five compute records in release with four memory windows and --split 0. On all five, the PR and local repair produced byte-identical validated DXIL and static samplers. CPU times are medians for translate_compute after one warm-up per process, with six measurements per revision and the order rotated across parent, PR and repair. PSO times are medians for the first CreateComputePipelineState on the RX 580, with three interleaved trials per revision. Parentheses give the range.

Record hash DXIL bytes, parent → PR DXIL select i1, parent → PR CPU translation, ms, parent → PR → repair First PSO, s, parent → PR
06ac9019d1c01f0e 206,000 → 205,396 3,729 → 3,693 30.0 → 34.7 → 35.3 4.29 (4.18–12.54) → 4.72 (4.15–13.95)
2e0055c25f49848a 234,292 → 231,280 4,792 → 4,736 31.5 → 38.4 → 39.1 —
6e148dbd563de205 305,204 → 301,244 5,631 → 5,568 43.0 → 54.0 → 54.6 —
95cc13288a27a96e 3,888,520 → 3,615,432 79,816 → 68,576 779.0 → 785.2 → 830.4 —
c5696074df0b1cbc 419,420 → 407,132 8,359 → 7,814 80.4 → 94.7 → 85.5 59.19 (54.39–61.92) → 58.54 (51.55–64.14)

To reproduce a row’s shader output, run xcl shaders <pack> --direct --hash <record-hash> --validate --split 0 --windows 4 --threads 1 --timeout 90 --dump <dir>. The driver builds used each record’s static samplers, the XCL ABI root signature, an empty cached-PSO field and a fresh executable name per first-use trial. Windows returned 0x887a002d from ShaderCacheControl. Repeating the same executable for 06ac9019d1c01f0e took 1.3 ms on the parent and 6.1 ms on the PR. These are first-call timings with the driver’s implicit cache available. The largest record, 95cc13288a27a96e, requests wave32 and was checked through DXIL validation only.

A separate seeded retail sample (xcl shaders <pack> --direct --validate --seed 1972 --sample 96 --split 0 --windows 4 --threads 1 --max-bytes 0 --timeout 90) validated 96 programs per revision, including 51 pixel shaders, 29 mesh, 10 compute, 4 vertex and 2 geometry. The parent and PR differed on 95 programs, reducing total DXIL from 10,932,744 to 10,438,868 bytes (4.52%). All 96 PR outputs matched the repair byte for byte.

On the largest record, disabling guard propagation on the PR head left 68,620 scalar selects and 3,616,632 DXIL bytes. Turning it back on removed another 44 selects and 1,200 bytes. Most of the 11,240-select reduction from the parent was already present with that pass disabled. Each shader timed on the driver had both faster and slower PR trials. All driver trials and 78 of the 90 CPU observations finished before an Orca restart. The remaining 12 CPU observations used the same binaries and settings afterward.

Regression run

Both release builds ran xcl-gpu run powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\smoke.ps1 -Game <folder> -Title Retail -Seconds 60 -Xcl .\target\release\xcl.exe on the RX 580 with XCL_DIRECT_DXIL=1 and separate, initially empty XCL data and DXIL-cache directories.

Generated smoke blocks, parent and PR head
xcl-smoke v1
commit: aa9ab8a3e7b738ec48899e37805f6a7d2d22da53
gpu: Radeon RX 580 Series
title: Retail
seconds: 60
exit: 0xc0000409
frames shown: none logged (the run did not reach its end)
presents per 2 s (last 3): 3 51 24
device removals: 0
crashes: 0
peak commit: 10240 MB
xcl-smoke v1
commit: 8d419c01b1a0aba6e04c9dea8b9e7b795816e65e
gpu: Radeon RX 580 Series
title: Retail
seconds: 60
exit: 0xc0000409
frames shown: none logged (the run did not reach its end)
presents per 2 s (last 3): 55 60 9
device removals: 0
crashes: 0
peak commit: 10975 MB

Not tested

Execution of the retail shader records with game inputs, other adapters, and world-load completion. The clean parent and PR head both terminated early with 0xc0000409 in their 60-second RX 580 title smokes with XCL_DIRECT_DXIL=1. Neither produced a final frame count.

AI use

OpenAI Codex, GPT-6.2 Astra at maximum reasoning effort, wrote the synthetic shader and local repair, ran the checks and prepared the report.

@raylitebull
raylitebull force-pushed the feat/dxil-opt-select-guard-prop branch from 8d419c0 to e3dfb2e Compare November 25, 2026 02:08
@raylitebull

Copy link
Copy Markdown
Member Author

Thanks for the RX 580 repro and clear root-cause diagnosis, @philip-roy-jones!

Fixed the cross-lane quad-derivative miscompilation in e3dfb2e (rebased cleanly onto 94193f0, also dropping the redundant kernel.rs TRANSLATOR_VERSION bump after #1947):

  • Root cause (opt.rs::guard_eligible): guard_eligible previously allowed any FnAttrs::ReadNone call (not ending in .f64) to propagate per-lane select guards to its operands, which swept quad derivatives (dx.op.unary.* opcodes 83..=86, DerivCoarseX/Y and DerivFineX/Y) into guarded simplification because they share the ReadNone declaration with lane-local math.
  • Strict lane-local allowlist: replaced the ReadNone catch-all in guard_eligible with an explicit allowlist of strictly lane-local, non-trapping dx.op.* intrinsics (op_code in 6..=42 | 44..=56 | 124..=132 — pure math/bit/conversion ops only). All cross-lane ops (83..=86 derivatives, 87..=89 Eval*, Wave*/Quad*, implicit-LOD texture ops, handle constructors 216..=218) return false and keep Demand::Any.
  • Regression tests added: opt::tests::guarded_derivatives_and_cross_lane_ops_preserve_select_operands and graphics_tests::guarded_derivatives_read_neighbor_values (DXIL validation/disasm + 8x8 fullscreen draw test).

Pushed e3dfb2e for GitHub Actions Build and test and fresh RX 580 / NVIDIA re-testing!

@philip-roy-jones

Copy link
Copy Markdown
Contributor

@raylitebull, here is the patch for the quad-derivative readback on 8d419c0. The guard pass treats dx.op.unary as lane-local because it is marked readnone. Its four derivative opcodes read neighboring lanes. If an even pixel reads a derivative, the odd pixel’s selected input still matters.

The patch keeps those four calls out of guard propagation. The added 8×8 draw checks coarse and fine differences in both directions. On the RX 580, the first pixel went from four zeroes to four sevens, and the repaired shader matched all 256 expected output components. GPU test report

Patch against 8d419c0 (apply with git apply)
diff --git a/crates/xcl/src/gpu/dxil/graphics_tests.rs b/crates/xcl/src/gpu/dxil/graphics_tests.rs
index d2d8f88..28349ef 100644
--- a/crates/xcl/src/gpu/dxil/graphics_tests.rs
+++ b/crates/xcl/src/gpu/dxil/graphics_tests.rs
@@ -939,6 +939,52 @@ fn fullscreen_vs() -> Vec<u8> {
     s.finish_graphics(io, StageInfo::Vertex)
 }
 
+#[test]
+fn guarded_derivatives_read_neighbor_values() {
+    use crate::gpu::dxil::ops::Deriv;
+    use crate::gpu::recomp::{dxc, runner};
+    use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT;
+
+    if !draw_ready() {
+        return;
+    }
+    if dxc::location().is_err() {
+        return runner::skip_test("no DXC");
+    }
+    let mut s = Shader::new(Stage::Pixel, (6, 6));
+    let mut io = GraphicsIo::new(Stage::Pixel);
+    let pos = io.input(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4));
+    let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4));
+    let i32 = s.m.i32();
+    let one = s.m.i32c(1);
+    let zero = s.m.i32c(0);
+    let (low, high, off) = (f(&mut s, 2.0), f(&mut s, 9.0), f(&mut s, -1.0));
+    for (axis, ops) in [[Deriv::CoarseX, Deriv::FineX], [Deriv::CoarseY, Deriv::FineY]].into_iter().enumerate() {
+        let coord = io.load_input(&mut s, pos, 0, axis as u8);
+        let pixel = s.m.cast(CastOp::FPToUI, coord, i32);
+        let parity = s.m.bin(BinOp::And, pixel, one);
+        let even = s.m.cmp(Pred::Eq, parity, zero);
+        // The even pixel observes a derivative of 9 - 2 across its pair.
+        let input = s.m.select(even, low, high);
+        for (i, op) in ops.into_iter().enumerate() {
+            let delta = s.deriv(op, input);
+            let result = s.m.select(even, delta, off);
+            io.store_output(&mut s, tgt, 0, (2 * axis + i) as u8, result);
+        }
+    }
+    let ps = s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false });
+    assert_valid(&ps);
+    let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }];
+    let verts = [-1.0, -1.0, -1.0, 3.0, 3.0, -1.0];
+    let pixels = runner::draw(&fullscreen_vs(), &ps, &layout, &verts, 8, &[], &[0; 4], SIZE, CLEAR).expect("draw");
+    for (i, pixel) in pixels.iter().enumerate() {
+        let (x, y) = (i as u32 % SIZE, i as u32 / SIZE);
+        let dx = if x % 2 == 0 { 7.0 } else { -1.0 };
+        let dy = if y % 2 == 0 { 7.0 } else { -1.0 };
+        assert_eq!(*pixel, [dx, dx, dy, dy], "pixel ({x}, {y})");
+    }
+}
+
 /// Implicit-LOD sampling and fine derivatives in an emitted pixel shader
 /// (the `ops` library could only test these in compute shaders).
 #[test]
diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs
index 9672d2f..2a4c41b 100644
--- a/crates/xcl/src/gpu/dxil/module/opt.rs
+++ b/crates/xcl/src/gpu/dxil/module/opt.rs
@@ -382,9 +382,13 @@ impl Module {
         match op {
             Op::Bin(BinOp::UDiv | BinOp::SDiv | BinOp::URem | BinOp::SRem, ..) => false,
             Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) => true,
-            Op::Call(f, _) => {
+            Op::Call(f, args) => {
                 let d = &self.funcs[*f as usize];
-                d.attrs == FnAttrs::ReadNone && !d.name.ends_with(".f64")
+                // The readnone unary declaration also serves quad derivatives. A lane
+                // taking the result can read an input from a lane with a false guard.
+                let derivative = d.name.starts_with("dx.op.unary.")
+                    && matches!(args.first().and_then(|&v| self.const_u64(v)), Some(83..=86));
+                d.attrs == FnAttrs::ReadNone && !d.name.ends_with(".f64") && !derivative
             }
             _ => false,
         }

AI use

OpenAI Codex, GPT-6.2 Astra at maximum reasoning effort, wrote the change and regression test and ran the comparisons. I checked the optimizer change and the test before sharing them.

@JJAutoCompare

Copy link
Copy Markdown

PR #1972 — Intel Arc A770 guarded derivative verification

Tested

  • Clean checkout of e3dfb2e02ce639f3ca84ce130bbaef1dcc6a9493. GitHub showed PR #1972 open at this head before and after the run.
  • Windows 11 Enterprise Evaluation x64 build 26200.9974, AMD Ryzen 7 3800X, Intel Arc A770 with driver 32.0.101.9175, and Rust 1.100.0 (0ef1bc386 2026-11-09), x86_64-pc-windows-msvc. The fixture loaded dxcompiler and dxil 1.9.2609.5 from the configured DXC directory.
  • The build completed outside the GPU lock. The exact test ran under the Arc A770 mutex and exited 0 in 0.17 s. 1 passed, 0 failed, 0 ignored, 0 skipped (1,124 filtered out). The log had zero SKIPPED lines, so both DXC validation and GPU readback ran.
  • DXC validated the emitted SM 6.6 vertex and pixel shaders. The pixel disassembly assertion checked that the inputs to the four coarse/fine X/Y derivative opcodes had not been folded to the constant 2.0. The fullscreen 8×8 draw matched all 64 RGBA pixels (256 components) on readback. Each pixel matched [ex, ex, ey, ey], where ex was 7.0 on even columns and -1.0 on odd columns, and ey followed the same rule for rows.
$env:TEMP = 'L:/XclTooling/pr1972/run-20261125T031056362Z'
$env:TMP = $env:TEMP
$env:CARGO_TARGET_DIR = 'L:/XclTooling/pr1778-2e2ee55-20261125-020159/target'
$env:CARGO_BUILD_JOBS = '2'
$env:CARGO_INCREMENTAL = '0'
$env:CARGO_PROFILE_DEV_DEBUG = '0'
$env:CARGO_PROFILE_TEST_DEBUG = '0'
$env:XCL_ADAPTER = 'A770'
$env:XCL_DXC_DIR = 'C:/Users/ljensen/AppData/Local/XclTooling/dxc-1.9.2609/bin/x64'
& 'C:/Users/ljensen/.cargo/bin/cargo.exe' test -p xcl --lib --no-run

Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned -Force
$testExe = 'L:/XclTooling/pr1778-2e2ee55-20261125-020159/target/debug/build/xcl/97fdf2b9ff8e1482/out/xcl-97fdf2b9ff8e1482.exe'
$fixture = 'gpu::dxil::graphics::tests::guarded_derivatives_read_neighbor_values'
& 'L:/XclTooling/Invoke-ArcTest.ps1' -Test { & $testExe --exact $fixture --nocapture --test-threads=1 }

XCL_DXIL_NO_OPT was unset. build.log and arc-test.log are alongside this report.

Not tested

  • Other fixtures, the workspace suite, a main-versus-head comparison, a retail title smoke run, other adapters, and release builds.

AI use

  • T3 Code / Codex (gpt-6.2-sol) ran the checked-in fixture and wrote this report.

@DavidM1911

Copy link
Copy Markdown
Contributor

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

Thanks!

@raylitebull

Copy link
Copy Markdown
Member Author

Fixed the CI assertion in opt::tests::guarded_derivatives_and_cross_lane_ops_preserve_select_operands in commit 7e36ea5 (rebased onto 56ec08d, keeping the strict lane-local dx.op allowlist 6..=42 | 44..=56 | 124..=132 from e3dfb2e):

  • CSE legitimately merged the 4 identical select(c, 2.0, 9.0) instructions into Inst(2) (none of quad-derivative opcodes 83..=86 were folded to 2.0, and graphics_tests::guarded_derivatives_read_neighbor_values already compiled cleanly).
  • Updated guarded_derivatives_and_cross_lane_ops_preserve_select_operands to share one s = select(c, 2.0, 9.0) across all 4 quad derivatives (83..=86, asserting args[1] == s) and the contrast lane-local FAbs (6, asserting args[1] == 2.0).

Thanks again @philip-roy-jones — pushed 7e36ea5 for GitHub Actions Build and test and re-testing!

@raylitebull
raylitebull force-pushed the feat/dxil-opt-select-guard-prop branch from 7e36ea5 to 528ca10 Compare November 25, 2026 10:52
@raylitebull

Copy link
Copy Markdown
Member Author

Rebased #1972 cleanly onto 13c2a405 in commit 528ca109, resolving crates/xcl/src/gpu/dxil/module/opt.rs doc-comment and EOF test conflicts alongside #2194 (e64bd17b simplify_cfg).

Verified locally (cargo check --workspace --tests + cargo test -p xcl --lib gpu::dxil::module::opt::tests: 11 passed, 0 failed, dxil 1.8.2502.11 validated) and pushed 528ca109.

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