Skip to content
Closed
880 changes: 880 additions & 0 deletions crates/xcl/src/gpu/recomp/aperture_tests.rs

Large diffs are not rendered by default.

22 changes: 18 additions & 4 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4488,7 +4488,8 @@ impl Em {
}
}
if windows > 1 {
h = windowed(&h, windows);
let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" };
h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent));
}
h
}
Expand Down Expand Up @@ -4820,7 +4821,9 @@ const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Lo
/// Several memory windows: every `mem.Method(` of the program (and of the preludes) becomes
/// an accessor `xcl_mMethod(` that switches on `xcl_w` between `mem` and `mem1`.., whose
/// definitions replace the placeholder.
fn windowed(h: &str, windows: u32) -> String {
/// `heap`: Some(storage class) – the accessors take window k from the descriptor heap
/// (`Options::heap_windows`) instead of switching over the root UAVs.
fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String {
let mut out = String::with_capacity(h.len() + 8192);
let mut rest = h;
while let Some(i) = rest.find("mem.") {
Expand All @@ -4838,11 +4841,11 @@ fn windowed(h: &str, windows: u32) -> String {
}
}
out.push_str(rest);
out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows), 1)
out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap), 1)
}

/// The accessor functions: one per `mem` method (and overload) the translator emits.
fn mem_accessors(windows: u32) -> String {
fn mem_accessors(windows: u32, heap: Option<&str>) -> String {
let mut sigs: Vec<(&str, String, &str, &str)> = vec![
("uint", "Load".into(), "uint a", "a"),
("uint2", "Load2".into(), "uint a", "a"),
Expand All @@ -4867,6 +4870,17 @@ fn mem_accessors(windows: u32) -> String {
}
}
let mut s = String::new();
if let Some(coherent) = heap {
// one access: window k is descriptor MEM_HEAP_BASE + k (a window the program does not
// have reads window 0, as the switch's default did)
let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + (xcl_w < {windows}u ? xcl_w : 0u))]", super::MEM_HEAP_BASE);
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 " };
let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ XCL_MW; {r}m.{name}({args}); }}");
}
return s;
}
let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_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)); ");
Expand Down
24 changes: 23 additions & 1 deletion crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ pub use emit::mesh_passthrough;
pub mod runner;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod aperture_tests;

/// First descriptor of the memory windows in the shader-visible heap (`Options::heap_windows`):
/// window k is raw UAV `MEM_HEAP_BASE + k`.
pub const MEM_HEAP_BASE: u32 = 0;

/// 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;
pub mod upper_lanes;

use std::collections::{BTreeMap, BTreeSet};
Expand Down Expand Up @@ -486,14 +496,19 @@ pub struct Options {
/// then exactly the single-window form); 2..4 add `mem1`.. (u3..) and pick the window of
/// every access from the high address bits
pub mem_windows: u32,
/// with `mem_windows` > 1: reach window k through descriptor `MEM_HEAP_BASE + k` of the
/// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`) – one access per
/// site instead of a `switch` over the root UAVs `mem`, `mem1`.., which inlines every
/// access once per window (HANDOFF: twice the DXC + driver time with 4 windows)
pub heap_windows: bool,
/// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`:
/// always the guarded block chain)
pub structured: bool,
}

impl Default for Options {
fn default() -> Self {
Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, structured: true }
Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true }
}
}

Expand Down Expand Up @@ -1290,6 +1305,13 @@ fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet<u64>) -> BTreeMap<u64
}

pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
let normalized;
let opt = if opt.mem_windows & HEAP_WINDOWS != 0 {
normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() };
&normalized
} else {
opt
};
let mut insts: Vec<Decoded> = Vec::new();
let mut off = 0usize;
while off + 4 <= code.len() {
Expand Down
38 changes: 36 additions & 2 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,43 @@ pub fn fspx(blob: &[u8]) -> Option<Fspx<'_>> {
Some(Fspx { threads, rsrc1: u32_at(head, 0x14)?, rsrc2: u32_at(head, 0x18)?, code: &code[..4 * (end + 1)] })
}

/// Memory windows of the title's unified memory (1 without it).
/// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when
/// shaders take them from the descriptor heap (`heap_windows`).
pub fn mem_windows() -> u32 {
crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)
let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32);
if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) {
n | super::HEAP_WINDOWS
} else {
n
}
}

thread_local! {
/// this thread translates in the switch form (`in_switch_form`)
static SWITCH_FORM: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Run `f` with this thread's translations in the switch form over root UAVs (`mem_windows`
/// without `HEAP_WINDOWS`, so other cache keys): for a pipeline the driver would not build with
/// heap windows. The root signature and the binds are the same for both forms.
pub fn in_switch_form<R>(f: impl FnOnce() -> R) -> R {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
SWITCH_FORM.with(|s| s.set(self.0));
}
}
let _restore = Restore(SWITCH_FORM.with(|s| s.replace(true)));
f()
}

/// Whether translated shaders reach the memory windows through the shared descriptor heap
/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`.. made by `console_heap::set_window_views`)
/// instead of a `switch` over root UAVs. On unless `XCL_HEAP_WINDOWS=0` or the views could not
/// be made (no shared heap: then the switch, as before).
pub fn heap_windows() -> bool {
static ENV: OnceLock<bool> = OnceLock::new();
*ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").map_or(true, |v| v != "0")) && !crate::hle::d3d12x::console_heap::window_views_failed()
}

/// A static sampler of a translated program: (S#, comparison) – see `Translation`.
Expand Down
54 changes: 53 additions & 1 deletion crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,6 +1183,24 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern
for b in &bufs[1..] {
list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]);
}
// the windows as raw UAVs at MEM_HEAP_BASE.. of a shader-visible heap
// (`Options::heap_windows`; programs with the root-UAV switch ignore it)
let dh: ID3D12DescriptorHeap = dev
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: super::MEM_HEAP_BASE + 4,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
.map_err(e)?;
let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
for k in 0..4usize {
let (b, size) = bufs.get(k).map_or((&mem_buf, arena.windows[0].1), |b| (b, arena.windows[k].1));
let mut h = dh.GetCPUDescriptorHandleForHeapStart();
h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc;
dev.CreateUnorderedAccessView(b, None::<&ID3D12Resource>, Some(&raw_window_uav(size as u64)), h);
}
list.SetDescriptorHeaps(&[Some(dh.clone())]);
list.SetComputeRootSignature(&gpu.rs);
list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress());
list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress());
Expand Down Expand Up @@ -1212,6 +1230,22 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern
}
}

/// A raw UAV of a memory window of `bytes` (`Options::heap_windows`): at most 2^30 − 1 dwords,
/// the largest byte size a 32-bit field holds (AMD's V# NUM_RECORDS). The sparse windows hand
/// out their last 64 KiB tile – a view of 4 GiB − 64 KiB left it unreachable (zeros, dropped
/// stores); this one misses only the window's last dword. On an RTX 3090 a view of exactly 2^30
/// dwords works too (`aperture_tests::e1c_window_view_last_tile`); AMD is not measured.
pub fn raw_window_uav(bytes: u64) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
let bytes = bytes.min((1u64 << 32) - 4);
D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT_R32_TYPELESS,
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: (bytes / 4) as u32, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW },
},
}
}

/// 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 @@ -1308,7 +1342,25 @@ fn dispatch_with(
transition(&mem_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
]);
let _bound = bind_resources(dev, &list, &[], &[])?;
let bound = bind_resources(dev, &list, &[], &[])?;
// A PSO built by the backend's hook uses the runtime's window count: with heap windows
// (`Options::heap_windows`) its accesses go to ResourceDescriptorHeap[MEM_HEAP_BASE + w],
// so every window slot is a raw view of `mem` (no textures here to share the heap with).
let dh: ID3D12DescriptorHeap = dev
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: super::MEM_HEAP_BASE + 4,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
.map_err(e)?;
let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
for k in 0..4usize {
let mut h = dh.GetCPUDescriptorHandleForHeapStart();
h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc;
dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h);
}
list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]);
list.SetComputeRootSignature(rs);
list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress());
list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress());
Expand Down
15 changes: 14 additions & 1 deletion crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2837,6 +2837,17 @@ fn gpu_mesh_mode_reads_memory_windows() {
/// accesses in window 0.
#[test]
fn gpu_memory_windows_above_4_gib() {
memory_windows_above_4_gib(false);
}

/// The same program with the windows taken from the descriptor heap (`Options::heap_windows`):
/// same results, and no `switch` over windows in the HLSL.
#[test]
fn gpu_memory_windows_from_the_heap() {
memory_windows_above_4_gib(true);
}

fn memory_windows_above_4_gib(heap: bool) {
if !gpu_ready() {
return;
}
Expand Down Expand Up @@ -2867,8 +2878,10 @@ fn gpu_memory_windows_above_4_gib() {
let p = prog(&refs);
let one = translate(&p, &Options::default()).unwrap();
assert!(!one.hlsl.contains("mem1") && !one.hlsl.contains("xcl_w =") && !one.hlsl.contains("xcl_m"), "one window: the single-window HLSL");
let t = translate(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap();
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);
let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap();
let hi = |a: u64| (a >> 32) as u32;
let mut st = KernelState::default();
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,7 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis
/// arguments the console's way – compute or graphics) and the argument table in unified
/// memory, u1 res, u2… the memory windows; then the pipeline.
unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> {
super::list_x::ensure_view_heap(this);
let u = crate::gpu::uma::get().ok_or("no unified memory")?;
let windows = super::real::uma_window_vas();
let first = *windows.first().ok_or("unified memory is not open on the GPU")?;
Expand Down
36 changes: 35 additions & 1 deletion crates/xcl/src/hle/d3d12x/console_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

use std::sync::Mutex;

use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;

/// bytes of a CBV/SRV/UAV slot (T# / V#) and of a sampler slot (S#)
Expand Down Expand Up @@ -157,13 +158,46 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool {
inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV),
heap,
cap,
next: 0,
// the memory windows' raw UAVs (`set_window_views`) come first
next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_WINDOWS as u32,
free: Vec::new(),
});
}
true
}

static WINDOW_VIEWS_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Whether the memory windows could not be put in the shared heap (`set_window_views`):
/// translated shaders then switch over root UAVs (`pso::heap_windows`).
pub fn window_views_failed() -> bool {
WINDOW_VIEWS_FAILED.load(std::sync::atomic::Ordering::Relaxed)
}

/// 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.
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 g = GLOBAL.lock().unwrap();
let s = g.as_ref().unwrap();
for k in 0..crate::gpu::uma::MAX_WINDOWS {
let (raw, bytes) = windows.get(k).copied().filter(|w| w.0 != 0).unwrap_or(windows[0]);
let raw = raw as *mut std::ffi::c_void;
let Some(r) = ID3D12Resource::from_raw_borrowed(&raw) else { continue };
let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (s.cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * s.inc as u64) as usize };
s.dev.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at);
}
true
};
if !ok {
WINDOW_VIEWS_FAILED.store(true, std::sync::atomic::Ordering::Relaxed);
crate::xlog_warn!("memory windows: not in the shared descriptor heap – translated shaders switch over the windows' root UAVs");
}
ok
}

/// `count` descriptors of the shared heap: the index of the first. None: no shared heap, or
/// no room left in it.
fn reserve_global(count: u32) -> Option<u32> {
Expand Down
9 changes: 9 additions & 0 deletions crates/xcl/src/hle/d3d12x/console_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,8 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
let mut layout: Option<Arc<Layout>> = None;
let mut table: Vec<u8> = Vec::new();
let mut pso: Option<*const ConsolePso> = None;
// heap windows (`pso::heap_windows`): a dispatch needs the shared heap even when the list set none
let mut heaps_set = false;
let chunks: Vec<Vec<u32>> = st.chunks.iter().map(|(c, used)| c[..*used].chunks(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()).collect();
'chunks: for words in &chunks {
let mut at = 0usize;
Expand All @@ -691,6 +693,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
}
}
list.SetDescriptorHeaps(&heaps);
heaps_set = true;
at += 2 + 2 * n;
} else if w0 == TRANSITIONS_MARKER {
let n = get(1) as usize;
Expand Down Expand Up @@ -794,6 +797,12 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
Some(r) => list.SetComputeRootSignature(r),
None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?),
}
if !heaps_set && crate::gpu::recomp::pso::heap_windows() {
if let Some(g) = super::console_heap::global_heap() {
list.SetDescriptorHeaps(&[Some(g)]);
heaps_set = true;
}
}
list.SetComputeRootUnorderedAccessView(0, va(io_at));
list.SetComputeRootUnorderedAccessView(1, va(res_at));
for k in 0..4 {
Expand Down
Loading