From e22a0a6e781b3080f124fd6832b656fc66ff0820 Mon Sep 17 00:00:00 2001 From: Zondy <292338413+zondy1i@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:29:24 +0800 Subject: [PATCH] Recompiler: batch consecutive v_readfirstlane/v_readlane exchanges in split-wave64 --- crates/xcl/src/gpu/recomp/emit.rs | 148 +++++++++++++++++++++++++- crates/xcl/src/gpu/recomp/tests.rs | 160 +++++++++++++++++++++++++++++ 2 files changed, 307 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 2f817a809f..a9d83eb325 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -41,6 +41,9 @@ pub(super) struct Em { ps_writes_mask: bool, /// LDS used (compute): declare the groupshared array uses_lds: bool, + /// Pre-scanned guest LDS usage (including implicit geometry LDS), set before emitting so + /// split-wave64 readlane batching never expands `XCL_X_SLOT` into guest LDS headroom. + may_use_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: @@ -611,6 +614,7 @@ impl Em { has_ps_vm: false, ps_writes_mask: false, uses_lds: false, + may_use_lds: false, uses_scratch: false, x64_words: 1, mask_whole_live: BTreeMap::new(), @@ -647,6 +651,7 @@ impl Em { self.img_writes = image_write_srsrcs(insts); let mut writes_nonzero_dp = false; let mut has_s_barrier = false; + let mut may_use_lds = matches!(self.opt.mode, Mode::Geometry(_)); for d in insts { let name = d.inst.name.to_ascii_lowercase(); if stop_at_endpgm && matches!(name.as_str(), "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done") { @@ -655,6 +660,12 @@ impl Em { if name == "s_barrier" { has_s_barrier = true; } + if d.enc.name == "ENC_DS" + && !matches!(name.as_str(), "ds_swizzle_b32" | "ds_bpermute_b32") + && rdna2::field_value(d.enc, &d.words, "GDS").unwrap_or(0) == 0 + { + may_use_lds = true; + } if matches!(self.opt.mode, Mode::Pixel(_)) && d.enc.name == "ENC_EXP" && rdna2::field_value(d.enc, &d.words, "VM") == Some(1) { self.has_ps_vm = true; } @@ -688,6 +699,7 @@ impl Em { _ => {} } } + self.may_use_lds = may_use_lds; self.dynamic_f16_rm = writes_nonzero_dp && self.has_f16_round_op && !self.has_f64_round_op; self.safe_barrier = has_s_barrier && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) @@ -1010,16 +1022,26 @@ impl Em { /// Emit one basic block's instructions in order; stops at the first non-fallthrough flow. /// In split-wave64 mode, folds cross-half reduction tails (`v_readlane(v, L)` -> `v_op(v, s, v)` - /// -> `v_readlane(v, L^32)`, 32-bit and 64-bit `v_add_f64`) into a single `xcl_x_meet()`. + /// -> `v_readlane(v, L^32)`, 32-bit and 64-bit `v_add_f64`) and batches consecutive independent + /// `v_readfirstlane_b32` / `v_readlane_b32` exchanges into a single `xcl_x_meet()`. pub fn emit_insts(&mut self, block: &[Decoded], end: u64) -> Flow { let mut flow = Flow::Next; let mut i = 0; while i < block.len() { if self.x64() { + let n = self.x64_readlane_batch_len(&block[i..]); + if n > 2 && self.emit_x64_readlane_batch(&block[i..i + n]) { + i += n; + continue; + } if let Some(consumed) = self.try_emit_x64_reduction_tail(&block[i..]) { i += consumed; continue; } + if n >= 2 && self.emit_x64_readlane_batch(&block[i..i + n]) { + i += n; + continue; + } } let next = block.get(i + 1).map(|n| n.pc).unwrap_or(end); flow = self.inst(&block[i], next); @@ -1246,6 +1268,130 @@ impl Em { None } + /// SGPRs read by a plain `v_readfirstlane_b32` / `v_readlane_b32` source code. + fn x64_readlane_src_sgprs(code: u64) -> u128 { + match code { + 0..=124 | 126..=127 => 1u128 << code, + 251 => 3u128 << 106, // VCCZ + 252 => 3u128 << 126, // EXECZ + _ => 0, + } + } + + /// If `d` is a split-wave64 `v_readfirstlane_b32` / `v_readlane_b32` that will emit an + /// exchange, returns `(sgprs_read, sgprs_written)`. + fn x64_batchable_readlane(&self, d: &Decoded) -> Option<(u128, u128)> { + if d.variant != Variant::Plain { + return None; + } + let name = d.inst.name; + if !matches!(name, "V_READFIRSTLANE_B32" | "V_READLANE_B32") { + return None; + } + if !(d.enc.name.starts_with("ENC_VOP") || d.enc.name.starts_with("VOP")) { + return None; + } + if name == "V_READLANE_B32" && self.upper.as_ref().and_then(|u| u.reads.get(&d.pc)).is_some() { + return None; + } + let (outs, _) = Self::ops(d); + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + let written = match dst { + Dst::S(n) if n < 128 => 1u128 << n, + Dst::Null => 0, + _ => return None, + }; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let mut reads = Self::x64_readlane_src_sgprs(fv("SRC0")); + if name == "V_READFIRSTLANE_B32" { + reads |= 3u128 << 126; // EXEC_LO | EXEC_HI + } else { + reads |= Self::x64_readlane_src_sgprs(fv("SRC1")); + } + Some((reads, written)) + } + + /// Length of a dependency-free split-wave64 `v_readfirstlane_b32` / `v_readlane_b32` batch + /// starting at `rest[0]`. Bounded so the per-wave exchange slots stay <= 256 dwords (1 KB), + /// and disabled when the program may use guest LDS so `XCL_X_LDS_TOP` is never shrunk. + fn x64_readlane_batch_len(&self, rest: &[Decoded]) -> usize { + if self.may_use_lds || self.uses_lds || matches!(self.opt.mode, Mode::Geometry(_)) { + return 0; + } + let waves = self.x64_threads().div_ceil(64).max(1) as usize; + let cap = (64 / waves).clamp(2, 8); + let mut written = 0u128; + let mut n = 0; + for d in rest.iter().take(cap) { + let Some((r, w)) = self.x64_batchable_readlane(d) else { break }; + if (r & written) != 0 { + break; + } + written |= w; + n += 1; + } + n + } + + /// Emit `batch` (`len >= 2`) of consecutive split-wave64 `v_readfirstlane_b32` / + /// `v_readlane_b32` instructions using a single multi-word `xcl_x_meet()` exchange. + fn emit_x64_readlane_batch(&mut self, batch: &[Decoded]) -> bool { + struct Item { + pc: u64, + text: String, + src: String, + lane: Option, + dst: Dst, + } + let mut items = Vec::with_capacity(batch.len()); + let mut need_first = false; + for d in batch { + let (outs, ins) = Self::ops(d); + let Ok(u) = self.sources(d, &ins, false) else { return false }; + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + let src = u.first().cloned().unwrap_or_default(); + let lane = if d.inst.name == "V_READFIRSTLANE_B32" { + need_first = true; + None + } else { + Some(u.get(1).cloned().unwrap_or_default()) + }; + items.push(Item { pc: d.pc, text: rdna2::format(d), src, lane, dst }); + } + self.x64_words = self.x64_words.max(items.len()); + for it in &items { + self.line(&format!("// {:04x}: {}", it.pc, it.text)); + self.cur_pc = it.pc; + } + let t = self.t(); + if need_first { + let (el, eh) = (self.sreg(126), self.sreg(127)); + self.line(&format!("uint {t}_fl = first_lane({el}, {eh});")); + } + let mut lanes = Vec::with_capacity(items.len()); + for (i, it) in items.iter().enumerate() { + let l = match &it.lane { + None => format!("{t}_fl"), + Some(b) => { + let lv = format!("{t}_l{i}"); + self.line(&format!("uint {lv} = ({b}) & 63u;")); + lv + } + }; + self.line(&format!("uint {t}_m{i} = WaveReadLaneAt({}, {l} & 31u);", it.src)); + self.line(&format!("xcl_x_put({i}u, {t}_m{i});")); + lanes.push(l); + } + self.line(&format!("bool {t}_ok = xcl_x_meet();")); + for (i, (it, l)) in items.iter().zip(lanes.iter()).enumerate() { + self.line(&format!( + "uint {t}_r{i} = ({l} >> 5) == xcl_half ? {t}_m{i} : ({t}_ok ? xcl_x_get({i}u) : 0u);" + )); + self.write32(&it.dst, &format!("{t}_r{i}")); + } + true + } + pub fn inst(&mut self, d: &Decoded, next: u64) -> Flow { let name = d.inst.name.to_ascii_lowercase(); let text = rdna2::format(d); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..9e2ec5ea4d 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7145,6 +7145,166 @@ fn gpu_split_wave64_reduction_tails() { assert_eq!(r.sgpr[21], 0x1111, "inactive-lane-0 s_out keeps unmodified old v7[0]"); } +/// Split-wave64 uniform lane-read batching rules: consecutive independent reads share one +/// multi-word `xcl_x_meet()`, while SGPR/EXEC dependencies, jump targets, and the per-wave +/// slot cap split batches cleanly. +#[test] +fn split_wave64_readlane_batching_rules() { + let split = |mode| Options { mode, wave64: true, split_wave64: true, ..Default::default() }; + + // 4 consecutive v_readfirstlane_b32 (e.g. a 128-bit descriptor waterfall): 1 exchange, slot 4 + let four = prog(&[ + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 0)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 3)], None), + ]); + let t = translate(&four, &split(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_meet();").count(), 1, "4 reads share 1 meet:\n{}", t.hlsl); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 0); + assert!(t.hlsl.contains("#define XCL_X_SLOT 4u"), "{}", t.hlsl); + + // Native wave64 (split_wave64 = false) is untouched: no split exchange prelude or calls + let t_native = translate(&four, &Options { mode: Mode::Kernel, wave64: true, split_wave64: false, ..Default::default() }).unwrap(); + assert!(!t_native.hlsl.contains("xcl_x_meet")); + assert!(!t_native.hlsl.contains("xcl_x_put")); + + // Dependency on lane-selector SGPR breaks the batch + let dep = prog(&[ + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 0)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 10)], None), + ]); + let t = translate(&dep, &split(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_meet();").count(), 0, "SGPR dependency must not batch"); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 2); + + // Writing EXEC breaks a following v_readfirstlane_b32 + let exec_dep = prog(&[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 126), ("SRC0", V + 0), ("SRC1", 128)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)], None), + ]); + let t = translate(&exec_dep, &split(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_meet();").count(), 0, "EXEC write must split following v_readfirstlane"); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 2); + + // Branch target landing between two reads splits basic blocks (never batched across a leader) + let branch_split = prog(&[ + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None), // targets the second v_readfirstlane + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 0)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)], None), + ]); + let t = translate(&branch_split, &split(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_meet();").count(), 0, "jump target must split batch"); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 2); + + // Slot cap: 10 consecutive reads -> 8 + 2 in 64-thread groups (slot 8), 4 + 4 + 2 in 1024-thread groups (slot 4) + let ten = prog( + &(0..10u64) + .map(|i| ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 10 + i), ("SRC0", V + i)], None)) + .collect::>() + .iter() + .map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)) + .collect::>(), + ); + let t64 = translate(&ten, &split(Mode::Kernel)).unwrap(); + assert!(t64.hlsl.contains("#define XCL_X_SLOT 8u"), "64-thread cap should be 8"); + assert_eq!(t64.hlsl.matches("= xcl_x_meet();").count(), 2, "10 reads -> batches of 8 + 2"); + + let cs1024 = super::CsInterface { threads: [1024, 1, 1], ..Default::default() }; + let t1024 = translate(&ten, &split(Mode::Compute(cs1024))).unwrap(); + assert!(t1024.hlsl.contains("#define XCL_X_SLOT 4u"), "1024-thread cap should be 4"); + assert_eq!(t1024.hlsl.matches("= xcl_x_meet();").count(), 3, "10 reads -> batches of 4 + 4 + 2"); +} + +/// Programs that access guest LDS (even after a `v_readfirstlane_b32` run, e.g. at 512 threads) +/// must keep the 1-word exchange slot so `XCL_X_LDS_TOP` is never shrunk into guest LDS space. +/// Non-LDS `ENC_DS` lane ops (`ds_swizzle_b32`) do not disable batching. +#[test] +fn split_wave64_readlane_batch_preserves_guest_lds_top() { + let cs512 = super::CsInterface { threads: [512, 1, 1], ..Default::default() }; + let opt = Options { mode: Mode::Compute(cs512), wave64: true, split_wave64: true, ..Default::default() }; + + let mut with_lds: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = (0..8u64) + .map(|i| ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 10 + i), ("SRC0", V + i)], None)) + .collect(); + with_lds.push(("DS_WRITE_B32", "ENC_DS", vec![("ADDR", 1), ("DATA0", 0)], None)); + let code_lds = prog(&with_lds.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect::>()); + let t_lds = translate(&code_lds, &opt).unwrap(); + assert!(t_lds.hlsl.contains("#define XCL_X_SLOT 1u"), "guest LDS shader must keep 1-word slot:\n{}", t_lds.hlsl); + assert!(t_lds.hlsl.contains("#define XCL_X_LDS_TOP 8142u"), "512-thread LDS top must stay 8142u:\n{}", t_lds.hlsl); + assert_eq!(t_lds.hlsl.matches("= xcl_x_meet();").count(), 0); + + let mut with_swizzle: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = (0..8u64) + .map(|i| ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 10 + i), ("SRC0", V + i)], None)) + .collect(); + with_swizzle.push(("DS_SWIZZLE_B32", "ENC_DS", vec![("VDST", 16), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 4 << 2)], None)); + let code_sw = prog(&with_swizzle.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect::>()); + let t_sw = translate(&code_sw, &opt).unwrap(); + assert!(t_sw.hlsl.contains("#define XCL_X_SLOT 8u"), "ds_swizzle_b32 must not disable batching:\n{}", t_sw.hlsl); + assert_eq!(t_sw.hlsl.matches("= xcl_x_meet();").count(), 1); +} + +/// GPU verification of batched split-wave64 `v_readfirstlane_b32` / `v_readlane_b32`: +/// upper-half active lanes, mixed lower/upper lane reads in one exchange, SGPR dependency split, +/// and EXEC-modifying split. +#[test] +fn gpu_split_wave64_batched_readlanes() { + if !gpu_ready() { + return; + } + // Activate only lane 38 (upper half: exec_lo = 0, exec_hi = 1 << 6) + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], Some(1 << 6)), + // Batch 1 (4 words): 4 consecutive v_readfirstlane_b32 from upper-half lane 38 + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 0)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 3)], None), + // Batch 2 (3 words): mixed lower lane (5), upper lane (41), and v_readfirstlane (38) + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 128 + 41)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 0), ("SRC1", 128 + 5)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", 20)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 16), ("SRC0", V + 2)], None), + // Dependency split: s17 = v4[lane 41] (= 7), then s18 = v5[lane s17] (= v5[7]) + ("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", 20)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 5), ("SRC1", 17)], None), + // EXEC dependency split: exec_lo = v6[lane 41] (= 1 << 9), then s19 = v7[first_lane = 9] + ("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 126), ("SRC0", V + 6), ("SRC1", 20)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 7)], None), + ]); + if runner::split_wave64() { + let t = translate(&code, &runner::options(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_meet();").count(), 2, "two independent runs batched:\n{}", t.hlsl); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 4, "two dependent pairs kept separate"); + } + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l = l as u32; + r[0] = 0x1000 + l; + r[1] = 0x2000 + l; + r[2] = 0x3000 + l; + r[3] = 0x4000 + l; + r[4] = if l == 41 { 7 } else { 0 }; + r[5] = 0x5000 + l; + r[6] = if l == 41 { 1 << 9 } else { 0 }; + r[7] = 0x7000 + l; + } + let r = runner::run_code(&code, &st, &[]).unwrap(); + assert_eq!(r.sgpr[10], 0x1000 + 38, "batch 1 word 0 (lane 38)"); + assert_eq!(r.sgpr[11], 0x2000 + 38, "batch 1 word 1 (lane 38)"); + assert_eq!(r.sgpr[12], 0x3000 + 38, "batch 1 word 2 (lane 38)"); + assert_eq!(r.sgpr[13], 0x4000 + 38, "batch 1 word 3 (lane 38)"); + assert_eq!(r.sgpr[14], 0x1000 + 5, "batch 2 lower lane 5"); + assert_eq!(r.sgpr[15], 0x2000 + 41, "batch 2 upper lane 41"); + assert_eq!(r.sgpr[16], 0x3000 + 38, "batch 2 v_readfirstlane lane 38"); + assert_eq!(r.sgpr[17], 7, "dependent lane index from upper half"); + assert_eq!(r.sgpr[18], 0x5000 + 7, "dependent readlane uses new s17"); + assert_eq!(r.sgpr[19], 0x7000 + 9, "v_readfirstlane observes updated exec_lo (lane 9)"); +} + /// Masks that are read whole after a write `x64_masks` must not take for an overwrite (an /// SDWA compare into its SDST, `s_bitset1`, `s_movreld`) or through a read the operand /// tables do not show (`s_movrels`, an SMEM register offset, an SDWA scalar src1): each is