From 894e29d63b3a668f5d04bb74a6cc88f06798805f Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:51:40 +0300 Subject: [PATCH 1/3] Recompiler: fold 64-bit ints, bitcast selects and commutative CSE in 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) --- crates/xcl/src/gpu/dxil/core_tests.rs | 104 ++++++++++ crates/xcl/src/gpu/dxil/module/opt.rs | 273 ++++++++++++++++++++++---- crates/xcl/src/gpu/dxil/shader.rs | 2 + 3 files changed, 344 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..510a96ea83 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -831,3 +831,107 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { } } } + +/// Post-phi folding: i64 window-high + `Int64Ops` cleanup, finite constant `BitCast` +/// (preserving Inf/NaN bitcasts), `bitcast(select)`, nested same-condition selects, +/// commutative integer/compare CSE, `zext(i1)` compares, and GPU execution parity. +#[test] +fn opt_folds_i64_bitcast_selects_and_commutative_cse() { + use super::{container::Stage, module::{BinOp, CastOp, Pred}, shader::{Feature, Shader}, validate}; + use crate::gpu::recomp::runner; + + let mut s = Shader::new(Stage::Compute, (6, 6)); + let (io, res, lane) = (s.raw_uav(0, 0), s.raw_uav(1, 0), s.thread_id_in_group(0)); + let (i32t, f32t, i64t) = (s.m.i32(), s.m.f32(), s.m.i64()); + s.require(Feature::Int64Ops); + let (c0, c2, c4, c99) = (s.m.i32c(0), s.m.i32c(2), s.m.i32c(4), s.m.i32c(99)); + let (c32_64, k15, k25, kinf) = (s.m.const_int(i64t, 32), s.m.i32c(1.5f32.to_bits()), s.m.f32c(2.5f32.to_bits()), s.m.i32c(0x7F80_0000)); + let off = s.m.bin(BinOp::Shl, lane, c2); + let off4 = s.m.bin(BinOp::Add, off, c4); + let (a, b) = (s.raw_load(io, off, 1)[0], s.raw_load(io, off4, 1)[0]); + + // Commutative Add + flipped integer Cmp CSE and zext(i1) compare folding. + let (sum1, sum2) = (s.m.bin(BinOp::Add, a, b), s.m.bin(BinOp::Add, b, a)); + let diff = s.m.bin(BinOp::Sub, sum1, sum2); + let (cmp1, cmp2) = (s.m.cmp(Pred::ULt, a, b), s.m.cmp(Pred::UGt, b, a)); + let same_cmp = s.m.cmp(Pred::Eq, cmp1, cmp2); + let same_z = s.m.cast(CastOp::ZExt, same_cmp, i32t); + let same_b = s.m.cmp(Pred::Ne, same_z, c0); + + // 64-bit window-high extraction folds to 0 and drops Int64Ops cleanly. + let z64 = s.m.cast(CastOp::ZExt, a, i64t); + let shr64 = s.m.bin(BinOp::LShr, z64, c32_64); + let hi = s.m.cast(CastOp::Trunc, shr64, i32t); + + // Finite constant BitCast, nested same-condition Select, and bitcast(select(...)). + let f1 = s.m.bitcast(k15, f32t); + let f2 = s.m.fbin(BinOp::Add, f1, k25, 0); + let (b1, b2) = (s.m.bitcast(f1, i32t), s.m.bitcast(f2, i32t)); + let s1 = s.m.select(cmp1, b1, hi); + let s2 = s.m.select(cmp1, b2, s1); + let f_out = s.m.bitcast(s2, f32t); + let bits_out = s.m.bitcast(f_out, i32t); + + // Non-finite (+Inf) constant BitCast must not materialize an invalid float constant. + let inf_f = s.m.bitcast(kinf, f32t); + let inf_bits = s.m.bitcast(inf_f, i32t); + let inf_zero = s.m.bin(BinOp::Sub, inf_bits, kinf); + let extra = s.m.bin(BinOp::Add, diff, inf_zero); + let v0 = s.m.bin(BinOp::Add, bits_out, extra); + let out = s.m.select(same_b, v0, c99); + s.raw_store(res, off, &[out]); + let dxil = s.finish([32, 1, 1], Some(32)); + validate::validate(&dxil).expect("synthetic shader validates"); + let dis = validate::disassemble(&dxil).expect("disasm"); + assert!(!dis.contains("64-Bit integer") && !dis.contains("bitcast i32 1069547520"), "{dis}"); + + // Multi-window RDNA2 loop: i64 pack/unpack and float-const bitcasts fold away. + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 132)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 242)], None), + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 132), ("VSRC1", 0)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 240), ("VSRC1", 2)], None), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 242), ("VSRC1", 2)], None), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 2), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None), + ]); + let dx4 = translate(&code, KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }).expect("4w"); + validate::validate(&dx4).expect("4w validates"); + let dis4 = validate::disassemble(&dx4).expect("disasm4"); + assert!( + !dis4.contains("64-Bit integer") && !dis4.contains("bitcast i32 1065353216"), + "expected 4-window loop i64 and const bitcast to fold away:\n{dis4}" + ); + + if !matches!(runner::wave32_supported(), Ok(true)) { + return runner::skip_test("no wave32"); + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let mut sgpr = vec![0u32; 128]; + for l in 0..33 { + sgpr[l] = if l % 2 == 0 { 1 } else { 5 }; + } + let r = runner::run(&dxil, &runner::KernelState { sgpr, vgpr: vec![vec![0; 256]; 64], scc: 0 }, &[]).expect("GPU"); + for l in 0..32 { + assert_eq!(r.raw[l], if l % 2 == 0 { 4.0f32.to_bits() } else { 0 }, "lane {l}"); + } + let dx1 = translate(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }).expect("1w"); + let hlsl = crate::gpu::recomp::translate(&code, &crate::gpu::recomp::Options { wave64: false, ..Default::default() }) + .expect("hlsl") + .hlsl; + let dxc = crate::gpu::recomp::dxc::compile(&hlsl, "main", "cs_6_6", &[]).expect("dxc"); + let mut state = runner::KernelState { sgpr: vec![0u32; 128], vgpr: vec![vec![0; 256]; 64], scc: 0 }; + for l in 0..32 { + state.vgpr[l][0] = (l as u32) * 4; + } + let mem: Vec = (0..64).map(|i| i * 7 + 1).collect(); + let got = runner::run(&dx1, &state, &mem).expect("direct"); + let want = runner::run(&dxc, &state, &mem).expect("hlsl"); + for l in 0..32 { + assert_eq!(got.vgpr[l][2..=3], want.vgpr[l][2..=3], "lane {l}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 5e867f55a0..5d279da1d3 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; -use super::{BinOp, Block, CastOp, FnAttrs, Module, Op, Pred, Ty, Value}; +use super::{BinOp, Block, CastOp, ConstDef, FnAttrs, Module, Op, Pred, Ty, TypeDef, Value}; impl Op { /// Calls `f` on every value operand. @@ -105,10 +105,108 @@ impl Module { } } + fn zext_src(&self, v: Value) -> Option<(Value, u32)> { + let Value::Inst(j) = v else { return None }; + let Op::Cast(CastOp::ZExt, inner, _) = self.insts[j as usize].op else { return None }; + self.int_width(self.value_ty(inner)).map(|sw| (inner, sw)) + } + + /// Reinterprets `v` as `to` for free: inverse `BitCast`, dominating `BitCast` in CSE, + /// or finite constant bitcast (excluding NaN and Inf in both directions). + fn free_bitcast(&mut self, v: Value, to: Ty, table: &HashMap<(Op, Ty), Value>) -> Option { + let from = self.value_ty(v); + if self.types[from.0 as usize] == TypeDef::Double || self.types[to.0 as usize] == TypeDef::Double { + return None; + } + if let Value::Inst(j) = v { + if let Op::Cast(CastOp::BitCast, inner, _) = self.insts[j as usize].op { + if self.value_ty(inner) == to { + return Some(inner); + } + } + } + if let Some(&hit) = table.get(&(Op::Cast(CastOp::BitCast, v, to), to)) { + return Some(hit); + } + let fbits = |v| match v { + Value::Const(c) => match &self.consts[c as usize] { + ConstDef::Float(_, b) => Some(*b), + ConstDef::Null(t) if self.is_float(*t) => Some(0), + _ => None, + }, + _ => None, + }; + match (&self.types[from.0 as usize], &self.types[to.0 as usize]) { + (TypeDef::Int(32), TypeDef::Float) => self.const_u64(v).filter(|&b| (b as u32 & 0x7FFF_FFFF) < 0x7F80_0000).map(|b| self.const_float(to, b & 0xFFFF_FFFF)), + (TypeDef::Float, TypeDef::Int(32)) => fbits(v).filter(|&b| (b as u32 & 0x7FFF_FFFF) < 0x7F80_0000).map(|b| self.const_int(to, b & 0xFFFF_FFFF)), + (TypeDef::Int(16), TypeDef::Half) => self.const_u64(v).filter(|&b| (b as u16 & 0x7FFF) < 0x7C00).map(|b| self.const_float(to, b & 0xFFFF)), + (TypeDef::Half, TypeDef::Int(16)) => fbits(v).filter(|&b| (b as u16 & 0x7FFF) < 0x7C00).map(|b| self.const_int(to, b & 0xFFFF)), + _ => None, + } + } + + /// Pushes `bitcast(select(c, a, b), to)` into `select` in place when `select` has no + /// non-bitcast uses (so the original select dies in DCE) and both arms convert for free, + /// returning the original `(op, ty)` so CSE can still reuse the bitcast key in dominated blocks. + fn simplify_bitcast_select(&mut self, op: &mut Op, repl: &mut [Option], table: &HashMap<(Op, Ty), Value>, bc_only: &[Option>]) -> Option<(Op, Ty)> { + let Op::Cast(CastOp::BitCast, Value::Inst(j), to) = *op else { return None }; + if bc_only[j as usize] != Some(Some(to)) { + return None; + } + let Op::Select(c, t, f) = self.insts[j as usize].op else { return None }; + let nt = self.free_bitcast(resolve(repl, t), to, table)?; + let nf = self.free_bitcast(resolve(repl, f), to, table)?; + let orig = (op.clone(), to); + *op = Op::Select(resolve(repl, c), resolve(repl, nt), resolve(repl, nf)); + Some(orig) + } + + /// Collapses nested same-condition selects (`select(c, t, select(c, _, f)) -> select(c, t, f)`). + fn simplify_select(&self, op: &mut Op, ty: Ty, repl: &mut [Option]) { + let Op::Select(c, t, f) = op else { return }; + if self.types[ty.0 as usize] == TypeDef::Double { + return; + } + if let Value::Inst(j) = *f { + if let Op::Select(c2, _, f2) = self.insts[j as usize].op { + if resolve(repl, c2) == *c { + *f = resolve(repl, f2); + } + } + } + if let Value::Inst(j) = *t { + if let Op::Select(c2, t2, _) = self.insts[j as usize].op { + if resolve(repl, c2) == *c { + *t = resolve(repl, t2); + } + } + } + } + + /// Canonicalizes operand order on commutative integer ops and integer compares for CSE. + fn canonicalize_commutative(&self, op: &mut Op, ty: Ty) { + match op { + Op::Bin(BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor, a, b, _) + if self.int_width(ty).is_some() && *b < *a => std::mem::swap(a, b), + Op::Cmp(p, a, b) if self.int_width(self.value_ty(*a)).is_some() && *b < *a => { + *p = match *p { + Pred::Eq => Pred::Eq, Pred::Ne => Pred::Ne, + Pred::UGt => Pred::ULt, Pred::ULt => Pred::UGt, + Pred::UGe => Pred::ULe, Pred::ULe => Pred::UGe, + Pred::SGt => Pred::SLt, Pred::SLt => Pred::SGt, + Pred::SGe => Pred::SLe, Pred::SLe => Pred::SGe, + _ => return, + }; + std::mem::swap(a, b); + } + _ => {} + } + } + /// Cheap algebraic & constant simplification on already-resolved operands. - fn simplify_op(&mut self, op: &Op, ty: Ty) -> Option { - // Keep 64-bit instructions intact so Int64Ops / Doubles shader flags stay consistent. - if matches!(self.types[ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { + fn simplify_op(&mut self, op: &Op, ty: Ty, table: &HashMap<(Op, Ty), Value>) -> Option { + // Keep f64 instructions intact so Doubles / DoubleExtensions shader flags stay consistent. + if matches!(self.types[ty.0 as usize], TypeDef::Double) { return None; } match *op { @@ -119,18 +217,19 @@ impl Module { match self.const_u64(c) { Some(1) => Some(t), Some(0) => Some(f), - _ => None, + _ => (self.int_width(ty) == Some(1) && self.const_u64(t) == Some(1) && self.const_u64(f) == Some(0)) + .then_some(c), } } Op::Bin(bop, a, b, 0) => { let w = self.int_width(ty)?; - // avoid dropping 64-bit ops that keep Int64Ops shader flags consistent - if w > 32 { + if w > 64 { return None; } - let mask = (1u64 << w) - 1; + let mask = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 }; let (ca, cb) = (self.const_u64(a), self.const_u64(b)); if let (Some(x), Some(y)) = (ca, cb) { + let sx = if w >= 64 { x as i64 } else { ((x << (64 - w)) as i64) >> (64 - w) }; let r = match bop { BinOp::Add => Some(x.wrapping_add(y)), BinOp::Sub => Some(x.wrapping_sub(y)), @@ -140,7 +239,7 @@ impl Module { BinOp::Xor => Some(x ^ y), BinOp::Shl if y < w as u64 => Some(x << y), BinOp::LShr if y < w as u64 => Some(x >> y), - BinOp::AShr if y < w as u64 => Some((((x << (64 - w)) as i64) >> (64 - w + y as u32)) as u64), + BinOp::AShr if y < w as u64 => Some((sx >> (y as u32)) as u64), BinOp::UDiv if y != 0 => Some(x / y), BinOp::URem if y != 0 => Some(x % y), _ => None, @@ -247,6 +346,30 @@ impl Module { } } } + BinOp::LShr => { + if let Some(sh) = cb.filter(|&sh| sh < w as u64) { + if self.zext_src(a).is_some_and(|(_, sw)| sh >= sw as u64) { + return Some(self.const_int(ty, 0)); + } + if let Value::Inst(j) = a { + if let Op::Bin(BinOp::Or, x, y, 0) = self.insts[j as usize].op { + for (lo, hi) in [(x, y), (y, x)] { + let lo_cleared = self.const_u64(lo) == Some(0) + || self.zext_src(lo).is_some_and(|(_, sw)| sh >= sw as u64); + if let (true, Value::Inst(hj)) = (lo_cleared, hi) { + if let Op::Bin(BinOp::Shl, z, k, 0) = self.insts[hj as usize].op { + if self.const_u64(k) == Some(sh) + && self.zext_src(z).is_some_and(|(_, sw)| (sw as u64) + sh <= w as u64) + { + return Some(z); + } + } + } + } + } + } + } + } _ => {} } None @@ -254,11 +377,12 @@ impl Module { Op::Cmp(p, a, b) => { let at = self.value_ty(a); let w = self.int_width(at)?; - if w > 32 { + if w > 64 { return None; } - if let (Some(x), Some(y)) = (self.const_u64(a), self.const_u64(b)) { - let sx = |v: u64| ((v << (64 - w)) as i64) >> (64 - w); + let (ca, cb) = (self.const_u64(a), self.const_u64(b)); + if let (Some(x), Some(y)) = (ca, cb) { + let sx = |v: u64| if w >= 64 { v as i64 } else { ((v << (64 - w)) as i64) >> (64 - w) }; let r = match p { Pred::Eq => Some(x == y), Pred::Ne => Some(x != y), @@ -286,29 +410,53 @@ impl Module { return Some(self.const_int(ty, r as u64)); } } - None - } - Op::Cast(CastOp::BitCast, Value::Inst(j), to) => { - if matches!(self.types[self.insts[j as usize].ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { - return None; + if w == 1 { + if matches!((p, cb), (Pred::Eq, Some(1)) | (Pred::Ne, Some(0))) { + return Some(a); + } + if matches!((p, ca), (Pred::Eq, Some(1)) | (Pred::Ne, Some(0))) { + return Some(b); + } + } + if let Some((inner, 1)) = self.zext_src(a) { + if matches!((p, cb), (Pred::Ne | Pred::UGt, Some(0)) | (Pred::Eq, Some(1))) { + return Some(inner); + } } - if let Op::Cast(CastOp::BitCast, inner, _) = self.insts[j as usize].op { - if self.value_ty(inner) == to { + if let Some((inner, 1)) = self.zext_src(b) { + if matches!((p, ca), (Pred::Ne | Pred::ULt, Some(0)) | (Pred::Eq, Some(1))) { return Some(inner); } } None } + Op::Cast(CastOp::BitCast, v, to) => self.free_bitcast(v, to, table), Op::Cast(cop @ (CastOp::ZExt | CastOp::SExt | CastOp::Trunc), v, to) => { let sw = self.int_width(self.value_ty(v))?; let dw = self.int_width(to)?; - if sw > 32 || dw > 32 { + if sw > 64 || dw > 64 { return None; } + if sw == dw { + return Some(v); + } + if cop == CastOp::Trunc { + if let Value::Inst(j) = v { + if let Op::Cast(CastOp::ZExt | CastOp::SExt, inner, _) = self.insts[j as usize].op { + if self.value_ty(inner) == to { + return Some(inner); + } + } + } + } let x = self.const_u64(v)?; + let dm = if dw >= 64 { u64::MAX } else { (1u64 << dw) - 1 }; let r = match cop { - CastOp::ZExt | CastOp::Trunc => x & ((1u64 << dw) - 1), - CastOp::SExt => ((((x << (64 - sw)) as i64) >> (64 - sw)) as u64) & ((1u64 << dw) - 1), + CastOp::ZExt | CastOp::Trunc => x & dm, + CastOp::SExt => { + let sx = if sw >= 64 { x as i64 } else { ((x << (64 - sw)) as i64) >> (64 - sw) }; + (sx as u64) & dm + } _ => unreachable!(), }; Some(self.const_int(to, r)) @@ -317,8 +465,8 @@ impl Module { } } - /// Whether an unused instruction can go. 64-bit values stay: helpers already set - /// the Int64Ops / Doubles / DoubleExtensions flags for them. + /// Whether an unused instruction can go. Double values stay: helpers already set + /// the Doubles / DoubleExtensions flags for them (`Int64Ops` is refreshed in `infer_type_features`). fn removable(&self, op: &Op, ty: Ty, wide: &[Ty]) -> bool { if wide.contains(&ty) { return false; @@ -336,9 +484,15 @@ impl Module { let d = &self.funcs[*f as usize]; matches!(d.attrs, FnAttrs::ReadNone | FnAttrs::ReadOnly) && !d.name.ends_with(".f64") - && ["dx.op.unary.", "dx.op.binary.", "dx.op.tertiary.", "dx.op.loadInput.", "dx.op.annotateHandle", "dx.op.createHandleFromBinding", "dx.op.cbufferLoadLegacy."] - .iter() - .any(|p| d.name.starts_with(p)) + && [ + "dx.op.unary.", "dx.op.unaryBits.", "dx.op.binary.", "dx.op.tertiary.", "dx.op.quaternary.", + "dx.op.dot", "dx.op.legacyF16ToF32", "dx.op.legacyF32ToF16", "dx.op.bitcast", + "dx.op.isSpecialFloat.", "dx.op.threadId", "dx.op.groupId.", "dx.op.flattenedThreadIdInGroup.", + "dx.op.loadInput.", "dx.op.annotateHandle", "dx.op.createHandleFromBinding", + "dx.op.cbufferLoadLegacy.", + ] + .iter() + .any(|p| d.name.starts_with(p)) } _ => false, } @@ -426,7 +580,7 @@ impl Module { /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,fold,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); @@ -507,7 +661,42 @@ impl Module { Enter(usize), Leave(usize), } - let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; + let (do_fold, do_cse) = (!skip("fold"), !skip("cse")); + // None = unseen, Some(Some(to)) = only used by BitCast(_, to), Some(None) = other use. + let mut bc_only: Vec>> = vec![None; if do_fold { self.insts.len() } else { 0 }]; + if do_fold { + for &b in &order { + for &u in &self.blocks[b as usize] { + if repl[u as usize].is_some() { + continue; + } + match self.insts[u as usize].op { + Op::Cast(CastOp::BitCast, v, to) => if let Value::Inst(j) = resolve(&mut repl, v) { + bc_only[j as usize] = match bc_only[j as usize] { + None => Some(Some(to)), + Some(Some(prev)) if prev == to => Some(Some(to)), + _ => Some(None), + }; + }, + Op::Select(c, t, f) if self.types[self.insts[u as usize].ty.0 as usize] != TypeDef::Double => { + let rc = resolve(&mut repl, c); + if let Value::Inst(j) = rc { bc_only[j as usize] = Some(None); } + for arm in [t, f] { + if let Value::Inst(j) = resolve(&mut repl, arm) { + if !matches!(self.insts[j as usize].op, Op::Select(c2, _, _) if resolve(&mut repl, c2) == rc) { + bc_only[j as usize] = Some(None); + } + } + } + } + _ => self.insts[u as usize].op.for_each_operand(|v| { + if let Value::Inst(j) = resolve(&mut repl, v) { bc_only[j as usize] = Some(None); } + }), + } + } + } + } + let mut stack = if !do_fold && !do_cse { Vec::new() } else { vec![Step::Enter(0)] }; let mut cse_replaced = false; while let Some(step) = stack.pop() { let b = match step { @@ -527,16 +716,26 @@ impl Module { let mut local: HashMap<(Op, Ty), Value> = HashMap::new(); for k in 0..self.blocks[b].len() { let i = self.blocks[b][k] as usize; + let ty = self.insts[i].ty; let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); op.map_operands(|v| resolve(&mut repl, v)); if repl[i].is_none() { - if let Some(s) = self.simplify_op(&op, self.insts[i].ty) { - repl[i] = Some(s); - cse_replaced = true; + let alias_key = if do_fold { + let k = self.simplify_bitcast_select(&mut op, &mut repl, &table, &bc_only); + self.simplify_select(&mut op, ty, &mut repl); + if let Some(s) = self.simplify_op(&op, ty, &table) { + repl[i] = Some(resolve(&mut repl, s)); + cse_replaced = true; + } + k } else { + None + }; + if repl[i].is_none() && do_cse { + self.canonicalize_commutative(&mut op, ty); let kind = self.cse_kind(&op); if kind != Cse::No { - let key = (op.clone(), self.insts[i].ty); + let key = (op.clone(), ty); let t = if kind == Cse::Dom { &mut table } else { &mut local }; if let Some(&v) = t.get(&key) { repl[i] = Some(v); @@ -553,6 +752,10 @@ impl Module { local.clear(); } } + if let (true, Some(akey)) = (do_cse, alias_key) { + let old = table.insert(akey.clone(), repl[i].unwrap_or(Value::Inst(i as u32))); + undo.push((akey, old)); + } } self.insts[i].op = op; } @@ -605,8 +808,8 @@ impl Module { } // dead instructions: live = side effects, terminators and their operands, transitively - let (i64t, f64t) = self.existing_i64_f64(); - let wide: Vec = i64t.into_iter().chain(f64t).collect(); + let (_, f64t) = self.existing_i64_f64(); + let wide: Vec = f64t.into_iter().collect(); let mut live = vec![false; self.insts.len()]; let mut work: Vec = Vec::new(); for &b in &order { diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index a0a970925d..4257732fc4 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -506,6 +506,8 @@ impl Shader { let (i64, f64) = self.m.existing_i64_f64(); if i64.is_some_and(|t| self.m.insts_use_type(t)) { self.require(Feature::Int64Ops); + } else { + self.features.remove(&Feature::Int64Ops); } if f64.is_some_and(|t| self.m.insts_use_type(t)) { self.require(Feature::Doubles); From 81998cea70c79bc2eac35af3c076d6bbe90a0e4f Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:45:25 -0500 Subject: [PATCH 2/3] Recompiler: fold direct DXIL EXEC selects no lane observes The direct translator writes a VGPR under EXEC as select(exec, new, old). A lane-local instruction under the same EXEC that reads the register, and whose own result is selected by that EXEC again, never observes the old arm. optimize() now tracks where each value is observed (unused, only where one condition holds, all lanes) and reads through such selects; DCE then drops the selects left without uses. Phis, memory, wave ops, derivatives and integer division observe all lanes. XCL_DXIL_NO_OPT=select leaves the pass out. Tests turn it off per thread; the translator thread takes the caller's setting. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/kernel.rs | 9 +- crates/xcl/src/gpu/dxil/mod.rs | 2 + crates/xcl/src/gpu/dxil/module.rs | 2 + crates/xcl/src/gpu/dxil/module/opt.rs | 172 +++++++++++++++++++++++- crates/xcl/src/gpu/dxil/select_tests.rs | 113 ++++++++++++++++ 5 files changed, 296 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/select_tests.rs diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 6ef85ad800..53ce5f0117 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -159,10 +159,17 @@ fn translate_entry( // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs let code = code.to_vec(); + // tests: the caller's choice of optimiser passes goes along to the translator thread + #[cfg(test)] + let no_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables)) + .spawn(move || { + #[cfg(test)] + super::module::NO_SELECT_FOLD.with(|c| c.set(no_fold)); + translate_on_this_thread(&code, o, entry, compact, nest, tables) + }) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index a0ec94583f..9540026ed1 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -57,3 +57,5 @@ mod msaa_tests; mod round_tests; #[cfg(test)] mod geometry_tests; +#[cfg(test)] +mod select_tests; diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..8e2745bc7e 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -16,6 +16,8 @@ use std::collections::HashMap; use super::bitstream::{signed, BitWriter}; mod opt; +#[cfg(test)] +pub(crate) use opt::NO_SELECT_FOLD; pub(super) mod split; // ---------------------------------------------------------------- types diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 5d279da1d3..29365ede88 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -68,6 +68,12 @@ impl Op { } } +#[cfg(test)] +thread_local! { + /// Tests: leave out `fold_guarded_selects` on this thread (the form to compare against). + pub(crate) static NO_SELECT_FOLD: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + /// How an instruction may be merged with an identical one. #[derive(PartialEq)] enum Cse { @@ -580,7 +586,7 @@ impl Module { /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,fold,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,fold,cse,select,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); @@ -807,6 +813,14 @@ impl Module { } } + #[cfg(test)] + let skip_fold = NO_SELECT_FOLD.with(|c| c.get()); + #[cfg(not(test))] + let skip_fold = false; + if !skip("select") && !skip_fold { + self.fold_guarded_selects(&order, &repl); + } + // dead instructions: live = side effects, terminators and their operands, transitively let (_, f64t) = self.existing_i64_f64(); let wide: Vec = f64t.into_iter().collect(); @@ -909,6 +923,119 @@ impl Module { } } + /// A lane's result depends only on that lane's operands, and no operand value is undefined + /// behaviour (no memory, wave ops, derivatives, integer division). + fn lane_local(&self, op: &Op, ty: Ty) -> bool { + match op { + Op::Bin(BinOp::UDiv | BinOp::URem, ..) => false, + Op::Bin(BinOp::SDiv | BinOp::SRem, ..) => self.is_float(ty), + Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) => true, + Op::Call(f, args) => { + let d = &self.funcs[*f as usize]; + // unary .. dot4, make / split double, bitcasts and legacy conversions + d.attrs == FnAttrs::ReadNone + && d.name.starts_with("dx.op.") + && args.first().and_then(|&a| self.const_u64(a)).is_some_and(|id| matches!(id, 6..=56 | 101 | 102 | 124..=132)) + } + _ => false, + } + } + + /// Selects whose other arm no lane can observe. The translator writes a VGPR under EXEC as + /// `select(exec, new, old)`; a following lane-local instruction under the same EXEC reads + /// that select, and its own result is again selected by EXEC. Where a value is only observed + /// in lanes where `c` holds, an operand `select(c, x, y)` can be `x`; the false arm of + /// `select(c, a, select(c, x, y))` can be `y`, the true arm of `select(c, select(c, x, y), b)` + /// `x`. No instruction's value changes in a lane that observes it. Phis, memory, wave ops and + /// everything not `lane_local` observe all lanes. The selects left without uses go in DCE. + fn fold_guarded_selects(&mut self, order: &[u32], repl: &[Option]) { + #[derive(Clone, Copy, PartialEq)] + enum Seen { + Unused, + Where(Value), + All, + } + fn meet(s: &mut Seen, by: Seen) { + *s = match (*s, by) { + (x, Seen::Unused) => x, + (Seen::Unused, y) => y, + (Seen::Where(a), Seen::Where(b)) if a == b => Seen::Where(a), + _ => Seen::All, + } + } + let live = |i: u32| repl[i as usize].is_none(); + let mut seen = vec![Seen::Unused; self.insts.len()]; + // phis may come before a use's definition (back edges) + for &b in order { + for &i in &self.blocks[b as usize] { + if let (true, Op::Phi(inc)) = (live(i), &self.insts[i as usize].op) { + for &(v, _) in inc { + if let Value::Inst(j) = v { + seen[j as usize] = Seen::All; + } + } + } + } + } + // every other use follows its definition: users first + for &b in order.iter().rev() { + for &i in self.blocks[b as usize].iter().rev() { + if !live(i) { + continue; + } + let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty); + if matches!(op, Op::Phi(_)) { + continue; + } + let me = if self.lane_local(op, ty) { seen[i as usize] } else { Seen::All }; + if me == Seen::Unused { + continue; + } + let mut by = |v: Value, s: Seen| { + if let Value::Inst(j) = v { + meet(&mut seen[j as usize], s); + } + }; + match *op { + Op::Select(c, a, b) => { + by(c, me); + by(a, Seen::Where(c)); + by(b, me); + } + _ => op.for_each_operand(|v| by(v, me)), + } + } + } + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k]; + let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty); + if !live(i) || seen[i as usize] == Seen::Unused || !self.lane_local(op, ty) { + continue; + } + let me = seen[i as usize]; + let cu = if let Op::Select(c, ..) = *op { Some(c) } else { None }; + let mut op = op.clone(); + let mut pos = 0; + op.map_operands(|mut v| { + let at = pos; + pos += 1; + while let Value::Inst(j) = v { + let Op::Select(c, x, y) = self.insts[j as usize].op else { break }; + v = match (cu, at) { + (Some(cu), 1) if cu == c => x, + (Some(cu), 2) if cu == c => y, + _ if me == Seen::Where(c) => x, + _ => break, + }; + } + v + }); + self.insts[i as usize].op = op; + } + } + } + /// Simplifies the CFG to a fixed point: /// 1. Collapses degenerate `CondBr(_, t, t)` and `Switch` cases matching the default target. /// 2. Bypasses empty trampoline blocks (`[Br(t)]`) whenever `t`'s phis allow it. @@ -1603,4 +1730,47 @@ mod tests { let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); assert!(m.uses_well_formed(&order)); } + + #[test] + fn guarded_selects_fold_where_no_lane_sees_the_other_arm() { + let mut m = Module::new(); + m.define_entry("main"); + let entry = m.entry_block(); + m.set_block(entry); + + let void = m.void(); + let i32t = m.i32(); + let src_ty = m.func_ty(i32t, &[]); + let src = m.declare("dx.op.waveGetLaneIndex", src_ty, FnAttrs::ReadNone); + let sink_ty = m.func_ty(void, &[i32t]); + let sink = m.declare("dx.op.storeOutput.i32", sink_ty, FnAttrs::NoUnwind); + + let x = m.call(src, &[]); + let (c1, c3, c5, k) = (m.i32c(1), m.i32c(3), m.i32c(5), m.i32c(0xA5A5_5A5A)); + let exec = m.cmp(Pred::ULt, x, c5); + let old = m.bin(BinOp::Xor, x, k); + // v = exec ? x + 1 : old; v = exec ? v * 3 : v + let a = m.bin(BinOp::Add, x, c1); + let s1 = m.select(exec, a, old); + let p = m.bin(BinOp::Mul, s1, c3); + let s2 = m.select(exec, p, s1); + // read where every lane counts: stays + let s3 = m.select(exec, a, x); + let q = m.bin(BinOp::Sub, s3, c1); + m.call(sink, &[s2]); + m.call(sink, &[q]); + m.ret(); + m.optimize(); + + let Value::Inst(s2i) = s2 else { panic!() }; + let Value::Inst(pi) = p else { panic!() }; + assert!(matches!(m.insts[s2i as usize].op, Op::Select(c, t, f) if c == exec && t == p && f == old), "s2 = select(exec, p, old)"); + assert!(matches!(m.insts[pi as usize].op, Op::Bin(BinOp::Mul, v, w, 0) if (v, w) == (a, c3) || (v, w) == (c3, a)), "p = a * 3"); + let body = &m.blocks[entry.0 as usize]; + let has = |v: Value| matches!(v, Value::Inst(i) if body.contains(&i)); + assert!(!has(s1), "s1 has no uses left"); + assert!(has(s3), "s3 is read in every lane"); + let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); + assert!(m.uses_well_formed(&order)); + } } diff --git a/crates/xcl/src/gpu/dxil/select_tests.rs b/crates/xcl/src/gpu/dxil/select_tests.rs new file mode 100644 index 0000000000..2c8e278d97 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/select_tests.rs @@ -0,0 +1,113 @@ +//! `Module::optimize`'s select folding (`fold_guarded_selects`) on the GPU: the same program +//! translated with and without it gives the same words in every register of every lane, +//! inactive lanes included. + +use super::kernel::{translate, KernelOptions}; +use super::module::NO_SELECT_FOLD; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::runner::{self, KernelState}; + +const V: u64 = 256; + +fn prog(list: &[(&str, &str, &[(&str, u64)])]) -> Vec { + let mut v = Vec::new(); + for (n, e, f) in list { + v.extend(encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}"))); + } + v.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + v +} + +fn translate_fold(code: &[u8], o: KernelOptions, fold: bool) -> Vec { + NO_SELECT_FOLD.with(|c| c.set(!fold)); + let r = translate(code, o); + NO_SELECT_FOLD.with(|c| c.set(false)); + r.unwrap_or_else(|e| panic!("translate (fold {fold}): {e}")) +} + +/// Chains of VALU writes under a narrowed EXEC, narrowed again and restored, with the +/// registers read by `v_readlane` and DPP while lanes are off; NaN, signed zeros, infinities +/// and denormals as operands; sentinels in the lanes that never run. +#[test] +fn gpu_select_fold_keeps_inactive_lanes() { + match (runner::adapter(), runner::wave64_programs_supported()) { + (Ok(_), Ok(true)) => {} + (a, _) => return runner::skip_test(if a.is_err() { "no GPU" } else { "no wave64" }), + } + let code = prog(&[ + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 0)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 2)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 4), ("SRC1", V + 3), ("SRC2", V + 4)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 4)]), + ("V_CMP_GT_F32", "ENC_VOPC", &[("SRC0", V + 4), ("VSRC1", 5)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 4), ("VSRC1", 5)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 131)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 6), ("SRC1", 137)]), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 6)]), + ("V_MAX_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 4)]), + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 9), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 4), ("SRC1", 133)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 6), ("VSRC1", 6)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 4), ("VSRC1", 6)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 7), ("VSRC1", 8)]), + ]); + // NaNs, signed zeros, infinities, denormals, ordinary values + const EDGE: [u32; 12] = [0x7FC0_1234, 0x0000_0000, 0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x0000_0001, 0x807F_FFFF, 0x3FC0_0000, 0xC000_0000, 0x3F80_0000, 0x4120_0000, 0xBE80_0000]; + let mut st = KernelState::default(); + let mut x = 0x9E37_79B9_7F4A_7C15u64; + for (l, r) in st.vgpr.iter_mut().enumerate() { + for w in r.iter_mut().take(4) { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + *w = if x % 3 == 0 { x as u32 } else { EDGE[(x >> 8) as usize % EDGE.len()] }; + } + for (k, w) in r.iter_mut().enumerate().skip(4).take(8) { + *w = 0xA000_0000 | (l as u32) << 8 | k as u32; + } + } + (st.sgpr[0], st.sgpr[1]) = (0xF0F0_5A3C, 0x0FF0_C3A5); + (st.sgpr[2], st.sgpr[3]) = (0x3333_FF0F, 0xFFFF_3333); + let mut ran = 0; + for (wave64, split) in [(false, false), (true, true), (true, false)] { + if wave64 && !split && runner::wave64_supported() != Ok(true) { + continue; + } + let o = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let (old, new) = (translate_fold(&code, o, false), translate_fold(&code, o, true)); + assert!(new.len() < old.len(), "wave64 {wave64} split {split}: nothing folded ({} -> {} B)", old.len(), new.len()); + let a = runner::run(&old, &st, &[]).expect("GPU run without the fold"); + let b = runner::run(&new, &st, &[]).expect("GPU run with the fold"); + let lanes = if wave64 { 64 } else { 32 }; + let mut bad = Vec::new(); + for l in 0..lanes { + for k in 0..12 { + if a.vgpr[l][k] != b.vgpr[l][k] { + bad.push(format!("lane {l} v{k}: {:#010x} without, {:#010x} with", a.vgpr[l][k], b.vgpr[l][k])); + } + } + // lanes off from the start keep their sentinels + let on = (st.sgpr[l / 32] >> (l % 32)) & 1 == 1; + if !on { + for k in [4, 5, 7, 8] { + assert_eq!(b.vgpr[l][k], st.vgpr[l][k], "wave64 {wave64} split {split}: lane {l} v{k} was written while off"); + } + } + } + for k in 0..128 { + if a.sgpr[k] != b.sgpr[k] { + bad.push(format!("s{k}: {:#010x} without, {:#010x} with", a.sgpr[k], b.sgpr[k])); + } + } + if a.scc != b.scc { + bad.push(format!("scc: {} without, {} with", a.scc, b.scc)); + } + assert!(bad.is_empty(), "wave64 {wave64} split {split}:\n{}", bad.join("\n")); + ran += 1; + } + assert!(ran >= 2); +} From 71b76742803a7055d1feb9083cdd290c56a96abc Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:08:56 -0500 Subject: [PATCH 3/3] Recompiler: fold the bitcast pairs the EXEC select fold leaves The select fold reads through select(exec, bitcast(f), old) to the bitcast, so a float operation that read the register through bitcast(select) now reads bitcast(bitcast(f)). The CSE peephole that folds such pairs ran before the fold, so they stayed (6,305 in one program of 110 k instructions). A linear pass after the fold maps bitcast(bitcast(x)) back to x when the types match (64-bit kept, as in the peephole); DCE drops the casts left without uses. Measured on the 802 programs in use at the crash (bound DXIL bytes): 239.44 MiB on main, 219.95 with the select fold, 212.88 with this. XCL_DXIL_NO_OPT=pairs leaves the pass out. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/kernel.rs | 6 +- crates/xcl/src/gpu/dxil/module.rs | 2 +- crates/xcl/src/gpu/dxil/module/opt.rs | 76 ++++++++++++++++++++- crates/xcl/src/gpu/dxil/select_tests.rs | 89 ++++++++++++++++++++++++- 4 files changed, 166 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 53ce5f0117..10f71acc2d 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -161,13 +161,15 @@ fn translate_entry( let code = code.to_vec(); // tests: the caller's choice of optimiser passes goes along to the translator thread #[cfg(test)] - let no_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); + let no_fold = (super::module::NO_SELECT_FOLD.with(|c| c.get()), super::module::NO_PAIR_FOLD.with(|c| c.get())); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) .spawn(move || { #[cfg(test)] - super::module::NO_SELECT_FOLD.with(|c| c.set(no_fold)); + super::module::NO_SELECT_FOLD.with(|c| c.set(no_fold.0)); + #[cfg(test)] + super::module::NO_PAIR_FOLD.with(|c| c.set(no_fold.1)); translate_on_this_thread(&code, o, entry, compact, nest, tables) }) .map_err(|e| format!("translator thread: {e}"))? diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 8e2745bc7e..e8b476c91f 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -17,7 +17,7 @@ use super::bitstream::{signed, BitWriter}; mod opt; #[cfg(test)] -pub(crate) use opt::NO_SELECT_FOLD; +pub(crate) use opt::{NO_PAIR_FOLD, NO_SELECT_FOLD}; pub(super) mod split; // ---------------------------------------------------------------- types diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 29365ede88..899c6259df 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -72,6 +72,8 @@ impl Op { thread_local! { /// Tests: leave out `fold_guarded_selects` on this thread (the form to compare against). pub(crate) static NO_SELECT_FOLD: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: leave out `fold_bitcast_pairs` on this thread. + pub(crate) static NO_PAIR_FOLD: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// How an instruction may be merged with an identical one. @@ -586,7 +588,7 @@ impl Module { /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,fold,cse,select,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,fold,cse,select,pairs,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); @@ -814,11 +816,14 @@ impl Module { } #[cfg(test)] - let skip_fold = NO_SELECT_FOLD.with(|c| c.get()); + let (skip_fold, skip_pairs) = (NO_SELECT_FOLD.with(|c| c.get()), NO_PAIR_FOLD.with(|c| c.get())); #[cfg(not(test))] - let skip_fold = false; + let (skip_fold, skip_pairs) = (false, false); if !skip("select") && !skip_fold { self.fold_guarded_selects(&order, &repl); + if !skip("pairs") && !skip_pairs { + self.fold_bitcast_pairs(&order, &repl); + } } // dead instructions: live = side effects, terminators and their operands, transitively @@ -1036,6 +1041,32 @@ impl Module { } } + /// `bitcast(bitcast(x))` back to `x`'s type is `x`. The peephole folds these during CSE; + /// `fold_guarded_selects` leaves new ones where it took a select's arm that was a bitcast. + fn fold_bitcast_pairs(&mut self, order: &[u32], repl: &[Option]) { + let mut alias: Vec> = vec![None; self.insts.len()]; + // definitions come before their uses except in phis: phis take their aliases in pass 2 + for pass in 0..2 { + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + if repl[i].is_some() { + continue; + } + let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); + op.map_operands(|v| match v { + Value::Inst(j) => alias[j as usize].unwrap_or(v), + _ => v, + }); + if pass == 0 && matches!(op, Op::Cast(CastOp::BitCast, ..)) { + alias[i] = self.simplify_op(&op, self.insts[i].ty, &HashMap::new()); + } + self.insts[i].op = op; + } + } + } + } + /// Simplifies the CFG to a fixed point: /// 1. Collapses degenerate `CondBr(_, t, t)` and `Switch` cases matching the default target. /// 2. Bypasses empty trampoline blocks (`[Br(t)]`) whenever `t`'s phis allow it. @@ -1773,4 +1804,43 @@ mod tests { let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); assert!(m.uses_well_formed(&order)); } + + #[test] + fn bitcast_pairs_left_by_the_select_fold_fold() { + let mut m = Module::new(); + m.define_entry("main"); + let entry = m.entry_block(); + m.set_block(entry); + + let void = m.void(); + let (i32t, f32t) = (m.i32(), m.f32()); + let src_ty = m.func_ty(i32t, &[]); + let src = m.declare("dx.op.waveGetLaneIndex", src_ty, FnAttrs::ReadNone); + let sink_ty = m.func_ty(void, &[i32t]); + let sink = m.declare("dx.op.storeOutput.i32", sink_ty, FnAttrs::NoUnwind); + + let x = m.call(src, &[]); + let (c5, one) = (m.i32c(5), m.f32c(0x3F80_0000)); + let exec = m.cmp(Pred::ULt, x, c5); + // v = exec ? bits(float(x) + 1) : x; v = exec ? bits(float(v) + 1) : v + let xf = m.bitcast(x, f32t); + let a = m.bin(BinOp::Add, xf, one); + let ai = m.bitcast(a, i32t); + let s1 = m.select(exec, ai, x); + let s1f = m.bitcast(s1, f32t); + let b = m.bin(BinOp::Add, s1f, one); + let bi = m.bitcast(b, i32t); + let s2 = m.select(exec, bi, s1); + m.call(sink, &[s2]); + m.ret(); + m.optimize(); + + let Value::Inst(bx) = b else { panic!() }; + assert!(matches!(m.insts[bx as usize].op, Op::Bin(BinOp::Add, v, w, _) if v == a && w == one), "b = a + 1"); + let body = &m.blocks[entry.0 as usize]; + let has = |v: Value| matches!(v, Value::Inst(i) if body.contains(&i)); + assert!(!has(s1f), "bitcast(bitcast(a)) has no uses left"); + let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); + assert!(m.uses_well_formed(&order)); + } } diff --git a/crates/xcl/src/gpu/dxil/select_tests.rs b/crates/xcl/src/gpu/dxil/select_tests.rs index 2c8e278d97..27ce61c2fc 100644 --- a/crates/xcl/src/gpu/dxil/select_tests.rs +++ b/crates/xcl/src/gpu/dxil/select_tests.rs @@ -3,7 +3,7 @@ //! inactive lanes included. use super::kernel::{translate, KernelOptions}; -use super::module::NO_SELECT_FOLD; +use super::module::{NO_PAIR_FOLD, NO_SELECT_FOLD}; use crate::gpu::rdna2::encode; use crate::gpu::recomp::runner::{self, KernelState}; @@ -111,3 +111,90 @@ fn gpu_select_fold_keeps_inactive_lanes() { } assert!(ran >= 2); } + +fn translate_pairs(code: &[u8], o: KernelOptions, pairs: bool) -> Vec { + NO_PAIR_FOLD.with(|c| c.set(!pairs)); + let r = translate(code, o); + NO_PAIR_FOLD.with(|c| c.set(false)); + r.unwrap_or_else(|e| panic!("translate (pairs {pairs}): {e}")) +} + +/// `fold_bitcast_pairs` on the GPU: float chains under a narrowed EXEC, where the select fold +/// leaves `bitcast(bitcast(x))` between the operations, give the same words with the pairs +/// folded: NaN payloads (quiet and signalling), signed zeros, infinities and denormals. +#[test] +fn gpu_bitcast_pair_fold_keeps_words() { + match (runner::adapter(), runner::wave64_programs_supported()) { + (Ok(_), Ok(true)) => {} + (a, _) => return runner::skip_test(if a.is_err() { "no GPU" } else { "no wave64" }), + } + let code = prog(&[ + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 0)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 2)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 4), ("SRC1", V + 3), ("SRC2", V + 4)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 4)]), + ("V_MAX_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 4), ("VSRC1", 0)]), + ("V_MIN_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 6), ("VSRC1", 5)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 8), ("SRC0", V + 7), ("VSRC1", 4)]), + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 9), ("SRC0", 0xFA), ("VSRC0", 8), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 8), ("SRC1", 131)]), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 8), ("VSRC1", 9)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 10), ("VSRC1", 6)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 4), ("VSRC1", 7)]), + ]); + // NaNs with payloads (quiet, signalling), signed zeros, infinities, denormals, ordinary values + const EDGE: [u32; 14] = [0x7FC0_1234, 0xFFC0_DEAD, 0x7F80_0001, 0x0000_0000, 0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x0000_0001, 0x807F_FFFF, 0x3FC0_0000, 0xC000_0000, 0x3F80_0000, 0x4120_0000, 0xBE80_0000]; + let mut st = KernelState::default(); + let mut x = 0x2545_F491_4F6C_DD1Du64; + for (l, r) in st.vgpr.iter_mut().enumerate() { + for w in r.iter_mut().take(4) { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + *w = if x % 3 == 0 { x as u32 } else { EDGE[(x >> 8) as usize % EDGE.len()] }; + } + for (k, w) in r.iter_mut().enumerate().skip(4).take(8) { + *w = 0xA000_0000 | (l as u32) << 8 | k as u32; + } + } + (st.sgpr[0], st.sgpr[1]) = (0xF0F0_5A3C, 0x0FF0_C3A5); + (st.sgpr[2], st.sgpr[3]) = (0x3333_FF0F, 0xFFFF_3333); + let mut ran = 0; + for (wave64, split) in [(false, false), (true, true), (true, false)] { + if wave64 && !split && runner::wave64_supported() != Ok(true) { + continue; + } + let o = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let (old, new) = (translate_pairs(&code, o, false), translate_pairs(&code, o, true)); + assert!(new.len() < old.len(), "wave64 {wave64} split {split}: no pairs folded ({} -> {} B)", old.len(), new.len()); + let a = runner::run(&old, &st, &[]).expect("GPU run without the pair fold"); + let b = runner::run(&new, &st, &[]).expect("GPU run with the pair fold"); + let lanes = if wave64 { 64 } else { 32 }; + let mut bad = Vec::new(); + for l in 0..lanes { + for k in 0..12 { + if a.vgpr[l][k] != b.vgpr[l][k] { + bad.push(format!("lane {l} v{k}: {:#010x} without, {:#010x} with", a.vgpr[l][k], b.vgpr[l][k])); + } + } + // lanes off from the start keep their sentinels + let on = (st.sgpr[l / 32] >> (l % 32)) & 1 == 1; + if !on { + for k in [4, 5, 6, 7, 8, 10] { + assert_eq!(b.vgpr[l][k], st.vgpr[l][k], "wave64 {wave64} split {split}: lane {l} v{k} was written while off"); + } + } + } + for k in 0..128 { + if a.sgpr[k] != b.sgpr[k] { + bad.push(format!("s{k}: {:#010x} without, {:#010x} with", a.sgpr[k], b.sgpr[k])); + } + } + assert!(bad.is_empty(), "wave64 {wave64} split {split}:\n{}", bad.join("\n")); + ran += 1; + } + assert!(ran >= 2); +}