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
905 changes: 888 additions & 17 deletions crates/xcl/src/gpu/dxil/cfg.rs

Large diffs are not rendered by default.

95 changes: 73 additions & 22 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! The compact form: each distinct block of a program lowered once, in a loop over a table.

use super::cfg::{Cfg, Term};
use super::cfg::{Cfg, CfgOp, Term};
use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET};
use super::lower_mem::VAR_TMP;
use super::module::{Block, Pred, Value};
use std::collections::{BTreeSet, HashMap};
use std::collections::{BTreeMap, BTreeSet, HashMap};

pub struct Plan {
/// the reachable blocks in address order: the loop's block numbers
Expand Down Expand Up @@ -41,21 +41,31 @@ impl Plan {

/// Whether a program takes the form by itself: large, mostly repeated blocks, small tables.
pub fn wanted(cfg: &Cfg, p: &Plan, tables: usize) -> bool {
let insts = |n: usize| cfg.blocks[p.order[n]].insts.len();
let insts = |n: usize| cfg.blocks[p.order[n]].ops.iter().filter(|op| matches!(op, CfgOp::Inst(_))).count();
let all: usize = (0..p.order.len()).map(insts).sum();
let once: usize = p.rep.iter().map(|&n| insts(n)).sum();
large(cfg) && once * 10 < all * 3 && p.words() <= tables
}

/// Whether a program is large enough for `wanted` to be asked.
pub fn large(cfg: &Cfg) -> bool {
cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::<usize>() >= 20_000
cfg.rpo
.iter()
.map(|&b| cfg.blocks[b].ops.iter().filter(|op| matches!(op, CfgOp::Inst(_))).count())
.sum::<usize>()
>= 20_000
}

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_with(cfg, &lw.static_samplers, &lw.whole_live)
}

/// Like [`plan`], taking `static_samplers` and `whole_live` explicitly so callers
/// can check compact eligibility before `Lw` construction or `s_cbranch_execz` collapsing.
pub fn plan_with(cfg: &Cfg, static_samplers: &BTreeMap<u64, [u32; 4]>, whole_live: &BTreeMap<u64, u128>) -> 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 @@ -68,22 +78,39 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
for (n, &b) in order.iter().enumerate() {
let blk = &cfg.blocks[b];
let mut key = vec![cfg.headers.contains(&b) as u64];
for &i in &blk.insts {
let d = &cfg.insts[i];
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);
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) {
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));
}
if d.inst.name == "S_GETPC_B64" {
key.push(d.pc);
for op in &blk.ops {
match op {
CfgOp::Inst(i) => {
let d = &cfg.insts[*i];
key.push(0);
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 = 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) = 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));
}
if d.inst.name == "S_GETPC_B64" {
key.push(d.pc);
}
}
CfgOp::SaveExecZ { id, regs } => {
key.push(1);
key.push(*id as u64);
key.push(regs.len() as u64);
key.extend(regs.iter().map(|&r| r as u64));
}
CfgOp::RestoreIfExecZ { id, regs } => {
key.push(2);
key.push(*id as u64);
key.push(regs.len() as u64);
key.extend(regs.iter().map(|&r| r as u64));
}
}
}
let (end, to) = match blk.term {
Expand Down Expand Up @@ -301,8 +328,32 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block
let l = lw.sub(left, one);
lw.s.m.store(budget, l, 4);
}
for &i in &blk.insts {
lw.inst(&cfg.insts[i])?;
let mut saved_execz: HashMap<u32, (Value, Vec<(u32, Value)>)> = HashMap::new();
for op in &blk.ops {
match op {
CfgOp::Inst(i) => lw.inst(&cfg.insts[*i])?,
CfgOp::SaveExecZ { id, regs } => {
let lo = lw.sreg(126);
let mask = if lw.wave64 {
let hi = lw.sreg(127);
lw.or(lo, hi)
} else {
lo
};
let was_zero = lw.cmpc(Pred::Eq, mask, 0);
let snap: Vec<(u32, Value)> = regs.iter().map(|&r| (r, lw.rd(r))).collect();
saved_execz.insert(*id, (was_zero, snap));
}
CfgOp::RestoreIfExecZ { id, regs } => {
let (was_zero, snap) = saved_execz.remove(id).expect("paired SaveExecZ");
debug_assert_eq!(snap.len(), regs.len());
for (r, old) in snap {
let cur = lw.rd(r);
let v = lw.sel(was_zero, old, cur);
lw.wr(r, v);
}
}
}
}
let next = match blk.term {
Term::End => lw.c(END),
Expand Down
8 changes: 4 additions & 4 deletions crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ fn early_outs(copies: usize) -> Vec<u8> {
fn branches_to_many_places_keep_their_target_in_the_entry() {
let code = early_outs(1000);
let cfg = super::cfg::Cfg::build(&code).unwrap();
let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
let leaders = cfg.orig_leaders.clone();
let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel);
let p = super::compact::plan(&cfg, &lw).unwrap();
Expand Down Expand Up @@ -161,7 +161,7 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]));
v.extend(i("S_ENDPGM", "ENC_SOPP", &[]));
let cfg = super::cfg::Cfg::build(&v).unwrap();
let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
let leaders = cfg.orig_leaders.clone();
let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel);
let p = super::compact::plan(&cfg, &lw).unwrap();
Expand Down Expand Up @@ -216,7 +216,7 @@ fn gpu_compact_inline_table_above_old_cap_checks_late_entries() {
let code = two_segments(COPIES);
let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 };
let cfg = super::cfg::Cfg::build(&code).unwrap();
let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
let leaders = cfg.orig_leaders.clone();
let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel);
let p = super::compact::plan(&cfg, &lw).unwrap();
assert!(p.inline && p.words() > 8192 && p.words() <= 12288);
Expand Down Expand Up @@ -312,7 +312,7 @@ fn nested_compact_ir_structure_bounds_switch_fanout_and_merge_fanin() {
// 4 groups of sizes (4, 4, 4, 1), exercising full inner switches and a singleton tail group.
let code = multi_class_program(11, 3);
let cfg = super::cfg::Cfg::build(&code).unwrap();
let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
let leaders = cfg.orig_leaders.clone();
let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 };

let inspect = |nest: Nest| -> (usize, usize, usize, usize) {
Expand Down
65 changes: 65 additions & 0 deletions crates/xcl/src/gpu/dxil/core_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -632,3 +632,68 @@ fn dot8_u32_u4_unclamped_lowers_to_dot4_add_u8_packed() {
let dis_clamped = super::validate::disassemble(&dxil_clamped).unwrap();
assert!(!dis_clamped.contains("dot4AddPacked"), "clamped dot8 should stay 64-bit saturating:\n{dis_clamped}");
}

/// Collapsed forward `s_cbranch_execz` regions (triggered above the block threshold)
/// produce bit-exact SGPRs, SCC, EXEC, and per-lane VGPRs matching the HLSL reference
/// across EXEC == 0, partial EXEC, and full EXEC.
#[test]
fn collapsed_execz_kernel_matches_hlsl_on_gpu() {
use crate::gpu::recomp::{self, runner::{self, KernelState}, Options};
let mut seq: Vec<(&str, &str, &[(&str, u64)], Option<u32>)> = Vec::new();
// 70 repeated nested `s_cbranch_execz` blocks (> 128 blocks total so Pass 2 triggers).
// Each iteration saves EXEC, narrows via `s_and_saveexec_b64`, conditionally modifies
// v1, v2, live-out SGPR s10, and SCC, then restores EXEC via `s_mov_b64 exec, s[4:5]`.
for _ in 0..70 {
seq.push(("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 2)], None));
seq.push(("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 6)], None));
seq.push(("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 8)], None));
seq.push(("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 3)], None));
seq.push(("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)], None));
seq.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None));
seq.push(("V_XOR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 10), ("VSRC1", 2)], None));
seq.push(("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 6)], None));
seq.push(("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 4)], None));
}
let code = prog(&seq);
// Verify CFG actually collapsed to 1 block!
let cfg = super::cfg::Cfg::build_for(&code, true, true).unwrap();
assert_eq!(cfg.rpo.len(), 1, "expected 70 nested execz blocks to collapse to 1, got {}", cfg.rpo.len());
let split = runner::split_wave64() || runner::wave64_supported() != Ok(true);
let dxil = translate(&code, KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }).unwrap();
if runner::adapter().is_err() || runner::wave64_programs_supported() != Ok(true) || recomp::dxc::location().is_err() {
return;
}
let hlsl = recomp::translate(&code, &Options { wave64: true, split_wave64: split, ..Default::default() }).unwrap();
let hlsl_dxil = recomp::dxc::compile(&hlsl.hlsl, "main", "cs_6_6", &[]).unwrap();

// Test 3 cases: (EXEC, s[2:3], s[8:9]) covering EXEC==0, partial EXEC, and full EXEC
let cases: [(u64, u64, u64); 3] = [
(0, 0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF_FFFF_FFFF),
(0x0F0F_0F0F_0F0F_0F0F, 0x00FF_00FF_00FF_00FF, 0x0555_0555_0555_0555),
(0xFFFF_FFFF_FFFF_FFFF, 0xAAAA_AAAA_AAAA_AAAA, 0xCCCC_CCCC_CCCC_CCCC),
];
for (exec, m1, m2) in cases {
let mut st = KernelState::default();
st.sgpr[126] = exec as u32;
st.sgpr[127] = (exec >> 32) as u32;
st.sgpr[2] = m1 as u32;
st.sgpr[3] = (m1 >> 32) as u32;
st.sgpr[8] = m2 as u32;
st.sgpr[9] = (m2 >> 32) as u32;
st.sgpr[10] = 0x1234_5678;
st.scc = 1;
for lane in 0..64 {
st.vgpr[lane][1] = 100 + lane as u32;
st.vgpr[lane][2] = 0xDEAD_0000 | lane as u32;
}
let ref_out = runner::run(&hlsl_dxil, &st, &[]).unwrap();
let got_out = runner::run(&dxil, &st, &[]).unwrap();
assert_eq!((got_out.sgpr[126], got_out.sgpr[127]), (ref_out.sgpr[126], ref_out.sgpr[127]), "exec mismatch for exec={exec:#x}");
assert_eq!(got_out.scc, ref_out.scc, "scc mismatch for exec={exec:#x}");
assert_eq!(got_out.sgpr[10], ref_out.sgpr[10], "s10 mismatch for exec={exec:#x}");
for lane in 0..64 {
assert_eq!(got_out.vgpr[lane][1], ref_out.vgpr[lane][1], "v1[{lane}] mismatch for exec={exec:#x}");
assert_eq!(got_out.vgpr[lane][2], ref_out.vgpr[lane][2], "v2[{lane}] mismatch for exec={exec:#x}");
}
}
}
Loading
Loading