Skip to content
Open
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
4 changes: 4 additions & 0 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,12 +252,16 @@ fn translate_entry_with(
let code = code.to_vec();
#[cfg(test)]
let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get());
#[cfg(test)]
let quad_op = super::lanes::QUAD_OP_IN_TEST.with(|c| c.get());
std::thread::Builder::new()
.name("xcl-dxil-translate".into())
.stack_size(256 << 20)
.spawn(move || {
#[cfg(test)]
super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold));
#[cfg(test)]
super::lanes::QUAD_OP_IN_TEST.with(|c| c.set(quad_op));
translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask)
})
.map_err(|e| format!("translator thread: {e}"))?
Expand Down
182 changes: 160 additions & 22 deletions crates/xcl/src/gpu/dxil/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ use super::lower::{Lw, Partner, VAR_BAR_ALIVE, VAR_XLW};
use super::module::{BinOp, Pred, RmwOp, Value};
use super::ops::barrier;

#[cfg(test)]
thread_local! {
/// Tests can compare `Lw::ballot_ps` with the `quadOp` form it had;
/// `kernel::translate_entry_with` hands the choice to the translator's thread.
pub(super) static QUAD_OP_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

impl Lw {
/// Groupshared storage, created in the entry block before anything else:
/// the program's LDS (`lds_words` > 0), multi-wave safe-barrier counters
Expand Down Expand Up @@ -891,23 +898,45 @@ impl Lw {
}

/// Pixel-shader ballot including helper lanes (parity with HLSL `ballot_px` in
/// `recomp/emit.rs`): each quad collects its 4 bits through `QuadReadAcross*`
/// (which see helper lanes) and feeds them to [`Lw::ballot_ps_quad`]. Entry `EXEC` in
/// `setup_pixel` runs before `self.gfx` is set, so it stays live-lanes-only.
/// `recomp/emit.rs`): each quad collects its 4 bits through `QuadReadLaneAt` (which sees
/// helper lanes) and feeds them to [`Lw::ballot_ps_quad`]. Entry `EXEC` in `setup_pixel`
/// runs before `self.gfx` is set, so it stays live-lanes-only.
///
/// Not through `QuadReadAcross*` (`quadOp`), as it was: an AMD RDNA2 driver (amdxc64
/// 32.0.21030.2001 and 32.0.21045.29003) dies with a null read at the start of the pipeline
/// build of a retail title's pixel shader in which 10 of 27 such ballots take a value that
/// derives from `WaveReadLaneAt`. With the 4 reads the same pipeline builds. The compare
/// path reads its quad the same way for the same driver (`lower_valu`, #134).
fn ballot_ps(&mut self, cond: Value) -> (Value, Value) {
let z = self.c(0);
if self.s.m.const_u64(cond) == Some(0) {
return (z, z);
}
let qbit = self.andc(self.lane, 3);
let own_b = self.u(cond);
let own = self.bin(BinOp::Shl, own_b, qbit);
let qx = self.s.quad_op(own, super::ops::QuadDir::ReadAcrossX);
let qy = self.s.quad_op(own, super::ops::QuadDir::ReadAcrossY);
let qd = self.s.quad_op(own, super::ops::QuadDir::ReadAcrossDiagonal);
let q0 = self.or(own, qx);
let q1 = self.or(qy, qd);
let q = self.or(q0, q1);
#[cfg(test)]
let quad_op = QUAD_OP_IN_TEST.with(|c| c.get());
#[cfg(not(test))]
let quad_op = false;
let q = if quad_op {
let qbit = self.andc(self.lane, 3);
let own = self.bin(BinOp::Shl, own_b, qbit);
let qx = self.s.quad_op(own, super::ops::QuadDir::ReadAcrossX);
let qy = self.s.quad_op(own, super::ops::QuadDir::ReadAcrossY);
let qd = self.s.quad_op(own, super::ops::QuadDir::ReadAcrossDiagonal);
let q0 = self.or(own, qx);
let q1 = self.or(qy, qd);
self.or(q0, q1)
} else {
// (bit `p` = the quad's member `p`, the lane `4k + p`, as `own << (lane & 3)` above)
let mut q = z;
for p in 0..4u32 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not certain about this one: the new form quad-reads every member's predicate without masking it by that member's EXEC bit, unlike the compare path it copies (lower_valu.rs:1344-1361 ANDs each member with lanebit_at(el, eh, qbase|p)). In a quad where some lanes are hardware-inactive (after a discard/demote, or switched off by divergent control flow at the ballot), QuadReadLaneAt of those lanes is undefined, and that bit goes into the mask through ballot_ps_quad. A later s_cbranch_vccnz / s_and_saveexec on it can see lanes set that should be clear. The quadOp form had the same gap.

let kp = self.c(p);
let r = self.s.quad_read_lane_at(own_b, kp);
let sh = self.shlc(r, p);
q = self.or(q, sh);
}
q
};
let (lo, hi) = self.ballot_ps_quad(q);
self.note_own_bit(lo, hi, cond);
(lo, hi)
Expand Down Expand Up @@ -1188,19 +1217,77 @@ mod ps_ballot_tests {
);
}

/// Translates `code` with a pixel shader's carry ballots in the `quadOp` form (`true`) or in
/// the `quadReadLaneAt` form XCL emits (`false`).
fn translate_with_quad_op(quad_op: bool, code: &[u8], opt: KernelOptions, psi: &PsInterface) -> kernel::Kernel {
super::QUAD_OP_IN_TEST.with(|c| c.set(quad_op));
let k = kernel::translate_pixel(code, opt, psi);
super::QUAD_OP_IN_TEST.with(|c| c.set(false));
let k = k.expect("translate PS");
validate::validate(&k.dxil).expect("validate PS");
k
}

/// A carry mask (no compare): `v_add_co_u32` of `0xBE780000` and the bits of `pos.x` carries
/// from `pos.x = 17.0` on, inside a quad. Red is `v_cndmask` by the mask: `pos.x`, or 1.0
/// where it is clear. It takes a lane's own bit, which is the predicate (`Lw::own_bits`).
/// Green, with `whole`, is `v_cndmask` by the mask shifted one lane down, read from its word:
/// the bit of the lane to the right, a helper lane on a triangle's edge, as the quad's live
/// lanes collected it (in the quad's right lanes: the bit of another quad's lane, not
/// defined); without, the DPP `ddx` of red, which reads the lane next to each one.
/// With `readfirstlane`, the carry's other operand comes through `WaveReadLaneAt` instead of
/// the literal: the shape in a retail title's pixel shader whose pipeline build took an AMD
/// RDNA2 driver down while these ballots read their quad through `quadOp`.
fn carry_ballot_ps_code(wave64: bool, readfirstlane: bool, whole: bool) -> Vec<u8> {
let ins = |n, e, f: &[(&str, u64)], lit| encode(n, e, f, lit).unwrap();
let mut code = ins(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None);
if readfirstlane {
code.extend(ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 3)], None));
code.extend(ins("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 106), ("SRC0", 4), ("SRC1", V + 2)], None));
} else {
code.extend(ins("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 106), ("SRC0", 255), ("SRC1", V + 2)], Some(0xBE78_0000)));
}
code.extend(ins("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 242), ("VSRC1", 2)], None));
if whole {
code.extend(ins(if wave64 { "S_LSHR_B64" } else { "S_LSHR_B32" }, "ENC_SOP2", &[("SDST", 10), ("SSRC0", 106), ("SSRC1", 129)], None));
code.extend(ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 242), ("SRC1", V + 2), ("SRC2", 10)], None));
} else {
code.extend(ins("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 5), ("DPP_CTRL", 0xB1), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None));
code.extend(ins("V_SUB_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 6), ("VSRC1", 5)], None));
}
code.extend(ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 5), ("VSRC1", 7), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1), ("VM", 1)], None));
code.extend(ins("S_ENDPGM", "ENC_SOPP", &[], None));
code
}

#[test]
fn direct_ps_non_vopc_carry_ballot_uses_quad_op() {
fn direct_ps_non_vopc_carry_ballot_reads_its_quad_lane_by_lane() {
let psi = ps_interface();
let mut code = Vec::new();
code.extend(encode("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None).unwrap());
code.extend(encode("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 106), ("SRC0", V + 2), ("SRC1", V + 3)], None).unwrap());
code.extend(encode("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 128), ("VSRC1", 4)], None).unwrap());
code.extend(encode("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 5), ("VSRC1", 3), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1), ("VM", 1)], None).unwrap());
code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
let k = kernel::translate_pixel(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate carry PS");
validate::validate(&k.dxil).expect("validate carry PS");
let dis = validate::disassemble(&k.dxil).expect("disassemble carry PS");
assert!(dis.contains("dx.op.quadOp.i32"), "non-VOPC PS carry ballot must preserve helper lanes via quadOp:\n{dis}");
let mut lane_reads = [[0usize; 2]; 2];
for (wave64, readfirstlane) in [(false, false), (true, false), (false, true), (true, true)] {
let opt = KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 };
let code = carry_ballot_ps_code(wave64, readfirstlane, false);
let dis = validate::disassemble(&translate_with_quad_op(false, &code, opt, &psi).dxil).expect("disassemble PS");
let old = validate::disassemble(&translate_with_quad_op(true, &code, opt, &psi).dxil).expect("disassemble PS");
let reads = |d: &str| d.matches("call i32 @dx.op.quadReadLaneAt.i32(").count();
assert!(!dis.contains("dx.op.quadOp"), "wave64 {wave64}, readfirstlane {readfirstlane}: a PS carry ballot must not emit quadOp (an AMD driver dies building it):\n{dis}");
assert_eq!(old.matches("call i32 @dx.op.quadOp.i32(").count(), 3, "wave64 {wave64}, readfirstlane {readfirstlane}: the form compared with is the quadOp one:\n{old}");
// (the other quad reads, of the DPP `ddx`, are in both forms)
assert_eq!(reads(&dis), reads(&old) + 4, "wave64 {wave64}, readfirstlane {readfirstlane}: one read per lane of the quad:\n{dis}");
lane_reads[wave64 as usize][readfirstlane as usize] = dis.matches("@dx.op.waveReadLaneAt.").count();
// in both forms `v_cndmask` takes the carry itself (`Lw::own_bits`), not the mask's word
for (form, d) in [("quadReadLaneAt", &dis), ("quadOp", &old)] {
let sel = d.lines().find(|l| l.contains("select i1 ") && l.contains("1065353216")).expect("the v_cndmask");
let cond = sel.split("select i1 ").nth(1).unwrap().split(',').next().unwrap().trim();
let def = d.lines().find(|l| l.trim_start().starts_with(&format!("{cond} ="))).unwrap_or("");
assert!(!def.is_empty() && !def.contains("icmp ne"), "wave64 {wave64}, readfirstlane {readfirstlane}, {form}: the v_cndmask tests the mask's word (select cond {def}):
{d}");
}
}
// with `v_readfirstlane` the carry's operand comes through `WaveReadLaneAt`
for (wave64, [plain, first]) in lane_reads.into_iter().enumerate() {
assert!(first > plain, "wave64 {}: {first} WaveReadLaneAt with v_readfirstlane, {plain} without", wave64 == 1);
}
}

/// This lane's bit of a mask made from its own predicate is that predicate (`Lw::own_bits`),
Expand Down Expand Up @@ -1233,6 +1320,57 @@ mod ps_ballot_tests {
}
}

#[test]
fn gpu_direct_ps_carry_ballot_draws_the_same_lane_by_lane_as_through_quadop() {
match (runner::adapter(), runner::wave32_supported(), dxc::location()) {
(Ok(_), Ok(true), Ok(_)) => {}
(a, w, d) => return runner::skip_test(if a.is_err() || w.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave32" }),
}
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT;
let vs = dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap();
let psi = ps_interface();
let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0];
let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }];
let size = 32usize;
let wave64_ok = matches!(runner::wave64_programs_supported(), Ok(true));
for wave64 in [false, true] {
if wave64 && !wave64_ok {
continue;
}
let opt = KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 };
for whole in [false, true] {
let code = carry_ballot_ps_code(wave64, false, whole);
let [by_lane, by_quad_op] = [false, true].map(|quad_op| {
let ps = translate_with_quad_op(quad_op, &code, opt, &psi);
runner::draw(&vs, &ps.dxil, &layout, &quad, 8, &[], &[], size as u32, [9.0; 4]).unwrap()
});
// the mask is clear left of x = 17 and set from there on
let red = |x: f32| if x >= 17.0 { x } else { 1.0 };
let bad: Vec<(usize, usize, [f32; 4], [f32; 4], [f32; 4])> = (0..size * size)
.filter_map(|i| {
let (px, py) = (i % size, i / size);
let (x, left) = (px as f32 + 0.5, px % 2 == 0);
let beside = if left { x + 1.0 } else { x - 1.0 };
let (mut p, mut o) = (by_lane[i], by_quad_op[i]);
let green = match (whole, left) {
(false, _) => red(beside) - red(x),
(true, true) => if beside >= 17.0 { x } else { 1.0 },
(true, false) => {
(p[1], o[1]) = (0.0, 0.0); // another quad's lane
0.0
}
};
let want = [red(x), green, x, py as f32 + 0.5];
// the two forms agree on every pixel; what they draw is known but for the
// quads on the diagonal, where the triangles meet (helper lanes)
(p != o || (px / 2 != py / 2 && p != want)).then_some((px, py, p, o, want))
})
.collect();
assert!(bad.is_empty(), "wave64 {wave64}, whole {whole}: {} pixels differ between the two forms or do not hold the mask, first {:?}", bad.len(), &bad[..bad.len().min(6)]);
}
}
}

#[test]
fn gpu_direct_ps_masks_hold_helper_lanes_on_triangle_edges() {
match (runner::adapter(), runner::wave64_programs_supported(), dxc::location()) {
Expand Down
Loading