Skip to content
Draft
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
2 changes: 1 addition & 1 deletion crates/xcl/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf};
// `pso.rs` also contains cache storage and pipeline setup. Keep it out of the source hash so
// those changes do not discard translations; bump this only when its container parsing,
// translation options, profiles, or post-translation HLSL changes.
const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v2";
const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v3";

const TRANSLATOR_SOURCES: &[&str] = &[
"src/gpu/dxbc.rs",
Expand Down
58 changes: 54 additions & 4 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,10 @@ fn translate_on_this_thread(
[1, 1, 1]
}
};
// Entry setup may contain real control flow (compute dispatch limits use a guarded
// prologue). The program must start after that prologue's join, not by appending another
// branch to the already-terminated physical entry block.
let prologue = lw.cur();
// the HLSL kernel loads and stores every register its emitted instructions name: all of
// them in a program with branches, those up to the first s_endpgm in straight-line code
let branchy = cfg.insts.iter().any(|d| crate::gpu::rdna2::branch_target(d).is_some());
Expand Down Expand Up @@ -325,12 +329,12 @@ fn translate_on_this_thread(
if gs_only {
// the GS alone: in the lower hardware wave only
let gate = lw.block(Some(1));
lw.edge(Block(0), gate);
lw.edge(prologue, gate);
lw.s.m.set_block(gate);
let up = lw.upper;
lw.cond_br(up, exit, h0);
} else {
lw.edge(Block(0), h0);
lw.edge(prologue, h0);
}
let switch = if two_phase { Some(lw.block(None)) } else { None };
// scalar loads the program repeats keep their first values (compute programs and kernels:
Expand Down Expand Up @@ -440,7 +444,7 @@ fn translate_on_this_thread(
}
}
lw.s.m.ret();
lw.s.m.set_block(Block(0));
lw.s.m.set_block(prologue);
lw.s.m.br(h0);
let hw = if split || !o.wave64 { 32 } else { 64 };
let limit = if compute && (!split || split_tid.is_some()) { dispatch_piece_limit() } else { 0 };
Expand Down Expand Up @@ -474,7 +478,7 @@ impl Lw {
/// `entry`: the shader with its buffers,
/// the SSA's entry block, the program's LDS and the split form's exchange storage and
/// partner. The caller then sets up the lanes for its entry (`setup_lanes*`), lowers the
/// program's blocks, branches from `Block(0)` to the first of them and ends with
/// program's blocks, branches from the entry prologue's exit to the first of them and ends with
/// [`Lw::finish`]. #1426's block walk (`translate_on_this_thread`) and the recompiler's
/// per-lane lowering (`recomp::lower_dxil`) both build their `Lw` here.
pub fn new(insts: &[Decoded], leaders: &BTreeSet<u64>, o: KernelOptions, entry: &Entry) -> Lw {
Expand Down Expand Up @@ -644,6 +648,15 @@ impl Lw {
}
}

#[cfg(test)]
#[test]
fn compute_dispatch_limit_prologue_reaches_the_program_after_its_guard() {
let code = crate::gpu::rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap();
let cs = CsInterface { threads: [64, 1, 1], ..Default::default() };
let options = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 };
translate_compute(&code, options, &cs).expect("a guarded dispatch-limit prologue");
}

#[cfg(test)]
#[test]
fn dispatch_chain_native_wave64_builds_whole() {
Expand Down Expand Up @@ -741,7 +754,44 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3])
}
let zero = lw.c(0);
sgpr.insert(VAR_SCC, zero);
let io = lw.init.io.expect("the I/O buffer");
let mut dispatch_limited = lw.s.m.i1c(false);
let mut limits = Vec::new();
for (k, _) in cs.threads.iter().enumerate().filter(|(_, &threads)| threads > 1) {
let off = lw.c((crate::gpu::recomp::IO_THREAD_LIMIT[k] * 4) as u32);
let limit = lw.s.raw_load(io, off, 1)[0];
let zero = lw.c(0);
let limited = lw.cmp(Pred::Ne, limit, zero);
dispatch_limited = lw.lor(dispatch_limited, limited);
limits.push((k, limit));
}
let (lo, hi) = entry_exec(lw, total, tid);
let (exec_lo, exec_hi) = (lw.tmp_var(), lw.tmp_var());
lw.wr(exec_lo, lo);
lw.wr(exec_hi, hi);
let _ = lw.guarded(dispatch_limited, &mut |lw| {
let mut dispatch_live = lw.s.m.i1c(true);
for &(k, limit) in &limits {
let zero = lw.c(0);
let unlimited = lw.cmp(Pred::Eq, limit, zero);
let group = lw.s.group_id(k as u32);
let width = lw.c(cs.threads[k]);
let base = lw.mul(group, width);
let id = lw.add(base, gtid[k]);
let inside = lw.cmp(Pred::ULt, id, limit);
let axis_live = lw.lor(unlimited, inside);
dispatch_live = lw.land(dispatch_live, axis_live);
}
let (dispatch_lo, dispatch_hi) = lw.ballot(dispatch_live);
let old_lo = lw.rd(exec_lo);
let old_hi = lw.rd(exec_hi);
let lo = lw.and(old_lo, dispatch_lo);
let hi = lw.and(old_hi, dispatch_hi);
lw.wr(exec_lo, lo);
lw.wr(exec_hi, hi);
Ok(())
});
let (lo, hi) = (lw.rd(exec_lo), lw.rd(exec_hi));
sgpr.insert(126, lo);
sgpr.insert(127, hi);
let mut vgpr = HashMap::new();
Expand Down
46 changes: 45 additions & 1 deletion crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl Init {
}
let v = self.first(s, var);
let cur = s.m.current_block();
let before = s.m.set_insert_before_term(false);
let before = s.m.set_insert_before_term(true);
s.m.set_block(self.entry);
let i32 = s.m.i32();
let p = s.m.alloca(i32, 4);
Expand Down Expand Up @@ -133,6 +133,7 @@ impl Init {
}
}
let cur = s.m.current_block();
let before = s.m.set_insert_before_term(true);
s.m.set_block(self.entry);
self.touched.insert(var);
let io = self.io.expect("io");
Expand All @@ -146,10 +147,53 @@ impl Init {
s.raw_load(io, off, 1)[0]
};
s.m.set_block(cur);
s.m.set_insert_before_term(before);
v
}
}

#[cfg(test)]
mod init_tests {
use super::{Init, VAR_BUDGET};
use crate::gpu::dxil::{container::Stage, shader::Shader};
use std::collections::{BTreeSet, HashMap};

fn after_terminated_entry() -> (Shader, Init) {
let mut s = Shader::new(Stage::Compute, (6, 6));
let io = s.raw_uav(0, 0);
let entry = s.m.current_block();
let body = s.m.new_block();
s.m.br(body);
s.m.set_block(body);
let init = Init {
io: Some(io),
compute: None,
vgpr_base: None,
entry,
touched: BTreeSet::new(),
slots: HashMap::new(),
mem: None,
};
(s, init)
}

#[test]
fn lazy_register_load_precedes_an_entry_terminator() {
let (mut s, mut init) = after_terminated_entry();
let _ = init.first(&mut s, 4);
s.m.ret();
s.try_finish([1, 1, 1], None).expect("lazy register load after an entry branch");
}

#[test]
fn compact_register_slot_precedes_an_entry_terminator() {
let (mut s, mut init) = after_terminated_entry();
let _ = init.slot(&mut s, VAR_BUDGET);
s.m.ret();
s.try_finish([1, 1, 1], None).expect("compact register slot after an entry branch");
}
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Partner {
Present,
Expand Down
18 changes: 17 additions & 1 deletion crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5082,7 +5082,23 @@ impl Em {
// waves in the group: a last, partial wave counts (96 threads: 2 of 64)
let _ = writeln!(h, " {} = {}u | ((gi / {lanes}u) << 6);", sname(next).unwrap(), (x * y * z).div_ceil(lanes));
}
let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn());
h.push_str(" bool xcl_dispatch_limited = false;\n");
for (k, c) in ["x", "y", "z"].iter().enumerate().filter(|(k, _)| cs.threads[*k] > 1) {
let slot = super::IO_THREAD_LIMIT[k] * 4;
let _ = writeln!(h, " uint xcl_limit_{c} = io.Load({slot}u);\n xcl_dispatch_limited = xcl_dispatch_limited || xcl_limit_{c} != 0u;");
}
let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0;");
let _ = writeln!(h, " if (xcl_dispatch_limited) {{\n bool xcl_dispatch_live = true;");
for (k, c) in ["x", "y", "z"].iter().enumerate().filter(|(k, _)| cs.threads[*k] > 1) {
let group = match remap {
Some((ratio, dim, _)) if dim == k => format!("(gid.{c} / {ratio}u)"),
_ => format!("gid.{c}"),
};
let threads = cs.threads[k];
let _ = writeln!(h, " xcl_dispatch_live = xcl_dispatch_live && (xcl_limit_{c} == 0u || {group} * {threads}u + gtid.{c} < xcl_limit_{c});");
}
let ballot = self.ballot_fn();
let _ = writeln!(h, " e0 = {ballot}(xcl_dispatch_live);\n }} else {{\n e0 = {ballot}(true);\n }}\n exec_lo = e0.x; exec_hi = e0.y; }}");
for &v in &self.vgprs {
let init = match v {
0 => "gtid.x",
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,11 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21;
pub const IO_GS_PRIMS: usize = 110;
pub const IO_GS_VERTICES: usize = 111;
pub const IO_UMA_BASE_HI: usize = 112;
/// io slots of a `DispatchX` with thread dimensions (flag 0x20): the thread count of each axis
/// when it is not a whole number of groups (0: the last group is whole), so the program can leave
/// the lanes past it out of EXEC. Written by D3D12.X and read by both compute backends.
/// (113 is left for the group-limit slot of #1428.)
pub const IO_THREAD_LIMIT: [usize; 3] = [114, 115, 116];

impl GsInterface {
/// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register)
Expand Down
26 changes: 24 additions & 2 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1012,13 +1012,19 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool {
/// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in
/// registers. None: not a console compute shader.
pub fn compute_user_sgprs(blob: &[u8]) -> Option<u32> {
compute_interface(blob).map(|cs| cs.user_sgprs)
}

/// The dispatch ABI of a console compute program: its user SGPRs and the console's group shape
/// (`numthreads`). None: not a console compute program.
pub fn compute_interface(blob: &[u8]) -> Option<super::CsInterface> {
if let Some(f) = fspx(blob) {
return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2).user_sgprs);
return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2));
}
let sh = xbox::parse(blob)?;
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?;
match interface(blob, &sh, f)? {
Mode::Compute(cs) => Some(cs.user_sgprs),
Mode::Compute(cs) => Some(cs),
_ => None,
}
}
Expand Down Expand Up @@ -1048,6 +1054,9 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo
let sh = xbox::parse(blob).ok_or("not a console shader container")?;
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?;
let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) };
if direct_compute_needs_hlsl(&cs) {
return Err("multidimensional groups need the HLSL console-linear thread reorder".into());
}
let p = f.programs.first().ok_or("FSSM without a program")?;
let code = &f.data[p.offset..p.offset + p.len];
let wave64 = super::fssm_wave64(f, code);
Expand All @@ -1071,6 +1080,19 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo
Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None })
}

fn direct_compute_needs_hlsl(cs: &super::CsInterface) -> bool {
cs.threads[1] > 1 || cs.threads[2] > 1
}

#[cfg(test)]
#[test]
fn direct_compute_routes_multidimensional_thread_groups_to_hlsl() {
let cs = |threads| super::CsInterface { threads, user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 3 };
assert!(!direct_compute_needs_hlsl(&cs([64, 1, 1])));
assert!(direct_compute_needs_hlsl(&cs([8, 8, 1])));
assert!(direct_compute_needs_hlsl(&cs([4, 4, 4])));
}

/// `XCL_DXIL_DUMP=<hash>[,<hash>…]` (`[SHADER]` hashes, or `all`): writes the direct path's
/// DXIL to `%TEMP%\xcl-dxil-dump\<hash>.dxil` (with `XCL_TRANSLATED_CACHE=0`, so cached
/// translations are redone).
Expand Down
67 changes: 65 additions & 2 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5178,10 +5178,19 @@ fn gpu_compute_mode_dispatch_abi() {
("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None),
("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 9), ("DATA", 11), ("SADDR", 0x7D)], None),
]);
let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() });
let opt = on_gpu(Options { mode: Mode::Compute(cs.clone()), wave64: true, ..Default::default() });
let t = translate(&p, &opt).unwrap();
assert!(t.complete(), "{:?}", t.unsupported_why);
let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")));
let hlsl_dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"));
let split = opt.wave64 && (opt.split_wave64 || runner::split_wave64());
let direct_dxil = crate::gpu::dxil::kernel::translate_compute(
&p,
crate::gpu::dxil::kernel::KernelOptions { wave64: opt.wave64, split, mem_windows: opt.mem_windows, sampler_base: opt.static_sampler_base },
&cs,
)
.unwrap_or_else(|e| panic!("direct DXIL: {e}"))
.dxil;
let dxil = if direct_enabled(&opt) { direct_dxil.clone() } else { hlsl_dxil.clone() };
let (w, h, base) = (32usize, 24usize, 0x100usize);
let mut io = vec![0u32; 128];
io[0] = base as u32;
Expand All @@ -5196,6 +5205,24 @@ fn gpu_compute_mode_dispatch_abi() {
assert_eq!(out[at + 1], (px | py << 16) as u32, "({x}, {y}): value of thread {} through LDS", 127 - i);
}
}

// DispatchX thread limits seed EXEC in both backends. The hardware groups still contain
// 32x24 threads, but only the 20x17 console dispatch rectangle may reach memory.
for (backend, dxil) in [("HLSL", hlsl_dxil), ("direct DXIL", direct_dxil)] {
let mut limited_io = io.clone();
limited_io[super::IO_THREAD_LIMIT[0]] = 20;
limited_io[super::IO_THREAD_LIMIT[1]] = 17;
let sentinel = 0xA5A5_5A5Au32;
let out = runner::dispatch(&dxil, [2, 3, 1], &limited_io, &vec![sentinel; (base + w * h * 8) / 4]).unwrap();
for y in 0..h {
for x in 0..w {
let at = (base + (y * w + x) * 8) / 4;
let written = x < 20 && y < 17;
assert_eq!(out[at] != sentinel, written, "{backend} ({x}, {y}) own write");
assert_eq!(out[at + 1] != sentinel, written, "{backend} ({x}, {y}) partner write");
}
}
}
}

/// A wave32 program in a 64-lane hardware wave (what VS / PS may get from the driver): the
Expand Down Expand Up @@ -7439,6 +7466,42 @@ fn wave_local_remap_decision_and_console_ids() {
assert!(fallback.hlsl.contains("numthreads(128, 1, 1)") && fallback.hlsl.contains("#define XCL_X_SPIN 1"));
}

#[test]
fn dispatch_thread_limits_seed_compute_exec_for_native_and_remapped_groups() {
use super::{CsInterface, Mode, Options};
let p = prog(&[
("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 0), ("SADDR", 0x7D)], None),
]);
let translated = |threads, split_wave64| {
translate(
&p,
&Options {
mode: Mode::Compute(CsInterface { threads, user_sgprs: 2, tgid: [true; 3], tg_size: false, tid_components: 3 }),
wave64: true,
split_wave64,
..Default::default()
},
)
.unwrap()
};

let native = translated([8, 8, 1], false);
assert!(native.hlsl.contains("uint xcl_limit_x = io.Load(456u);"));
assert!(native.hlsl.contains("gid.x * 8u + gtid.x < xcl_limit_x"));
assert!(native.hlsl.contains("uint xcl_limit_y = io.Load(460u);"));
assert!(native.hlsl.contains("gid.y * 8u + gtid.y < xcl_limit_y"));
assert!(!native.hlsl.contains("xcl_limit_z"), "a one-thread axis is always whole");
assert!(native.hlsl.contains("if (xcl_dispatch_limited)"));
assert!(native.hlsl.contains("ballot(xcl_dispatch_live)"));
assert!(native.hlsl.contains("ballot(true)"), "ordinary Dispatch keeps the original entry ballot");

let remapped = translated([128, 1, 1], true);
assert_eq!(remapped.dispatch_remap, Some((2, 0)));
assert!(remapped.hlsl.contains("(gid.x / 2u) * 128u + gtid.x < xcl_limit_x"));
assert!(remapped.hlsl.contains("xcl_x_ballot(xcl_dispatch_live)"));
}

/// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64
/// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the
/// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32
Expand Down
Loading
Loading