Skip to content
Draft
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
134 changes: 119 additions & 15 deletions crates/xcl/src/gpu/recomp/dxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};

use windows::core::{Interface, GUID, HRESULT, PCWSTR};
use windows::Win32::Graphics::Direct3D::Dxc::{DxcBuffer, IDxcBlob, IDxcCompiler3, IDxcResult, CLSID_DxcCompiler, DXC_CP_UTF8};
use windows::Win32::Graphics::Direct3D::Dxc::{
CLSID_DxcCompiler, CLSID_DxcLinker, CLSID_DxcUtils, DxcBuffer, IDxcBlob, IDxcBlobEncoding, IDxcCompiler3, IDxcLinker, IDxcResult, IDxcUtils, DXC_CP, DXC_CP_UTF8,
};

type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT;

Expand Down Expand Up @@ -210,6 +212,92 @@ pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<
}

fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<Vec<u8>, String> {
// compute (also what MS and GS programs run as): DXC's time for its memory accesses is
// linear this way (`emit::linked_form`). Anything wrong with it: as one program, as before.
if profile.starts_with("cs_") && linking() {
if let Some((program, library)) = super::emit::linked_form(src, LINK_MIN_ACCESSES) {
match compile_linked(&program, &library, entry, profile, extra) {
Ok(dxil) => return Ok(dxil),
Err(e) => {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| crate::xlog_warn!("DXC: a program could not be linked with its memory accessors, compiled whole: {e}"));
}
}
}
}
compile_whole(src, entry, profile, extra)
}

/// Accesses a program needs to be linked with its accessors: with 100 both ways take DXC 0.3 s.
const LINK_MIN_ACCESSES: usize = 100;

/// `XCL_LINK_MEM=0`: every program is compiled whole (into the same cache: compare with
/// another `XCL_DXIL_CACHE`).
fn linking() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("XCL_LINK_MEM").map_or(true, |v| v != "0"))
}

/// Compile `program` and `library` (its memory accessors, kept once compiled) as libraries and
/// link them to `profile`.
fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<Vec<u8>, String> {
let model = profile.split_once('_').map_or("6_6", |(_, m)| m);
let lib = format!("lib_{model}");
let accessors = {
static KEPT: Mutex<Option<HashMap<String, Arc<Vec<u8>>>>> = Mutex::new(None);
let key = format!("{lib} {extra:?}\n{library}");
let kept = KEPT.lock().unwrap().get_or_insert_with(HashMap::new).get(&key).cloned();
match kept {
Some(a) => a,
None => {
let a = Arc::new(compile_whole(library, "", &lib, extra)?);
KEPT.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, a.clone());
a
}
}
};
let program = compile_whole(program, "", &lib, extra)?;
let instance = |clsid: &GUID, iid: &GUID| -> Result<*mut c_void, String> {
let mut p = std::ptr::null_mut();
let hr = unsafe { create_fn()?(clsid, iid, &mut p) };
if hr.is_err() || p.is_null() {
return Err(format!("DxcCreateInstance: {hr:?}"));
}
Ok(p)
};
unsafe {
let linker = IDxcLinker::from_raw(instance(&CLSID_DxcLinker, &IDxcLinker::IID)?);
let utils = IDxcUtils::from_raw(instance(&CLSID_DxcUtils, &IDxcUtils::IID)?);
let names = [crate::util::wide("program"), crate::util::wide("accessors")];
for (name, dxil) in names.iter().zip([&program, &*accessors]) {
let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, dxil.len() as u32, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?;
linker.RegisterLibrary(PCWSTR(name.as_ptr()), &blob).map_err(|e| format!("RegisterLibrary: {e}"))?;
}
let (entry, profile) = (crate::util::wide(entry), crate::util::wide(profile));
let r = linker
.Link(PCWSTR(entry.as_ptr()), PCWSTR(profile.as_ptr()), &names.each_ref().map(|n| PCWSTR(n.as_ptr())), None)
.map_err(|e| format!("Link: {e}"))?;
output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult())
}
}

/// The bytes of a finished DXC operation, or its messages.
unsafe fn output(status: windows::core::Result<HRESULT>, errors: windows::core::Result<IDxcBlobEncoding>, result: windows::core::Result<IDxcBlob>) -> Result<Vec<u8>, String> {
if status.map_err(|e| format!("{e}"))?.is_err() {
let msg = errors
.ok()
.map(|b| {
let s = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize());
String::from_utf8_lossy(s).trim_end_matches('\0').to_string()
})
.unwrap_or_default();
return Err(format!("dxc: {msg}"));
}
let blob = result.map_err(|e| format!("{e}"))?;
Ok(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec())
}

fn compile_whole(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<Vec<u8>, String> {
let c = compiler()?;
let mut args: Vec<Vec<u16>> = ["-E", entry, "-T", profile, "-HV", "2021"].iter().map(|a| crate::util::wide(a)).collect();
// DXC's optimiser was superlinear on translated programs full of short-circuit `?:` /
Expand All @@ -231,20 +319,7 @@ fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result
let buf = DxcBuffer { Ptr: src.as_ptr() as *const c_void, Size: src.len(), Encoding: DXC_CP_UTF8.0 };
unsafe {
let r: IDxcResult = c.Compile(&buf, Some(&ptrs), None).map_err(|e| format!("Compile: {e}"))?;
let status = r.GetStatus().map_err(|e| format!("{e}"))?;
if status.is_err() {
let msg = r
.GetErrorBuffer()
.ok()
.map(|b| {
let s = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize());
String::from_utf8_lossy(s).trim_end_matches('\0').to_string()
})
.unwrap_or_default();
return Err(format!("dxc: {msg}"));
}
let blob: IDxcBlob = r.GetResult().map_err(|e| format!("{e}"))?;
Ok(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec())
output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult())
}
}

Expand Down Expand Up @@ -981,3 +1056,32 @@ mod cache_tests {
});
}
}

/// `src` compiled whole and linked with its memory accessors, whatever their number, with the
/// seconds each took.
#[cfg(test)]
pub(super) fn both_forms(src: &str, profile: &str) -> Result<[(Vec<u8>, f64); 2], String> {
std::thread::scope(|s| {
let t = std::thread::Builder::new().stack_size(DXC_STACK).spawn_scoped(s, || {
let (program, library) = super::emit::linked_form(src, 0).ok_or("no linked form")?;
let t0 = std::time::Instant::now();
let linked = compile_linked(&program, &library, "main", profile, &[])?;
let linked = (linked, t0.elapsed().as_secs_f64());
let t0 = std::time::Instant::now();
let whole = compile_whole(src, "main", profile, &[])?;
Ok([(whole, t0.elapsed().as_secs_f64()), linked])
});
t.map_err(|e| e.to_string())?.join().map_err(|_| "DXC: panic".to_string())?
})
}

/// The disassembly of a DXIL container.
#[cfg(test)]
pub(super) fn disassemble(dxil: &[u8]) -> Result<String, String> {
let c = compiler()?;
let buf = DxcBuffer { Ptr: dxil.as_ptr() as *const c_void, Size: dxil.len(), Encoding: 0 };
unsafe {
let r: IDxcResult = c.Disassemble(&buf).map_err(|e| format!("Disassemble: {e}"))?;
output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult()).map(|b| String::from_utf8_lossy(&b).into_owned())
}
}
62 changes: 50 additions & 12 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4828,8 +4828,8 @@ fn windowed(h: &str, windows: u32) -> String {
out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows), 1)
}

/// The accessor functions: one per `mem` method (and overload) the translator emits.
fn mem_accessors(windows: u32) -> String {
/// The `mem` methods (and overloads) the translator emits: result, name, parameters, arguments.
fn mem_methods() -> Vec<(&'static str, String, &'static str, &'static str)> {
let mut sigs: Vec<(&str, String, &str, &str)> = vec![
("uint", "Load".into(), "uint a", "a"),
("uint2", "Load2".into(), "uint a", "a"),
Expand All @@ -4853,23 +4853,61 @@ fn mem_accessors(windows: u32) -> String {
sigs.push(("void", format!("Interlocked{op}64"), "uint a, int64_t v, out int64_t o", "a, v, o"));
}
}
let mut s = String::new();
let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ ");
sigs
}

/// The body of an accessor: the switch on the window `w` (`xcl_loadx4`, a `mem` method).
fn loadx4_switch(windows: u32, w: &str) -> String {
let mut s = format!("[branch] switch ({w}) {{ ");
for k in 1..windows {
let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); ");
}
let _ = writeln!(s, "default: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }} }}");
for (ret, name, params, args) in sigs {
let r = if ret == "void" { "" } else { "return " };
let _ = write!(s, "{ret} xcl_m{name}({params}) {{ [branch] switch (xcl_w) {{ ");
for k in 1..windows {
let _ = write!(s, "case {k}u: {r}mem{k}.{name}({args}); break; ");
}
let _ = writeln!(s, "default: {r}mem.{name}({args}); break; }} }}");
s.push_str("default: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }");
s
}

fn method_switch(windows: u32, w: &str, ret: &str, name: &str, args: &str) -> String {
let r = if ret == "void" { "" } else { "return " };
let mut s = format!("[branch] switch ({w}) {{ ");
for k in 1..windows {
let _ = write!(s, "case {k}u: {r}mem{k}.{name}({args}); break; ");
}
let _ = write!(s, "default: {r}mem.{name}({args}); break; }}");
s
}

/// The accessor functions: one per `mem` method.
fn mem_accessors(windows: u32) -> String {
let mut s = format!("uint4 xcl_loadx4(uint4 a) {{ {} }}\n", loadx4_switch(windows, "xcl_w"));
for (ret, name, params, args) in mem_methods() {
let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ {} }}", method_switch(windows, "xcl_w", ret, &name, args));
}
s
}

/// A translated program with several memory windows as two libraries for DXC's linker: the
/// program, whose accessors are only declared, and the accessors. DXC inlines a function when
/// it compiles the program, before it optimises: a switch per access, and its time grows with
/// the square of them. The linker inlines the declared ones afterwards. None: no windows, or
/// fewer than `min_accesses` places that use them (DXC is fast enough then).
pub(super) fn linked_form(hlsl: &str, min_accesses: usize) -> Option<(String, String)> {
let (windows, inline) = (2..=4).map(|w| (w, mem_accessors(w))).find(|(_, a)| hlsl.contains(a.as_str()))?;
let (head, rest) = hlsl.split_once(inline.as_str())?;
if rest.matches("xcl_m").count() + rest.matches("xcl_loadx4(").count() < min_accesses || rest.matches("[numthreads(").count() != 1 {
return None;
}
let mut declared = String::from("uint4 xcl_l_loadx4(uint w, uint4 a);\nuint4 xcl_loadx4(uint4 a) { return xcl_l_loadx4(xcl_w, a); }\n");
let mut library: String = head.lines().filter(|l| l.contains("RWByteAddressBuffer mem")).map(|l| format!("{l}\n")).collect();
let _ = writeln!(library, "export uint4 xcl_l_loadx4(uint w, uint4 a) {{ {} }}", loadx4_switch(windows, "w"));
for (ret, name, params, args) in mem_methods() {
let r = if ret == "void" { "" } else { "return " };
let _ = writeln!(declared, "{ret} xcl_l_{name}(uint w, {params});\n{ret} xcl_m{name}({params}) {{ {r}xcl_l_{name}(xcl_w, {args}); }}");
let _ = writeln!(library, "export {ret} xcl_l_{name}(uint w, {params}) {{ {} }}", method_switch(windows, "w", ret, &name, args));
}
let program = format!("{head}{declared}{}", rest.replacen("[numthreads(", "[shader(\"compute\")]\n[numthreads(", 1));
Some((program, library))
}

/// Sub-dword d16 forms: (bytes, sign-extend, store, half: 0 low / 1 high) by the name after
/// the `buffer_` / `flat_` / `global_` prefix.
fn d16_small(op: &str) -> Option<(u32, bool, bool, u32)> {
Expand Down
Loading