From 3ecf4cffc31a631e207ce2004a87f05d1a49feba Mon Sep 17 00:00:00 2001 From: Foniass <107039406+Foniass@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:11:55 +0100 Subject: [PATCH] Wave64 console programs on GPUs with 32-lane waves only: two exchanging wave32 halves NVIDIA's D3D12 wave range is 32..32, so a [WaveSize(64)] compute shader is rejected at PSO creation: wave64 compute programs were refused there (their dispatches skipped every frame), and mesh / ES+GS programs ran as two independent halves only when they had no cross-half operation. Now, when the device cannot run 64-lane waves (the same detection as before, `pso::wave32_only_for_device`), each console wave of a wave64 kernel, compute, mesh or ES+GS program runs as two hardware wave32s of the same thread group that exchange through groupshared memory wherever a value has to be the whole wave's: every mask (ballot), v_readlane / v_readfirstlane, ds_bpermute and GLC scalar loads. Both halves then hold the full 64-bit EXEC / VCC and identical SGPRs and take every branch the same way; DPP, ds_swizzle and v_permlane(x)16 stay inside a half and need nothing. One console wave per group meets at group barriers; several (mesh, compute > 64 threads) meet pairwise through double-buffered slots and arrival counters, bounded so that a desynchronised pair degrades instead of hanging the GPU. Hardware threads take console thread ids in the order their waves arrive: NVIDIA does not form waves from consecutive thread indices for 3-D groups (8 x 8 x 4). GPUs with 64-lane waves get byte-identical HLSL for every native translation the test suite makes. Design, hazards and measured cost: docs/wave64-on-wave32.md. The idea of a groupshared rendezvous kept in the LDS tail, and the finding that NVIDIA rejects [WaveSize(64)], come from PR #33 (ElHombreAlex); the protocol here is new (double-buffered slots, counted arrivals, barriers where they are legal). Tests: the instruction tests run on 32-lane GPUs too (`runner::options`), and the kernel runner fails when the two halves end with different SGPRs; new tests for cross-half masks, lane reads and scalar loads, for four diverging console waves per group in 1-D and 3-D groups, mesh form checks, and an ignored benchmark (`bench_split_wave64`). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/emit.rs | 310 ++++++++++++++++++++++++--- crates/xcl/src/gpu/recomp/mod.rs | 44 ++-- crates/xcl/src/gpu/recomp/pso.rs | 32 +-- crates/xcl/src/gpu/recomp/runner.rs | 32 ++- crates/xcl/src/gpu/recomp/tests.rs | 318 +++++++++++++++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 14 +- crates/xcl/tests/console_shaders.rs | 2 +- crates/xcl/tests/gpu_pso_e2e.rs | 2 +- docs/wave64-on-wave32.md | 136 ++++++++++++ 9 files changed, 756 insertions(+), 134 deletions(-) create mode 100644 docs/wave64-on-wave32.md diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 3ebd7bc..edfc5e1 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; -use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -36,6 +36,9 @@ pub(super) struct Em { uses_lds: bool, /// scratch_* used: declare the per-lane private memory uses_scratch: bool, + /// split wave64 (`x64`): words one exchange carries (1: masks and lane reads, up to 16: + /// coherent scalar loads, 32: `ds_bpermute`) + x64_words: usize, /// MIMG instruction address → its sampler's S# when the code builds it from constants pub static_ss: BTreeMap, /// the static samplers sampled with: (S#, comparison), in register order @@ -300,6 +303,7 @@ impl Em { ps_done: false, uses_lds: false, uses_scratch: false, + x64_words: 1, static_ss: BTreeMap::new(), static_used: Vec::new(), max_vgpr: 0, @@ -323,6 +327,41 @@ impl Em { format!("t{}", self.tmp) } + /// A wave64 program on a GPU with 32-lane waves only: each console wave runs as two + /// hardware wave32 halves that exchange masks and lane values (`PRELUDE_X64`, + /// docs/wave64-on-wave32.md). + fn x64(&self) -> bool { + self.opt.wave64 && self.opt.split_wave64 && matches!(self.opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_) | Mode::Geometry(_)) + } + + /// `ballot` of the program's wave (both halves' words in the split form). + fn ballot_fn(&self) -> &'static str { + if self.x64() { + "xcl_x_ballot" + } else { + "ballot" + } + } + + /// Lane read whose source lane the ISA keeps in the reader's 32-lane half (DPP16, DPP8, + /// ds_swizzle, v_permlane(x)16). + fn rla_half_fn(&self) -> &'static str { + if self.x64() { + "xcl_x_rla_half" + } else { + "rla" + } + } + + /// Lane read with the same lane index in every lane (v_readlane, v_readfirstlane). + fn rla_uniform_fn(&self) -> &'static str { + if self.x64() { + "xcl_x_rla_uniform" + } else { + "rla" + } + } + fn act(&self) -> &'static str { // no short-circuit `?:` (HLSL 2021 makes it a branch – one per instruction at -O0) if self.opt.wave64 { @@ -532,7 +571,8 @@ impl Em { fn write_mask(&mut self, dst: &Dst, cond: &str) { let a = self.act(); let m = self.t(); - self.line(&format!("uint2 {m} = ballot(and({a}, ({cond})));")); + let ballot = self.ballot_fn(); + self.line(&format!("uint2 {m} = {ballot}(and({a}, ({cond})));")); if self.opt.wave64 { self.write64(dst, &format!("{m}.x"), &format!("{m}.y")); } else { @@ -562,7 +602,7 @@ impl Em { if name == "s_setpc_b64" { if let Mode::Geometry(g) = &self.opt.mode { return match g.gs_start { - Some(s) if s > 0 && self.opt.geometry_wave32 => Flow::JumpExpr(format!("select(xcl_es_phase, 0xFFFFFFFFu, {s}u)")), + Some(s) if s > 0 && self.x64() => Flow::JumpExpr(format!("select(xcl_es_phase, 0xFFFFFFFFu, {s}u)")), Some(s) if s > 0 => Flow::Jump(s), _ => Flow::End, }; @@ -613,7 +653,11 @@ impl Em { match name { "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" => Flow::End, "s_barrier" => { - if matches!(self.opt.mode, Mode::Kernel | Mode::Mesh(_) | Mode::Geometry(_) | Mode::Compute(_)) { + if self.x64() && matches!(self.opt.mode, Mode::Geometry(_)) { + // split ES+GS: the GS phase runs in the lower hardware wave alone (one console + // wave: nothing to wait for), a group barrier there would wait for the other + self.line("if (xcl_es_phase) GroupMemoryBarrierWithGroupSync();"); + } else if matches!(self.opt.mode, Mode::Kernel | Mode::Mesh(_) | Mode::Geometry(_) | Mode::Compute(_)) { self.line("GroupMemoryBarrierWithGroupSync();"); } Flow::Next @@ -1132,6 +1176,17 @@ impl Em { vals.push(v); } } + // split wave64, a coherent load (GLC / DLC: memory other waves may be writing): both + // halves take the lower half's values, so they cannot see two different ones + let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); + if self.x64() && coherent { + self.x64_words = self.x64_words.max(vals.len()); + for (i, v) in vals.iter().enumerate() { + self.line(&format!("xcl_x_put({i}u, {v});")); + } + let get: Vec = vals.iter().enumerate().map(|(i, v)| format!("{v} = xcl_x_get({i}u);")).collect(); + self.line(&format!("if (xcl_x_meet() && xcl_half != 0u) {{ {} }}", get.join(" "))); + } for (i, v) in vals.iter().enumerate() { let s = self.sreg(sdata + i as u64); self.line(&format!("{s} = {v};")); @@ -2074,7 +2129,8 @@ impl Em { self.line(&format!( "bool {t}_ok = and({t}_l >= 0, or({fi}, lanebit_at({el}, {eh}, (uint){t}_l)));" )); - self.line(&format!("uint {t} = rla({v}, (uint)max({t}_l, 0));")); + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({v}, (uint)max({t}_l, 0));")); let (rm, bm) = (fv("ROW_MASK"), fv("BANK_MASK")); // write enable: row/bank masks, and an invalid source either reads 0 (bound_ctrl) or disables let mut en = format!("((({rm}u >> (lane_id >> 4)) & 1u) != 0u && (({bm}u >> ((lane_id >> 2) & 3u)) & 1u) != 0u)"); @@ -2088,7 +2144,8 @@ impl Em { let sel: u64 = (0..8).map(|i| fv(&format!("LANE_SEL_{i}")) << (3 * i)).sum(); let fi = rdna2::field_value(d.enc, &d.words, "SRC0").unwrap_or(0) == 0xEA; self.line(&format!("uint {t}_l = (lane_id & ~7u) | (({sel}u >> (3u * (lane_id & 7u))) & 7u);")); - self.line(&format!("uint {t} = rla({v}, {t}_l);")); + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({v}, {t}_l);")); if !fi { self.line(&format!("{t} = select(lanebit_at({el}, {eh}, {t}_l), {t}, 0u);")); } @@ -2860,7 +2917,8 @@ impl Em { let (el, eh) = (self.sreg(126), self.sreg(127)); let eh = if self.opt.wave64 { eh } else { "0u".into() }; self.line(&format!("bool {t}_ok = or({fi}, lanebit_at({el}, {eh}, {t}_l));")); - self.line(&format!("uint {t} = rla({a}, {t}_l);")); + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({a}, {t}_l);")); if bound { format!("select({t}_ok, {t}, 0u)") } else { @@ -2871,13 +2929,15 @@ impl Em { let (el, eh) = (self.sreg(126), self.sreg(127)); let eh = if self.opt.wave64 { eh } else { "0u".into() }; let t = self.t(); - self.line(&format!("uint {t} = rla({a}, first_lane({el}, {eh}));")); + let rla = self.rla_uniform_fn(); + self.line(&format!("uint {t} = {rla}({a}, first_lane({el}, {eh}));")); self.write32(&dst, &t); return Ok(()); } "v_readlane_b32" => { let t = self.t(); - self.line(&format!("uint {t} = rla({a}, {b} & {wmask}u);")); + let rla = self.rla_uniform_fn(); + self.line(&format!("uint {t} = {rla}({a}, {b} & {wmask}u);")); self.write32(&dst, &t); return Ok(()); } @@ -3305,7 +3365,8 @@ impl Em { if let Some(decl) = decl { self.line(&decl); } - self.line(&format!("uint {t} = rla({a}, {src});")); + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({a}, {src});")); let dst = Dst::V(f("VDST")); self.write32(&dst, &t); return Ok(()); @@ -3313,7 +3374,13 @@ impl Em { "ds_bpermute_b32" => { let (a, v) = (self.vreg(f("ADDR")), self.vreg(f("DATA0"))); let m = if self.opt.wave64 { 63 } else { 31 }; - self.line(&format!("uint {t} = rla({v}, (({a} + {off16}u) >> 2) & {m}u);")); + let rla = if self.x64() { + self.x64_words = 32; + "xcl_x_rla_any" + } else { + "rla" + }; + self.line(&format!("uint {t} = {rla}({v}, (({a} + {off16}u) >> 2) & {m}u);")); let dst = Dst::V(f("VDST")); self.write32(&dst, &t); return Ok(()); @@ -3333,7 +3400,10 @@ impl Em { let addr = self.vreg(f("ADDR")); let a = format!("{t}_ad"); self.line(&format!("uint {a} = {addr};")); - let lds = |at: String| format!("xcl_lds[(({at}) >> 2) & 8191u]"); + // split wave64: the exchange lives in the top of the LDS block (`XCL_X_LDS_TOP` = the + // last dword below it) + let x64 = self.x64(); + let lds = |at: String| if x64 { format!("xcl_lds[min((({at}) >> 2) & 8191u, XCL_X_LDS_TOP)]") } else { format!("xcl_lds[(({at}) >> 2) & 8191u]") }; let mut st = Vec::new(); let rw = |n: &str| -> Option<(bool, u64, u64, bool)> { // (write?, dwords per element, stride of offsets (bytes), two elements?) @@ -3462,6 +3532,58 @@ impl Em { // ---------------------------------------------------------------- whole shader + /// Split wave64: threads of the console's thread group. + fn x64_threads(&self) -> u32 { + match &self.opt.mode { + Mode::Compute(cs) => cs.threads.iter().product(), + Mode::Mesh(ms) => ms.threads, + _ => 64, + } + } + + /// Split wave64: whether the pairs meet through arrival counters (several console waves + /// per group, or `XCL_WAVE64_SPIN` for testing) instead of group barriers. + fn x64_spin(&self) -> bool { + self.x64_threads() > 64 || std::env::var_os("XCL_WAVE64_SPIN").is_some() + } + + /// The console LDS block (`xcl_lds`) is declared before the split-wave64 prelude, which + /// keeps its exchange in the top of it. + fn x64_lds(&self) -> bool { + // geometry mode always has the LDS (the ES ring and the GS output) + self.x64() && (self.uses_lds || matches!(self.opt.mode, Mode::Geometry(_))) + } + + /// Storage and functions of the split wave64 form (`PRELUDE_X64`). + fn x64_prelude(&self, h: &mut String) { + let threads = self.x64_threads(); + let waves = threads.div_ceil(64).max(1) as usize; + let slot = self.x64_words; + // slots (console wave, half, parity), the arrival counters (console wave, half), the + // wave counter of `xcl_x_thread` + let (slots, counters) = (waves * 4 * slot, waves * 2); + let _ = writeln!(h, "#define XCL_X_THREADS {threads}u\n#define XCL_X_WAVES {waves}u\n#define XCL_X_SLOT {slot}u\n#define XCL_X_SPIN {}", self.x64_spin() as u32); + if self.x64_lds() { + // the D3D12 limit (32 KB) is the whole block already: the exchange takes its top, + // the program's LDS accesses stop below it (`XCL_X_LDS_TOP`) + let base = 8192 - slots - counters - 1; + h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB); the top holds the wave64 exchange\n"); + let _ = writeln!(h, "#define XCL_X_LDS_TOP {}u", base - 1); + let _ = writeln!(h, "#define XCL_XS(i) xcl_lds[{base}u + (i)]\n#define XCL_XC(i) xcl_lds[{}u + (i)]\n#define XCL_XW xcl_lds[8191u]", base + slots); + } else { + let _ = writeln!(h, "groupshared uint xcl_xs[{slots}];\ngroupshared uint xcl_xc[{counters}];\ngroupshared uint xcl_xw;"); + h.push_str("#define XCL_XS(i) xcl_xs[(i)]\n#define XCL_XC(i) xcl_xc[(i)]\n#define XCL_XW xcl_xw\n"); + } + h.push_str(PRELUDE_X64); + } + + /// Split wave64, at the start of `main`: the console thread this thread stands for + /// (`xcl_tid`, `xcl_x_thread`), its lane, half and wave, and the size of the other half. + fn x64_entry(&self, h: &mut String) { + h.push_str(" uint xcl_tid = xcl_x_thread(gi);\n lane_id = xcl_tid & 63u;\n xcl_half = (xcl_tid >> 5) & 1u;\n xcl_cw = xcl_tid >> 6;\n"); + h.push_str(" xcl_xn = XCL_X_THREADS > ((xcl_tid & ~31u) ^ 32u) ? min(32u, XCL_X_THREADS - ((xcl_tid & ~31u) ^ 32u)) : 0u;\n"); + } + pub fn finish(&self, body: &str) -> String { let mut h = String::new(); h.push_str("// generated by XCL (RDNA2 -> HLSL), do not edit\n"); @@ -3489,6 +3611,9 @@ impl Em { let _ = writeln!(h, "{ty} xcl_ss{k} : register(s{k}, space1);"); } h.push_str(PRELUDE); + if self.x64() { + self.x64_prelude(&mut h); + } let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); h.push_str(PRELUDE_MEM); @@ -3507,12 +3632,18 @@ impl Em { // hw_wave 64 with a wave32 program: the wave-size independent form (two halves) let split = self.opt.hw_wave == 64 && !self.opt.wave64; let lanes = if self.opt.wave64 || split { 64 } else { 32 }; - if self.uses_lds { + if self.uses_lds && !self.x64_lds() { h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB)\n"); } - let _ = writeln!(h, "[WaveSize({lanes})]\n[numthreads({lanes}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex)\n{{"); + // split wave64: 64 threads (the console wave) in two hardware wave32s + let hw_lanes = if self.x64() { 32 } else { lanes }; + let _ = writeln!(h, "[WaveSize({hw_lanes})]\n[numthreads({lanes}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex)\n{{"); if split { h.push_str(" uint xcl_hw_lane = WaveGetLaneIndex();\n xcl_w32 = WaveGetLaneCount() > 32u;\n xcl_half = xcl_w32 ? xcl_hw_lane >> 5 : 0u;\n lane_id = xcl_hw_lane & 31u;\n"); + } else if self.x64() { + self.x64_entry(&mut h); + // the console lane: its registers in io / res + h.push_str(" uint xcl_hw_lane = xcl_tid;\n"); } else { h.push_str(" uint xcl_hw_lane = WaveGetLaneIndex();\n lane_id = xcl_hw_lane;\n"); } @@ -3528,6 +3659,16 @@ impl Em { } let _ = writeln!(h, " res.Store({}u, scc);", KERNEL_SCC_SLOT * 4); h.push_str(" }\n"); + if self.x64() { + // the upper half's scalar state too: the runner checks both halves agree + h.push_str(" if (xcl_tid == 32u) {\n"); + for &c in &sg { + let _ = writeln!(h, " res.Store({}u, {});", (KERNEL_SPLIT_SGPRS + c as usize) * 4, sname(c).unwrap()); + } + let _ = writeln!(h, " res.Store({}u, scc);", (KERNEL_SPLIT_SGPRS + KERNEL_SCC_SLOT) * 4); + let _ = writeln!(h, " res.Store({}u, {KERNEL_SPLIT_MAGIC}u);", (KERNEL_SPLIT_SGPRS + KERNEL_SGPRS) * 4); + h.push_str(" }\n"); + } for &v in &self.vgprs { let _ = writeln!(h, " res.Store(({}u + xcl_hw_lane * {}u + {v}u) * 4u, v{v});", KERNEL_SGPRS, KERNEL_VGPRS); } @@ -3569,15 +3710,23 @@ impl Em { } Mode::Compute(cs) => { let lanes = if self.opt.wave64 { 64 } else { 32 }; - if self.uses_lds { + if self.uses_lds && !self.x64_lds() { h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB)\n"); } let [x, y, z] = cs.threads; + // split wave64: the same group in hardware wave32s (a console wave = two of them) + let hw_lanes = if self.x64() { 32 } else { lanes }; let _ = writeln!( h, - "[WaveSize({lanes})]\n[numthreads({x}, {y}, {z})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" + "[WaveSize({hw_lanes})]\n[numthreads({x}, {y}, {z})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" ); - h.push_str(" lane_id = WaveGetLaneIndex();\n"); + if self.x64() { + // the console thread's ids (`xcl_x_thread`), not this hardware thread's + self.x64_entry(&mut h); + let _ = writeln!(h, " gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;", x * y); + } else { + h.push_str(" lane_id = WaveGetLaneIndex();\n"); + } load_sgprs(&mut h); // system SGPRs after the user data: enabled group ids, then TG_SIZE let mut next = cs.user_sgprs as u64; @@ -3592,7 +3741,7 @@ impl Em { if cs.tg_size && sg.contains(&next) { let _ = writeln!(h, " {} = ({}u / {lanes}u) | ((gi / {lanes}u) << 6);", sname(next).unwrap(), x * y * z); } - h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); + let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); for &v in &self.vgprs { let init = match v { 0 => "gtid.x", @@ -3606,16 +3755,18 @@ impl Em { h.push_str("}\n"); } Mode::Mesh(ms) => { - let split_wave32 = self.opt.wave64 && self.opt.mesh_wave32; - let native_lanes = if !self.opt.wave64 || split_wave32 { 32 } else { 64 }; + // split wave64: each console wave in two hardware wave32s (`PRELUDE_X64`) + let native_lanes = if !self.opt.wave64 || self.x64() { 32 } else { 64 }; let lanes = if self.opt.wave64 { 64 } else { 32 }; - if self.uses_lds { + if self.uses_lds && !self.x64_lds() { h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB)\n"); } let t = ms.threads; let _ = writeln!(h, "[WaveSize({native_lanes})]\n[numthreads({t}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{{"); - if split_wave32 { - h.push_str(" xcl_half = (gi >> 5) & 1u;\n xcl_logical_wave64 = true;\n lane_id = WaveGetLaneIndex() + 32u * xcl_half;\n"); + if self.x64() { + // the console thread's index (`xcl_x_thread`), not this hardware thread's + self.x64_entry(&mut h); + h.push_str(" gi = xcl_tid;\n"); } else { h.push_str(" lane_id = WaveGetLaneIndex();\n"); } @@ -3628,7 +3779,7 @@ impl Em { if sg.contains(&3) { h.push_str(" s3 = (s3 & 0xF0FFFFFFu) | (xcl_wave << 24);\n"); } - h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); + let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); for &v in &self.vgprs { let init = if v == 5 { format!("gid.x * {t}u + xcl_slot") } else { "0u".into() }; let _ = writeln!(h, " uint v{v} = {init};"); @@ -3637,7 +3788,7 @@ impl Em { h.push_str("}\n"); } Mode::Geometry(g) => { - if !self.opt.geometry_wave32 { + if !self.x64() { let pg = super::GS_PRIMS_PER_GROUP; let rec = g.record(); let (vd, vb) = (rec.vert_dwords(), g.vertex_bytes()); @@ -3706,9 +3857,10 @@ impl Em { let maxt = g.max_vertex_count.saturating_sub(2).max(1); let nreg = g.input_registers(); let fetched = super::fetched_registers(&g.es_inputs); - let native_lanes = if self.opt.geometry_wave32 { 32 } else { 64 }; - h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB)\n"); - let _ = writeln!(h, "[WaveSize({native_lanes})]\n[numthreads(64, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{{"); + // split wave64 (the native form is above): the ES in both hardware wave32s, the GS + // (at most 21 primitives) in the lower one alone; `xcl_lds` comes with `PRELUDE_X64` + h.push_str("[WaveSize(32)]\n[numthreads(64, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{\n"); + h.push_str(" uint xcl_tid = xcl_x_thread(gi);\n gi = xcl_tid;\n"); let _ = writeln!(h, " uint xcl_total = io.Load({}u);\n uint xcl_vin = io.Load({}u);", super::IO_GS_PRIMS * 4, super::IO_GS_VERTICES * 4); let _ = writeln!(h, " uint xcl_p0 = gid.x * {pg}u;\n uint xcl_np = xcl_total > xcl_p0 ? min({pg}u, xcl_total - xcl_p0) : 0u;\n uint xcl_nv = 3u * xcl_np;"); let _ = writeln!(h, " uint xcl_rec = gid.x * {}u;", rec.record_dwords()); @@ -3718,11 +3870,8 @@ impl Em { h.push_str(" {\n"); let _ = writeln!(h, " bool xcl_es_phase = {};", if es { "true" } else { "false" }); let _ = writeln!(h, " uint xcl_entry_pc = {}u;", if es { 0 } else { gs_start }); - if self.opt.geometry_wave32 { - h.push_str(" lane_id = gi; xcl_half = gi >> 5; xcl_logical_wave64 = true;\n"); - } else { - h.push_str(" lane_id = gi; xcl_half = 0u; xcl_logical_wave64 = false;\n"); - } + // the GS phase has no other half to exchange with + let _ = writeln!(h, " lane_id = gi; xcl_half = gi >> 5; xcl_xn = {}u;", if es { 32 } else { 0 }); let _ = writeln!(h, " uint xcl_emitted = 0u, xcl_strip = 0u, xcl_ntri = 0u, xcl_gs_base = 0xFFFFFFFFu;\n uint xcl_tri[{maxt}];"); load_sgprs(h); if sg.contains(&2) { @@ -3731,7 +3880,7 @@ impl Em { if sg.contains(&3) { h.push_str(" s3 = xcl_nv | (xcl_np << 8); // merged wave info: ES vertices, GS primitives, wave 0\n"); } - h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); + h.push_str(" uint scc = 0u;\n { uint2 e0 = xcl_x_ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); for &v in &self.vgprs { let init = match v { // LDS dword offsets of the triangle's vertices (ES vertex i at i · item) @@ -4436,6 +4585,99 @@ void st_bytes(uint a, uint4 r, uint n) { uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), c[(sel - 4u) & 3u])); } "#; +/// A console wave64 as two hardware wave32 halves of one thread group (docs/wave64-on-wave32.md): +/// per-lane code is unchanged, and the halves meet ("exchange") wherever a value has to be +/// the whole wave's – masks, lane reads, coherent scalar loads – so both hold the same SGPRs +/// and take the same branches. Follows `PRELUDE` (`lane_id`, `xcl_half`); the emitter +/// defines `XCL_X_SLOT` (words per exchange), `XCL_X_SPIN` and the storage `XCL_XS(i)` / +/// `XCL_XC(i)` before it. +const PRELUDE_X64: &str = r#" +// console wave in the group; exchanges so far (the same in both halves); lanes of the other +// half (0: it does not exist – nothing to exchange with) +static uint xcl_cw = 0u; +static uint xcl_xk = 0u; +static uint xcl_xn = 0u; +// the other half did not arrive in time (a desynchronised pair): no more exchanges, the +// wave finishes with its own half's values instead of hanging the GPU +static bool xcl_x_dead = false; +// The console thread (index in the group) this hardware thread stands for. The threads of a +// group are interchangeable, but the console forms its waves from consecutive thread +// indices and the PC GPU need not (NVIDIA does not for 3-D groups such as 8 x 8 x 4): each +// hardware wave takes the next 32 console threads as it arrives (a partial wave the last +// ones), and the program sees those threads' ids. Also zeroes the arrival counters. +uint xcl_x_thread(uint gi) { + if (gi == 0u) XCL_XW = 0u; + if (gi < 2u * XCL_X_WAVES) XCL_XC(gi) = 0u; + GroupMemoryBarrierWithGroupSync(); + uint n = WaveActiveCountBits(true); + uint base = XCL_X_THREADS & ~31u; + if (WaveIsFirstLane() && n == 32u) InterlockedAdd(XCL_XW, 32u, base); + return WaveReadLaneFirst(base) + WavePrefixCountBits(true); +} +// a slot per (console wave, half, parity of the exchange): the other half can be at most one +// exchange ahead, so it never overwrites the slot being read +uint xcl_x_at(uint half, uint k) { return ((xcl_cw * 2u + half) * 2u + (k & 1u)) * XCL_X_SLOT; } +void xcl_x_put(uint i, uint v) { XCL_XS(xcl_x_at(xcl_half, xcl_xk) + i) = v; } +uint xcl_x_get(uint i) { return XCL_XS(xcl_x_at(xcl_half ^ 1u, xcl_xk - 1u) + i); } +// meet the other half after `xcl_x_put`: true = its words are readable (`xcl_x_get`) +bool xcl_x_meet() { + uint k = xcl_xk; + xcl_xk = k + 1u; + if (xcl_xn == 0u) return false; +#if XCL_X_SPIN + // several console waves per group: a group barrier would wait for the other console + // waves too, whose control flow may differ – the pair meets through arrival counters + // instead. Every lane fences its slot store; the wave's lane count (a wave operation: + // all its lanes got here) goes into this half's counter in one atomic, and one lane + // waits for the other half's count (one atomic per poll), the others for its verdict. + if (xcl_x_dead) return false; + GroupMemoryBarrier(); + uint lanes = WaveActiveCountBits(true); + uint ok = 1u; + if (WaveIsFirstLane()) { + uint o; + InterlockedAdd(XCL_XC(xcl_cw * 2u + xcl_half), lanes, o); + uint need = (k + 1u) * xcl_xn; + [loop] for (uint n = 0u; ; n++) { + uint c; + InterlockedAdd(XCL_XC(xcl_cw * 2u + (xcl_half ^ 1u)), 0u, c); + if ((int)(c - need) >= 0) break; + if (n >= (1u << 20)) { ok = 0u; break; } + } + } + if (WaveReadLaneFirst(ok) == 0u) { xcl_x_dead = true; return false; } + GroupMemoryBarrier(); +#else + // one console wave per group: its two halves are the whole group and reach every + // exchange together + GroupMemoryBarrierWithGroupSync(); +#endif + return true; +} +uint2 xcl_x_ballot(bool b) { + uint m = WaveActiveBallot(b).x; + xcl_x_put(0u, m); + uint o = xcl_x_meet() ? xcl_x_get(0u) : 0u; + return xcl_half != 0u ? uint2(o, m) : uint2(m, o); +} +// v_readlane / v_readfirstlane: the same lane index in both halves; the owner half's value +uint xcl_x_rla_uniform(uint v, uint l) { + uint m = WaveReadLaneAt(v, l & 31u); + xcl_x_put(0u, m); + uint o = xcl_x_meet() ? xcl_x_get(0u) : 0u; + return (l >> 5) == xcl_half ? m : o; +} +// ds_bpermute: any lane of the wave +uint xcl_x_rla_any(uint v, uint l) { + xcl_x_put(WaveGetLaneIndex(), v); + uint o = xcl_x_meet() ? xcl_x_get(l & 31u) : 0u; + uint m = WaveReadLaneAt(v, l & 31u); + return (l >> 5) == xcl_half ? m : o; +} +// DPP16, DPP8, ds_swizzle, v_permlane(x)16: the ISA keeps the source in the reader's half +uint xcl_x_rla_half(uint v, uint l) { return WaveReadLaneAt(v, l & 31u); } +"#; + const PRELUDE: &str = r#" static uint lane_id; // loop iterations a lane may run (`LOOP_GUARD`): far above what a working program needs diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 5478ca5..dc7a4c3 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -74,7 +74,11 @@ pub const KERNEL_LANES: usize = 64; pub const KERNEL_SCC_SLOT: usize = 125; /// first dword of the export area in `res`: 64 targets × 64 lanes × 4 components pub const KERNEL_EXPORTS: usize = KERNEL_SGPRS + KERNEL_LANES * KERNEL_VGPRS; -pub const KERNEL_RES_DWORDS: usize = KERNEL_EXPORTS + 64 * KERNEL_LANES * 4; +/// split wave64 (`Options::split_wave64`): the upper half's SGPRs (+ SCC slot), then +/// `KERNEL_SPLIT_MAGIC` – the runner checks both halves ended with the same scalar state +pub const KERNEL_SPLIT_SGPRS: usize = KERNEL_EXPORTS + 64 * KERNEL_LANES * 4; +pub const KERNEL_SPLIT_MAGIC: u32 = 0x5741_5645; +pub const KERNEL_RES_DWORDS: usize = KERNEL_SPLIT_SGPRS + KERNEL_SGPRS + 1; /// Vertex shader interface. #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -465,10 +469,11 @@ pub struct Options { /// kernel mode only: 64 forces `[WaveSize(64)]` for a wave32 program, which then runs as /// two independent halves – the wave-size independent form VS/PS always get (tests) pub hw_wave: u32, - /// geometry mode: emulate one logical wave64 with two native wave32 phases - pub geometry_wave32: bool, - /// mesh mode: run a logical wave64 mesh program as two native wave32 halves - pub mesh_wave32: bool, + /// the GPU runs only 32-lane waves (`D3D12_FEATURE_DATA_D3D12_OPTIONS1::WaveLaneCountMax` + /// < 64, e.g. NVIDIA): each console wave of a wave64 kernel / compute / mesh / geometry + /// program runs as two hardware wave32 halves that exchange masks and lane values through + /// groupshared memory (`docs/wave64-on-wave32.md`). No effect on wave32 programs, VS / PS. + pub split_wave64: bool, /// first register (space 1) of the program's static samplers (another stage of the same /// pipeline may come first) pub static_sampler_base: u32, @@ -483,7 +488,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, geometry_wave32: false, mesh_wave32: 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, structured: true } } } @@ -1160,27 +1165,14 @@ pub fn geometry_wave32_hazards(code: &[u8]) -> BTreeSet<&'static str> { out } -/// Translate a complete ES+GS program for the adapter-selected geometry path. -pub fn translate_geometry(code: &[u8], interface: GsInterface, geometry_wave32: bool) -> Result { - if geometry_wave32 { - let hazards = geometry_wave32_hazards(code); - if !hazards.is_empty() { - return Err(format!("geometry program requires unsupported cross-half wave64 semantics: {hazards:?}")); - } - } - translate(code, &Options { mode: Mode::Geometry(interface), wave64: true, geometry_wave32, ..Default::default() }) +/// Translate a complete ES+GS program; `split_wave64`: for a GPU with 32-lane waves only. +pub fn translate_geometry(code: &[u8], interface: GsInterface, split_wave64: bool) -> Result { + translate(code, &Options { mode: Mode::Geometry(interface), wave64: true, split_wave64, ..Default::default() }) } -/// Translate an NGG mesh program; a wave64 program split into wave32 halves is refused -/// when it needs cross-half semantics, as for split geometry. -pub fn translate_mesh(code: &[u8], ms: MsInterface, wave64: bool, mesh_wave32: bool) -> Result { - if wave64 && mesh_wave32 { - let hazards = geometry_wave32_hazards(code); - if !hazards.is_empty() { - return Err(format!("mesh program requires unsupported cross-half wave64 semantics: {hazards:?}")); - } - } - translate(code, &Options { mode: Mode::Mesh(ms), wave64, mesh_wave32, ..Default::default() }) +/// Translate an NGG mesh program; `split_wave64`: for a GPU with 32-lane waves only. +pub fn translate_mesh(code: &[u8], ms: MsInterface, wave64: bool, split_wave64: bool) -> Result { + translate(code, &Options { mode: Mode::Mesh(ms), wave64, split_wave64, ..Default::default() }) } /// Wave size the program was compiled for: 64-bit EXEC/VCC writes mean wave64. @@ -1372,7 +1364,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // smaller for DXC and the driver on big programs) emit_structured(&ctx, &mut em, &mut code, 0, u64::MAX, None, 0, None, &BTreeSet::new(), 1, &mut blocks, &mut flags); } else { - if gs_jump.is_some() && opt.geometry_wave32 { + if gs_jump.is_some() && opt.split_wave64 && opt.wave64 { code.push_str(" uint pc = xcl_entry_pc;\n"); } else { code.push_str(" uint pc = 0;\n"); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 15ac366..f9b5753 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -41,7 +41,14 @@ pub struct Compiled { /// samplers take registers from `sampler_base` (space 1). /// Fails when the blob is not a console shader or the program is not fully translated. pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result { - let (mut t, profile) = console_translation(blob, stage, sampler_base)?; + console_to_dxil_for(blob, stage, sampler_base, false) +} + +/// `console_to_dxil` for a GPU that runs only 32-lane waves when `split_wave64` +/// (`wave32_only_for_device`): a wave64 compute program gets the split form +/// (`Options::split_wave64`) instead of `[WaveSize(64)]`, which such a driver rejects. +pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result { + let (mut t, profile) = console_translation(blob, stage, sampler_base, split_wave64)?; if let Some([r, g, b]) = (stage == Stage::Pixel).then(|| debug_color(blob)).flatten() { t.hlsl = t.hlsl.replacen(" return xo;\n}", &format!(" xo.t0 = float4({r:.3}, {g:.3}, {b:.3}, 1.0);\n return xo;\n}}"), 1); } @@ -130,10 +137,10 @@ fn debug_color(blob: &[u8]) -> Option<[f32; 3]> { /// The HLSL (and its DXC profile) `console_to_dxil` compiles. pub fn console_to_hlsl(blob: &[u8], stage: Stage) -> Result<(String, &'static str), String> { - console_translation(blob, stage, 0).map(|(t, p)| (t.hlsl, p)) + console_translation(blob, stage, 0, false).map(|(t, p)| (t.hlsl, p)) } -fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<(super::Translation, &'static str), String> { +fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { let sh = xbox::parse(blob).ok_or("not a console shader container")?; // the hardware variant for this pipeline slot: VS (not the ES variant used with GS), PS let want = match stage { @@ -155,7 +162,7 @@ fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<( }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::detect_wave64(code), static_sampler_base: sampler_base, mem_windows: mem_windows(), ..Default::default() })?; + let t = translate(code, &Options { mode, wave64: super::detect_wave64(code), split_wave64, static_sampler_base: sampler_base, mem_windows: mem_windows(), ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -193,7 +200,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option /// The mesh-shader (NGG) program of a console MS container; the pass-through carries what /// the pixel shader `ps` (its container: console or PC) reads. -pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, mesh_wave32: bool) -> Result { +pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 7)).ok_or("no NGG hardware variant")?; let mode = interface(blob, &sh, f).ok_or("unknown MS interface (e.g. lines / points)")?; @@ -201,15 +208,16 @@ pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, mesh_wave32: bool) -> Result let record = ms.clone(); let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - finish_two_pass(super::translate_mesh(code, ms.clone(), super::detect_wave64(code), mesh_wave32)?, record, ps) + finish_two_pass(super::translate_mesh(code, ms.clone(), super::detect_wave64(code), split_wave64)?, record, ps) } -/// Whether the adapter's supported wave range requires split geometry execution. -pub fn geometry_uses_wave32(wave_min: u32, wave_max: u32) -> bool { +/// Whether the adapter runs only 32-lane waves (its wave range lacks 64): wave64 compute, +/// mesh and geometry programs then need the split form. +pub fn wave32_only(wave_min: u32, wave_max: u32) -> bool { !(wave_min <= 64 && wave_max >= 64) } -pub fn geometry_uses_wave32_for_device(device: &ID3D12Device) -> bool { +pub fn wave32_only_for_device(device: &ID3D12Device) -> bool { let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); if unsafe { device.CheckFeatureSupport( @@ -222,14 +230,14 @@ pub fn geometry_uses_wave32_for_device(device: &ID3D12Device) -> bool { { return true; } - geometry_uses_wave32(options.WaveLaneCountMin, options.WaveLaneCountMax) + wave32_only(options.WaveLaneCountMin, options.WaveLaneCountMax) } /// A legacy GS pipeline: the ES variant of a console VS + the GS as one program. -pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, geometry_wave32: bool) -> Result { +pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { let (code, g) = super::geometry_program(vs, gs)?; let record = g.record(); - let translation = super::translate_geometry(&code, g, geometry_wave32)?; + let translation = super::translate_geometry(&code, g, split_wave64)?; finish_two_pass(translation, record, ps) } diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 85d20f4..a32e77d 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -350,6 +350,32 @@ pub fn wave64_supported() -> Result { gpu.as_ref().map(|x| x.wave64).map_err(|x| x.clone()) } +/// Whether wave64 programs need the split form here (`Options::split_wave64`): the +/// adapter runs only 32-lane waves. False without a usable GPU. +pub fn split_wave64() -> bool { + wave64_supported() == Ok(false) +} + +/// `Options` for programs run on this adapter: the split wave64 form where it is needed. +pub fn options(mode: super::Mode) -> super::Options { + super::Options { mode, split_wave64: split_wave64(), ..Default::default() } +} + +/// A split wave64 kernel stores the upper half's SGPRs too: both halves must end with the +/// same scalar state (they would otherwise have branched differently). +fn split_halves_agree(raw: &[u32]) -> Result<(), String> { + let at = super::KERNEL_SPLIT_SGPRS; + if raw[at + KERNEL_SGPRS] != super::KERNEL_SPLIT_MAGIC { + return Ok(()); + } + let differ: Vec = (0..KERNEL_SGPRS).filter(|&i| raw[i] != raw[at + i]).map(|i| format!("s{i}: {:#x} / {:#x}", raw[i], raw[at + i])).collect(); + if differ.is_empty() { + Ok(()) + } else { + Err(format!("split wave64: the halves ended with different SGPRs (lower / upper): {}", differ.join(", "))) + } +} + /// Whether the adapter runs mesh shaders (`mesh_draw`); an integrated RDNA2 GPU, for one, /// reports wave64 but no mesh shader tier. pub fn mesh_shaders_supported() -> Result { @@ -514,6 +540,7 @@ pub fn run_with_statics( .map(|l| raw[KERNEL_SGPRS + l * KERNEL_VGPRS..KERNEL_SGPRS + (l + 1) * KERNEL_VGPRS].to_vec()) .collect(); drop(bound); + split_halves_agree(&raw)?; Ok(KernelResult { sgpr: raw[..KERNEL_SGPRS].to_vec(), vgpr, scc: raw[KERNEL_SCC_SLOT], raw, mem: mem_out, textures: tex_out }) } } @@ -534,7 +561,7 @@ pub fn run_program(code: &[u8], state: &KernelState, extra: &[u32]) -> Result<(K /// Translate + compile + run RDNA2 code as a kernel, with test textures and samplers. pub fn run_code_with(code: &[u8], state: &KernelState, mem: &[u32], textures: &[TestTexture], samplers: &[TestSampler]) -> Result { - let t = super::translate(code, &super::Options::default())?; + let t = super::translate(code, &options(super::Mode::Kernel))?; if !t.complete() { return Err(format!("unsupported instructions: {:?}", t.unsupported)); } @@ -544,7 +571,7 @@ pub fn run_code_with(code: &[u8], state: &KernelState, mem: &[u32], textures: &[ /// Translate + compile + run RDNA2 code as a kernel. pub fn run_code(code: &[u8], state: &KernelState, mem: &[u32]) -> Result { - let opt = super::Options::default(); + let opt = options(super::Mode::Kernel); let t = super::translate(code, &opt)?; if !t.complete() { return Err(format!("unsupported instructions: {:?}", t.unsupported)); @@ -1172,6 +1199,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result bool { match (runner::adapter(), runner::wave64_supported(), super::dxc::location()) { - (Ok(_), Ok(true), Ok(_)) => true, + (Ok(_), Ok(_), Ok(_)) => true, (a, w, d) => { - println!("GPU/DXC wave64 unavailable – skipping ({:?} / {:?} / {:?})", a.as_ref().err(), w.ok(), d.as_ref().err()); - runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }); + println!("GPU/DXC unavailable – skipping ({:?} / {:?} / {:?})", a.as_ref().err(), w.as_ref().ok(), d.as_ref().err()); + runner::skip_test(if a.is_err() || w.is_err() { "no GPU" } else { "no DXC" }); false } } } +/// 64-lane hardware waves (a test of how a program runs in them). +fn wave64_hardware() -> bool { + let w = runner::wave64_supported() == Ok(true); + if !w { + println!("no 64-lane waves on this GPU – skipping"); + runner::skip_test("no wave64"); + } + w +} + +/// `o` for a program run on this adapter (the split wave64 form where it is needed). +fn on_gpu(o: Options) -> Options { + Options { split_wave64: runner::split_wave64(), ..o } +} + fn gpu_ready_wave32() -> bool { match (runner::adapter(), super::dxc::location()) { (Ok(_), Ok(_)) => true, @@ -107,9 +124,9 @@ fn geometry_wave32_rejects_cross_half_operations() { #[test] fn geometry_wave_path_selection_preserves_native_wave64() { - assert!(super::pso::geometry_uses_wave32(32, 32)); - assert!(!super::pso::geometry_uses_wave32(32, 64)); - assert!(!super::pso::geometry_uses_wave32(64, 64)); + assert!(super::pso::wave32_only(32, 32)); + assert!(!super::pso::wave32_only(32, 64)); + assert!(!super::pso::wave32_only(64, 64)); } #[test] @@ -1735,7 +1752,7 @@ fn gpu_mesh_mode_two_passes() { list.push(exp(20, 1, [21, 0, 0, 0], 1)); let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let code = prog(&refs); - let t = translate(&code, &Options { mode: Mode::Mesh(ms.clone()), wave64: true, ..Default::default() }).unwrap(); + let t = translate(&code, &on_gpu(Options { mode: Mode::Mesh(ms.clone()), wave64: true, ..Default::default() })).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let cs = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); let pass = mesh_passthrough(&ms); @@ -1983,7 +2000,7 @@ fn gpu_unified_memory_arena() { ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None), ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), ]); - let t = translate(&p, &Options::default()).unwrap(); + let t = translate(&p, &on_gpu(Options::default())).unwrap(); let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); let hi = (va >> 32) as u32; let mut st = KernelState::default(); @@ -2037,7 +2054,7 @@ 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, &Options { mem_windows: 2, ..Default::default() }).unwrap(); + let t = translate(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap(); assert!(t.hlsl.contains("RWByteAddressBuffer mem1 : register(u3)")); 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; @@ -2141,7 +2158,7 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), ]); let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 6, ..Default::default() }; - let t = translate(&p, &Options { mode: Mode::Compute(cs), mem_windows: 4, ..Default::default() }).unwrap(); + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), mem_windows: 4, ..Default::default() })).unwrap(); let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); // Execute on the real D3D12.X device + queue (goes through q_execute_command_lists -> sparse::before_execute) @@ -2375,10 +2392,10 @@ fn gpu_geometry_mode_es_gs_strip() { }; let mut code = es; code.extend_from_slice(&gs); - let native = translate(&code, &Options { mode: Mode::Geometry(g.clone()), wave64: true, geometry_wave32: false, ..Default::default() }).unwrap(); + let native = translate(&code, &Options { mode: Mode::Geometry(g.clone()), wave64: true, split_wave64: false, ..Default::default() }).unwrap(); assert!(native.hlsl.contains("[WaveSize(64)]")); assert!(!native.hlsl.contains("xcl_es_phase") && !native.hlsl.contains("GroupMemoryBarrierWithGroupSync();\n if (gi < 32u)")); - let t = translate(&code, &Options { mode: Mode::Geometry(g.clone()), wave64: true, geometry_wave32: true, ..Default::default() }).unwrap(); + let t = translate(&code, &Options { mode: Mode::Geometry(g.clone()), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); assert!(t.hlsl.contains("[WaveSize(32)]")); assert!(t.hlsl.contains("xcl_es_phase") && t.hlsl.contains("GroupMemoryBarrierWithGroupSync();\n if (gi < 32u)")); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -2429,9 +2446,9 @@ fn gpu_geometry_mode_es_gs_strip() { } /// v_mbcnt over a v_cmp mask in a geometry program (the compaction index of an ES / GS): -/// lanes 32..63 count the active lanes of 0..31 too. The split wave32 form only has its own -/// half of a mask, so it must refuse the program; whatever translates must give the logical -/// wave64 counts (the compute pass alone: no mesh shaders needed). +/// lanes 32..63 count the active lanes of 0..31 too. The split form (two wave32 halves) must +/// give the logical wave64 counts – it exchanges the halves' mask words – and so must the +/// native form where the GPU has 64-lane waves (the compute pass alone: no mesh shaders needed). #[test] fn gpu_geometry_wave32_prefix_count_over_a_mask() { if !gpu_ready_wave32() { @@ -2499,10 +2516,7 @@ fn gpu_geometry_wave32_prefix_count_over_a_mask() { let wrong: Vec<_> = (0..64).filter(|&l| got[l] != want[l]).map(|l| (l, got[l], want[l])).collect(); assert!(wrong.is_empty(), "lanes (got [vcc, s[10:11], exec], want): {wrong:?}"); }; - match translate_geometry(&code, g.clone(), true) { - Ok(t) => run(&t), - Err(err) => assert!(err.contains("prefix count over a whole-wave mask"), "{err}"), - } + run(&translate_geometry(&code, g.clone(), true).unwrap()); // the native wave64 form keeps the program, and computes the reference where it can run let native = translate_geometry(&code, g, false).unwrap(); if runner::wave64_supported() == Ok(true) { @@ -2714,7 +2728,7 @@ fn gpu_compute_mode_dispatch_abi() { ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None), ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 9), ("DATA", 11), ("SADDR", 0x7D)], None), ]); - let t = translate(&p, &Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }).unwrap(); + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); let (w, h, base) = (32usize, 24usize, 0x100usize); @@ -2737,7 +2751,7 @@ fn gpu_compute_mode_dispatch_abi() { /// two halves behave as separate waves – ballots, lane counts, readlane and mbcnt per half. #[test] fn gpu_wave32_program_in_wave64_hardware() { - if !gpu_ready() { + if !gpu_ready() || !wave64_hardware() { return; } let p = prog(&[ @@ -3005,7 +3019,7 @@ fn gpu_bvh64_intersect_ray_across_memory_windows_and_grazing() { code.extend(mimg("IMAGE_BVH_INTERSECT_RAY", 108, 40, 3)); code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); - let t = translate(&code, &Options { mem_windows: 2, ..Default::default() }).unwrap(); + let t = translate(&code, &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap(); let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); let mut st = KernelState::default(); @@ -4064,39 +4078,239 @@ fn far_jumps_are_direct_branches() { } } +/// Mesh mode for a GPU with 32-lane waves only: the console's two wave64s per group as four +/// hardware wave32s exchanging masks and lane reads (counter-paired: two console waves), +/// programs with cross-half operations included; native wave64 and wave32 programs unchanged. #[test] -fn mesh_wave32_emits_wave32_logical_wave64() { - let code = 0xBF81_0000u32.to_le_bytes(); // s_endpgm - let ms = super::MsInterface { threads: 128, max_vertices: 64, max_primitives: 64, outputs: vec![] }; - let native = translate(&code, &Options { mode: Mode::Mesh(ms.clone()), wave64: true, mesh_wave32: false, ..Default::default() }).unwrap(); - assert!(native.hlsl.contains("[WaveSize(64)]")); - assert!(native.hlsl.contains("[numthreads(128, 1, 1)]")); - assert!(!native.hlsl.contains("xcl_logical_wave64 = true")); - - let split = translate(&code, &Options { mode: Mode::Mesh(ms), wave64: true, mesh_wave32: true, ..Default::default() }).unwrap(); - assert!(split.hlsl.contains("[WaveSize(32)]")); - assert!(split.hlsl.contains("[numthreads(128, 1, 1)]")); - assert!(split.hlsl.contains("xcl_half = (gi >> 5) & 1u;")); - assert!(split.hlsl.contains("xcl_logical_wave64 = true;")); - assert!(split.hlsl.contains("lane_id = WaveGetLaneIndex() + 32u * xcl_half;")); - assert!(split.complete(), "{:?}", split.unsupported_why); -} - -#[test] -fn mesh_wave32_rejects_cross_half_operations() { +fn mesh_split_wave64_form() { let ms = super::MsInterface { threads: 128, max_vertices: 64, max_primitives: 64, outputs: vec![] }; let lane = prog(&[("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)], None)]); let branch = prog(&[("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)], None)]); - for (code, hazard) in [(&lane, "cross-half lane exchange"), (&branch, "branch on a whole-wave mask")] { - let e = super::translate_mesh(code, ms.clone(), true, true).err().expect("split mesh must refuse"); - assert!(e.contains("mesh program requires unsupported cross-half wave64 semantics") && e.contains(hazard), "{e}"); - // native wave64 and wave32 programs are not split, so nothing is refused - assert!(super::translate_mesh(code, ms.clone(), true, false).is_ok()); - assert!(super::translate_mesh(code, ms.clone(), false, true).is_ok()); + for code in [&lane, &branch] { + let native = super::translate_mesh(code, ms.clone(), true, false).unwrap(); + assert!(native.hlsl.contains("[WaveSize(64)]") && native.hlsl.contains("[numthreads(128, 1, 1)]") && !native.hlsl.contains("xcl_x_")); + let split = super::translate_mesh(code, ms.clone(), true, true).unwrap(); + assert!(split.complete(), "{:?}", split.unsupported_why); + assert!(split.hlsl.contains("[WaveSize(32)]") && split.hlsl.contains("[numthreads(128, 1, 1)]")); + assert!(split.hlsl.contains("uint xcl_tid = xcl_x_thread(gi);") && split.hlsl.contains("#define XCL_X_SPIN 1")); + assert!(split.hlsl.contains("xcl_x_ballot(true)")); + // a wave32 program is not split + let w32 = super::translate_mesh(code, ms.clone(), false, true).unwrap(); + assert!(w32.hlsl.contains("[WaveSize(32)]") && !w32.hlsl.contains("xcl_x_")); + if super::dxc::location().is_ok() { + super::dxc::compile(&split.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", split.hlsl)); + } + } + assert!(super::translate_mesh(&lane, ms, true, true).unwrap().hlsl.contains("xcl_x_rla_uniform(")); +} + +/// Operations whose result spans both 32-lane halves of a wave64 – what the split form +/// exchanges: masks with bits in either half (counted, scanned, branched on), readlane / +/// readfirstlane of a lane in the other half, ds_bpermute across the halves, a GLC scalar +/// load. The same results natively (64-lane waves) and split (32-lane waves only); split, +/// the runner also checks both halves end with the same SGPRs. +#[test] +fn gpu_split_wave64_cross_half_operations() { + if !gpu_ready() { + return; + } + let code = prog(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(40)), // vcc = lanes 0..39 + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V + 1), ("SRC1", 2)], None), // lane s2 = 37 + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 106), ("SRC1", 128)], None), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 107), ("SRC1", V + 5)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)], None), // exec = lanes 48..63 + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], Some(0xFFFF_0000)), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V + 1)], None), + ("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 126)], None), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)], None), // not taken: only the upper half is active + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 3)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 4), ("DATA0", 1)], None), // lane 63 - l + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(50)), // vcc = lane 50 only + ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)], None), // not taken + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 129)], None), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 126), ("SSRC1", 106)], None), // scc = vcc != 0 + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 7), ("SSRC0", 129), ("SSRC1", 130)], None), + // s[8:9] = 0: the test memory + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 12), ("SBASE", 4), ("OFFSET", 0), ("SOFFSET", 125), ("GLC", 1)], None), + ]); + let mut st = KernelState::default(); + st.sgpr[2] = 37; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 1000 + l as u32; + r[2] = 0x77; + r[4] = (63 - l as u32) * 4; + } + let mem = [0xABCDu32, 0x1234, 0x5678, 0x9ABC]; + let r = runner::run_code(&code, &st, &mem).unwrap(); + assert_eq!(r.sgpr[0], 40, "s_bcnt1 of a mask over both halves"); + assert_eq!(r.sgpr[1], 1037, "readlane of lane 37 (upper half)"); + assert_eq!(r.sgpr[3], 1048, "readfirstlane with only the upper half active"); + assert_eq!(r.sgpr[4], 48, "s_ff1 of exec"); + assert_eq!(r.sgpr[5], 1, "branch on a vcc with a bit in the upper half only"); + assert_eq!(r.sgpr[7], 1, "scc from a 64-bit mask operation"); + assert_eq!((r.sgpr[10], r.sgpr[11]), (0, 1 << 18), "s_and_b64 exec, vcc"); + assert_eq!(&r.sgpr[12..16], &mem, "s_load_dwordx4 glc"); + for l in 0..64 { + let v = &r.vgpr[l]; + assert_eq!(v[5], (l as u32).min(40), "lane {l}: v_mbcnt over vcc"); + assert_eq!(v[2], if l >= 48 { 1048 } else { 0x77 }, "lane {l}: write under exec of the upper half"); + assert_eq!(v[6], 1000 + 63 - l as u32, "lane {l}: ds_bpermute from lane {}", 63 - l); + } +} + +/// A group of four wave64s whose waves take different paths: each loops 2 · (wave + 1) +/// times through a ballot, s_bcnt1 and a readlane, then exchanges lanes across its halves +/// with ds_bpermute. Split (32-lane GPUs) this is the counter-paired form – a group barrier +/// per exchange would deadlock or mix the waves up. 3-D groups too: NVIDIA does not form its +/// waves from consecutive thread indices there (8 × 8 × 4), the console does. +#[test] +fn gpu_split_wave64_waves_diverge() { + if !gpu_ready() { + return; + } + use super::{dxc, CsInterface}; + let p = prog(&[ + // v0 = thread index in the group: v0 + v1 · s1 + v2 · s2 (s1 = x, s2 = x · y) + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None), + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 20)], None), + ("V_LSHRREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 134), ("VSRC1", 0)], None), // wave + ("V_AND_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], Some(63)), // lane + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 1)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), // n = 2 (w + 1) + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 128)], None), // sum + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)], None), // i + // loop: k = 5 i + 3; sum += popcount(lanes < k) + v0 of lane k + ("S_MUL_I32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 12), ("SSRC1", 133)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 13), ("SSRC1", 131)], None), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 13), ("VSRC1", 2)], None), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", 106)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 14)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V), ("SRC1", 13)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 15)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 12), ("SSRC1", 10)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF5)], None), // → loop + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 2)], Some(33)), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 3)], None), + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("DATA0", 0)], None), // v0 of lane ^ 33 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 11)], None), + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 16), ("SSRC0", 4), ("SSRC1", 136)], None), // group · 256 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 16), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 131), ("VSRC1", 7)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 7)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 5), ("SADDR", 0x7D)], None), + ]); + for dims in [[256u32, 1, 1], [64, 1, 1], [8, 8, 4], [16, 4, 1]] { + let threads = dims.iter().product::(); + let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + if runner::split_wave64() && std::env::var_os("XCL_WAVE64_SPIN").is_none() { + let spin = if threads > 64 { "#define XCL_X_SPIN 1" } else { "#define XCL_X_SPIN 0" }; + assert!(t.hlsl.contains("[WaveSize(32)]") && t.hlsl.contains(spin), "{dims:?}"); + } + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let base = 0x100usize; + let mut io = vec![0u32; 128]; + io[0] = base as u32; + io[1] = dims[0]; + io[2] = dims[0] * dims[1]; + let groups = 3usize; + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * 256 * 8) / 4]).unwrap(); + for g in 0..groups { + for tid in 0..threads as usize { + let (w, l) = (tid / 64, tid % 64); + let want: u32 = (0..2 * (w + 1)).map(|i| (5 * i + 3).min(64) as u32 + (w * 64 + 5 * i + 3) as u32).sum(); + let at = (base + (g * 256 + tid) * 8) / 4; + assert_eq!(out[at], want, "{dims:?}, group {g} thread {tid}: loop of wave {w}"); + assert_eq!(out[at + 1], (w * 64 + (l ^ 33)) as u32, "{dims:?}, group {g} thread {tid}: ds_bpermute"); + } + } + } +} + +/// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64 +/// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the +/// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32 +/// program (no exchanges) and as a wave64 program – natively on a GPU with 64-lane waves, +/// split on one with 32-lane waves only. Wall time of the dispatch, best of 5. +#[test] +#[ignore] +fn bench_split_wave64() { + if !gpu_ready() { + return; + } + use super::{dxc, CsInterface}; + let body = |readfirstlane: bool| { + let mut l: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 10), ("SSRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 2), ("SRC0", V)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 4), ("SRC0", 128)], None), + // loop: an LCG step, a mask from it, a conditional count + ("V_MUL_LO_U32", "ENC_VOP3", vec![("VDST", 2), ("SRC0", V + 2), ("SRC1", 255)], Some(1_103_515_245)), + ("V_ADD_NC_U32", "ENC_VOP2", vec![("VDST", 2), ("SRC0", 255), ("VSRC1", 2)], Some(12345)), + ("V_LSHRREV_B32", "ENC_VOP2", vec![("VDST", 3), ("SRC0", 144), ("VSRC1", 2)], None), + ("V_CMP_GT_U32", "ENC_VOPC", vec![("SRC0", 255), ("VSRC1", 3)], Some(0x4000)), + ("V_ADD_NC_U32", "ENC_VOP2", vec![("VDST", 5), ("SRC0", 129), ("VSRC1", 4)], None), + ("V_CNDMASK_B32", "ENC_VOP2", vec![("VDST", 4), ("SRC0", V + 4), ("VSRC1", 5)], None), + ]; + let mut back = 0xFFF3u64; // → the loop start: 48 bytes of loop body before the branch + if readfirstlane { + l.push(("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 11), ("SRC0", V + 3)], None)); + l.push(("V_ADD_NC_U32", "ENC_VOP2", vec![("VDST", 4), ("SRC0", 11), ("VSRC1", 4)], None)); + back -= 2; + } + l.extend([ + ("S_ADD_U32", "ENC_SOP2", vec![("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", vec![("SSRC0", 10), ("SSRC1", 1)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", vec![("SIMM16", back)], None), + ("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_ADD_NC_U32", "ENC_VOP2", vec![("VDST", 6), ("SRC0", 0), ("VSRC1", 6)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", vec![("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None), + ]); + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = l.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + prog(&refs) + }; + let iterations = 32768u32; + println!("GPU: {} ({} lanes per wave at most)", runner::adapter().unwrap(), if runner::wave64_supported() == Ok(true) { 64 } else { 32 }); + for readfirstlane in [false, true] { + let p = body(readfirstlane); + for threads in [64u32, 256] { + let mut ms = Vec::new(); + for wave64 in [false, true] { + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let groups = (1u32 << 18) / threads; + let mut io = vec![0u32; 128]; + io[0] = 0; + io[1] = iterations; + let mem = vec![0u32; threads as usize]; + let best = (0..5) + .map(|_| { + let t0 = std::time::Instant::now(); + runner::dispatch(&dxil, [groups, 1, 1], &io, &mem).unwrap(); + t0.elapsed().as_secs_f64() * 1000.0 + }) + .fold(f64::MAX, f64::min); + ms.push(best); + } + let form = if runner::split_wave64() { if threads > 64 { "split, counter-paired" } else { "split, barrier" } } else { "native" }; + println!( + "{} exchange(s) / iteration, {threads} threads per group, 2^18 threads x {iterations} iterations: wave32 {:.1} ms, wave64 ({form}) {:.1} ms = {:.2}x", + 1 + readfirstlane as u32, + ms[0], + ms[1], + ms[1] / ms[0] + ); + } } - - let plain = prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)], None)]); - let split = super::translate_mesh(&plain, ms, true, true).unwrap(); - assert!(split.hlsl.contains("xcl_logical_wave64 = true;")); - assert!(split.complete(), "{:?}", split.unsupported_why); } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 814f0df..d72e380 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -316,13 +316,15 @@ pub fn device_raw() -> *mut c_void { DEVICE.load(Ordering::Acquire) as *mut c_void } -fn geometry_wave32_required(device: *mut c_void) -> bool { +/// The device runs only 32-lane waves: wave64 compute, mesh and geometry programs need the +/// split form (`Options::split_wave64`). Unknown device: assume so. +fn wave32_only(device: *mut c_void) -> bool { if device.is_null() { return true; } unsafe { let Some(dev) = ID3D12Device::from_raw_borrowed(&device) else { return true }; - crate::gpu::recomp::pso::geometry_uses_wave32_for_device(dev) + crate::gpu::recomp::pso::wave32_only_for_device(dev) } } @@ -2532,7 +2534,7 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// shader the recompiler could not take, `Some(Ok(hr))` = translated pipeline created (or the /// driver's verdict on it). unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { - use crate::gpu::recomp::pso::{console_to_dxil, is_console, Stage}; + use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; } @@ -2541,7 +2543,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi if !is_console(cs) { return None; } - let compiled = match console_to_dxil(cs, Stage::Compute, 0) { + let compiled = match console_to_dxil_for(cs, Stage::Compute, 0, wave32_only(this)) { Ok(b) => b, Err(e) => { note_translation_error(format!("CS: {e}")); @@ -3102,7 +3104,7 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * return Some(E_INVALIDARG); } let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1)); - let (tp, (ps, ps_samplers)) = match (console_mesh(ms, ps, geometry_wave32_required(this)), two_pass_ps(ps)) { + let (tp, (ps, ps_samplers)) = match (console_mesh(ms, ps, wave32_only(this)), two_pass_ps(ps)) { (Ok(tp), Ok(ps)) => (tp, ps), (Err(e), _) => { note_translation_error(format!("MS: {e}")); @@ -3135,7 +3137,7 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * /// with the description's state. unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8], gs: &[u8], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let (tp, (ps, ps_samplers)) = match ( - crate::gpu::recomp::pso::console_geometry(vs, gs, shader_bytes(&d.PS), geometry_wave32_required(this)), + crate::gpu::recomp::pso::console_geometry(vs, gs, shader_bytes(&d.PS), wave32_only(this)), two_pass_ps(shader_bytes(&d.PS)), ) { (Ok(tp), Ok(ps)) => (tp, ps), diff --git a/crates/xcl/tests/console_shaders.rs b/crates/xcl/tests/console_shaders.rs index 347636f..e2b96c6 100644 --- a/crates/xcl/tests/console_shaders.rs +++ b/crates/xcl/tests/console_shaders.rs @@ -293,7 +293,7 @@ fn inputs() -> Vec { fn run_both(c: &IDxcCompiler3, body: &str) -> Result<(Vec, Vec), String> { let src = kernel(body); let blob = console_compile(c, &src, &["-E", "main", "-T", "cs_6_6", "-enable-16bit-types", "-D", "XCL_CONSOLE=1"])?; - let translated = pso::console_to_dxil(&blob, pso::Stage::Compute, 0).map_err(|e| format!("translation: {e}"))?; + let translated = pso::console_to_dxil_for(&blob, pso::Stage::Compute, 0, runner::split_wave64()).map_err(|e| format!("translation: {e}"))?; // the console run: the buffer at 0x1_0000, its address the one root argument – in user // SGPRs or in a table at 0x100, as XCL passes them on a console list's dispatch let (table_at, base) = (0x100usize, 0x1_0000usize); diff --git a/crates/xcl/tests/gpu_pso_e2e.rs b/crates/xcl/tests/gpu_pso_e2e.rs index 58b0142..24818df 100644 --- a/crates/xcl/tests/gpu_pso_e2e.rs +++ b/crates/xcl/tests/gpu_pso_e2e.rs @@ -455,7 +455,7 @@ fn retail_es_gs_voxelize_geometry_mode() { use xcl::gpu::recomp::{self, dxc, IO_GS_PRIMS, IO_GS_VERTICES, MESH_HEADER}; let (code, g) = recomp::geometry_program(&blobs[0], &blobs[1]).expect("ES + GS pair"); assert_eq!((g.max_vertex_count, g.vertex_bytes()), (3, 64)); - let split_wave32 = recomp::pso::geometry_uses_wave32_for_device(&_dev); + let split_wave32 = recomp::pso::wave32_only_for_device(&_dev); let t = recomp::translate_geometry(&code, g.clone(), split_wave32).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let cs = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md new file mode 100644 index 0000000..9125dba --- /dev/null +++ b/docs/wave64-on-wave32.md @@ -0,0 +1,136 @@ +# Wave64 console programs on 32-lane GPUs + +Status: implemented for compute / kernel mode, the mesh (NGG) first pass and ES+GS +(`gpu/recomp/emit.rs`, `PRELUDE_X64`). The native path is untouched: the form below is only +generated when the adapter cannot run 64-lane waves (`D3D12_FEATURE_DATA_D3D12_OPTIONS1` +`WaveLaneCountMax < 64`, e.g. NVIDIA, whose D3D12 range is 32..32). On such an adapter a +`[WaveSize(64)]` compute shader is rejected at PSO creation, so until now wave64 compute +programs were refused there, and mesh / ES+GS programs ran as two independent halves only +when they had no cross-half operation (`geometry_wave32_hazards`) and were refused otherwise. + +## Execution model it relies on + +The recompiler runs every console lane through every instruction; EXEC only masks writes. +Branches are scalar (SCC, VCC/EXEC == 0, SGPR values), so control flow is uniform per +console wave as long as every scalar value is identical in all of the wave's threads. +Scalar values come from scalar code (identical when its inputs are), from scalar memory, and +from a handful of vector → scalar instructions: masks (`v_cmp*`, carries – all through +`ballot()`), `v_readlane` / `v_readfirstlane` (through `rla()`), and nothing else. Cross-lane +vector reads (DPP16, DPP8, `ds_swizzle`, `v_permlane(x)16`, `ds_bpermute`) also go through +`rla()`. + +## The form + +One console wave64 = two hardware wave32s of the same thread group ("halves"): the console +group keeps its `numthreads` and the shader gets `[WaveSize(32)]`. Which hardware threads +play which console thread is decided at the start (`xcl_x_thread`): the threads of a group +are interchangeable, but the console forms its waves from consecutive thread indices and +the PC GPU need not – on the RTX 5070 Ti, 1-D groups get consecutive `SV_GroupIndex` values +per wave, an 8 × 8 × 4 group does not. Each hardware wave takes the next 32 console threads +from a groupshared counter as it arrives (a partial wave the last ones), and the program +gets that console thread's ids (v0..v2 in compute, the vertex slot in mesh mode). Console +lane = console thread % 64, half = bit 5, console wave = console thread / 64. + +Per-lane code is unchanged. The two halves meet ("exchange") exactly where a value has to be +whole-wave: + +| operation | exchange | +|---|---| +| `ballot()` (every mask: `v_cmp*`, `v_cmpx*`, carries, EXEC at entry) | one word: each half gives its 32-bit ballot, both get the 64-bit mask | +| `v_readlane`, `v_readfirstlane` (lane index uniform) | one word: each half gives the value of lane `l & 31`, the half that owns `l` wins | +| `ds_bpermute` (any lane) | 32 words: each half gives its lanes | +| DPP16, DPP8, `ds_swizzle`, `v_permlane(x)16` | none: the ISA keeps them inside a 32-lane half (`WaveReadLaneAt(v, l & 31)`) | +| `s_load*` / `s_buffer_load*` with GLC (or DLC) | up to 16 words: half 0's values for both (memory another wave writes may change between the two halves' loads; without GLC the console's scalar cache is not coherent either, so plain loads are read by both halves) | + +So both halves hold the full 64-bit EXEC / VCC / masks and identical SGPRs; every branch is +taken the same way by both, and the existing scalar code (`s_bcnt1_i32_b64`, `s_ff1`, +`s_cbranch_execz`, `v_mbcnt_hi`, …) needs no change. The kernel-mode runner stores the +SGPRs of both halves and the tests fail if they ever differ. + +### Synchronisation + +* **One console wave per group** (≤ 64 threads: kernel mode, most compute, ES+GS): + `GroupMemoryBarrierWithGroupSync` between writing and reading the slot. All hardware + waves of the group are the two halves of the same console wave, which execute the same + sequence of exchanges, so every barrier is reached by both. Portable (no forward-progress + assumption) and cheap. +* **Several console waves per group** (mesh: 128 threads, compute > 64 threads): a group + barrier would also wait for the *other* console waves, whose control flow may differ (wave + index, per-wave data). Each pair instead meets through groupshared arrival counters: + every lane stores its slot word(s) and fences (`GroupMemoryBarrier`); the wave's lane + count (`WaveActiveCountBits` – a wave operation, so all its lanes have fenced) goes into + its half's counter in one atomic; one lane waits until the partner's counter reaches + `lanes × (k + 1)` (k = exchange number, identical in both halves) and the others take its + verdict (`WaveReadLaneFirst`); a fence, then the read. Slots are double-buffered by the + parity of k: the partner can be at most one exchange ahead, so it never overwrites the + slot being read. The wait is bounded (2^20 polls): if it ever runs out (a desynchronised + pair – should not happen, see hazards), the wave stops exchanging (`xcl_x_dead`) and + finishes with half-local values instead of hanging the GPU until a TDR. This relies on + co-resident waves of one group making progress, which holds on GPUs (all waves of a group + are resident on one SM / CU) but not necessarily on WARP. `XCL_WAVE64_SPIN=1` forces this + variant everywhere (the test suite passes with it too). + +A console wave whose upper half does not exist (group of 32 or 96 threads) exchanges with +nobody: the missing lanes count as inactive (ballot bits 0), exactly as on the console. The +GS phase of ES+GS runs in the lower half only (≤ 21 primitives), likewise without a partner. + +### Memory + +The exchange needs groupshared space: per console wave 2 counters + 2 halves × 2 parities × +slot (1 word, 16 with wide GLC scalar loads, 32 with `ds_bpermute`). Without console LDS it +has arrays of its own; with LDS (`xcl_lds`, already the full 32 KB D3D12 limit) it lives in +the top of the LDS block (as PR #33 did), and the program's LDS accesses are clamped below +it. A program that really uses the whole 32 KB of LDS therefore loses its top dwords on a +32-lane GPU (the console allows 64 KB; XCL already wraps at 32 KB). + +## Hazards (and why they are handled) + +1. **Divergent halves** – anything that lets the two halves compute different scalar values + desynchronises the exchanges. Covered: masks and lane reads (exchanged), GLC scalar loads + (half 0's value), `s_memtime` (constant 0). Not exchanged: non-GLC scalar loads of memory + that changes during the dispatch (incoherent on the console as well). +2. **Barriers in divergent control flow** – the barrier variant is only used when the group + is exactly one console wave, whose control flow is identical in both halves; console + `s_barrier` stays a group barrier (all console waves reach it, as on the console). The GS + phase (lower half only) has no exchanges and its `s_barrier` is dropped (one wave). +3. **Lane numbering** – handled by `xcl_x_thread` (see above); NVIDIA really does form waves + of non-consecutive thread indices for 3-D groups (`gpu_split_wave64_waves_diverge` fails + without the remap). +4. **`WaveReadLaneAt` with a per-lane index** – used inside a half as before. +5. **Forward progress** – only the multi-wave variant spins; see above. + +## Cost + +A wave64 program pays one exchange per mask write (`v_cmp*`, carries) and per readlane / +readfirstlane / ds_bpermute / coherent scalar load, nothing per ALU, memory or DPP +instruction. Wave32 programs, VS / PS and everything on GPUs with 64-lane waves are +unchanged (the HLSL of every native translation the test suite makes is byte-identical). + +Measured on an RTX 5070 Ti (`bench_split_wave64`, an ignored test): a loop of 8 +instructions with one exchange, 2^18 threads × 32 768 iterations, wave32 program (no +exchange) vs the same as wave64 split: + +| | 1 exchange / 8 instructions | 2 exchanges / 10 instructions | +|---|---|---| +| one console wave per group (barrier) | 1.3× | 1.6–2.2× | +| four console waves per group (counters) | 4.6–5× | 8.4–9.7× | + +This is the worst case – real shaders have far more ALU and memory work per mask. The +counter-paired variant is the expensive one: a waiting wave keeps issuing (no way to park +it in HLSL), taking issue slots from the waves it waits for. The next step would be to skip +the exchange for masks only used lane by lane (`v_cmp` + `v_cndmask` selects; each half's +own word is enough there), which needs a liveness pass over the mask registers. + +## Relation to earlier work + +* **PR #33** (ElHombreAlex, draft): first wave64 → wave32 "rendezvous" through groupshared + for compute, and the finding that NVIDIA rejects `[WaveSize(64)]`. Its exchange keeps one + slot per half (the partner can overwrite it with the next exchange before it is read), + publishes from lane 0 only and times out into stale data; the FSR4 pass it targeted hung + the GPU. This design keeps its idea of placing the exchange in the LDS tail and fixes the + protocol (double-buffered slots, counted arrivals, barriers where they are legal). +* **PR #35** (bmjask): a separate per-slot lowering of mesh programs, validation only and + not connected to translation; its merged parts (`mesh_wave.rs` requirement report, + `mesh_dispatch.rs` scratch / rendezvous model) are not used by this form. +* **PRs #14 / #39** (split ES+GS / mesh into independent halves and reject cross-half + operations): replaced by the exchange form, which needs no rejection list.