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
24 changes: 15 additions & 9 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5121,7 +5121,8 @@ fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String {
/// `default` (reads return 0, stores/atomics are dropped and zero their `out` parameter) so
/// 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.
/// (`Options::heap_windows`), and the same rule is a select of the null view
/// (`MEM_HEAP_NULL`), with no branch around the access.
fn mem_accessors(windows: u32, heap: Option<&str>) -> String {
let mut sigs: Vec<(&str, String, &str, &str, &str)> = vec![
("uint", "Load".into(), "uint a", "a", "return 0u;"),
Expand All @@ -5148,15 +5149,20 @@ fn mem_accessors(windows: u32, heap: Option<&str>) -> String {
}
let mut s = String::new();
if let Some(coherent) = heap {
// one access: window k is descriptor MEM_HEAP_BASE + k; an `xcl_w` outside the windows
// does what the switch's `default` does
let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE);
let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}");
for (ret, name, params, args, def) in sigs {
// one access, no branch: window k is descriptor MEM_HEAP_BASE + k, and an `xcl_w`
// outside the windows selects the null view at MEM_HEAP_NULL, which does what the
// switch's `default` does. A branch around every access cost NVIDIA's compiler time
// (brothernog on #680).
let _ = writeln!(
s,
"#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex(xcl_w < {windows}u ? {}u + xcl_w : {}u)]",
super::MEM_HEAP_BASE,
super::MEM_HEAP_NULL
);
let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}");
for (ret, name, params, args, _) in sigs {
let r = if ret == "void" { "" } else { "return " };
// (the switch's `break` leaves the accessor)
let outside = def.replace("break;", "return;");
let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}");
let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ XCL_MW; {r}m.{name}({args}); }}");
}
return s;
}
Expand Down
6 changes: 6 additions & 0 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ mod heap_window_tests;
/// window k is raw UAV `MEM_HEAP_BASE + k`.
pub const MEM_HEAP_BASE: u32 = 0;

/// The descriptor after the memory windows (`Options::heap_windows`): a null raw UAV. An access
/// with `xcl_w` outside a program's windows takes it instead of branching around the access
/// (a null view's loads and atomics return 0 and its stores are dropped – what the switch
/// form's `default` does).
pub const MEM_HEAP_NULL: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_WINDOWS as u32;

/// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys):
/// `Options::heap_windows`. `translate` takes it out of `mem_windows`.
pub const HEAP_WINDOWS: u32 = 0x100;
Expand Down
17 changes: 15 additions & 2 deletions crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1366,7 +1366,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern
let dh: ID3D12DescriptorHeap = dev
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: super::MEM_HEAP_BASE + 4,
NumDescriptors: super::MEM_HEAP_NULL + 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
Expand All @@ -1378,6 +1378,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern
h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc;
dev.CreateUnorderedAccessView(b, None::<&ID3D12Resource>, Some(&raw_window_uav(size as u64)), h);
}
set_null_window_view(dev, dh.GetCPUDescriptorHandleForHeapStart(), inc);
list.SetDescriptorHeaps(&[Some(dh.clone())]);
list.SetComputeRootSignature(&gpu.rs);
list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress());
Expand Down Expand Up @@ -1426,6 +1427,17 @@ pub fn raw_window_uav(bytes: u64) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
}
}

/// The null raw UAV at `MEM_HEAP_NULL` of a heap starting at `start` (`Options::heap_windows`:
/// accesses outside a program's windows select it – loads and atomics give 0, stores drop).
///
/// # Safety
/// `start` is the CPU handle of a heap of `dev` with at least `MEM_HEAP_NULL + 1` descriptors
/// of increment `inc`.
pub unsafe fn set_null_window_view(dev: &ID3D12Device, start: D3D12_CPU_DESCRIPTOR_HANDLE, inc: usize) {
let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + super::MEM_HEAP_NULL as usize * inc };
dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(4)), at);
}

/// Create a committed resource from a description (validation of decoded descriptors).
pub fn try_create_texture(desc: &D3D12_RESOURCE_DESC) -> Result<(), String> {
let mut g = GPU.lock().unwrap();
Expand Down Expand Up @@ -1529,7 +1541,7 @@ fn dispatch_with(
let dh: ID3D12DescriptorHeap = dev
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: super::MEM_HEAP_BASE + 4,
NumDescriptors: super::MEM_HEAP_NULL + 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
Expand All @@ -1540,6 +1552,7 @@ fn dispatch_with(
h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc;
dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h);
}
set_null_window_view(dev, dh.GetCPUDescriptorHandleForHeapStart(), inc);
list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]);
list.SetComputeRootSignature(rs);
list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress());
Expand Down
6 changes: 5 additions & 1 deletion crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3271,7 +3271,11 @@ fn memory_windows_above_4_gib(heap: bool) {
let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap();
assert!(t.hlsl.contains("RWByteAddressBuffer mem1 : register(u3)"));
assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap, "heap windows: no switch over windows");
assert_eq!(t.hlsl.contains("ResourceDescriptorHeap[NonUniformResourceIndex(0u + xcl_w)]"), heap);
// heap windows: a window outside the program's two selects the null view after all
// MAX_WINDOWS descriptors (not descriptor 2, a live window's view), with no branch
let select = format!("ResourceDescriptorHeap[NonUniformResourceIndex(xcl_w < 2u ? 0u + xcl_w : {}u)]", super::MEM_HEAP_NULL);
assert_eq!(t.hlsl.contains(&select), heap);
assert!(!t.hlsl.contains("if (xcl_w >="), "heap windows: no branch around an access");
let hlsl_dxil = || super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap();
// the direct translator binds windows as root UAVs only (no heap windows yet)
let dxil = if heap { hlsl_dxil() } else { direct_or(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() }), hlsl_dxil()) };
Expand Down
25 changes: 17 additions & 8 deletions crates/xcl/src/hle/d3d12x/console_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,9 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool {
inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV),
heap,
cap,
// the memory windows' raw UAVs (`set_window_views`) come first
next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_WINDOWS as u32,
// the memory windows' raw UAVs and the null view after them (`set_window_views`)
// come first
next: crate::gpu::recomp::MEM_HEAP_NULL + 1,
free: Vec::new(),
});
}
Expand All @@ -175,9 +176,9 @@ pub fn window_views_failed() -> bool {
}

/// The memory windows' buffers `(resource, bytes)` as raw UAVs at `MEM_HEAP_BASE + k` of the
/// shared heap, made now if need be (`Options::heap_windows`: shaders take window k from there).
/// A window without a buffer gets window 0's. False (and the shaders keep the switch): no
/// shared heap.
/// shared heap, and the null view at `MEM_HEAP_NULL` after them, made now if need be
/// (`Options::heap_windows`: shaders take window k from there). A window without a buffer
/// gets window 0's. False (and the shaders keep the switch): no shared heap.
pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool {
let ok = !windows.is_empty() && windows[0].0 != 0 && shared_heap(dev) && {
let (device, cpu, inc) = {
Expand All @@ -193,6 +194,8 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -
let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * inc as u64) as usize };
device.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at);
}
// accesses outside a program's windows select the null view at MEM_HEAP_NULL
crate::gpu::recomp::runner::set_null_window_view(&device, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu as usize }, inc as usize);
true
};
if !ok {
Expand Down Expand Up @@ -558,13 +561,17 @@ mod tests {
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
static UNLOCKED: AtomicBool = AtomicBool::new(true);
static CALLS: AtomicU32 = AtomicU32::new(0);
static NULL_AT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
#[repr(C)]
struct Object { vt: *const usize }
unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 }
unsafe extern "system" fn create_uav(_this: *mut c_void, _resource: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, _at: D3D12_CPU_DESCRIPTOR_HANDLE) {
unsafe extern "system" fn create_uav(_this: *mut c_void, resource: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
// The adopted device hook can re-enter descriptor bookkeeping.
UNLOCKED.fetch_and(GLOBAL.try_lock().is_ok(), Ordering::Relaxed);
CALLS.fetch_add(1, Ordering::Relaxed);
if resource.is_null() {
NULL_AT.store(at.ptr, Ordering::Relaxed);
}
}
let mut vt = [0usize; 20];
vt[1] = retain as usize;
Expand All @@ -579,10 +586,12 @@ mod tests {
dev: dev.clone(),
heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void),
cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024,
next: crate::gpu::uma::MAX_WINDOWS as u32, free: Vec::new(),
next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(),
});
assert!(set_window_views(&dev, &[(&mut resource as *mut _ as usize, 0x10000)]));
assert_eq!(CALLS.load(Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32);
// one view per window, then the null view after them
assert_eq!(CALLS.load(Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32 + 1);
assert_eq!(NULL_AT.load(Ordering::Relaxed), 0x1000 + crate::gpu::recomp::MEM_HEAP_NULL as usize * 32);
assert!(UNLOCKED.load(Ordering::Relaxed), "device callback ran while GLOBAL was locked");
*GLOBAL.lock().unwrap() = None;
}
Expand Down
Loading