From a59afc8dc572c6a7da8a1265f81267a44cf7b8c4 Mon Sep 17 00:00:00 2001 From: alox0099 Date: Sat, 28 Nov 2026 12:17:06 +0100 Subject: [PATCH] Recompiler: a program's HLSL has only the prelude functions it reaches Every translated program carried PRELUDE and PRELUDE_MEM whole: 91 helper functions, about 31 KB, of which a program calls a few. The DXIL cache is keyed on the HLSL, so a change to any one helper changed the key of every program and a title recompiled all of them: #587 (frexp_mant), #2334 (msad_u8, pk_sad_u16) and #2247 (rla) each did on the retail pack. finish() now puts placeholders where the two preludes go and replaces them with the globals and only the functions the program reaches: those named outside the two preludes and, in turn, those the kept functions name. A name counts wherever it appears as a word, so a stray match keeps a function it need not, never the other way round. DXC drops unreached functions, so the DXIL does not change. Measured on a retail shader pack (26 698 programs), main b49be18 against this commit: `xcl shaders --recomp` gives the same report (same programs translated, same refusals). 671 of its programs dumped by both (one in 40) and compiled with dxc.exe with the same flags: 671 / 671 byte-identical DXIL. Their HLSL is 6.6 % smaller (27.6 % for the 439 under 200 KB). Of those 671, frexp_mant and pk_sad_u16 are now in none (before: all 671) and rla in 487. Two pixel shaders drop below the 1 MiB line where XCL picks -O1, so DXC compiles them at -O3: 0.5 s more each, 0.2 - 1 % smaller DXIL. gpu_mad_nf_f16_rounds_intermediate_in_binary16 calls mad_nf_f16 in code it adds to a translation; it now adds the definitions with it (missing_prelude_functions, test only). Assisted-by: Claude Code (Claude Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/emit.rs | 165 ++++++++++++++++++++++++++++- crates/xcl/src/gpu/recomp/tests.rs | 4 + 2 files changed, 166 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 47fe4184b9..4611aad028 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5084,7 +5084,7 @@ impl Em { let ty = if *cmp { "SamplerComparisonState" } else { "SamplerState" }; let _ = writeln!(h, "{ty} xcl_ss{k} : register(s{k}, space1);"); } - h.push_str(PRELUDE); + h.push_str(PRELUDE_HERE); if body.contains(LOOP_CAP_INIT) { h.push_str("// loop passes one entry of a loop may run (`Em::loop_guard`) static uint xcl_cap = 1u << 16; @@ -5111,7 +5111,7 @@ static uint xcl_cap = 1u << 16; } let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); - h.push_str(PRELUDE_MEM); + h.push_str(PRELUDE_MEM_HERE); if self.uses_scratch { h.push_str(PRELUDE_SCRATCH); } @@ -5650,6 +5650,7 @@ static uint xcl_cap = 1u << 16; h.push_str(" return xo;\n}\n"); } } + h = with_preludes(&h); if windows > 1 { let coherent = if self.coherent_mem { "globallycoherent " } else { "" }; h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent)); @@ -6142,6 +6143,123 @@ fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String { out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap), 1) } +/// Placeholders where `PRELUDE` and `PRELUDE_MEM` go (`with_preludes`). +const PRELUDE_HERE: &str = "//XCL_PRELUDE\n"; +const PRELUDE_MEM_HERE: &str = "//XCL_PRELUDE_MEM\n"; + +/// `PRELUDE` and `PRELUDE_MEM` in place of their placeholders, with only the functions the +/// program reaches: those named outside the two preludes (the program, the other preludes, +/// the preludes' globals) and the ones those functions name in turn. A program keeps a few +/// of the ~90, so a change to one helper no longer changes the HLSL – and the DXIL cache key – +/// of every program, only of those that use it. Unreached functions are only text to DXC, +/// which drops them, so the DXIL does not change. A name is matched as a whole word anywhere, +/// comments included: a stray match keeps a function it need not. +fn with_preludes(h: &str) -> String { + let items: Vec<(Option<&str>, &str)> = prelude_items(PRELUDE).into_iter().chain(prelude_items(PRELUDE_MEM)).collect(); + let mut roots = vec![h]; + roots.extend(items.iter().filter(|i| i.0.is_none()).map(|i| i.1)); + let kept = reached(&items, &roots); + let first = prelude_items(PRELUDE).len(); + let join = |range: std::ops::Range| -> String { range.filter(|&i| items[i].0.is_none() || kept[i]).map(|i| items[i].1).collect() }; + h.replacen(PRELUDE_HERE, &join(0..first), 1).replacen(PRELUDE_MEM_HERE, &join(first..items.len()), 1) +} + +/// Which of the prelude functions `items` the texts `roots` reach: named in them, or named by +/// a function reached. +fn reached(items: &[(Option<&str>, &str)], roots: &[&str]) -> Vec { + let mut by_name: std::collections::HashMap<&str, Vec> = std::collections::HashMap::new(); + for (i, (name, _)) in items.iter().enumerate() { + if let Some(n) = name { + by_name.entry(n).or_default().push(i); + } + } + let mut kept = vec![false; items.len()]; + let mut todo: Vec = Vec::new(); + let reach = |text: &str, kept: &mut Vec, todo: &mut Vec| { + for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) { + for &i in by_name.get(word).map(Vec::as_slice).unwrap_or(&[]) { + if !kept[i] { + kept[i] = true; + todo.push(i); + } + } + } + }; + for text in roots { + reach(text, &mut kept, &mut todo); + } + while let Some(i) = todo.pop() { + reach(items[i].1, &mut kept, &mut todo); + } + kept +} + +/// Tests that call prelude functions in code they add to a translation (`code`): the +/// definitions of the ones it reaches that `hlsl` does not have yet, in the preludes' order. +#[cfg(test)] +pub(super) fn missing_prelude_functions(hlsl: &str, code: &str) -> String { + let items: Vec<(Option<&str>, &str)> = prelude_items(PRELUDE).into_iter().chain(prelude_items(PRELUDE_MEM)).collect(); + let kept = reached(&items, &[code]); + items.iter().zip(kept).filter(|(i, k)| *k && !hlsl.contains(i.1)).map(|(i, _)| i.1).collect() +} + +/// A prelude's top-level pieces in order, which put together are the prelude again: a function +/// definition with the comment lines right above it (Some(its name)), or anything else (None: +/// globals, comments, blank lines). Braces in `//` comments are not counted. +fn prelude_items(p: &str) -> Vec<(Option<&str>, &str)> { + let mut items = Vec::new(); + let (mut start, mut comments) = (0usize, None::); + let mut at = 0usize; + let mut open: Option<(&str, usize, i32)> = None; + for line in p.split_inclusive('\n') { + let code = line.split("//").next().unwrap_or(""); + let depth = code.matches('{').count() as i32 - code.matches('}').count() as i32; + let end = at + line.len(); + if let Some((name, from, d)) = open { + let d = d + depth; + if d > 0 { + open = Some((name, from, d)); + } else { + items.push((Some(name), &p[from..end])); + (start, open) = (end, None); + } + } else if let Some(name) = function_name(code) { + let from = comments.unwrap_or(at); + if start < from { + items.push((None, &p[start..from])); + } + if depth > 0 { + open = Some((name, from, depth)); + } else { + items.push((Some(name), &p[from..end])); + start = end; + } + comments = None; + } else if line.trim_start().starts_with("//") { + comments.get_or_insert(at); + } else { + comments = None; + } + at = end; + } + if start < p.len() { + items.push((None, &p[start..])); + } + items +} + +/// The name of the function a top-level prelude line defines (`type name(… {`), if it is one. +fn function_name(code: &str) -> Option<&str> { + let (head, _) = code.split_once('(')?; + if !code.contains('{') || head.contains('=') || head.trim_start().starts_with("static ") { + return None; + } + let mut words = head.split_whitespace(); + let (_ty, name) = (words.next()?, words.next()?); + let is_ident = |s: &str| s.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + (words.next().is_none() && is_ident(name)).then_some(name) +} + /// The `mem` methods (and overloads) the translator emits: result, name, parameters, arguments, /// and what an access outside the windows does (the switch's `default`; its `break` leaves /// the accessor). @@ -7251,7 +7369,7 @@ uint fclass64(double f) { #[cfg(test)] mod tests { - use super::{mem_accessors, PRELUDE, PRELUDE_MEM}; + use super::{mem_accessors, prelude_items, with_preludes, PRELUDE, PRELUDE_HERE, PRELUDE_MEM, PRELUDE_MEM_HERE}; #[test] fn heap_window_loads_and_stores_use_null_descriptors_without_branches() { @@ -7265,6 +7383,47 @@ mod tests { assert!(!h.contains("xcl_mStore(uint a, uint v) { [branch]"), "ordinary store kept a divergent guard:\n{h}"); } + #[test] + fn the_preludes_split_into_their_functions_and_back() { + for p in [PRELUDE, PRELUDE_MEM] { + let items = prelude_items(p); + assert_eq!(items.iter().map(|i| i.1).collect::(), p); + // every braced block at the top level is a function: the rest has no braces + for (name, text) in &items { + let code: String = text.lines().map(|l| l.split("//").next().unwrap_or("")).collect(); + match name { + Some(n) => assert!(code.contains(&format!("{n}(")) && code.contains('{'), "{n}: {text}"), + None => assert!(!code.contains('{') && !code.contains('}'), "a block that is not a function:\n{text}"), + } + } + } + let names: Vec<_> = prelude_items(PRELUDE).into_iter().filter_map(|i| i.0).collect(); + for n in ["mul_hi_u32", "ballot", "rla", "cube_dir", "first_lane"] { + assert!(names.contains(&n), "{n} not found: {names:?}"); + } + } + + #[test] + fn a_program_gets_the_helpers_it_reaches_and_no_others() { + let h = format!("RWByteAddressBuffer io : register(u0);\n{PRELUDE_HERE}{PRELUDE_MEM_HERE}void main() {{ uint4 r = fmt_pack(uint4(0u, 0u, 0u, 0u), 0u); uint c = ballot(true).x; }}\n"); + let out = with_preludes(&h); + assert!(!out.contains(PRELUDE_HERE) && !out.contains(PRELUDE_MEM_HERE)); + // named by the program, and what they name in turn (fmt_pack: put_bits, fmt_encode) + for f in ["uint4 fmt_pack(", "uint2 ballot(", "put_bits(inout", "fmt_encode("] { + assert!(out.contains(f), "{f} missing:\n{out}"); + } + for f in ["uint rla(", "float3 cube_dir(", "uint mul_hi_u32("] { + assert!(!out.contains(f), "{f} kept although nothing reaches it"); + } + // the globals stay, and the comments above a function go with it + assert!(out.contains("static uint lane_id;") && out.contains("static bool xcl_w32 = false;")); + assert!(!out.contains("AMD cube coordinates")); + // a program that names everything gets the preludes whole + let all: String = prelude_items(PRELUDE).iter().chain(prelude_items(PRELUDE_MEM).iter()).filter_map(|i| i.0).map(|n| format!("{n}(); ")).collect(); + let whole = with_preludes(&format!("{PRELUDE_HERE}{PRELUDE_MEM_HERE}{all}")); + assert_eq!(whole, format!("{PRELUDE}{PRELUDE_MEM}{all}")); + } + #[test] fn format_helpers_select_uint4_components_without_runtime_indexing() { for indexed in ["r[i]", "r[i + 1u]", "c[(sel - 4u) & 3u]"] { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 6777b5a967..24683d7ecd 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -10642,6 +10642,10 @@ fn gpu_mad_nf_f16_rounds_intermediate_in_binary16() { let marker = " v0 = select((((exec_lo >> lane_id) & 1u) != 0u), (v0), v0);\n"; assert!(hlsl.contains(marker), "unexpected kernel body:\n{hlsl}"); hlsl = hlsl.replace(marker, probe); + // the translation has only the prelude functions its own code reaches + let helpers = super::emit::missing_prelude_functions(&hlsl, probe); + assert!(helpers.contains("float mad_nf_f16("), "{helpers}"); + hlsl = hlsl.replacen("[WaveSize(", &format!("{helpers}[WaveSize("), 1); let dxil = super::dxc::compile(&hlsl, "main", "cs_6_6", &[]).unwrap(); let mut st = KernelState::default();