Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,22 @@ pub(super) fn atomic_candidate(cfg: &Cfg) -> bool {
}

pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option<Plan> {
automatic_plan_impl(cfg, Some(lw), split_compute)
}

/// True when `code` qualifies for `automatic_plan` (`large()` or `split_compute && atomic_candidate()`)
/// under compact direct-DXIL lowering.
pub(crate) fn prefers_compact(code: &[u8], split_compute: bool) -> bool {
let Ok(cfg) = Cfg::build(code) else {
return false;
};
automatic_plan_impl(&cfg, None, split_compute).is_some()
}

fn automatic_plan_impl(cfg: &Cfg, lw: Option<&Lw>, split_compute: bool) -> Option<Plan> {
let large = large(cfg);
if !large && !(split_compute && atomic_candidate(cfg)) { return None; }
let p = plan(cfg, lw)?;
let p = plan_impl(cfg, lw)?;
if p.words() > MAX_TABLE_WORDS { return None; }
let insts = |n: usize| cfg.blocks[p.order[n]].insts.len();
let all: usize = (0..p.order.len()).map(insts).sum();
Expand All @@ -67,6 +80,10 @@ pub const END: u32 = u32::MAX;

/// Sorts the reachable blocks into classes the lowering would emit the same for.
pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
plan_impl(cfg, Some(lw))
}

fn plan_impl(cfg: &Cfg, lw: Option<&Lw>) -> Option<Plan> {
let mut order = cfg.rpo.clone();
order.sort_by_key(|&b| (cfg.blocks[b].pc, b));
let mut number = vec![END; cfg.blocks.len()];
Expand All @@ -84,11 +101,11 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
key.push(d.words.len() as u64);
key.extend(d.words.iter().map(|&w| w as u64));
key.push(d.literal.map_or(u64::MAX, |l| l as u64));
let sampler = lw.static_samplers.get(&d.pc);
let sampler = lw.and_then(|l| l.static_samplers.get(&d.pc));
key.push(sampler.is_some() as u64);
key.extend(sampler.into_iter().flatten().map(|&w| w as u64));
// what `Lw::write_mask` asks of this address, for any register a mask can go to
if let Some(&l) = lw.whole_live.get(&d.pc) {
if let Some(&l) = lw.and_then(|l| l.whole_live.get(&d.pc)) {
let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST"));
let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa);
key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3));
Expand Down
25 changes: 25 additions & 0 deletions crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,3 +421,28 @@ fn gpu_nested_compact_matches_plain_and_flat() {
.expect("nested budget GPU run");
assert_eq!((got3.sgpr, got3.vgpr, got3.scc), (plain3.sgpr, plain3.vgpr, plain3.scc), "nested loop budget");
}

#[test]
fn prefers_compact_requires_both_large_and_automatic_plan() {
let rep = repeated(2400);
assert!(
crate::gpu::dxil::compact::prefers_compact(&rep, false),
"large repetitive branch-heavy program must prefer compact direct DXIL"
);
let small = repeated(4);
assert!(
!crate::gpu::dxil::compact::prefers_compact(&small, false),
"small program must not defer to compact"
);
// Large (>=20,000 instructions) but single non-repetitive basic block: `large()` is true, `automatic_plan` is None.
let mut big_flat = Vec::with_capacity(20_050 * 4);
for i in 0u32..20_020 {
let dst = i % 64;
big_flat.extend_from_slice(&(0x8000_0000u32 | (dst << 16) | (dst << 8) | ((i + 1) % 64)).to_le_bytes());
}
big_flat.extend_from_slice(&0xBF81_0000u32.to_le_bytes()); // S_ENDPGM
assert!(
!crate::gpu::dxil::compact::prefers_compact(&big_flat, false),
"large but non-repetitive program must NOT defer to compact"
);
}
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/dxil/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

pub mod bitstream;
pub mod cfg;
mod compact;
pub(crate) mod compact;
pub mod container;
pub mod coverage;
pub mod graphics;
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/gpu/recomp/lower_dxil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,11 @@ pub fn enabled() -> bool {
std::env::var("XCL_PER_LANE").is_ok_and(|v| v == "1")
}

/// Maximum DXIL size (512 KiB) accepted from the per-lane compute lowering before
/// `pso::direct_compute` tries the per-instruction direct DXIL path (which supports
/// `compact` table lowering and `split_compute` dispatch chains).
pub(crate) const MAX_COMPUTE_DXIL_BYTES: usize = 512 << 10;

/// A compute program in its per-lane form with the runtime's options `o` (`pso::direct_compute`):
/// the container and its static samplers.
pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> Result<crate::gpu::dxil::kernel::Kernel, String> {
Expand Down
161 changes: 149 additions & 12 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1242,23 +1242,88 @@ pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split
let wave64 = super::fssm_wave64(f, code);
let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base };
// `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses
// (and for a program that reads constant data in its code: the per-lane form has no table)
if super::lower_dxil::enabled() && !(!rodata.is_empty() && takes_code_address(code)) {
match super::lower_dxil::compute_with(code, &cs, o) {
Ok(k) => {
crate::gpu::dxil::coverage::record_translated("CS per-lane");
dump_direct(blob, &k.dxil);
return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None });
// (and for a program that reads constant data in its code: the per-lane form has no table;
// or when compact lowering qualifies via `automatic_plan`, or per-lane DXIL exceeds 512 KiB).
let use_per_lane = super::lower_dxil::enabled() && !(!rodata.is_empty() && takes_code_address(code));
let prefer_compact = use_per_lane && crate::gpu::dxil::compact::prefers_compact(code, o.split);
let (k, used_per_lane) = choose_compute_kernel(
use_per_lane,
prefer_compact,
super::lower_dxil::MAX_COMPUTE_DXIL_BYTES,
|| super::lower_dxil::compute_with(code, &cs, o),
|| crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata),
)?;
if used_per_lane {
crate::gpu::dxil::coverage::record_translated("CS per-lane");
}
dump_direct(blob, &k.dxil);
Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None })
}

/// Select between per-lane (`lower_dxil`) and per-instruction (`translate_compute_rodata`) direct
/// DXIL for a compute shader:
/// - When `prefer_compact` (`compact::automatic_plan`), try per-instruction first and fall back
/// to per-lane on error so a failed rodata translation never drops straight to HLSL.
/// - Otherwise try per-lane first; if its DXIL exceeds `max_per_lane_bytes`, compare against
/// per-instruction (logging any error) and keep whichever is split or smaller.
fn choose_compute_kernel(
use_per_lane: bool,
prefer_compact: bool,
max_per_lane_bytes: usize,
mut per_lane: impl FnMut() -> Result<crate::gpu::dxil::kernel::Kernel, String>,
mut per_inst: impl FnMut() -> Result<crate::gpu::dxil::kernel::Kernel, String>,
) -> Result<(crate::gpu::dxil::kernel::Kernel, bool), String> {
if !use_per_lane {
return per_inst().map(|k| (k, false));
}
if prefer_compact {
match per_inst() {
Ok(k) => return Ok((k, false)),
Err(e) => {
crate::xlog_warn!(
"[SHADER] compact-preferred per-instruction compute failed ({}); falling back to per-lane form",
e.lines().next().unwrap_or("")
);
return match per_lane() {
Ok(k) => Ok((k, true)),
Err(_) => Err(e),
};
}
}
}
match per_lane() {
Ok(k) if k.dxil.len() <= max_per_lane_bytes => Ok((k, true)),
Ok(k) => match per_inst() {
Ok(alt) if alt.dispatch_chain.is_some() || alt.dxil.len() < k.dxil.len() => {
crate::xlog_info!(
"[SHADER] per-lane DXIL {} B exceeded {} B cap – using per-instruction form ({} B, split={})",
k.dxil.len(),
max_per_lane_bytes,
alt.dxil.len(),
alt.dispatch_chain.is_some()
);
Ok((alt, false))
}
Ok(_) => Ok((k, true)),
Err(e) => {
let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e);
crate::xlog_info!("[SHADER] per-lane fallback reason=\"{reason}\" detail=\"{}\" – per-instruction form", e.lines().next().unwrap_or(""));
crate::xlog_warn!(
"[SHADER] per-lane DXIL {} B exceeded {} B cap, per-instruction form failed ({}); keeping per-lane DXIL",
k.dxil.len(),
max_per_lane_bytes,
e.lines().next().unwrap_or("")
);
Ok((k, true))
}
},
Err(e) => {
let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e);
crate::xlog_info!(
"[SHADER] per-lane fallback reason=\"{reason}\" detail=\"{}\" – per-instruction form",
e.lines().next().unwrap_or("")
);
per_inst().map(|k| (k, false))
}
}
let k = crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata)?;
dump_direct(blob, &k.dxil);
Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None })
}

/// `XCL_DXIL_DUMP=<hash>[,<hash>…]` (`[SHADER]` hashes, or `all`): writes the direct path's
Expand Down Expand Up @@ -2925,3 +2990,75 @@ mod compile_time_bench {
println!("100 repeated PSO shader requests, warm DXIL cache, ms: {batches:?}");
}
}

#[cfg(test)]
mod pr2796_tests {
use super::*;
use crate::gpu::dxil::kernel::Kernel;

fn fake_kernel(len: usize) -> Kernel {
Kernel {
dxil: vec![0u8; len],
static_samplers: Vec::new(),
dispatch_chain: None,
}
}

#[test]
fn choose_compute_kernel_early_defer_falls_back_to_per_lane_on_rodata_err() {
let (k, used_pl) = choose_compute_kernel(
true,
true,
512 << 10,
|| Ok(fake_kernel(64 << 10)),
|| Err("rodata lowering unsupported".into()),
)
.expect("must fall back to per-lane instead of sending to HLSL");
assert!(used_pl);
assert_eq!(k.dxil.len(), 64 << 10);
}

#[test]
fn choose_compute_kernel_early_defer_uses_compact_when_ok() {
let mut pl_called = false;
let (k, used_pl) = choose_compute_kernel(
true,
true,
512 << 10,
|| {
pl_called = true;
Ok(fake_kernel(900 << 10))
},
|| Ok(fake_kernel(120 << 10)),
)
.unwrap();
assert!(!pl_called, "early defer must skip per-lane when compact succeeds");
assert!(!used_pl);
assert_eq!(k.dxil.len(), 120 << 10);
}

#[test]
fn choose_compute_kernel_over_cap_picks_smaller_or_keeps_per_lane_on_err() {
let (k, used_pl) = choose_compute_kernel(
true,
false,
512 << 10,
|| Ok(fake_kernel(700 << 10)),
|| Ok(fake_kernel(200 << 10)),
)
.unwrap();
assert!(!used_pl);
assert_eq!(k.dxil.len(), 200 << 10);

let (k2, used_pl2) = choose_compute_kernel(
true,
false,
512 << 10,
|| Ok(fake_kernel(700 << 10)),
|| Err("per-instruction failed".into()),
)
.unwrap();
assert!(used_pl2, "must keep per-lane DXIL when per-instruction fails");
assert_eq!(k2.dxil.len(), 700 << 10);
}
}
Loading