Repository navigation
dxil: guarded-value demand propagation and algebraic/bitcast folding in opt - #1972
raylitebull wants to merge 1 commit into
Conversation
|
Full-suite run, since this PR has no test report yet. Tested exact head Tested
Not tested
AI use
|
|
| 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
8rather than43. - 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.
|
Overlap note: full credit to #1906 (@Decodere), which already covers the shared Once #1906 lands (or in our next update), we will trim #1972 down to only the independent |
c04f6c6 to
6e1b44f
Compare
|
Thanks for catching and proving the loop-header phi case, @WebIdentity1! Updated
Verified locally with |
6e1b44f to
8d419c0
Compare
|
Trimmed and rebased
|
|
RADV numbers for the two 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
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. |
|
RX 580 retest of the author’s fix at The 8×8 draw on the updated PR returned all 256 expected output components. At the author’s requested reference
Both release builds exited early with Generated smoke blocks for the reference and updated PRRadeon 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 The 8×8 draw uses XCL’s direct DXIL builder. On this head, a source search found explicit calls to Tested
With the repair, the existing five optimizer tests passed. The separate native-wave64 compute test Retail shader compilation I translated five compute records in release with four memory windows and
To reproduce a row’s shader output, run A separate seeded retail sample ( 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 Generated smoke blocks, parent and PR headNot 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 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. |
8d419c0 to
e3dfb2e
Compare
|
Thanks for the RX 580 repro and clear root-cause diagnosis, Fixed the cross-lane quad-derivative miscompilation in
Pushed |
|
@raylitebull, here is the patch for the quad-derivative readback on 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. |
PR #1972 — Intel Arc A770 guarded derivative verificationTested
$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 }
Not tested
AI use
|
|
Verification on RTX 3060 Ti (Windows 11), branch merged with current
Thanks! |
Adds guarded-value demand propagation (
propagate_select_guards) and full-EXEC lane-bit folding (and(lshr(-1, s), 1) -> 1) insidecrates/xcl/src/gpu/dxil/module/opt.rsto eliminate redundantselectchains on lowered RDNA shader IR before DXIL serialization.Part of #1269.
What is in it
crates/xcl/src/gpu/dxil/module/opt.rs(+589 / -63acrossopt.rs+graphics_tests.rs, gated byXCL_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-seedingOp::Phiincoming operands asDemand::Anybefore the reverse-RPO walk, chasing nestedselectreplacements transitively, and restrictingdx.op.*intrinsics inguard_eligibleto a strict lane-local math/bit/conversion allowlistop_code in 6..=42 | 44..=56 | 124..=132so quad derivatives83..=86,Eval*87..=89,Wave*/Quad*, and implicit-LOD texture ops always receiveDemand::Any).known_lt_32& full-EXEC lane-bit fold (and(lshr(-1, s), 1) -> 1) insiderun_cse_simplify, while preservinglocal.clear()acrossdx.op.discardfor wave/quad operations.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, andoptimized_valu_chain_validates_with_dxil.crates/xcl/src/gpu/dxil/graphics_tests.rs: addguarded_derivatives_read_neighbor_values(DXIL validation + disassembly check + fullscreen 8x8 quad-derivative draw test).simplify_oprules 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 #1947XCL_DIRECT_DXIL_SOURCE_IDinstead of a manualTRANSLATOR_VERSIONbump.)Tested
rustc 1.99.1 (58cf8f9c3 2026-10-13), rebased cleanly onto94193f0(e3dfb2e).e3dfb2eupdatedguard_eligible+ added both regression tests atop94193f0via pure git during a local test hold and is queued for GitHub ActionsBuild and test+ reviewer verification.8d419c0(ontoaa9ab8a) passedcargo check --workspace --testsandgpu::dxil::module::opt::tests(5/5).Regression run
scripts/smoke.ps1pair and GPUguarded_derivatives_read_neighbor_valuesone3dfb2evs94193f0have not been run locally yet. AMD and NVIDIA reviewers are invited to test one3dfb2evs94193f0(includingguarded_derivatives_read_neighbor_values,scripts/smoke.ps1, andXCL_DIRECT_DXIL=1) and post results in the comments.Not tested
cargo check/opt::tests/guarded_derivatives_read_neighbor_valuesand 60 sscripts/smoke.ps1pair one3dfb2e, fullcargo test --workspacesuite, runtime GPU execution across AMD / NVIDIA / Intel hardware, and Linux/Wine/vkd3d-proton.AI use