diff --git a/README.md b/README.md index 321cc03a9e..ce77c714fa 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,8 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups made up of complete native waves can use the per-lane form for branches on whole-wave masks. + With direct DXIL on NVIDIA, `XCL_DXIL_OUTLINE=1` lets compute shaders share a scalar-load function when its + addressing form and width occur at four or more emitted sites. The switch defaults to off. Other adapters keep scalar loads inline. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). ```powershell diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs index cd0b61fd85..5bb1df7b1e 100644 --- a/crates/xcl/src/gpu/adapter.rs +++ b/crates/xcl/src/gpu/adapter.rs @@ -13,6 +13,7 @@ //! (`gpu::recomp::runner`), so the GPU tests can be run on each adapter of a machine in turn. use std::fmt; +use std::sync::OnceLock; use windows::Win32::Graphics::Dxgi::*; @@ -115,6 +116,18 @@ pub(crate) fn select_indices>(names: &[S], sel: &Selector) -> Vec< Vec::new() } +/// The title may fall back to another adapter while opening its D3D12 device. +pub(crate) static TITLE_VENDOR: OnceLock = OnceLock::new(); + +/// Offline shaders and the test runner select the first matching hardware adapter. +pub(crate) fn shader_vendor() -> Option { + static OFFLINE_VENDOR: OnceLock> = OnceLock::new(); + TITLE_VENDOR.get().copied().or_else(|| *OFFLINE_VENDOR.get_or_init(|| { + let factory: IDXGIFactory6 = unsafe { CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) }.ok()?; + candidates(&factory, &Selector::from_env_or("auto")).first().map(|(_, d)| d.VendorId) + })) +} + /// The adapter's name from its description. pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String { let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..e38eb6b485 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -831,3 +831,170 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { } } } + +fn scalar_load_fixture() -> Vec { + prog(&[ + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 4), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 32), ("SBASE", 4), ("OFFSET", 4), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 40), ("SBASE", 4), ("OFFSET", 8), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 44), ("SBASE", 4), ("OFFSET", 12), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 48), ("SBASE", 4), ("OFFSET", 4), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 50), ("SBASE", 4), ("OFFSET", 8), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 52), ("SBASE", 4), ("OFFSET", 12), ("SOFFSET", 125)], None), + ]) +} + +#[test] +fn scalar_load_threshold_counts_emitted_sites_per_shape() { + let threshold = super::lower_mem::MIN_OUTLINE_SITES; + let opts = KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; + for n in [threshold - 1, threshold] { + let mut code = Vec::new(); + for site in 0..n { + for _ in 0..2 { + // The second load of the same address is a reload hit. + code.extend(encode("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), + ("OFFSET", u64::from(site) * 4), ("SOFFSET", 125)], None).unwrap()); + } + } + code.extend(prog(&[("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 36), ("SBASE", 4), ("SOFFSET", 125)], None)])); + let blob = super::kernel::translate_outline_fixture(&code, opts, true).unwrap(); + let ir = super::validate::disassemble(&blob).unwrap(); + assert_eq!(ir.contains("@xcl_scalar_load_2("), n == threshold); + assert!(!ir.contains("@xcl_buffer_load_2(")); + } +} + +#[test] +fn scalar_load_outlining_requires_nvidia() { + assert!(super::kernel::outline_supported(Some(0x10de))); + for vendor in [Some(0x1002), Some(0x8086), Some(0x1414), None] { + assert!(!super::kernel::outline_supported(vendor)); + } +} + +#[test] +fn outlined_scalar_loads_validate() { + for windows in [1, 4, 0x104] { + let opts = KernelOptions { wave64: true, split: true, mem_windows: windows, sampler_base: 0 }; + let blob = super::kernel::translate_outline_fixture(&scalar_load_fixture(), opts, true).unwrap(); + super::validate::validate(&blob).unwrap(); + let ir = super::validate::disassemble(&blob).unwrap(); + for name in ["@xcl_buffer_load_4(", "@xcl_scalar_load_2("] { + let definition = ir.lines().find(|l| l.starts_with("define internal void") && l.contains(name)).expect("wide load helper"); + assert!(definition.contains("[16 x i32]* noalias"), "{definition}"); + } + } +} + +fn outline_fixture_applies(vendor: Option) -> bool { + if vendor.is_none() { + crate::gpu::recomp::runner::skip_test("could not identify the GPU for scalar-load outlining"); + return false; + } + if !super::kernel::outline_supported(vendor) { + use std::io::Write; + let thread = std::thread::current(); + let _ = writeln!(std::io::stderr(), "SKIPPED {}: NVIDIA-only scalar-load fixture", thread.name().unwrap_or("?")); + return false; + } + true +} + +#[test] +fn outlined_scalar_loads_strict_vendor_exclusion() { + // Isolate XCL_REQUIRE_GPU from the other tests running in this process. + const CHILD: &str = "XCL_TEST_OUTLINE_VENDOR_CHILD"; + if std::env::var_os(CHILD).is_some() { + assert!(!outline_fixture_applies(Some(0x1002))); + assert!(outline_fixture_applies(Some(0x10de))); + assert!(std::panic::catch_unwind(|| outline_fixture_applies(None)).is_err()); + return; + } + for mode in ["wave64", "mesh"] { + let test = std::thread::current(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", test.name().unwrap()]) + .env(CHILD, "1").env("XCL_REQUIRE_GPU", mode) + .output().unwrap(); + assert!(output.status.success(), "{mode}: {}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + } +} + +#[test] +fn outlined_scalar_loads_match_inline_at_view_end() { + if !outline_fixture_applies(crate::gpu::adapter::shader_vendor()) { + return; + } + use crate::gpu::recomp::runner::{self, KernelState}; + let (wave32, native64) = match (runner::wave32_supported(), runner::wave64_supported()) { + (Ok(a), Ok(b)) => (a, b), + (Err(e), _) | (_, Err(e)) => return runner::skip_test(&e), + }; + if !wave32 && !native64 { + return runner::skip_test("no wave32 or wave64 GPU"); + } + let memory: Vec = (0..32).map(|i| 0xabc0_0000 + i).collect(); + for (wave64, split) in [(false, false), (true, true), (true, false)] { + if (wave64 && !split && !native64) || ((!wave64 || split) && !wave32) { continue; } + let opts = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let blobs = [false, true].map(|enabled| super::kernel::translate_outline_fixture(&scalar_load_fixture(), opts, enabled).unwrap()); + for (lo, hi) in [(u32::MAX, 0), (0, 0x7f), (1, 0)] { + let mut state = KernelState::default(); + state.sgpr[126..128].copy_from_slice(&[lo, hi]); + state.sgpr[8..12].copy_from_slice(&[16, 0, 10, 0]); + let [a, b] = blobs.each_ref().map(|dxil| runner::run(dxil, &state, &memory).unwrap()); + assert_eq!(a.raw, b.raw); + assert_eq!(&b.sgpr[24..28], &[memory[4], memory[5], memory[6], 0]); + assert_eq!(&b.sgpr[32..36], &[memory[5], memory[6], 0, 0]); + } + } +} + +#[test] +fn outlined_scalar_loads_preserve_distinct_image_descriptors() { + if !outline_fixture_applies(crate::gpu::adapter::shader_vendor()) { + return; + } + use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT; + + if !runner::wave32_supported().unwrap_or(false) { + return runner::skip_test("no wave32 GPU"); + } + + // Keep four different descriptor indices live across calls to the same eight-word helper. + let mut code = Vec::new(); + let mut memory = Vec::new(); + for i in 0..4 { + code.extend(encode("S_LOAD_DWORDX8", "ENC_SMEM", &[("SDATA", 16 + 8 * i), ("SBASE", 4), ("OFFSET", 32 * i), ("SOFFSET", 125)], None).unwrap()); + memory.extend_from_slice(&[2 * i as u32, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]); + } + for i in 0..4 { + code.extend(encode("IMAGE_STORE", "ENC_MIMG", &[("VDATA", 4 + i), ("VADDR", 0), ("SRSRC", 4 + 2 * i), ("DMASK", 1), ("DIM", 1), ("UNORM", 1)], None).unwrap()); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let textures: Vec<_> = (0..4).map(|_| TestTexture { + dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 32, height: 1, depth: 1, + texel_bytes: 4, data: vec![0; 128], uav: true, + }).collect(); + let mut state = KernelState::default(); + for (lane, vgprs) in state.vgpr.iter_mut().enumerate() { + vgprs[0] = lane as u32; + for i in 0..4 { vgprs[4 + i] = 0x12340000 + (i as u32) * 32 + lane as u32; } + } + let opts = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + for outline in [false, true] { + let dxil = super::kernel::translate_outline_fixture(&code, opts, outline).unwrap(); + let result = runner::run_with(&dxil, &state, &memory, &textures, &[]).unwrap(); + assert_eq!(result.textures.len(), textures.len()); + for (i, bytes) in result.textures.iter().enumerate() { + assert_eq!(bytes.len(), 32 * 4); + for (lane, texel) in bytes.chunks_exact(4).enumerate() { + let expected = 0x12340000 + i as u32 * 32 + lane as u32; + assert_eq!(u32::from_le_bytes(texel.try_into().unwrap()), expected, "outline={outline} texture={i} lane={lane}"); + } + } + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..c22dfeee0f 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -148,6 +148,24 @@ pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wav translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables) } +pub(super) fn outline_supported(vendor: Option) -> bool { + vendor == Some(0x10de) // NVIDIA +} + +pub(crate) fn outline_enabled() -> bool { + if !std::env::var("XCL_DXIL_OUTLINE").is_ok_and(|v| v == "1") { + return false; + } + if outline_supported(crate::gpu::adapter::shader_vendor()) { + return true; + } + static WARN: std::sync::Once = std::sync::Once::new(); + WARN.call_once(|| { + crate::xlog_warn!("XCL_DXIL_OUTLINE=1 requires an NVIDIA adapter. Using inline scalar loads."); + }); + false +} + fn translate_entry( code: &[u8], o: KernelOptions, @@ -158,11 +176,12 @@ fn translate_entry( ) -> Result { // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs + let outline = matches!(entry, Entry::Kernel | Entry::Compute(_)) && outline_enabled(); let code = code.to_vec(); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables)) + .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables, outline)) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -186,6 +205,11 @@ fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec ((0..n).map(|k| if coherent { s.raw_uav_coherent(2 + k, 0) } else { s.raw_uav(2 + k, 0) }).collect(), None) } +#[cfg(test)] +pub(super) fn translate_outline_fixture(code: &[u8], o: KernelOptions, outline: bool) -> Result, String> { + translate_on_this_thread(code, o, Entry::Kernel, Some(false), None, 0, outline).map(|k| k.dxil) +} + fn translate_on_this_thread( code: &[u8], o: KernelOptions, @@ -193,6 +217,7 @@ fn translate_on_this_thread( compact: Option, nest: Option, tables: usize, + outline: bool, ) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -336,6 +361,22 @@ fn translate_on_this_thread( // scalar loads the program repeats keep their first values (compute programs and kernels: // the other stages enter their code by edges the CFG does not hold) let reloads = if follow_loads { super::reload::analyze(&cfg) } else { Default::default() }; + if outline && follow_loads { + // Compact lowering emits each representative once and does not substitute reloads. + let mut count_block = |b: usize| { + for &i in &cfg.blocks[b].insts { + if plan.is_none() && reloads.get(b, i).is_some_and(|r| r.available) { continue; } + if let Some((buffer, words)) = super::lower_mem::scalar_load_shape(cfg.insts[i].inst.name) { + lw.scalar_load_sites[buffer as usize][words.ilog2() as usize] += 1; + } + } + }; + if let Some(p) = &plan { + for &r in &p.rep { count_block(p.order[r]); } + } else { + for &b in &cfg.rpo { count_block(b); } + } + } let mut gs_entry: Option = None; if let Some(p) = &plan { match nest { @@ -553,6 +594,7 @@ impl Lw { guard_override: None, mask_override: None, local_masks: false, + scalar_load_sites: [[0; 5]; 2], exchange_error: None, pc: 0, }; diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..b41c428f1c 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -264,6 +264,7 @@ pub struct Lw { /// when it is never read whole. Set by a caller that reads back only each lane's own bit /// (the per-lane form's bridge), so no exchange meets the other half. pub local_masks: bool, + pub scalar_load_sites: [[u32; 5]; 2], } impl Lw { diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..e9ac60e448 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -151,6 +151,25 @@ pub struct FmtComp1 { pub dflt: Value, } +pub(super) const MIN_OUTLINE_SITES: u32 = 4; + +pub(super) fn scalar_load_shape(name: &str) -> Option<(bool, u32)> { + let (buffer, width) = if let Some(width) = name.strip_prefix("S_BUFFER_LOAD_") { + (true, width) + } else { + (false, name.strip_prefix("S_LOAD_")?) + }; + let count = match width { + "DWORD" => 1, + "DWORDX2" => 2, + "DWORDX4" => 4, + "DWORDX8" => 8, + "DWORDX16" => 16, + _ => return None, + }; + Some((buffer, count)) +} + impl Lw { /// Runs `f` on the active memory window (`mem`, `mem1`.. at u2.., or descriptor heap /// when `self.heap_mem` is set via `XCL_HEAP_WINDOWS`), returning `out_tys.len()` values @@ -1141,41 +1160,13 @@ impl Lw { self.write64(&Dst::S(sdata), z, z); return Ok(()); } - let count = match name.trim_start_matches("s_buffer_load_").trim_start_matches("s_load_") { - "dword" => 1, - "dwordx2" => 2, - "dwordx4" => 4, - "dwordx8" => 8, - "dwordx16" => 16, - _ => return err(d, "SMEM"), - }; + let Some((buffer, count)) = scalar_load_shape(d.inst.name) else { return err(d, "SMEM") }; let sdata = Self::field(d, "SDATA"); let sbase = Self::field(d, "SBASE"); let imm = Self::fv(d, "OFFSET") as u32; let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); let soff = if soff == 125 { self.c(0) } else { self.code32(soff, None, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))? }; - let mut vals = if name.starts_with("s_buffer_load") { - let (d0, d1, d2) = (self.sreg(sbase), self.sreg(sbase + 1), self.sreg(sbase + 2)); - let k = self.c(imm); - let off = self.add(k, soff); - self.buffer_window(d0, d1, &[Ea::U(k), Ea::U(soff)], false); - let st = self.lshrc(d1, 16); - let st = self.andc(st, 0x3FFF); - let sz = self.cmpc(Pred::Eq, st, 0); - let lim = self.mul(d2, st); - let lim = self.sel(sz, d2, lim); - let base = self.add(d0, off); - let base_aligned = self.andc(base, !3); - let raw = self.mem_ld_chunks(base_aligned, count); - let z = self.c(0); - (0..count) - .map(|i| { - let o = self.addc(off, 4 * i); - let ok = self.cmp(Pred::ULt, o, lim); - self.sel(ok, raw[i as usize], z) - }) - .collect::>() - } else { + if !buffer { // a repeat of a load nothing has changed since: its values (`reload`) let slot = self.reload.map(|r| super::reload::VAR_RELOAD + 16 * r.slot); if let (Some(var), Some(true)) = (slot, self.reload.map(|r| r.available)) { @@ -1185,15 +1176,16 @@ impl Lw { } return Ok(()); } - let imm = ((imm << 11) as i32 >> 11) as u32; - let b = self.sreg(sbase); - let hi = self.sreg(sbase + 1); - let k = self.c(imm); - self.window_at(hi, b, &[Ea::S(k), Ea::U(soff)], false); - let a = self.add(b, k); - let a = self.add(a, soff); - let base_aligned = self.andc(a, !3); - self.mem_ld_chunks(base_aligned, count) + } + let lo = self.sreg(sbase); + let hi = self.sreg(sbase + 1); + let size = if buffer { self.sreg(sbase + 2) } else { self.c(0) }; + let imm = self.c(if buffer { imm } else { ((imm << 11) as i32 >> 11) as u32 }); + let args = [lo, hi, size, imm, soff]; + let mut vals = if self.scalar_load_sites[buffer as usize][count.ilog2() as usize] >= MIN_OUTLINE_SITES { + self.call_scalar_load(count, buffer, args) + } else { + self.scalar_load(count, buffer, args) }; let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); if self.split && coherent { @@ -1216,6 +1208,93 @@ impl Lw { Ok(()) } + fn scalar_load(&mut self, count: u32, buffer: bool, [d0, d1, d2, k, soff]: [Value; 5]) -> Vec { + if buffer { + let off = self.add(k, soff); + self.buffer_window(d0, d1, &[Ea::U(k), Ea::U(soff)], false); + let st = self.lshrc(d1, 16); + let st = self.andc(st, 0x3FFF); + let sz = self.cmpc(Pred::Eq, st, 0); + let lim = self.mul(d2, st); + let lim = self.sel(sz, d2, lim); + let base = self.add(d0, off); + let base_aligned = self.andc(base, !3); + let raw = self.mem_ld_chunks(base_aligned, count); + let z = self.c(0); + (0..count) + .map(|i| { + let o = self.addc(off, 4 * i); + let ok = self.cmp(Pred::ULt, o, lim); + self.sel(ok, raw[i as usize], z) + }) + .collect::>() + } else { + self.window_at(d1, d0, &[Ea::S(k), Ea::U(soff)], false); + let a = self.add(d0, k); + let a = self.add(a, soff); + let base_aligned = self.andc(a, !3); + self.mem_ld_chunks(base_aligned, count) + } + } + + fn call_scalar_load(&mut self, count: u32, buffer: bool, inputs: [Value; 5]) -> Vec { + use super::module::{FnAttrs, Block}; + use super::ssa::Ssa; + + let name = format!("xcl_{}_load_{count}", if buffer { "buffer" } else { "scalar" }); + let uma = if self.windowed() { self.uma_base() } else { self.c(0) }; + let slot = self.s.m.return_slot(); + let args = [inputs[0], inputs[1], inputs[2], inputs[3], inputs[4], uma, slot]; + let f = if let Some(f) = self.s.m.function(&name) { + f + } else { + let word = self.s.m.i32(); + let params: Vec<_> = args.iter().map(|&a| self.s.m.type_of(a)).collect(); + let void = self.s.m.void(); + let signature = self.s.m.func_ty(void, ¶ms); + let f = self.s.m.declare(&name, signature, FnAttrs::NoInlineScalarLoadOut); + let body = self.s.m.declarations(); + let caller = std::mem::replace(&mut self.s.m, body); + let ssa = std::mem::replace(&mut self.ssa, Ssa::new(word)); + let old_base = self.uma_base_val.replace(Value::Param(word, 5)); + let old_mems = self.mems.clone(); + // Root-bound handles belong to a function. Re-create the same bindings locally. + for mem in &mut self.mems { + if let Some(index) = mem.binding { + let bind = self.s.bindings[index].clone(); + let h = self.s.handle_from_binding(bind.class, bind.lower, bind.lower, bind.space, bind.lower); + mem.handle = self.s.annotate(h, bind.kind | 0x1000 | if bind.coherent { 0x4000 } else { 0 }, 0); + } + } + self.ssa.expect_preds(&mut self.s, Block(0), 0, &mut |s, v| self.init.load(s, v)); + let results = self.scalar_load(count, buffer, std::array::from_fn(|i| Value::Param(word, i as u32))); + // Consecutive calls may feed distinct live descriptor indices. Passing every word + // through caller storage avoids a native driver reusing the later call's scalar return. + let out = Value::Param(params[6], 6); + let z = self.c(0); + for (i, v) in results.into_iter().enumerate() { + let k = self.c(i as u32); + let at = self.s.m.gep(out, &[z, k]); + self.s.m.store(at, v, 4); + } + self.s.m.ret(); + self.s.m.optimize(); + self.mems = old_mems; + self.uma_base_val = old_base; + self.ssa = ssa; + let body = std::mem::replace(&mut self.s.m, caller); + self.s.m.finish_helper(f, body); + f + }; + self.s.m.call(f, &args); + let z = self.c(0); + (0..count).map(|i| { + let k = self.c(i); + let at = self.s.m.gep(slot, &[z, k]); + self.s.m.load(at, 4) + }).collect() + } + // ------------------------------------------------------------ MUBUF / MTBUF pub fn mubuf(&mut self, d: &Decoded, name: &str) -> LResult<()> { diff --git a/crates/xcl/src/gpu/dxil/lower_window.rs b/crates/xcl/src/gpu/dxil/lower_window.rs index 1f41e5817d..9db239d635 100644 --- a/crates/xcl/src/gpu/dxil/lower_window.rs +++ b/crates/xcl/src/gpu/dxil/lower_window.rs @@ -28,7 +28,7 @@ impl Lw { /// The high dword of the UMA base (`IO_UMA_BASE_HI` of the io buffer, `xcl_uma_base`), /// hoisted to the entry block so multi-window shaders load it once rather than on every /// memory operation. - fn uma_base(&mut self) -> Value { + pub(super) fn uma_base(&mut self) -> Value { if let Some(v) = self.uma_base_val { return v; } diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..64009f367e 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -43,6 +43,7 @@ enum TypeDef { /// A value: global variable, function, module constant or instruction result. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Value { + Param(Ty, u32), Global(u32), Func(u32), Const(u32), @@ -80,12 +81,15 @@ pub enum FnAttrs { NoUnwind, /// `noduplicate nounwind` (barriers) NoDuplicate, + /// A scalar load takes six words and a private, non-aliasing output pointer. + NoInlineScalarLoadOut, } impl FnAttrs { /// Index into the PARAMATTR table (+1; 0 = none). fn index(self) -> u64 { match self { + FnAttrs::NoInlineScalarLoadOut => 5, FnAttrs::None => 0, FnAttrs::ReadNone => 1, FnAttrs::ReadOnly => 2, @@ -248,6 +252,8 @@ pub struct Module { type_ids: HashMap, consts: Vec, const_ids: HashMap, + return_slot: Option, + helpers: std::collections::BTreeMap>, funcs: Vec, func_ids: HashMap, globals: Vec, @@ -276,6 +282,8 @@ impl Module { type_ids: HashMap::new(), consts: Vec::new(), const_ids: HashMap::new(), + return_slot: None, + helpers: Default::default(), funcs: Vec::new(), func_ids: HashMap::new(), globals: Vec::new(), @@ -509,6 +517,7 @@ impl Module { Value::Const(c) => match &self.consts[c as usize] { ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, }, + Value::Param(ty, _) => ty, Value::Inst(i) => self.insts[i as usize].ty, } } @@ -623,6 +632,42 @@ impl Module { let t = self.struct_elem(at, idx); self.push(Op::Extract(agg, idx), t) } + + /// Calls consume and read their scratch in one basic block. Every piece may + /// therefore have its own entry-block allocation for SMEM results. + pub fn return_slot(&mut self) -> Value { + if let Some(slot) = self.return_slot { return slot; } + let word = self.i32(); + let words = self.array(16, word); + let current = self.current_block(); + self.set_block(Block(0)); + let old = self.set_insert_before_term(true); + let slot = self.alloca(words, 4); + self.set_insert_before_term(old); + self.set_block(current); + self.return_slot = Some(slot); + slot + } + + pub fn function(&self, name: &str) -> Option { + self.func_ids.get(name).copied() + } + + /// A helper owns its local instructions. Its symbol indices start with the caller's + /// tables and those tables grow only while the caller is suspended. + pub fn finish_helper(&mut self, f: u32, mut body: Module) { + if let Some(err) = body.error() { self.fail(err); } + self.types.clone_from(&body.types); + self.type_ids.clone_from(&body.type_ids); + self.consts.clone_from(&body.consts); + self.const_ids.clone_from(&body.const_ids); + self.funcs.clone_from(&body.funcs); + self.func_ids.clone_from(&body.func_ids); + self.globals.clone_from(&body.globals); + self.helpers = std::mem::take(&mut body.helpers); + self.helpers.insert(f, std::rc::Rc::new(body)); + } + pub fn call(&mut self, f: u32, args: &[Value]) -> Value { let ret = match &self.types[self.funcs[f as usize].ty.0 as usize] { TypeDef::Func(r, p) => { @@ -838,15 +883,11 @@ impl Module { Value::Func(f) => fused[f as usize] = true, _ => {} }; - for &b in &order { - for &i in &self.blocks[b] { - let op = &self.insts[i as usize].op; - if let Op::Call(f, _) = op { - mark(Value::Func(*f)); - } - op.for_each_operand(&mut mark); - } - } + self.any_emitted_inst(|_, op, _| { + if let Op::Call(f, _) = op { mark(Value::Func(*f)); } + op.for_each_operand(&mut mark); + false + }); for c in &self.consts { if let ConstDef::Aggregate(_, e) = c { e.iter().copied().for_each(&mut mark); @@ -895,6 +936,7 @@ impl Module { } let abs = |v: Value| -> u64 { match v { + Value::Param(..) => unreachable!("parameter in entry"), Value::Global(g) => gmap[g as usize].expect("use of a dropped global"), Value::Func(f) => n_globals + fmap[f as usize].expect("use of a dropped function"), Value::Const(c) => const_base + c as u64, @@ -920,11 +962,20 @@ impl Module { w.record(PARAMATTR_GRP_CODE_ENTRY, &[2, FN, 0, ATTR_NOUNWIND, 0, ATTR_READONLY]); w.record(PARAMATTR_GRP_CODE_ENTRY, &[3, FN, 0, ATTR_NOUNWIND]); w.record(PARAMATTR_GRP_CODE_ENTRY, &[4, FN, 0, ATTR_NODUPLICATE, 0, ATTR_NOUNWIND]); + let scalar_out = self.funcs.iter().zip(&fused).any(|(f, used)| *used && f.attrs == FnAttrs::NoInlineScalarLoadOut); + if scalar_out { + w.record(PARAMATTR_GRP_CODE_ENTRY, &[5, FN, 0, ATTR_NOINLINE, 0, ATTR_NOUNWIND]); + // LLVM attribute index 0 is the return value, 1 is the first parameter. + w.record(PARAMATTR_GRP_CODE_ENTRY, &[6, 7, 0, ATTR_NOALIAS]); + } w.end_block(); w.enter_block(BLOCK_PARAMATTR); for g in 1..=4 { w.record(PARAMATTR_CODE_ENTRY, &[g]); } + if scalar_out { + w.record(PARAMATTR_CODE_ENTRY, &[6, 5]); + } w.end_block(); self.write_types(&mut w); @@ -942,12 +993,13 @@ impl Module { &[g.ty.0 as u64, ((g.addrspace as u64) << 2) | 2 | g.constant as u64, init, linkage, align, 0, 0, 0, 0, 0, 0, 0], ); } - for f in self.funcs.iter().enumerate().filter(|(i, _)| fused[*i]).map(|x| x.1) { + for (idx, f) in self.funcs.iter().enumerate().filter(|(i, _)| fused[*i]) { + let helper = self.helpers.contains_key(&(idx as u32)); // [type, cc, isproto, linkage, paramattr, align, section, visibility, // gc, unnamed_addr, prologue, dllstorage, comdat, prefix, personality] w.record( MODULE_CODE_FUNCTION, - &[f.ty.0 as u64, 0, (!f.defined) as u64, LINKAGE_EXTERNAL, f.attrs.index(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + &[f.ty.0 as u64, 0, (!(f.defined || helper)) as u64, if helper { LINKAGE_INTERNAL } else { LINKAGE_EXTERNAL }, f.attrs.index(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ); } @@ -1028,6 +1080,35 @@ impl Module { } w.end_block(); + for (&f, helper) in &self.helpers { + if !fused[f as usize] { continue; } + let TypeDef::Func(_, params) = &self.types[self.funcs[f as usize].ty.0 as usize] else { unreachable!() }; + let (blocks, positions) = helper.block_layout(); + let first = inst_base + params.len() as u64; + let mut next = first; + let mut ids = vec![0; helper.insts.len()]; + for &block in &blocks { + for &id in &helper.blocks[block] { + ids[id as usize] = next; + if !helper.is_void(helper.insts[id as usize].ty) { next += 1; } + } + } + let local_id = |v| match v { + Value::Param(_, i) => inst_base + u64::from(i), + Value::Inst(i) => ids[i as usize], + _ => abs(v), + }; + w.enter_block(BLOCK_FUNCTION); + w.record(FUNC_CODE_DECLAREBLOCKS, &[blocks.len() as u64]); + for block in blocks { + for &id in &helper.blocks[block] { + helper.write_inst(&mut w, id as usize, ids[id as usize], &local_id, &positions, &mut operands); + } + } + if let Some(err) = helper.error() { self.fail(err); } + w.end_block(); + } + w.end_block(); // module w.finish() } @@ -1276,6 +1357,7 @@ impl Module { Value::Const(c) => match &self.consts[c as usize] { ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, }, + Value::Param(ty, _) => ty, Value::Inst(i) => self.insts[i as usize].ty, } } @@ -1299,7 +1381,9 @@ const MODULE_CODE_FUNCTION: u32 = 8; const PARAMATTR_CODE_ENTRY: u32 = 2; const PARAMATTR_GRP_CODE_ENTRY: u32 = 3; +const ATTR_NOALIAS: u64 = 9; const ATTR_NODUPLICATE: u64 = 12; +const ATTR_NOINLINE: u64 = 14; const ATTR_NOUNWIND: u64 = 18; const ATTR_READNONE: u64 = 20; const ATTR_READONLY: u64 = 21; @@ -1404,40 +1488,54 @@ impl Module { Op::Ret | Op::Unreachable => InstInfo::Term(None, Vec::new()), } } - /// Whether an instruction of the entry function produces or consumes a - /// value of type `t` (the shader-flag rules key off instruction types). /// The 64-bit integer and double types, if already interned (lookup /// without adding them to the type table). pub fn existing_i64_f64(&self) -> (Option, Option) { (self.type_ids.get(&TypeDef::Int(64)).copied(), self.type_ids.get(&TypeDef::Double).copied()) } - /// Whether the entry uses a D3D11.1 double extension through plain - /// instructions: double `fdiv`, or conversions between double and - /// integers (DXC's shader-flag rules; `Fma` is flagged by its helper). + /// Visit instructions in reachable blocks, following calls into emitted helpers. + fn any_emitted_inst(&self, mut test: impl FnMut(&Module, &Op, Ty) -> bool) -> bool { + let mut pending = vec![self]; + let mut seen = std::collections::BTreeSet::new(); + while let Some(body) = pending.pop() { + for block in body.block_layout().0 { + for &i in &body.blocks[block] { + let d = &body.insts[i as usize]; + if test(body, &d.op, d.ty) { return true; } + if let Op::Call(f, _) = &d.op { + if let Some(helper) = self.helpers.get(f) { + if seen.insert(*f) { pending.push(helper.as_ref()); } + } + } + } + } + } + false + } + + pub fn uses_fmad(&self) -> bool { + self.any_emitted_inst(|m, op, _| matches!(op, Op::Call(f, args) + if m.funcs[*f as usize].name.starts_with("dx.op.tertiary.") + && args.first().and_then(|&v| m.const_u64(v)) == Some(46))) + } + + /// D3D11.1 double extensions include double division and integer conversions. pub fn uses_double_extensions(&self) -> bool { - let Some(f64) = self.type_ids.get(&TypeDef::Double).copied() else { return false }; - self.insts.iter().any(|d| match &d.op { - Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, - Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, + let Some(&f64) = self.type_ids.get(&TypeDef::Double) else { return false }; + self.any_emitted_inst(|m, op, ty| match op { + Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => ty == f64, + Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => m.value_ty(*v) == f64, Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, _ => false, }) } + pub fn insts_use_type(&self, t: Ty) -> bool { - self.blocks.iter().flatten().any(|&i| { - let d = &self.insts[i as usize]; - if d.ty == t { - return true; - } - let ops: Vec = match self.inst_info(i) { - InstInfo::Call(_, a) => a.to_vec(), - InstInfo::Phi(l) => l.iter().map(|p| p.0).collect(), - InstInfo::Load(p) => vec![p], - InstInfo::Store(p, v) => vec![p, v], - InstInfo::Other(v) => v, - InstInfo::Term(c, _) => c.into_iter().collect(), - }; - ops.into_iter().any(|v| self.value_ty(v) == t) + self.any_emitted_inst(|m, op, ty| { + if ty == t { return true; } + let mut used = false; + op.for_each_operand(|v| used |= m.value_ty(v) == t); + used }) } /// True if any surviving `dx.op.annotateHandle` call carries the `IsROV` flag (`0x2000`). @@ -1542,6 +1640,51 @@ impl Module { mod tests { use super::*; + #[test] + fn feature_scans_follow_only_reachable_helper_code() { + use crate::gpu::dxil::{container::Stage, shader::{Feature, Shader}, validate}; + let mut shader = Shader::new(Stage::Compute, (6, 6)); + shader.require(Feature::DisableMathRefactoring); + let m = &mut shader.m; + let (word, wide, double, float) = (m.i32(), m.i64(), m.f64(), m.f32()); + let void = m.void(); + let sig = m.func_ty(void, &[word]); + let outer = m.declare("outer", sig, FnAttrs::NoUnwind); + let mut outer_body = m.declarations(); + let inner = outer_body.declare("inner", sig, FnAttrs::NoUnwind); + let mut body = outer_body.declarations(); + let p = Value::Param(word, 0); + let w = body.cast(CastOp::ZExt, p, wide); + let d = body.cast(CastOp::UIToFP, w, double); + let v = body.cast(CastOp::FPTrunc, d, float); + let fm_ty = body.func_ty(float, &[word, float, float, float]); + let fm = body.declare("dx.op.tertiary.f32", fm_ty, FnAttrs::ReadNone); + let opcode = body.i32c(46); + let mad = body.call(fm, &[opcode, v, v, v]); + let result = body.bitcast(mad, word); + let shared = body.global("helper_word", word, 3, None, false, 4); + body.store(shared, result, 4); + body.ret(); + outer_body.finish_helper(inner, body); + outer_body.call(inner, &[p]); + outer_body.ret(); + m.finish_helper(outer, outer_body); + let dead = m.new_block(); + m.set_block(dead); + let arg = m.i32c(1); + m.call(outer, &[arg]); + m.ret(); + m.set_block(m.entry_block()); + assert!(!m.insts_use_type(wide) && !m.uses_double_extensions() && !m.uses_fmad()); + m.call(outer, &[arg]); + m.ret(); + assert!(m.insts_use_type(wide) && m.insts_use_type(double)); + assert!(m.uses_double_extensions() && m.uses_fmad()); + let blob = shader.try_finish([1, 1, 1], None).unwrap(); + validate::validate(&blob).unwrap(); + } + + #[test] fn sign_extension_does_not_intern_unrelated_integer_types() { let mut wide = Module::new(); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 7a88b9ae11..3b8372004e 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -112,6 +112,8 @@ impl Shader { for &i in block { if b == 0 && prefix.contains(&i) { continue; } match &self.m.insts[i as usize].op { + Op::Alloca(..) if self.m.return_slot == Some(Value::Inst(i)) => {} + Op::Load(ptr, _) if self.m.is_return_pointer(*ptr) => {} Op::Alloca(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => return None, Op::Store(..) if split_tid.is_some() && exchange <= 1 => exchange = 1, Op::Load(p, _) if self.m.global_root(*p).is_some_and(|g| self.m.globals[g].constant) => {} @@ -158,6 +160,12 @@ impl Shader { let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); let slab = Slab::new(&mut dst); + for &block in &plan.blocks[stage] { + for &id in &src.blocks[block.0 as usize] { + let v = Value::Inst(id); + if src.is_return_pointer(v) { src.rebuild_static(v, &mut dst.m, &mut values)?; } + } + } for &id in prefix { let def = &src.insts[id as usize]; let mut op = def.op.clone(); @@ -214,7 +222,7 @@ impl Shader { for &block in &plan.blocks[stage] { dst.m.set_block(local[&block]); for &i in &src.blocks[block.0 as usize] { - if block == Block(0) && prefix.contains(&i) { continue; } + if src.is_return_pointer(Value::Inst(i)) || (block == Block(0) && prefix.contains(&i)) { continue; } let old = &src.insts[i as usize]; if matches!(old.op, Op::Ret) && stage + 1 < plan.blocks.len() { let zero = dst.m.i32c(0); @@ -284,19 +292,22 @@ impl Shader { // typed UAV loads (`texture_load` without a mip): the whole program's flag stays only on // the pieces that have one, the validator wants flags to match usage let uav_load = |args: &[Value], m: &Module| args.get(2).is_some_and(|&mip| matches!(mip, Value::Const(c) if matches!(m.consts[c as usize], super::ConstDef::Undef(_)))); - if !self.m.blocks.iter().flatten().any(|&i| matches!(&self.m.insts[i as usize].op, - Op::Call(f, args) if self.m.funcs[*f as usize].name.starts_with("dx.op.textureLoad") && uav_load(args, &self.m))) { - self.features.remove(&Feature::TypedUavLoadAdditionalFormats); - } - for def in &self.m.insts { - if let Op::Call(f, args) = &def.op { - if self.m.funcs[*f as usize].name == "dx.op.createHandleFromHeap" { - self.features.insert(if self.m.const_u64(args[2]) == Some(0) { + let mut typed_load = false; + self.m.any_emitted_inst(|m, op, _| { + if let Op::Call(f, args) = op { + let name = &m.funcs[*f as usize].name; + if name.starts_with("dx.op.textureLoad") && uav_load(args, m) { + typed_load = true; + } + if name == "dx.op.createHandleFromHeap" { + self.features.insert(if m.const_u64(args[2]) == Some(0) { Feature::ResourceHeapIndexing } else { Feature::SamplerHeapIndexing }); } } - } + false + }); + if !typed_load { self.features.remove(&Feature::TypedUavLoadAdditionalFormats); } } } @@ -502,7 +513,16 @@ impl Module { None } + fn is_return_pointer(&self, v: Value) -> bool { + if self.return_slot.is_none() { return false; } + if Some(v) == self.return_slot { return true; } + let Value::Inst(i) = v else { return false }; + matches!(&self.insts[i as usize].op, Op::Gep(base, indices) + if Some(*base) == self.return_slot && indices.iter().all(|i| matches!(i, Value::Const(_)))) + } + fn transport_words(&self, v: Value) -> Option { + if self.is_return_pointer(v) { return Some(0); } let def = &self.insts[inst(v)?]; match &self.types[def.ty.0 as usize] { TypeDef::Int(1..=32) | TypeDef::Float => Some(1), @@ -526,6 +546,15 @@ impl Module { fn rebuild_static(&self, v: Value, dst: &mut Module, map: &mut HashMap) -> Option { let Value::Inst(id) = v else { return Some(v) }; if let Some(&old) = map.get(&v) { return Some(old); } + if self.is_return_pointer(v) { + let slot = dst.return_slot(); + let value = match &self.insts[id as usize].op { + Op::Gep(_, indices) => dst.gep(slot, indices), + _ => slot, + }; + map.insert(v, value); + return Some(value); + } let Op::Call(f, args) = &self.insts[id as usize].op else { return None }; let args: Vec<_> = args.iter().map(|&a| self.rebuild_static(a, dst, map)).collect::>()?; let new = dst.call(*f, &args); @@ -586,6 +615,7 @@ impl Module { type_ids: self.type_ids.clone(), consts: self.consts.clone(), const_ids: self.const_ids.clone(), + helpers: self.helpers.clone(), funcs: self.funcs.clone(), func_ids: self.func_ids.clone(), globals: self.globals.clone(), diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index a0a970925d..ce58efa8be 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -601,7 +601,7 @@ impl Shader { /// `dx.op.tertiary.*` `FMad` (op 46), since DXIL validation forbids `FMad` /// together with `DisableMathRefactoring`. pub(super) fn feature_flags(&self) -> (u64, u64) { - let drop_no_refactor = self.features.contains(&Feature::DisableMathRefactoring) && self.uses_fmad(); + let drop_no_refactor = self.features.contains(&Feature::DisableMathRefactoring) && self.m.uses_fmad(); let mut flags = 0u64; let mut sfi0 = 0u64; for &f in &self.features { @@ -613,23 +613,6 @@ impl Shader { } (flags, sfi0) } - - /// True if any surviving instruction calls `dx.op.tertiary.*` with opcode - /// `46` (`Tertiary::FMad`). - fn uses_fmad(&self) -> bool { - use super::module::{Block, InstInfo}; - for b in 0..self.m.block_count() { - for &inst in self.m.block_insts(Block(b as u32)) { - let InstInfo::Call(name, args) = self.m.inst_info(inst) else { continue }; - if name.starts_with("dx.op.tertiary.") - && args.first().and_then(|&v| self.m.const_u64(v)) == Some(46) - { - return true; - } - } - } - false - } } /// The function attributes DXC gives each `dx.op` declaration (DXC 1.9 diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b8b0cde0f1..120b5ba341 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -154,7 +154,7 @@ fn shader_cache() -> &'static Mutex { /// 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); - if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { + if !cache_allowed(stage, translation_override_active) { return compile_one().map(|(c, _)| c); } let key = ShaderKey { @@ -904,10 +904,18 @@ fn cached_shader( Ok(shader) } +fn translation_override_active(name: &str) -> bool { + match name { + "XCL_DXIL_OUTLINE" => crate::gpu::dxil::kernel::outline_enabled(), + _ => std::env::var_os(name).is_some(), + } +} + fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] .iter() .any(|name| present(name)) + && (stage != Stage::Compute || !present("XCL_DXIL_OUTLINE")) && (stage != Stage::Pixel || ![ "XCL_DEBUG_MAGENTA", @@ -1145,7 +1153,7 @@ fn console_mesh_with( let compile_one = || compile(code, ms, wave64); // Cache the mesh compute pass in RAM (`ShaderCache` + in-flight coalescing) and on disk // (`translated/v2`, namespaced by backend) across all `(MS, PS)` pipelines that share it. - let cs = if cache_allowed(Stage::Mesh, |name| std::env::var_os(name).is_some()) { + let cs = if cache_allowed(Stage::Mesh, translation_override_active) { let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), stage: Stage::Mesh, @@ -2002,6 +2010,10 @@ mod shader_cache_tests { assert!(!cache_allowed(Stage::Vertex, |v| v == name)); assert!(!cache_allowed(Stage::Pixel, |v| v == name)); } + assert!(!cache_allowed(Stage::Compute, |v| v == "XCL_DXIL_OUTLINE")); + for stage in [Stage::Vertex, Stage::Pixel, Stage::Mesh] { + assert!(cache_allowed(stage, |v| v == "XCL_DXIL_OUTLINE")); + } for name in [ "XCL_DEBUG_MAGENTA", "XCL_DEBUG_LOD0", diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..f2ddbd90d3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -513,6 +513,7 @@ pub fn init() -> Result { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?; let mut device: Option = None; let mut name = String::new(); + let mut vendor_id = 0; // WARP fallback let sel = crate::gpu::adapter::Selector::from_env_or(&cfg.d3d12_adapter); if sel != crate::gpu::adapter::Selector::Warp { let mut list = crate::gpu::adapter::candidates(&factory, &sel); @@ -523,6 +524,7 @@ pub fn init() -> Result { for (adapter, desc) in list { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { device = Some(dev); + vendor_id = desc.VendorId; name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; } @@ -545,6 +547,7 @@ pub fn init() -> Result { let _ = q.RegisterMessageCallback(Some(debug_message), D3D12_MESSAGE_CALLBACK_FLAG_NONE, std::ptr::null_mut(), &mut cookie); } } + let _ = crate::gpu::adapter::TITLE_VENDOR.set(vendor_id); open_uma(&device); super::device_x::probe_dynamic_depth_bias(&device); let raw = device.into_raw(); // one reference kept for the process lifetime diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 5ffa519a96..6343194c73 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -188,7 +188,7 @@ fn offline_compute_pipeline_is_reused_by_a_second_process() { let run = |enabled: bool| { let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input) .args(["--precompile", "--pipelines"]).env("XCL_DXIL_CACHE", &cache) - .env("TMP", &dir).env("TEMP", &dir).env("XCL_DXIL_DUMP", "all") + .env("TMP", &dir).env("TEMP", &dir).env("XCL_DXIL_DUMP", "all").env_remove("XCL_DXIL_OUTLINE") .env("XCL_PSO_DISK_CACHE", if enabled { "1" } else { "0" }).output().unwrap(); let text = String::from_utf8_lossy(&out.stdout).into_owned(); assert!(out.status.success() && text.contains("pipelines made on the GPU 1, refused 0"), "{text}\n{}", String::from_utf8_lossy(&out.stderr));