diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index ec63906c58..0f260ef869 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -569,7 +569,12 @@ pub(super) fn toolchain_identity() -> &'static str { } /// FNV-1a 64 of the inputs that determine the DXIL. +#[cfg(test)] fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str) -> u64 { + cache_key_for_toolchain_extra(src, entry, profile, toolchain, &[]) +} + +fn cache_key_for_toolchain_extra(src: &str, entry: &str, profile: &str, toolchain: &str, extra: &[&str]) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for part in [env!("CARGO_PKG_VERSION"), toolchain, profile, entry, src] { for b in part.bytes().chain([0u8]) { @@ -577,9 +582,22 @@ fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &st h = h.wrapping_mul(0x100_0000_01b3); } } + if !extra.is_empty() { + for part in std::iter::once("xcl-extra").chain(extra.iter().copied()) { + for b in part.bytes().chain([0u8]) { + h ^= b as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + } + } h } +pub(super) fn cache_key_with_extra(src: &str, entry: &str, profile: &str, extra: &[&str]) -> u64 { + cache_key_for_toolchain_extra(src, entry, profile, toolchain_identity(), extra) +} + +#[cfg(test)] fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { cache_key_for_toolchain(src, entry, profile, toolchain_identity()) } @@ -665,6 +683,11 @@ pub fn compile_cached_in(dir: &Path, src: &str, entry: &str, profile: &str) -> R compile_cached_in_with(dir, src, entry, profile, || compile(src, entry, profile, &[])) } +/// Like `compile_cached_in`, keyed also by extra DXC flags such as `["-opt-disable", "gvn"]`. +pub fn compile_cached_in_with_extra(dir: &Path, src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<(Vec, bool), String> { + compile_cached_in_observed_with_extra(dir, src, entry, profile, extra, cache_counters(), || compile(src, entry, profile, extra)) +} + type CacheFlight = (PathBuf, u64); fn cache_flight(key: CacheFlight) -> Arc> { @@ -804,7 +827,22 @@ fn compile_cached_in_observed( where F: FnOnce() -> Result, String>, { - let key = cache_key(src, entry, profile); + compile_cached_in_observed_with_extra(dir, src, entry, profile, &[], counters, compile_one) +} + +fn compile_cached_in_observed_with_extra( + dir: &Path, + src: &str, + entry: &str, + profile: &str, + extra: &[&str], + counters: &CacheCounters, + compile_one: F, +) -> Result<(Vec, bool), String> +where + F: FnOnce() -> Result, String>, +{ + let key = cache_key_with_extra(src, entry, profile, extra); let dir = normalized_cache_dir(dir); let file = dir.join(format!("{key:016x}.dxil")); if let Some(b) = cached_file(&file) { @@ -921,6 +959,10 @@ pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, compile_cached_in(&cache_dir(), src, entry, profile) } +pub fn compile_cached_with_extra(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<(Vec, bool), String> { + compile_cached_in_with_extra(&cache_dir(), src, entry, profile, extra) +} + #[cfg(test)] mod cache_tests { use super::*; @@ -1043,6 +1085,35 @@ mod cache_tests { assert_ne!(a, cache_key_for_toolchain("source", "main", "cs_6_6", "compiler-a/signer-b")); } + #[test] + fn cache_key_tracks_extra_dxc_flags() { + let base = cache_key_for_toolchain("source", "main", "cs_6_6", "tc"); + assert_eq!(base, cache_key_for_toolchain_extra("source", "main", "cs_6_6", "tc", &[])); + let nogvn = cache_key_for_toolchain_extra("source", "main", "cs_6_6", "tc", &["-opt-disable", "gvn"]); + assert_ne!(base, nogvn); + assert_ne!(nogvn, cache_key_for_toolchain_extra("source", "main", "cs_6_6", "tc", &["-O0"])); + } + + #[test] + fn dxil_cache_with_extra_flags_round_trip() { + if location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let dir = std::env::temp_dir().join(format!("xcl-dxil-extra-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let src = "RWByteAddressBuffer o : register(u0);\n[numthreads(64, 1, 1)] void main(uint3 t : SV_DispatchThreadID) {\n uint a = o.Load(t.x * 4);\n uint b = (a & 1) ? o.Load(t.x * 4 + 256) : o.Load(t.x * 4 + 256) + 1;\n o.Store(t.x * 4, b);\n}"; + let (default_dxil, hit0) = compile_cached_in(&dir, src, "main", "cs_6_6").unwrap(); + let (nogvn_dxil, hit1) = compile_cached_in_with_extra(&dir, src, "main", "cs_6_6", &["-opt-disable", "gvn"]).unwrap(); + assert!(!hit0 && !hit1); + assert!(valid_dxil_container(&default_dxil) && valid_dxil_container(&nogvn_dxil)); + assert_ne!(default_dxil, nogvn_dxil, "-opt-disable gvn must change the compiled DXIL"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2, "extra-flag build must use a distinct cache entry"); + let (cached_nogvn, hit2) = compile_cached_in_with_extra(&dir, src, "main", "cs_6_6", &["-opt-disable", "gvn"]).unwrap(); + assert!(hit2 && cached_nogvn == nogvn_dxil); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn validates_dxil_cache_structure_and_rebuilds_corruption() { let valid = synthetic_dxil(7); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index c9a50b72b4..477ea140f4 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -125,6 +125,13 @@ pub struct Compiled { pub samplers: Vec, } +/// A no-GVN compilation and the disk-cache keys for both compiler variants. +pub struct WithoutGvn { + pub compiled: Compiled, + pub rejected_key: u64, + pub retry_key: u64, +} + /// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static /// samplers take registers from `sampler_base` (space 1). /// Fails when the blob is not a console shader or the program is not fully translated. @@ -140,6 +147,18 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows()) } +/// Like `console_to_dxil_for`, disabling DXC's GVN pass for retrying driver-rejected shaders +/// without overwriting the default `ShaderCache` / `translated` entries. +pub fn console_to_dxil_without_gvn(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result { + console_to_dxil_in_without_gvn(blob, stage, sampler_base, split_wave64, mem_windows()) +} + +/// Like `console_to_dxil_in`, disabling DXC's GVN pass and using a distinct DXIL disk-cache key. +pub fn console_to_dxil_in_without_gvn(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { + compile_console_shader_with_extra(blob, stage, sampler_base, windows, split_wave64, &["-opt-disable", "gvn"]) + .map(|(compiled, _, rejected_key, retry_key)| WithoutGvn { compiled, rejected_key, retry_key }) +} + /// Global in-memory cache for translated shaders shared by `console_to_dxil_in` and `console_mesh`. fn shader_cache() -> &'static Mutex { static CACHE: OnceLock> = OnceLock::new(); @@ -446,6 +465,10 @@ fn enormous(stage: Stage, hlsl_len: usize) -> bool { /// The program's DXIL, and whether it is an `enormous` one the direct translator made (its /// disk cache entry then follows that translator's version: `translated::cached`). fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool), String> { + compile_console_shader_with_extra(blob, stage, sampler_base, windows, split_wave64, &[]).map(|(c, direct, _, _)| (c, direct)) +} + +fn compile_console_shader_with_extra(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, extra: &[&str]) -> Result<(Compiled, bool, u64, u64), String> { // `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path // for what it cannot translate yet if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() { @@ -455,7 +478,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: match direct_compute(blob, sampler_base, windows, split_wave64) { Ok(c) => { crate::gpu::dxil::coverage::record_translated("CS"); - return Ok((c, false)); + return Ok((c, false, 0, 0)); } Err(e) => direct_fallback("CS", &e), } @@ -470,12 +493,15 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: match direct_graphics(blob, stage, sampler_base, windows) { Ok(c) => { crate::gpu::dxil::coverage::record_translated(if stage == Stage::Vertex { "VS" } else { "PS" }); - return Ok((c, false)); + return Ok((c, false, 0, 0)); } Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e), } } let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?; + if !extra.is_empty() && extra.contains(&"-opt-disable") && t.hlsl.len() > 8 * 1024 * 1024 { + return Err("already compiled at -O0 without GVN".into()); + } if enormous(stage, t.hlsl.len()) && !crate::gpu::dxil::kernel::enabled() { if dxc::defer() { return Err("DXIL not compiled yet".into()); @@ -488,7 +514,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: t.hlsl.len() >> 10, c.dxil.len() >> 10 ); - return Ok((c, true)); + return Ok((c, true, 0, 0)); } Err(e) => direct_fallback("CS", &e), } @@ -522,8 +548,10 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: }) { t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } - let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; - Ok((Compiled { dxil, samplers: t.static_samplers }, false)) + let rejected_key = dxc::cache_key_with_extra(&t.hlsl, "main", profile, &[]); + let retry_key = dxc::cache_key_with_extra(&t.hlsl, "main", profile, extra); + let dxil = dxc::compile_cached_with_extra(&t.hlsl, "main", profile, extra)?.0; + Ok((Compiled { dxil, samplers: t.static_samplers }, false, rejected_key, retry_key)) } /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6cf818107b..485a50ed45 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -555,6 +555,11 @@ pub fn init() -> Result { } } +thread_local! { + /// First line of the latest error-severity D3D12 debug layer message on this thread. + static LAST_D3D12_ERROR: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + /// A debug layer message: errors and warnings into the log – the first 8 of each message id /// (3 000 in all). One cap for all of them (200) was used up in seconds by two per-frame state /// errors of a retail game, long before the message that came with its device removal. @@ -564,6 +569,12 @@ unsafe extern "system" fn debug_message(_category: D3D12_MESSAGE_CATEGORY, sever if severity.0 > D3D12_MESSAGE_SEVERITY_WARNING.0 { return; } + if severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && !text.is_null() { + let msg = String::from_utf8_lossy(text.as_bytes()); + if let Some(line) = first_error_line(&msg) { + LAST_D3D12_ERROR.with(|e| *e.borrow_mut() = Some(line.to_string())); + } + } { let mut g = PER_ID.lock().unwrap(); let n = g.get_or_insert_with(HashMap::new).entry(id.0).or_insert(0); @@ -4277,7 +4288,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { - use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + use crate::gpu::recomp::pso::{console_to_dxil_for, console_to_dxil_without_gvn, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; } @@ -4297,7 +4308,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Err(())); } }; - let dxil = compiled.dxil; + let mut dxil = compiled.dxil; // a big program: the driver's compile takes it seconds to a minute (a retail game's 1 MB // ray-tracing resolve programs ~30 s each, ~600 of them): built in the background like one // whose DXIL is missing – the title's loading does not wait for it, its first bind does @@ -4326,6 +4337,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } // in the background, a few at a time and within the commit headroom the program asks for let record = crate::gpu::shader::fnv64(cs); + LAST_D3D12_ERROR.with(|e| *e.borrow_mut() = None); let (mut hr, mut in_driver) = driver_compile_identified( "compute", dxil.len(), @@ -4333,6 +4345,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const Some((record, cached.is_some())), || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); + let mut refusal_elapsed = in_driver; if hr < 0 && cached.is_some() { // a blob the driver does not take (another root signature at the same address…): compiled forget_compute_blob(key); @@ -4349,8 +4362,9 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const ); hr = retried; in_driver += took; + refusal_elapsed = took; } - let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; + let mut reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { keep_compute_blob(key, *ppv, dxil.len()); if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { @@ -4359,6 +4373,101 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else if reused && from_disk { driver_cache::note(true, None); } + let mut retried_no_gvn: Option<(u64, u64, String)> = None; + let mut failure_note: Option = None; + if hr < 0 && !HEAP_WINDOW_OOM.with(|o| o.get()) { + let first_hr = hr; + let first_msg = LAST_D3D12_ERROR.with(|e| e.borrow_mut().take()); + let first_reason = format_driver_rejection(first_hr, first_msg.as_deref()); + let mut retry_reused = false; + let mut retry_in_driver = std::time::Duration::ZERO; + let mut retry_dxil = None; + let mut retry_keys = None; + let mut retry_attempted = false; + let (retry_hr, retried) = retry_compute_pso_without_gvn( + first_hr, + refusal_elapsed, + &dxil, + || { + let without = console_to_dxil_without_gvn(cs, Stage::Compute, 0, wave32_only(this))?; + retry_keys = Some((without.rejected_key, without.retry_key)); + Ok(without.compiled.dxil) + }, + |new_dxil| { + LAST_D3D12_ERROR.with(|e| *e.borrow_mut() = None); + retry_attempted = true; + retry_dxil = Some(new_dxil.to_vec()); + copy.CS = bytecode(new_dxil); + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let retry_key = compute_blob_key(new_dxil, rs as usize, copy.Flags.0); + let mut retry_cached = compute_blob(retry_key); + let retry_disk = driver_cache::path(new_dxil, copy.Flags.0); + let retry_from_disk = retry_cached.is_none(); + if retry_from_disk { + retry_cached = retry_disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + } + if let Some(b) = &retry_cached { + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } + let (mut retry_hr, mut took) = driver_compile_identified( + "compute no-gvn", + new_dxil.len(), + gate_compute_driver_compile(retry_cached.is_some()), + Some((record, retry_cached.is_some())), + || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), + ); + if retry_hr < 0 && retry_cached.is_some() { + forget_compute_blob(retry_key); + if retry_from_disk { + driver_cache::note(false, retry_disk.as_deref()); + } + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let (uncached_hr, uncached_took) = driver_compile_identified( + "compute no-gvn retry", + new_dxil.len(), + gate_compute_driver_compile(false), + Some((record, false)), + || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), + ); + retry_hr = uncached_hr; + took += uncached_took; + } + let reused = retry_hr >= 0 && retry_cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; + if retry_hr >= 0 && !reused { + keep_compute_blob(retry_key, *ppv, new_dxil.len()); + if let (Some(p), Some(b)) = (retry_disk.as_deref(), compute_blob(retry_key)) { + driver_cache::keep(p, &b, took); + } + } else if reused && retry_from_disk { + driver_cache::note(true, None); + } + retry_reused = reused; + retry_in_driver = took; + retry_hr + }, + ); + hr = retry_hr; + if let Some(retry_dxil) = retry_dxil { + dxil = retry_dxil; + } + if retried { + reused = retry_reused; + in_driver = retry_in_driver; + retried_no_gvn = retry_keys.map(|(g, ng)| (g, ng, first_reason.clone())); + } else { + failure_note = Some(if retry_attempted { + let retry_msg = LAST_D3D12_ERROR.with(|e| e.borrow_mut().take()); + let retry_reason = format_driver_rejection(hr, retry_msg.as_deref()); + if let Some((g, ng)) = retry_keys { + format!("{first_reason}; retry without GVN {g:016x} -> {ng:016x} refused: {retry_reason}") + } else { + retry_reason + } + } else { + first_reason + }); + } + } if hr < 0 { // A huge program's verdict in the log itself: `note_translation_error` goes to the // report, or to the notes of a cached-only attempt – a retail title's 13.8 MB program @@ -4374,7 +4483,10 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const in_driver.as_millis() ); } - note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); + note_translation_error(format!( + "the driver rejected the compute PSO with the translated CS ({})", + failure_note.unwrap_or_else(|| format!("{hr:#x}")) + )); return Some(Err(())); } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); @@ -4383,15 +4495,169 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } note_translated_compute(hr, ppv); + let retry_note = retried_no_gvn + .map(|(g, ng, reason)| format!(", retried without GVN (dxil cache {g:016x} -> {ng:016x}; driver refused: {reason})")) + .unwrap_or_default(); crate::xlog_info!( - "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", + "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{}{})", dxil.len(), in_driver.as_millis(), - if reused { ", the driver's blob of an earlier build" } else { "" } + if reused { ", the driver's blob of an earlier build" } else { "" }, + retry_note ); Some(Ok(hr)) } +pub(crate) fn first_error_line(text: &str) -> Option<&str> { + text.lines().map(str::trim).find(|l| !l.is_empty()) +} + +fn format_driver_rejection(hr: HRESULT, retained_message: Option<&str>) -> String { + if let Some(line) = retained_message.and_then(first_error_line) { + return format!("{hr:#x}: {line}"); + } + let msg = windows::core::Error::from_hresult(windows::core::HRESULT(hr)).to_string(); + first_error_line(&msg).map(str::to_string).unwrap_or_else(|| format!("{hr:#x}")) +} + +/// Upper bound on how long an initial driver refusal may take to qualify for a `-opt-disable gvn` +/// retry: fast handle-phi refusals can benefit, while multi-minute OOMs should not pay for another compile. +pub(crate) const NO_GVN_RETRY_MAX_REFUSAL: std::time::Duration = std::time::Duration::from_secs(5); + +/// Retry a fast driver-rejected compute PSO once using DXIL recompiled without DXC's GVN pass +/// (avoiding handle phis that some drivers refuse with `E_OUTOFMEMORY`, #756). +fn retry_compute_pso_without_gvn( + first_hr: HRESULT, + first_elapsed: std::time::Duration, + orig_dxil: &[u8], + recompile: impl FnOnce() -> Result, String>, + mut create: impl FnMut(&[u8]) -> HRESULT, +) -> (HRESULT, bool) { + if first_hr >= 0 || first_elapsed > NO_GVN_RETRY_MAX_REFUSAL { + return (first_hr, false); + } + let Ok(retry_dxil) = recompile() else { + return (first_hr, false); + }; + if retry_dxil == orig_dxil { + return (first_hr, false); + } + let hr2 = create(&retry_dxil); + (hr2, hr2 >= 0) +} + +#[cfg(test)] +mod compute_pso_retry_tests { + use super::*; + + const REFUSED_OOM: HRESULT = 0x8007_000Eu32 as i32; + const REFUSED_ARG: HRESULT = 0x8007_0057u32 as i32; + + #[test] + fn compute_pso_success_skips_no_gvn_retry() { + let mut calls = 0; + let (hr, retried) = retry_compute_pso_without_gvn(0, std::time::Duration::ZERO, b"orig", || panic!("successful PSO must not recompile"), |_| { + calls += 1; + 0 + }); + assert_eq!((hr, retried, calls), (0, false, 0)); + } + + #[test] + fn compute_pso_refusal_retries_without_gvn() { + let mut seen = Vec::new(); + let (hr, retried) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_millis(100), + b"orig-dxil", + || Ok(b"no-gvn-dxil".to_vec()), + |dxil| { + seen.push(dxil.to_vec()); + 0 + }, + ); + assert_eq!((hr, retried), (0, true)); + assert_eq!(seen, vec![b"no-gvn-dxil".to_vec()]); + } + + #[test] + fn compute_pso_refusal_skips_unchanged_dxil() { + let mut calls = 0; + let (hr, retried) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_millis(100), + b"same-dxil", + || Ok(b"same-dxil".to_vec()), + |_| { + calls += 1; + 0 + }, + ); + assert_eq!((hr, retried, calls), (REFUSED_OOM, false, 0)); + } + + #[test] + fn compute_pso_refusal_propagates_retry_failure() { + let (hr1, retried1) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_millis(100), + b"orig-dxil", + || Err("already -O0".into()), + |_| 0, + ); + assert_eq!((hr1, retried1), (REFUSED_OOM, false)); + let (hr2, retried2) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_millis(100), + b"orig-dxil", + || Ok(b"no-gvn-dxil".to_vec()), + |_| REFUSED_ARG, + ); + assert_eq!((hr2, retried2), (REFUSED_ARG, false)); + } + + #[test] + fn compute_pso_slow_refusal_skips_no_gvn_retry() { + let mut calls = 0; + let (hr, retried) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_secs(6), + b"orig-dxil", + || panic!("slow refusal must not trigger another compile"), + |_| { + calls += 1; + 0 + }, + ); + assert_eq!((hr, retried, calls), (REFUSED_OOM, false, 0)); + let (hr_edge, retried_edge) = retry_compute_pso_without_gvn( + REFUSED_OOM, + NO_GVN_RETRY_MAX_REFUSAL, + b"orig-dxil", + || Ok(b"no-gvn-dxil".to_vec()), + |_| 0, + ); + assert_eq!((hr_edge, retried_edge), (0, true)); + } + + #[test] + fn first_error_line_picks_first_nonempty_trimmed_line() { + assert_eq!(first_error_line("\n \n useful detail \r\nsecond line\n"), Some("useful detail")); + assert_eq!(first_error_line(" \r\n\t "), None); + } + + #[test] + fn format_driver_rejection_uses_debug_message_or_hresult() { + assert_eq!( + format_driver_rejection(REFUSED_OOM, Some("\n D3D12 ERROR: rejected phi handle \nsecond line")), + "0x8007000e: D3D12 ERROR: rejected phi handle" + ); + let fallback = format_driver_rejection(REFUSED_OOM, None); + assert!(!fallback.is_empty() && !fallback.contains('\n')); + assert!(fallback.to_ascii_lowercase().contains("8007000e")); + } +} + /// The blobs of `COMPUTE_BLOBS`, kept on disk between runs. /// /// `COMPUTE_BLOBS` saves the second build of a program in one run; the first build of every diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 68ee303327..5bab01dc39 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1220,12 +1220,39 @@ impl Pipelines { } } - /// The compute pipeline of `c` (made and released). - fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); + #[cfg(test)] + fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { + let _ = self.make_with_cache_path_result(c, path_override); } - fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { + fn make_with_cache_path_and_retry(&self, name: &str, c: &recomp::pso::Compiled, retry_without_gvn: impl FnOnce() -> Option) { + let Some((Err(first_error), first_elapsed)) = self.make_with_cache_path_result(c, None) else { return }; + if first_elapsed > crate::hle::d3d12x::real::NO_GVN_RETRY_MAX_REFUSAL { + return; + } + let Some(nogvn) = retry_without_gvn() else { return }; + if nogvn.compiled.dxil == c.dxil { + return; + } + let reason = crate::hle::d3d12x::real::first_error_line(&first_error).unwrap_or(&first_error).to_string(); + // Count the retry as the pipeline's final result, not as an extra refused pipeline. + self.refused.fetch_sub(1, Ordering::Relaxed); + let retried = self.make_with_cache_path_result(&nogvn.compiled, None); + match retried { + None => { + self.refused.fetch_add(1, Ordering::Relaxed); + } + Some((Ok(()), _)) => eprintln!( + " {name}: driver refused compute pipeline ({reason}); built without GVN (dxil cache {:016x} -> {:016x}, {} B DXIL)", + nogvn.rejected_key, + nogvn.retry_key, + nogvn.compiled.dxil.len() + ), + Some((Err(_), _)) => {} + } + } + + fn make_with_cache_path_result(&self, c: &recomp::pso::Compiled, path_override: Option) -> Option<(Result<(), String>, std::time::Duration)> { use windows::Win32::Graphics::Direct3D12::*; let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); let rs = { @@ -1239,7 +1266,7 @@ impl Pipelines { } Err(_) => { self.refused.fetch_add(1, Ordering::Relaxed); - return; + return None; } }, } @@ -1260,7 +1287,7 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(c.dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return None; } { let mut n = self.running.0.lock().unwrap(); @@ -1288,14 +1315,16 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(c.dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return None; } - let r = if let Some(pso) = from_cache { + let (r, elapsed) = if let Some(pso) = from_cache { self.reused.fetch_add(1, Ordering::Relaxed); - Ok(pso) + (Ok(pso), std::time::Duration::ZERO) } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let t0 = std::time::Instant::now(); let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; + let elapsed = t0.elapsed(); if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); @@ -1305,11 +1334,12 @@ impl Pipelines { } } } - pso + (pso, elapsed) }; *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + let error = r.as_ref().err().map(ToString::to_string); let done = match r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, @@ -1317,6 +1347,7 @@ impl Pipelines { if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } + Some((error.map_or(Ok(()), Err), elapsed)) } } @@ -1388,7 +1419,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); + p.make_with_cache_path_and_retry(&name, &c, || { + recomp::pso::console_to_dxil_in_without_gvn(&blob, recomp::pso::Stage::Compute, 0, split, windows).ok() + }); } compiled.fetch_add(1, Ordering::Relaxed) }