Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 74 additions & 4 deletions crates/xcl/src/gpu/recomp/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ pub trait Ir: Sink {
fn whole_needs_exchange(&self) -> bool {
false
}
/// Whether this IR can lower whole-wave branches (`ballot` across the full console wave,
/// including a split wave64 whose partner half is present or spin-synced).
fn can_wave_branch(&self) -> bool {
!self.whole_needs_exchange()
}
/// the number of bits set in `v` (`countbits`)
fn count_bits(&mut self, v: Self::V) -> Self::V;
/// `d` lowered with another lowering's instruction semantics (#1426's `Lw::inst_guarded`):
Expand Down Expand Up @@ -155,6 +160,9 @@ struct Lower<'a, I: Ir> {
sum: &'a Summary,
guarded: HashSet<u64>,
wave_branches: bool,
/// Whether SCC is live after instruction `i` (used to skip dead whole-wave SCC ballots).
scc_live_after: Vec<bool>,
cur_inst: usize,
wave64: bool,
/// the markers: a number where a mask was written, a bit where a number was
num_marker: I::V,
Expand Down Expand Up @@ -546,6 +554,15 @@ impl<'a, I: Ir> Lower<'a, I> {
self.ir.icmp(Cmp::Ne, word, zero)
}

/// Whole-wave `mask_nonzero` for an SCC write: skips the ballot (and any split-wave64
/// exchange barrier) when no subsequent instruction reads SCC before it is overwritten.
pub(super) fn mask_nonzero_scc(&mut self, bit: I::V) -> I::V {
if self.wave_branches && !self.scc_live_after[self.cur_inst] {
return self.ir.boolean(false);
}
self.mask_nonzero(bit)
}

fn salu(&mut self, b: usize, d: &Decoded) -> R<()> {
let name = d.inst.name;
let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f);
Expand Down Expand Up @@ -589,7 +606,7 @@ impl<'a, I: Ir> Lower<'a, I> {
if sd != 125 {
self.write_bit(b, sd, if base.ends_with("_WREXEC") { new } else { old });
}
let scc = self.mask_nonzero(new);
let scc = self.mask_nonzero_scc(new);
self.write_scc(b, scc);
return Ok(());
}
Expand All @@ -613,7 +630,7 @@ impl<'a, I: Ir> Lower<'a, I> {
};
self.write_bit(b, sd, v);
if op != "MOV" {
let scc = self.mask_nonzero(v);
let scc = self.mask_nonzero_scc(v);
self.write_scc(b, scc);
}
return Ok(());
Expand All @@ -624,7 +641,7 @@ impl<'a, I: Ir> Lower<'a, I> {
if cmp64.contains(&name) && [s0, s1].iter().any(|&c| c <= 127 && self.holds_mask(b, c as u8)) {
let (a, c) = (self.src_bit(b, d, s0)?, self.src_bit(b, d, s1)?);
let x = self.ir.bin(Bin::Xor, a, c);
let x = self.mask_nonzero(x);
let x = self.mask_nonzero_scc(x);
let v = if name == cmp64[0] { self.not(x) } else { x };
self.write_scc(b, v);
return Ok(());
Expand Down Expand Up @@ -1155,6 +1172,50 @@ fn lower<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, ir: I) -> R<(I, V
lower_with(insts, stage, wave64, ir, false).map(|(ir, stale, _)| (ir, stale))
}

/// Backward liveness of SCC over `sum.blocks`: `live_after[i]` is true when some path
/// from instruction `i` can read SCC before an unconditional scalar instruction overwrites it.
fn compute_scc_liveness(insts: &[Decoded], sum: &Summary) -> Vec<bool> {
let reads_scc = |d: &Decoded| -> bool {
matches!(d.inst.name, "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1")
|| d.ienc.operands.iter().any(|o| o.input && o.ty == "OPR_SSRC_SPECIAL_SCC")
|| ["SSRC0", "SSRC1", "SRC0", "SRC1", "SRC2", "SOFFSET"]
.iter()
.any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(253))
};
let writes_scc = |d: &Decoded| -> bool {
d.inst.name.starts_with("S_")
&& d.ienc.operands.iter().any(|o| o.output && o.ty == "OPR_SSRC_SPECIAL_SCC")
};
let nb = sum.blocks.len();
let mut live_in = vec![false; nb];
let mut live_after = vec![false; insts.len()];
loop {
let mut changed = false;
for &b in sum.order.iter().rev() {
let block = &sum.blocks[b];
let mut live = block.succ.iter().any(|&(s, _)| live_in[s]);
for i in block.insts.clone().rev() {
live_after[i] = live;
let d = &insts[i];
if writes_scc(d) {
live = false;
}
if reads_scc(d) {
live = true;
}
}
if live_in[b] != live {
live_in[b] = live;
changed = true;
}
}
if !changed {
break;
}
}
live_after
}

/// Survey: every reason the per-lane form refuses a compute program, not only the first. An
/// instruction it refuses is left out and the lowering goes on, so a later reason may follow
/// from an earlier one; a program the lane-mask analysis refuses gives that one reason.
Expand All @@ -1174,8 +1235,13 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
let launch = if pixel { lane_masks::LaunchExec::Unknown } else { lane_masks::LaunchExec::All };
// Ballots reconstruct every bit only when the entire console wave is present.
let wave_branches = matches!(stage, Stage::Compute(cs) if cs.threads.iter().product::<u32>() % (if wave64 { 64 } else { 32 }) == 0)
&& !ir.whole_needs_exchange();
&& ir.can_wave_branch();
let sum = lane_masks::analyze_branches(insts, wave64, launch, wave_branches).map_err(|e| e.to_string())?;
let scc_live_after = if wave_branches {
compute_scc_liveness(insts, &sum)
} else {
vec![true; insts.len()]
};
let n = sum.blocks.len();
if n == 0 {
return Err("empty program".into());
Expand Down Expand Up @@ -1249,6 +1315,8 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
sum: &sum,
guarded,
wave_branches,
scc_live_after,
cur_inst: 0,
wave64,
num_marker,
bit_marker,
Expand Down Expand Up @@ -1432,6 +1500,7 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
l.ssa.seal(&mut l.ir, s);
l.unguarded = true;
for j in run.clone() {
l.cur_inst = j;
let r = l.lower_inst(s, &insts[j]);
l.note_inst(r, s, &insts[j])?;
}
Expand All @@ -1449,6 +1518,7 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
i += 1;
continue;
}
l.cur_inst = i;
let r = l.lower_inst(cur, &insts[i]);
l.note_inst(r, cur, &insts[i])?;
i += 1;
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/recomp/lower/wave.rs
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ impl<I: Ir> Lower<'_, I> {
let z = self.c(0);
let bit = self.ir.icmp(Cmp::Ne, w, z);
self.write_bit(b, sd, bit);
let scc = self.mask_nonzero(bit);
let scc = self.mask_nonzero_scc(bit);
self.write_scc(b, scc);
return Ok(true);
}
Expand Down
100 changes: 99 additions & 1 deletion crates/xcl/src/gpu/recomp/lower_dxil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,10 +226,18 @@ impl Ir for DxilIr {
fn whole_needs_exchange(&self) -> bool {
self.lw.split
}
fn can_wave_branch(&self) -> bool {
!self.lw.split
|| matches!(
self.lw.partner,
crate::gpu::dxil::lower::Partner::Present | crate::gpu::dxil::lower::Partner::Spin
)
}
fn ballot(&mut self, c: Value) -> [Value; 2] {
if self.lw.split {
// this half's word from the hardware, the other's through the exchange
let (lo, hi) = self.lw.ballot(c);
self.tails[self.cur] = self.lw.cur();
return [lo, hi];
}
let w = self.lw.s.wave_ballot(c);
Expand Down Expand Up @@ -282,7 +290,9 @@ impl Ir for DxilIr {
if self.lw.split {
// the lowering's lane reads take the same lane in every lane (readlane,
// readfirstlane, writelane's source)
return self.lw.read_lane_uniform(v, lane);
let r = self.lw.read_lane_uniform(v, lane);
self.tails[self.cur] = self.lw.cur();
return r;
}
self.lw.s.wave_read_lane_at(v, lane)
}
Expand Down Expand Up @@ -797,6 +807,94 @@ mod tests {
}
}

#[test]
fn split_wave64_wave_branches_on_the_gpu() {
for threads in [64u32, 128] {
let mut cs = compute_cs();
cs.threads = [threads, 1, 1];
for (lines, expected) in wave_branch_cases(true) {
let dxil = super::compute_split(&decode(&lines), &cs)
.unwrap_or_else(|e| panic!("split threads={threads}, {lines:?}: {e}"));
if crate::gpu::dxil::validate::validator_supported() {
crate::gpu::dxil::validate::validate(&dxil)
.unwrap_or_else(|e| panic!("split threads={threads}, {lines:?}: {e}"));
}
if gpu() {
let out = runner::dispatch(&dxil, [1, 1, 1], &[], &vec![0; threads as usize]).unwrap();
// Wave 0 (lanes 0..63) has lane 63 matching `SRC0 = 63`.
assert_eq!(&out[..64], &[expected; 64], "split threads={threads} wave0, {lines:?}");
if threads == 128 {
// Wave 1 (lanes 64..127) has no lane with v0 == 63, so compare against
// the regular direct split-wave64 translator across all 128 threads.
let bytes: Vec<u8> = lines
.iter()
.flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap())
.collect();
let o = super::KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
let ref_dxil = crate::gpu::dxil::kernel::translate_compute(&bytes, o, &cs).unwrap().dxil;
let ref_out = runner::dispatch(&ref_dxil, [1, 1, 1], &[], &vec![0; 128]).unwrap();
assert_eq!(&out[..128], &ref_out[..128], "split threads=128 parity, {lines:?}");
}
}
}
}
}

#[test]
fn split_wave64_dead_scc_skips_exchange_barrier() {
let mut cs = compute_cs();
cs.threads = [64, 1, 1];
// Case A: `S_AND_SAVEEXEC_B64` writes SCC, immediately overwritten by `S_CMP_EQ_U32`
// before any SCC read -> no split-exchange ballot should be emitted.
let dead_scc = [
("V_CMP_LE_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)][..]), // lanes 32..63
("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]),
("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 4)]),
("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 128)]),
("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 137), ("SSRC1", 129)]),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 6), ("VSRC1", 1)]),
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 0)]),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 125)]),
("S_ENDPGM", "ENC_SOPP", &[]),
];
// Case B: `S_CSELECT_B32` directly consumes the SCC written by `S_AND_SAVEEXEC_B64`
// -> split-exchange ballot MUST be emitted (+2 GROUP_SYNC barriers).
let live_scc = [
("V_CMP_LE_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)][..]),
("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]),
("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 4)]),
("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 137), ("SSRC1", 129)]),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 6), ("VSRC1", 1)]),
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 0)]),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 125)]),
("S_ENDPGM", "ENC_SOPP", &[]),
];
let dxil_dead = super::compute_split(&decode(&dead_scc), &cs).unwrap();
let dxil_live = super::compute_split(&decode(&live_scc), &cs).unwrap();
if crate::gpu::dxil::validate::validator_supported() {
crate::gpu::dxil::validate::validate(&dxil_dead).unwrap();
crate::gpu::dxil::validate::validate(&dxil_live).unwrap();
}
if let (Ok(dis_dead), Ok(dis_live)) = (
crate::gpu::dxil::validate::disassemble(&dxil_dead),
crate::gpu::dxil::validate::disassemble(&dxil_live),
) {
let b_dead = dis_dead.matches("@dx.op.barrier(").count();
let b_live = dis_live.matches("@dx.op.barrier(").count();
assert_eq!(b_live, b_dead + 2, "live SCC should emit one split-exchange (+2 barriers); dead={b_dead}, live={b_live}");
}
if gpu() {
for dxil in [&dxil_dead, &dxil_live] {
let out = runner::dispatch(dxil, [1, 1, 1], &[], &[0; 64]).unwrap();
// `V_CMP_LE_U32(32, v0)` selects upper half (lanes 32..63): lower gets 0+9, upper gets 7+9.
assert_eq!(&out[..32], &[9; 32]);
assert_eq!(&out[32..64], &[16; 32]);
}
}
}

#[test]
fn a_per_lane_compute_program_runs_on_the_gpu() {
if !gpu() {
Expand Down
Loading