From 22026ba5a497b94d7f2462a34a94cfcb5a96c37b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 07:39:42 -0800 Subject: [PATCH 1/3] Recompiler: order split wave64 LDS instructions Adapt the default-on LDS ordering and read-run elision from PR #1252 to the current emitter while preserving coherent-memory, barrier, and wave-local remap state. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/emit.rs | 65 +++++++++- crates/xcl/src/gpu/recomp/mod.rs | 2 +- crates/xcl/src/gpu/recomp/tests.rs | 189 +++++++++++++++++++++++++++++ docs/wave64-on-wave32.md | 15 ++- 4 files changed, 268 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 27dd870629..17cd0a7ca3 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -78,6 +78,21 @@ pub(super) struct Em { img_writes: Vec, /// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`) pub coherent_mem: bool, + /// split wave64: what lies between the basic block's previous LDS access and here + x64_lds: LdsGap, + /// first instructions of the basic blocks (branch targets, after branches) + block_starts: BTreeSet, +} + +/// Split wave64 (`x64_lds_meet`): since the basic block's previous LDS access +#[derive(Clone, Copy, PartialEq)] +enum LdsGap { + /// that was a write or an atomic, or there was none in the block + Open, + /// that was a read, and no exchange since + Read, + /// the halves met in an exchange since + Met, } /// The T# SGPRs (SRSRC) of a program's image stores and atomics, at most 16, sorted. An @@ -595,7 +610,9 @@ fn to_f16_rounded_expr(dynamic_rm: bool, e: &str) -> String { } impl Em { - pub fn new(opt: Options) -> Self { + /// `block_starts`: the first instructions of the program's basic blocks (branch targets and + /// the instructions after branches): split wave64 elides no LDS meeting across them. + pub fn new(opt: Options, block_starts: BTreeSet) -> Self { Em { opt, reductions: Default::default(), @@ -629,6 +646,8 @@ impl Em { has_s_barrier: false, img_writes: Vec::new(), coherent_mem: false, + x64_lds: LdsGap::Open, + block_starts, } } @@ -986,6 +1005,9 @@ impl Em { ballot = "ballot_px_local"; } } + if ballot == "xcl_x_ballot" { + self.x64_met(); + } match if ballot == "ballot_px" { quad_bits(a, cond, &m) } else { None } { Some((reads, q)) => { if !reads.is_empty() { @@ -1255,6 +1277,9 @@ impl Em { let text = rdna2::format(d); self.line(&format!("// {:04x}: {text}", d.pc)); self.cur_pc = d.pc; + if self.block_starts.contains(&d.pc) { + self.x64_lds = LdsGap::Open; + } // a far jump (`rdna2::resolve_far_jumps`) is an unconditional branch if let Some(t) = d.far_target { return Flow::Jump(t); @@ -1994,6 +2019,7 @@ impl Em { } 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(" "))); + self.x64_met(); } for (i, v) in vals.iter().enumerate() { let s = self.sreg(sdata + i as u64); @@ -4094,6 +4120,7 @@ impl Em { let rla = self.rla_uniform_fn(); // (a live lane of EXEC where there is one: `first_lane_live`) self.line(&format!("uint {t} = {rla}({a}, first_lane_live({el}, {eh}));")); + self.x64_met(); self.write32(&dst, &t); return Ok(()); } @@ -4121,6 +4148,8 @@ impl Em { (Some(Read::Shadow), Some((v, l))) => self.line(&format!("uint {t} = xcl_sh{v}_{l}; if (!xcl_hw32) {t} = {read};")), _ => self.line(&format!("uint {t} = {read};")), } + // split wave64 (no `upper` there): the last arm, an exchange + self.x64_met(); self.write32(&dst, &t); return Ok(()); } @@ -4526,6 +4555,33 @@ impl Em { } /// LDS (`groupshared`, compute only) and the DS cross-lane permutes. + /// Split wave64: the console runs an instruction in all 64 lanes before the next, so a lane + /// reads the LDS the other half wrote an instruction earlier with no s_barrier – the halves + /// meet before every LDS access (nothing exchanged: the meeting is the order). Called once + /// the access is known to be translated. Not in geometry mode: ES lanes write their own + /// items and read no other lane's before the barrier where the phases meet. + /// No meeting for a read right after a read of the same basic block, nor when the halves + /// met in an exchange since the block's previous access (`LdsGap`). Still in order: for + /// accesses j < i of the stream, one a write, the halves meet between them (the access + /// after a write and every write meet, or an exchange lies before them; a block's first + /// access meets), and both halves pass the same meetings: the other half's j is done + /// before this half's i. Two reads need no order. + fn x64_lds_meet(&mut self, write: bool) { + if self.x64() && !matches!(self.opt.mode, Mode::Geometry(_)) { + if self.x64_lds == LdsGap::Open || (write && self.x64_lds == LdsGap::Read) { + self.line("xcl_x_meet();"); + } + self.x64_lds = if write { LdsGap::Open } else { LdsGap::Read }; + } + } + + /// An exchange (`xcl_x_meet`) the current instruction always runs, in the split form. + fn x64_met(&mut self) { + if self.x64() { + self.x64_lds = LdsGap::Met; + } + } + fn ds(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> { let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); let act = self.act(); @@ -4557,6 +4613,7 @@ impl Em { self.line(&format!("uint {t}_l = (({a} + {off16}u) >> 2) & {m}u;")); let rla = if self.x64() { self.x64_words = 32; + self.x64_met(); "xcl_x_rla_any" } else { "rla" @@ -4587,6 +4644,7 @@ impl Em { } // ADDTID forms have no ADDR VGPR: byte address = M0[15:0] + offset16 + 4 * lane_id. if matches!(name, "ds_write_addtid_b32" | "ds_read_addtid_b32") { + self.x64_lds_meet(name == "ds_write_addtid_b32"); self.uses_lds = true; let m0 = self.sreg(124); let at = format!("(({m0} & 0xFFFFu) + {off16}u + 4u * lane_id)"); @@ -4651,6 +4709,7 @@ impl Em { }; // d16 8 / 16-bit LDS accesses (half of the VGPR) if let Some((bits, signed, write, half)) = ds_d16(name) { + self.x64_lds_meet(write); let at = format!("{a} + {off16}u"); let slot = lds(at.clone()); let sh = format!("((({at}) & 3u) * 8u)"); @@ -4676,6 +4735,7 @@ impl Em { _ => None, }; if let Some((bits, signed, write)) = small { + self.x64_lds_meet(write); let at = format!("{a} + {off16}u"); let slot = lds(at.clone()); let sh = format!("((({at}) & 3u) * 8u)"); @@ -4697,6 +4757,7 @@ impl Em { return Ok(()); } if let Some((write, n, stride, two)) = rw(name) { + self.x64_lds_meet(write); let addrs: Vec = if two { vec![format!("{a} + {}u", o0 * stride), format!("{a} + {}u", o1 * stride)] } else { @@ -4729,6 +4790,7 @@ impl Em { }; // two exchanges (ds_wrxchg2(st64)_rtn_b32): old values to VDST, VDST + 1 if op == "wrxchg2_b32" || op == "wrxchg2st64_b32" { + self.x64_lds_meet(true); let stride = if op == "wrxchg2_b32" { 4 } else { 256 }; let (s0, s1) = (lds(format!("{a} + {}u", o0 * stride)), lds(format!("{a} + {}u", o1 * stride))); let (v0, v1) = (self.vreg(f("DATA0")), self.vreg(f("DATA1"))); @@ -4744,6 +4806,7 @@ impl Em { let (v, v2) = if op.starts_with("cmpst_") { (d1, d0) } else { (d0, d1) }; let slot = lds(format!("{a} + {off16}u")); let body = rmw32(&op, &At::Ref(slot), &v, &v2, &format!("{t}_o"), &t).ok_or("DS")?; + self.x64_lds_meet(true); self.line(&format!("uint {t}_o = 0u; if ({act}) {{ {body} }}")); if rtn { let r = self.vreg(f("VDST")); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index a8ffdc7a10..e9a8429b7f 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1571,7 +1571,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result { leaders.insert(next); } } - let mut em = emit::Em::new(opt.clone()); + let mut em = emit::Em::new(opt.clone(), leaders.clone()); em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts); em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 747f1542f2..3f24160dfd 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7453,6 +7453,195 @@ fn gpu_split_wave64_waves_diverge() { } } +/// A console wave64 runs an instruction in all 64 lanes before the next one. Each half writes +/// a word per lane, the other half reads it, then the writer overwrites it, with constant EXEC +/// masks so nothing else makes the split wave32 halves meet between the six accesses. +fn lds_order_program() -> Vec { + prog(&[ + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 1)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 5), ("VSRC1", 0)], None), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 10)], Some(0x1000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 10)], Some(0x2000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 255), ("VSRC1", 10)], Some(0x3000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 255), ("VSRC1", 10)], Some(0x4000_0000)), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 160), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)], None), + // lanes 32..63: a[own] = 1 << 28 | n + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 193)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 6)], None), + // lanes 0..31: v4 = a[other], b[own] = 2 << 28 | n + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 2)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 7), ("OFFSET1", 4)], None), + // lanes 32..63: v5 = b[other], then overwrite a + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 193)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 5), ("ADDR", 2), ("OFFSET1", 4)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 8)], None), + // lanes 0..31: overwrite b after the other half read it + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 9), ("OFFSET1", 4)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 131), ("VSRC1", 10)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 0), ("VSRC1", 12)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 12), ("DATA", 4), ("SADDR", 0x7D)], None), + ]) +} + +fn lds_order_cs(threads: u32) -> super::CsInterface { + super::CsInterface { threads: [threads, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 } +} + +#[test] +fn split_wave64_meets_before_each_lds_access() { + let meets = |code: &[u8], wave64: bool, split_wave64: bool| { + let t = translate(code, &Options { mode: Mode::Compute(lds_order_cs(64)), wave64, split_wave64, ..Default::default() }).unwrap(); + (t.hlsl.matches("xcl_x_meet();").count(), t.complete()) + }; + let p = lds_order_program(); + assert_eq!(meets(&p, true, true), (6, true)); + assert_eq!(meets(&p, true, false), (0, true), "native wave64"); + assert_eq!(meets(&p, false, true), (0, true), "a wave32 program"); + let gds = prog(&[("DS_READ_ADDTID_B32", "ENC_DS", &[("VDST", 3), ("GDS", 1)], None)]); + assert_eq!(meets(&gds, true, true), (0, false), "GDS: not translated"); +} + +#[test] +fn gpu_split_wave64_lds_follows_instruction_order() { + if !gpu_ready() { + return; + } + let p = lds_order_program(); + for threads in [64usize, 256] { + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(lds_order_cs(threads as u32)), wave64: true, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + if runner::split_wave64() { + assert!(t.hlsl.contains("[WaveSize(32)]")); + } + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let (groups, base) = (1024usize, 0x100usize); + let mut io = vec![0u32; 128]; + io[0] = base as u32; + io[1] = threads.trailing_zeros(); + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * threads * 8) / 4]).unwrap(); + let mut wrong = Vec::new(); + for n in 0..groups * threads { + let (at, lane, other) = ((base + n * 8) / 4, n % 64, (n ^ 32) as u32); + let want = if lane < 32 { [0x1000_0000 | other, 0] } else { [0, 0x2000_0000 | other] }; + if out[at..at + 2] != want { + wrong.push(format!("group {} thread {}: read {:x?}, not {want:x?}", n / threads, n % threads, &out[at..at + 2])); + } + } + assert!(wrong.is_empty(), "{threads} threads per group: {} of {} threads read LDS out of instruction order: {}", wrong.len(), groups * threads, wrong[..wrong.len().min(4)].join("; ")); + } +} + +type LdsInst = (&'static str, &'static str, &'static [(&'static str, u64)], Option); +const LDS_W: LdsInst = ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 6)], None); +const LDS_R: LdsInst = ("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 2)], None); +const LANE_X: LdsInst = ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 3)], None); + +fn lds_read_run_program(exchange: bool) -> Vec { + let head: [LdsInst; 11] = [ + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 1)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 5), ("VSRC1", 0)], None), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 10)], Some(0x1000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 10)], Some(0x2000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 255), ("VSRC1", 10)], Some(0x3000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 15), ("SRC0", 255), ("VSRC1", 10)], Some(0x4000_0000)), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 160), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 12)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 13), ("OFFSET1", 4)], None), + ]; + let reads: [LdsInst; 4] = [ + ("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 2)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 5), ("ADDR", 2), ("OFFSET1", 4)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET1", 4)], None), + ]; + let tail: [LdsInst; 5] = [ + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 14)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 15), ("OFFSET1", 4)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 16), ("SRC0", 132), ("VSRC1", 10)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 16), ("SRC0", 0), ("VSRC1", 16)], None), + ("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 16), ("DATA", 4), ("SADDR", 0x7D)], None), + ]; + let x = exchange.then_some(LANE_X); + prog(&head.into_iter().chain(x).chain(reads).chain(x).chain(tail).collect::>()) +} + +fn x64_lds_meets(code: &[u8]) -> (usize, String) { + let t = translate(code, &Options { mode: Mode::Compute(lds_order_cs(64)), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + (t.hlsl.matches("xcl_x_meet();").count(), t.hlsl) +} + +#[test] +fn split_wave64_meets_once_per_read_run() { + let meets = |l: &[LdsInst]| x64_lds_meets(&prog(l)).0; + let (w, r, x) = (LDS_W, LDS_R, LANE_X); + let br: LdsInst = ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)], None); + assert_eq!(x64_lds_meets(&lds_read_run_program(false)).0, 5, "two writes, four reads, two writes: 8 before"); + assert_eq!(x64_lds_meets(&lds_read_run_program(true)).0, 3, "the same with two exchanges"); + assert_eq!(meets(&[w, r, r, r, r]), 2, "four reads after a write: one meeting"); + assert_eq!(meets(&[r, r, w]), 2, "a write after reads: one"); + assert_eq!(meets(&[w, x, r, x, w]), 1, "an exchange since the previous access"); + assert_eq!(meets(&[w, x, w, w]), 2, "the exchange counts for the next access only"); + assert_eq!(meets(&[r, br, r]), 2, "a branch target starts a block"); +} + +#[test] +fn split_wave64_lds_local_mask_is_no_meeting() { + let cmp: LdsInst = ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 0)], None); + let bcnt: LdsInst = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 9), ("SSRC0", 106)], None); + let (n, hlsl) = x64_lds_meets(&prog(&[LDS_W, cmp, LDS_R])); + assert!(hlsl.contains("xcl_x_ballot_local(and("), "{hlsl}"); + assert_eq!(n, 2); + let (n, hlsl) = x64_lds_meets(&prog(&[LDS_W, cmp, bcnt, LDS_R])); + assert!(hlsl.contains("xcl_x_ballot(and("), "{hlsl}"); + assert_eq!(n, 1); +} + +#[test] +fn split_wave64_lds_meets_at_loop_head() { + let back: LdsInst = ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None); + assert_eq!(x64_lds_meets(&prog(&[LDS_R, LDS_R, back])).0, 2); +} + +#[test] +fn gpu_split_wave64_lds_read_run_follows_instruction_order() { + if !gpu_ready() { + return; + } + for (exchange, threads) in [(false, 64usize), (false, 256), (true, 64), (true, 256)] { + let p = lds_read_run_program(exchange); + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(lds_order_cs(threads as u32)), wave64: true, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let (groups, base) = (1024usize, 0x100usize); + let mut io = vec![0u32; 128]; + io[0] = base as u32; + io[1] = threads.trailing_zeros(); + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * threads * 16) / 4]).unwrap(); + let mut wrong = Vec::new(); + for n in 0..groups * threads { + let (at, o) = ((base + n * 16) / 4, (n ^ 32) as u32); + let want = [0x1000_0000 | o, 0x2000_0000 | o, 0x1000_0000 | o, 0x2000_0000 | o]; + if out[at..at + 4] != want { + wrong.push(format!("group {} thread {}: read {:x?}, not {want:x?}", n / threads, n % threads, &out[at..at + 4])); + } + } + assert!(wrong.is_empty(), "exchange {exchange}, {threads} threads per group: {} of {} threads wrong: {}", wrong.len(), groups * threads, wrong[..wrong.len().min(4)].join("; ")); + } +} + #[test] fn wave_local_remap_decision_and_console_ids() { use super::{CsInterface, Mode, Options}; diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index c11d203537..dbc87e46da 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -43,6 +43,7 @@ whole-wave: | `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) | +| an LDS access (`ds_read*`, `ds_write*`, the LDS atomics) in kernel, compute and mesh mode | no words: the halves meet before it, so each half's earlier instructions are done (hazard 6) | 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`, @@ -100,6 +101,18 @@ it. A program that really uses the whole 32 KB of LDS therefore loses its top dw 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. +6. **LDS order** – a console wave runs an instruction in all 64 lanes before the next one, + so a lane reads the LDS another lane wrote an instruction earlier with no `s_barrier`. + Two halves that meet only at exchanges read such a word before it is written, or after a + later write (`gpu_split_wave64_lds_follows_instruction_order`: up to three quarters of + the threads on an RTX 5070 Ti). The halves therefore meet before an LDS access, except a + read right after a read in the same basic block (two reads need no order) or an access + after an exchange that lies between it and the block's previous access (the exchange is + a meeting). The meeting orders instructions, not the lanes of one instruction: when + lanes of both halves write or atomically update the same word in one instruction, which + half goes first is not the console's order. Geometry mode has no meetings: it assumes ES + code reads no other lane's item before the `s_barrier` (ES lanes write their own items, + and the phases meet at a group barrier). ### Masks read lane by lane @@ -139,7 +152,7 @@ destination, 0 in every lane), which are the same in both halves either way. A wave64 program pays one exchange per mask write that is read whole (`v_cmp*` feeding `s_and_saveexec`, `s_cbranch_vccz`, `s_bcnt1`, …) and per readlane / readfirstlane / -ds_bpermute / coherent scalar load, nothing per ALU, memory or DPP instruction, nor for +ds_bpermute / coherent scalar load / LDS access, nothing per ALU, global memory or DPP instruction, nor for masks read lane by lane (selects, 64-bit carry chains). Wave32 programs and everything on GPUs with 64-lane waves are unchanged (the HLSL of every native translation the test suite makes is byte-identical). A wave64 VS / PS pays nothing for a lane ≥ 32 read as a constant (the lane read is skipped) and From dbe6b30b6b2e9ac9a66d2488dad825a6ae171128 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 07:44:04 -0800 Subject: [PATCH 2/3] Recompiler: route split wave64 LDS through HLSL The direct per-instruction and per-lane lowerings do not yet order real LDS accesses between the two hardware halves. Refuse that unsafe combination so runtime routing uses the HLSL path's ordered meetings, while retaining native waves, geometry, and DS cross-lane operations. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 4 ++- crates/xcl/src/gpu/dxil/kernel.rs | 13 +++++++- crates/xcl/src/gpu/dxil/robustness_tests.rs | 32 ++++++++++++++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 37 +++++++++++++++++++++ 4 files changed, 84 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0e0b08d8c5..384f15b90c 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,9 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o masks and lane values ([`docs/wave64-on-wave32.md`](docs/wave64-on-wave32.md)) – slower than 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. + made up of complete native waves can use the per-lane form for branches on whole-wave masks; + split-wave64 programs that access LDS stay on the HLSL path to preserve instruction order + between their two hardware wave32 halves. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). ```powershell diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index a9dd50fe1d..c0b5e2396a 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -158,6 +158,14 @@ pub enum Entry { Geometry(GsInterface), } +/// Whether `d` accesses the group's LDS rather than using the DS encoding for a cross-lane +/// operation. GDS is separate global memory and is refused by the instruction lowering itself. +pub(crate) fn real_lds_access(d: &Decoded) -> bool { + d.enc.name == "ENC_DS" + && crate::gpu::rdna2::field_value(d.enc, &d.words, "GDS") != Some(1) + && !matches!(d.inst.name, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") +} + /// A compute-mode program (the CS ABI of `cs`). pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result { translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None) @@ -226,6 +234,9 @@ fn translate_on_this_thread( let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); let compute = matches!(entry, Entry::Compute(_)); let split = o.wave64 && o.split && !gfx; + if split && !matches!(entry, Entry::Geometry(_)) && cfg.insts.iter().any(real_lds_access) { + return Err("split wave64 LDS access needs the HLSL path".into()); + } let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); let uses_lds = lw.lds.is_some(); @@ -592,7 +603,7 @@ impl Lw { let mut slot = 1u32; for d in insts { let n = d.inst.name; - if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") { + if real_lds_access(d) { uses_lds = true; } if n == "DS_BPERMUTE_B32" { diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index 78a028cf23..0d550c9704 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -139,6 +139,38 @@ fn a_group_barrier_of_several_hardware_waves_is_left_to_the_hlsl_path() { kernel::translate_mesh(&code, o(false, false), &ms(32)).expect("a mesh pass of one 32-lane wave"); } +#[test] +fn split_wave64_real_lds_is_left_to_the_hlsl_path() { + let write = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None)]); + let swizzle = prog(&[("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 1), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 4)], None)]); + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + + let e = kernel::translate_compute(&write, o(true, true), &cs).err().expect("split LDS translated"); + assert!(e.contains("split wave64 LDS access needs the HLSL path"), "{e}"); + kernel::translate_compute(&write, o(true, false), &cs).expect("native wave64 LDS"); + kernel::translate_compute(&write, o(false, false), &cs).expect("native wave32 LDS"); + kernel::translate_compute(&swizzle, o(true, true), &cs).expect("split cross-lane DS"); +} + +#[test] +fn real_lds_classification_excludes_cross_lane_ds_and_gds() { + let one = |name, fields: &[(&str, u64)]| { + let bytes = encode(name, "ENC_DS", fields, None).unwrap(); + crate::gpu::rdna2::decode(&bytes, 0).unwrap() + }; + assert!(kernel::real_lds_access(&one("DS_READ_B32", &[("VDST", 1), ("ADDR", 0)]))); + assert!(!kernel::real_lds_access(&one("DS_READ_B32", &[("VDST", 1), ("ADDR", 0), ("GDS", 1)]))); + for (name, fields) in [ + ("DS_SWIZZLE_B32", &[("VDST", 1), ("ADDR", 0)][..]), + ("DS_BPERMUTE_B32", &[("VDST", 1), ("ADDR", 0), ("DATA0", 1)][..]), + ("DS_PERMUTE_B32", &[("VDST", 1), ("ADDR", 0), ("DATA0", 1)][..]), + ("DS_NOP", &[][..]), + ] { + assert!(!kernel::real_lds_access(&one(name, fields)), "{name}"); + } +} + // ---- builder misuse: recorded as the first error, finish fails instead of panicking use super::container::Stage; diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index cec9257c8a..3c101b368a 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -352,10 +352,18 @@ pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec, Vec), Str Ok((ir.finish([lanes, 1, 1], lanes)?.dxil, stale)) } +fn refuse_split_real_lds(insts: &[Decoded]) -> Result<(), String> { + if insts.iter().any(crate::gpu::dxil::kernel::real_lds_access) { + return Err("split wave64 LDS access needs the HLSL path".into()); + } + Ok(()) +} + /// `kernel` in the split form: a wave64 program as two hardware wave32s (`DxilIr::split`). /// EXEC at launch must be the whole console wave, as the CPU interpreter and the HLSL path /// start it. pub fn kernel_split(insts: &[Decoded]) -> Result<(Vec, Vec), String> { + refuse_split_real_lds(insts)?; let (ir, stale) = lower::lower_kernel(insts, true, DxilIr::split(insts, &Entry::Kernel))?; Ok((ir.finish([64, 1, 1], 32)?.dxil, stale)) } @@ -363,6 +371,7 @@ pub fn kernel_split(insts: &[Decoded]) -> Result<(Vec, Vec), String> { /// `compute` in the split form: each console wave64 as two hardware wave32s, threads numbered /// by arrival (`Lw::setup_lanes_compute`). pub fn compute_split(insts: &[Decoded], cs: &super::CsInterface) -> Result, String> { + refuse_split_real_lds(insts)?; let ir = lower::lower_compute(insts, cs, true, DxilIr::split(insts, &Entry::Compute(cs.clone())))?; Ok(ir.finish(cs.threads, 32)?.dxil) } @@ -421,6 +430,9 @@ pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> R insts.push(d); } crate::gpu::rdna2::resolve_far_jumps(&mut insts); + if o.wave64 && o.split { + refuse_split_real_lds(&insts)?; + } // as `kernel::translate_entry`: a thread with a large stack, a panic is a refusal let cs = cs.clone(); std::thread::Builder::new() @@ -799,6 +811,31 @@ mod tests { } } + #[test] + fn the_runtime_path_leaves_split_wave64_lds_to_hlsl() { + let bytes = crate::gpu::rdna2::encode("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None).unwrap(); + let cs = compute_cs(); + let o = |wave64, split| super::KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + + let e = super::compute_with(&bytes, &cs, o(true, true)).err().expect("split LDS translated"); + assert!(e.contains("split wave64 LDS access needs the HLSL path"), "{e}"); + let insts = [crate::gpu::rdna2::decode(&bytes, 0).unwrap()]; + let e = super::kernel_split(&insts).err().expect("split kernel LDS translated"); + assert!(e.contains("split wave64 LDS access needs the HLSL path"), "{e}"); + let e = super::compute_split(&insts, &cs).err().expect("split compute LDS translated"); + assert!(e.contains("split wave64 LDS access needs the HLSL path"), "{e}"); + super::compute_with(&bytes, &cs, o(true, false)).expect("native wave64 LDS"); + super::compute_with(&bytes, &cs, o(false, false)).expect("native wave32 LDS"); + + let swizzle = crate::gpu::rdna2::encode( + "DS_SWIZZLE_B32", + "ENC_DS", + &[("VDST", 1), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 4)], + None, + ).unwrap(); + super::compute_with(&swizzle, &cs, o(true, true)).expect("split cross-lane DS"); + } + /// The f64 program of `lower`'s tests, as `f32_programs_on_the_gpu`. #[test] fn f64_programs_on_the_gpu() { From e909e148b58c14feecf985b4bf138eee6487b411 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 07:48:56 -0800 Subject: [PATCH 3/3] Recompiler: reuse reduction meetings for LDS order Fused split-wave64 reduction tails emit their own guaranteed cross-half meeting, but did not record it in the LDS ordering state. Mark those exchanges as Met so a following LDS access does not pay for a redundant meeting. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/emit.rs | 3 +++ crates/xcl/src/gpu/recomp/tests.rs | 34 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 17cd0a7ca3..08b4624379 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1165,6 +1165,7 @@ impl Em { self.line(&format!("uint {t}_m = WaveReadLaneAt({v}, {lane32}u);")); self.line(&format!("xcl_x_put(0u, {t}_m);")); self.line(&format!("uint {t}_o = xcl_x_meet() ? xcl_x_get(0u) : 0u;")); + self.x64_met(); self.line(&format!("uint {t}_r1 = xcl_half == {}u ? {t}_m : {t}_o;", l1 >> 5)); self.line(&format!("uint {t}_r2 = xcl_half == {}u ? {t}_m : {t}_o;", l2 >> 5)); self.write32(&dst1, &format!("{t}_r1")); @@ -1189,6 +1190,7 @@ impl Em { self.line(&format!("uint {t}_m = WaveReadLaneAt({v}, {lane32}u);")); self.line(&format!("xcl_x_put(0u, {t}_m);")); self.line(&format!("uint {t}_o = xcl_x_meet() ? xcl_x_get(0u) : 0u;")); + self.x64_met(); self.line(&format!("uint {r1} = xcl_half == {}u ? {t}_m : {t}_o;", l1 >> 5)); self.line(&format!("uint {r2} = xcl_half == {}u ? {t}_m : {t}_o;", l2 >> 5)); self.write32(&Dst::S(s1), &r1); @@ -1240,6 +1242,7 @@ impl Em { self.line(&format!("uint {t}_mh = WaveReadLaneAt({vh}, {lane32}u);")); self.line(&format!("xcl_x_put(0u, {t}_ml); xcl_x_put(1u, {t}_mh);")); self.line(&format!("bool {t}_ok = xcl_x_meet();")); + self.x64_met(); self.line(&format!("uint {t}_ol = {t}_ok ? xcl_x_get(0u) : 0u;")); self.line(&format!("uint {t}_oh = {t}_ok ? xcl_x_get(1u) : 0u;")); let (h1, h2) = (l1 >> 5, l2 >> 5); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 3f24160dfd..8049734fb4 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7597,6 +7597,40 @@ fn split_wave64_meets_once_per_read_run() { assert_eq!(meets(&[r, br, r]), 2, "a branch target starts a block"); } +#[test] +fn split_wave64_reduction_exchange_orders_the_next_lds_access() { + let lo: LdsInst = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", 128 + 32)], None); + let hi: LdsInst = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", 128)], None); + let (n, hlsl) = x64_lds_meets(&prog(&[LDS_W, lo, hi, LDS_R])); + assert_eq!(hlsl.matches("xcl_x_meet() ?").count(), 4, "one folded exchange and three prelude calls:\n{hlsl}"); + assert_eq!(hlsl.matches("= xcl_x_rla_uniform(").count(), 0, "the pair was not folded:\n{hlsl}"); + assert_eq!(n, 1, "the folded exchange must order the following LDS read:\n{hlsl}"); +} + +#[test] +fn split_wave64_reduction32_exchange_orders_the_next_lds_access() { + let read_hi: LdsInst = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", 128 + 32)], None); + let reduce: LdsInst = ("V_MIN_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 8), ("VSRC1", 2)], None); + let read_lo: LdsInst = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 128)], None); + let (n, hlsl) = x64_lds_meets(&prog(&[LDS_W, read_hi, reduce, read_lo, LDS_R])); + assert_eq!(hlsl.matches("xcl_x_meet() ?").count(), 4, "one folded exchange and three prelude calls:\n{hlsl}"); + assert_eq!(hlsl.matches("= xcl_x_rla_uniform(").count(), 0, "the 32-bit tail was not folded:\n{hlsl}"); + assert_eq!(n, 1, "the folded 32-bit exchange must order the following LDS read:\n{hlsl}"); +} + +#[test] +fn split_wave64_reduction64_exchange_orders_the_next_lds_access() { + let read_hi_lo: LdsInst = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 2), ("SRC1", 128 + 32)], None); + let read_hi_hi: LdsInst = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 3), ("SRC1", 128 + 32)], None); + let reduce: LdsInst = ("V_ADD_F64", "ENC_VOP3", &[("VDST", 2), ("SRC0", 2), ("SRC1", V + 2)], None); + let read_lo_lo: LdsInst = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 2), ("SRC1", 128)], None); + let read_lo_hi: LdsInst = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 3), ("SRC1", 128)], None); + let (n, hlsl) = x64_lds_meets(&prog(&[LDS_W, read_hi_lo, read_hi_hi, reduce, read_lo_lo, read_lo_hi, LDS_R])); + assert_eq!(hlsl.matches("= xcl_x_meet();").count(), 1, "the 64-bit tail did not fold to one exchange:\n{hlsl}"); + assert_eq!(hlsl.matches("= xcl_x_rla_uniform(").count(), 0, "the 64-bit tail was not folded:\n{hlsl}"); + assert_eq!(n, 2, "one required LDS meet plus the folded 64-bit exchange; the following read must reuse it:\n{hlsl}"); +} + #[test] fn split_wave64_lds_local_mask_is_no_meeting() { let cmp: LdsInst = ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 0)], None);