From 0ab2fb4d03e7f91f9dae314633685a8882b57d27 Mon Sep 17 00:00:00 2001 From: Foniass <107039406+Foniass@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:02:37 +0100 Subject: [PATCH] xcl run: XCL_RT_LEAVE_OUT leaves out a title's ray-tracing programs A title's ray-tracing programs that start rays or shade their hits (on a retail title about 1,000 programs of ~1 MB of DXIL each, the largest of its cold driver compiles) do nothing while the title has built no acceleration structure: every ray misses. On amd-dev's runs, allowing them pushed the title's commit at world entry from about 10 to 21 GB. XCL_RT_LEAVE_OUT=[,...] (off by default) leaves out the compute programs whose shader container holds one of the fragments: the title's pipeline gets the dummy program an untranslatable console shader gets, so its dispatches are skipped, and the shader preparation and `xcl shaders --precompile` pass them over (and say how many). The fragments name the programs (names in the container's debug data, found with `xcl rpf --find`); XCL's source names no title's programs. So that leaving them out stays harmless, XCL watches the acceleration structures the title's views name and warns once when one gets a root node. Ported from amd-dev (raylitebull's WIP 6fa964de, gpu/rt_leave_out.rs as on amd-dev, and its hooks), itself ported from Vice-Tay (GPL-3.0-or-later, commit 1f69d67, `left_out` in crates/victory-gpu/src/pipeline/make.rs); THIRD_PARTY.md names it. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 + THIRD_PARTY.md | 1 + crates/xcl/src/gpu/mod.rs | 1 + crates/xcl/src/gpu/rt_leave_out.rs | 181 +++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/present.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 19 ++- crates/xcl/src/shaders.rs | 8 ++ 7 files changed, 215 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/gpu/rt_leave_out.rs diff --git a/README.md b/README.md index d55abf4300..9df7459b90 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,11 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o a shader the direct translator cannot handle yet goes through HLSL and DXC instead. `XCL_DIRECT_DXIL=1` keeps vertex and pixel shaders on the HLSL path, `XCL_DIRECT_DXIL=0` every shader (except very large compute programs, `XCL_DIRECT_HUGE`). +- **Ray-tracing programs left out:** `XCL_RT_LEAVE_OUT=[,…]` (off by default) leaves + out the compute programs whose shader container holds one of the fragments (names from its debug + data, `xcl rpf --find`): their dispatches are skipped and the shader preparation passes them + over. Meant for a title's ray-tracing programs while it has built no acceleration structure; XCL + warns once when one of the title's structures gets a root node. - **DXC:** 1.8 or newer is recommended, from the [DirectXShaderCompiler releases](https://github.com/microsoft/DirectXShaderCompiler/releases): unpack one and point `XCL_DXC_DIR` at its `bin\x64`. A Windows SDK may hold an older one (the same `10.0.26100.0` diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index db38e8a443..c0f6c77744 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -11,6 +11,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | +| [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs` (the programs left out, after `left_out` in `crates/victory-gpu/src/pipeline/make.rs`, commit 1f69d67) | port, 2026-11-27 | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index 0264fdb555..13c6d68bce 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod fence; pub mod pack; pub mod rdna2; pub mod recomp; +pub mod rt_leave_out; mod rdna2_spec; mod rdna2_xbox; pub mod shader; diff --git a/crates/xcl/src/gpu/rt_leave_out.rs b/crates/xcl/src/gpu/rt_leave_out.rs new file mode 100644 index 0000000000..174248a4b9 --- /dev/null +++ b/crates/xcl/src/gpu/rt_leave_out.rs @@ -0,0 +1,181 @@ +//! `XCL_RT_LEAVE_OUT=[,…]` (off by default): compute programs whose shader +//! container holds one of the fragments are left out – the title's pipeline gets the dummy +//! compute program a console shader that cannot be translated gets, so its dispatches are +//! skipped, and the shader preparation and `xcl shaders --precompile` pass them over. +//! +//! What it is for: a title's ray-tracing programs that shade the hits of rays or start rays +//! (on a retail title about 1,000 programs, ~1 MB of DXIL each, the largest of its cold driver +//! compiles) do nothing while the title has built no acceleration structure: every ray misses. +//! The fragments name those programs (a name in the container's debug data; find it with +//! `xcl rpf --find`); XCL's source names no title's programs. +//! +//! So that leaving them out stays harmless, XCL watches the acceleration structures the +//! title's views name (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE` in unified +//! memory) and warns once when one of them gets a root node: from then on rays can hit, and +//! the programs left out would have shaded those hits. +//! +//! Ported from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later; THIRD_PARTY.md). +//! Changes (2026-11-27): the programs are named by the user's fragments instead of names in +//! the source; one switch; the structure watch and its warning are new; the preparation and +//! the precompile pass the programs over. + +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +/// Fragments shorter than this are refused: they would match bytes of any container. +const SHORTEST: usize = 6; +/// Acceleration structures remembered for the watch (distinct addresses). +const MOST_STRUCTURES: usize = 4096; + +/// The fragments of a `XCL_RT_LEAVE_OUT` value: comma-separated, trimmed, at least +/// [`SHORTEST`] bytes each (shorter ones are dropped). +pub fn fragments_of(value: &str) -> Vec> { + value.split(',').map(str::trim).filter(|f| f.len() >= SHORTEST).map(|f| f.as_bytes().to_vec()).collect() +} + +/// Whether `container` holds one of `fragments`. +pub fn holds_any(container: &[u8], fragments: &[Vec]) -> bool { + fragments.iter().any(|f| container.windows(f.len()).any(|w| w == f.as_slice())) +} + +fn fragments() -> &'static [Vec] { + static F: OnceLock>> = OnceLock::new(); + F.get_or_init(|| { + let Ok(v) = std::env::var("XCL_RT_LEAVE_OUT") else { return Vec::new() }; + let f = fragments_of(&v); + let dropped = v.split(',').map(str::trim).filter(|s| !s.is_empty() && s.len() < SHORTEST).count(); + if f.is_empty() { + crate::xlog_warn!("XCL_RT_LEAVE_OUT: no fragment of at least {SHORTEST} bytes – nothing is left out"); + } else { + crate::xlog_info!( + "XCL_RT_LEAVE_OUT: compute programs holding one of {} fragment(s) are left out while rays cannot hit{}", + f.len(), + if dropped > 0 { format!(" ({dropped} shorter than {SHORTEST} bytes ignored)") } else { String::new() } + ); + } + f + }) +} + +/// Whether the switch is on (at least one usable fragment). +pub fn enabled() -> bool { + !fragments().is_empty() +} + +static LEFT_OUT: AtomicU64 = AtomicU64::new(0); + +/// Whether the compute program in `container` is left out; counts and logs the first few. +pub fn left_out(container: &[u8]) -> bool { + if !enabled() || !holds_any(container, fragments()) { + return false; + } + let n = LEFT_OUT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 3 || n.is_power_of_two() { + crate::xlog_info!( + "XCL_RT_LEAVE_OUT: compute program of record {:016x} left out (#{n}): its dispatches are skipped", + crate::gpu::shader::fnv64(container) + ); + } + true +} + +/// How many compute programs were left out so far. +pub fn left_out_count() -> u64 { + LEFT_OUT.load(Ordering::Relaxed) +} + +static STRUCTURES: Mutex> = Mutex::new(BTreeSet::new()); + +/// An acceleration structure in unified memory that a title's view names (only kept while the +/// switch is on). +pub fn note_structure(va: u64) { + if enabled() { + let mut s = STRUCTURES.lock().unwrap(); + if s.len() < MOST_STRUCTURES { + s.insert(va); + } + } +} + +/// The root node id in an acceleration structure's header: `None` while it has none (0 or +/// all ones, as before a build). +pub fn root_of(header: &[u8]) -> Option { + let at = crate::gpu::bvh::ROOT_AT; + let root = u32::from_le_bytes(header.get(at..at + 4)?.try_into().ok()?); + (root != 0 && root != u32::MAX).then_some(root) +} + +/// Looks at the structures views named (called every few hundred frames): warns once when one +/// has a root node, since the programs left out would then have hits to shade. +pub fn check_structures() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !enabled() || WARNED.load(Ordering::Relaxed) { + return; + } + let all: Vec = STRUCTURES.lock().unwrap().iter().copied().collect(); + let header = crate::gpu::bvh::HEADER_BYTES; + for va in all { + let p = va as usize; + if !crate::gpu::shader::readable(p, header) { + continue; + } + // SAFETY: `readable` just checked the range; title memory, only read + let bytes = unsafe { std::slice::from_raw_parts(p as *const u8, header) }; + if let Some(root) = root_of(bytes) { + if !WARNED.swap(true, Ordering::Relaxed) { + crate::xlog_warn!( + "XCL_RT_LEAVE_OUT: the acceleration structure at {va:#x} has a root node ({root:#x}) now – rays can hit, and the {} compute program(s) left out would shade those hits; run without XCL_RT_LEAVE_OUT for this title", + left_out_count() + ); + } + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fragments_are_trimmed_and_short_ones_dropped() { + let f = fragments_of(" ResolveA ,abc, ,LongerName,"); + assert_eq!(f, vec![b"ResolveA".to_vec(), b"LongerName".to_vec()]); + assert!(fragments_of("").is_empty()); + assert!(fragments_of("short").is_empty()); + } + + #[test] + fn a_container_is_matched_by_any_fragment_anywhere() { + let mut container = vec![0u8; 64]; + container.extend_from_slice(b"\x00prog_Example_Name_x\x00"); + container.extend_from_slice(&[0xFF; 32]); + assert!(holds_any(&container, &fragments_of("Other_Name,Example_Name"))); + assert!(!holds_any(&container, &fragments_of("Example_Names"))); + assert!(!holds_any(&container, &[])); + // a fragment at the very end still matches + assert!(holds_any(b"xxxxEnd_of_it", &fragments_of("End_of_it"))); + } + + #[test] + fn a_header_without_a_root_has_none() { + let mut h = vec![0u8; crate::gpu::bvh::HEADER_BYTES]; + assert_eq!(root_of(&h), None); + let at = crate::gpu::bvh::ROOT_AT; + h[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(root_of(&h), None); + h[at..at + 4].copy_from_slice(&0x25u32.to_le_bytes()); + assert_eq!(root_of(&h), Some(0x25)); + assert_eq!(root_of(&h[..at]), None, "a header too short to hold the root"); + } + + #[test] + fn a_built_structure_from_the_builder_has_a_root() { + // XCL's own builder writes the console layout the watch reads + let tris = crate::gpu::bvh::tests::random_tris(8, 3); + let b = crate::gpu::bvh::build(&tris, 0); + let root = root_of(&b.data).expect("a built structure has a root id"); + assert_eq!(root, b.root); + } +} diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d0941c4ea6..793514e610 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -127,6 +127,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u if let Some(t) = LAST.lock().unwrap().replace(now) { crate::xlog_info!("D3D12.X: {frames} frames presented, {:.1} fps over the last 300", 300.0 / (now - t).as_secs_f64()); } + crate::gpu::rt_leave_out::check_structures(); } super::real::stop_if_device_removed(); if !PRESENTX.swap(true, Ordering::Relaxed) { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bd9cd731cf..e527503f0a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3266,6 +3266,7 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const // and what rays read past it: the rest of the top level, its bottom levels, the // parent pointers (`bvh_want`; `XCL_BVH_WALK=0`: the 64 KiB above only) super::bvh_want::view_made(va); + crate::gpu::rt_leave_out::note_structure(va); let w = crate::gpu::desc::bvh_words(va, true); return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); } @@ -8720,11 +8721,27 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const hr } +/// Whether `desc`'s console compute program is one `XCL_RT_LEAVE_OUT` leaves out. +unsafe fn rt_left_out(desc: *const c_void) -> bool { + if !crate::gpu::rt_leave_out::enabled() || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return false; + } + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + shader_bytes(&d.CS).is_some_and(|cs| crate::gpu::recomp::pso::is_console(cs) && crate::gpu::rt_leave_out::left_out(cs)) +} + unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let _cost = crate::hle::api_cost::time(crate::hle::api_cost::Call::Pipeline); super::null::capture_compute_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); - let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; + // `XCL_RT_LEAVE_OUT`: not translated or built; the dummy program below, its dispatches skipped + let (mut console, missed) = if rt_left_out(desc) { + (Some(Err(())), false) + } else if super::pso_async::enabled() { + attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) + } else { + (translated_compute_pso(this, f, desc, riid, ppv), false) + }; if missed { if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, compute_key, build_compute)) { // a console program the worker is translating (its root signature comes with it); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 427de54058..df73b27ae0 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -3495,6 +3495,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): // into the translation cache too, so the title does not translate it again if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { + // the title's pipeline would leave it out too (`gpu::rt_leave_out`) + if crate::gpu::rt_leave_out::left_out(&blob) { + record_done(); + continue; + } if let Some(coverage) = coverage { match coverage.covers(i, &blob) { Ok(true) => { record_done(); continue; } @@ -3631,6 +3636,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on skipped.into_inner(), t0.elapsed().as_secs_f64() ); + if crate::gpu::rt_leave_out::enabled() { + println!("compute programs passed over (XCL_RT_LEAVE_OUT): {}", crate::gpu::rt_leave_out::left_out_count()); + } if let Some(p) = pipelines { if startup.is_none() { make_pipelines(p, pipeline_jobs.into_inner().unwrap());