Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions crates/xcl/src/gpu/dxil/core_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
24 changes: 23 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -184,7 +205,7 @@ fn translate_entry(
fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec<RawUav>, Option<bool>) {
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));
Expand Down Expand Up @@ -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(),
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool>,
/// Heap windows read without a branch (`recomp::HEAP_FLAT`; compute programs only).
pub heap_flat: bool,
pub res: Option<RawUav>,
/// the buffer format table (`FMT_INFO`), created on first use
pub fmt_table: Option<Value>,
Expand Down
18 changes: 18 additions & 0 deletions crates/xcl/src/gpu/dxil/lower_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,24 @@ impl Lw {
n: usize,
f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec<Value>,
) -> Vec<Value> {
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)
Expand Down
7 changes: 6 additions & 1 deletion crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -1521,7 +1526,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result<Translation, String> {
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
Expand Down
16 changes: 14 additions & 2 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,14 @@ pub fn fspx(blob: &[u8]) -> Option<Fspx<'_>> {
/// 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
}
Expand Down Expand Up @@ -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<bool> = 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);

Expand Down
8 changes: 8 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
40 changes: 32 additions & 8 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<u64, String> {
crate::cli::parse_hex_u64_str(s)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -1702,7 +1702,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, 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 { "" }
);
Expand Down Expand Up @@ -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::<u32>().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]
Expand Down