From f9935af1647917d02a585dcdf160af0a5755d988 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:53:23 +0100 Subject: [PATCH] Recompiler: XCL_DIRECT_COMPACT_MIN= takes big compute programs compact The direct translator picks the compact form (each distinct block lowered once, run from a table) only for size: from 10,000 instructions or 2,000 blocks, and only when most of the program repeats. Below that a big program gets the plain form, whose register allocation in the driver can be the program's cost. The title's shadow-mask program (cs d9fac2f1d8f646fd, ~6,000 instructions, a light loop around nearly all of it; 20-139 ms a frame in the open world) compiles on RDNA4 (RGA, amdxc64 gfx1201, the run's heap windows) to 256 VGPRs and 18 KB of scratch a lane, ~18,000 scratch loads and stores; its compact form to 215 VGPRs, 75 SGPRs and no scratch, 32,146 instead of 58,333 instructions. XCL_DIRECT_COMPACT_MIN=: a compute program of at least n reachable instructions takes the compact form whenever its table fits, however little of it repeats (compact::sized_plan); otherwise the automatic choice as before. Unset by default; the caches key the value. Measured on the GPU (RX 9070 XT, Adrenalin as installed, RDNA4 wave32; the program patched past its early exits with a light mask of all ones, zero memory, 40x40 groups of 4x8, one 32-light word; ms a dispatch): plain 95.6 (8,192-dword LDS) / 80.0 (declared LDS), compact 24.7 / 4.0. Port onto main: the conflicts were only the caches identities and the test plumbing next to amd-dev-only switches (declared LDS, coherent per access, one-wave group IDs); only the XCL_DIRECT_COMPACT_MIN parts are taken. (cherry picked from commit 41dc012e) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 38 +++++++++++- crates/xcl/src/gpu/dxil/compact_tests.rs | 77 ++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 17 +++++- crates/xcl/src/gpu/recomp/pso.rs | 22 +++++++ 4 files changed, 151 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 65c1a51b00..5a97cabac5 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -270,6 +270,41 @@ pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { repeated.then_some(p) } +/// `XCL_DIRECT_COMPACT_MIN=` (unset: off): a compute program of at least that +/// many reachable non-terminator instructions takes the compact form whenever it has one whose +/// table fits (`sized_plan`), however little of it repeats. The automatic choice is about size; +/// this one is about speed: on a big program the driver's register allocation of the plain +/// form can spill most of the program's values (a retail title's 6,000-instruction shadow-mask +/// program: 256 VGPRs and 18 KB of scratch a lane on RDNA4), and the compact form's blocks, +/// each lowered on its own, need none. +pub fn compact_min() -> Option { + #[cfg(test)] + if let Some(v) = COMPACT_MIN_FOR_TEST.with(|c| c.get()) { + return v; + } + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_DIRECT_COMPACT_MIN").ok().and_then(|v| v.trim().parse::().ok()).filter(|&n| n > 0)) +} + +#[cfg(test)] +thread_local! { + /// `compact_min` for the translations of this test thread + pub(crate) static COMPACT_MIN_FOR_TEST: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} + +/// The compact form of a program of at least `min` reachable instructions whose table fits +/// (`compact_min`). +pub fn sized_plan(cfg: &Cfg, lw: &Lw, min: usize) -> Option { + if insts(cfg) < min { + return None; + } + plan(cfg, lw).filter(|p| p.words() <= MAX_TABLE_WORDS) +} + +fn insts(cfg: &Cfg) -> usize { + cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum() +} + /// Reachable non-terminator instruction count threshold for trying the compact form. const LARGE_INSTS: usize = 10_000; /// Reachable basic-block count threshold for trying the compact form: branch-heavy @@ -280,8 +315,7 @@ const LARGE_BLOCKS: usize = 2_000; /// Whether to consider compaction based on the reachable instruction and block counts. pub fn large(cfg: &Cfg) -> bool { - cfg.rpo.len() >= LARGE_BLOCKS - || cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= LARGE_INSTS + cfg.rpo.len() >= LARGE_BLOCKS || insts(cfg) >= LARGE_INSTS } pub const END: u32 = u32::MAX; diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index cf56c97c85..15d4d14e2a 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -479,3 +479,80 @@ fn gpu_nested_compact_matches_plain_and_flat() { .expect("nested budget GPU run"); assert_eq!((got3.sgpr, got3.vgpr, got3.scc), (plain3.sgpr, plain3.vgpr, plain3.scc), "nested loop budget"); } + +/// `f` with `XCL_DIRECT_COMPACT_MIN` taken as `min` by the translations of this thread. +fn with_compact_min(min: Option, f: impl FnOnce() -> R) -> R { + let before = super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.replace(Some(min))); + let r = f(); + super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.set(before)); + r +} + +/// `XCL_DIRECT_COMPACT_MIN`: a compute program of at least that many instructions takes the +/// compact form, below the automatic choice's size; a smaller one, or a kernel, keeps the plain +/// form. +#[test] +fn a_compute_program_from_the_compact_size_takes_the_compact_form() { + if compact_mode().is_some() { + return; + } + use crate::gpu::recomp::CsInterface; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + // 100 copies: 900 instructions, below the automatic thresholds + let code = repeated(100); + let compute = |min| with_compact_min(min, || super::kernel::translate_compute(&code, o, &cs)).unwrap().dxil.len(); + let plain = compute(None); + assert!(compute(Some(500)) * 3 < plain, "compact {} B, plain {plain} B", compute(Some(500))); + assert_eq!(compute(Some(5000)), plain, "below the size"); + let kernel = |min| with_compact_min(min, || translate_full(&code, o)).unwrap().dxil; + assert_eq!(kernel(Some(500)), kernel(None), "a kernel keeps its form"); +} + +/// A compute program in the compact form `XCL_DIRECT_COMPACT_MIN` gives it runs as in the plain +/// one: every thread of a 2-D wave32 group stores its own (group, y, x). +#[test] +fn gpu_compute_compact_form_from_the_size_runs_as_the_plain_form() { + use crate::gpu::recomp::{CsInterface, KERNEL_SGPRS}; + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + const V: u64 = 256; + let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut code = Vec::new(); + code.extend(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 1)])); // y · 8 + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)])); // + x + code.extend(i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 134)])); // gid · 64 + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)])); // i + // v3 = x · (y + 1): a loop of y + 1 passes, each lane leaving EXEC after its own + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)])); + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 1)])); + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)])); // loop: v3 += x + code.extend(i("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 129), ("VSRC1", 5)])); // v5 -= 1 + code.extend(i("V_CMP_GT_I32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 5)])); // vcc = 0 > v5 + code.extend(i("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)])); // exec &= !vcc + code.extend(i("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)])); + code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); // exec = all + code.extend(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 2)])); // 4i + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)])); + code.extend(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 3), ("SADDR", 0x7D)])); + code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + let cs = CsInterface { threads: [8, 4, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2, ..Default::default() }; + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let groups = 4u32; + let mut want = vec![0xFFFF_FFFFu32; 64 * groups as usize]; + for g in 0..groups { + for y in 0..4 { + for x in 0..8 { + want[(g * 64 + y * 8 + x) as usize] = x * (y + 1); + } + } + } + for min in [None, Some(1)] { + let k = with_compact_min(min, || super::kernel::translate_compute(&code, o, &cs)).unwrap_or_else(|e| panic!("{min:?}: {e}")); + let mem = runner::dispatch(&k.dxil, [groups, 1, 1], &vec![0u32; KERNEL_SGPRS], &vec![0xFFFF_FFFFu32; want.len()]).expect("GPU run"); + assert_eq!(&mem[..want.len()], &want[..], "compact size {min:?}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index f57cf8d7c0..06dd44e165 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -103,6 +103,14 @@ pub fn compact_mode() -> Option { } } +/// `XCL_DIRECT_COMPACT_MIN` (`compact::compact_min`), for the caches' identities. +pub fn compact_min() -> Option { + super::compact::compact_min() +} + +#[cfg(test)] +pub(crate) use super::compact::COMPACT_MIN_FOR_TEST; + /// Non-default `XCL_DIRECT_COMPACT_NEST` cache tag for the translated cache identity. pub fn compact_nest_tag() -> Option { super::compact::nest_mode().cache_tag() @@ -251,11 +259,15 @@ fn translate_entry_with( // a register's definition and its use): a thread with a large stack for big programs let code = code.to_vec(); #[cfg(test)] + let compact_min = super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.get()); + #[cfg(test)] let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) .spawn(move || { + #[cfg(test)] + super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.set(compact_min)); #[cfg(test)] super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask) @@ -424,7 +436,10 @@ fn translate_on_this_thread( _ if !compute && !kernel => None, Some(false) => None, Some(true) => super::compact::plan(&cfg, &lw), - None => super::compact::automatic_plan(&cfg, &lw, compute && split), + None => match super::compact::compact_min() { + Some(min) if compute => super::compact::sized_plan(&cfg, &lw, min).or_else(|| super::compact::automatic_plan(&cfg, &lw, split)), + _ => super::compact::automatic_plan(&cfg, &lw, compute && split), + }, }; if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index f4a3b95d8c..8c8ba2e355 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -375,6 +375,11 @@ mod translated { Some(on) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }), _ => id, }; + // `XCL_DIRECT_COMPACT_MIN`: compute programs from that size take the compact form + let id = match crate::gpu::dxil::kernel::compact_min() { + Some(n) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &format!("xcl-direct-compact-min-{n}")), + _ => id, + }; // `XCL_DIRECT_COMPACT_NEST`: a non-default nesting policy changes the compact IR let id = match crate::gpu::dxil::kernel::compact_nest_tag() { Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag), @@ -690,6 +695,10 @@ mod translated { Some(tag) => identity_for(&id.to_string(), tag), None => id, }; + let id = match crate::gpu::dxil::kernel::compact_min() { + Some(n) => identity_for(&id.to_string(), &format!("xcl-direct-compact-min-{n}")), + None => id, + }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); if crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) @@ -2127,6 +2136,19 @@ mod slab_tests { mod shader_cache_tests { use super::*; + /// `XCL_DIRECT_COMPACT_MIN` translations are other entries of the direct translator's caches. + #[test] + fn a_compact_size_is_another_direct_output() { + let with = |n| { + let before = crate::gpu::dxil::kernel::COMPACT_MIN_FOR_TEST.with(|c| c.replace(Some(n))); + let id = translated::direct_output_identity(None, 1); + crate::gpu::dxil::kernel::COMPACT_MIN_FOR_TEST.with(|c| c.set(before)); + id + }; + assert_ne!(with(None), with(Some(4096))); + assert_ne!(with(Some(4096)), with(Some(8192))); + } + /// The switch form (no heap windows, or a pipeline retried in it) has 4 root UAVs: a wider /// count there is 4, which every translator takes; the heap form keeps all of them. #[test]