From 8e3acf5ef1d0451c68127d44e49fb4df745fde89 Mon Sep 17 00:00:00 2001 From: CowboyBingus <267457386+CowboyBingus@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:44:53 -0800 Subject: [PATCH 1/4] Recompiler: decode and set up the emitter in prepare(), shared by translate No behaviour change: the decoding, block leaders and emitter set-up at the start of translate() move into prepare(), so a second form of the program (the compact form) is built from exactly the same decoded program and emitter state. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/mod.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index d1e7d8bc4e..82b9cd993d 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1383,8 +1383,18 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B out } -pub fn translate(code: &[u8], opt: &Options) -> Result { - let program = code; +/// 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 +1473,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 { From 711f9f218f4159a525b352b0b58801e63d92094f Mon Sep 17 00:00:00 2001 From: CowboyBingus <267457386+CowboyBingus@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:45:58 -0800 Subject: [PATCH 2/4] Recompiler: compact form that emits every distinct block text once DXC inlines every helper of a cs_6_x target, so a retail compute shader with thousands of equal blocks (ActivateProbes 56c0cd3b82a00c6e: 88,863 instructions, 3,281 buffer_load_format_x) becomes 29.75 MB of DXIL that the driver needs minutes for. translate_compact() cuts the program into blocks (leaders, plus every instruction whose HLSL exceeds 600 B on its own), emits each instruction with emit::Em as translate() does, temporaries numbered from t1 per instruction, and shares equal block texts as cases of one dispatch loop. Branches go to a block at an offset from their own (part of the text), so a static table only holds every block's case, packed. The table is capped at 8,192 words: on an RTX 5070 Ti, CreateComputePipelineState of this program's compact form with an added 12,288-word static array succeeded; with 15,360 words it failed with E_OUTOFMEMORY. Back edges spend the loop budget (65,536 per lane); once it is spent the program ends, where the structured form leaves the loop and runs what follows. compact_wanted() picks programs of 20,000+ instructions whose distinct blocks hold under 30 % of them. Not called yet. Measured on 56c0cd3b82a00c6e (4 memory windows, split wave64, RTX 5070 Ti, a local merge, 31be310): 723,453 B HLSL, DXIL 1,053,264 B in 12.5 s, CreateComputePipelineState 9.7 s from a new exe with no cached blob. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/compact.rs | 360 +++++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/emit.rs | 6 + crates/xcl/src/gpu/recomp/mod.rs | 1 + 3 files changed, 367 insertions(+) create mode 100644 crates/xcl/src/gpu/recomp/compact.rs diff --git a/crates/xcl/src/gpu/recomp/compact.rs b/crates/xcl/src/gpu/recomp/compact.rs new file mode 100644 index 0000000000..c741f24a61 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/compact.rs @@ -0,0 +1,360 @@ +//! 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 share one `case` of a +//! dispatch loop. A branch goes to the block at an offset from its own (part of the text), 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. +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) +} + +/// 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) +} + +fn compact(code: &[u8], opt: &Options, heavy: 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); each block's text + let mut texts: Vec<(String, u64)> = Vec::new(); + let mut index: HashMap = HashMap::new(); + let mut class = Vec::with_capacity(n); + for (k, b) in list.into_iter().enumerate() { + let mut text = b.text; + if let Some((cond, t)) = b.branch { + let to = *at.get(&t).ok_or_else(|| format!("+{:#x}: branch to {t:#x}, which starts no block", b.pc))?; + let nb = if to >= k { format!("xcl_b + {}u", to - k) } else { format!("xcl_b - {}u", k - to) }; + let _ = if cond.is_empty() { writeln!(text, " xcl_nb = {nb};") } else { writeln!(text, " if ({cond}) xcl_nb = {nb};") }; + } + let c = match index.get(&text) { + Some(&c) => c, + None => { + index.insert(text.clone(), texts.len()); + texts.push((text, b.pc)); + texts.len() - 1 + } + }; + class.push(c as u32); + } + // the table: the blocks' cases, `per` to a word + let bits = (usize::BITS - texts.len().saturating_sub(1).leading_zeros()).max(1); + let per = (32 / bits) as usize; + let words: Vec = class.chunks(per).map(|c| c.iter().enumerate().fold(0u32, |w, (j, &v)| w | v << (j as u32 * bits))).collect(); + 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 _ = writeln!(body, " switch ((XCL_BT[xcl_b / {per}u] >> (xcl_b % {per}u * {bits}u)) & {mask:#x}u) {{"); + 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, + }) +} + +#[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 + ]) + } + + #[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("switch ((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).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).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 069c8b3f6f..8409e32af5 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 82b9cd993d..348322ce77 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; From cca0932dec48992bad3ea7156ac1a1513e4551ab Mon Sep 17 00:00:00 2001 From: CowboyBingus <267457386+CowboyBingus@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:18:45 -0800 Subject: [PATCH 3/4] Tests: A/B tests of translate_compact against translate on the GPU tests_compact translates each program with translate and with compact::translate_compact and runs both on the same inputs. The kernel programs assert byte-identical SGPRs, SCC, VGPRs of all lanes, exports and the split form's upper-half SGPRs, plus flat memory or the first 64 KiB of each memory window; the compute dispatch compares memory. Programs: nested execz regions, divergent and scalar backward loops, one block repeated at five addresses, far jumps (s_getpc_b64, add or sub, s_setpc_b64) forward and backward, v_mul_lo_u32, buffer_load_format_x in twelve formats and repeated as a block of its own, a cross-lane block (ballot, readfirstlane, readlane) repeated under four exec masks, s_endpgm before the last block, a loop through four memory windows with loads, stores and per-lane atomics, a compute dispatch, and 200 forward jumps that #1307's bound sends to pc blocks in translate (gpu_compact_against_the_pc_block_fallback). The kernel programs run in each form forms() lists for the adapter (wave64 split or native, wave32; with branches also unstructured), and in the wave64 forms with mem_windows: 4; the compute dispatch runs in wave64 (split where the adapter needs it) and wave32. Every program here except one has a branch, and the tests assert that translate_compact gives it the compact form: they read its dispatch loop back from the HLSL. translate_compact keeps translate's form for a program without branches, so the two straight-line programs start with a branch to the next instruction. For the repeated blocks, the exchange block, the buffer loads, the window loop, the far jumps and s_endpgm they also assert the shape: fewer cases than blocks, one case for the four copies of the exchange block and one for the block after the load, the load a case of its own, the far jumps' block offsets, two program ends before the last block. The exception is the memory-window program of gpu_memory_windows_above_4_gib (no branch): it gets translate's form from both, so its test compares translate with itself; the window loop runs the compact form through the windows. The atomics in the memory-window programs add to a dword per lane. On an RTX 5070 Ti (split wave64, 4 windows), with all 64 lanes adding to one dword, 40 runs of the same DXIL returned two different lane 0 values (5 and 35 runs): the split halves' atomics land in either order. gpu_compact_sample_big_cs (XCL_SAMPLE_BIG_CS=) runs a retail program both ways. A program translate_compact 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. Needs the compact backend (compact.rs and `pub mod compact`). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/mod.rs | 2 + crates/xcl/src/gpu/recomp/tests_compact.rs | 1220 ++++++++++++++++++++ 2 files changed, 1222 insertions(+) create mode 100644 crates/xcl/src/gpu/recomp/tests_compact.rs diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 348322ce77..3d3d4ca696 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -71,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 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 0000000000..bd97e81286 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/tests_compact.rs @@ -0,0 +1,1220 @@ +//! 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); + let run = |t: &Translation, backend: &str| { + 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) + }; + (run(&normal, "translate"), run(&compact, "translate_compact")) +} + +/// 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) + let per: usize = after("switch ((XCL_BT[xcl_b / ", "u]").parse().unwrap(); + let bits: u32 = 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 class: Vec = (0..n).map(|b| ((words[b / per] >> (b % per) as u32 * bits) & ((1u32 << bits) - 1)) as usize).collect(); + let mut cases: Vec<(u64, String)> = Vec::new(); + let mut open = false; + for l in h[h.find("switch ((XCL_BT[").unwrap()..].lines().skip(1) { + 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() + } +} + +/// `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); +} + +/// 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()), + ("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); +} + +#[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")); +} From 5328b157590f14bd4b04eaa6719d9b112f766e1b Mon Sep 17 00:00:00 2001 From: CowboyBingus <267457386+CowboyBingus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:36:38 -0800 Subject: [PATCH 4/4] Recompiler: route compute programs through a compact backend (XCL_COMPACT_CS) The switch XCL_COMPACT_CS: unset / auto = the programs compact_wanted picks, 0 = none, 1 = every compute program; another value logs a warning and acts as auto. `translate_routed` gives a compute program to translate_compact where the switch says so and uses `translate` when that returns an error or an incomplete translation. The PSO path (console_translation, both FSPX and FSSM), `xcl shaders` statistics and precompile, and the shader dump's recompile use it. The on-disk translation cache names an entry of a program routed to the compact backend `..._c.bin`, so a compact and a normal translation of one program never share a file; the file name of a normal entry is unchanged. compact.rs is added to the translator sources that identify compatible cache entries (this commit changes that identity, so existing entries are translated again once). One INFO line per compute program routed to the compact backend, the first time: instructions and HLSL bytes, or why it fell back. When dxc::compile_cached fails on a compute program's compact-form HLSL, the program is compiled in the normal form (or taken from the normal form's translation-cache entry when that is on disk), and the result is kept under the normal entry, never the `_c` one; one WARN line is logged before that. A cached-only attempt is not retried: its DXIL is not refused, only not made yet. A refusal is not remembered between runs. A driver (CreateComputePipelineState) rejection of a compact pipeline is not retried in the normal form. With XCL_DIRECT_DXIL (#1426) on, a compute program XCL_COMPACT_CS routes to the compact form goes to the HLSL path's compact form first, not to the direct translator; if DXC refuses that HLSL, the retry in the normal form goes to the direct translator first, then to translate. Every other compute program goes to the direct translator as before, and to the HLSL path when that falls back. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/build.rs | 1 + crates/xcl/src/gpu/recomp/mod.rs | 116 +++++++++++++++++ crates/xcl/src/gpu/recomp/pso.rs | 215 ++++++++++++++++++++++++------- crates/xcl/src/gpu/shader.rs | 2 +- crates/xcl/src/shaders.rs | 6 +- 5 files changed, 287 insertions(+), 53 deletions(-) diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8e..f2a6096cbd 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/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 3d3d4ca696..5afecf456a 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1386,6 +1386,76 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B out } +/// `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 { @@ -1530,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 00ac0a064b..6600bf8e64 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()) } @@ -279,11 +280,12 @@ 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 { + /// `compact`: the program went to the compact backend (`CompactCs`): `_c` 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, if compact { "_c" } else { "" })) } fn header(ident: u64, blob: &[u8]) -> Vec { @@ -380,12 +382,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 +411,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 +451,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 +459,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 +484,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 +515,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 +534,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 +581,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 +656,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 +875,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 +950,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 +1003,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 +1110,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 +1336,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 +1382,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 +1390,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 +1444,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 +1463,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 +1488,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 +1500,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 +1514,63 @@ 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_c.bin", crate::gpu::shader::fnv64(blob))); + 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 +1602,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 +1623,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 +1631,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 +1646,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 +1661,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/shader.rs b/crates/xcl/src/gpu/shader.rs index 2eb90fb852..4790203473 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 ff9ac68b2e..3e7d7307a9 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; }