diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8..f2a6096cb 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -10,6 +10,7 @@ const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/rdna2.rs", "src/gpu/rdna2_spec.rs", "src/gpu/rdna2_xbox.rs", + "src/gpu/recomp/compact.rs", "src/gpu/recomp/dxc.rs", "src/gpu/recomp/emit.rs", "src/gpu/recomp/mesh_wave.rs", diff --git a/crates/xcl/src/gpu/recomp/compact.rs b/crates/xcl/src/gpu/recomp/compact.rs new file mode 100644 index 000000000..0495d0d4d --- /dev/null +++ b/crates/xcl/src/gpu/recomp/compact.rs @@ -0,0 +1,582 @@ +//! Compact form of a very large program: every distinct block text is emitted once. +//! +//! DXC inlines every function of a cs_6_x target, so HLSL helpers do not share code: the +//! 3,281 buffer loads of a retail program become 3,281 copies of the format conversion. Here +//! the program is cut into blocks (at the leaders, and around every instruction whose HLSL is +//! long), each instruction is emitted by `emit::Em` exactly as in `translate`, with its +//! temporaries numbered from t1, and blocks with the same text and branch condition share one +//! `case` of a dispatch loop. A branch goes to the block at an offset from its own: the offset +//! most of a case's blocks jump by, and for the others the target by block index (`select`), +//! so the table (`XCL_BT`) only gives every block, in address order, its case; falling through +//! goes to the next block. The block index is the same in every lane (branch conditions are +//! wave-uniform), as `pc` of the guarded block chain is, so the split-wave64 halves walk the +//! same blocks. + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::fmt::Write as _; + +use super::{emit, prepare, rdna2, Mode, Options, Prepared, Translation, LOOP_GUARD}; + +/// Programs with fewer instructions keep the normal form (`compact_wanted`). +pub const COMPACT_MIN_INSTRUCTIONS: usize = 20_000; + +/// An instruction whose HLSL is longer than this (bytes) is a block of its own, so the blocks +/// around it can still be shared when their other instructions differ. +const HEAVY: usize = 600; + +/// Largest table (32-bit words). A static array is constant data for the driver: on an +/// RTX 5070 Ti, CreateComputePipelineState took 12,288 words and failed with E_OUTOFMEMORY +/// at 15,360. A table the usual packing makes larger is packed across words; the program falls +/// back to `translate` only when that is still larger. +const MAX_TABLE_WORDS: usize = 8192; + +/// The compact form pays: at least `COMPACT_MIN_INSTRUCTIONS` instructions, and the distinct +/// blocks (equal code, branch targets aside) hold under 30 % of them. A function of the code +/// alone; nothing is emitted. +pub fn compact_wanted(code: &[u8]) -> bool { + // an instruction has at least 4 bytes + if code.len() < 4 * COMPACT_MIN_INSTRUCTIONS { + return false; + } + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { return false }; + off += d.len; + insts.push(d); + } + if insts.len() < COMPACT_MIN_INSTRUCTIONS { + return false; + } + rdna2::resolve_far_jumps(&mut insts); + let mut leaders = BTreeSet::new(); + for d in &insts { + let t = rdna2::branch_target(d); + if t.is_some() || d.inst.flags & rdna2::F_TERMINATOR != 0 { + leaders.insert(d.pc + d.len as u64); + } + leaders.extend(t); + } + // a block's key: its code, without the last instruction's bytes when that one branches + let mut seen: HashSet<(&[u8], &str)> = HashSet::new(); + let (mut distinct, mut first, mut start) = (0usize, 0usize, 0usize); + for (k, d) in insts.iter().enumerate() { + let end = d.pc as usize + d.len; + if k + 1 < insts.len() && !leaders.contains(&(end as u64)) { + continue; + } + let key = if rdna2::branch_target(d).is_some() { (&code[start..d.pc as usize], d.inst.name) } else { (&code[start..end], "") }; + if seen.insert(key) { + distinct += k + 1 - first; + } + (first, start) = (k + 1, end); + } + distinct * 10 < insts.len() * 3 +} + +/// `recomp::translate` in the compact form (same contract and output; `Translation::blocks` +/// is the number of distinct block texts). A program without branches gets `translate`'s +/// straight-line form; geometry programs (ES → GS through s_setpc) are not supported. +pub fn translate_compact(code: &[u8], opt: &Options) -> Result { + compact(code, opt, HEAVY, MAX_TABLE_WORDS) +} + +/// One block in address order: its text, and the branch that ends it (condition, empty when +/// it always jumps; target). +struct Block { + pc: u64, + text: String, + branch: Option<(String, u64)>, +} + +fn block(pc: u64, mut text: String, flow: emit::Flow) -> Result { + let branch = match flow { + emit::Flow::Next => None, + emit::Flow::Jump(t) => Some((String::new(), t)), + emit::Flow::Cond(c, t) => Some((c, t)), + emit::Flow::End => { + text.push_str(" xcl_nb = 0xFFFFFFFFu;\n"); + None + } + emit::Flow::JumpExpr(_) => return Err(format!("+{pc:#x}: compact form: computed jump")), + }; + Ok(Block { pc, text, branch }) +} + +/// The HLSL of one instruction without its comment lines; in its own scope when it declares +/// temporaries (every instruction numbers them from t1). +fn inst_text(em: &mut emit::Em, d: &rdna2::Decoded, next: u64) -> (String, emit::Flow) { + em.reset_temps(); + let flow = em.inst(d, next); + let temps = em.reset_temps(); + let mut s = String::new(); + for l in em.take().lines().filter(|l| !l.trim_start().starts_with("//")) { + s.push_str(l); + s.push('\n'); + } + if temps > 0 && !s.is_empty() { + s = format!(" {{\n{s} }}\n"); + } + (s, flow) +} + +/// The blocks of the program in address order (`heavy`: see `HEAVY`). +fn blocks(insts: &[rdna2::Decoded], leaders: &BTreeSet, em: &mut emit::Em, heavy: usize) -> Result, String> { + em.indent = 3; + let mut out = Vec::new(); + // the open block: its address and text; `dead`: after the block's last instruction + let mut open: Option<(u64, String)> = None; + let mut dead = false; + for (i, d) in insts.iter().enumerate() { + if leaders.contains(&d.pc) { + if let Some((pc, text)) = open.take() { + out.push(block(pc, text, emit::Flow::Next)?); + } + dead = false; + } + if dead { + continue; + } + let next = insts.get(i + 1).map(|n| n.pc).unwrap_or(u64::MAX); + let (text, flow) = inst_text(em, d, next); + if text.len() > heavy && matches!(flow, emit::Flow::Next) { + if let Some((pc, text)) = open.take() { + out.push(block(pc, text, emit::Flow::Next)?); + } + out.push(block(d.pc, text, flow)?); + continue; + } + let (pc, mut body) = open.take().unwrap_or((d.pc, String::new())); + body.push_str(&text); + if matches!(flow, emit::Flow::Next) { + open = Some((pc, body)); + } else { + out.push(block(pc, body, flow)?); + dead = true; + } + } + if let Some((pc, text)) = open.take() { + out.push(block(pc, text, emit::Flow::Next)?); + } + Ok(out) +} + +/// The setting of `XCL_COMPACT_NEST`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Nest { + /// One switch over all cases. + Flat, + /// Groups of this many cases (a power of two up to `MAX_NEST`). + Groups(usize), + /// `AUTO_GROUP` cases per group for a program of `NEST_MIN_CASES` cases or more, flat below. + Auto, +} + +impl From for Nest { + fn from(p: usize) -> Nest { + if p == 0 { Nest::Flat } else { Nest::Groups(p) } + } +} + +/// `XCL_COMPACT_NEST=

`: the dispatch loop switches in two levels, on `case >> log2(P)` and +/// then inside the group of P cases (`compact_with`). A power of two up to `MAX_NEST`; unset or +/// `0`: one switch over all cases; `auto`: groups of `AUTO_GROUP` from `NEST_MIN_CASES` cases +/// on, one switch below. Anything else warns and leaves it off. Read once. +pub(super) fn nest_from_env() -> Nest { + static S: std::sync::OnceLock = std::sync::OnceLock::new(); + *S.get_or_init(|| { + let Ok(v) = std::env::var("XCL_COMPACT_NEST") else { return Nest::Flat }; + parse_nest(&v).unwrap_or_else(|| { + crate::xlog_warn!("[SHADER] XCL_COMPACT_NEST={v:?} is not 0, auto or a power of two up to {MAX_NEST} – off"); + Nest::Flat + }) + }) +} + +/// The group size of the two-level dispatch is at most this: a shift of 32 or more is masked +/// by HLSL to a shift of 0. +const MAX_NEST: usize = 1 << 16; + +/// `XCL_COMPACT_NEST=auto` nests programs of at least this many cases (distinct texts). Measured +/// on an RTX 4090 with a cold driver: 751 cases 11.6 s flat, 5.9 s nested; 698 cases 9.5 s, 4.8 s; +/// 2,516 cases 168 s, 36 s. Groups of 16, 32 and 64 tie. 512 is below the smallest program +/// measured; on RADV the ~700-case ones built up to 28 % slower nested. +const NEST_MIN_CASES: usize = 512; + +/// The group size of `Nest::Auto`. +const AUTO_GROUP: usize = 32; + +fn parse_nest(v: &str) -> Option { + let v = v.trim(); + if v.eq_ignore_ascii_case("auto") { + return Some(Nest::Auto); + } + v.parse::().ok().filter(|&p| p == 0 || (p.is_power_of_two() && p <= MAX_NEST)).map(Nest::from) +} + +/// The group size (0 = flat) for a program of `cases` cases. +fn resolve_nest(nest: Nest, cases: usize, min_cases: usize) -> usize { + match nest { + Nest::Flat => 0, + Nest::Groups(p) => p, + Nest::Auto if cases >= min_cases => AUTO_GROUP, + Nest::Auto => 0, + } +} + +/// `translate_compact` with the bound `heavy` (`HEAVY`); a table of more than `dense_above` +/// words is packed across words. +pub(super) fn compact(code: &[u8], opt: &Options, heavy: usize, dense_above: usize) -> Result { + compact_at(code, opt, heavy, dense_above, nest_from_env(), NEST_MIN_CASES) +} + +/// `compact` with the group size of the two-level dispatch given (0 = flat). +/// DXC folds the groups' exits back into one merge block with a phi operand per case unless +/// each group ends in `xcl_nb = min(xcl_nb, n)`, which it cannot see through. +pub(super) fn compact_with(code: &[u8], opt: &Options, heavy: usize, dense_above: usize, nest: usize) -> Result { + compact_at(code, opt, heavy, dense_above, Nest::from(nest), NEST_MIN_CASES) +} + +/// `compact_with` with the setting (`nest_from_env`): `Nest::Auto` is resolved once the cases +/// are counted, nesting from `min_cases` cases on. +fn compact_at(code: &[u8], opt: &Options, heavy: usize, dense_above: usize, nest: Nest, min_cases: usize) -> Result { + if matches!(opt.mode, Mode::Geometry(_)) { + return Err("compact form: geometry programs are not supported".into()); + } + let Prepared { insts, leaders, branches, mut em, .. } = prepare(code, opt)?; + if branches == 0 { + return super::translate(code, opt); + } + let list = blocks(&insts, &leaders, &mut em, heavy)?; + let n = list.len(); + let at: HashMap = list.iter().enumerate().map(|(k, b)| (b.pc, k)).collect(); + // the distinct texts (with the address of the first block of each), keyed on the code and + // the branch condition: the target is data, one per block of the text (`targets`) + let mut texts: Vec<(String, u64)> = Vec::new(); + let mut index: HashMap = HashMap::new(); + let mut conds: Vec> = Vec::new(); + let mut targets: Vec> = Vec::new(); + let mut class = Vec::with_capacity(n); + for (k, b) in list.into_iter().enumerate() { + let mut key = b.text; + let mut to = None; + if let Some((cond, t)) = &b.branch { + to = Some(*at.get(t).ok_or_else(|| format!("+{:#x}: branch to {t:#x}, which starts no block", b.pc))?); + let _ = writeln!(key, "\u{1}{cond}"); + } + let c = match index.get(&key) { + Some(&c) => c, + None => { + index.insert(key.clone(), texts.len()); + conds.push(b.branch.map(|(cond, _)| cond)); + targets.push(Vec::new()); + texts.push((key, b.pc)); + texts.len() - 1 + } + }; + if let Some(to) = to { + targets[c].push((k, to)); + } + class.push(c as u32); + } + // a text's branch: the offset most of its blocks jump by, and the target of each other + // block by its index (`select`, no branch: the index is wave-uniform) + for (c, (text, _)) in texts.iter_mut().enumerate() { + let Some(cond) = &conds[c] else { continue }; + text.truncate(text.rfind('\u{1}').unwrap()); + let mut count: HashMap = HashMap::new(); + for &(k, to) in &targets[c] { + *count.entry(to as i64 - k as i64).or_default() += 1; + } + let d = *count.iter().max_by_key(|&(d, n)| (*n, -d.abs(), *d)).unwrap().0; + let off = if d >= 0 { format!("xcl_b + {d}u") } else { format!("xcl_b - {}u", -d) }; + let nb = if count.len() == 1 { + off + } else { + let _ = writeln!(text, " uint xcl_t = {off};"); + let minority: Vec<(usize, usize)> = targets[c].iter().copied().filter(|&(k, to)| to as i64 - k as i64 != d).collect(); + pick_targets(text, &minority, MAX_SELECTS, 0); + "xcl_t".to_string() + }; + let _ = if cond.is_empty() { writeln!(text, " xcl_nb = {nb};") } else { writeln!(text, " if ({cond}) xcl_nb = {nb};") }; + } + // the table: the blocks' cases, `per` to a word; past `dense_above` words, packed across + // words (`bits` from bit `xcl_b * bits`; one word of padding for the second read) + let bits = (usize::BITS - texts.len().saturating_sub(1).leading_zeros()).max(1); + let per = (32 / bits) as usize; + let mut words: Vec = class.chunks(per).map(|c| c.iter().enumerate().fold(0u32, |w, (j, &v)| w | v << (j as u32 * bits))).collect(); + let dense = words.len() > dense_above; + if dense { + words = vec![0u32; (n * bits as usize).div_ceil(32) + 1]; + for (b, &v) in class.iter().enumerate() { + let p = b * bits as usize; + let (w, s) = (p / 32, (p % 32) as u32); + words[w] |= v << s; + if s + bits > 32 { + words[w + 1] |= v >> (32 - s); + } + } + } + if words.len() > MAX_TABLE_WORDS { + return Err(format!("compact form: {n} blocks of {} texts need a {}-word table (at most {MAX_TABLE_WORDS})", texts.len(), words.len())); + } + let mut body = String::new(); + let _ = writeln!(body, " static const uint XCL_BT[{}] = {{", words.len()); + for row in words.chunks(16) { + let row: Vec = row.iter().map(|v| format!("{v:#x}u")).collect(); + let _ = writeln!(body, " {},", row.join(", ")); + } + body.push_str(" };\n uint xcl_b = 0u;\n [loop] for (;;) {\n uint xcl_nb = xcl_b + 1u;\n"); + let mask = (1u64 << bits) - 1; + let selector = if dense { + let _ = writeln!(body, " uint xcl_p = xcl_b * {bits}u;"); + format!("((XCL_BT[xcl_p >> 5u] >> (xcl_p & 31u)) | ((XCL_BT[(xcl_p >> 5u) + 1u] << 1u) << (31u - (xcl_p & 31u)))) & {mask:#x}u") + } else { + format!("(XCL_BT[xcl_b / {per}u] >> (xcl_b % {per}u * {bits}u)) & {mask:#x}u") + }; + let nest = resolve_nest(nest, texts.len(), min_cases); + if nest > 0 { + let _ = writeln!(body, " uint xcl_c = {selector};"); + let _ = writeln!(body, " switch (xcl_c >> {}u) {{", nest.trailing_zeros()); + for (g, group) in texts.chunks(nest).enumerate() { + let _ = writeln!(body, " case {g}u: switch (xcl_c) {{"); + for (j, (text, pc)) in group.iter().enumerate() { + let _ = write!(body, " case {}u: {{ // {pc:x}\n{text} }} break;\n", g * nest + j); + } + let _ = writeln!(body, " default: xcl_nb = 0xFFFFFFFFu; break;"); + let _ = writeln!(body, " }} xcl_nb = min(xcl_nb, {n}u); break;"); + } + } else { + let _ = writeln!(body, " switch ({selector}) {{"); + for (k, (text, pc)) in texts.iter().enumerate() { + let _ = write!(body, " case {k}u: {{ // {pc:x}\n{text} }} break;\n"); + } + } + body.push_str(" default: xcl_nb = 0xFFFFFFFFu; break;\n }\n"); + let _ = writeln!(body, " if (xcl_nb >= {n}u) break;"); + // a back edge spends the loop budget (LOOP_GUARD, 65,536 per lane); once it is spent the + // program ends, as in the guarded block chain. The structured form instead leaves the + // loop and runs what follows. + let _ = writeln!(body, " if (xcl_nb <= xcl_b) {{ {LOOP_GUARD} }}"); + body.push_str(" xcl_b = xcl_nb;\n }\n"); + let hlsl = em.finish(&body); + let static_samplers = em.static_used.clone(); + Ok(Translation { + hlsl, + unsupported: em.unsupported, + unsupported_why: em.unsupported_why, + ignored: em.ignored, + instructions: insts.len(), + blocks: texts.len(), + static_samplers, + }) +} + +/// The most selects a case evaluates for its branch target; a longer list is searched through +/// a tree on the block index first. +pub(super) const MAX_SELECTS: usize = 32; + +/// The lines that set `xcl_t` for the blocks of `list` (block, target; sorted by block): one +/// select each, or, past `max`, a `[branch] if (xcl_b < pivot)` that picks the half of the list +/// holding the block (`xcl_b` is wave-uniform, so is the branch). +fn pick_targets(text: &mut String, list: &[(usize, usize)], max: usize, depth: usize) { + let pad = " ".repeat(12 + 4 * depth); + if list.len() <= max { + for &(k, to) in list { + let _ = writeln!(text, "{pad}xcl_t = select(xcl_b == {k}u, {to}u, xcl_t);"); + } + return; + } + let mid = (list.len().div_ceil(max) / 2) * max; + let _ = writeln!(text, "{pad}[branch] if (xcl_b < {}u) {{", list[mid].0); + pick_targets(text, &list[..mid], max, depth + 1); + let _ = writeln!(text, "{pad}}} else {{"); + pick_targets(text, &list[mid..], max, depth + 1); + let _ = writeln!(text, "{pad}}}"); +} + +#[cfg(test)] +mod tests { + use super::super::runner::{self, KernelState}; + use super::*; + use crate::gpu::rdna2::encode; + + const V: u64 = 256; // VALU source code of v0 + + type Inst<'a> = (&'a str, &'a str, &'a [(&'a str, u64)]); + + fn prog(list: &[Inst]) -> 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 + } + + /// A scalar loop, then three exec-guarded regions (the first two with the same code, the + /// third skipped: no lane passes its compare). + fn guarded() -> Vec { + let mul: Inst = ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", V)]); + let add: Inst = ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V + 2), ("VSRC1", 1)]); + let save: Inst = ("S_MOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 126)]); + let restore: Inst = ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 2)]); + prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]), // 0: s0 = 0 + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 138)]), // 4: s1 = 10 + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)]), // 8: s0 += s1 + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)]), // 12: s1 -= 1 + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 128)]), // 16 + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), // 20: → 8 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 0)]), // 24: v1 = s0 + save, // 28 + ("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", 148), ("VSRC1", 0)]), // 32: 20 > v0 + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 3)]), // 36: → 52 + mul, // 40 + add, // 48 + restore, // 52 + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 158), ("VSRC1", 0)]), // 56: 30 < v0 + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 3)]), // 60: → 76 + mul, // 64 + add, // 72 + restore, // 76 + ("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 0)]), // 80: 0 > v0 + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), // 84: → 92 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 135)]), // 88: v4 = 7 + restore, // 92 + ("S_ENDPGM", "ENC_SOPP", &[]), // 96 + ]) + } + + /// The two-level dispatch: `ceil(cases / P)` inner switches, every case once, one `min` per + /// group; with the nest off the text is the flat one. + #[test] + fn nested_dispatch_groups_the_cases() { + let code = guarded(); + let opt = Options::default(); + // every instruction a block of its own: enough cases for several groups + let flat = compact_with(&code, &opt, 0, MAX_TABLE_WORDS, 0).unwrap(); + let cases = flat.hlsl.matches("u: { // ").count(); + assert!(cases >= 9, "{}", flat.hlsl); + assert!(!flat.hlsl.contains("xcl_c") && !flat.hlsl.contains("min(xcl_nb") && flat.hlsl.contains(" switch ((XCL_BT[xcl_b / "), "{}", flat.hlsl); + let at = flat.hlsl.find(" if (xcl_nb >= ").unwrap() + " if (xcl_nb >= ".len(); + let n: usize = flat.hlsl[at..at + flat.hlsl[at..].find("u) break;").unwrap()].parse().unwrap(); + for p in [2usize, 4, 8, 16] { + let t = compact_with(&code, &opt, 0, MAX_TABLE_WORDS, p).unwrap(); + let groups = cases.div_ceil(p); + let h = &t.hlsl; + assert_eq!(h.matches("u: switch (xcl_c) {").count(), groups, "P = {p}: inner switches"); + assert_eq!(h.matches(&format!("switch (xcl_c >> {}u) {{", p.trailing_zeros())).count(), 1, "P = {p}"); + assert_eq!(h.matches(&format!("xcl_nb = min(xcl_nb, {n}u); break;")).count(), groups, "P = {p}: min per group"); + assert_eq!(h.matches("min(xcl_nb").count(), groups, "P = {p}"); + for k in 0..cases { + assert_eq!(h.matches(&format!(" case {k}u: {{ // ")).count(), 1, "P = {p}: case {k}"); + } + assert_eq!(h.matches("u: { // ").count(), cases, "P = {p}"); + assert_eq!(h.matches("default: xcl_nb = 0xFFFFFFFFu; break;").count(), groups + 1, "P = {p}: a default per group and the outer one"); + assert!(t.complete() && t.blocks == flat.blocks && t.instructions == flat.instructions, "P = {p}"); + } + // packed across words as well + let dense = compact_with(&code, &opt, 0, 0, 4).unwrap(); + assert!(dense.hlsl.contains("uint xcl_p = xcl_b * ") && dense.hlsl.contains("uint xcl_c = ((XCL_BT[xcl_p >> 5u]"), "{}", dense.hlsl); + } + + #[test] + fn the_nest_size_is_zero_or_a_power_of_two_up_to_the_limit() { + let g = |p| Some(Nest::Groups(p)); + for (v, want) in [("0", Some(Nest::Flat)), ("1", g(1)), (" 32 ", g(32)), ("65536", g(65536)), ("auto", Some(Nest::Auto)), (" AUTO ", Some(Nest::Auto)), ("131072", None), ("4294967296", None), ("48", None), ("-1", None), ("x", None), ("", None)] { + assert_eq!(parse_nest(v), want, "{v:?}"); + } + } + + #[test] + fn auto_nest_starts_at_the_case_threshold() { + assert_eq!(NEST_MIN_CASES, 512); + assert_eq!([(0, Nest::Auto), (511, Nest::Auto), (512, Nest::Auto), (9000, Nest::Auto)].map(|(n, s)| resolve_nest(s, n, NEST_MIN_CASES)), [0, 0, AUTO_GROUP, AUTO_GROUP]); + assert_eq!((resolve_nest(Nest::Flat, 9000, 512), resolve_nest(Nest::Groups(4), 1, 512)), (0, 4)); + let code = guarded(); + let opt = Options::default(); + let cases = compact_with(&code, &opt, 0, MAX_TABLE_WORDS, 0).unwrap().hlsl.matches("u: { // ").count(); + let at = compact_at(&code, &opt, 0, MAX_TABLE_WORDS, Nest::Auto, cases).unwrap(); + assert!(at.hlsl.contains(&format!("switch (xcl_c >> {}u) {{", AUTO_GROUP.trailing_zeros())) && at.hlsl.matches("u: switch (xcl_c) {").count() == cases.div_ceil(AUTO_GROUP), "{}", at.hlsl); + let below = compact_at(&code, &opt, 0, MAX_TABLE_WORDS, Nest::Auto, cases + 1).unwrap(); + assert!(!below.hlsl.contains("xcl_c") && below.hlsl.contains(" switch ((XCL_BT[xcl_b / "), "{}", below.hlsl); + let flat = compact_with(&code, &opt, 0, MAX_TABLE_WORDS, 0).unwrap(); + assert_eq!(below.hlsl, flat.hlsl); + } + + #[test] + fn equal_blocks_share_one_case() { + let code = guarded(); + let t = translate_compact(&code, &Options::default()).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(t.hlsl.contains("(XCL_BT[xcl_b / ") && t.hlsl.contains("static const uint XCL_BT[1]"), "{}", t.hlsl); + // blocks: 0, 8, 24, 40, 52, 64, 76, 88, 92; 40 and 64 are the same code + assert_eq!(t.blocks, 8, "{}", t.hlsl); + assert_eq!(t.hlsl.matches("v3 = select(").count(), 1, "{}", t.hlsl); + // branches by offset: the loop's back edge, the skips over two blocks and over one + assert!(t.hlsl.contains("xcl_nb = xcl_b + 0u;") && t.hlsl.contains("xcl_nb = xcl_b + 2u;") && t.hlsl.contains("xcl_nb = xcl_b + 1u;"), "{}", t.hlsl); + // every instruction a block of its own: the same instruction texts are shared too + let each = compact(&code, &Options::default(), 0, MAX_TABLE_WORDS).unwrap(); + assert!(each.blocks < each.instructions && each.blocks > t.blocks, "{}", each.hlsl); + // no branches: the straight-line form of `translate` + let line = prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])]); + assert_eq!(translate_compact(&line, &Options::default()).unwrap().hlsl, super::super::translate(&line, &Options::default()).unwrap().hlsl); + if super::super::dxc::location().is_ok() { + for o in [Options::default(), Options { split_wave64: true, mem_windows: 4, ..Options::default() }] { + let t = translate_compact(&code, &o).unwrap(); + super::super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + } + } + } + + #[test] + fn compact_is_wanted_for_large_repetitive_programs() { + assert!(!compact_wanted(&guarded())); + // 20,000 instructions: one guarded block 5,000 times, or 10,000 different blocks + let unit = prog(&[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V + 2), ("VSRC1", 1)]), + ("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", 148), ("VSRC1", 0)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 135)]), + ]); + let same: Vec = unit.iter().copied().cycle().take(unit.len() * 5000).collect(); + assert!(compact_wanted(&same)); + assert!(!compact_wanted(&same[..same.len() - 4])); + let mut different = Vec::new(); + for k in 0..10_000u32 { + different.extend(encode("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 255)], Some(k)).unwrap()); + different.extend(encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + } + assert!(!compact_wanted(&different)); + } + + /// The compact form ends in the same state as `translate` (both block cuts). + #[test] + fn gpu_compact_matches_translate() { + match (runner::adapter(), runner::wave64_programs_supported(), super::super::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, w, d) => { + runner::skip_test(if a.is_err() || w.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }); + return; + } + } + let code = guarded(); + let mem: Vec = code.chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + let mut st = KernelState::default(); + for (lane, v) in st.vgpr.iter_mut().enumerate() { + v[0] = lane as u32; + } + let opt = runner::options(Mode::Kernel); + let run = |t: Translation| { + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = super::super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + runner::run(&dxil, &st, &mem).unwrap() + }; + let want = run(super::super::translate(&code, &opt).unwrap()); + assert_eq!((want.sgpr[0], want.vgpr[5][3], want.vgpr[40][3], want.vgpr[25][3]), (55, 80, 1655, 0)); + for heavy in [HEAVY, 0] { + let got = run(compact(&code, &opt, heavy, MAX_TABLE_WORDS).unwrap()); + assert_eq!((got.sgpr, got.vgpr, got.scc), (want.sgpr.clone(), want.vgpr.clone(), want.scc), "heavy {heavy}"); + } + } +} diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 069c8b3f6..8409e32af 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -692,6 +692,12 @@ impl Em { std::mem::take(&mut self.out) } + /// Number the following temporaries from t1 again; returns how many were made since the + /// last reset (the compact form emits each instruction on its own and shares equal texts). + pub fn reset_temps(&mut self) -> usize { + std::mem::take(&mut self.tmp) + } + fn line(&mut self, s: &str) { for _ in 0..self.indent { self.out.push_str(" "); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index d1e7d8bc4..5afecf456 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -53,6 +53,7 @@ pub mod cfg; pub mod dxc; +pub mod compact; pub mod dxil; pub mod lane_masks; pub mod lower; @@ -70,6 +71,8 @@ pub mod ssa; mod tests; #[cfg(test)] mod heap_window_tests; +#[cfg(test)] +mod tests_compact; /// First descriptor of the memory windows in the shader-visible heap (`Options::heap_windows`): /// window k is raw UAV `MEM_HEAP_BASE + k`. Not 0: a T# whose word 0 is 0 (an empty console @@ -1383,8 +1386,88 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B out } -pub fn translate(code: &[u8], opt: &Options) -> Result { - let program = code; +/// `XCL_COMPACT_CS`: which compute programs go through the compact backend (`compact`): +/// unset / `auto` the ones it wants (`compact::compact_wanted`), `0` none, `1` all. Read once. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompactCs { + Auto, + Never, + Always, +} + +impl CompactCs { + fn parse(v: Option<&str>) -> Option { + match v.map(str::trim) { + None | Some("auto") => Some(CompactCs::Auto), + Some("0") => Some(CompactCs::Never), + Some("1") => Some(CompactCs::Always), + Some(_) => None, + } + } + + pub fn get() -> CompactCs { + static S: std::sync::OnceLock = std::sync::OnceLock::new(); + *S.get_or_init(|| { + let v = std::env::var("XCL_COMPACT_CS").ok(); + CompactCs::parse(v.as_deref()).unwrap_or_else(|| { + crate::xlog_warn!("[SHADER] XCL_COMPACT_CS={:?} is not auto / 0 / 1 – auto", v.unwrap_or_default()); + CompactCs::Auto + }) + }) + } + + /// Whether the compute program `code` goes through the compact backend. + pub fn takes(self, code: &[u8]) -> bool { + match self { + CompactCs::Auto => compact::compact_wanted(code), + CompactCs::Never => false, + CompactCs::Always => true, + } + } +} + +/// `translate`, but a compute program goes through the compact backend where `XCL_COMPACT_CS` +/// says so (`CompactCs`); where that fails or leaves instructions out, through `translate`. +pub fn translate_routed(code: &[u8], opt: &Options) -> Result { + translate_as(code, opt, CompactCs::get()).map(|(t, _)| t) +} + +/// `translate_routed` with the switch given, and whether the translation is the compact form. +pub(super) fn translate_as(code: &[u8], opt: &Options, cs: CompactCs) -> Result<(Translation, bool), String> { + if matches!(opt.mode, Mode::Compute(_)) && cs.takes(code) { + match compact::translate_compact(code, opt) { + Ok(t) if t.complete() => { + note_compact(code, || format!("{} instructions, {} B HLSL", t.instructions, t.hlsl.len())); + return Ok((t, true)); + } + Ok(t) => note_compact(code, || format!("incomplete (missing {:?}) – translated as before", t.unsupported.keys().collect::>())), + Err(e) => note_compact(code, || format!("{e} – translated as before")), + } + } + translate(code, opt).map(|t| (t, false)) +} + +/// One INFO line per compute program the compact backend got, the first time. +fn note_compact(code: &[u8], what: impl FnOnce() -> String) { + static SEEN: std::sync::Mutex> = std::sync::Mutex::new(BTreeSet::new()); + let h = super::shader::fnv64(code); + if SEEN.lock().unwrap().insert(h) { + crate::xlog_info!("[SHADER] compact backend, compute program {h:016x}: {}", what()); + } +} + +/// A decoded program, its block leaders and the emitter set up for it (`translate`, +/// `compact::translate_compact`). +struct Prepared { + insts: Vec, + starts: BTreeSet, + leaders: BTreeSet, + branches: usize, + gs_jump: Option>, + em: emit::Em, +} + +fn prepare(code: &[u8], opt: &Options) -> Result { let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; @@ -1463,6 +1546,12 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { if let Mode::Pixel(ps) = &opt.mode { em.ps_modes = emit::ps_attr_modes(&insts, ps.input_ena); } + Ok(Prepared { insts, starts, leaders, branches, gs_jump, em }) +} + +pub fn translate(code: &[u8], opt: &Options) -> Result { + let program = code; + let Prepared { insts, starts, leaders, branches, gs_jump, mut em } = prepare(code, opt)?; let mut body = String::new(); let mut blocks = 0usize; if branches == 0 { @@ -1511,6 +1600,52 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { Ok(Translation { hlsl, unsupported: em.unsupported, unsupported_why: em.unsupported_why, ignored: em.ignored, instructions: insts.len(), blocks, static_samplers }) } +#[cfg(test)] +mod compact_cs_tests { + use super::*; + + #[test] + fn the_switch_reads_auto_0_and_1() { + assert_eq!(CompactCs::parse(None), Some(CompactCs::Auto)); + assert_eq!(CompactCs::parse(Some("auto")), Some(CompactCs::Auto)); + assert_eq!(CompactCs::parse(Some("0")), Some(CompactCs::Never)); + assert_eq!(CompactCs::parse(Some(" 1 ")), Some(CompactCs::Always)); + assert_eq!(CompactCs::parse(Some("yes")), None); + assert_eq!(CompactCs::parse(Some("")), None); + assert!(!CompactCs::Never.takes(&[0; 8])); + assert!(CompactCs::Always.takes(&[0; 8])); + assert_eq!(CompactCs::Auto.takes(&[0; 8]), compact::compact_wanted(&[0; 8])); + } + + /// Only compute programs are routed, and a compact result that fails falls back to `translate`. + #[test] + fn only_compute_goes_to_the_compact_backend() { + // a program with a branch: its compact form is complete and differs from `translate`'s + // in both modes, so only the mode decides which of the two is routed + let mut code = rdna2::encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap(); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let cs = CsInterface::from_rsrc2([64, 1, 1], 0); + for mode in [Mode::Kernel, Mode::Compute(cs)] { + let opt = Options { mode: mode.clone(), ..Default::default() }; + let normal = translate(&code, &opt).unwrap(); + let compact = compact::translate_compact(&code, &opt).unwrap(); + assert!(compact.complete() && compact.hlsl != normal.hlsl); + assert_eq!(translate_as(&code, &opt, CompactCs::Never).map(|(t, c)| (t.hlsl, c)).unwrap(), (normal.hlsl.clone(), false)); + let always = translate_as(&code, &opt, CompactCs::Always).map(|(t, c)| (t.hlsl, c)).unwrap(); + assert_eq!(always, if matches!(mode, Mode::Kernel) { (normal.hlsl, false) } else { (compact.hlsl, true) }); + } + // a branch over an instruction the recompiler does not know: the compact form is + // incomplete, and the routed translation is `translate`'s + let mut code = rdna2::encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap(); + code.extend(rdna2::encode("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 0), ("VSRC", 0), ("ATTR", 0)], None).unwrap()); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let opt = Options { mode: Mode::Compute(CsInterface::from_rsrc2([64, 1, 1], 0)), ..Default::default() }; + let compact = compact::translate_compact(&code, &opt).unwrap(); + assert!(!compact.complete() && compact.hlsl != translate(&code, &opt).unwrap().hlsl); + assert_eq!(translate_as(&code, &opt, CompactCs::Always).map(|(t, c)| (t.hlsl, c)).unwrap(), (translate(&code, &opt).unwrap().hlsl, false)); + } +} + #[cfg(test)] mod attribute_tests { use super::*; diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 00ac0a064..6aabfe520 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -12,7 +12,7 @@ use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; -use super::{dxc, interface, translate, Mode, Options}; +use super::{dxc, interface, translate_as, CompactCs, Mode, Options}; use crate::gpu::xbox; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -150,9 +150,9 @@ fn shader_cache() -> &'static Mutex { /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { - let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); + let compile_as = |form| compile_console_shader(blob, stage, sampler_base, windows, split_wave64, form); if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { - return compile_one().map(|(c, _)| c); + return normal_after_refusal(compile_as(CompactCs::get()), || compile_as(CompactCs::Never)).map(|(c, _)| c); } let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), @@ -164,7 +164,8 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa }; // with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag, // direct translator version, routing mode): never mixed with the HLSL path's entries - let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); + let disk = |compact, form| translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compact, || compile_as(form)); + let from_disk = || normal_after_refusal(disk(stage == Stage::Compute && compact_form(blob), CompactCs::get()), || disk(false, CompactCs::Never)); cached_shader(shader_cache(), key, blob, from_disk).map(|shader| shader.as_ref().clone()) } @@ -176,6 +177,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa /// translation parameters; translator sources and the DXC toolchain identify compatible builds. /// `XCL_TRANSLATED_CACHE=0` turns it off. mod translated { + use super::super::compact::Nest; use super::{Compiled, Stage}; use std::path::{Path, PathBuf}; use std::sync::OnceLock; @@ -279,11 +281,24 @@ mod translated { b.iter().fold(0x9E37_79B9_7F4A_7C15u64, |h, &x| (h ^ x as u64).wrapping_mul(0xFF51_AFD7_ED55_8CCD).rotate_left(29)) } - pub(super) fn file(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool) -> PathBuf { + /// `_c` for a program that went to the compact backend (`CompactCs`), then `_n

` when it + /// switches in two levels (`XCL_COMPACT_NEST`), `_na` for `auto` (the group size then follows + /// from the program); nothing otherwise. + pub(super) fn compact_tag(compact: bool, nest: Nest) -> String { + match (compact, nest) { + (false, _) => String::new(), + (true, Nest::Flat) => "_c".to_string(), + (true, Nest::Groups(n)) => format!("_c_n{n}"), + (true, Nest::Auto) => "_c_na".to_string(), + } + } + + /// `compact`: the program went to the compact backend (`CompactCs`): `compact_tag` before `.bin`. + pub(super) fn file(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool, compact: bool) -> PathBuf { dir.join("translated") .join("v2") .join(format!("{ident:016x}")) - .join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}.bin", crate::gpu::shader::fnv64(blob), split as u8)) + .join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}{}.bin", crate::gpu::shader::fnv64(blob), split as u8, compact_tag(compact, super::super::compact::nest_from_env()))) } fn header(ident: u64, blob: &[u8]) -> Vec { @@ -380,12 +395,13 @@ mod translated { sampler_base: u32, windows: u32, split: bool, + compact: bool, translate: impl FnOnce() -> Result, ) -> Result { if ident == 0 { return translate(); } - let path = file(dir, ident, blob, stage, sampler_base, windows, split); + let path = file(dir, ident, blob, stage, sampler_base, windows, split, compact); if let Some(c) = load_in(&path, ident, blob) { super::dxc::note_memory_hit(); return Ok(c); @@ -408,9 +424,10 @@ mod translated { sampler_base: u32, windows: u32, split: bool, + compact: bool, translate: impl FnOnce() -> Result<(Compiled, bool), String>, ) -> Result { - cached_rerouted(dir, identity(), direct_output(), blob, stage, sampler_base, windows, split, translate) + cached_rerouted(dir, identity(), direct_output(), blob, stage, sampler_base, windows, split, compact, translate) } /// What the direct translator's output depends on besides the HLSL path's identity: its @@ -447,6 +464,7 @@ mod translated { sampler_base: u32, windows: u32, split: bool, + compact: bool, translate: impl FnOnce() -> Result<(Compiled, bool), String>, ) -> Result { if ident == 0 { @@ -454,14 +472,14 @@ mod translated { } let rerouted = rerouted_identity(ident, direct); for id in [ident, rerouted] { - if let Some(c) = load_in(&file(dir, id, blob, stage, sampler_base, windows, split), id, blob) { + if let Some(c) = load_in(&file(dir, id, blob, stage, sampler_base, windows, split, compact), id, blob) { super::dxc::note_memory_hit(); return Ok(c); } } let (c, direct) = translate()?; let id = if direct { rerouted } else { ident }; - store_in(&file(dir, id, blob, stage, sampler_base, windows, split), id, blob, &c); + store_in(&file(dir, id, blob, stage, sampler_base, windows, split, compact), id, blob, &c); Ok(c) } } @@ -479,14 +497,30 @@ fn enormous(stage: Stage, hlsl_len: usize) -> bool { // `TRANSLATION_GLUE_REVISION` in build.rs; cache serialization changes need not bump it. /// The program's DXIL, and whether it is an `enormous` one the direct translator made (its /// disk cache entry then follows that translator's version: `translated::cached`). -fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool), String> { +fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, form: CompactCs) -> Result<(Compiled, bool), String> { // `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path - // for what it cannot translate yet - if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() { - if dxc::defer() { - return Err("DXIL not compiled yet".into()); - } - match direct_compute(blob, sampler_base, windows, split_wave64) { + // for what it cannot translate yet – except those `XCL_COMPACT_CS` routes to the compact form + let compact_routed = stage == Stage::Compute && form != CompactCs::Never && compact_form(blob); + let direct_on = stage == Stage::Compute && goes_direct(crate::gpu::dxil::kernel::enabled(), compact_routed); + if direct_on && dxc::defer() { + return Err("DXIL not compiled yet".into()); + } + let direct = direct_on.then_some(|| direct_compute(blob, sampler_base, windows, split_wave64)); + direct_first(direct, || compile_hlsl(blob, stage, sampler_base, windows, split_wave64, form)) +} + +/// Whether a compute program goes to the direct DXIL translator (`direct_on`: `XCL_DIRECT_DXIL` +/// takes compute): not one `XCL_COMPACT_CS` routes to the compact form (`compact_routed`), +/// which goes to the HLSL path's compact form first. +fn goes_direct(direct_on: bool, compact_routed: bool) -> bool { + direct_on && !compact_routed +} + +/// A compute program the direct translator (`direct`, see `goes_direct`) translates never +/// reaches `hlsl`, the HLSL path; one it falls back on does. +fn direct_first(direct: Option Result>, hlsl: impl FnOnce() -> Result<(Compiled, bool), String>) -> Result<(Compiled, bool), String> { + if let Some(direct) = direct { + match direct() { Ok(c) => { crate::gpu::dxil::coverage::record_translated("CS"); return Ok((c, false)); @@ -494,6 +528,10 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: Err(e) => direct_fallback("CS", &e), } } + hlsl() +} + +fn compile_hlsl(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, form: CompactCs) -> Result<(Compiled, bool), String> { // `XCL_DIRECT_DXIL=all`: vertex / pixel shaders too (not with the PS debug hooks below) let ps_debug = stage == Stage::Pixel && (debug_color(blob).is_some() || ["XCL_DEBUG_LOD0", "XCL_DEBUG_PS_SUB", "XCL_DEBUG_PS_EXPR"].iter().any(|v| std::env::var_os(v).is_some())); @@ -509,7 +547,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e), } } - let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?; + let (mut t, profile, compact) = console_translation(blob, stage, sampler_base, windows, split_wave64, form)?; if enormous(stage, t.hlsl.len()) && !crate::gpu::dxil::kernel::enabled() { if dxc::defer() { return Err("DXIL not compiled yet".into()); @@ -556,10 +594,26 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: }) { t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } - let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; + // (in a cached-only attempt the DXIL is not refused, only not made yet) + let dxil = dxc::compile_cached(&t.hlsl, "main", profile).map_err(|e| if compact && !dxc::in_cached_only() { format!("{COMPACT_REFUSED}{e}") } else { e })?.0; Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }, false)) } +/// The start of `compile_console_shader`'s error when DXC refused a compact form. +const COMPACT_REFUSED: &str = "DXC refused the compact form: "; + +/// `first`, or where DXC refused its compact form, `normal`: the normal form, which is kept +/// under the normal form's entry, never the compact one's. +fn normal_after_refusal(first: Result, normal: impl FnOnce() -> Result) -> Result { + match first { + Err(e) if e.starts_with(COMPACT_REFUSED) => { + crate::xlog_warn!("[SHADER] {e} – compiled in the normal form"); + normal() + } + r => r, + } +} + /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. fn sample_at_lod0(hlsl: &str) -> String { let mut out = String::with_capacity(hlsl.len()); @@ -615,7 +669,7 @@ fn debug_color(blob: &[u8]) -> Option<[f32; 3]> { /// The HLSL (and its DXC profile) `console_to_dxil` compiles. pub fn console_to_hlsl(blob: &[u8], stage: Stage) -> Result<(String, &'static str), String> { - console_translation(blob, stage, 0, mem_windows(), false).map(|(t, p)| (t.hlsl, p)) + console_translation(blob, stage, 0, mem_windows(), false, CompactCs::get()).map(|(t, p, _)| (t.hlsl, p)) } /// Upper entry cap for `ShaderCache` (the 64 MiB byte limit is the primary bound; a retail game @@ -834,7 +888,7 @@ pub fn compute_user_sgprs(blob: &[u8]) -> Option { /// The HLSL and profile a console program compiles from at pipeline creation (for /// `xcl shaders --export-hlsl`: compile-time investigations outside a title). pub fn console_hlsl(blob: &[u8], stage: Stage, windows: u32, split_wave64: bool) -> Result<(String, &'static str), String> { - console_translation(blob, stage, 0, windows, split_wave64).map(|(t, p)| (t.hlsl, p)) + console_translation(blob, stage, 0, windows, split_wave64, CompactCs::get()).map(|(t, p, _)| (t.hlsl, p)) } /// A direct DXIL translation that fell back to the HLSL path: one structured log line @@ -909,18 +963,36 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) } -pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { +/// Whether `console_translation` gives the program of the compute container `blob` the compact +/// backend (`CompactCs`): the form its translation is kept on disk under. +fn compact_form(blob: &[u8]) -> bool { + let cs = super::CompactCs::get(); + match cs { + super::CompactCs::Never => return false, + super::CompactCs::Always => return true, + super::CompactCs::Auto => {} + } + if let Some(f) = fspx(blob) { + return cs.takes(f.code); + } + let Some(sh) = xbox::parse(blob) else { return false }; + let Some(f) = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)) else { return false }; + f.programs.first().and_then(|p| f.data.get(p.offset..p.offset + p.len)).is_some_and(|code| cs.takes(code)) +} + +/// The translation, its profile and whether it is the compact form (`CompactCs` `form`). +pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, form: CompactCs) -> Result<(super::Translation, &'static str, bool), String> { if let Some(f) = fspx(blob) { if stage != Stage::Compute { return Err("an FSPX (driver) container in a graphics slot".into()); } let cs = super::CsInterface::from_rsrc2(f.threads, f.rsrc2); - let t = translate(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let (t, compact) = translate_as(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() }, form)?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); } - return Ok((t, "cs_6_6")); + return Ok((t, "cs_6_6", compact)); } let sh = xbox::parse(blob).ok_or("not a console shader container")?; // the hardware variant for this pipeline slot: VS (not the ES variant used with GS), PS @@ -944,12 +1016,12 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::detect_wave64(code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let (t, compact) = translate_as(code, &Options { mode, wave64: super::detect_wave64(code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() }, form)?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); } - Ok((t, profile)) + Ok((t, profile, compact)) } /// A console geometry stage as XCL runs it, in two passes: the console program as a compute @@ -1051,7 +1123,7 @@ fn console_mesh_with( split_wave64: split, cache_dir: cache_dir.to_path_buf(), }; - let from_disk = || translated::cached(cache_dir, blob, Stage::Mesh, 0, windows, split, || compile_one().map(|c| (c, false))); + let from_disk = || translated::cached(cache_dir, blob, Stage::Mesh, 0, windows, split, false, || compile_one().map(|c| (c, false))); cached_shader(cache, key, blob, from_disk)?.as_ref().clone() } else { compile_one()? @@ -1277,15 +1349,16 @@ mod shader_cache_tests { #[test] fn translated_namespace_tracks_every_request_input() { let dir = PathBuf::from("cache"); - let base = translated::file(&dir, 42, b"console", Stage::Compute, 3, 2, false); + let base = translated::file(&dir, 42, b"console", Stage::Compute, 3, 2, false, false); let paths = [ base.clone(), - translated::file(&dir, 43, b"console", Stage::Compute, 3, 2, false), - translated::file(&dir, 42, b"consolf", Stage::Compute, 3, 2, false), - translated::file(&dir, 42, b"console", Stage::Vertex, 3, 2, false), - translated::file(&dir, 42, b"console", Stage::Compute, 4, 2, false), - translated::file(&dir, 42, b"console", Stage::Compute, 3, 3, false), - translated::file(&dir, 42, b"console", Stage::Compute, 3, 2, true), + translated::file(&dir, 43, b"console", Stage::Compute, 3, 2, false, false), + translated::file(&dir, 42, b"consolf", Stage::Compute, 3, 2, false, false), + translated::file(&dir, 42, b"console", Stage::Vertex, 3, 2, false, false), + translated::file(&dir, 42, b"console", Stage::Compute, 4, 2, false, false), + translated::file(&dir, 42, b"console", Stage::Compute, 3, 3, false, false), + translated::file(&dir, 42, b"console", Stage::Compute, 3, 2, true, false), + translated::file(&dir, 42, b"console", Stage::Compute, 3, 2, false, true), ]; assert_eq!(paths.iter().collect::>().len(), paths.len()); assert!(base.starts_with(dir.join("translated").join("v2").join("000000000000002a"))); @@ -1322,7 +1395,7 @@ mod shader_cache_tests { translated::store_in(&unnamespaced, ident, blob, &old); let mut calls = 0; - let first = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { + let first = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || { calls += 1; Ok(compiled(7)) }) @@ -1330,9 +1403,9 @@ mod shader_cache_tests { assert_eq!(calls, 1); assert_eq!(first.dxil, synthetic_dxil(7)); assert!(unnamespaced.exists()); - assert!(translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false).exists()); + assert!(translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false, false).exists()); - let second = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || panic!("v2 entry was not reused")).unwrap(); + let second = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || panic!("v2 entry was not reused")).unwrap(); assert_eq!(second.dxil, first.dxil); let _ = std::fs::remove_dir_all(&dir); } @@ -1384,7 +1457,7 @@ mod shader_cache_tests { let hlsl = identity_with("s", "t", Backend::Hlsl, 1); let direct = identity_with("s", "t", Backend::DirectCompute, 1); let go = |ident, marker: u8, calls: &mut u32| { - cached_in(&dir, ident, blob, Stage::Compute, 0, 1, true, || { + cached_in(&dir, ident, blob, Stage::Compute, 0, 1, true, false, || { *calls += 1; Ok(compiled(marker)) }) @@ -1403,7 +1476,7 @@ mod shader_cache_tests { let v2 = identity_with("s", "t", Backend::DirectCompute, 2); assert_eq!(go(v2, 3, &mut calls), 3, "a version bump misses"); // another split_wave64 / sampler base is another entry - let other = cached_in(&dir, direct, blob, Stage::Compute, 0, 1, false, || Ok(compiled(4))).unwrap(); + let other = cached_in(&dir, direct, blob, Stage::Compute, 0, 1, false, false, || Ok(compiled(4))).unwrap(); assert_eq!(other.dxil[67], 4); let _ = std::fs::remove_dir_all(&dir); } @@ -1428,7 +1501,7 @@ mod shader_cache_tests { let (enormous_blob, plain_blob) = (b"console-enormous".as_slice(), b"console-plain".as_slice()); let ident = 0x1234; let go = |blob: &[u8], version: u64, marker: u8, rerouted: bool, calls: &mut u32| { - cached_rerouted(&dir, ident, version, blob, Stage::Compute, 0, 1, true, || { + cached_rerouted(&dir, ident, version, blob, Stage::Compute, 0, 1, true, false, || { *calls += 1; Ok((compiled(marker), rerouted)) }) @@ -1440,9 +1513,9 @@ mod shader_cache_tests { assert_eq!(go(enormous_blob, 7, 1, true, &mut calls), 1); assert_eq!(go(enormous_blob, 7, 9, true, &mut calls), 1, "rerouted hit"); assert_eq!(calls, 1); - let rerouted_file = translated::file(&dir, rerouted_identity(ident, 7), enormous_blob, Stage::Compute, 0, 1, true); + let rerouted_file = translated::file(&dir, rerouted_identity(ident, 7), enormous_blob, Stage::Compute, 0, 1, true, false); assert!(rerouted_file.exists(), "kept under the rerouted identity"); - assert!(!translated::file(&dir, ident, enormous_blob, Stage::Compute, 0, 1, true).exists(), "not under the HLSL one"); + assert!(!translated::file(&dir, ident, enormous_blob, Stage::Compute, 0, 1, true, false).exists(), "not under the HLSL one"); assert_eq!(go(plain_blob, 7, 2, false, &mut calls), 2); assert_eq!(calls, 2); // a new direct translator: the rerouted program is translated again, the HLSL one is not @@ -1454,6 +1527,68 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); } + /// A compact translation and the normal one of the same program never share a disk entry, + /// and the normal one keeps its file name. + #[test] + fn translated_compact_and_normal_forms_are_kept_apart() { + let dir = std::env::temp_dir().join(format!("xcl-translated-compact-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (blob, ident) = (b"console", 42); + let normal = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false, false); + assert_eq!(normal.file_name().unwrap().to_string_lossy(), format!("{:016x}_Compute_0_1_0.bin", crate::gpu::shader::fnv64(blob))); + assert_eq!(translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false, true).file_name().unwrap().to_string_lossy(), format!("{:016x}_Compute_0_1_0{}.bin", crate::gpu::shader::fnv64(blob), translated::compact_tag(true, super::super::compact::nest_from_env()))); + use super::super::compact::Nest; + assert_eq!(translated::compact_tag(true, Nest::Flat), "_c"); + assert_eq!(translated::compact_tag(true, Nest::Groups(32)), "_c_n32"); + assert_eq!(translated::compact_tag(true, Nest::Auto), "_c_na"); + assert_eq!(translated::compact_tag(false, Nest::Groups(32)), ""); + let first = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || Ok(compiled(1))).unwrap(); + let compact = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, true, || Ok(compiled(2))).unwrap(); + assert_eq!((first.dxil[67], compact.dxil[67]), (1, 2), "the compact form did not reuse the normal entry"); + let again = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || panic!("normal entry lost")).unwrap(); + let again_c = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, true, || panic!("compact entry lost")).unwrap(); + assert_eq!((again.dxil[67], again_c.dxil[67]), (1, 2)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A compact form DXC refused is compiled in the normal form and kept under the normal + /// entry, not the compact one; any other result is left as it is. + #[test] + fn a_refused_compact_form_is_compiled_in_the_normal_form() { + let dir = std::env::temp_dir().join(format!("xcl-translated-refused-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (blob, ident) = (b"console", 42); + let disk = |compact, r: Result| translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, compact, || r); + let got = normal_after_refusal(disk(true, Err(format!("{COMPACT_REFUSED}dxc: error"))), || disk(false, Ok(compiled(2)))).ok().map(|c| c.dxil[67]); + assert_eq!(got, Some(2)); + assert!(translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false, false).exists()); + assert!(!translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false, true).exists()); + assert_eq!(normal_after_refusal(Err::("dxc: error".into()), || panic!("compiled again")).err().as_deref(), Some("dxc: error")); + assert_eq!(normal_after_refusal(Ok(compiled(1)), || panic!("compiled again")).ok().map(|c| c.dxil[67]), Some(1)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// With `XCL_DIRECT_DXIL` and `XCL_COMPACT_CS` both set, a program routed to the compact + /// form does not go to the direct translator; any other goes to it first, and the HLSL path + /// runs only when the direct translator is off or falls back. + #[test] + fn the_compact_routing_goes_before_direct_dxil() { + assert!(!goes_direct(true, true), "a compact-routed program went to the direct translator"); + assert!(goes_direct(true, false)); + assert!(!goes_direct(false, false) && !goes_direct(false, true)); + let hlsl_ran = std::cell::Cell::new(false); + let hlsl = || { + hlsl_ran.set(true); + Ok((compiled(2), false)) + }; + assert_eq!(direct_first(Some(|| Ok(compiled(1))), hlsl).ok().map(|(c, _)| c.dxil[67]), Some(1)); + assert!(!hlsl_ran.get(), "the HLSL path ran after a direct translation"); + assert_eq!(direct_first(Some(|| Err("not translated".to_string())), hlsl).ok().map(|(c, _)| c.dxil[67]), Some(2)); + assert!(hlsl_ran.replace(false), "a direct fallback did not reach the HLSL path"); + assert_eq!(direct_first(None:: Result>, hlsl).ok().map(|(c, _)| c.dxil[67]), Some(2)); + assert!(hlsl_ran.get()); + } + fn key(hash: u64) -> ShaderKey { ShaderKey { hash, @@ -1485,7 +1620,7 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); let blob = b"console-corrupt"; let ident = 42u64; - let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false); + let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false, false); // Store a valid entry first, then corrupt only the DXIL payload while keeping the // XCLTRAN2 header and payload length intact (e.g. zeroed blocks after a hard reset). @@ -1506,7 +1641,7 @@ mod shader_cache_tests { // `cached_in` must rebuild, overwrite the corrupt file on disk, and reuse the rebuilt entry. let mut calls = 0usize; - let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { + let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || { calls += 1; Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)] }) }) @@ -1514,7 +1649,7 @@ mod shader_cache_tests { assert_eq!(calls, 1); assert_eq!(rebuilt.dxil, synthetic_dxil(9)); - let cached = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { + let cached = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || { panic!("rebuilt translated cache entry was not reused") }) .unwrap(); @@ -1529,9 +1664,9 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); let blob = b"console-fresh"; let ident = 42u64; - let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false); + let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false, false); - let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { + let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || { Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }) }) .err() @@ -1544,12 +1679,12 @@ mod shader_cache_tests { // A real container emitted by the direct DXIL backend must be accepted and cached. let real_direct = crate::gpu::dxil::shader::Shader::new(crate::gpu::dxil::container::Stage::Compute, (6, 6)).finish([1, 1, 1], None); - let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { + let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || { Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new() }) }) .unwrap(); assert_eq!(stored.dxil, real_direct); - let hit = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { + let hit = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, false, || { panic!("valid direct DXIL entry was not reused") }) .unwrap(); diff --git a/crates/xcl/src/gpu/recomp/tests_compact.rs b/crates/xcl/src/gpu/recomp/tests_compact.rs new file mode 100644 index 000000000..748a4fbf1 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/tests_compact.rs @@ -0,0 +1,1633 @@ +//! A/B tests of the compact form (`compact::translate_compact`) against the normal one +//! (`translate`): the same program, translated both ways, compiled with DXC and run on the GPU +//! with the same inputs, must leave byte-identical results (SGPRs, SCC, VGPRs of every lane, +//! exports, the upper half's SGPRs of the split wave64 form, and memory). +//! +//! Every program runs in each form this adapter has: wave64 split into two 32-lane halves +//! (`runner::split_wave64`, e.g. NVIDIA), wave64 in 64-lane waves (where the GPU has them) and +//! as a wave32 program; control flow also with `structured: false` (the normal form's guarded +//! block chain). `XCL_SAMPLE_BIG_CS=` adds a retail program. + +use std::collections::HashMap; + +use super::runner::{self, KernelResult, KernelState}; +use super::{compact, translate, CsInterface, Mode, Options, Translation}; +use super::{KERNEL_EXPORTS, KERNEL_LANES, KERNEL_RES_DWORDS, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS}; +use crate::gpu::rdna2::{self, encode}; + +const V: u64 = 256; // VALU source code of v0 +const EXEC: u64 = 126; +const VCC: u64 = 106; + +/// Initial state of an A/B run: registers, and flat memory from address 0. +#[derive(Clone)] +struct Inputs { + state: KernelState, + mem: Vec, +} + +impl Inputs { + /// All 64 lanes on, v0 = lane index, `mem` as given. + fn lanes(mem: Vec) -> Self { + let mut state = KernelState::default(); + for (l, r) in state.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + } + Inputs { state, mem } + } + + fn vgpr(mut self, reg: usize, f: impl Fn(usize) -> u32) -> Self { + for (l, r) in self.state.vgpr.iter_mut().enumerate() { + r[reg] = f(l); + } + self + } + + fn sgprs(mut self, at: usize, v: &[u32]) -> Self { + self.state.sgpr[at..at + v.len()].copy_from_slice(v); + self + } +} + +/// A GPU that runs wave64 programs (split or native) and DXC; `skip_test` otherwise. +fn gpu_ready() -> bool { + match (runner::adapter(), runner::wave64_programs_supported(), super::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => true, + (a, w, d) => { + runner::skip_test(if a.is_err() || w.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }); + false + } + } +} + +/// The forms a program runs in on this adapter: (label, options), mode Kernel. +fn forms(control_flow: bool) -> Vec<(String, Options)> { + let mut base = Vec::new(); + if runner::split_wave64() { + base.push(("wave64 split".to_string(), Options { wave64: true, split_wave64: true, ..Default::default() })); + } + if runner::wave64_supported() == Ok(true) { + base.push(("wave64 native".to_string(), Options { wave64: true, split_wave64: false, ..Default::default() })); + } + base.push(("wave32".to_string(), Options { wave64: false, ..Default::default() })); + let mut out = Vec::new(); + for (name, o) in base { + if control_flow { + out.push((format!("{name}, unstructured"), Options { structured: false, ..o.clone() })); + } + out.push((name, o)); + } + out +} + +/// Translation (must be complete) → DXIL. +fn compiled(t: &Translation, backend: &str) -> Vec { + assert!(t.complete(), "{backend}: unsupported {:?}", t.unsupported_why); + super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{backend}: DXC: {e}")) +} + +fn both_translations(code: &[u8], opt: &Options) -> (Translation, Translation) { + let normal = translate(code, opt).unwrap_or_else(|e| panic!("translate: {e}")); + let compact = compact::translate_compact(code, opt).unwrap_or_else(|e| panic!("translate_compact: {e}")); + (normal, compact) +} + +/// Result dwords of a kernel run, then its memory, as bytes. +fn bytes(r: &KernelResult) -> Vec { + r.raw.iter().chain(r.mem.iter()).flat_map(|w| w.to_le_bytes()).collect() +} + +/// Runs `code` translated by `translate` and by `compact::translate_compact` (options `opt` +/// as given, mode Kernel) on the same inputs: the result buffer (SGPRs, SCC, VGPRs, exports, +/// the split form's upper-half SGPRs) followed by the memory afterwards, as bytes, of each. +fn both_backends(code: &[u8], opt: &Options, inputs: &Inputs) -> (Vec, Vec) { + let (normal, compact) = both_translations(code, opt); + (ran(&normal, "translate", inputs), ran(&compact, "translate_compact", inputs)) +} + +/// `t` compiled and run on `inputs`: its result (`bytes` layout). +fn ran(t: &Translation, backend: &str, inputs: &Inputs) -> Vec { + let dxil = compiled(t, backend); + let r = runner::run_with_statics(&dxil, &inputs.state, &inputs.mem, &[], &[], &t.static_samplers).unwrap_or_else(|e| panic!("{backend}: run: {e}")); + bytes(&r) +} + +/// Name of result dword `i` (`bytes` layout). +fn slot(i: usize) -> String { + match i { + KERNEL_SCC_SLOT => "scc".into(), + _ if i < KERNEL_SGPRS => format!("s{i}"), + _ if i < KERNEL_EXPORTS => format!("lane {} v{}", (i - KERNEL_SGPRS) / KERNEL_VGPRS, (i - KERNEL_SGPRS) % KERNEL_VGPRS), + _ if i < KERNEL_SPLIT_SGPRS => { + let k = i - KERNEL_EXPORTS; + format!("export {} lane {} .{}", k / (KERNEL_LANES * 4), k / 4 % KERNEL_LANES, k % 4) + } + _ if i < KERNEL_RES_DWORDS => format!("upper half s{}", i - KERNEL_SPLIT_SGPRS), + _ => format!("mem[{:#x}]", 4 * (i - KERNEL_RES_DWORDS)), + } +} + +/// Dwords where `a` and `b` differ, named (first 24). +fn differences(a: &[u8], b: &[u8], name: fn(usize) -> String) -> Vec { + let w = |x: &[u8], i: usize| x.get(4 * i..4 * i + 4).map(|c| u32::from_le_bytes(c.try_into().unwrap())); + let n = a.len().max(b.len()).div_ceil(4); + let all: Vec = (0..n).filter(|&i| w(a, i) != w(b, i)).map(|i| format!("{}: {:x?} / {:x?}", name(i), w(a, i), w(b, i))).collect(); + let mut v: Vec = all.iter().take(24).cloned().collect(); + if all.len() > 24 { + v.push(format!("… {} dwords in all", all.len())); + } + v +} + +/// `both_backends` in every form of `forms`: the results must be identical. Returns each form +/// with its result (`bytes` layout). +fn assert_same(what: &str, code: &[u8], inputs: &Inputs, control_flow: bool) -> Vec<(String, Options, Vec)> { + let mut out = Vec::new(); + for (form, opt) in forms(control_flow) { + let (a, b) = both_backends(code, &opt, inputs); + let d = differences(&a, &b, slot); + assert!(d.is_empty(), "{what} ({form}): translate / translate_compact differ:\n{}", d.join("\n")); + println!("{what} ({form}): {} result bytes identical", a.len()); + out.push((form, opt, a)); + } + out +} + +/// Dword `i` of a result (`bytes` layout: `slot` names it). +fn dword(r: &[u8], i: usize) -> u32 { + u32::from_le_bytes(r[4 * i..4 * i + 4].try_into().unwrap()) +} + +/// Result dword of VGPR `v` of `lane`. +fn vgpr_slot(lane: usize, v: usize) -> usize { + KERNEL_SGPRS + lane * KERNEL_VGPRS + v +} + +/// The dispatch loop of a compact translation, read back from its HLSL: each case's text and +/// the address of its first block, and each block's case in address order (from `XCL_BT`). +struct Dispatch { + cases: Vec<(u64, String)>, + class: Vec, +} + +impl Dispatch { + fn of(t: &Translation) -> Self { + let h = &t.hlsl; + let after = |key: &str, end: &str| -> String { + let s = &h[h.find(key).unwrap_or_else(|| panic!("no {key:?} in the compact form:\n{h}")) + key.len()..]; + s[..s.find(end).unwrap()].to_string() + }; + let n: usize = after(" if (xcl_nb >= ", "u) break;").parse().unwrap(); + // switch ((XCL_BT[xcl_b / {per}u] >> (xcl_b % {per}u * {bits}u)) & {mask}u), or packed + // across words: uint xcl_p = xcl_b * {bits}u; switch (((XCL_BT[xcl_p >> 5u] >> …; nested + // (`XCL_COMPACT_NEST`): uint xcl_c = ; switch (xcl_c >> …) in groups + let dense = h.contains(" uint xcl_p = xcl_b * "); + let (per, bits): (usize, u32) = if dense { + (0, after(" uint xcl_p = xcl_b * ", "u;").parse().unwrap()) + } else { + let per = after("(XCL_BT[xcl_b / ", "u]").parse().unwrap(); + (per, after(&format!("(xcl_b % {per}u * "), "u))").parse().unwrap()) + }; + let table = after("static const uint XCL_BT[", "};"); + let words: Vec = table[table.find('{').unwrap() + 1..] + .split(',') + .map(str::trim) + .filter(|w| !w.is_empty()) + .map(|w| u32::from_str_radix(w.trim_start_matches("0x").trim_end_matches('u'), 16).unwrap()) + .collect(); + let mask = (1u64 << bits) - 1; + let class: Vec = (0..n) + .map(|b| { + let v = if dense { + let (w, s) = (b * bits as usize / 32, b * bits as usize % 32); + (words[w] as u64 | (words[w + 1] as u64) << 32) >> s + } else { + (words[b / per] >> (b % per) as u32 * bits) as u64 + }; + (v & mask) as usize + }) + .collect(); + let mut cases: Vec<(u64, String)> = Vec::new(); + let mut open = false; + let nested = h.contains(" uint xcl_c = "); + let switch = h.find(if nested { " uint xcl_c = " } else if dense { "switch (((XCL_BT[" } else { "switch ((XCL_BT[" }).unwrap(); + for l in h[switch..].lines().skip(1) { + if nested && (l.ends_with(": switch (xcl_c) {") || l.starts_with(" } xcl_nb = min(") || l.starts_with(" switch (xcl_c >> ")) { + continue; + } else if nested && l.starts_with(" default:") { + // each group ends with one; the loop's own default follows the last group + if h[switch..].contains(&format!(" case {}u: {{", cases.len())) { + continue; + } + break; + } else if let Some(rest) = l.strip_prefix(" case ") { + let (k, pc) = rest.split_once("u: { // ").unwrap_or_else(|| panic!("case line {l:?}")); + assert_eq!(k.parse::().unwrap(), cases.len(), "cases in order"); + cases.push((u64::from_str_radix(pc, 16).unwrap(), String::new())); + open = true; + } else if l == " } break;" { + open = false; + } else if l.starts_with(" default:") { + break; + } else if open { + let text = &mut cases.last_mut().unwrap().1; + text.push_str(l); + text.push('\n'); + } + } + assert_eq!(cases.len(), t.blocks, "Translation::blocks is the number of cases"); + assert!(class.iter().all(|&c| c < cases.len()), "table {class:?}, {} cases", cases.len()); + for (c, (pc, _)) in cases.iter().enumerate() { + assert!(class.contains(&c), "case {c} (+{pc:#x}) has a block"); + } + Dispatch { cases, class } + } + + fn blocks(&self) -> usize { + self.class.len() + } + + /// How many blocks run case `c`. + fn uses(&self, c: usize) -> usize { + self.class.iter().filter(|&&k| k == c).count() + } + + /// The cases whose text contains `s`. + fn with(&self, s: &str) -> Vec { + (0..self.cases.len()).filter(|&c| self.cases[c].1.contains(s)).collect() + } + + /// The one case whose text contains `s`. + fn only(&self, s: &str) -> usize { + let v = self.with(s); + assert_eq!(v.len(), 1, "cases with {s:?}: {v:?}"); + v[0] + } + + /// The cases with the line `l` (indentation of a case's text included). + fn with_line(&self, l: &str) -> Vec { + (0..self.cases.len()).filter(|&c| self.cases[c].1.lines().any(|x| x == l)).collect() + } + + /// Where case `c` sends `block` (an index, as `class` has them), read from the case's lines + /// the way the GPU runs them: the target, the selects run for it and the `[branch] if`s it + /// goes through. Only what follows `uint xcl_t` is read: the offset, then the tree. + fn target(&self, c: usize, block: usize) -> (usize, usize, usize) { + let num = |s: &str| -> usize { s.trim_end_matches(';').trim_end_matches(')').trim_end_matches('{').trim().trim_end_matches('u').parse().unwrap() }; + let mut to = None; + let (mut selects, mut ifs) = (0, 0); + // per open `if`: (its parent runs, its condition, its side runs) + let mut open: Vec<(bool, bool, bool)> = Vec::new(); + for l in self.cases[c].1.lines().map(str::trim) { + let live = open.last().map_or(true, |f| f.2); + if let Some(rest) = l.strip_prefix("uint xcl_t = xcl_b ") { + let (sign, n) = rest.split_once(' ').unwrap(); + to = Some(if sign == "+" { block + num(n) } else { block - num(n) }); + } else if to.is_none() { + continue; + } else if let Some(rest) = l.strip_prefix("[branch] if (xcl_b < ") { + let below = block < num(rest.split_once(')').unwrap().0); + open.push((live, below, live && below)); + ifs += live as usize; + } else if l == "} else {" { + let f = open.last_mut().unwrap(); + f.2 = f.0 && !f.1; + } else if l == "}" { + open.pop().unwrap(); + } else if let Some(rest) = l.strip_prefix("xcl_t = select(xcl_b == ") { + let v: Vec<&str> = rest.split(", ").collect(); + selects += live as usize; + if live && num(v[0]) == block { + to = Some(num(v[1])); + } + } + } + assert!(open.is_empty(), "unbalanced ifs in: +{}", self.cases[c].1); + (to.unwrap_or_else(|| panic!("no xcl_t in: +{}", self.cases[c].1)), selects, ifs) + } +} + +/// `check` on the compact form of `code` in every form of `forms`. +fn assert_shape(what: &str, code: &[u8], control_flow: bool, check: fn(&Dispatch, &Options)) { + for (form, opt) in forms(control_flow) { + let t = compact::translate_compact(code, &opt).unwrap_or_else(|e| panic!("{what} ({form}): {e}")); + let d = Dispatch::of(&t); + check(&d, &opt); + println!("{what} ({form}): compact form has {} cases for {} blocks", d.cases.len(), d.blocks()); + } +} + +/// Assembler with labels: branches (SOPP SIMM16) and far jumps (s_getpc_b64 / add or sub of +/// a literal / s_setpc_b64) are patched to their label at the end, which also checks every +/// branch decodes to its label. +#[derive(Default)] +struct Asm { + code: Vec, + labels: HashMap<&'static str, usize>, + /// (offset of the SOPP branch, label) + branches: Vec<(usize, &'static str)>, + /// (offset of s_getpc_b64, label, subtract) + far: Vec<(usize, &'static str, bool)>, +} + +impl Asm { + fn i(&mut self, name: &str, enc: &str, fields: &[(&str, u64)], lit: Option) -> &mut Self { + self.code.extend(encode(name, enc, fields, lit).unwrap_or_else(|e| panic!("{name}: {e}"))); + self + } + + fn label(&mut self, l: &'static str) -> &mut Self { + assert!(self.labels.insert(l, self.code.len()).is_none(), "label {l} twice"); + self + } + + /// `name` (an s_branch / s_cbranch_*) to `l`. + fn br(&mut self, name: &str, l: &'static str) -> &mut Self { + self.branches.push((self.code.len(), l)); + self.i(name, "ENC_SOPP", &[("SIMM16", 0)], None) + } + + /// The compiler's far jump through s[4:5] to `l` (backward when `l` comes first). + fn far_jump(&mut self, l: &'static str, backward: bool) -> &mut Self { + self.far.push((self.code.len(), l, backward)); + let (lo, hi) = if backward { ("S_SUB_U32", "S_SUBB_U32") } else { ("S_ADD_U32", "S_ADDC_U32") }; + self.i("S_GETPC_B64", "ENC_SOP1", &[("SDST", 4)], None) + .i(lo, "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 255)], Some(0)) + .i(hi, "ENC_SOP2", &[("SDST", 5), ("SSRC0", 5), ("SSRC1", 128)], None) + .i("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 4)], None) + } + + /// The program, with s_endpgm at the end. + fn end(&mut self) -> Vec { + self.i("S_ENDPGM", "ENC_SOPP", &[], None); + let mut code = std::mem::take(&mut self.code); + for &(at, l) in &self.branches { + let rel = (self.labels[l] as i64 - (at as i64 + 4)) / 4; + code[at..at + 2].copy_from_slice(&(rel as i16).to_le_bytes()); + } + for &(at, l, backward) in &self.far { + let pc = at as i64 + 4; // what s_getpc_b64 returns + let lit = if backward { pc - self.labels[l] as i64 } else { self.labels[l] as i64 - pc }; + code[at + 8..at + 12].copy_from_slice(&(lit as u32).to_le_bytes()); + } + let mut insts = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + let d = rdna2::decode(&code[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + for &(at, l) in &self.branches { + let d = insts.iter().find(|d| d.pc == at as u64).unwrap(); + assert_eq!(rdna2::branch_target(d), Some(self.labels[l] as u64), "branch at {at:#x} to {l}"); + } + for &(at, l, _) in &self.far { + let d = insts.iter().find(|d| d.pc == at as u64 + 16).unwrap(); + assert_eq!(d.far_target, Some(self.labels[l] as u64), "far jump at {at:#x} to {l}"); + } + code + } +} + +/// Code as flat memory from address 0 (where `runner::run_program` puts it), then `extra`. +fn code_mem(code: &[u8], extra: usize) -> Vec { + let mut m: Vec = code.chunks(4).map(|c| { + let mut b = [0u8; 4]; + b[..c.len()].copy_from_slice(c); + u32::from_le_bytes(b) + }).collect(); + m.resize(m.len() + extra, 0); + m +} + +/// A value per lane that differs in every byte (a multiplicative hash of the lane). +fn hash(l: usize, salt: u32) -> u32 { + (l as u32 ^ salt).wrapping_mul(0x9E37_79B9).rotate_left(13) ^ salt.wrapping_mul(0x85EB_CA6B) +} + +// --------------------------------------------------------------------------------------------- +// programs + +/// s_cbranch_scc1 to the next instruction: a program without branches gets `translate`'s form +/// from `translate_compact`; with this one it gets the compact form. +fn branch_first(a: &mut Asm) -> &mut Asm { + a.br("S_CBRANCH_SCC1", "first").label("first") +} + +/// The compact form is used (`Dispatch::of` reads its dispatch loop): two blocks at least. +fn dispatched(d: &Dispatch, _: &Options) { + assert!(d.blocks() >= 2, "{} blocks", d.blocks()); +} + +/// Nested exec-masked regions: s_and_saveexec_b64 / s_cbranch_execz / s_or_b64 restore, three +/// deep, with an else half (s_xor_b64 exec), a region no lane enters, and one only lanes 48..63 +/// enter (in the split form: one half has no lane in it). +fn execz_nest() -> Vec { + let mut a = Asm::default(); + a.i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None) + // if (lane < 40) + .i("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 128 + 40), ("VSRC1", 0)], None) + .i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", VCC)], None) + .br("S_CBRANCH_EXECZ", "else1") + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)], None) + // if (lane > 10) + .i("V_CMP_LT_U32", "ENC_VOPC", &[("SRC0", 138), ("VSRC1", 0)], None) + .i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", VCC)], None) + .br("S_CBRANCH_EXECZ", "out2") + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 1)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 20), ("SSRC1", 129)], None) + // if (lane == 1000): nobody + .i("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(1000)) + .i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", VCC)], None) + .br("S_CBRANCH_EXECZ", "out3") + .i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 255)], Some(0x55)) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 21), ("SSRC0", 129)], None) + .label("out3") + .i("S_OR_B64", "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", 6)], None) + .label("out2") + .i("S_OR_B64", "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", 4)], None) + // else (lanes 40..63) + .label("else1") + .i("S_XOR_B64", "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", 2)], None) + .br("S_CBRANCH_EXECZ", "out1") + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", 255)], Some(0x0101_0101)) + // if (lane >= 48) + .i("V_CMP_LE_U32", "ENC_VOPC", &[("SRC0", 128 + 48), ("VSRC1", 0)], None) + .i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 8), ("SSRC0", VCC)], None) + .br("S_CBRANCH_EXECZ", "out4") + .i("V_XOR_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 1)], Some(0xA5A5_0000)) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 22), ("SSRC0", 22), ("SSRC1", 135)], None) + .label("out4") + .i("S_OR_B64", "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", 8)], None) + .label("out1") + .i("S_OR_B64", "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", 2)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 20), ("VSRC1", 1)], None) + .end() +} + +/// A divergent loop with a backward branch, as the console compiler writes it: each lane runs +/// `v5 = lane & 7` iterations; the loop leaves through s_cbranch_execz and restores exec. +/// Then a uniform scalar loop (s_cbranch_scc1 back). +fn backward_loops() -> Vec { + let mut a = Asm::default(); + a.i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)], None) + .i("V_AND_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 135), ("VSRC1", 0)], None) + .i("S_MOV_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", EXEC)], None) + .label("vloop") + .i("V_CMP_NE_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 5)], None) + .i("S_AND_B64", "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", VCC)], None) + .br("S_CBRANCH_EXECZ", "vdone") + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 4), ("SRC1", 131)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 4)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 193), ("VSRC1", 5)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 129)], None) + .br("S_BRANCH", "vloop") + .label("vdone") + .i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC), ("SSRC0", 10)], None) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 138)], None) + .label("sloop") + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 1), ("VSRC1", 6)], None) + .i("S_SUB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None) + .i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 128)], None) + .br("S_CBRANCH_SCC1", "sloop") + .end() +} + +/// The same instruction sequence (`X`: VALU + scalar work ending in `s_cbranch_scc1` over the +/// next instruction) at five addresses: its successors differ at each (the branch is relative), +/// one copy is in a loop, one is reached only by an s_branch, and one ends the program. +fn repeated_blocks() -> Vec { + fn x(a: &mut Asm) -> &mut Asm { + a.i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)], None) + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", V + 3)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 131)], None) + .i("S_CMP_GT_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 135)], None) + .i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None) // over the next instruction + } + let mut a = Asm::default(); + a.i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 133)], None) + .label("loop"); + x(&mut a).i("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 4)], None); + x(&mut a).i("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 130), ("VSRC1", 4)], None); + x(&mut a).i("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 132), ("VSRC1", 4)], None); + a.i("S_SUB_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 129)], None) + .i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 11), ("SSRC1", 128)], None) + .br("S_CBRANCH_SCC1", "loop") + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None); + x(&mut a).br("S_BRANCH", "last").i("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 136), ("VSRC1", 4)], None).label("last"); + x(&mut a).i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 10)], None); + a.end() +} + +/// `repeated_blocks` in the compact form: fewer cases than blocks, and one case runs several. +fn repeated_shape(d: &Dispatch, _: &Options) { + assert!(d.cases.len() < d.blocks(), "{} cases, {} blocks", d.cases.len(), d.blocks()); + assert!((0..d.cases.len()).any(|c| d.uses(c) >= 3), "table {:?}", d.class); +} + +/// The same block (`X`: VALU + scalar work ending in `s_cbranch_scc1`) twice, branching +/// forward over a block from the first and back to the first from the second: one case with +/// two targets. s10 runs 2, 5, 8, 11, 14, so both branches are taken and both fall through. +fn shared_targets() -> Vec { + fn x<'a>(a: &'a mut Asm, to: &'static str) -> &'a mut Asm { + a.i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)], None) + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", V + 3)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 131)], None) + .i("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 139)], None) + .br("S_CBRANCH_SCC1", to) + } + let mut a = Asm::default(); + a.i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 130)], None).label("top"); + x(&mut a, "mid").i("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 4)], None).label("mid"); + x(&mut a, "top").i("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 130), ("VSRC1", 4)], None); + a.end() +} + +/// `shared_targets` in the compact form: the two copies of `X` are one case, which picks the +/// second one's target by its block index. +fn shared_targets_shape(d: &Dispatch, _: &Options) { + let c = d.only("xcl_t = select(xcl_b == "); + assert_eq!(d.uses(c), 2, "table {:?}", d.class); + assert_eq!(d.cases[c].1.matches("select(xcl_b == ").count(), 1, "{}", d.cases[c].1); +} + +/// Copies of `many_targets`: more than twice the selects a case evaluates. +const MANY: usize = 2 * compact::MAX_SELECTS; + +/// The copy `many_targets` jumps to from copy `i` (`MANY`: the end). +fn many_target(i: usize) -> usize { + (i + 2 + i % 6).min(MANY) +} + +/// `MANY` copies of one block (VALU + scalar work, `s_and` of the running sum with 4, then +/// `s_cbranch_scc1`) one after the other: each ends in a branch, so each is a block of its own +/// and all share a text. Copy `i` jumps to copy `many_target(i)`, so no more than a sixth of +/// them jump by the same distance and the rest of the case's targets are selects. Some jump +/// and some fall through (bit 2 of s10, which grows by 3 per copy that runs). +fn many_targets() -> Vec { + fn name(i: usize) -> &'static str { + Box::leak(format!("copy{i}").into_boxed_str()) + } + let mut a = Asm::default(); + for i in 0..MANY { + a.label(name(i)) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)], None) + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", V + 3)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 131)], None) + .i("S_AND_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 10), ("SSRC1", 132)], None) + .br("S_CBRANCH_SCC1", name(many_target(i))); + } + a.label(name(MANY)).end() +} + +/// `many_targets` in the compact form: one case holds the copies' branches, with a `[branch] if` +/// on the block index. +fn many_targets_shape(d: &Dispatch, _: &Options) { + let c = d.only("[branch] if (xcl_b < "); + assert!(d.uses(c) >= MANY, "table {:?}", d.class); +} + +/// Far jumps (s_getpc_b64, add / sub of a literal, s_setpc_b64): a backward one closes a loop, +/// a forward one jumps over code that must not run. +fn far_jumps() -> Vec { + let mut a = Asm::default(); + a.i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 133)], None) + .label("top") + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 21), ("SSRC0", 21), ("SSRC1", 20)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 20), ("VSRC1", 1)], None) + .i("S_SUB_U32", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 20), ("SSRC1", 129)], None) + .i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 20), ("SSRC1", 128)], None) + .br("S_CBRANCH_SCC1", "out") + .far_jump("top", true) + .label("out") + .far_jump("skip", false) + .i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 135)], None) // jumped over + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 135)], None) + .label("skip") + .i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 137)], None) + .end() +} + +/// `far_jumps` in the compact form: it has no s_branch, so its two unconditional jumps are the +/// s_setpc_b64s, each in a case with its s_getpc_b64 (`s4 = `): back one block, forward two. +fn far_jumps_shape(d: &Dispatch, _: &Options) { + for (l, what) in [(" xcl_nb = xcl_b - 1u;", "backward"), (" xcl_nb = xcl_b + 2u;", "forward")] { + let c = d.with_line(l); + assert_eq!(c.len(), 1, "{what} far jump: cases {c:?}"); + assert!(d.cases[c[0]].1.contains("s4 = 0x"), "{what} far jump:\n{}", d.cases[c[0]].1); + } +} + +/// `far_jumps` ran its loop five times (s21 = 5 + 4 + 3 + 2 + 1) and skipped the two moves +/// (lanes of the wave: 64 for wave64, 32 for wave32). +fn far_jumps_ran(r: &[u8], opt: &Options) { + assert_eq!((dword(r, 21), dword(r, 22)), (15, 0x33), "s21, s22"); + for l in 0..if opt.wave64 { 64 } else { 32 } { + assert_eq!((dword(r, vgpr_slot(l, 2)), dword(r, vgpr_slot(l, 3))), (0x22, 9), "lane {l} v2, v3"); + } +} + +/// v_mul_lo_u32 with VGPR, SGPR, inline-constant and literal operands (low 32 bits of the +/// product: wraps), next to v_mul_hi_u32 / v_mul_u32_u24. After `branch_first`. +fn mul_lo() -> Vec { + let mut a = Asm::default(); + branch_first(&mut a) + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", V + 2)], None) + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", 8), ("SRC1", V + 1)], None) + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 193)], None) + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 255)], Some(0xDEAD_BEEF)) + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 10), ("SRC1", V + 10)], None) + .i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", V + 2)], None) + .i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 16), ("SRC0", V + 1), ("VSRC1", 2)], None) + .end() +} + +/// buffer_load_format_x of twelve formats (V# k at s[12 + 4k], format field in word 3), lanes +/// indexed with a stride of 4: lanes past num_records read 0. Also an unaligned offset. After +/// `branch_first`. +const LOAD_X_FORMATS: [u32; 12] = [1, 2, 4, 5, 7, 13, 20, 22, 29, 36, 50, 56]; + +fn load_format_x() -> Vec { + let mut a = Asm::default(); + branch_first(&mut a); + for k in 0..LOAD_X_FORMATS.len() as u64 { + a.i("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 20 + k), ("VADDR", 0), ("SRSRC", 3 + k), ("SOFFSET", 128), ("IDXEN", 1)], None); + } + a.i("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 40), ("VADDR", 0), ("SRSRC", 3 + 7), ("SOFFSET", 128), ("IDXEN", 1), ("OFFSET", 2)], None) + .i("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 41), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None) + .end() +} + +/// Inputs of `load_format_x` / `load_x_repeated`, the data at `base` (0: flat memory; a window +/// address for `arena_both`, which copies `mem` there). +fn load_format_x_inputs(base: u64) -> Inputs { + let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; + let mem: Vec = (0..1024).map(|i| hash(i, 0x5EED)).collect(); + let mut st = Inputs::lanes(mem).vgpr(1, |l| 3 * l as u32); + for (k, &fmt) in LOAD_X_FORMATS.iter().enumerate() { + // base + 0x100 + 0x100·k, stride 4, 48 records + let at = base + 0x100 + 0x100 * k as u64; + st = st.sgprs(12 + 4 * k, &[at as u32, (at >> 32) as u32 & 0xFFFF | 4 << 16, 48, ident | fmt << 12]); + } + st +} + +/// buffer_load_format_x at several addresses: the same block (one V#, a load, an add, a branch +/// over the next instruction) four times under different exec masks, and once with another +/// V# (16_16_FLOAT), each entered after an s_cbranch_execz. +fn load_x_repeated() -> Vec { + fn l(a: &mut Asm, srsrc: u64) -> &mut Asm { + a.i("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 20), ("VADDR", 0), ("SRSRC", srsrc), ("SOFFSET", 128), ("IDXEN", 1)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 21), ("SRC0", V + 20), ("VSRC1", 21)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 70), ("SSRC0", 70), ("SSRC1", 129)], None) + .i("S_CMP_GT_U32", "ENC_SOPC", &[("SSRC0", 70), ("SSRC1", 130)], None) + .i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None) + } + let mut a = Asm::default(); + a.i("S_MOV_B64", "ENC_SOP1", &[("SDST", 72), ("SSRC0", EXEC)], None); + let masks: [(u32, u32, &'static str); 5] = [(u32::MAX, u32::MAX, "c0"), (0, 0xFFFF_0000, "c1"), (0x0000_FFFF, 0, "c2"), (0xF0F0_F0F0, 0x0F0F_0F0F, "c3"), (0, 0, "c4")]; + for (k, &(lo, hi, end)) in masks.iter().enumerate() { + a.i("S_MOV_B32", "ENC_SOP1", &[("SDST", EXEC), ("SSRC0", 255)], Some(lo)) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", EXEC + 1), ("SSRC0", 255)], Some(hi)) + .br("S_CBRANCH_EXECZ", end); + // the fourth copy loads through another V# (srsrc 3 + 8: 16_16_FLOAT) + l(&mut a, if k == 3 { 3 + 8 } else { 3 + 7 }).i("V_OR_B32", "ENC_VOP2", &[("VDST", 22), ("SRC0", 128 + 1 + k as u64), ("VSRC1", 22)], None).label(end); + } + a.i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC), ("SSRC0", 72)], None); + a.end() +} + +/// `load_x_repeated` in the compact form: each load is a block of its own (one case for the +/// four through s[40:43], one for s[44:47]), and the block after it, the same in all five +/// copies, is one case. +fn load_x_shape(d: &Dispatch, _: &Options) { + assert!(d.cases.len() < d.blocks(), "{} cases, {} blocks", d.cases.len(), d.blocks()); + let loads = d.with("FMT_INFO["); + assert_eq!(loads.len(), 2, "cases with a buffer_load_format_x: {loads:?}"); + for &c in &loads { + let text = &d.cases[c].1; + assert_eq!(text.matches("FMT_INFO[").count(), 1, "one load in case {c}:\n{text}"); + assert!(!text.contains("v21 = ") && !text.contains("xcl_nb"), "case {c} is the load alone:\n{text}"); + } + let by = |s: &str| loads.iter().copied().find(|&c| d.cases[c].1.contains(s)).unwrap_or_else(|| panic!("no load through {s}")); + assert_eq!((d.uses(by("(s43 >> 12)")), d.uses(by("(s47 >> 12)"))), (4, 1), "blocks per load case"); + assert_eq!(d.uses(d.only("v21 = ")), 5, "the block after the load"); +} + +/// Cross-lane work (a v_cmp ballot into an SGPR pair and its s_bcnt1, v_readfirstlane_b32, +/// v_readlane_b32 of lanes 5 and 40) in one block repeated under four exec masks: lanes 32..63 +/// only (the split form's first active lane is in the upper half), the low half only, every +/// lane, and alternating lanes. Each copy is entered after an s_cbranch_execz and ends in a +/// branch over the next instruction. +fn exchange_repeated() -> Vec { + fn e(a: &mut Asm) -> &mut Asm { + a.i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", V)], None) + .i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 20)], None) + .i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 2)], None) + .i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 3), ("SRC1", 133)], None) + .i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 25), ("SRC0", V + 3), ("SRC1", 255)], Some(40)) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 26), ("SSRC1", 22)], None) + .i("S_XOR_B32", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 26), ("SSRC1", 23)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 26), ("SSRC1", 24)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 26), ("SSRC1", 25)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 26), ("VSRC1", 2)], None) + .i("V_XOR_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 23), ("VSRC1", 1)], None) + .i("S_BITCMP1_B32", "ENC_SOPC", &[("SSRC0", 26), ("SSRC1", 128)], None) + .i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None) + } + let mut a = Asm::default(); + a.i("S_MOV_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", EXEC)], None); + let masks: [(u32, u32, &'static str); 4] = [(0, 0xFFFF_FFFF, "x0"), (0xFFFF_FFFF, 0, "x1"), (u32::MAX, u32::MAX, "x2"), (0x5555_5555, 0xAAAA_AAAA, "x3")]; + for (k, &(lo, hi, end)) in masks.iter().enumerate() { + a.i("S_MOV_B32", "ENC_SOP1", &[("SDST", EXEC), ("SSRC0", 255)], Some(lo)) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", EXEC + 1), ("SSRC0", 255)], Some(hi)) + .br("S_CBRANCH_EXECZ", end); + e(&mut a).i("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 128 + 1 + k as u64), ("VSRC1", 4)], None).label(end); + } + a.i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC), ("SSRC0", 30)], None); + a.end() +} + +/// `exchange_repeated` in the compact form: the exchange block (the only one writing s25) is +/// one case for its four copies; in the split wave64 form its ballot and lane reads go through +/// the halves' exchange (`xcl_x_ballot`, `xcl_x_rla_uniform`). +fn exchange_shape(d: &Dispatch, opt: &Options) { + assert!(d.cases.len() < d.blocks(), "{} cases, {} blocks", d.cases.len(), d.blocks()); + let c = d.only("s25 = "); + assert_eq!(d.uses(c), 4, "blocks of the exchange case"); + let text = &d.cases[c].1; + if opt.wave64 && opt.split_wave64 { + assert_eq!((text.matches("= xcl_x_ballot(and(").count(), text.matches("= xcl_x_rla_uniform(").count()), (1, 3), "{text}"); + } +} + +/// s_endpgm before the last block: s30 picks the path. 1: the first s_endpgm; 0: `tail`, which +/// branches back to `mid` (its own s_endpgm); 2: `tail` and on to the end. Lanes below 20 also +/// take an execz-guarded block in `mid`. +fn endpgm_early() -> Vec { + let mut a = Asm::default(); + a.i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None) + .i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 30), ("SSRC1", 129)], None) + .br("S_CBRANCH_SCC0", "tail") + .i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 129)], None) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 31), ("SSRC0", 129)], None) + .i("S_ENDPGM", "ENC_SOPP", &[], None) + .label("mid") + .i("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 128 + 20), ("VSRC1", 0)], None) + .i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", VCC)], None) + .br("S_CBRANCH_EXECZ", "mid_out") + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 135), ("VSRC1", 1)], None) + .label("mid_out") + .i("S_OR_B64", "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", 2)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 131), ("VSRC1", 1)], None) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 31), ("SSRC0", 131)], None) + .i("S_ENDPGM", "ENC_SOPP", &[], None) + .label("tail") + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V), ("VSRC1", 1)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 32), ("SSRC0", 32), ("SSRC1", 133)], None) + .i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 30), ("SSRC1", 128)], None) + .br("S_CBRANCH_SCC1", "mid") + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 31), ("SSRC0", 132)], None) + .end() +} + +/// `endpgm_early` in the compact form: two blocks before the last one end the program. +fn endpgm_shape(d: &Dispatch, _: &Options) { + let ends = d.with_line(" xcl_nb = 0xFFFFFFFFu;"); + let n = d.blocks(); + assert!(ends.contains(&d.class[n - 1]), "the last block ends the program"); + assert_eq!(d.class[..n - 1].iter().filter(|c| ends.contains(c)).count(), 2, "early ends: table {:?}, cases {ends:?}", d.class); +} + +/// Memory windows with branches: a scalar loop (two iterations, s0) around four copies of one +/// block body, copy k through window k (s[20:21] = s[40 + 2k : 41 + 2k], the V# s[24:27] = +/// s[48 + 4k : 51 + 4k]) under its own exec mask, entered after an s_cbranch_execz. The body: +/// global_load_dword from the lane's dword at +v42, global_atomic_add of it at +v41 (returns +/// the old value), buffer_load_format_x through the V#, their sum stored back at +v42 (read by +/// the next iteration), s22 counted; it ends in a branch over the copy's own v_or. +fn window_loop() -> Vec { + let glbl = "ENC_FLAT_GLBL"; + fn body<'a>(a: &'a mut Asm, glbl: &str) -> &'a mut Asm { + a.i("GLOBAL_LOAD_DWORD", glbl, &[("VDST", 30), ("ADDR", 42), ("SADDR", 20), ("OFFSET", 0)], None) + .i("GLOBAL_ATOMIC_ADD", glbl, &[("VDST", 31), ("ADDR", 41), ("DATA", 30), ("SADDR", 20), ("OFFSET", 0), ("GLC", 1)], None) + .i("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 32), ("VADDR", 0), ("SRSRC", 6), ("SOFFSET", 128), ("IDXEN", 1)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 33), ("SRC0", V + 30), ("VSRC1", 31)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 33), ("SRC0", V + 32), ("VSRC1", 33)], None) + .i("GLOBAL_STORE_DWORD", glbl, &[("ADDR", 42), ("DATA", 33), ("SADDR", 20), ("OFFSET", 0)], None) + .i("S_ADD_U32", "ENC_SOP2", &[("SDST", 22), ("SSRC0", 22), ("SSRC1", 129)], None) + .i("S_BITCMP1_B32", "ENC_SOPC", &[("SSRC0", 22), ("SSRC1", 128)], None) + .i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None) + } + let mut a = Asm::default(); + a.i("S_MOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", EXEC)], None) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 130)], None) + .label("loop"); + let masks: [(u32, u32, &'static str); 4] = [(u32::MAX, u32::MAX, "w0"), (0, u32::MAX, "w1"), (0x5555_5555, 0xAAAA_AAAA, "w2"), (u32::MAX, 0, "w3")]; + for (k, &(lo, hi, end)) in masks.iter().enumerate() { + let k = k as u64; + a.i("S_MOV_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 40 + 2 * k)], None) + .i("S_MOV_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 48 + 4 * k)], None) + .i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 50 + 4 * k)], None) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", EXEC), ("SSRC0", 255)], Some(lo)) + .i("S_MOV_B32", "ENC_SOP1", &[("SDST", EXEC + 1), ("SSRC0", 255)], Some(hi)) + .br("S_CBRANCH_EXECZ", end); + body(&mut a, glbl).i("V_OR_B32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 129 + k), ("VSRC1", 34)], None).label(end); + } + a.i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC), ("SSRC0", 2)], None) + .i("S_SUB_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None) + .i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None) + .br("S_CBRANCH_SCC1", "loop") + .end() +} + +/// Inputs of `window_loop` in a four-window `arena`: window k's base at s[40 + 2k] (+0x2000), +/// its V# at s[48 + 4k] (+0x4000, stride 4, 64 records, 32_FLOAT); per-lane offsets v42 +/// (+4·lane, loaded and stored) and v41 (+0x800 + 4·lane, the atomic: a dword per lane, so its +/// return value does not depend on the order of the lanes or of the split form's halves). +fn window_loop_inputs(arena: &crate::gpu::uma::Uma) -> Inputs { + let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; + let mut st = Inputs::lanes(Vec::new()).vgpr(41, |l| 0x800 + 4 * l as u32).vgpr(42, |l| 4 * l as u32); + for k in 0..4 { + let w = arena.window(k).0 as u64; + let (base, vsharp) = (w + 0x2000, w + 0x4000); + st = st + .sgprs(40 + 2 * k, &[base as u32, (base >> 32) as u32]) + .sgprs(48 + 4 * k, &[vsharp as u32, (vsharp >> 32) as u32 & 0xFFFF | 4 << 16, 64, ident | 22 << 12]); + } + st +} + +/// `window_loop` in the compact form: not `translate`'s HLSL; fewer cases than blocks; the +/// buffer_load_format_x a case of its own run by the four copies, and the body's last part +/// (the store and the branch) one case for the four. +fn window_loop_shape(d: &Dispatch, _: &Options) { + assert!(d.cases.len() < d.blocks(), "{} cases, {} blocks", d.cases.len(), d.blocks()); + let load = d.only("FMT_INFO["); + assert!(!d.cases[load].1.contains("xcl_nb"), "the load alone: +{}", d.cases[load].1); + assert_eq!(d.uses(load), 4, "blocks of the buffer_load_format_x case"); + assert_eq!(d.uses(d.only("v33 = ")), 4, "blocks of the body's last part"); +} + +/// Memory-window loads and stores (the `gpu_memory_windows_above_4_gib` program, windows 0 +/// and 1); `four`: also a load from window 3 (v[14:15]) stored into window 2 (v[16:17]). +fn window_program(four: bool) -> Vec { + let glbl = "ENC_FLAT_GLBL"; + let mut a = Asm::default(); + a.i("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 1), ("OFFSET", 0)], None) + .i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None) + .i("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), ("OFFSET", 4)], None) + .i("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None) + .i("GLOBAL_LOAD_DWORD", glbl, &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)], None) + .i("GLOBAL_STORE_DWORD", glbl, &[("ADDR", 8), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0)], None) + .i("GLOBAL_ATOMIC_ADD", glbl, &[("VDST", 10), ("ADDR", 3), ("DATA", 11), ("SADDR", 16), ("OFFSET", 0), ("GLC", 1)], None); + if four { + a.i("GLOBAL_LOAD_DWORD", glbl, &[("VDST", 12), ("ADDR", 14), ("SADDR", 0x7D), ("OFFSET", 0)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 12), ("SRC0", V + 6), ("VSRC1", 12)], None) + .i("GLOBAL_STORE_DWORD", glbl, &[("ADDR", 16), ("DATA", 12), ("SADDR", 0x7D), ("OFFSET", 0)], None); + } + a.end() +} + +// --------------------------------------------------------------------------------------------- +// tests + +/// Without a GPU: both forms of the small programs translate completely and DXC compiles them +/// (wave64 split and native, wave32; structured and not). +#[test] +fn compact_and_normal_forms_compile() { + if super::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let programs = [ + ("execz nest", execz_nest()), + ("repeated blocks", repeated_blocks()), + ("shared targets", shared_targets()), + ("far jumps", far_jumps()), + ("exchange repeated", exchange_repeated()), + ("buffer_load_format_x repeated", load_x_repeated()), + ("s_endpgm early", endpgm_early()), + ("window loop", window_loop()), + ]; + for (what, code) in &programs { + for (wave64, split) in [(true, true), (true, false), (false, false)] { + for structured in [true, false] { + let opt = Options { wave64, split_wave64: split, structured, ..Default::default() }; + let (normal, compact) = both_translations(code, &opt); + compiled(&normal, &format!("{what} translate wave64={wave64} split={split} structured={structured}")); + compiled(&compact, &format!("{what} translate_compact wave64={wave64} split={split} structured={structured}")); + assert_eq!(normal.instructions, compact.instructions, "{what}: instruction count"); + } + } + } +} + +#[test] +fn gpu_compact_execz_nest() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 1)); + assert_shape("execz nest", &execz_nest(), true, dispatched); + assert_same("execz nest", &execz_nest(), &inputs, true); +} + +#[test] +fn gpu_compact_backward_loops() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(6, |l| hash(l, 6)); + assert_shape("backward loops", &backward_loops(), true, dispatched); + assert_same("backward loops", &backward_loops(), &inputs, true); +} + +/// The select chain of a case with many targets is cut: every block of `many_targets` gets its +/// target through at most `MAX_SELECTS` selects and `ceil(log2(leaves))` ifs. Before, each ran +/// the whole chain, one select per block of the minority and no `[branch] if`. +#[test] +fn compact_many_targets_take_a_bounded_path() { + let code = many_targets(); + let opt = Options::default(); + let both = [("translate_compact", compact::translate_compact(&code, &opt)), ("every instruction a block", compact::compact(&code, &opt, 0, 0))]; + for (what, t) in both { + let d = Dispatch::of(&t.unwrap_or_else(|e| panic!("{what}: {e}"))); + let c = d.only("[branch] if (xcl_b < "); + let all = d.cases[c].1.matches("xcl_t = select(xcl_b == ").count(); + assert!(all > compact::MAX_SELECTS, "{what}: {all} selects in all"); + let leaves = all.div_ceil(compact::MAX_SELECTS); + let depth = (usize::BITS - (leaves - 1).leading_zeros()) as usize; + // a block per copy (translate_compact), or one per instruction; then the end + let per = (d.blocks() - 1) / MANY; + assert_eq!(d.blocks(), per * MANY + 1, "{what}"); + let mine: Vec = (0..d.blocks()).filter(|&b| d.class[b] == c).collect(); + assert_eq!(mine.len(), MANY, "{what}: blocks of the case"); + let (mut most_selects, mut most_ifs) = (0, 0); + for (j, &b) in mine.iter().enumerate() { + let (to, selects, ifs) = d.target(c, b); + assert_eq!(to, per * many_target(j), "{what}: copy {j} (block {b})"); + assert!(selects <= compact::MAX_SELECTS && ifs <= depth, "{what}: copy {j}: {selects} selects, {ifs} ifs (at most {} and {depth})", compact::MAX_SELECTS); + (most_selects, most_ifs) = (most_selects.max(selects), most_ifs.max(ifs)); + } + assert!(most_ifs >= 1, "{what}: no block goes through an if"); + println!("{what}: {all} selects in the case, a path has at most {most_selects} selects and {most_ifs} ifs"); + } +} + +#[test] +fn gpu_compact_many_targets() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(2, |l| hash(l, 2)).vgpr(3, |l| hash(l, 3) | 1); + assert_shape("many targets", &many_targets(), true, many_targets_shape); + assert_same("many targets", &many_targets(), &inputs, true); +} + +#[test] +fn gpu_compact_shared_targets() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(2, |l| hash(l, 2)).vgpr(3, |l| hash(l, 3) | 1); + assert_shape("shared targets", &shared_targets(), true, shared_targets_shape); + assert_same("shared targets", &shared_targets(), &inputs, true); +} + +/// A table packed across words (`compact::compact` past `dense_above`) gives every block the +/// case the usual packing gives it, and the program runs as `translate`'s does. Every +/// instruction is a block of its own (`heavy` 0), so some cases straddle words. +#[test] +fn gpu_compact_dense_table() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 1)).vgpr(2, |l| hash(l, 2)).vgpr(3, |l| hash(l, 3) | 1).vgpr(6, |l| hash(l, 6)); + let mut straddled = 0; + let programs = [("shared targets", shared_targets()), ("many targets", many_targets()), ("repeated blocks", repeated_blocks()), ("execz nest", execz_nest()), ("backward loops", backward_loops())]; + for (what, code) in programs { + for (form, opt) in forms(true) { + let packed = compact::compact(&code, &opt, 0, usize::MAX).unwrap_or_else(|e| panic!("{what} ({form}): {e}")); + let dense = compact::compact(&code, &opt, 0, 0).unwrap_or_else(|e| panic!("{what} ({form}): {e}")); + let (p, d) = (Dispatch::of(&packed), Dispatch::of(&dense)); + assert!(!packed.hlsl.contains("xcl_p") && dense.hlsl.contains("uint xcl_p = xcl_b * "), "{what} ({form})"); + let bits = (usize::BITS - (d.cases.len() - 1).leading_zeros()) as usize; + straddled += (0..d.blocks()).filter(|b| b * bits % 32 + bits > 32).count(); + assert_eq!((&p.class, &p.cases), (&d.class, &d.cases), "{what} ({form})"); + let want = ran(&translate(&code, &opt).unwrap(), "translate", &inputs); + let got = ran(&dense, "compact, packed across words", &inputs); + let diff = differences(&want, &got, slot); + assert!(diff.is_empty(), "{what} ({form}): translate / packed table differ:\n{}", diff.join("\n")); + println!("{what} ({form}): {} blocks, {} cases, {} result bytes identical", d.blocks(), d.cases.len(), got.len()); + } + } + assert!(straddled > 0, "no case straddles a word"); + println!("{straddled} blocks' cases straddle a word"); +} + +/// The two-level dispatch (`compact::compact_with` with groups of 2 and 4 cases, every +/// instruction a block of its own) runs as `translate` does, in every form of this adapter. +#[test] +fn gpu_compact_nested_dispatch() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 1)).vgpr(2, |l| hash(l, 2)).vgpr(3, |l| hash(l, 3) | 1).vgpr(6, |l| hash(l, 6)); + let programs = [("shared targets", shared_targets()), ("many targets", many_targets()), ("repeated blocks", repeated_blocks()), ("execz nest", execz_nest()), ("backward loops", backward_loops())]; + for (what, code) in programs { + for (form, opt) in forms(true) { + let want = ran(&translate(&code, &opt).unwrap(), "translate", &inputs); + for p in [2, 4] { + let t = compact::compact_with(&code, &opt, 0, usize::MAX, p).unwrap_or_else(|e| panic!("{what} ({form}): {e}")); + assert!(t.hlsl.contains("switch (xcl_c >> "), "{what} ({form}): not nested"); + let got = ran(&t, "compact, nested", &inputs); + let diff = differences(&want, &got, slot); + assert!(diff.is_empty(), "{what} ({form}), groups of {p}: translate / nested differ:\n{}", diff.join("\n")); + } + } + } +} + +#[test] +fn gpu_compact_repeated_blocks() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(2, |l| hash(l, 2)).vgpr(3, |l| hash(l, 3) | 1); + assert_shape("repeated blocks", &repeated_blocks(), true, repeated_shape); + assert_same("repeated blocks", &repeated_blocks(), &inputs, true); +} + +#[test] +fn gpu_compact_far_jumps() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 1)).vgpr(2, |_| 0x22).sgprs(22, &[0x33]); + assert_shape("far jumps", &far_jumps(), true, far_jumps_shape); + for (form, opt, r) in assert_same("far jumps", &far_jumps(), &inputs, true) { + println!("far jumps ({form}): checking s21, s22, v2, v3"); + far_jumps_ran(&r, &opt); + } +} + +#[test] +fn gpu_compact_v_mul_lo_u32() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 1)).vgpr(2, |l| hash(l, 2)).sgprs(8, &[0x8000_0001]); + assert_shape("v_mul_lo_u32", &mul_lo(), false, dispatched); + assert_same("v_mul_lo_u32", &mul_lo(), &inputs, false); +} + +#[test] +fn gpu_compact_buffer_load_format_x() { + if !gpu_ready() { + return; + } + assert_shape("buffer_load_format_x", &load_format_x(), false, dispatched); + assert_same("buffer_load_format_x", &load_format_x(), &load_format_x_inputs(0), false); +} + +/// The plain (unsplit) wave64 form needs 64-lane waves: it is in `forms` only where the GPU has +/// them, and this test says when it is not. +#[test] +fn gpu_compact_native_wave64_form() { + if !gpu_ready() { + return; + } + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + let opt = Options { wave64: true, split_wave64: false, ..Default::default() }; + for (what, code, inputs) in [ + ("execz nest", execz_nest(), Inputs::lanes(Vec::new())), + ("backward loops", backward_loops(), Inputs::lanes(Vec::new())), + ("buffer_load_format_x", load_format_x(), load_format_x_inputs(0)), + ] { + let (a, b) = both_backends(&code, &opt, &inputs); + let d = differences(&a, &b, slot); + assert!(d.is_empty(), "{what} (wave64 native): differ:\n{}", d.join("\n")); + } +} + +/// Compute mode (the game's path: user SGPRs, group id, thread id, `runner::dispatch`), four +/// groups of 64 threads: the divergent loop, then a global store per thread. Memory compared. +#[test] +fn gpu_compact_compute_dispatch() { + if !gpu_ready() { + return; + } + // s0, s1 user SGPRs; s2 group id x; v0 thread id + let mut a = Asm::default(); + a.i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 2)], None) + .i("V_AND_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 135), ("VSRC1", 0)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 2), ("VSRC1", 5)], None) + .i("S_MOV_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", EXEC)], None) + .label("loop") + .i("V_CMP_NE_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 5)], None) + .i("S_AND_B64", "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", VCC)], None) + .br("S_CBRANCH_EXECZ", "done") + .i("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 4), ("SRC1", 255)], Some(0x0100_0193)) + .i("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 4)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 193), ("VSRC1", 5)], None) + .br("S_BRANCH", "loop") + .label("done") + .i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC), ("SSRC0", 10)], None) + .i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 136)], None) + .i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 3), ("VSRC1", 6)], None) + .i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 0), ("VSRC1", 6)], None) + .i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None) + .i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None); + let code = a.end(); + let mut io = vec![0u32; 128]; + io[0] = 0x40; // store base + for wave64 in [true, false] { + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let opt = Options { mode: Mode::Compute(cs), wave64, split_wave64: wave64 && runner::split_wave64(), ..Default::default() }; + if wave64 && !opt.split_wave64 && runner::wave64_supported() != Ok(true) { + continue; + } + let (normal, compact) = both_translations(&code, &opt); + dispatched(&Dispatch::of(&compact), &opt); + let mem = vec![0xFFFF_FFFFu32; 0x40 / 4 + 4 * 64]; + let a = runner::dispatch(&compiled(&normal, "translate"), [4, 1, 1], &io, &mem).unwrap(); + let b = runner::dispatch(&compiled(&compact, "translate_compact"), [4, 1, 1], &io, &mem).unwrap(); + let to = |m: &[u32]| m.iter().flat_map(|w| w.to_le_bytes()).collect::>(); + let d = differences(&to(&a), &to(&b), |i| format!("mem[{:#x}]", 4 * i)); + assert!(d.is_empty(), "compute (wave64={wave64}): differ:\n{}", d.join("\n")); + assert!(a[0x40 / 4..].iter().all(|&w| w != 0xFFFF_FFFF), "compute (wave64={wave64}): every thread stored"); + } +} + +/// Bytes of each UMA window `arena_both` sets up and compares. +const SPAN: usize = 0x10000; + +/// `both_backends` through `runner::run_in_arena` (the `mem_windows` form): before each run the +/// first `SPAN` bytes of every window of `arena` are filled from a hash and `inputs.mem` is +/// copied to the start of window 0; result buffer, then every window's first `SPAN` bytes. +fn arena_both(code: &[u8], opt: &Options, inputs: &Inputs, arena: &crate::gpu::uma::Uma) -> (Vec, Vec) { + let window = |k: usize| unsafe { std::slice::from_raw_parts_mut(arena.window(k).0 as *mut u32, SPAN / 4) }; + let (normal, compact) = both_translations(code, opt); + let run = |t: &Translation, backend: &str| { + let dxil = compiled(t, backend); + for k in 0..arena.windows() { + for (i, w) in window(k).iter_mut().enumerate() { + *w = hash(i, 0xA0 + k as u32); + } + } + window(0)[..inputs.mem.len()].copy_from_slice(&inputs.mem); + let r = runner::run_in_arena(&dxil, &inputs.state, arena).unwrap_or_else(|e| panic!("{backend}: {e}")); + let mut v: Vec = r.raw.iter().flat_map(|w| w.to_le_bytes()).collect(); + for k in 0..arena.windows() { + v.extend(window(k).iter().flat_map(|x| x.to_le_bytes())); + } + v + }; + (run(&normal, "translate"), run(&compact, "translate_compact")) +} + +/// Name of dword `i` of an `arena_both` result. +fn arena_slot(i: usize) -> String { + if i < KERNEL_RES_DWORDS { + return slot(i); + } + let k = i - KERNEL_RES_DWORDS; + format!("window {} +{:#x}", k / (SPAN / 4), 4 * (k % (SPAN / 4))) +} + +fn assert_same_in_arena(what: &str, code: &[u8], opt: &Options, inputs: &Inputs, arena: &crate::gpu::uma::Uma, form: &str) { + let (a, b) = arena_both(code, opt, inputs, arena); + let d = differences(&a, &b, arena_slot); + assert!(d.is_empty(), "{what} ({form}, {} windows): translate / translate_compact differ:\n{}", opt.mem_windows, d.join("\n")); + println!("{what} ({form}, {} windows): {} result bytes identical", opt.mem_windows, a.len()); +} + +/// Memory windows (`mem_windows` 2 and 4, `runner::run_in_arena`): loads, stores and an atomic +/// in window 1 next to window 0; with 4, a load from window 3 stored into window 2. The program +/// has no branch, so `translate_compact` gives `translate`'s form: `gpu_compact_memory_windows_loop` +/// runs the compact one. +#[test] +fn gpu_compact_memory_windows() { + if !gpu_ready() { + return; + } + for windows in [2usize, 4] { + let arena = crate::gpu::uma::Uma::with_windows(windows, 1 << 20).unwrap(); + let w = |k: usize| arena.window(k).0 as u64; + let hi = |a: u64| (a >> 32) as u32; + let (w0, w1) = (w(0), w(1)); + let mut st = Inputs::lanes(Vec::new()) + .sgprs(2, &[(w1 + 0x1000) as u32, hi(w1)]) + .sgprs(8, &[(w1 + 0x2000) as u32, hi(w1) & 0xFFFF | 4 << 16, 64, 0]) + .sgprs(12, &[(w0 + 0x3000) as u32, hi(w0) & 0xFFFF | 4 << 16, 64, 0]) + .sgprs(16, &[(w1 + 0x6000) as u32, hi(w1)]) + .vgpr(2, |l| 7 * l as u32) + // the atomic's address: a dword per lane. On one dword, the split form's two halves' + // atomics land in either order, in both backends, and the values they return differ + .vgpr(3, |l| 4 * l as u32) + .vgpr(4, |l| (w1 + 0x4000 + 4 * l as u64) as u32) + .vgpr(5, |_| hi(w1)) + .vgpr(8, |l| (w1 + 0x5000 + 4 * l as u64) as u32) + .vgpr(9, |_| hi(w1)) + .vgpr(11, |l| l as u32 + 1); + if windows == 4 { + let (w2, w3) = (w(2), w(3)); + st = st.vgpr(14, |l| (w3 + 0x7000 + 8 * l as u64) as u32).vgpr(15, |_| hi(w3)).vgpr(16, |l| (w2 + 0x8000 + 4 * l as u64) as u32).vgpr(17, |_| hi(w2)); + } + let code = window_program(windows == 4); + for (form, o) in forms(false) { + assert_same_in_arena("memory windows", &code, &Options { mem_windows: windows as u32, ..o }, &st, &arena, &form); + } + } +} + +/// `window_loop` (branches, repeated blocks, loads, stores and atomics in four windows) in every +/// form of `forms` with `mem_windows: 4`: the compact form is used (its HLSL is not +/// `translate`'s), and both leave the same registers and windows. Every copy runs in both +/// iterations in the wave64 forms (s22 = 8). +#[test] +fn gpu_compact_memory_windows_loop() { + if !gpu_ready() { + return; + } + let arena = crate::gpu::uma::Uma::with_windows(4, 1 << 20).unwrap(); + let inputs = window_loop_inputs(&arena); + let code = window_loop(); + for (form, o) in forms(true) { + let opt = Options { mem_windows: 4, ..o }; + let (normal, compact) = both_translations(&code, &opt); + assert_ne!(normal.hlsl, compact.hlsl, "{form}: the compact form is used"); + let d = Dispatch::of(&compact); + window_loop_shape(&d, &opt); + println!("window loop ({form}, 4 windows): compact form has {} cases for {} blocks", d.cases.len(), d.blocks()); + let (a, b) = arena_both(&code, &opt, &inputs, &arena); + let diff = differences(&a, &b, arena_slot); + assert!(diff.is_empty(), "window loop ({form}, 4 windows): translate / translate_compact differ: +{}", diff.join(" +")); + if opt.wave64 { + assert_eq!(dword(&a, 22), 8, "window loop ({form}): s22"); + // every window's stored (+0x2000) and atomic (+0x2800) dwords changed (`arena_both` + // fills window k with hash(i, 0xA0 + k)) + for k in 0..4 { + for at in [0x2000, 0x2800] { + let changed = (at / 4..at / 4 + 64).filter(|&i| dword(&a, KERNEL_RES_DWORDS + k * SPAN / 4 + i) != hash(i, 0xA0 + k as u32)).count(); + assert!(changed > 0, "window loop ({form}): window {k} +{at:#x} written"); + } + } + } + println!("window loop ({form}, 4 windows): {} result bytes identical", a.len()); + } +} + +/// The form titles run in: the wave64 forms of `forms` (split on a 32-lane GPU) with +/// `mem_windows: 4`, run in a four-window arena, for every program here (buffer_load_format_x +/// reads V#s in window 0). +#[test] +fn gpu_compact_programs_with_four_windows() { + if !gpu_ready() { + return; + } + let arena = crate::gpu::uma::Uma::with_windows(4, 1 << 20).unwrap(); + let w0 = arena.window(0).0 as u64; + let lanes = || Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 1)).vgpr(2, |l| hash(l, 2)).vgpr(3, |l| hash(l, 3) | 1); + type Shape = Option; + let programs: Vec<(&str, Vec, Inputs, Shape)> = vec![ + ("execz nest", execz_nest(), lanes(), Some(dispatched)), + ("backward loops", backward_loops(), lanes(), Some(dispatched)), + ("repeated blocks", repeated_blocks(), lanes(), Some(repeated_shape)), + ("far jumps", far_jumps(), lanes(), Some(far_jumps_shape)), + ("v_mul_lo_u32", mul_lo(), lanes().sgprs(8, &[0x8000_0001]), Some(dispatched)), + ("exchange repeated", exchange_repeated(), lanes(), Some(exchange_shape)), + ("s_endpgm early (s30 = 0)", endpgm_early(), lanes(), Some(endpgm_shape)), + ("s_endpgm early (s30 = 2)", endpgm_early(), lanes().sgprs(30, &[2]), Some(endpgm_shape)), + ("buffer_load_format_x", load_format_x(), load_format_x_inputs(w0), Some(dispatched)), + ("buffer_load_format_x repeated", load_x_repeated(), load_format_x_inputs(w0), Some(load_x_shape)), + ]; + let wave64: Vec<(String, Options)> = forms(true).into_iter().filter(|(_, o)| o.wave64).collect(); + assert!(!wave64.is_empty(), "gpu_ready: a wave64 form runs here"); + assert_eq!(wave64.iter().any(|(_, o)| o.split_wave64), runner::split_wave64(), "the split form runs where the adapter needs it"); + for (what, code, inputs, shape) in &programs { + for (form, o) in &wave64 { + let opt = Options { mem_windows: 4, ..o.clone() }; + if let Some(check) = shape { + check(&Dispatch::of(&compact::translate_compact(code, &opt).unwrap()), &opt); + } + assert_same_in_arena(what, code, &opt, inputs, &arena, form); + } + } +} + +/// Cross-lane exchanges in a repeated block (`exchange_repeated`). +#[test] +fn gpu_compact_exchange_repeated() { + if !gpu_ready() { + return; + } + let inputs = Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 1) % 64).vgpr(2, |l| hash(l, 2)).vgpr(3, |l| hash(l, 3)); + assert_shape("exchange repeated", &exchange_repeated(), true, exchange_shape); + assert_same("exchange repeated", &exchange_repeated(), &inputs, true); +} + +/// buffer_load_format_x in a repeated block (`load_x_repeated`). +#[test] +fn gpu_compact_buffer_load_format_x_repeated() { + if !gpu_ready() { + return; + } + assert_shape("buffer_load_format_x repeated", &load_x_repeated(), true, load_x_shape); + assert_same("buffer_load_format_x repeated", &load_x_repeated(), &load_format_x_inputs(0), true); +} + +/// s_endpgm before the last block (`endpgm_early`), each of its three paths. +#[test] +fn gpu_compact_endpgm_before_last_block() { + if !gpu_ready() { + return; + } + assert_shape("s_endpgm early", &endpgm_early(), true, endpgm_shape); + for path in 0..3u32 { + let inputs = Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 1)).sgprs(30, &[path]); + // s31: 1 at the first s_endpgm, 3 at the second, 4 at the last + let want = [3, 1, 4][path as usize]; + for (form, _, r) in assert_same(&format!("s_endpgm early (s30 = {path})"), &endpgm_early(), &inputs, true) { + assert_eq!(dword(&r, 31), want, "s_endpgm early (s30 = {path}, {form}): s31"); + } + } +} + +/// 200 conditional forward jumps whose targets all follow them: past #1307's bound, so +/// `translate` falls back to `pc` blocks after `prepare` (the program it does that with is the +/// one `translate` was given). The compact form of the same program computes the same. +#[test] +fn gpu_compact_against_the_pc_block_fallback() { + if !gpu_ready() { + return; + } + let i = |name: &str, e: &str, f: &[(&str, u64)]| encode(name, e, f, None).unwrap(); + let mut code: Vec = Vec::new(); + let mut at = Vec::new(); + for k in 0..200u64 { + code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)])); + code.extend(i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128 + k % 16)])); + at.push(code.len()); + code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)])); + } + for a in at { + let d = ((code.len() - a) / 4 - 1) as u16; + code[a..a + 2].copy_from_slice(&d.to_le_bytes()); + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 0), ("VSRC1", 1)])); + } + code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + let normal = translate(&code, &Options::default()).unwrap(); + assert!(normal.complete() && normal.hlsl.contains("pc =="), "translate did not fall back to pc blocks"); + let inputs = Inputs::lanes(Vec::new()).vgpr(1, |l| hash(l, 2)); + assert_same("pc-block fallback", &code, &inputs, false); +} + +/// `XCL_SAMPLE_BIG_CS=`: a retail program's code (e.g. 56c0cd3b82a00c6e, 488 744 bytes), +/// run as a kernel through both backends: v0 = lane index, the code as memory from address 0 +/// plus 64 KiB of zeros, every other input 0. Does nothing when the variable is unset. +/// DXC takes minutes on programs this size. A program the compact form refuses (e.g. its table +/// limit) is SKIPPED; when the driver cannot create `translate`'s pipeline (e.g. E_OUTOFMEMORY), +/// the A/B comparison is SKIPPED and the compact form must still compile and run. +#[test] +fn gpu_compact_sample_big_cs() { + let Some(path) = std::env::var_os("XCL_SAMPLE_BIG_CS") else { return }; + if !gpu_ready() { + return; + } + let code = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", std::path::Path::new(&path).display())); + let wave64 = super::detect_wave64(&code); + let opt = Options { wave64, split_wave64: wave64 && runner::split_wave64(), ..Default::default() }; + let t0 = std::time::Instant::now(); + let normal = translate(&code, &opt).unwrap_or_else(|e| panic!("translate: {e}")); + let compact = match compact::translate_compact(&code, &opt) { + Ok(t) => t, + Err(e) => { + eprintln!("SKIPPED gpu_compact_sample_big_cs: compact form refused: {e}"); + return; + } + }; + eprintln!( + "big CS: {} instructions, wave64 {wave64}, split {}; HLSL {} / {} bytes (translate / compact), {:.1} s", + normal.instructions, + opt.split_wave64, + normal.hlsl.len(), + compact.hlsl.len(), + t0.elapsed().as_secs_f64() + ); + assert_eq!(normal.unsupported, compact.unsupported, "unsupported instructions"); + let inputs = Inputs::lanes(code_mem(&code, 0x4000)); + let mut results = Vec::new(); + for (t, backend) in [(&normal, "translate"), (&compact, "translate_compact")] { + let t1 = std::time::Instant::now(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{backend}: DXC: {e}")); + eprintln!("big CS {backend}: DXIL {} bytes in {:.1} s", dxil.len(), t1.elapsed().as_secs_f64()); + let t2 = std::time::Instant::now(); + match runner::run_with_statics(&dxil, &inputs.state, &inputs.mem, &[], &[], &t.static_samplers) { + Ok(r) => { + eprintln!("big CS {backend}: ran in {:.2} s", t2.elapsed().as_secs_f64()); + results.push(Some(bytes(&r))); + } + // only `translate`'s pipeline may fail to be created; the compact form must run + Err(e) if backend == "translate" && e.starts_with("CreateComputePipelineState") => { + eprintln!("big CS translate: {e} after {:.1} s", t2.elapsed().as_secs_f64()); + results.push(None); + } + Err(e) => panic!("{backend}: run: {e}"), + } + } + let (Some(a), Some(b)) = (&results[0], &results[1]) else { + eprintln!("SKIPPED gpu_compact_sample_big_cs: A/B comparison (translate's pipeline was not created)"); + return; + }; + let d = differences(a, b, slot); + assert!(d.is_empty(), "big CS: translate / translate_compact differ:\n{}", d.join("\n")); +} + +/// `XCL_SAMPLE_BIG_CS=`: DXC does not fold the two-level dispatch (groups of 32 cases) +/// back: its DXIL is under 80 % of the flat compact form's (folded back it is about 100 %). +/// Measured with `xcl shaders --precompile`: 36 % for ActivateRays (2,848,780 -> 1,037,876 B), +/// 64 % for two other programs (942,812 -> 602,444 and 847,392 -> 539,260 B). Only DXC is +/// needed, no GPU. The results of the two forms are compared on the synthetic programs +/// (`gpu_compact_nested_dispatch`): a sample's own dispatch does not finish in the runner's +/// 10 s with zero inputs, flat or nested. Does nothing when the variable is unset. +#[test] +fn compact_sample_big_cs_nested_dxil() { + let Some(path) = std::env::var_os("XCL_SAMPLE_BIG_CS") else { return }; + if super::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let code = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", std::path::Path::new(&path).display())); + let wave64 = super::detect_wave64(&code); + let opt = Options { wave64, split_wave64: wave64 && runner::split_wave64(), ..Default::default() }; + let mut len = Vec::new(); + for (nest, what) in [(0, "flat"), (32, "nested")] { + let t = match compact::compact_with(&code, &opt, 600, 8192, nest) { + Ok(t) => t, + Err(e) => { + eprintln!("SKIPPED compact_sample_big_cs_nested_dxil: compact form refused: {e}"); + return; + } + }; + let t1 = std::time::Instant::now(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{what}: DXC: {e}")); + eprintln!("big CS {what}: HLSL {} bytes, DXIL {} bytes in {:.1} s", t.hlsl.len(), dxil.len(), t1.elapsed().as_secs_f64()); + len.push(dxil.len()); + } + eprintln!("big CS nested DXIL: {:.0} % of the flat form's", 100.0 * len[1] as f64 / len[0] as f64); + assert!(len[1] * 10 < len[0] * 8, "big CS: nested DXIL {} B is not under 80 % of the flat {} B", len[1], len[0]); +} + +/// The cases of a dispatch switch from line `*i` of `lines` on, up to the first line that is +/// not a case: ` case {k}u: { // {pc}`, its text, ` } break;`. Each is (number, +/// address, text). +fn dispatch_cases<'a>(lines: &[&'a str], i: &mut usize) -> Result)>, String> { + let mut cases = Vec::new(); + while let Some((k, pc)) = lines.get(*i).and_then(|l| l.strip_prefix(" case ")).and_then(|l| l.split_once("u: { // ")) { + let k: usize = k.parse().map_err(|_| format!("line {}: case number {k:?}", *i + 1))?; + let start = *i + 1; + let len = lines[start..].iter().position(|&l| l == " } break;").ok_or_else(|| format!("case {k}: no end"))?; + cases.push((k, pc, lines[start..start + len].to_vec())); + *i = start + len + 1; + } + Ok(cases) +} + +/// Checks that the two-level dispatch in `nested` (groups of `p`) runs what the flat one in +/// `flat` runs, for every block: +/// - the text before the switch (the table, the loop head) and after it is the same; +/// - the case number `xcl_c` is the flat switch's expression of the table; +/// - case `k` sits in group `k >> log2(p)`, with the flat case's address and text; +/// - every group ends in `xcl_nb = min(xcl_nb, n)` with the loop's own `n`. +/// +/// The `min` changes only an `xcl_nb` of `n` or more, which ends the loop either way +/// (`if (xcl_nb >= n) break;`), and `xcl_nb` is declared in the loop. A case number past the +/// last case reaches a default in both forms. Returns the number of cases. +fn nested_matches_flat(flat: &str, nested: &str, p: usize) -> Result { + const TAIL: &str = " default: xcl_nb = 0xFFFFFFFFu; break;\n }\n"; + let at = flat.find(" switch (").ok_or("flat: no switch")?; + let line = &flat[at..at + flat[at..].find('\n').ok_or("flat: switch line")? + 1]; + let selector = line.strip_prefix(" switch (").and_then(|l| l.strip_suffix(") {\n")).ok_or("flat: switch line")?; + let nat = nested.find(" uint xcl_c = ").ok_or("nested: no xcl_c")?; + if flat[..at] != nested[..nat] { + return Err("the text before the dispatch differs".into()); + } + let head = format!(" uint xcl_c = {selector};\n switch (xcl_c >> {}u) {{\n", p.trailing_zeros()); + if !nested[nat..].starts_with(&head) { + return Err(format!("nested: the case number is not the flat switch's {selector:?} in groups of {p}")); + } + let (fend, nend) = (flat.rfind(TAIL).ok_or("flat: no default")?, nested.rfind(TAIL).ok_or("nested: no default")?); + if flat[fend..] != nested[nend..] { + return Err("the text after the dispatch differs".into()); + } + let tail = &flat[fend..]; + let b = tail.find("if (xcl_nb >= ").ok_or("no loop bound")? + "if (xcl_nb >= ".len(); + let n = &tail[b..b + tail[b..].find("u)").ok_or("loop bound")?]; + let fl: Vec<&str> = flat[at + line.len()..fend].lines().collect(); + let mut i = 0; + let want = dispatch_cases(&fl, &mut i)?; + if i != fl.len() { + return Err(format!("flat: line {:?} between the cases", fl[i])); + } + let nl: Vec<&str> = nested[nat + head.len()..nend].lines().collect(); + let (mut i, mut g, mut got) = (0, 0usize, Vec::new()); + let end = [" default: xcl_nb = 0xFFFFFFFFu; break;".to_string(), format!(" }} xcl_nb = min(xcl_nb, {n}u); break;")]; + while i < nl.len() { + if nl[i] != format!(" case {g}u: switch (xcl_c) {{") { + return Err(format!("nested: group {g} starts with {:?}", nl[i])); + } + i += 1; + let cases = dispatch_cases(&nl, &mut i)?; + if let Some((k, ..)) = cases.iter().find(|c| c.0 / p != g) { + return Err(format!("nested: case {k} in group {g}")); + } + if nl.get(i..i + 2) != Some(&[end[0].as_str(), end[1].as_str()][..]) { + return Err(format!("nested: group {g} ends with {:?}", nl.get(i..(i + 2).min(nl.len())))); + } + i += 2; + got.extend(cases); + g += 1; + } + if got != want { + let k = got.iter().zip(&want).position(|(a, b)| a != b).unwrap_or(got.len().min(want.len())); + return Err(format!("case {k} differs ({} nested cases, {} flat)", got.len(), want.len())); + } + Ok(want.len()) +} + +/// `nested_matches_flat` on the synthetic programs, in every group size and both table +/// packings; and it finds a case moved to another group, a case's text changed, and a group's +/// bound changed. +#[test] +fn nested_dispatch_runs_the_flat_cases() { + let programs = [("shared targets", shared_targets()), ("many targets", many_targets()), ("repeated blocks", repeated_blocks()), ("execz nest", execz_nest()), ("backward loops", backward_loops())]; + let opt = Options::default(); + for (what, code) in &programs { + for dense in [usize::MAX, 0] { + let flat = compact::compact_with(code, &opt, 0, dense, 0).unwrap(); + for p in [1, 2, 4, 8, 16, 32] { + let t = compact::compact_with(code, &opt, 0, dense, p).unwrap(); + let cases = nested_matches_flat(&flat.hlsl, &t.hlsl, p).unwrap_or_else(|e| panic!("{what}, groups of {p}, dense {}: {e}", dense == 0)); + assert_eq!(cases, flat.blocks, "{what}"); + } + } + } + let code = many_targets(); + let flat = compact::compact_with(&code, &opt, 0, usize::MAX, 0).unwrap().hlsl; + let t = compact::compact_with(&code, &opt, 0, usize::MAX, 2).unwrap().hlsl; + assert_eq!(nested_matches_flat(&flat, &t, 2), Ok(flat.matches("u: { // ").count())); + // cases 1 and 2 swap numbers: 2 is then in group 0 + let moved = t.replacen(" case 1u: {", " case X: {", 1).replacen(" case 2u: {", " case 1u: {", 1).replacen(" case X: {", " case 2u: {", 1); + assert_eq!(nested_matches_flat(&flat, &moved, 2), Err("nested: case 2 in group 0".into())); + let at = t.find(" case 1u: {").unwrap(); + let at = at + t[at..].find('\n').unwrap() + 1; + let changed = format!("{} xcl_nb = 0u;\n{}", &t[..at], &t[at..]); + assert!(nested_matches_flat(&flat, &changed, 2).unwrap_err().starts_with("case 1 differs"), "changed"); + let bound = t.replacen("xcl_nb = min(xcl_nb, ", "xcl_nb = min(xcl_nb, 1u + ", 1); + assert!(nested_matches_flat(&flat, &bound, 2).unwrap_err().starts_with("nested: group 0 ends with"), "bound"); + assert!(nested_matches_flat(&flat, &t, 4).is_err(), "another group size"); +} + +/// `XCL_SAMPLE_BIG_CS=`: the two-level dispatch of a retail program runs the flat one's +/// cases for every block (`nested_matches_flat`), in groups of 16, 32 and 64, with both table +/// packings. The two forms' results cannot be compared on the GPU for these programs: run as a +/// kernel with zero or random inputs, a retail program does not finish or removes the device, +/// flat or nested (#1269). CPU only. Does nothing when the variable is unset. +#[test] +fn compact_sample_big_cs_nested_runs_the_flat_cases() { + let Some(path) = std::env::var_os("XCL_SAMPLE_BIG_CS") else { return }; + let code = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", std::path::Path::new(&path).display())); + let wave64 = super::detect_wave64(&code); + for split_wave64 in if wave64 { vec![false, true] } else { vec![false] } { + let opt = Options { wave64, split_wave64, ..Default::default() }; + for dense in [8192, 0] { + let flat = match compact::compact_with(&code, &opt, 600, dense, 0) { + Ok(t) => t, + Err(e) => { + eprintln!("SKIPPED compact_sample_big_cs_nested_runs_the_flat_cases: compact form refused: {e}"); + return; + } + }; + for p in [16, 32, 64] { + let t = compact::compact_with(&code, &opt, 600, dense, p).unwrap_or_else(|e| panic!("groups of {p}: {e}")); + let cases = nested_matches_flat(&flat.hlsl, &t.hlsl, p).unwrap_or_else(|e| panic!("big CS, groups of {p}, split {split_wave64}, dense {}: {e}", dense == 0)); + assert_eq!(cases, flat.blocks, "big CS, groups of {p}"); + eprintln!("big CS: {cases} cases, groups of {p}, wave64 {wave64}, split {split_wave64}, dense {}: the nested dispatch runs the flat cases", dense == 0); + } + } + } +} diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 2eb90fb85..479020347 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -393,7 +393,7 @@ fn recompile(blob: &[u8], sh: &xbox::XboxShader, base: &std::path::Path) { for (j, p) in f.programs.iter().enumerate() { let code = &f.data[p.offset..p.offset + p.len]; let opt = recomp::Options { mode: mode.clone(), wave64: recomp::detect_wave64(code), ..Default::default() }; - let Ok(t) = recomp::translate(code, &opt) else { continue }; + let Ok(t) = recomp::translate_routed(code, &opt) else { continue }; let _ = std::fs::write(base.with_extension(format!("fssm{i}.p{j}.hlsl")), &t.hlsl); let built = if dxc && t.complete() { Some(recomp::dxc::compile_cached(&t.hlsl, "main", profile)) } else { None }; if let Some(Err(e)) = &built { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ff9ac68b2..3e7d7307a 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -508,7 +508,7 @@ impl RecompAgg { } // `XCL_RECOMP_WINDOWS=4`: as a title with unified memory translates (`pso::mem_windows`) let mem_windows = std::env::var("XCL_RECOMP_WINDOWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1); - match recomp::translate(code, &recomp::Options { mode, wave64, mem_windows, ..Default::default() }) { + match recomp::translate_routed(code, &recomp::Options { mode, wave64, mem_windows, ..Default::default() }) { Ok(t) => { let e = self.by_mode.entry(label.to_string()).or_default(); e.0 += 1; @@ -1061,7 +1061,7 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) } .map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?; let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev)); - let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; + let (translation, profile, _) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split, recomp::CompactCs::get()).map_err(|e| Failed(format!("{name}: {e}")))?; let dxc_start = std::time::Instant::now(); let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; let dxc_ms = dxc_start.elapsed().as_millis(); @@ -1424,7 +1424,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; let opt = recomp::Options { mode: mode.clone(), wave64: recomp::detect_wave64(code), split_wave64: split, mem_windows: windows, ..Default::default() }; - let Ok(t) = recomp::translate(code, &opt) else { continue }; + let Ok(t) = recomp::translate_routed(code, &opt) else { continue }; if !t.complete() { continue; }