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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ xcl disasm <shader.bin> [--hex] # RDNA2 disassembler (console contain
xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N
xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run
xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines --used-only # only the compute pipelines an earlier run of the title used
xcl shaders D:\data\shaders.rpf --precompile --only ms --pipelines # the compute passes of console mesh shaders (two-pass path), saved for the next run
xcl shaders D:\data\shaders.rpf --export-hlsl out --record-hash HEX # exact compute HLSL for investigation
xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # cold driver PSO timing (cache disabled)
xcl rpf D:\data\shaders.rpf --extract NAME --out folder
Expand Down
8 changes: 7 additions & 1 deletion crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1165,7 +1165,13 @@ fn console_mesh_with(
/// The mesh-shader (NGG) program of a console MS container; the pass-through carries what
/// the pixel shader `ps` (its container: console or PC) reads.
pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result<TwoPass, String> {
let windows = mem_windows();
console_mesh_in(blob, ps, split_wave64, mem_windows())
}

/// `console_mesh` with the title's memory windows given (`xcl shaders --precompile` builds the
/// compute passes without a title: the same DXIL, so the same driver blob keys, as at its run).
/// The compute pass does not depend on `ps`; only the pass-through mesh shader does.
pub fn console_mesh_in(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool, windows: u32) -> Result<TwoPass, String> {
let dir = dxc::cache_dir();
console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, ms, wave64| {
compile_console_mesh(blob, code, ms, wave64, windows, split_wave64)
Expand Down
12 changes: 10 additions & 2 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4710,6 +4710,13 @@ fn compute_blob_key(dxil: &[u8], rs: usize, flags: i32) -> (u64, usize, i32) {
(h.finish(), rs, flags)
}

/// The file of the driver blob of a two-pass pipeline's compute pass (`finish_two_pass`): by its
/// DXIL alone, with no pipeline flags, shared by every `(MS, PS)` pipeline of the console MS.
/// `xcl shaders --precompile --only ms --pipelines` writes it under this name too.
pub(crate) fn two_pass_compute_blob_path(cs: &[u8]) -> Option<std::path::PathBuf> {
driver_cache::path(cs, 0)
}

fn compute_blob(key: (u64, usize, i32)) -> Option<std::sync::Arc<Vec<u8>>> {
COMPUTE_BLOBS.lock().unwrap().as_ref().and_then(|(m, _)| m.get(&key).cloned())
}
Expand Down Expand Up @@ -6136,10 +6143,11 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu:
cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop<Option<ID3D12RootSignature>>>(rs);
cdesc.CS = bytecode(&tp.cs);
// Reuse the compiled driver blob of the compute pass across all `(MS/GS, PS)` pipelines that
// share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`.
// share `tp.cs` (in memory and on disk – an earlier run's or `xcl shaders --precompile
// --only ms --pipelines`'), matching `translated_compute_pso_once`.
let ckey = compute_blob_key(&tp.cs, rs as usize, 0);
let mut ccached = compute_blob(ckey);
let cdisk = driver_cache::path(&tp.cs, 0);
let cdisk = two_pass_compute_blob_path(&tp.cs);
let cfrom_disk = ccached.is_none();
if cfrom_disk {
ccached = cdisk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new);
Expand Down
143 changes: 127 additions & 16 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,7 @@ struct ShadersOptions {
pipelines: bool,
used_only: bool,
direct: bool,
sample: usize,
sample: Option<usize>,
seed: u64,
validate: bool,
compare: bool,
Expand Down Expand Up @@ -851,7 +851,7 @@ fn parse_args(args: &[String]) -> Result<ShadersOptions, String> {
pipelines: false,
used_only: false,
direct: false,
sample: 200,
sample: None,
seed: 1,
validate: false,
compare: false,
Expand Down Expand Up @@ -889,7 +889,7 @@ fn parse_args(args: &[String]) -> Result<ShadersOptions, String> {
"--pipelines" => opts.pipelines = true,
"--used-only" => opts.used_only = true,
"--direct" => opts.direct = true,
"--sample" => opts.sample = p.parse_usize("--sample")?,
"--sample" => opts.sample = Some(p.parse_usize("--sample")?),
"--seed" => opts.seed = p.parse_u64("--seed")?,
"--validate" => opts.validate = true,
"--compare" => opts.compare = true,
Expand Down Expand Up @@ -981,7 +981,8 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys);
// the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`)
let windows = runtime_windows();
return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None) {
// `--sample N`: only the first N programs `--only` lets through (all without it)
return match precompile(&input, opts.limit, opts.sample.unwrap_or(usize::MAX), windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None) {
Ok(()) => 0,
Err(e) => { eprintln!("xcl shaders: {e}"); 2 }
};
Expand Down Expand Up @@ -1199,8 +1200,11 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
/// different at run time: a PS's static samplers after its VS's (sampler base 0 here) and the
/// mesh pass-through, which the runtime builds for its pixel shader.
/// `--pipelines`: each compute program's pipeline made on the GPU as a title's would be (XCL's
/// ABI root signature with its static samplers). Save the driver's compiled blob in the same
/// cache the runtime reads at startup. Nothing runs on the GPU.
/// ABI root signature with its static samplers), and each MS's two-pass compute pass (`--only ms`
/// for those alone; the pass-through mesh pipeline needs the title's PS and state and is left to
/// the runtime). Save the driver's compiled blob in the same cache the runtime reads at startup.
/// Nothing runs on the GPU. `--sample N`: only the first N programs `--only` lets through.
/// `--used-only` passes the MSs over: a mesh pipeline's key has its PS too.
/// Programs whose DXIL is over `XCL_PIPELINE_MAX_KB` (8 MiB by default; 0 turns the cap off)
/// and that have no blob yet are counted as capped and left to the runtime: their driver
/// compile takes tens of minutes and gigabytes, and stopped the pass on the biggest programs
Expand Down Expand Up @@ -1454,10 +1458,13 @@ impl Pipelines {
/// into a dispatch chain of at least two pieces, each piece is built and cached under the
/// dispatch-chain root signature (`.chain.pso`) as the runtime does (`dispatch_chain::build`),
/// instead of the unsplit whole container.
#[cfg(test)]
fn make(&self, c: &recomp::pso::Compiled) {
self.make_with_cache_path(c, None);
}

/// The compute pipeline of `c` (made and released), its driver blob kept in `path_override`
/// (None: the runtime's file for a compute pipeline of that DXIL, as `make`).
fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option<PathBuf>) {
if path_override.is_none() {
if let Some(chain) = c.dispatch_chain.as_deref().filter(|chain| chain.pieces.len() >= 2) {
Expand Down Expand Up @@ -1647,12 +1654,33 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R
if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; }
for input in inputs {
if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); }
precompile(&input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress))?;
precompile(&input, usize::MAX, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress))?;
}
Ok(())
}

fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet<u64>>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> {
/// An MS the runtime builds as two-pass pipelines (`pso::console_mesh`): its first NGG variant
/// (hardware stage 7) has a triangle interface (lines / points are not translated).
fn two_pass_mesh(blob: &[u8], sh: &xbox::XboxShader) -> bool {
sh.stage == "MS"
&& sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 7)).is_some_and(|f| matches!(recomp::interface(blob, sh, f), Some(recomp::Mode::Mesh(_))))
}

/// The compute pipeline a title makes from a console program, as the runtime makes it, and the
/// file the runtime looks for its driver blob in: a CS's own pipeline (`pso::console_to_dxil_in`;
/// None: `Pipelines` keys it as the runtime keys compute pipelines), or, for an MS (`mesh`), the
/// compute pass of its two-pass pipelines (`pso::console_mesh_in` with no pixel shader – the
/// compute pass does not depend on it –, `real::two_pass_compute_blob_path`).
fn precompiled_compute(blob: &[u8], mesh: bool, split: bool, windows: u32) -> Result<(recomp::pso::Compiled, Option<PathBuf>), String> {
if !mesh {
return recomp::pso::console_to_dxil_in(blob, recomp::pso::Stage::Compute, 0, split, windows).map(|c| (c, None));
}
let tp = recomp::pso::console_mesh_in(blob, None, split, windows)?;
let path = crate::hle::d3d12x::real::two_pass_compute_blob_path(&tp.cs);
Ok((recomp::pso::Compiled { dispatch_chain: None, dxil: tp.cs, samplers: tp.samplers }, path))
}

fn precompile(input: &Input, limit: usize, sample: usize, windows: u32, split: Option<bool>, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet<u64>>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> {
let pipelines = if pipelines {
let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str()))
.map_err(|e| format!("No pipeline device: {e}"))?;
Expand All @@ -1665,7 +1693,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
};
let pipelines = pipelines.as_ref();
let n = input.len().min(limit);
let next = AtomicUsize::new(0);
let (next, taken) = (AtomicUsize::new(0), AtomicUsize::new(0));
let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0));
let errors: Mutex<Vec<String>> = Mutex::new(Vec::new());
let unused = AtomicUsize::new(0);
Expand Down Expand Up @@ -1719,18 +1747,26 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
record_done();
continue;
}
// `--sample N`: the first N programs `--only` lets through
if taken.fetch_add(1, Ordering::Relaxed) >= sample {
break;
}
// 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(_)))) {
if used.is_some_and(|u| !used_compute(&blob, u)) {
// into the translation cache too, so the title does not translate it again; an MS
// as the compute pass of its two-pass pipelines (`pso::console_mesh_in`)
let compute = sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_))));
let mesh = !compute && two_pass_mesh(&blob, &sh);
if compute || mesh {
// a mesh pipeline's key has its PS too: `--used-only` passes the MSs over
if used.is_some_and(|u| mesh || !used_compute(&blob, u)) {
unused.fetch_add(1, Ordering::Relaxed);
record_done();
continue;
}
match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) {
Ok(c) => {
match precompiled_compute(&blob, mesh, split, windows) {
Ok((c, path)) => {
if let Some(p) = pipelines {
p.make(&c);
p.make_with_cache_path(&c, path);
if startup.is_some() && c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) {
p.make_one(&c.dxil, &c.samplers, true, None);
}
Expand Down Expand Up @@ -2195,6 +2231,81 @@ mod tests {
sample(5, &[compute])
}

/// A signature part (v1): (name, system value, register, mask) per element, floats.
fn signature(elements: &[(&str, u32, u32, u8)]) -> Vec<u8> {
let mut d = Vec::new();
d.extend_from_slice(&(elements.len() as u32).to_le_bytes());
d.extend_from_slice(&8u32.to_le_bytes());
let mut names = Vec::new();
let base = 8 + 32 * elements.len() as u32;
for &(name, sv, reg, mask) in elements {
for v in [0, base + names.len() as u32, 0, sv, 3, reg] {
d.extend_from_slice(&v.to_le_bytes());
}
d.extend_from_slice(&[mask, mask, 0, 0, 0, 0, 0, 0]);
names.extend_from_slice(name.as_bytes());
names.push(0);
}
d.extend_from_slice(&names);
d
}

/// A console MS container as the retail title's: an NGG variant (hardware stage 7), triangles,
/// 128 threads, 64 vertices and primitives, a position and a texture coordinate out.
fn mesh_sample() -> Vec<u8> {
let mut r = vec![0u8; 48];
r[12..14].copy_from_slice(&64u16.to_le_bytes());
r[14..16].copy_from_slice(&64u16.to_le_bytes());
r[24] = 13; // mesh
r[27] = 2; // triangles
for (k, t) in [128u32, 1, 1].iter().enumerate() {
r[36 + 4 * k..40 + 4 * k].copy_from_slice(&t.to_le_bytes());
}
let mut psv = 48u32.to_le_bytes().to_vec();
psv.extend_from_slice(&r);
psv.extend_from_slice(&0u32.to_le_bytes());
let osg = signature(&[("SV_Position", 1, 0, 0xF), ("TEXCOORD", 0, 1, 0x3)]);
let dxil = crate::gpu::xbox::tests::dxil_part(13, &[fssm(&CODE, &[(7, 13)])]);
crate::gpu::xbox::tests::container(&[(b"SFI0", &[0; 8]), (b"OSG1", &osg), (b"PSV0", &psv), (b"HASH", &[0; 20]), (b"DXIL", &dxil), (b"PRIV", &[7; 16])])
}

/// `--precompile --only ms --pipelines` keeps the driver blob of an MS's two-pass compute pass
/// in the file the runtime reads it from (`finish_two_pass`): the same DXIL and static
/// samplers (so root signature) as the runtime's `console_mesh` with the title's PS, for the
/// split wave64 form and heap windows as without them.
#[test]
fn an_ms_compute_pass_is_precompiled_under_the_runtimes_key() {
if let Err(reason) = recomp::dxc::location() {
recomp::runner::skip_test(&format!("no DXC: {reason}"));
return;
}
let blob = mesh_sample();
let sh = xbox::parse(&blob).expect("a console container");
assert_eq!(sh.stage, "MS");
assert!(two_pass_mesh(&blob, &sh));
let ps = crate::gpu::xbox::tests::container(&[(b"ISG1", &signature(&[("SV_Position", 1, 0, 0xF), ("TEXCOORD", 0, 1, 0x3)]))]);
for (split, windows) in [(false, 4), (true, 4), (true, 4 | recomp::HEAP_WINDOWS)] {
let (pre, path) = precompiled_compute(&blob, true, split, windows).expect("translated");
let run = recomp::pso::console_mesh_in(&blob, Some(&ps), split, windows).expect("translated at run time");
assert_eq!(pre.dxil, run.cs, "split {split}, windows {windows:#x}");
assert_eq!(pre.samplers, run.samplers);
assert!(path.is_some());
assert_eq!(path, crate::hle::d3d12x::real::two_pass_compute_blob_path(&run.cs));
}
// the runtime's `console_mesh` is `console_mesh_in` with the title's memory windows
let windows = recomp::pso::mem_windows();
assert_eq!(recomp::pso::console_mesh(&blob, Some(&ps), true).unwrap().cs, recomp::pso::console_mesh_in(&blob, None, true, windows).unwrap().cs);
// a CS is not an MS: its own pipeline, under the compute pipelines' file
let cs = compute_sample();
assert!(!two_pass_mesh(&cs, &xbox::parse(&cs).unwrap()));
if let Ok((_, path)) = precompiled_compute(&cs, false, false, 4) {
assert_eq!(path, None);
}
// nor is a PS
let ps_blob = sample(0, &[fssm(&CODE, &[(5, 1)])]);
assert!(!two_pass_mesh(&ps_blob, &xbox::parse(&ps_blob).unwrap()));
}

#[test]
fn record_hash_is_strict_hex() {
assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB);
Expand Down Expand Up @@ -2362,7 +2473,7 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) ->
use crate::gpu::dxil::coverage::{self, Report, Sample};
let top = opts.top;
let json = opts.json;
let want = if opts.sample == 0 { usize::MAX } else { opts.sample };
let want = match opts.sample.unwrap_or(200) { 0 => usize::MAX, n => n };
let seed = opts.seed;
let validate = opts.validate;
let compare = opts.compare;
Expand Down
Loading