diff --git a/Cargo.lock b/Cargo.lock index 9fcde4604..2293b4248 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -553,6 +553,7 @@ dependencies = [ "serde_json", "toml", "windows", + "windows-core", "windows-sys 0.61.2", ] diff --git a/README.md b/README.md index 2a957e95e..2bbab76db 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,14 @@ xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compi xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` +Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. Add +`-Pipelines` to warm the GPU driver's compute-pipeline cache too (slower and GPU/driver-specific): + +```powershell +.\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' +.\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' -Pipelines +``` + - **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the window stays open until Enter. diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index f3f6d604d..a9fd1b602 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -19,6 +19,7 @@ retour = "0.3" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1" +windows-core = "0.62" [dependencies.windows] version = "0.62" diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index b769d8008..6e5a3c834 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -12,13 +12,15 @@ use std::cell::RefCell; use std::collections::HashMap; use std::ffi::c_void; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::core::{Interface, GUID, HRESULT, PCWSTR}; use windows::Win32::Graphics::Direct3D::Dxc::{DxcBuffer, IDxcBlob, IDxcCompiler3, IDxcResult, CLSID_DxcCompiler, DXC_CP_UTF8}; +use windows::Win32::System::Com::{IMalloc, IMalloc_Impl}; type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT; +type CreateInstance2 = unsafe extern "system" fn(*mut c_void, *const GUID, *const GUID, *mut *mut c_void) -> HRESULT; /// A dotted version, `10.0.26100.0` or `1.9.2602.17`, as four numbers (missing ones are 0). fn parse_version(s: &str) -> Option<[u32; 4]> { @@ -191,7 +193,7 @@ unsafe fn library(create: CreateInstance, class: &GUID, file: &Path) -> Library lib } -static LIB: OnceLock> = OnceLock::new(); +static LIB: OnceLock), String>> = OnceLock::new(); static TOOLCHAIN: OnceLock = OnceLock::new(); /// The DXC in use; empty while none is loaded (asking does not load it). @@ -288,10 +290,10 @@ mod version_tests { /// Folder with dxcompiler.dll (+ dxil.dll) that will be used. pub fn location() -> Result<&'static Path, String> { - load().map(|(p, _)| p.as_path()) + load().map(|(p, ..)| p.as_path()) } -fn load() -> Result<&'static (PathBuf, usize), String> { +fn load() -> Result<&'static (PathBuf, usize, Option), String> { LIB.get_or_init(|| { use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; for dir in candidates() { @@ -307,6 +309,7 @@ fn load() -> Result<&'static (PathBuf, usize), String> { continue; } if let Some(f) = GetProcAddress(h, b"DxcCreateInstance\0".as_ptr()) { + let f2 = GetProcAddress(h, b"DxcCreateInstance2\0".as_ptr()).map(|f| f as usize); let mut t = Toolchain { dir: dir.display().to_string(), ..Default::default() }; t.dxcompiler = library(std::mem::transmute::(f as usize), &CLSID_DxcCompiler, &dxc); if let Some(g) = if signer.is_null() { None } else { GetProcAddress(signer, b"DxcCreateInstance\0".as_ptr()) } { @@ -318,7 +321,7 @@ fn load() -> Result<&'static (PathBuf, usize), String> { crate::xlog_warn!("DXC {} is older than {}.{}: {OUTDATED_COST}; {OUTDATED_FIX}", t.dxcompiler, RECOMMENDED.0, RECOMMENDED.1); } let _ = TOOLCHAIN.set(t); - return Ok((dir, f as usize)); + return Ok((dir, f as usize, f2)); } } } @@ -330,14 +333,93 @@ fn load() -> Result<&'static (PathBuf, usize), String> { /// The PC compiler's DxcCreateInstance (for titles that use the console's `dxcompiler_xs.dll`). pub fn create_instance() -> Option { - load().ok().map(|&(_, f)| f) + load().ok().map(|&(_, f, _)| f) } fn create_fn() -> Result { - let &(_, f) = load()?; + let &(_, f, _) = load()?; Ok(unsafe { std::mem::transmute::(f) }) } +fn create2_fn() -> Result, String> { + let &(_, _, f) = load()?; + Ok(f.map(|f| unsafe { std::mem::transmute::(f) })) +} + +/// A serialized process heap for one DXC compiler. DXC allocates heavily through `IMalloc`; +/// one private heap per compiler keeps its workers off the process heap's global lock. +#[windows::core::implement(IMalloc)] +struct DxcMalloc { + heap: windows_sys::Win32::Foundation::HANDLE, +} + +// DXC may allocate and release through the interface on its own internal threads. The heap is +// serialized and the handle never changes, so sharing the COM object is safe. +unsafe impl Send for DxcMalloc {} +unsafe impl Sync for DxcMalloc {} + +impl DxcMalloc { + fn new() -> Result { + let heap = unsafe { windows_sys::Win32::System::Memory::HeapCreate(0, 0, 0) }; + if heap.is_null() { + Err(format!("HeapCreate for DXC: {}", std::io::Error::last_os_error())) + } else { + Ok(Self { heap }) + } + } +} + +impl IMalloc_Impl for DxcMalloc_Impl { + fn Alloc(&self, cb: usize) -> *mut c_void { + unsafe { windows_sys::Win32::System::Memory::HeapAlloc(self.heap, 0, cb) } + } + + fn Realloc(&self, pv: *const c_void, cb: usize) -> *mut c_void { + unsafe { + if pv.is_null() { + return windows_sys::Win32::System::Memory::HeapAlloc(self.heap, 0, cb); + } + if cb == 0 { + let _ = windows_sys::Win32::System::Memory::HeapFree(self.heap, 0, pv); + return std::ptr::null_mut(); + } + windows_sys::Win32::System::Memory::HeapReAlloc(self.heap, 0, pv, cb) + } + } + + fn Free(&self, pv: *const c_void) { + if !pv.is_null() { + let _ = unsafe { windows_sys::Win32::System::Memory::HeapFree(self.heap, 0, pv) }; + } + } + + fn GetSize(&self, pv: *const c_void) -> usize { + if pv.is_null() { + usize::MAX + } else { + unsafe { windows_sys::Win32::System::Memory::HeapSize(self.heap, 0, pv) } + } + } + + fn DidAlloc(&self, pv: *const c_void) -> i32 { + if pv.is_null() { + -1 + } else { + (unsafe { windows_sys::Win32::System::Memory::HeapValidate(self.heap, 0, pv) } != 0) as i32 + } + } + + fn HeapMinimize(&self) { + unsafe { windows_sys::Win32::System::Memory::HeapCompact(self.heap, 0) }; + } +} + +impl Drop for DxcMalloc { + fn drop(&mut self) { + let _ = unsafe { windows_sys::Win32::System::Memory::HeapDestroy(self.heap) }; + } +} + thread_local! { static COMPILER: RefCell> = const { RefCell::new(None) }; } @@ -347,9 +429,30 @@ fn compiler() -> Result { if let Some(x) = c.borrow().as_ref() { return Ok(x.clone()); } - let create = create_fn()?; let mut p = std::ptr::null_mut(); - let hr = unsafe { create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut p) }; + let mut hr = HRESULT(crate::util::E_NOTIMPL); + if let Some(create2) = create2_fn()? { + let malloc: IMalloc = DxcMalloc::new()?.into(); + hr = unsafe { create2(malloc.as_raw(), &CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut p) }; + if hr.is_ok() && !p.is_null() { + static LOGGED: AtomicBool = AtomicBool::new(false); + if !LOGGED.swap(true, Ordering::Relaxed) { + crate::xlog_info!("DXC: compiler workers use private heaps"); + } + } else if hr.0 == crate::util::E_INVALIDARG { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("DXC: DxcCreateInstance2 rejected a private allocator; using DxcCreateInstance"); + } + p = std::ptr::null_mut(); + } else { + return Err(format!("DxcCreateInstance2: {hr:?}")); + } + } + if p.is_null() { + let create = create_fn()?; + hr = unsafe { create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut p) }; + } if hr.is_err() || p.is_null() { return Err(format!("DxcCreateInstance: {hr:?}")); } @@ -359,6 +462,73 @@ fn compiler() -> Result { }) } +#[cfg(test)] +mod private_heap_tests { + use super::*; + + #[test] + fn private_dxc_allocator_obeys_imalloc_contract() { + let malloc: IMalloc = DxcMalloc::new().unwrap().into(); + unsafe { + let zero = malloc.Alloc(0); + assert!(!zero.is_null()); + assert_eq!(malloc.DidAlloc(Some(zero)), 1); + malloc.Free(Some(zero)); + + let p = malloc.Alloc(16); + assert!(!p.is_null()); + for i in 0..16 { + p.cast::().add(i).write(i as u8); + } + assert!(malloc.GetSize(Some(p)) >= 16); + assert_eq!(malloc.DidAlloc(Some(p)), 1); + + let grown = malloc.Realloc(Some(p), 64); + assert!(!grown.is_null()); + for i in 0..16 { + assert_eq!(grown.cast::().add(i).read(), i as u8); + } + assert!(malloc.Realloc(Some(grown), 0).is_null()); + + let from_null = malloc.Realloc(None, 8); + assert!(!from_null.is_null()); + malloc.Free(Some(from_null)); + malloc.Free(None); + } + } + + #[test] + fn private_allocators_compile_on_two_threads() { + if location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + if create2_fn().ok().flatten().is_none() { + crate::gpu::recomp::runner::skip_test("DXC has no DxcCreateInstance2"); + return; + } + let start = Arc::new(std::sync::Barrier::new(3)); + std::thread::scope(|scope| { + let threads: Vec<_> = [1, 2] + .into_iter() + .map(|x| { + let start = start.clone(); + scope.spawn(move || { + start.wait(); + let src = format!("[numthreads({x}, 1, 1)] void main() {{}}"); + compile_here(&src, "main", "cs_6_6", &[]) + }) + }) + .collect(); + start.wait(); + for thread in threads { + let dxil = thread.join().unwrap().unwrap(); + assert!(valid_dxil_container(&dxil)); + } + }); + } +} + /// Stack of the thread DXC runs on: its LLVM passes recurse along long dependency chains of /// big translated programs (2 MB overflowed on a 7 000-instruction retail PS); the caller may /// be a game thread with a small stack. Reserved, committed only as used. diff --git a/scripts/precompile-shaders.ps1 b/scripts/precompile-shaders.ps1 new file mode 100644 index 000000000..c7ea5a7ac --- /dev/null +++ b/scripts/precompile-shaders.ps1 @@ -0,0 +1,94 @@ +# Fill XCL's DXIL cache from a readable RPF9 shader package without launching a title. +# +# .\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' +# .\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' -Pipelines +# +# The package is read only. Cached DXIL goes to XCL_DXIL_CACHE when -Cache is supplied, +# otherwise to XCL's default (%LOCALAPPDATA%\xcl\dxil). -Pipelines also asks the GPU +# driver to warm its own compute-pipeline cache; it does not execute shader code. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][string]$Package, + [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe'), + [ValidateSet('all', 'cs', 'vs', 'ps', 'ms')][string]$Only = 'cs', + [ValidateRange(1, 32)][int]$MemoryWindows = 4, + [ValidateSet('auto', 'on', 'off')][string]$SplitWave64 = 'auto', + [ValidateRange(0, [int]::MaxValue)][int]$Limit = 0, + [ValidateRange(0, 256)][int]$DxcThreads = 0, + [ValidateRange(0, 256)][int]$PipelineThreads = 0, + [string]$Cache, + [switch]$Pipelines, + [switch]$NoBuild, + [switch]$PlanOnly +) +$ErrorActionPreference = 'Stop' + +$packagePath = (Resolve-Path -LiteralPath $Package).Path +if (-not (Test-Path -LiteralPath $packagePath -PathType Leaf)) { + throw "shader package is not a file: $packagePath" +} + +# Fail early with a useful error instead of asking XCL to scan an unrelated or protected file. +$stream = [System.IO.File]::OpenRead($packagePath) +try { + $magic = New-Object byte[] 4 + if ($stream.Read($magic, 0, 4) -ne 4 -or [System.Text.Encoding]::ASCII.GetString($magic) -ne '9FPR') { + throw "shader package is not a readable RPF9 archive: $packagePath" + } +} finally { + $stream.Dispose() +} + +$repoRoot = Split-Path $PSScriptRoot -Parent +$xclPath = [System.IO.Path]::GetFullPath($Xcl) +$arguments = @('shaders', $packagePath, '--precompile', '--windows', "$MemoryWindows") +if ($Only -ne 'all') { $arguments += @('--only', $Only) } +if ($SplitWave64 -eq 'on') { $arguments += @('--split', '1') } +if ($SplitWave64 -eq 'off') { $arguments += @('--split', '0') } +if ($Limit -gt 0) { $arguments += @('--limit', "$Limit") } +if ($Pipelines) { + if ($Only -notin @('all', 'cs')) { + throw '-Pipelines is available only with -Only cs or -Only all' + } + $arguments += '--pipelines' +} + +$environment = @{} +if ($Cache) { $environment.XCL_DXIL_CACHE = [System.IO.Path]::GetFullPath($Cache) } +if ($DxcThreads -gt 0) { $environment.XCL_DXC_THREADS = "$DxcThreads" } +if ($PipelineThreads -gt 0) { $environment.XCL_PIPELINE_THREADS = "$PipelineThreads" } + +Write-Host "Package: $packagePath" +Write-Host "DXIL cache: $(if ($Cache) { $environment.XCL_DXIL_CACHE } else { '%LOCALAPPDATA%\xcl\dxil' })" +Write-Host "Command: `"$xclPath`" $($arguments -join ' ')" +foreach ($entry in $environment.GetEnumerator() | Sort-Object Key) { + Write-Host "Environment: $($entry.Key)=$($entry.Value)" +} +if ($PlanOnly) { return } + +if (-not (Test-Path -LiteralPath $xclPath -PathType Leaf)) { + if ($NoBuild) { throw "no $xclPath - omit -NoBuild to build it" } + & cargo build --release -p xcl --manifest-path (Join-Path $repoRoot 'Cargo.toml') + if ($LASTEXITCODE -ne 0) { throw "cargo build failed with exit code $LASTEXITCODE" } +} + +$saved = @{} +try { + foreach ($entry in $environment.GetEnumerator()) { + $saved[$entry.Key] = @{ + Present = Test-Path -LiteralPath "Env:$($entry.Key)" + Value = [System.Environment]::GetEnvironmentVariable($entry.Key, 'Process') + } + [System.Environment]::SetEnvironmentVariable($entry.Key, $entry.Value, 'Process') + } + & $xclPath @arguments + if ($LASTEXITCODE -ne 0) { throw "shader precompile failed with exit code $LASTEXITCODE" } +} finally { + foreach ($entry in $saved.GetEnumerator()) { + if ($entry.Value.Present) { + [System.Environment]::SetEnvironmentVariable($entry.Key, $entry.Value.Value, 'Process') + } else { + Remove-Item -LiteralPath "Env:$($entry.Key)" -ErrorAction SilentlyContinue + } + } +}