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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,9 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o
64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63
can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups
made up of complete native waves can use the per-lane form for branches on whole-wave masks.
With four heap-backed memory windows (`XCL_HEAP_WINDOWS=1`) and direct DXIL compute,
`XCL_BYTE_STORE_CS=<hex shader hash>` enables R8_UINT stores for single-byte writes in
that compute shader on adapters that support them. Use the same settings for precompile and play.
Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42).

```powershell
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/eh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ fn is_writable(va: usize, bytes: usize) -> bool {
if bytes > 0 && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) {
return true;
}
let _trap = crate::hle::d3d12x::watch_trap::guard(va, bytes);
let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
let found = unsafe { VirtualQuery(va as *const std::ffi::c_void, &mut m, std::mem::size_of_val(&m)) } != 0;
found
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() {
}
let code = two_segments(8192);
let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 };
let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 };
let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() };
let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len();
let (compact, plain) = (size(true), size(false));
assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves");
Expand Down
57 changes: 57 additions & 0 deletions crates/xcl/src/gpu/dxil/core_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,25 @@ fn gpu_direct_unaligned_multi_dword_format_store() {
assert_eq!(&got[0xFC..0x118], &want[0xFC..0x118], "bytes 0xFC..0x118 after the store at 0x102");
}

#[test]
fn typed_byte_store_adds_a_byte_view_and_keeps_the_raw_fallback() {
use crate::gpu::recomp::{BYTE_WINDOWS, HEAP_WINDOWS};
let code = prog(&[
("BUFFER_STORE_FORMAT_X", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None),
]);
let disassembly = |windows| {
let ko = KernelOptions { wave64: false, split: false, mem_windows: windows, sampler_base: 0 };
let dxil = translate(&code, ko).expect("formatted store translates");
super::validate::validate(&dxil).expect("valid formatted store DXIL");
super::validate::disassemble(&dxil).expect("disassemble formatted store")
};
let normal = disassembly(4 | HEAP_WINDOWS);
let typed = disassembly(4 | HEAP_WINDOWS | BYTE_WINDOWS);
let stores = |s: &str| s.matches("call void @dx.op.bufferStore.i32(").count();
assert_eq!(stores(&typed), stores(&normal) + 1);
assert!(typed.contains("@dx.op.atomicBinOp.i32"), "wider partial stores still use the raw view");
}

#[test]
fn window_at_lowers_to_32bit_carry_without_int64() {
let ko = KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 };
Expand Down Expand Up @@ -831,3 +850,41 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() {
}
}
}

#[test]
fn compute_lds_reservation_matches_descriptor_and_lane_storage() {
// Exercise both cache modes on ordinary CI without changing the test process environment.
if std::env::var_os("XCL_TEST_LDS_CHILD").is_none() {
for mode in ["0", "1"] {
let status = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "gpu::dxil::core_tests::compute_lds_reservation_matches_descriptor_and_lane_storage"])
.env("XCL_DECLARED_LDS", mode)
.env("XCL_TEST_LDS_CHILD", "1")
.status().unwrap();
assert!(status.success(), "declared LDS mode {mode}");
}
return;
}
use crate::gpu::recomp::CsInterface;
let code = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None)]);
for (threads, blocks, split, expected) in [
([64, 1, 1], 2u32, false, 256),
([8, 8, 1], 1, false, 129),
([8, 8, 1], 1, true, 135),
([128, 1, 1], 2, true, 269),
([8, 8, 1], 0, true, 8192),
([8, 8, 1], 64, true, 8192),
] {
let mut descriptor = [0u8; 0x48];
for (i, v) in [blocks << 15, threads[0], threads[1], threads[2]].into_iter().enumerate() {
descriptor[0x38 + 4*i..0x3c + 4*i].copy_from_slice(&v.to_le_bytes());
}
let cs = CsInterface::from_descriptor(&descriptor, 0).unwrap();
assert_eq!(cs.lds_dwords, blocks * 128);
let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 };
let dxil = super::kernel::translate_compute(&code, options, &cs).unwrap().dxil;
let dis = super::validate::disassemble(&dxil).unwrap();
let words = if super::kernel::declared_lds_enabled() { expected } else { 8192 };
assert!(dis.contains(&format!("@xcl_lds = external addrspace(3) global [{words} x i32]")), "{threads:?}, {blocks}, split={split}");
}
}
18 changes: 16 additions & 2 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ pub struct KernelOptions {
/// (the `gpu/dxil` sources are not in build.rs's translator source hash).
pub const TRANSLATOR_VERSION: u32 = 9;

/// Opt in for dispatches whose guest LDS contract is fixed by the pipeline header.
pub fn declared_lds_enabled() -> bool {
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ENABLED.get_or_init(|| std::env::var("XCL_DECLARED_LDS").is_ok_and(|value| value == "1"))
}

/// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this
/// translator, with the HLSL path as the fallback for what it cannot translate yet.
pub fn enabled() -> bool {
Expand Down Expand Up @@ -502,7 +508,7 @@ impl Lw {
s.enable_rov();
}
let coherent = cs.is_some() && crate::gpu::recomp::needs_coherent_mem(insts);
let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, coherent);
let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows & !crate::gpu::recomp::BYTE_WINDOWS, coherent);
let i32 = s.m.i32();
let z = s.m.i32c(0);
let mut lw = Lw {
Expand All @@ -517,6 +523,7 @@ impl Lw {
half: z,
mems,
heap_mem,
byte_windows: o.mem_windows & crate::gpu::recomp::BYTE_WINDOWS != 0 && heap_mem.is_some(),
res,
fmt_table: None,
fmt_desc_cache: HashMap::new(),
Expand Down Expand Up @@ -598,7 +605,14 @@ impl Lw {
if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() {
lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel);
}
lw.setup_storage(uses_lds, if split { slot } else { 1 });
let (declared, native_counter) = match entry {
Entry::Compute(cs) => {
let declared = if declared_lds_enabled() { cs.lds_dwords } else { 0 };
(declared, !split && (cs.threads[1] > 1 || cs.threads[2] > 1))
}
_ => (0, false),
};
lw.setup_storage(uses_lds, slot, declared, native_counter);
if let (Some(t), true) = (group_threads, split) {
lw.partner = match t {
0..=32 => Partner::Missing,
Expand Down
29 changes: 16 additions & 13 deletions crates/xcl/src/gpu/dxil/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,30 @@ use super::module::{BinOp, Pred, RmwOp, Value};
use super::ops::barrier;

impl Lw {
/// Groupshared storage, created in the entry block before anything else:
/// the program's LDS (`lds_words` > 0) and, in the split form, the halves'
/// exchange words — in the top of the LDS block when there is one (D3D12
/// allows 32 KB, the whole LDS), as the HLSL kernel lays it out.
pub fn setup_storage(&mut self, lds: bool, slot: u32) {
/// Put private lane-exchange words after the guest LDS. D3D12 permits
/// 8192 dwords in total, including any arrival counter for a native 2-D group.
pub fn setup_storage(&mut self, lds: bool, slot: u32, declared: u32, native_counter: bool) {
let i32 = self.s.m.i32();
self.xslot = slot.max(1);
if lds {
let g = self.s.groupshared("xcl_lds", i32, 8192);
let slots = 4 * self.xslot * self.waves;
let control = if self.split { slots + 2 * self.waves + 1 } else { u32::from(native_counter) };
// Unspecified or oversized reservations retain the existing 32 KiB layout.
let fits = declared != 0 && declared <= 8192 - control;
let words = if fits { declared + control } else { 8192 };
let g = self.s.groupshared("xcl_lds", i32, u64::from(words));
self.lds = Some(g);
if self.split {
// HLSL: exchange base = 8192 - slots - counters - 1 (slots = 4 · slot per console
// wave, 2 counters each); the program's LDS stops below it
let slots = 4 * self.xslot * self.waves;
let base = 8192 - slots - 2 * self.waves - 1;
let base = words - control;
self.lds_top = base - 1;
self.xs = Some((g, base));
self.xc = Some((g, base + slots));
self.xw = Some((g, 8191));
self.xw = Some((g, words - 1));
} else {
self.lds_top = 8191;
self.lds_top = if fits { declared - 1 } else { 8191 };
if native_counter {
self.xw = Some((g, words - 1));
}
}
} else if self.split {
let w = self.s.groupshared("xcl_xw", i32, 1);
Expand Down Expand Up @@ -117,7 +120,7 @@ impl Lw {
} else if y * z > 1 {
let i32 = self.s.m.i32();
let (g, at) = match (self.lds, lds_top_word) {
(Some(l), true) => (l, 8191),
(Some(_), true) => self.xw.expect("compute LDS arrival counter"),
_ => (self.s.groupshared("xcl_wt", i32, 1), 0),
};
let ai = self.c(at);
Expand Down
3 changes: 2 additions & 1 deletion crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ pub struct Lw {
/// the windows come from the descriptor heap (`lower_window`; `mems` only counts them):
/// Some(globallycoherent)
pub heap_mem: Option<bool>,
pub byte_windows: bool,
pub res: Option<RawUav>,
/// the buffer format table (`FMT_INFO`), created on first use
pub fmt_table: Option<Value>,
Expand Down Expand Up @@ -232,7 +233,7 @@ pub struct Lw {
pub xn: Value,
/// words per half in an exchange
pub xslot: u32,
/// the program's LDS (`xcl_lds`, 8192 dwords) and its last usable dword
/// the program's LDS (`xcl_lds`) and its last usable guest dword
pub lds: Option<super::ops::GroupShared>,
pub lds_top: u32,
/// DPP write enable of the instruction being lowered
Expand Down
26 changes: 25 additions & 1 deletion crates/xcl/src/gpu/dxil/lower_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,30 @@ impl Lw {
/// `st_bytes`: store the low `n` bytes of `r` at byte address `a` (n ≤ 16; partial
/// dwords through atomics so neighbours stay intact).
fn st_bytes(&mut self, a: Value, r: [Value; 4], n: Value) -> LResult<()> {
// A row of R8_UINT views spans one raw window. Partial multi-byte stores still use the atomic path.
if self.byte_windows {
let win = self.rd(super::lower::VAR_WIN);
let in_range = self.cmpc(Pred::ULt, win, self.mems.len() as u32);
let byte = self.cmpc(Pred::Eq, n, 1);
let typed = self.land(in_range, byte);
self.guarded(typed, &mut |lw| {
let row = lw.shlc(win, crate::gpu::recomp::BYTE_SEGMENTS.trailing_zeros());
let segment = lw.lshrc(a, crate::gpu::recomp::BYTE_SEGMENT_SHIFT);
let index = lw.or(row, segment);
let index = lw.addc(index, crate::gpu::recomp::BYTE_HEAP_BASE);
let coherent = lw.heap_mem.unwrap_or(false);
let view = lw.s.heap_typed_buffer_with_coherence(index, true, super::ops::CompType::U32, true, coherent);
let offset = lw.andc(a, (1 << crate::gpu::recomp::BYTE_SEGMENT_SHIFT) - 1);
let value = lw.andc(r[0], 255);
lw.s.buffer_store(view, offset, &[value]);
Ok(())
})?;
let other = self.lnot(typed);
return self.guarded(other, &mut |lw| lw.st_bytes_raw(a, r, n));
}
self.st_bytes_raw(a, r, n)
}
fn st_bytes_raw(&mut self, a: Value, r: [Value; 4], n: Value) -> LResult<()> {
let s = self.andc(a, 3);
let s = self.shlc(s, 3);
let b = self.andc(a, !3);
Expand Down Expand Up @@ -2072,7 +2096,7 @@ impl Lw {
fn lds_index(&mut self, at: Value) -> Value {
let i = self.lshrc(at, 2);
let i = self.andc(i, 8191);
if self.split {
if self.lds_top < 8191 {
let k = self.c(self.lds_top);
self.umin(i, k)
} else {
Expand Down
6 changes: 5 additions & 1 deletion crates/xcl/src/gpu/dxil/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,8 +553,12 @@ impl Shader {
}
/// `Buffer<comp>` / `RWBuffer<comp>` from the descriptor heap.
pub fn heap_typed_buffer(&mut self, index: Value, uav: bool, comp: CompType, nonuniform: bool) -> TypedBuffer {
self.heap_typed_buffer_with_coherence(index, uav, comp, nonuniform, false)
}
pub fn heap_typed_buffer_with_coherence(&mut self, index: Value, uav: bool, comp: CompType, nonuniform: bool, coherent: bool) -> TypedBuffer {
let h = self.handle_from_heap(index, false, nonuniform);
let handle = self.annotate(h, kind::TYPED_BUFFER | if uav { 0x1000 } else { 0 }, typed_props(comp, 1));
let properties = kind::TYPED_BUFFER | if uav { 0x1000 } else { 0 } | if coherent { 0x4000 } else { 0 };
let handle = self.annotate(h, properties, typed_props(comp, 1));
TypedBuffer { handle, comp, binding: None }
}
fn comp_ty(&mut self, c: CompType) -> Ty {
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/dxil/robustness_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ fn translate_all() -> Vec<Vec<u8>> {
input_ena: 0x302,
attrs: None,
};
let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 };
let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() };
let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 };
let mut out = Vec::new();
for (w, s) in [(false, false), (true, true), (true, false)] {
Expand Down
4 changes: 2 additions & 2 deletions crates/xcl/src/gpu/recomp/link_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ fn bench_memory_window_accessors() {
for round in 0..3 {
for windows in [1, 4] {
nonce = nonce.wrapping_mul(0x9E37_79B1) | 1;
let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1 };
let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() };
let t = translate(&program(n, nonce), &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, mem_windows: windows, ..Default::default() })).unwrap();
assert!(t.complete(), "{:?}", t.unsupported_why);
let forms = if windows == 1 {
Expand Down Expand Up @@ -212,7 +212,7 @@ fn linked_programs_keep_their_declarations() {
let list = [buf("BUFFER_LOAD_DWORD", 2, coherent), buf("BUFFER_STORE_DWORD", 3, false)];
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 cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1 };
let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() };
let t = translate(&p, &Options { mode: Mode::Compute(cs), wave64, mem_windows: 4, ..Default::default() }).unwrap();
let size = if wave64 { 64 } else { 32 };
assert!(t.hlsl.contains(&format!("[WaveSize({size})]")), "{}", t.hlsl);
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/recomp/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3072,7 +3072,7 @@ pub(crate) mod tests {
}

pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface {
crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }
crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }
}

/// A compute program run on the CPU over `groups` groups (wave32): the memory after.
Expand Down
8 changes: 8 additions & 0 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ pub const MEM_HEAP_BASE: u32 = 4;
/// 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;
/// An additional descriptor row for single-byte format stores. The count still describes the raw windows.
pub(crate) const BYTE_WINDOWS: u32 = 0x200;
pub(crate) const BYTE_HEAP_BASE: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32;
pub(crate) const BYTE_SEGMENT_SHIFT: u32 = 27;
pub(crate) const BYTE_SEGMENTS: u32 = 1 << (32 - BYTE_SEGMENT_SHIFT);

pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool {
windows <= crate::gpu::uma::MAX_WINDOWS
Expand Down Expand Up @@ -237,6 +242,8 @@ impl GsInterface {
/// Compute shader with the console's dispatch ABI (see the module docs).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CsInterface {
/// Static workgroup LDS from COMPUTE_PGM_RSRC2, in dwords. Zero means unspecified.
pub lds_dwords: u32,
pub threads: [u32; 3],
pub user_sgprs: u32,
/// TGID_X / Y / Z enabled: the group id follows the user SGPRs in this order
Expand All @@ -262,6 +269,7 @@ impl CsInterface {
fn from_rsrc2(threads: [u32; 3], r: u32) -> Self {
Self {
threads,
lds_dwords: ((r >> 15) & 0x1ff) * 128,
user_sgprs: (r >> 1) & 31,
tgid: [(r >> 7) & 1 == 1, (r >> 8) & 1 == 1, (r >> 9) & 1 == 1],
tg_size: (r >> 10) & 1 == 1,
Expand Down
Loading
Loading