From c0a0ec0310f36a83ba08d56c2033440ec128d564 Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:33:07 +0000 Subject: [PATCH] Recompiler: lift literals that differ inside a family (XCL_LIFT_LITERALS) A title's pack has compute programs that are one program with different numeric constants. Their HLSL differs only in those literals, so DXC and the driver compile each again. In a cold run of a retail game on an RTX 2070 SUPER, 13 such repeat driver compiles took 253 s of the 1,327 s spent in the driver (19 %). Pack-wide: 127 families, 312 programs, 156 extra compiles out of 2,682 compute programs (5.8 %), e.g. records b162ea7db32e1657 / 0ed9e58ef6dc9cdb (462 KB of DXIL each). With XCL_LIFT_LITERALS=1, preparation (`xcl shaders --precompile` and launch preparation) finds the families. Programs with the same instruction sequence are translated, and those whose HLSL is the same once literals are masked form a family. Only the literal positions that differ inside a family are lifted: plain `u` integer literals in main's body, never attributes, declarations, control flow, `[]` or texture offsets. A lifted literal reads the same uint from io after the SGPRs (lift::IO_LIFTED), so the program computes the same thing. Each member's lifted text is one text without comments, so the DXC cache (by text) and the driver blob cache (by DXIL) share it. A pipeline keeps its values, and both compute dispatch paths (bind.rs, console_list.rs) write them after the SGPRs. The table is kept next to the caches under the translation cache identity. A family member skips the translated disk cache, which keeps no lifted values. If DXC refuses a lifted text, the program compiles as it is. Off by default until cold-run numbers show the gain and no frame-time cost (a lifted literal is a uniform io load instead of a folded constant). Related: #2711 (identical split pieces share a container), #2088. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lift.rs | 533 ++++++++++++++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 1 + crates/xcl/src/gpu/recomp/pso.rs | 73 ++- crates/xcl/src/gpu/recomp/runner.rs | 3 +- crates/xcl/src/gpu/recomp/tests.rs | 48 ++ crates/xcl/src/hle/d3d12x/bind.rs | 12 +- crates/xcl/src/hle/d3d12x/console_list.rs | 2 + crates/xcl/src/hle/d3d12x/real.rs | 21 + crates/xcl/src/shaders.rs | 15 +- 9 files changed, 681 insertions(+), 27 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/lift.rs diff --git a/crates/xcl/src/gpu/recomp/lift.rs b/crates/xcl/src/gpu/recomp/lift.rs new file mode 100644 index 0000000000..8d1ce917d7 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lift.rs @@ -0,0 +1,533 @@ +//! Literal lifting (`XCL_LIFT_LITERALS=1`, off by default). +//! +//! A title's pack holds compute programs that are the same program except for some numeric +//! constants (a retail game: 127 such families of 312 programs, 156 of its 2 682 compute +//! programs). Their HLSL differs only in those literals, so DXC and the driver compile each one +//! again, and the driver compile is the slow part (13 such repeats were 253 s of the 1 327 s a +//! cold run spent in the driver). Lifting the literals that differ inside a family into dwords +//! of `io` after the SGPRs (`IO_LIFTED`) makes the HLSL of every member the same text, so the +//! existing keys share one DXC result (by its text) and one driver blob (by its DXIL). +//! +//! - The families are found when a pack is prepared (`build_families`): programs whose +//! instruction sequence is the same (`family_key`, cheap) are translated, and those whose HLSL +//! is the same once every literal is masked (`masked_hash`) form a family. The literal +//! positions that differ inside it are what gets lifted (`varying`), nothing else, so the +//! other constants stay folded. +//! - Only `u`-suffixed integer literals in plain statements of `main`'s body are lifted +//! (`scan`): never in attributes, declarations, control-flow lines, preprocessor lines, inside +//! `[]`, or lines with texture offsets or quad operations, where HLSL needs a constant. A +//! family with a differing literal anywhere else is not lifted. +//! - A lifted literal reads the same 32-bit value from `io` that the literal had, as a `uint` +//! like the literal, so the program computes the same thing: lifting is correct for any +//! program, the family only decides what is worth lifting. +//! - The table is kept next to the caches (`table_file`) under the translation cache identity, +//! so a later run of the same build (also with `XCL_PREPARE=0`) finds it. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, OnceLock, RwLock}; + +/// First `io` dword of a lifted program's values: right after the SGPRs. +pub const IO_LIFTED: usize = super::KERNEL_SGPRS; +/// Most literals one program gets lifted (a family needing more is left alone). +pub const LIFT_MAX: usize = 64; + +/// `XCL_LIFT_LITERALS=1`: families are found at preparation and their members lifted. +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_LIFT_LITERALS").is_ok_and(|v| v.trim() == "1")) +} + +/// A numeric token of the HLSL outside comments: its byte range, and whether it may be lifted. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Token { + pub start: usize, + pub end: usize, + pub liftable: bool, +} + +/// What `scan` finds: the numeric tokens, the byte ranges of comments, and where `main`'s body +/// starts (just after its `{`). +#[derive(Debug, Default)] +pub(crate) struct Scan { + pub tokens: Vec, + pub comments: Vec<(usize, usize)>, + pub body: Option, +} + +/// Line starts whose literals HLSL may need as constants, or that steer control flow. +const FIXED_STARTS: &[&str] = &[ + "#", "[", "for", "while", "do", "if", "else", "switch", "case", "default", "static", "const", "groupshared", "return", +]; +/// Line contents whose literals HLSL may need as constants (texture offsets, quad lanes). +const FIXED_PARTS: &[&str] = &["Sample", "Gather", "Quad", "int2(", "int3(", "int4(", "numthreads", "WaveSize"]; + +fn word_char(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' || c == b'.' +} + +/// The value of a `u`-suffixed decimal or hex literal that fits 32 bits. +pub(crate) fn uint_literal(text: &str) -> Option { + let digits = text.strip_suffix(['u', 'U'])?; + match digits.strip_prefix("0x").or_else(|| digits.strip_prefix("0X")) { + Some(hex) if !hex.is_empty() && hex.bytes().all(|c| c.is_ascii_hexdigit()) => u32::from_str_radix(hex, 16).ok(), + Some(_) => None, + None if !digits.is_empty() && digits.bytes().all(|c| c.is_ascii_digit()) => digits.parse().ok(), + None => None, + } +} + +/// Every numeric token of `src` outside comments and strings, in order. +pub(crate) fn scan(src: &str) -> Scan { + let b = src.as_bytes(); + let mut out = Scan::default(); + // main: 0 before, 1 in its signature, 2 in its body (`depth` braces deep), 3 after + let (mut main, mut depth, mut brackets) = (0u8, 0usize, 0usize); + let mut in_block = false; + let mut line_start = 0; + while line_start < b.len() { + let line_end = src[line_start..].find('\n').map_or(b.len(), |n| line_start + n + 1); + let line = &src[line_start..line_end]; + let trimmed = line.trim_start(); + if !in_block && main == 0 && trimmed.starts_with("void main(") { + main = 1; + } + let fixed_line = FIXED_STARTS.iter().any(|s| trimmed.starts_with(s)) || FIXED_PARTS.iter().any(|p| line.contains(p)); + let mut i = line_start; + while i < line_end { + let c = b[i]; + if in_block { + if src[i..].starts_with("*/") { + in_block = false; + out.comments.last_mut().unwrap().1 = i + 2; + i += 2; + } else { + i += 1; + } + continue; + } + if src[i..].starts_with("//") { + let end = if b[line_end - 1] == b'\n' { line_end - 1 } else { line_end }; + let end = if end > i && b[end - 1] == b'\r' { end - 1 } else { end }; + out.comments.push((i, end.max(i))); + i = line_end; + continue; + } + if src[i..].starts_with("/*") { + in_block = true; + out.comments.push((i, b.len())); + i += 2; + continue; + } + match c { + b'"' => { + // (HLSL has no escapes the emitter writes; a string ends at its quote) + i = src[i + 1..line_end].find('"').map_or(line_end, |n| i + n + 2); + continue; + } + b'{' if main == 1 => { + main = 2; + depth = 1; + out.body = Some(i + 1); + } + b'{' if main == 2 => depth += 1, + b'}' if main == 2 => { + depth -= 1; + if depth == 0 { + main = 3; + } + } + b'[' => brackets += 1, + b']' => brackets = brackets.saturating_sub(1), + b'0'..=b'9' if i == 0 || !word_char(b[i - 1]) => { + let mut end = i; + while end < line_end && word_char(b[end]) { + end += 1; + } + let liftable = main == 2 && !fixed_line && brackets == 0 && uint_literal(&src[i..end]).is_some(); + out.tokens.push(Token { start: i, end, liftable }); + i = end; + continue; + } + _ => {} + } + i += 1; + } + line_start = line_end; + } + out +} + +const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; +fn fnv(h: u64, bytes: &[u8]) -> u64 { + bytes.iter().fold(h, |h, &x| (h ^ x as u64).wrapping_mul(0x100_0000_01b3)) +} + +/// A hash of `src` without its comments and with every numeric token masked: programs with the +/// same one differ only in their literals. +pub(crate) fn masked_hash(src: &str) -> u64 { + let s = scan(src); + let mut cuts: Vec<(usize, usize, &[u8])> = s.comments.iter().map(|&(a, z)| (a, z, &b""[..])).collect(); + cuts.extend(s.tokens.iter().map(|t| (t.start, t.end, &b"#"[..]))); + cuts.sort_unstable_by_key(|c| c.0); + let (mut h, mut at) = (FNV_OFFSET, 0); + for (a, z, with) in cuts { + h = fnv(fnv(h, &src.as_bytes()[at..a]), with); + at = z; + } + fnv(h, &src.as_bytes()[at..]) +} + +/// The token positions that differ between the members of a family (HLSL with the same +/// `masked_hash`). None: nothing differs, too many differ, or one that differs is not liftable. +pub(crate) fn varying(members: &[&str]) -> Option> { + let scans: Vec = members.iter().map(|m| scan(m)).collect(); + let first = scans.first()?; + if scans.iter().any(|s| s.tokens.len() != first.tokens.len()) { + return None; + } + let text = |m: usize, k: usize| &members[m][scans[m].tokens[k].start..scans[m].tokens[k].end]; + let mut out = Vec::new(); + for k in 0..first.tokens.len() { + if (1..members.len()).any(|m| text(m, k) != text(0, k)) { + if !scans.iter().all(|s| s.tokens[k].liftable) { + return None; + } + out.push(k as u32); + } + } + (!out.is_empty() && out.len() <= LIFT_MAX).then_some(out) +} + +/// `src` with the tokens at `positions` read from `io` (`IO_LIFTED` onwards) and without its +/// comments (they differ between members: the lifted text of a family is then one text), and +/// the values those tokens had, in order. None: a position is not a liftable token, or the +/// program has no `main` body or `io` buffer. +pub(crate) fn rewrite(src: &str, positions: &[u32]) -> Option<(String, Vec)> { + if positions.is_empty() || positions.len() > LIFT_MAX || src.contains("xcl_lift") || !src.contains("RWByteAddressBuffer io ") { + return None; + } + let s = scan(src); + let body = s.body?; + let mut cuts: Vec<(usize, usize, String)> = s.comments.iter().map(|&(a, z)| (a, z, String::new())).collect(); + let mut values = Vec::with_capacity(positions.len()); + for (i, &p) in positions.iter().enumerate() { + let t = *s.tokens.get(p as usize)?; + if !t.liftable || t.start < body { + return None; + } + values.push(uint_literal(&src[t.start..t.end])?); + cuts.push((t.start, t.end, format!("xcl_lift{i}"))); + } + let loads: String = (0..positions.len()).map(|i| format!("\n uint xcl_lift{i} = io.Load({}u);", 4 * (IO_LIFTED + i))).collect(); + cuts.push((body, body, loads)); + cuts.sort_by_key(|c| (c.0, c.1)); + let mut out = String::with_capacity(src.len() + 64 * positions.len()); + let mut at = 0; + for (a, z, with) in cuts { + if a < at { + return None; + } + out.push_str(&src[at..a]); + out.push_str(&with); + at = z; + } + out.push_str(&src[at..]); + Some((out, values)) +} + +/// A cheap key of a compute program's instruction sequence (the instructions without their +/// operands): the members of a family share it, so only programs sharing it are translated to +/// find the families. None: not a compute program. +pub(crate) fn family_key(blob: &[u8]) -> Option { + super::pso::with_compute_code(blob, |code| { + let mut h = fnv(FNV_OFFSET, &(code.len() as u64).to_le_bytes()); + let mut off = 0; + while off + 4 <= code.len() { + match crate::gpu::rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + h = fnv(fnv(h, d.inst.name.as_bytes()), b" "); + off += d.len; + } + Err(_) => { + h = fnv(h, &code[off..off + 4]); + off += 4; + } + } + } + h + }) +} + +/// One lifted program in the table: the `masked_hash` of its HLSL and the positions to lift. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Entry { + pub masked: u64, + pub positions: Arc<[u32]>, +} + +/// (record hash, memory windows, split wave64) -> what to lift +type Table = HashMap<(u64, u32, bool), Entry>; + +fn table() -> &'static RwLock> { + static T: OnceLock>> = OnceLock::new(); + T.get_or_init(|| RwLock::new(None)) +} + +fn table_file() -> PathBuf { + super::dxc::cache_dir().join("lift").join(format!("{:016x}.txt", super::pso::translation_cache_identity())) +} + +pub(crate) fn format_table(t: &Table) -> String { + let mut lines: Vec = t + .iter() + .map(|((record, windows, split), e)| { + let p: Vec = e.positions.iter().map(|p| p.to_string()).collect(); + format!("{record:016x} {windows} {} {:016x} {}", *split as u8, e.masked, p.join(",")) + }) + .collect(); + lines.sort(); + lines.iter().map(|l| format!("{l}\n")).collect() +} + +pub(crate) fn parse_table(text: &str) -> Table { + text.lines() + .filter_map(|l| { + let mut f = l.split_ascii_whitespace(); + let record = u64::from_str_radix(f.next()?, 16).ok()?; + let windows = f.next()?.parse().ok()?; + let split = f.next()? == "1"; + let masked = u64::from_str_radix(f.next()?, 16).ok()?; + let positions: Vec = f.next()?.split(',').map(|p| p.parse().ok()).collect::>()?; + (!positions.is_empty() && positions.len() <= LIFT_MAX && f.next().is_none()) + .then(|| ((record, windows, split), Entry { masked, positions: positions.into() })) + }) + .collect() +} + +/// What to lift in this program (`record`: its `fnv64`), from the table preparation built +/// (read from disk the first time). +pub(crate) fn lookup(record: u64, windows: u32, split: bool) -> Option { + if !enabled() { + return None; + } + if let Some(t) = table().read().unwrap().as_ref() { + return t.get(&(record, windows, split)).cloned(); + } + let mut t = table().write().unwrap(); + let t = t.get_or_insert_with(|| std::fs::read_to_string(table_file()).map(|s| parse_table(&s)).unwrap_or_default()); + t.get(&(record, windows, split)).cloned() +} + +/// The program's HLSL lifted as its family's entry says, and the values to write after its +/// SGPRs. None: not in a family, or its HLSL is not the one the table was made from. +pub(crate) fn apply(blob: &[u8], windows: u32, split: bool, hlsl: &str) -> Option<(String, Vec)> { + let e = lookup(crate::gpu::shader::fnv64(blob), windows, split)?; + if masked_hash(hlsl) != e.masked { + return None; + } + rewrite(hlsl, &e.positions) +} + +/// Find the families among the compute programs `get` gives (`n` of them, translated for +/// `windows` / `split` as the title's pipelines are) and keep what to lift for each member, +/// in memory and next to the caches. Returns (families, programs lifted). +pub fn build_families(n: usize, get: impl Fn(usize) -> Option> + Sync, windows: u32, split: bool) -> (usize, usize) { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + let next = AtomicUsize::new(0); + let keys: Mutex>> = Mutex::new(HashMap::new()); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= n { + break; + } + if let Some(k) = get(i).and_then(|b| family_key(&b)) { + keys.lock().unwrap().entry(k).or_default().push(i); + } + }); + } + }); + let candidates: Vec = keys.into_inner().unwrap().into_values().filter(|v| v.len() > 1).flatten().collect(); + // the candidates' HLSL, grouped by its masked hash (translation as `console_to_dxil_in`) + let next = AtomicUsize::new(0); + let groups: Mutex>> = Mutex::new(HashMap::new()); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(&at) = candidates.get(i) else { break }; + let Some(blob) = get(at) else { continue }; + if let Ok((t, _)) = super::pso::console_translation(&blob, super::pso::Stage::Compute, 0, windows, split, false) { + groups.lock().unwrap().entry(masked_hash(&t.hlsl)).or_default().push((crate::gpu::shader::fnv64(&blob), t.hlsl)); + } + }); + } + }); + let mut found = Table::new(); + let mut families = 0; + for (masked, members) in groups.into_inner().unwrap() { + let texts: Vec<&str> = members.iter().map(|m| m.1.as_str()).collect(); + if members.len() < 2 { + continue; + } + let Some(positions) = varying(&texts) else { continue }; + families += 1; + let positions: Arc<[u32]> = positions.into(); + for (record, _) in &members { + found.insert((*record, windows, split), Entry { masked, positions: positions.clone() }); + } + } + let lifted = found.len(); + let mut t = table().write().unwrap(); + let t = t.get_or_insert_with(|| std::fs::read_to_string(table_file()).map(|s| parse_table(&s)).unwrap_or_default()); + t.retain(|k, _| k.1 != windows || k.2 != split); + t.extend(found); + let path = table_file(); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Err(e) = std::fs::write(&path, format_table(t)) { + crate::xlog_warn!("[SHADER] literal lifting: could not write {}: {e}", path.display()); + } + (families, lifted) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PROGRAM: &str = "RWByteAddressBuffer io : register(u0);\n\ + uint f(uint x) { return x + 7u; }\n\ + [numthreads(64, 1, 1)]\n\ + void main(uint3 gid : SV_GroupID) {\n\ + \x20 // 0000: v_nop ; lit 0x3f018182\n\ + \x20 uint t3 = 0x3F018182u;\n\ + \x20 uint s12 = io.Load(48u) + 20u; /* offset */\n\ + \x20 if (s12 == 5u) { t3 = 1u; }\n\ + \x20 uint a[4]; a[2u] = t3;\n\ + \x20 io.Store(0u, t3 + s12 + f(a[2u]) + asuint(1.5f));\n\ + }\n"; + + fn texts(src: &str) -> Vec<(&str, bool)> { + scan(src).tokens.iter().map(|t| (&src[t.start..t.end], t.liftable)).collect() + } + + #[test] + fn only_plain_uint_literals_of_mains_body_are_liftable() { + let t = texts(PROGRAM); + let liftable: Vec<&str> = t.iter().filter(|t| t.1).map(|t| t.0).collect(); + // not: the helper's 7u, numthreads, the comment, the `if` line, `[2u]`, 1.5f + assert_eq!(liftable, ["0x3F018182u", "48u", "20u", "0u"]); + assert!(t.contains(&("7u", false)) && t.contains(&("5u", false)) && t.contains(&("2u", false)) && t.contains(&("1.5f", false))); + assert!(!t.iter().any(|t| t.0 == "0000" || t.0 == "0x3f018182"), "comments are not scanned: {t:?}"); + } + + #[test] + fn uint_literals_parse_only_with_their_suffix_and_within_32_bits() { + assert_eq!(uint_literal("0x3F018182u"), Some(0x3F01_8182)); + assert_eq!(uint_literal("20U"), Some(20)); + assert_eq!(uint_literal("4294967295u"), Some(u32::MAX)); + for no in ["4294967296u", "20", "0xu", "1.5f", "0x1g2u", "u"] { + assert_eq!(uint_literal(no), None, "{no}"); + } + } + + #[test] + fn the_masked_hash_ignores_comments_and_literal_values_but_not_code() { + let other = PROGRAM.replace("0x3F018182u", "0x3B808081u").replace("lit 0x3f018182", "lit 0x3b808081").replace("+ 20u", "+ 40u"); + assert_eq!(masked_hash(PROGRAM), masked_hash(&other)); + assert_ne!(masked_hash(PROGRAM), masked_hash(&PROGRAM.replace("+ 20u", "- 20u"))); + assert_ne!(masked_hash(PROGRAM), masked_hash(&PROGRAM.replace("t3 + s12", "t3 * s12"))); + } + + #[test] + fn a_family_lifts_only_the_positions_that_differ() { + let other = PROGRAM.replace("0x3F018182u", "0x3B808081u").replace("+ 20u", "+ 40u"); + let p = varying(&[PROGRAM, &other]).unwrap(); + let t = scan(PROGRAM).tokens; + let lifted: Vec<&str> = p.iter().map(|&k| &PROGRAM[t[k as usize].start..t[k as usize].end]).collect(); + assert_eq!(lifted, ["0x3F018182u", "20u"]); + // identical programs: nothing to lift; a differing literal on an `if` line: not lifted + assert_eq!(varying(&[PROGRAM, PROGRAM]), None); + assert_eq!(varying(&[PROGRAM, &PROGRAM.replace("== 5u", "== 6u")]), None); + assert_eq!(varying(&[PROGRAM, &PROGRAM.replace("return x + 7u", "return x + 8u")]), None); + } + + #[test] + fn the_members_of_a_family_become_one_text_with_their_own_values() { + let other = PROGRAM.replace("0x3F018182u", "0x3B808081u").replace("lit 0x3f018182", "lit 0x3b808081").replace("+ 20u", "+ 40u"); + let p = varying(&[PROGRAM, &other]).unwrap(); + let (a, va) = rewrite(PROGRAM, &p).unwrap(); + let (b, vb) = rewrite(&other, &p).unwrap(); + assert_eq!(a, b); + assert_eq!((va, vb), (vec![0x3F01_8182, 20], vec![0x3B80_8081, 40])); + assert!(a.contains(&format!("uint xcl_lift0 = io.Load({}u);", 4 * IO_LIFTED)), "{a}"); + assert!(a.contains("uint t3 = xcl_lift0;") && a.contains("io.Load(48u) + xcl_lift1;"), "{a}"); + assert!(!a.contains("//") && !a.contains("/*"), "comments dropped: {a}"); + // the loads come first in main's body, before any use + assert!(a.find("xcl_lift0 = ").unwrap() < a.find("t3 = xcl_lift0").unwrap()); + } + + #[test] + fn a_position_that_is_not_liftable_or_missing_refuses_the_rewrite() { + let t = scan(PROGRAM).tokens; + let fixed = t.iter().position(|t| !t.liftable).unwrap() as u32; + assert_eq!(rewrite(PROGRAM, &[fixed]), None); + assert_eq!(rewrite(PROGRAM, &[t.len() as u32]), None); + assert_eq!(rewrite(PROGRAM, &[]), None); + assert_eq!(rewrite(&PROGRAM.replace("RWByteAddressBuffer io ", "RWByteAddressBuffer jo "), &[0]), None); + } + + /// `XCL_SAMPLE_LIFT_HLSL=` (`xcl shaders --export-hlsl` of a title's pack): the + /// families among its programs under 256 KB (the smallest `XCL_SAMPLE_LIFT_FAMILIES`, 8 by + /// default) compile lifted to one DXIL container each. Does nothing when unset. + #[test] + fn sample_families_compile_lifted_to_one_container() { + let Some(dir) = std::env::var_os("XCL_SAMPLE_LIFT_HLSL") else { return }; + let most: usize = std::env::var("XCL_SAMPLE_LIFT_FAMILIES").ok().and_then(|v| v.parse().ok()).unwrap_or(8); + let mut groups: HashMap> = HashMap::new(); + for e in std::fs::read_dir(dir).unwrap().flatten() { + if e.metadata().is_ok_and(|m| m.len() < 256 << 10) { + let text = std::fs::read_to_string(e.path()).unwrap(); + groups.entry(masked_hash(&text)).or_default().push(text); + } + } + let mut families: Vec<(Vec, Vec)> = groups + .into_values() + .filter_map(|mut g| { + g.sort(); + g.dedup_by(|a, b| scan(a).tokens.iter().zip(scan(b).tokens.iter()).all(|(x, y)| a[x.start..x.end] == b[y.start..y.end])); + let texts: Vec<&str> = g.iter().map(String::as_str).collect(); + let p = (g.len() > 1).then(|| varying(&texts)).flatten()?; + Some((g, p)) + }) + .collect(); + families.sort_by_key(|f| f.0[0].len()); + println!("{} liftable families under 256 KB", families.len()); + for (members, positions) in families.iter().take(most) { + let dxil: Vec> = members + .iter() + .map(|m| { + let (text, _) = rewrite(m, positions).unwrap(); + super::super::dxc::compile(&text, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")) + }) + .collect(); + println!("family of {} ({} KB, {} lifted): {} B DXIL", members.len(), members[0].len() >> 10, positions.len(), dxil[0].len()); + assert!(dxil.iter().all(|d| *d == dxil[0]), "one container for the family"); + } + } + + #[test] + fn the_table_survives_its_text_form() { + let mut t = Table::new(); + t.insert((0xb162_ea7d_b32e_1657, 4, true), Entry { masked: 0x1234, positions: vec![3, 17, 40].into() }); + t.insert((0x0ed9_e58e_f6dc_9cdb, 1, false), Entry { masked: 0xffff_0000_ffff_0000, positions: vec![0].into() }); + assert_eq!(parse_table(&format_table(&t)), t); + // damaged lines are dropped, not guessed + assert!(parse_table("zz 4 1 0 1\n0000000000000001 4 1 0 \n0000000000000001 4 1 0 1,x\n").is_empty()); + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 8452602e8a..3fa99cd2dd 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -55,6 +55,7 @@ pub mod cfg; pub mod dxc; pub mod dxil; pub mod lane_masks; +pub mod lift; pub mod lower; pub mod lower_dxil; pub(crate) mod emit; diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 69a926ee0b..f2ce19ec74 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -209,6 +209,9 @@ pub struct Compiled { pub dxil: Vec, pub samplers: Vec, pub dispatch_remap: Option<(u32, u32)>, + /// a lifted compute program's literals (`lift`): its dispatches write them to `io` from + /// `lift::IO_LIFTED` on. Empty for any other program. + pub lifted: Vec, } /// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static @@ -264,6 +267,11 @@ fn console_to_dxil_in_with(blob: &[u8], stage: Stage, sampler_base: u32, split_w rt32_mask, cache_dir: dxc::cache_dir(), }; + // a member of a literal family (`lift`) is translated again rather than read from the disk + // cache, which keeps no lifted values (an entry stored without lifting would stay unlifted) + if stage == Stage::Compute && super::lift::lookup(key.hash, windows, split_wave64).is_some() { + return cached_shader(shader_cache(), key, blob, || compile_one().map(|(c, _)| c)).map(|shader| shader.as_ref().clone()); + } // with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag, // direct translator version, routing mode): never mixed with the HLSL path's entries let from_disk = || translated::cached_for(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, rt32_mask, compile_one); @@ -452,7 +460,7 @@ mod translated { let start = b.len() - len; b.copy_within(start.., 0); b.truncate(len); - return Some(Compiled { dxil: b, samplers, dispatch_chain: None, dispatch_remap }); + return Some(Compiled { lifted: Vec::new(), dxil: b, samplers, dispatch_chain: None, dispatch_remap }); } else { let dwords_per_group = u32_(&mut rest)?; let count = u32_(&mut rest)?; @@ -469,7 +477,7 @@ mod translated { if !rest.is_empty() { return None; } Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { dwords_per_group, pieces })) }; - Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain, dispatch_remap }) + Some(Compiled { lifted: Vec::new(), dxil: whole.to_vec(), samplers, dispatch_chain, dispatch_remap }) } pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { @@ -872,11 +880,22 @@ 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; + // a member of a literal family: the family's one text, with this member's literals in `io` + // (if DXC refuses it, the program as it is) + let lifted = (stage == Stage::Compute && cs_subs.is_none()).then(|| super::lift::apply(blob, windows, split_wave64, &t.hlsl)).flatten(); + let (dxil, lifted) = match lifted.map(|(text, values)| (dxc::compile_cached(&text, "main", profile), values)) { + Some((Ok((dxil, ..)), values)) => (dxil, values), + other => { + if let Some((Err(e), _)) = other { + crate::xlog_warn!("[SHADER] {:016x}: lifted literals do not compile, translated as it is: {}", crate::gpu::shader::fnv64(blob), e.lines().next().unwrap_or("")); + } + (dxc::compile_cached(&t.hlsl, "main", profile)?.0, Vec::new()) + } + }; if stage == Stage::Compute { - note_compute_path(blob, if cs_subs.is_some() { "HLSL, with XCL_DEBUG_CS_SUB" } else { "HLSL" }); + note_compute_path(blob, if cs_subs.is_some() { "HLSL, with XCL_DEBUG_CS_SUB" } else if lifted.is_empty() { "HLSL" } else { "HLSL, literals lifted" }); } - Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: t.dispatch_remap }, false)) + Ok((Compiled { lifted, dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: t.dispatch_remap }, false)) } /// `XCL_DEBUG_PS_SUB` / `XCL_DEBUG_CS_SUB` = `hash:from=>to||from=>to…` (a dump hash, hex): the @@ -1299,7 +1318,7 @@ pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); + return Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); } Err(e) => { let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); @@ -1309,7 +1328,7 @@ pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split } let k = crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata)?; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) + Ok(Compiled { lifted: Vec::new(), dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) } /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's @@ -1346,7 +1365,19 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, s }; let k = crate::gpu::dxil::kernel::translate_entry_rodata_rt32(code, o, entry, &f.rodata(p), if stage == Stage::Pixel { rt32_mask } else { 0 })?; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) + Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) +} + +/// `f` of a compute program's code (its FSPX code or its compute variant's first program). +/// None: not a compute program. +pub(crate) fn with_compute_code(blob: &[u8], f: impl FnOnce(&[u8]) -> R) -> Option { + if let Some(x) = fspx(blob) { + return Some(f(x.code)); + } + let sh = xbox::parse(blob)?; + let v = sh.fssm.iter().find(|v| v.stages.first().is_some_and(|s| s.hw == 6))?; + let p = v.programs.first()?; + Some(f(v.data.get(p.offset..p.offset + p.len)?)) } pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, no_remap: bool) -> Result<(super::Translation, &'static str), String> { @@ -1425,7 +1456,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option return Err(format!("incomplete translation, missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers, dispatch_remap: None }, record, ps) + finish_two_pass_compiled(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: cs, samplers: t.static_samplers, dispatch_remap: None }, record, ps) } fn compile_console_mesh( @@ -1452,7 +1483,7 @@ fn compile_console_mesh( Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); + return Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); } Err(e) => direct_fallback("MS", &e), } @@ -1463,7 +1494,7 @@ fn compile_console_mesh( return Err(format!("incomplete translation, missing: {missing:?}")); } let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: None }) + Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: None }) } fn console_mesh_with( @@ -2030,7 +2061,7 @@ mod shader_cache_tests { fn translations_on_disk_need_the_same_bytes_and_identity() { let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id())); let path = dir.join("t.bin"); - let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)], dispatch_remap: Some((2, 1)) }; + let c = Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)], dispatch_remap: Some((2, 1)) }; translated::store_in(&path, 42, b"console", &c); let back = translated::load_in(&path, 42, b"console").expect("stored"); assert_eq!((back.dxil, back.samplers, back.dispatch_remap), (c.dxil.clone(), c.samplers.clone(), c.dispatch_remap)); @@ -2276,7 +2307,7 @@ mod shader_cache_tests { // Store a valid entry first, then corrupt only the DXIL payload while keeping the // XCLTRAN2 header and payload length intact (e.g. zeroed blocks after a hard reset). - let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)], dispatch_remap: None }; + let valid = Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)], dispatch_remap: None }; translated::store_in(&path, ident, blob, &valid); let mut raw = std::fs::read(&path).unwrap(); let dxil_start = raw.len() - valid.dxil.len(); @@ -2295,7 +2326,7 @@ mod shader_cache_tests { let mut calls = 0usize; let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { calls += 1; - Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)], dispatch_remap: None }) + Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)], dispatch_remap: None }) }) .unwrap(); assert_eq!(calls, 1); @@ -2319,20 +2350,20 @@ mod shader_cache_tests { let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false); let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None }) + Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None }) }) .err() .expect("invalid fresh DXIL must be rejected"); assert!(err.contains("invalid DXIL container"), "{err}"); assert!(!path.exists(), "invalid fresh DXIL must not be written to disk"); - translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None }); + translated::store_in(&path, ident, blob, &Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None }); assert!(!path.exists(), "store_in must not write an invalid DXIL container"); // A real container emitted by the direct DXIL backend must be accepted and cached. let real_direct = crate::gpu::dxil::shader::Shader::new(crate::gpu::dxil::container::Stage::Compute, (6, 6)).finish([1, 1, 1], None); let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new(), dispatch_remap: None }) + Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new(), dispatch_remap: None }) }) .unwrap(); assert_eq!(stored.dxil, real_direct); @@ -2346,6 +2377,7 @@ mod shader_cache_tests { fn compiled(marker: u8) -> Compiled { Compiled { + lifted: Vec::new(), dispatch_chain: None, dxil: synthetic_dxil(marker), samplers: vec![([marker as u32; 4], false)], @@ -2488,6 +2520,7 @@ mod shader_cache_tests { cached_shader(&cache, key(1), b"a", || { let dxil = dxc::compile_cached_in(&dir, "probe", "main", "cs_6_6")?.0; Ok(Compiled { + lifted: Vec::new(), dispatch_chain: None, dxil, samplers: Vec::new(), @@ -2523,6 +2556,7 @@ mod shader_cache_tests { key(4), b"d", Arc::new(Compiled { + lifted: Vec::new(), dispatch_chain: None, dxil: vec![0; limit + 1], samplers: Vec::new(), @@ -2728,6 +2762,7 @@ mod shader_cache_tests { let dxil = dxc::compile_cached_in(&dir, "pending probe", "main", "cs_6_6")?.0; Ok(Compiled { + lifted: Vec::new(), dispatch_chain: None, dxil, samplers: Vec::new(), @@ -2820,7 +2855,7 @@ mod shader_cache_tests { let (res, missed) = dxc::cached_only(|| { translated::cached_in(&dir, ident_v1, deferred_blob, Stage::Compute, 0, 1, false, || { let dxil = dxc::compile_cached_in(&dir, "deferred probe", "main", "cs_6_6")?.0; - Ok(Compiled { dxil, samplers: Vec::new(), dispatch_chain: None, dispatch_remap: None }) + Ok(Compiled { lifted: Vec::new(), dxil, samplers: Vec::new(), dispatch_chain: None, dispatch_remap: None }) }) }); assert!(res.is_err() && missed); @@ -2968,7 +3003,7 @@ mod direct_probe_tests { let cache = Mutex::new(ShaderCache::new(1 << 20)); let k0 = ShaderKey { hash: 99, stage: Stage::Pixel, sampler_base: 0, windows: 1, split_wave64: false, rt32_mask: 0, cache_dir: "cache".into() }; let k1 = ShaderKey { rt32_mask: 1 << 1, ..k0.clone() }; - let mk = |m: u8| Compiled { dispatch_chain: None, dxil: vec![m; 68], samplers: Vec::new(), dispatch_remap: None }; + let mk = |m: u8| Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: vec![m; 68], samplers: Vec::new(), dispatch_remap: None }; let a = cached_shader(&cache, k0, blob, || Ok(mk(1))).unwrap(); let b = cached_shader(&cache, k1, blob, || Ok(mk(2))).unwrap(); assert!(!Arc::ptr_eq(&a, &b)); diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index bdebc51704..916387b662 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1825,7 +1825,8 @@ fn dispatch_with( chain: Option<(&[ID3D12PipelineState], u32, u64)>, ) -> Result<(Vec, Vec), String> { let mut io = sgprs.to_vec(); - io.resize(KERNEL_SGPRS, 0); + // (more than the SGPRs: a lifted program's literals after them, `lift::IO_LIFTED`) + io.resize(io.len().max(KERNEL_SGPRS), 0); let mem_len = mem.len().max(64); unsafe { let (io_bytes, mem_bytes) = ((io.len() * 4) as u64, (mem_len * 4) as u64); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index c0faf78b0c..201a4f4619 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -12422,3 +12422,51 @@ fn geometry_padding_before_gs_start_keeps_its_entry() { assert!(t.hlsl.contains(&format!("if (pc == {s}u)")), "split {split}: {}", t.hlsl); } } + +/// Two programs that differ only in their literals (`lift`): lifted, they are one HLSL text and +/// one DXIL container, and each gives on the GPU what it gives as it is, with its own literals +/// in `io` after the SGPRs. +#[test] +fn gpu_lifted_literal_family_shares_dxil_and_keeps_results() { + if !gpu_ready() { + return; + } + use super::{dxc, lift, CsInterface}; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let program = |a: u32, b: u32| prog(&[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 0)], None), // lane · 4 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 0), ("VSRC1", 2)], None), // + output base + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 255)], Some(a)), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 255), ("VSRC1", 4)], Some(b)), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 4)], None), // + lane + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)], None), + ]); + let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); + let members = [(0x3F01_8182u32, 0x0000_1234u32), (0x3B80_8081, 0x00AB_0000)]; + let hlsl: Vec = members.iter().map(|&(a, b)| { + let t = translate(&program(a, b), &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + t.hlsl + }).collect(); + assert_eq!(lift::masked_hash(&hlsl[0]), lift::masked_hash(&hlsl[1]), "one family"); + let positions = lift::varying(&[&hlsl[0], &hlsl[1]]).unwrap_or_else(|| panic!("nothing liftable in:\n{}", hlsl[0])); + let lifted: Vec<(String, Vec)> = hlsl.iter().map(|h| lift::rewrite(h, &positions).unwrap()).collect(); + assert_eq!(lifted[0].0, lifted[1].0, "one text"); + let shared = dxc::compile(&lifted[0].0, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", lifted[0].0)); + assert_eq!(shared, dxc::compile(&lifted[1].0, "main", "cs_6_6", &[]).unwrap(), "one DXIL container"); + let base = 0x100usize; + for (k, &(a, b)) in members.iter().enumerate() { + let plain = dxc::compile(&hlsl[k], "main", "cs_6_6", &[]).unwrap(); + let mut io = vec![0u32; lift::IO_LIFTED]; + io[0] = base as u32; + let as_is = runner::dispatch(&plain, [1, 1, 1], &io, &vec![0u32; base / 4 + 64]).unwrap(); + io.extend_from_slice(&lifted[k].1); + let out = runner::dispatch(&shared, [1, 1, 1], &io, &vec![0u32; base / 4 + 64]).unwrap(); + for lane in 0..64 { + let at = base / 4 + lane; + assert_eq!(as_is[at], (a ^ b).wrapping_add(lane as u32), "member {k}, lane {lane}: as it is"); + assert_eq!(out[at], as_is[at], "member {k}, lane {lane}: lifted"); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7938495b9f..3428737eed 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -5152,6 +5152,7 @@ fn prepare_abi_state( u: &crate::gpu::uma::Uma, gfx: bool, user_sgprs: Option, + lifted: usize, ) -> Result { // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let full = |asked: usize| { @@ -5171,7 +5172,8 @@ fn prepare_abi_state( let table_bytes = (args.len() - inline).max(16); let table_at = state.arena.take(u, table_bytes, 256, &mut state.uma) .ok_or_else(|| full(table_bytes))? as usize; - let io_bytes = crate::gpu::recomp::KERNEL_SGPRS * std::mem::size_of::(); + // (a lifted program's literals follow the SGPRs: `recomp::lift::IO_LIFTED`) + let io_bytes = (crate::gpu::recomp::KERNEL_SGPRS + lifted) * std::mem::size_of::(); let io_at = state.arena.take(u, io_bytes, 256, &mut state.uma).ok_or_else(|| full(io_bytes))? as usize; let res_at = state.arena.take(u, 256, 256, &mut state.uma).ok_or_else(|| full(256))? as usize; Ok(PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator: state.allocator, heaps: state.heaps }) @@ -5251,14 +5253,16 @@ unsafe fn bind_abi_with_root_resolved( let first = first_window(super::real::uma_window_va(0), u.shadowed())?; // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs_exact(pso) }; - let prepared = prepare_abi_state(this, u, gfx, user_sgprs)?; + let lifted = if gfx { None } else { super::real::pso_lifted_exact(pso) }; + let prepared = prepare_abi_state(this, u, gfx, user_sgprs, lifted.as_ref().map_or(0, |l| l.len()))?; let PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator, heaps } = prepared; want_root_views(layout.as_deref(), &args, super::view_want::Path::RootView); if super::placements::any_superseded() { note_superseded_in_tables(u, layout.as_deref(), &args); } std::ptr::copy_nonoverlapping(args[inline..].as_ptr(), table_at as *mut u8, args.len() - inline); - let io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); + let mut io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); + io.extend_from_slice(lifted.as_deref().unwrap_or(&[])); let io_bytes = io.iter().flat_map(|word| word.to_le_bytes()).collect::>(); std::ptr::copy_nonoverlapping(io_bytes.as_ptr(), io_at as *mut u8, io_bytes.len()); std::ptr::write_bytes(res_at as *mut u8, 0, 256); @@ -7002,7 +7006,7 @@ void main(uint t : SV_GroupIndex) { state.allocator = 0x7301_1000; }); - let prepared = prepare_abi_state(list, &u, false, None).unwrap(); + let prepared = prepare_abi_state(list, &u, false, None, 0).unwrap(); assert!(Arc::ptr_eq(prepared.layout.as_ref().unwrap(), &layout)); assert_eq!(prepared.args, args); assert_eq!(prepared.inline, 4); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index ea46fa0e61..ea9e287b64 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -1061,6 +1061,8 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`) let (limit, folded) = super::bind::fold(x, y, z); io[crate::gpu::recomp::IO_GROUP_LIMIT] = limit; + // a lifted program's literals after the SGPRs (`recomp::lift::IO_LIFTED`) + io.extend_from_slice(super::real::pso_lifted_exact(real).as_deref().unwrap_or(&[])); let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?; let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?; // the pipeline's own root signature when it has static samplers diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6fcaf053c6..a89b568ab1 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2731,6 +2731,7 @@ fn forget_pso(pso: usize) { m.remove(&pso); } PSO_DISPATCH_REMAP.remove(pso); + PSO_LIFTED.remove(pso); remap_fallback::forget(pso); super::device_x::forget_base(pso); // the compute pass goes with the last user of its entry (`Drop for TwoPassPso`) @@ -5205,6 +5206,8 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { /// user SGPRs and the console's `numthreads` of the console CS of a translated compute pipeline static PSO_USER_SGPRS: Sharded<(u32, [u32; 3])> = Sharded::new(); static PSO_DISPATCH_REMAP: Sharded<(u32, u32)> = Sharded::new(); +/// the literals of a translated compute pipeline whose program has them lifted (`recomp::lift`) +static PSO_LIFTED: Sharded> = Sharded::new(); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). @@ -5251,6 +5254,23 @@ pub(super) fn pso_dispatch_remap_exact(pso: usize) -> Option<(u32, u32)> { PSO_DISPATCH_REMAP.get(pso) } +/// The literals a translated compute pipeline's dispatches write to `io` from +/// `recomp::lift::IO_LIFTED` on (None: its program has none lifted). +pub(super) fn pso_lifted_exact(pso: usize) -> Option> { + PSO_LIFTED.get(pso) +} + +fn note_pso_lifted(pso: *mut c_void, lifted: &[u32]) { + if pso.is_null() { + return; + } + if lifted.is_empty() { + PSO_LIFTED.remove(pso as usize); + } else { + PSO_LIFTED.insert(pso as usize, lifted.into()); + } +} + fn note_pso_dispatch_remap(pso: *mut c_void, remap: Option<(u32, u32)>) { if pso.is_null() { return; @@ -6099,6 +6119,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const PSO_USER_SGPRS.insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_pso_dispatch_remap(*ppv, compiled.dispatch_remap); + note_pso_lifted(*ppv, &compiled.lifted); remap_fallback::note(*ppv as usize, this, f, rs as usize, &compiled.samplers, d.Flags, d.NodeMask, record, cs, wave32_only(this), crate::gpu::recomp::pso::mem_windows(), compiled.dispatch_remap.is_some()); note_translated_compute(hr, ppv); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index acb63727b5..5b36e6994c 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1996,7 +1996,7 @@ mod pipeline_cap_tests { pipelines.max_dxil = dxil.len() - 1; let start = Instant::now(); - pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![], dispatch_remap: None }, Some(path.clone())); + pipelines.make_with_cache_path(&recomp::pso::Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: dxil.clone(), samplers: vec![], dispatch_remap: None }, Some(path.clone())); let elapsed = start.elapsed(); let capped = pipelines.capped.load(Ordering::Relaxed); let made = pipelines.made.load(Ordering::Relaxed); @@ -2037,7 +2037,7 @@ mod pipeline_cap_tests { std::fs::create_dir(&scratch.0).expect("scratch cache directory"); let hlsl = "RWByteAddressBuffer mem : register(u2); [numthreads(1,1,1)] void main() { mem.Store(0, 42); }"; let dxil = recomp::dxc::compile(hlsl, "main", "cs_6_6", &[]).expect("DXC compile"); - let compiled = recomp::pso::Compiled { dispatch_chain: None, dxil, samplers: vec![], dispatch_remap: None }; + let compiled = recomp::pso::Compiled { lifted: Vec::new(), dispatch_chain: None, dxil, samplers: vec![], dispatch_remap: None }; let path = scratch.0.join("padded.pso"); pipelines.make_with_cache_path(&compiled, Some(path.clone())); @@ -2135,6 +2135,7 @@ mod pipeline_cap_tests { .expect("whole DXC compile"); let max_piece = piece0.len().max(piece1.len()); let compiled = recomp::pso::Compiled { + lifted: Vec::new(), dispatch_chain: Some(Arc::new(crate::gpu::dxil::kernel::DispatchChain { pieces: vec![piece0.clone(), piece1.clone()], dwords_per_group: 4, @@ -2852,7 +2853,7 @@ mod pipeline_selection_tests { PipelineJob { used, prewarm_indirect: false, - compiled: recomp::pso::Compiled { dispatch_chain: None, dispatch_remap: None, dxil: vec![0; bytes], samplers: Vec::new() }, + compiled: recomp::pso::Compiled { lifted: Vec::new(), dispatch_chain: None, dispatch_remap: None, dxil: vec![0; bytes], samplers: Vec::new() }, } } @@ -3778,6 +3779,14 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); + // `XCL_LIFT_LITERALS=1`: the pack's literal families first, so their members compile lifted + if recomp::lift::enabled() { + let at = std::time::Instant::now(); + let (families, lifted) = recomp::lift::build_families(input.len(), |i| input.get(i).1, windows, split); + let line = format!("literal lifting: {families} families, {lifted} compute programs lifted ({:.1} s)", at.elapsed().as_secs_f64()); + crate::xlog_info!("[SHADER] {line}"); + println!("{line}"); + } std::thread::scope(|s| { for _ in 0..threads { s.spawn(|| loop {