diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..ae8b956d49 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -659,6 +659,17 @@ fn raw_loads_in_root_windows_are_branchless() { let heap_dxil = translate(&loads, KernelOptions { wave64: false, split: false, mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS, sampler_base: 0 }) .expect("heap windows translate"); super::validate::validate(&heap_dxil).expect("heap windows validate"); + let flat_dxil = translate(&loads, KernelOptions { + wave64: false, + split: false, + mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT, + sampler_base: 0, + }).expect("flat heap windows translate"); + super::validate::validate(&flat_dxil).expect("flat heap windows validate"); + if let (Ok(heap), Ok(flat)) = (super::validate::disassemble(&heap_dxil), super::validate::disassemble(&flat_dxil)) { + let branches = |s: &str| s.lines().filter(|line| line.trim_start().starts_with("br i1 ")).count(); + assert!(branches(&flat) < branches(&heap), "flat heap reads must remove guarded-read branches: guarded {}, flat {}", branches(&heap), branches(&flat)); + } let writes = prog(&[ ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0)], None), diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 814a71794d..4ae040401a 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -126,6 +126,27 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0) } +/// Whether `entry` uses the measured, one-path heap-window read form. Graphics, mesh and +/// geometry stages retain the guarded form until they have stage-specific measurements. +fn reads_heap_flat(entry: &Entry, heap: bool, mem_windows: u32) -> bool { + heap && matches!(entry, Entry::Kernel | Entry::Compute(_)) && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0 +} + +#[cfg(test)] +#[test] +fn only_compute_programs_read_heap_windows_flat() { + use crate::gpu::recomp::{GsInterface, MsInterface, HEAP_FLAT, HEAP_WINDOWS}; + let flat = 4 | HEAP_WINDOWS | HEAP_FLAT; + assert!(reads_heap_flat(&Entry::Kernel, true, flat)); + assert!(reads_heap_flat(&Entry::Compute(CsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Vertex(VsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), true, 4 | HEAP_WINDOWS)); + assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), false, flat)); +} + /// The entry ABI. #[derive(Clone)] pub enum Entry { @@ -184,7 +205,7 @@ fn translate_entry( fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec, Option) { let heap = mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0; let max = if heap { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; - let n = (mem_windows & !crate::gpu::recomp::HEAP_WINDOWS).clamp(1, max); + let n = (mem_windows & !(crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT)).clamp(1, max); if heap && n > 1 { let z = s.m.i32c(0); return (vec![RawUav { handle: z, binding: None }; n as usize], Some(coherent)); @@ -527,6 +548,7 @@ impl Lw { half: z, mems, heap_mem, + heap_flat: reads_heap_flat(entry, heap_mem.is_some(), o.mem_windows), res, fmt_table: None, fmt_desc_cache: HashMap::new(), diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 36f60988e5..41de2a7848 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -231,6 +231,8 @@ pub struct Lw { /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): /// Some(globallycoherent) pub heap_mem: Option, + /// Heap windows read without a branch (`recomp::HEAP_FLAT`; compute programs only). + pub heap_flat: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..c0ee9b6398 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -407,6 +407,24 @@ impl Lw { n: usize, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { + if let (Some(coherent), true) = (self.heap_mem, self.heap_flat) { + let z = self.c(0); + if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) { + return vec![z; n]; + } + let w = self.rd(super::lower::VAR_WIN); + let inside = self.cmpc(Pred::ULt, w, self.mems.len() as u32); + let ok = match guard { + Some(g) if self.s.m.const_u64(g) != Some(1) => self.and(g, inside), + _ => inside, + }; + let w = self.sel(ok, w, z); + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + debug_assert_eq!(vals.len(), n); + return vals.into_iter().map(|v| self.sel(ok, v, z)).collect(); + } let i32 = self.s.m.i32(); let tys = vec![i32; n]; self.with_mem_many_tys(guard, &tys, f) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index b888923bd0..a8ffdc7a10 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -90,6 +90,11 @@ pub const MEM_NULL_STORE: u32 = MEM_NULL_LOAD + 1; /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; +/// Flag in a memory-windows count next to `HEAP_WINDOWS` (`pso::mem_windows`, the caches' keys): +/// the direct DXIL translator reads the heap windows of compute stages without a branch +/// (`Lw::with_mem_i32s`). The HLSL path ignores it. +pub const HEAP_FLAT: u32 = 0x200; + pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { windows <= crate::gpu::uma::MAX_WINDOWS || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) @@ -1521,7 +1526,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result { let program = code; 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() }; + normalized = Options { mem_windows: opt.mem_windows & !(HEAP_WINDOWS | HEAP_FLAT), heap_windows: true, ..opt.clone() }; &normalized } else { opt diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 9321ea9c74..0659b96e1f 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -122,9 +122,14 @@ pub fn fspx(blob: &[u8]) -> Option> { /// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when /// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { - let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); + windows_for(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)) +} + +/// `n` windows as this run's programs take them (`mem_windows`; also the keys +/// `xcl shaders --precompile` makes, so they are the ones the runtime looks up). +pub fn windows_for(n: u32) -> u32 { if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { - n | super::HEAP_WINDOWS + n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 } } else { n } @@ -160,6 +165,13 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } +/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap +/// windows without a branch per access (`HEAP_FLAT`). Opt-in while it is measured. +pub fn heap_flat() -> bool { + static ENV: OnceLock = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) +} + /// A static sampler of a translated program: (S#, comparison) – see `Translation`. pub type StaticSampler = ([u32; 4], bool); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 8c264943f0..79a95df537 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4069,6 +4069,14 @@ fn gpu_memory_windows_from_the_heap() { memory_windows_above_4_gib(true); } +#[test] +fn heap_flat_cache_flag_does_not_change_hlsl_translation() { + let p = prog(&[("S_ENDPGM", "ENC_SOPP", &[], None)]); + let guarded = translate(&p, &Options { mem_windows: 4 | super::HEAP_WINDOWS, ..Default::default() }).unwrap(); + let flat = translate(&p, &Options { mem_windows: 4 | super::HEAP_WINDOWS | super::HEAP_FLAT, ..Default::default() }).unwrap(); + assert_eq!(flat.hlsl, guarded.hlsl, "HEAP_FLAT distinguishes direct-DXIL cache entries but is ignored by HLSL"); +} + fn memory_windows_above_4_gib(heap: bool) { if !gpu_ready() { return; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9a6f1f6175..e8069f05ac 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -914,12 +914,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; - // the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1` - // (`pso::mem_windows`), as `--precompile` - let runtime_windows = || { - let windows = opts.windows; - if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } - }; + let runtime_windows = || runtime_windows(opts.windows); let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -994,6 +989,11 @@ pub fn run(path: &Path, args: &[String]) -> i32 { print(path, &what, agg, top, json, t0, compile) } +/// The runtime's memory windows, as the offline commands key and translate programs. +fn runtime_windows(windows: u32) -> u32 { + recomp::pso::windows_for(windows) +} + #[cfg(test)] fn parse_record_hash(s: &str) -> Result { crate::cli::parse_hex_u64_str(s) @@ -1095,7 +1095,7 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows: println!( "{written} program(s) written to {} (split wave64: {split}, {} windows{}, {failures} failure(s))", dir.display(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" } ); if written == wanted { 0 } else { @@ -1702,7 +1702,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); @@ -2197,6 +2197,30 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { + /// Offline commands and the runtime must use the same cache identity. Environment switches + /// are process-global (`OnceLock`), so exercise each setting in a fresh test process. + #[test] + fn precompile_windows_are_the_runtimes() { + use crate::gpu::recomp::{pso, HEAP_FLAT, HEAP_WINDOWS}; + const RUN: &str = "XCL_TEST_PRECOMPILE_WINDOWS"; + if let Ok(want) = std::env::var(RUN) { + assert_eq!(super::runtime_windows(4), pso::windows_for(4)); + assert_eq!(super::runtime_windows(4), want.parse::().unwrap()); + return; + } + for (flat, want) in [("1", 4 | HEAP_WINDOWS | HEAP_FLAT), ("0", 4 | HEAP_WINDOWS)] { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "shaders::tests::precompile_windows_are_the_runtimes", "--nocapture"]) + .env(RUN, want.to_string()) + .env("XCL_HEAP_WINDOWS", "1") + .env("XCL_HEAP_FLAT", flat) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "XCL_HEAP_FLAT={flat}: {stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + } + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test]