Repository navigation
Recompiler: heap memory windows without a guard (min + null view), and the 64-bit atomics check - #1695
Recompiler: heap memory windows without a guard (min + null view), and the 64-bit atomics check#1695brothernog wants to merge 1 commit into
Conversation
3009567 to
dd9f1ff
Compare
|
@Pipodi heads-up for your test claim: I rebased this onto This comment was AI-assisted. |
|
Test report: #1695 at Tested
Regression run. The retail title, 60 s,
#1695
Not tested
AI use: Claude Code. A Claude Sonnet 5.5 subagent ran the suite, the builds and the smoke runs. Claude Opus 5.5 (the main session) planned the series, checked the numbers and wrote this report. |
|
Independent NVIDIA desktop verification of PR #1695 at Tested
Notes from diff review
Not tested
AI use
|
|
Two contributors checked independently and found that #1669 solves the same problem (for #1269) in a different way: #1607, group D44. You may want to compare them with the other author and agree on one, or say in the PR why both are needed. This is a hint, not a request from the maintainers; nobody from the project has adopted #1607 so far. AI use: Claude Code (Claude Opus 5.5), posted by a script from the #1607 table. |
|
Tested commit Tested
Not tested
AI use
|
|
Extra data for the null-view approach this PR shares with #1669, which I've closed in favour of this one. The two forms differ only in the index (
Not tested: this PR's head AI use: Claude Code (Claude Opus 5.5) wrote this. The numbers are from the reports linked above. |
|
Independent 8 GB NVIDIA Ampere ( Setup
Workspace tests (
Regression runs (
Base ( PR head ( PR head ( Not tested: world-loading run on AI use: Antigravity ( |
XCL #1695 on the RTX 4090 — BeginUpdate and ResolveVBuffer24 November 2026 · NVIDIA driver 621.24 · Eight matched rounds per shader With heap windows enabled, the median first driver PSO creation time for ResolveVBuffer went from 2325.2 to 2090.4 ms (-10.1%). PR creation was faster in 8/8 matched rounds. BeginUpdate went from 295.9 to 284.6 ms (-3.8%, faster in 8/8 rounds). With heap windows disabled, base and PR emitted byte-identical HLSL and DXIL for both shaders. PR #1695 · Shader optimization tracker #1269 Timing resultsAll times are CPU wall-clock milliseconds. Each cell gives the median of eight samples followed by the observed minimum and maximum in parentheses. “First PSO” means the first call to
Heap-enabled PR relative to heap-enabled base
Within the PR, switching from root windows to heap windows changed median first PSO creation by -27.2% for BeginUpdate and -75.1% for ResolveVBuffer. The off-to-off control gives a direct view of timing variability on identical bytecode. The measurements cover pipeline preparation. Frame time and GPU dispatch duration were outside the timing interval. Validation
Inputs and method
The first four rounds finished before the readback harness build. The last four rounds were repeated after both revisions’ test builds and GPU checks finished because some original trials overlapped that work. The tables and raw data use the eight uncontended rounds. Superseded samples are retained separately under The locally retained python build.py base pr
python run.py inspect base
python run.py inspect pr
python run.py measure
python verify.py build
python verify.py all
python upstream.py
python results.py
python report.pyAI assistance: OpenAI Codex prepared the harness, ran the measurements and drafted this report. |
|
Verification on RTX 3060 Ti (Windows 11), branch merged with current
Thanks! |
|
@minimalhipster990 thanks, this is the 4090 / 621.24 data the PR was missing. Two things from it matter beyond the timing:
Your −8.8 % DXIL and −10 % first PSO on ResolveVBuffer ( This comment was AI-assisted. |
|
Prepared and tested a current-main integration of your existing two commits, preserving the #1992 null-T# reservation and #1998 expanded-window layout. This is an integration patch for your PR, not a competing implementation or a claim to fix the retail heap-window hang. Base: The important integration detail is Tested — native Windows10 Home19045, Ryzen7800X3D, RTX3090 driver591.74, Rust/Cargo1.98.1MSVC, DXC/DXIL1.8.2502.11, debug; actual adapter printed.
The high-window fixture reuses the previously published #1998 probe, adapted from XCL #822 ( Not tested — full workspace suite, retail smoke/hang, other GPUs, hardware without heap atomic64 support, current compile-time/memory gains, or byte-identical heap-disabled output against main. Direct DXIL retains its existing guarded accessors; its run checks compatibility with the changed shared descriptor layout. Existing performance reports remain tied to their original revisions. No source commit/push or new PR; original branches/worktrees preserved. AI use — Codex (GPT-6) resolved this isolated integration, extended/reused the synthetic fixtures, ran the native comparisons and prepared the patch/report. The patch retains the existing PR's implementation and provenance. Integration patch against cbc296a (existing PR plus compatibility edits and tests)diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs
index 8f257a0..8d0b729 100644
--- a/crates/xcl/src/gpu/recomp/emit.rs
+++ b/crates/xcl/src/gpu/recomp/emit.rs
@@ -5582,7 +5582,7 @@ 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 an out-of-range `xcl_w` takes the null view at `MEM_HEAP_NULL`.
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;"),
@@ -5610,14 +5610,16 @@ 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 {
+ // takes the null view at MEM_HEAP_NULL, which does what the switch's `default` does. No
+ // branch: a guard gives each access two paths, DXC's GVN can join their handles into a
+ // `phi`, and NVIDIA refuses such programs at once with E_OUTOFMEMORY (#756).
+ let null = super::MEM_HEAP_NULL - super::MEM_HEAP_BASE;
+ let index = if windows >= null { format!("min(xcl_w, {null}u)") } else { format!("select(xcl_w < {windows}u, xcl_w, {null}u)") };
+ let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + {index})]", 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 " };
- // (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;
}
diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs
index d1e7d8b..3da939d 100644
--- a/crates/xcl/src/gpu/recomp/mod.rs
+++ b/crates/xcl/src/gpu/recomp/mod.rs
@@ -79,6 +79,10 @@ mod heap_window_tests;
/// (`console_heap::null_views`).
pub const MEM_HEAP_BASE: u32 = 4;
+/// The null raw UAV after the windows' views: an `xcl_w` outside the windows takes it (reads 0,
+/// stores and atomics dropped, atomics return 0: the switch's `default`).
+pub const MEM_HEAP_NULL: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_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;
@@ -519,8 +523,8 @@ pub struct Options {
/// 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
+ /// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`; `MEM_HEAP_NULL`
+ /// outside the windows) – one access per site, with no branch, 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`:
diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs
index b6dd120..31c2e17 100644
--- a/crates/xcl/src/gpu/recomp/pso.rs
+++ b/crates/xcl/src/gpu/recomp/pso.rs
@@ -105,7 +105,7 @@ pub fn in_switch_form<R>(f: impl FnOnce() -> R) -> R {
}
/// 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`)
+/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`..=`MEM_HEAP_NULL` made by `console_heap::set_window_views`)
/// instead of a `switch` over root UAVs. Opt-in: on with `XCL_HEAP_WINDOWS=1`, unless the views
/// could not be made (no shared heap: then the switch, as before). Off by default: two NVIDIA
/// setups failed with it (the driver's compiler ending the process; a device removal when the
diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs
index ed68335..5c20dcf 100644
--- a/crates/xcl/src/gpu/recomp/runner.rs
+++ b/crates/xcl/src/gpu/recomp/runner.rs
@@ -1528,7 +1528,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 + win_count as u32,
+ NumDescriptors: super::MEM_HEAP_NULL + 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
@@ -1540,6 +1540,9 @@ 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);
}
+ let mut h = dh.GetCPUDescriptorHandleForHeapStart();
+ h.ptr += super::MEM_HEAP_NULL as usize * inc;
+ dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(0)), h);
list.SetDescriptorHeaps(&[Some(dh.clone())]);
list.SetComputeRootSignature(&gpu.rs);
list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress());
@@ -1692,7 +1695,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 + win_count as u32,
+ NumDescriptors: super::MEM_HEAP_NULL + 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
@@ -1703,6 +1706,9 @@ 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);
}
+ let mut h = dh.GetCPUDescriptorHandleForHeapStart();
+ h.ptr += super::MEM_HEAP_NULL as usize * inc;
+ dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(0)), h);
list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]);
list.SetComputeRootSignature(rs);
list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress());
diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs
index 527dc4e..2a56083 100644
--- a/crates/xcl/src/gpu/recomp/tests.rs
+++ b/crates/xcl/src/gpu/recomp/tests.rs
@@ -3808,23 +3808,32 @@ 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);
+ memory_windows_above_4_gib(2, 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);
+ memory_windows_above_4_gib(2, true);
}
-fn memory_windows_above_4_gib(heap: bool) {
+// Adapted from XCL PR #822, e9705bb (GPL-2.0-only):
+// https://github.com/xcl-dev/xcl/pull/822. Also check 8 windows and explicit Direct DXIL.
+#[test]
+fn gpu_memory_windows_beyond_the_root_uavs() {
+ for windows in [8, 16] {
+ memory_windows_above_4_gib(windows, true);
+ }
+}
+
+fn memory_windows_above_4_gib(windows: usize, heap: bool) {
if !gpu_ready() {
return;
}
- let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap();
- let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64);
- assert_eq!(w1 - w0, 1 << 32);
+ let arena = crate::gpu::uma::Uma::with_windows(windows, 1 << 20).unwrap();
+ let (w0, w1) = (arena.window(0).0 as u64, arena.window(windows - 1).0 as u64);
+ assert_eq!(w1 - w0, ((windows - 1) as u64) << 32);
let word = |a: u64| unsafe { &mut *(a as *mut u32) };
*word(w1 + 0x1000) = 0xC0FFEE;
*word(w1 + 0x1004) = 0x1234;
@@ -3849,12 +3858,19 @@ fn memory_windows_above_4_gib(heap: bool) {
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, heap_windows: heap, ..Default::default() })).unwrap();
+ let t = translate(&p, &on_gpu(Options { mem_windows: windows as u32, 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(4u + xcl_w)]"), heap);
let hlsl_dxil = || super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap();
- let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil());
+ let dxil = if windows > 4 && runner::direct_dxil() {
+ // direct_or intentionally falls back above four windows: do not count that as DXIL coverage.
+ crate::gpu::dxil::kernel::translate(&p, crate::gpu::dxil::kernel::KernelOptions {
+ wave64: true, split: runner::split_wave64(),
+ mem_windows: windows as u32 | super::HEAP_WINDOWS, sampler_base: 0,
+ }).expect("expanded direct DXIL")
+ } else {
+ direct_or(&p, &on_gpu(Options { mem_windows: windows as u32, heap_windows: heap, ..Default::default() }), hlsl_dxil())
+ };
let hi = |a: u64| (a >> 32) as u32;
let mut st = KernelState::default();
st.sgpr[2..4].copy_from_slice(&[(w1 + 0x1000) as u32, hi(w1)]);
@@ -3883,6 +3899,13 @@ fn memory_windows_above_4_gib(heap: bool) {
}
assert_eq!(*word(w1 + 0x6000), 64, "global_atomic_add in window 1");
assert_eq!(*word(w0 + 0x6000), 0, "nothing in window 0 at the same low address");
+ if heap {
+ let null = super::MEM_HEAP_NULL - super::MEM_HEAP_BASE;
+ let index = if windows as u32 >= null { format!("min(xcl_w, {null}u)") } else { format!("select(xcl_w < {windows}u, xcl_w, {null}u)") };
+ assert!(t.hlsl.contains(&format!("ResourceDescriptorHeap[NonUniformResourceIndex({}u + {index})]", super::MEM_HEAP_BASE)));
+ assert!(!t.hlsl.contains("if (xcl_w"), "heap windows: no branch around an access");
+ }
+ println!("{windows} windows, target {}, direct={}: scalar/buffer/global loads, stores and atomic output correct", windows - 1, runner::direct_dxil());
}
/// Out-of-UMA addresses must NEVER alias onto live UMA windows via `& 3`:
@@ -3895,24 +3918,31 @@ fn memory_windows_above_4_gib(heap: bool) {
/// on `global_load`/`global_store` updates the target window accurately.
#[test]
fn gpu_memory_windows_reject_out_of_uma_aliasing() {
- memory_windows_reject_out_of_uma_aliasing(false);
+ memory_windows_reject_out_of_uma_aliasing(false, 2);
}
/// The same with the windows taken from the descriptor heap (`Options::heap_windows`): an
/// address outside them reads 0 and drops its stores and atomics there too.
#[test]
fn gpu_heap_windows_reject_out_of_uma_aliasing() {
- memory_windows_reject_out_of_uma_aliasing(true);
+ memory_windows_reject_out_of_uma_aliasing(true, 2);
+}
+
+/// Cover partial and complete expanded layouts; the full layout uses the min-index path.
+#[test]
+fn gpu_heap_windows_reject_out_of_uma_aliasing_all_slots() {
+ for windows in [4, 8, 16] { memory_windows_reject_out_of_uma_aliasing(true, windows); }
}
-fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
+fn memory_windows_reject_out_of_uma_aliasing(heap: bool, windows: u32) {
if !gpu_ready() {
return;
}
- let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap();
+ let arena = crate::gpu::uma::Uma::with_windows(windows as usize, 1 << 20).unwrap();
let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64);
assert_eq!(w1 - w0, 1 << 32);
let base_hi = (w0 >> 32) as u32;
+ let outside = windows.max(4);
assert!(base_hi >= 4);
let word = |a: u64| unsafe { &mut *(a as *mut u32) };
@@ -3933,24 +3963,24 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
(n, "ENC_FLAT_GLBL", f.iter().map(|&(a, b)| (unsafe { std::mem::transmute::<&str, &'static str>(a) }, b)).collect(), None)
};
let list = vec![
- // 1. Out-of-UMA s_load from hi = base_hi + 4 (would alias w0 under `& 3`) -> must read 0
+ // 1. Out-of-UMA s_load from hi = base_hi + outside (would alias w0 under `& 3`) -> must read 0
("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 30), ("SBASE", 1), ("OFFSET", 0)], None), // s[2:3]
// 2. 32-bit hi == 0 s_load at offset 0x4000 -> MUST read w0 + 0x4000
("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 31), ("SBASE", 2), ("OFFSET", 0)], None), // s[4:5]
- // 3. Out-of-UMA buffer_store with V# hi = base_hi + 5 and stride = 4 -> must NOT touch w1 + 0x1000
+ // 3. Out-of-UMA buffer_store with V# hi = base_hi + outside + 1 and stride = 4 -> must NOT touch w1 + 0x1000
("BUFFER_STORE_DWORD", "ENC_MUBUF", vec![("VDATA", 1), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None), // s[8:11]
- // 4. Out-of-UMA buffer_load with V# hi = base_hi + 5 and stride = 4 -> must read 0 (v2)
+ // 4. Out-of-UMA buffer_load with V# hi = base_hi + outside + 1 and stride = 4 -> must read 0 (v2)
("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 2), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None),
// 5. Valid strided V# buffer_load from w1 + 0x5000 (d1 has non-zero stride 4 in bits 29:16) -> must read 0x5566_7788 (v3)
("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 3), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), // s[12:15]
- // 6. Out-of-UMA global_store with hi = base_hi + 4 (would alias w0 + 0x1000) -> dropped
+ // 6. Out-of-UMA global_store with hi = base_hi + outside (would alias w0 + 0x1000) -> dropped
glbl("GLOBAL_STORE_DWORD", &[("ADDR", 4), ("DATA", 1), ("SADDR", 0x7D), ("OFFSET", 0)]),
// 7. Out-of-UMA global_store with hi = 0 (null/32-bit pointer at 0x2000) -> dropped, must NOT touch w0 + 0x2000
glbl("GLOBAL_STORE_DWORD", &[("ADDR", 6), ("DATA", 1), ("SADDR", 0x7D), ("OFFSET", 0)]),
- // 8. Out-of-UMA global_atomic_add (hi = base_hi + 5) & global_atomic_inc CAS loop (hi = 0xFFFF_FFFF) -> dropped & terminates cleanly
+ // 8. Out-of-UMA global_atomic_add (hi = base_hi + outside + 1) & global_atomic_inc CAS loop (hi = 0xFFFF_FFFF) -> dropped & terminates cleanly
glbl("GLOBAL_ATOMIC_ADD", &[("VDST", 10), ("ADDR", 8), ("DATA", 1), ("SADDR", 0x7D), ("OFFSET", 0), ("GLC", 1)]),
glbl("GLOBAL_ATOMIC_INC", &[("VDST", 11), ("ADDR", 12), ("DATA", 1), ("SADDR", 0x7D), ("OFFSET", 0), ("GLC", 1)]),
- // 9. Out-of-UMA buffer_atomic_add with V# hi = base_hi + 4 (would alias w0 + 0x3000) -> dropped
+ // 9. Out-of-UMA buffer_atomic_add with V# hi = base_hi + outside (would alias w0 + 0x3000) -> dropped
("BUFFER_ATOMIC_ADD", "ENC_MUBUF", vec![("VDATA", 14), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1), ("GLC", 1)], None), // s[16:19]
// 10. 64-bit carry on global_load: s[20:21] = (w0 + 0xFFFF_FFF0) + v16 (0x20) -> w1 + 0x10 -> must read 0x99AA_BBCC (v17)
glbl("GLOBAL_LOAD_DWORD", &[("VDST", 17), ("ADDR", 16), ("SADDR", 20), ("OFFSET", 0)]),
@@ -3959,17 +3989,23 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
];
let refs: Vec<(&str, &str, &[(&str, u64)], Option<u32>)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect();
let p = prog(&refs);
- let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap();
+ let t = translate(&p, &on_gpu(Options { mem_windows: windows, heap_windows: heap, ..Default::default() })).unwrap();
assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap);
let hlsl_dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap();
- let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil);
+ let dxil = if windows > 4 && runner::direct_dxil() {
+ crate::gpu::dxil::kernel::translate(&p, crate::gpu::dxil::kernel::KernelOptions {
+ wave64: true, split: runner::split_wave64(), mem_windows: windows | super::HEAP_WINDOWS, sampler_base: 0,
+ }).expect("expanded direct DXIL")
+ } else {
+ direct_or(&p, &on_gpu(Options { mem_windows: windows, heap_windows: heap, ..Default::default() }), hlsl_dxil)
+ };
let mut st = KernelState::default();
- st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + 4]); // s[2:3]: out-of-UMA hi = base_hi + 4
+ st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + outside]); // s[2:3]: out-of-UMA hi = base_hi + outside
st.sgpr[4..6].copy_from_slice(&[0x4000, 0]); // s[4:5]: hi == 0 32-bit descriptor read
- st.sgpr[8..12].copy_from_slice(&[0x1000, ((base_hi + 5) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA V# (aliases w1 under & 3)
+ st.sgpr[8..12].copy_from_slice(&[0x1000, ((base_hi + outside + 1) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA V# (aliases w1 under & 3)
st.sgpr[12..16].copy_from_slice(&[0x5000, ((base_hi + 1) & 0xFFFF) | (4 << 16), 64, 0]); // valid strided V# in w1
- st.sgpr[16..20].copy_from_slice(&[0x3000, ((base_hi + 4) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA atomic V# (aliases w0 under & 3)
+ st.sgpr[16..20].copy_from_slice(&[0x3000, ((base_hi + outside) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA atomic V# (aliases w0 under & 3)
st.sgpr[20..22].copy_from_slice(&[0xFFFF_FFF0, base_hi]); // carry base
st.sgpr[22..24].copy_from_slice(&[0, base_hi]); // borrow base (0 - 16 borrows into base_hi - 1)
for r in st.vgpr.iter_mut() {
@@ -3980,11 +4016,11 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
r[11] = 0x7777_7777;
r[14] = 0xBAD0_DEAD;
r[4] = 0x1000;
- r[5] = base_hi + 4; // out-of-UMA global_store (aliases w0 under & 3)
+ r[5] = base_hi + outside; // out-of-UMA global_store (aliases w0 under & 3)
r[6] = 0x2000;
r[7] = 0; // hi == 0 global_store (null pointer -> must be dropped)
r[8] = 0x2000;
- r[9] = base_hi + 5; // out-of-UMA global_atomic_add (aliases w1 under & 3)
+ r[9] = base_hi + outside + 1; // out-of-UMA global_atomic_add (aliases w1 under & 3)
r[12] = 0x3000;
r[13] = 0xFFFF_FFFF; // out-of-UMA global_atomic_inc CAS loop
r[16] = 0x20; // carry offset: 0xFFFF_FFF0 + 0x20 = 0x1_0000_0010 -> w1 + 0x10
@@ -4008,6 +4044,7 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
assert_eq!(*word(w1 + 0x2000), CANARY1, "out-of-UMA global_atomic_add must not clobber w1");
assert_eq!(*word(w0 + 0x3000), CANARY0, "out-of-UMA buffer_atomic_add must not clobber w0");
assert_eq!(*word(w1 + 0x3000), CANARY1, "out-of-UMA global_atomic_inc must not clobber w1");
+ println!("INVALID windows={windows} heap={heap} adapter={} checks passed", runner::adapter().unwrap());
}
/// The start-up check of the coherent UMA windows (`real::check_uma_import`): the GPU sees what
diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs
index 14d4f36..248a198 100644
--- a/crates/xcl/src/hle/d3d12x/console_heap.rs
+++ b/crates/xcl/src/hle/d3d12x/console_heap.rs
@@ -167,8 +167,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_HEAP_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(),
});
}
@@ -212,10 +213,11 @@ pub fn window_views_failed() -> bool {
/// shared heap, made now if need be (`Options::heap_windows`: shaders take window k from there).
/// Active windows (`bytes > 0`) in wider layouts (8 / 16) must all have a valid buffer; unused
/// trailing slots (`(0, 0)`) safely alias window 0's buffer.
-pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool {
+/// `MEM_HEAP_NULL` after the windows is a null view; heap views require 64-bit atomics.
+pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)], atomics64: bool) -> bool {
let count = windows.len().max(crate::gpu::uma::MAX_WINDOWS);
let complete = count <= crate::gpu::uma::MAX_WINDOWS || windows.iter().all(|&(raw, bytes)| raw != 0 || bytes == 0);
- let ok = count <= crate::gpu::uma::MAX_HEAP_WINDOWS && complete && windows.first().is_some_and(|w| w.0 != 0) && shared_heap(dev) && {
+ let ok = atomics64 && count <= crate::gpu::uma::MAX_HEAP_WINDOWS && complete && windows.first().is_some_and(|w| w.0 != 0) && shared_heap(dev) && {
let (device, cpu, inc) = {
let g = GLOBAL.lock().unwrap();
let s = g.as_ref().unwrap();
@@ -229,11 +231,13 @@ 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);
}
+ let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + crate::gpu::recomp::MEM_HEAP_NULL as u64 * inc as u64) as usize };
+ device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(0)), at);
true
};
if !ok {
WINDOW_VIEWS_FAILED.store(true, std::sync::atomic::Ordering::Relaxed);
- crate::xlog_warn!("memory windows: could not bind {count} window(s) in the shared descriptor heap");
+ crate::xlog_warn!("memory windows: could not bind {count} window(s) (64-bit atomics on heap views: {atomics64}) in the shared descriptor heap");
}
ok
}
@@ -654,21 +658,21 @@ 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::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(),
+ next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(),
});
let window = (&mut resource as *mut _ as usize, 0x10000);
- assert!(set_window_views(&dev, &[window]));
- assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32);
+ assert!(set_window_views(&dev, &[window], true));
+ assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32 + 1);
let mut windows = [window; crate::gpu::uma::MAX_HEAP_WINDOWS];
- assert!(set_window_views(&dev, &windows));
- assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32);
+ assert!(set_window_views(&dev, &windows, true));
+ assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32 + 1);
// Unused trailing window `(0, 0)` safely aliases window 0; an active window that failed
// to open `(0, bytes > 0)` is rejected.
windows[7] = (0, 0);
- assert!(set_window_views(&dev, &windows));
- assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32);
+ assert!(set_window_views(&dev, &windows, true));
+ assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32 + 1);
windows[7] = (0, 0x10000);
- assert!(!set_window_views(&dev, &windows));
+ assert!(!set_window_views(&dev, &windows, true));
assert_eq!(CALLS.load(Ordering::Relaxed), 0);
assert!(UNLOCKED.load(Ordering::Relaxed), "device callback ran while GLOBAL was locked");
*GLOBAL.lock().unwrap() = None;
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index 9241a3a..88b52ea 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -370,7 +370,9 @@ unsafe fn open_uma(device: &ID3D12Device) {
// shaders take the windows from the shared descriptor heap (`pso::heap_windows`)
if n > 1 && crate::gpu::recomp::pso::heap_windows() {
let views: Vec<(usize, usize)> = bufs.iter().enumerate().map(|(k, b)| (b.0, u.window(k).1)).collect();
- if super::console_heap::set_window_views(device, &views) {
+ let mut o11 = D3D12_FEATURE_DATA_D3D12_OPTIONS11::default();
+ let atomics64 = device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS11, &mut o11 as *mut _ as *mut c_void, std::mem::size_of_val(&o11) as u32).is_ok() && o11.AtomicInt64OnDescriptorHeapResourceSupported.as_bool();
+ if super::console_heap::set_window_views(device, &views, atomics64) {
crate::xlog_info!("D3D12.X: memory windows from the shared descriptor heap (no per-access switch)");
}
} |
…them With heap windows (XCL_HEAP_WINDOWS=1) each memory access was guarded by `[branch] if (xcl_w >= windows)`. The guard gives every access two paths, and DXC's GVN can join their descriptor handles into a `phi` of `%dx.types.Handle`; NVIDIA refused such programs with E_OUTOFMEMORY in under a second (xcl-dev#756). Nothing in the form prevented it. Now the index is clamped instead: `min(xcl_w, 16)` with all heap windows in use, or a `select` with fewer, into ResourceDescriptorHeap. Slot MEM_HEAP_NULL = MEM_HEAP_BASE + MAX_HEAP_WINDOWS, after the window views, holds a null raw UAV: it reads 0 and drops stores and atomics, which is what the switch's `default` does. One path per access, so no handle `phi` can form. The shared heap's own allocations start after it. Heap views also need D3D12_OPTIONS11's AtomicInt64OnDescriptorHeapResourceSupported, for the 64-bit atomics on the windows; a device without it gets no views, and the shaders keep the switch over the root UAVs (window_views_failed). Rebased onto main with xcl-dev#1992 and xcl-dev#1998 (16 heap windows, expanded-window checks) by WebIdentity1's integration: the null view at MEM_HEAP_BASE + MAX_HEAP_WINDOWS rather than + MAX_WINDOWS, which would clamp valid higher windows; the window tests cover 4 / 8 / 16 layouts. Co-authored-by: WebIdentity1 <212448219+WebIdentity1@users.noreply.github.com>
dd9f1ff to
7372ef0
Compare
The preparation step (P0) for heap memory windows as a default, which @ivall invited on #680 (comment) and @Pipodi listed in #1269 (comment). Still opt-in (
XCL_HEAP_WINDOWS=1); nothing changes with the variable unset. Part of #1269.With heap windows, every memory access was
[branch] if (xcl_w >= windows) { default } m = ResourceDescriptorHeap[base + xcl_w]; .... The guard gives each access two paths, and DXC's GVN can join their handles into aphi %dx.types.Handle, which NVIDIA refused in under a second withE_OUTOFMEMORY(#756). Onmainthe programs that showed it no longer do (their translation changed withb8b1f49, as @psuedo-tty found too), so this PR doesn't claim to fix a refusal today. What it changes is that the form can't produce one: the index is clamped,min(xcl_w, 16u)with all 16 heap windows in use (aselectwith fewer), and the slot after the window views holds a null raw UAV that reads 0 and drops stores and atomics, as the switch'sdefaultdoes. One path per access.What is in it
One commit,
Recompiler: heap memory windows without a guard, a null view outside them, rebased ontomaincbc296a(#1992, #1998: 16 heap windows, the expanded-window checks) from @WebIdentity1's integration patch (comment):gpu/recomp/emit.rs(mem_accessors): the clamped index, no guard.gpu/recomp/mod.rs:MEM_HEAP_NULL=MEM_HEAP_BASE + MAX_HEAP_WINDOWS(descriptor 20;+ MAX_WINDOWSwould clamp valid higher windows), docs.hle/d3d12x/console_heap.rs:set_window_viewswrites the null view, and only with 64-bit atomics on heap views; the shared heap's own allocations start after it (21). The 4 null views at 0..3 (Recompiler: heap memory windows start after a null descriptor pair #1992) are unchanged.hle/d3d12x/real.rs: noAtomicInt64OnDescriptorHeapResourceSupported→ no views, and the shaders keep the switch (window_views_failed), as with no shared heap.gpu/recomp/runner.rs: the two test heaps get the null view too.gpu/recomp/tests.rs: the out-of-UMA aliasing and invalid-window tests cover 4 / 8 / 16 layouts and theminpath.gpu/uma.rs:expanded_heap_window_shaders_translate_and_validatechecks the clamped index (selectwith 8 windows,minwith 16) instead of the old guard.Tested
RTX 3050 8 GB (desktop, Ryzen 7 5800XT), NVIDIA 610.88, Windows 11 build 26300, Rust 1.100.0 MSVC, release, DXC 1.9.2602.17.
On
maincbc296a+ this PR,cargo test --release -p xcl --lib -- --test-threads=4: 1100 passed, 0 failed, 26 ignored. Same withXCL_HEAP_WINDOWS=1. WithXCL_DIRECT_DXIL=1, 1099 passed and 1 failed (gpu_image_get_resinfo_1d_array), which fails the same way onmaincbc296aalone.The new
gpu_heap_windows_reject_out_of_uma_aliasing_all_slotsfails with an aliasing index (xcl_w & 3u) in place of themin.cargo clippy --release -p xcl --all-targets: no new warnings (772 oncbc296aand on this branch).Five retail compute programs, measured before the rebase on
9e3831e(4 windows) (the list from [OFFICIAL] Looking for PRs with shaders optimization #1269, byfnv64of the console blob), split wave64, 4 windows, translated as the runtime does, then a coldCreateComputePipelineStatewith the runtime's root signature, one run each:mainguarded form4549529853faf5fda3c0b8a98beee431c9579f1bea53bccaf377ca6830935314f7016de4c088c4beNo handle
phiin either form on these five today. Driver times on this machine vary by up to ±25 % between runs of the same DXIL, so read the time column as "not slower".A title run with
XCL_HEAP_WINDOWS=1onmain9e3831eon this 8 GB card (for Recompiler: memory windows from the descriptor heap (no per-access switch) #680's open item 3): views made, 167 s, no device removal, no switch-form fallback, until the title's own watchdog exit.Regression run
Both with
XCL_HEAP_WINDOWS=1 XCL_NETWORK=0 XCL_PAGE_BUDGET_MB=4096, back to back:maincbc296a:This PR (
7372ef0): 95.0 % ofmain's frames, 110.9 % of its peak commit.Not tested
AtomicInt64OnDescriptorHeapResourceSupported(the fallback path is not exercised here).AI use
mainwith Recompiler: heap memory windows start after a null descriptor pair #1992 / UMA: support 8/16 heap windows (5/13 coherent) with 3-sparse (12 GiB) cap #1998 is @WebIdentity1's patch (prepared with Codex), applied as posted plus theuma.rstest update; I read the diff and ran the checks above.AI-assisted.