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
295 changes: 288 additions & 7 deletions crates/xcl/src/gpu/recomp/dxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1117,19 +1117,156 @@ pub(super) fn toolchain_identity() -> &'static str {
})
}

/// FNV-1a 64 of the inputs that determine the DXIL.
/// Sources shorter than this are keyed without their comments and indentation
/// (`hash_code_lines`). Up to 1 MiB DXC gets no -O switch (`compile_with`, `link_opt_args`), so
/// two such sources with the same code lines get the same DXC arguments and the same DXIL; the
/// margin covers a linked program's declarations (`emit::linked_form`, a few KB) on top of its
/// source. Longer sources are keyed on their full text: their length, comments included, picks
/// the -O level.
const KEY_CODE_LINES_BELOW: usize = 1024 * 1024 - 64 * 1024;

/// The key of a program XCL generates (`compile_cached`): FNV-1a 64 of the inputs that determine
/// the DXIL. DXC still compiles the full `src`; the key leaves out what does not reach the DXIL,
/// so programs that differ only in their `// pc: instruction` comments (data words, other
/// offsets) share one compile. A source in which line numbers or line splices could reach the
/// DXIL (`code_lines_keyable`) keeps its full-text key.
fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str) -> u64 {
key_for_toolchain(src, entry, profile, toolchain, src.len() < KEY_CODE_LINES_BELOW && code_lines_keyable(src))
}

/// The key of any other source (`compile_cached_in`): its full text.
fn exact_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str) -> u64 {
key_for_toolchain(src, entry, profile, toolchain, false)
}

/// Whether leaving out comments, indentation and empty lines cannot change what DXC compiles:
/// - no `__LINE__` and no `#line` directive: removing a comment or empty line moves the lines
/// below it, and those give their line numbers to the code;
/// - no backslash before a line break, also with spaces or tabs between: DXC splices the next
/// line onto it, into a `//` comment that ends there (`// note\ ` goes on to the next line);
/// - no `??/` trigraph (a backslash where trigraphs are on).
fn code_lines_keyable(src: &str) -> bool {
if src.contains("__LINE__") || src.contains("??/") {
return false;
}
if src.lines().any(|l| l.trim_start().strip_prefix('#').is_some_and(|d| d.trim_start().starts_with("line"))) {
return false;
}
let b = src.as_bytes();
!b.iter().enumerate().any(|(i, &c)| {
c == b'\\' && {
let rest = b[i + 1..].iter().position(|&n| !matches!(n, b' ' | b'\t' | 0x0B | 0x0C));
rest.is_none_or(|n| matches!(b[i + 1 + n], b'\n' | b'\r'))
}
})
}

fn key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str, code_lines: bool) -> u64 {
let mut h = 0xcbf2_9ce4_8422_2325u64;
for part in [env!("CARGO_PKG_VERSION"), toolchain, profile, entry, src] {
for b in part.bytes().chain([0u8]) {
h ^= b as u64;
h = h.wrapping_mul(0x100_0000_01b3);
let parts: [&str; 4] = [env!("CARGO_PKG_VERSION"), toolchain, profile, entry];
let full = [src];
let tag = ["code lines"];
for part in parts.iter().chain(if code_lines { &tag[..] } else { &full[..] }) {
h = fnv_bytes(h, part.bytes().chain([0u8]));
}
if code_lines {
h = hash_code_lines(h, src);
}
h
}

fn fnv_bytes(mut h: u64, bytes: impl Iterator<Item = u8>) -> u64 {
for b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x100_0000_01b3);
}
h
}

/// Hash `src` as DXC's preprocessor sees it, less what cannot change the DXIL: `//` and `/* */`
/// comments (outside string literals) become a space, every line is trimmed, and empty lines are
/// left out. Lines stay separate, so preprocessor directives keep their extent. For a source
/// without backslash-newlines (`cache_key_for_toolchain`).
fn hash_code_lines(mut h: u64, src: &str) -> u64 {
let mut line: Vec<u8> = Vec::with_capacity(256);
let (mut in_block, mut in_string) = (false, false);
let flush = |h: &mut u64, line: &mut Vec<u8>| {
let start = line.iter().position(|b| !b.is_ascii_whitespace());
if let Some(start) = start {
let end = line.iter().rposition(|b| !b.is_ascii_whitespace()).map_or(start, |e| e + 1);
*h = fnv_bytes(*h, line[start..end].iter().copied().chain([b'\n']));
}
line.clear();
};
let b = src.as_bytes();
let mut i = 0;
while i < b.len() {
let c = b[i];
if in_block {
if c == b'*' && b.get(i + 1) == Some(&b'/') {
in_block = false;
line.push(b' ');
i += 2;
continue;
}
// a newline inside a block comment still ends the line
if c == b'\n' {
flush(&mut h, &mut line);
}
i += 1;
continue;
}
if in_string {
line.push(c);
if c == b'\\' {
if let Some(&n) = b.get(i + 1) {
line.push(n);
i += 2;
continue;
}
} else if c == b'"' || c == b'\n' {
in_string = false;
if c == b'\n' {
line.pop();
flush(&mut h, &mut line);
}
}
i += 1;
continue;
}
match c {
b'/' if b.get(i + 1) == Some(&b'/') => {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
line.push(b' ');
continue;
}
b'/' if b.get(i + 1) == Some(&b'*') => {
in_block = true;
i += 2;
continue;
}
b'"' => {
in_string = true;
line.push(c);
}
b'\n' => flush(&mut h, &mut line),
_ => line.push(c),
}
i += 1;
}
flush(&mut h, &mut line);
h
}

/// The cache key of `src` given to `compile_cached_in` (its full text).
pub(crate) fn cache_key(src: &str, entry: &str, profile: &str) -> u64 {
exact_key_for_toolchain(src, entry, profile, toolchain_identity())
}

/// The cache key of a generated program given to `compile_cached` (`cache_key_for_toolchain`).
pub(crate) fn generated_cache_key(src: &str, entry: &str, profile: &str) -> u64 {
cache_key_for_toolchain(src, entry, profile, toolchain_identity())
}

Expand Down Expand Up @@ -1416,7 +1553,25 @@ fn compile_cached_in_observed<F>(
where
F: FnOnce() -> Result<Vec<u8>, String>,
{
let key = cache_key(src, entry, profile);
compile_cached_keyed(dir, src, cache_key(src, entry, profile), entry, profile, counters, compile_one)
}

/// `compile_cached_in_observed` with the cache key given (`cache_key`, `generated_cache_key`).
fn compile_cached_keyed<F>(
dir: &Path,
src: &str,
key: u64,
entry: &str,
profile: &str,
counters: &CacheCounters,
compile_one: F,
) -> Result<(Vec<u8>, bool), String>
where
F: FnOnce() -> Result<Vec<u8>, String>,
{
if let Some(d) = std::env::var_os("XCL_DXC_SOURCE_DUMP") {
let _ = std::fs::write(Path::new(&d).join(format!("{key:016x}.{profile}.hlsl")), src);
}
let dir = normalized_cache_dir(dir);
let file = dir.join(format!("{key:016x}.dxil"));
let err_file = dir.join(format!("{key:016x}.err"));
Expand Down Expand Up @@ -1562,8 +1717,17 @@ pub fn in_cached_only() -> bool {
CACHED_ONLY.with(|c| c.get())
}

/// `compile_cached_in` the DXIL cache for a program XCL generates (the recompiler's and
/// `emit`'s): keyed without its comments and indentation where that cannot change the DXIL
/// (`generated_cache_key`). Other HLSL (a debug substitution, a caller's own text) goes through
/// `compile_cached_in`, keyed by its full text.
pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec<u8>, bool), String> {
compile_cached_in(&cache_dir(), src, entry, profile)
compile_generated_in(&cache_dir(), src, entry, profile)
}

/// `compile_cached` through the cache in `dir`.
fn compile_generated_in(dir: &Path, src: &str, entry: &str, profile: &str) -> Result<(Vec<u8>, bool), String> {
compile_cached_keyed(dir, src, generated_cache_key(src, entry, profile), entry, profile, cache_counters(), || compile(src, entry, profile, &[]))
}

#[cfg(test)]
Expand Down Expand Up @@ -1688,6 +1852,123 @@ mod cache_tests {
assert_ne!(a, cache_key_for_toolchain("source", "main", "cs_6_6", "compiler-a/signer-b"));
}

#[test]
fn cache_key_leaves_out_comments_and_indentation() {
let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "tc");
let a = "// generated by XCL\n[numthreads(64, 1, 1)]\nvoid main()\n{\n // 0000: v_nop ; lit 0x1\n uint s0 = io.Load(0u); // the first SGPR\n /* a\n block */ io.Store(0u, s0);\n}\n";
let b = "// generated by XCL\n[numthreads(64, 1, 1)]\nvoid main()\n{\n // 0000: v_nop ; lit 0x2\n\n uint s0 = io.Load(0u);\n io.Store(0u, s0); \n}";
assert_eq!(key(a), key(b), "programs that differ only in comments and whitespace around lines share a key");
// what reaches the DXIL keeps keys apart
assert_ne!(key(a), key(&a.replace("io.Load(0u)", "io.Load(4u)")));
assert_ne!(key(a), key(&a.replace("uint s0", "uint s0")), "spaces inside a line are kept");
assert_ne!(key(a), key(&a.replace("[numthreads(64, 1, 1)]\nvoid", "[numthreads(64, 1, 1)] void")), "line breaks are kept");
assert_ne!(key("#define X 1\nuint y = X;\n"), key("#define X 1 uint y = X;\n"));
assert_ne!(key("[shader(\"compute\")]\n"), key("[shader(\"com//pute\")]\n"), "string literals are code");
assert_ne!(key(a), cache_key_for_toolchain(a, "main", "cs_6_7", "tc"));
assert_ne!(key(a), cache_key_for_toolchain(a, "other", "cs_6_6", "tc"));
// a backslash-newline continues a comment: such a source keys on its full text
let spliced = "uint a = 1u; // note \\\nuint b = 2u;\n";
assert_ne!(key(spliced), key("uint a = 1u;\n"));
assert_ne!(key(spliced), key("uint a = 1u; // other \\\nuint b = 2u;\n"));
}

#[test]
fn cache_key_distinguishes_line_macro_after_comment() {
let a = "RWByteAddressBuffer O : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { O.Store(0, __LINE__); }\n";
let b = "RWByteAddressBuffer O : register(u0);\n// differing comment line\n[numthreads(1, 1, 1)]\nvoid main() { O.Store(0, __LINE__); }\n";
assert_ne!(cache_key_for_toolchain(a, "main", "cs_6_6", "tc"), cache_key_for_toolchain(b, "main", "cs_6_6", "tc"));
}

#[test]
fn cache_key_distinguishes_whitespace_line_splice() {
let a = "RWByteAddressBuffer O : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() {\nuint n = 1 // note\n+ 2\n; O.Store(0, n); }\n";
let b = a.replacen("// note\n", "// note\\ \n", 1);
assert_ne!(cache_key_for_toolchain(a, "main", "cs_6_6", "tc"), cache_key_for_toolchain(&b, "main", "cs_6_6", "tc"));
}

#[test]
fn only_sources_whose_line_structure_cannot_reach_the_dxil_drop_their_comments() {
assert!(code_lines_keyable("uint a = 1u; // note\nuint s = \"a\\\\b\"; uint c = 2u \\ 3u;\n"));
for no in [
"uint a = __LINE__;\n",
"#line 40\nuint a = 1u;\n",
" # line 40 \"x.hlsl\"\nuint a = 1u;\n",
"uint a = 1u; // note\\\t\r\nuint b = 2u;\n",
"uint a = 1u; // note \\ ",
"uint a = 1u; // note ??/\nuint b = 2u;\n",
] {
assert!(!code_lines_keyable(no), "{no:?}");
assert_ne!(cache_key_for_toolchain(no, "main", "cs_6_6", "tc"), cache_key_for_toolchain(&format!("// x\n{no}"), "main", "cs_6_6", "tc"), "{no:?}");
}
// any other HLSL (`compile_cached_in`) keys on its full text, comments included
let a = "uint a = 1u; // note\n";
assert_ne!(exact_key_for_toolchain(a, "main", "cs_6_6", "tc"), exact_key_for_toolchain("uint a = 1u; // other\n", "main", "cs_6_6", "tc"));
assert_eq!(cache_key_for_toolchain(a, "main", "cs_6_6", "tc"), cache_key_for_toolchain("uint a = 1u; // other\n", "main", "cs_6_6", "tc"));
}

/// With DXC: a generated program compiled into an empty cache does not answer for one that
/// DXC compiles differently (`__LINE__`, a line splice), which gets its own compile (the same
/// DXIL as compiling it alone); one that differs only in comments still shares the entry.
#[test]
fn a_program_compiled_differently_misses_the_cache_of_its_comment_twin() {
if location().is_err() {
super::super::runner::skip_test("no DXC");
return;
}
let line = "RWByteAddressBuffer O : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { O.Store(0, __LINE__); }\n";
let splice = "RWByteAddressBuffer O : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() {\nuint n = 1 // note\n+ 2\n; O.Store(0, n); }\n";
let pairs = [
(line.to_string(), line.replacen("[numthreads", "// differing comment line\n[numthreads", 1)),
(splice.to_string(), splice.replacen("// note\n", "// note\\ \n", 1)),
];
for (k, (a, b)) in pairs.iter().enumerate() {
let dir = std::env::temp_dir().join(format!("xcl-dxil-twin-{}-{k}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (dxil_a, hit_a) = compile_generated_in(&dir, a, "main", "cs_6_6").unwrap();
let (dxil_b, hit_b) = compile_generated_in(&dir, b, "main", "cs_6_6").unwrap();
assert!(!hit_a && !hit_b, "pair {k}: the second program missed the first's entry");
assert_eq!(dxil_b, compile(b, "main", "cs_6_6", &[]).unwrap(), "pair {k}: its own DXIL");
assert_ne!(dxil_a, dxil_b, "pair {k}: DXC compiles the two differently");
let _ = std::fs::remove_dir_all(&dir);
}
let dir = std::env::temp_dir().join(format!("xcl-dxil-twin-{}-shared", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let plain = "RWByteAddressBuffer O : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { O.Store(0, 3); }\n";
let (first, _) = compile_generated_in(&dir, plain, "main", "cs_6_6").unwrap();
let (again, hit) = compile_generated_in(&dir, &plain.replacen("[numthreads", "// 0000: v_nop ; lit 0x1\n[numthreads", 1), "main", "cs_6_6").unwrap();
assert!(hit && again == first, "comments alone still share the entry");
let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cache_key_of_a_long_source_keeps_its_comments() {
// from 1 MiB the length (comments included) picks the -O level (`link_opt_args`)
let code = "uint s0 = io.Load(0u);\n";
let mut long = String::new();
while long.len() < KEY_CODE_LINES_BELOW {
long.push_str(code);
}
let commented = format!("// 0000: v_nop\n{long}");
let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "tc");
assert_ne!(key(&long), key(&commented));
assert_eq!(key(&long), key(&long.clone()));
assert!(link_opt_args(KEY_CODE_LINES_BELOW, &[]).is_empty(), "keyed without comments only where DXC gets no -O switch");
}

#[test]
fn a_linked_program_stays_within_the_code_line_key_margin() {
// `compile_here` links a compute program: its -O level follows the linked program's
// length, which is the source plus the accessor declarations less the inline accessors
let inline = super::super::emit::mem_accessors(4, None);
let mut src = format!("{inline}[numthreads(64, 1, 1)]\nvoid main()\n{{\n");
for _ in 0..LINK_MIN_ACCESSES {
src.push_str(" xcl_mStore(0u, xcl_mLoad(0u));\n");
}
src.push_str("}\n");
let (program, _) = super::super::emit::linked_form(&src, LINK_MIN_ACCESSES).expect("linked form");
assert!(program.len() <= src.len() + (1024 * 1024 - KEY_CODE_LINES_BELOW), "{} > {} + margin", program.len(), src.len());
}

#[test]
fn validates_dxil_cache_structure_and_rebuilds_corruption() {
let valid = synthetic_dxil(7);
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6119,7 +6119,7 @@ fn method_switch(windows: u32, w: &str, ret: &str, name: &str, args: &str, def:
/// out-of-UMA pointers can never wrap onto live memory windows.
/// `heap`: Some(storage class) – window k is taken from the descriptor heap
/// (`Options::heap_windows`) and the same rule is one comparison before the access.
fn mem_accessors(windows: u32, heap: Option<&str>) -> String {
pub(super) fn mem_accessors(windows: u32, heap: Option<&str>) -> String {
let mut s = String::new();
if let Some(coherent) = heap {
// Redirect ordinary out-of-window loads/stores to null raw UAVs without a divergent
Expand Down
10 changes: 9 additions & 1 deletion crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,23 +846,30 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
Err(e) => direct_fallback("CS", &e),
}
}
// (a debug hook below edits the generated HLSL: it is then keyed by its full text,
// `dxc::compile_cached_in`)
let mut edited = false;
if let Some([r, g, b]) = (stage == Stage::Pixel).then(|| debug_color(blob)).flatten() {
t.hlsl = t.hlsl.replacen(" return xo;\n}", &format!(" xo.t0 = float4({r:.3}, {g:.3}, {b:.3}, 1.0);\n return xo;\n}}"), 1);
edited = true;
}
// `XCL_DEBUG_LOD0=hash,…`: those pixel shaders sample at LOD 0 instead of with implicit
// derivatives – tells derivative (helper lane) trouble apart from the rest
if stage == Stage::Pixel && std::env::var("XCL_DEBUG_LOD0").is_ok_and(|v| v.split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).any(|h| h == crate::gpu::shader::fnv64(blob))) {
t.hlsl = sample_at_lod0(&t.hlsl);
edited = true;
}
// `XCL_DEBUG_PS_SUB=hash:from=>to||from=>to…` (one pixel shader): every `from` in its HLSL
// becomes `to`
if let Some(v) = (stage == Stage::Pixel).then(|| std::env::var("XCL_DEBUG_PS_SUB").ok()).flatten() {
if let Some(subs) = debug_subs(&v, crate::gpu::shader::fnv64(blob)) {
apply_debug_subs(&mut t.hlsl, &subs, "XCL_DEBUG_PS_SUB");
edited = true;
}
}
if let Some(subs) = &cs_subs {
apply_debug_subs(&mut t.hlsl, subs, "XCL_DEBUG_CS_SUB");
edited = true;
}
// `XCL_DEBUG_PS_EXPR=hash:expression` (one pixel shader): its target 0 gets that HLSL
// expression, e.g. `float4(xi.a1.rgb, 1)` – an input or a register made visible
Expand All @@ -871,8 +878,9 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
(u64::from_str_radix(h.trim(), 16).ok()? == crate::gpu::shader::fnv64(blob)).then(|| e.to_string())
}) {
t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1);
edited = true;
}
let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0;
let dxil = if edited { dxc::compile_cached_in(&dxc::cache_dir(), &t.hlsl, "main", profile) } else { dxc::compile_cached(&t.hlsl, "main", profile) }?.0;
if stage == Stage::Compute {
note_compute_path(blob, if cs_subs.is_some() { "HLSL, with XCL_DEBUG_CS_SUB" } else { "HLSL" });
}
Expand Down
Loading
Loading