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
1 change: 1 addition & 0 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
key.push(sampler.is_some() as u64);
key.extend(sampler.into_iter().flatten().map(|&w| w as u64));
key.push(match lw.mask_batch_end.get(&d.pc) { None => 0, Some(false) => 1, Some(true) => 2 });
key.push(lw.uniform_reads.contains(&d.pc) as u64);
// what `Lw::write_mask` asks of this address, for any register a mask can go to
if let Some(&l) = lw.whole_live.get(&d.pc) {
let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST"));
Expand Down
693 changes: 693 additions & 0 deletions crates/xcl/src/gpu/dxil/idioms.rs

Large diffs are not rendered by default.

20 changes: 17 additions & 3 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ pub struct Kernel {
pub dxil: Vec<u8>,
pub static_samplers: Vec<([u32; 4], bool)>,
pub dispatch_chain: Option<std::sync::Arc<DispatchChain>>,
/// places where the halves of a split wave64 program meet
pub exchange_sites: u32,
}

pub use super::module::split::DispatchChain;
Expand All @@ -103,9 +105,14 @@ pub fn compact_mode() -> Option<bool> {
}
}

/// Non-default `XCL_DIRECT_COMPACT_NEST` cache tag for the translated cache identity.
/// Non-default `XCL_DIRECT_COMPACT_NEST` and `XCL_WAVE64_IDIOMS=0` cache tag for the translated cache identity.
pub fn compact_nest_tag() -> Option<String> {
super::compact::nest_mode().cache_tag()
let tags = [
super::compact::nest_mode().cache_tag(),
(!super::idioms::enabled()).then(|| "xcl-wave64-idioms-0".to_string()),
];
let tags: Vec<String> = tags.into_iter().flatten().collect();
(!tags.is_empty()).then(|| tags.join("-"))
}

/// `translate_full` in the compact form (`compact = true`) or the plain one.
Expand Down Expand Up @@ -252,12 +259,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 idioms = super::idioms::IDIOMS_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::idioms::IDIOMS_IN_TEST.with(|c| c.set(idioms));
translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask)
})
.map_err(|e| format!("translator thread: {e}"))?
Expand Down Expand Up @@ -336,6 +347,7 @@ fn translate_on_this_thread(
let mut lw = Lw::new_with_slot(&cfg.insts, &leaders, o, &entry, masks.words);
lw.whole_live.extend(masks.demand);
lw.mask_batch_end = masks.batch_end;
lw.uniform_reads = masks.uniform_reads;
lw.waterfall_ssamp = waterfall_ssamp;
// In non-kernel entries, constant data after the program is only reachable via `s_getpc_b64`
// (which supplies `CODE_ADDRESS_HI`). Without `s_getpc_b64`, probing every loaded dword against
Expand Down Expand Up @@ -736,6 +748,7 @@ impl Lw {
xs: None,
xw: None,
xc: None,
exchange_sites: 0,
barrier_waves: None,
safe_bar: None,
waves: 1,
Expand All @@ -754,6 +767,7 @@ impl Lw {
whole_live: Default::default(),
ps_masks: Default::default(),
mask_batch_end: Default::default(),
uniform_reads: Default::default(),
waterfall_ssamp: Default::default(),
pending_masks: Vec::new(),
guard_override: None,
Expand Down Expand Up @@ -879,7 +893,7 @@ impl Lw {
return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}"));
}
}
Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect(), dispatch_chain })
Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect(), dispatch_chain, exchange_sites: self.exchange_sites })
}
}

Expand Down
3 changes: 3 additions & 0 deletions crates/xcl/src/gpu/dxil/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,7 @@ impl Lw {
Partner::Spin => return self.exchange_spin(vals),
Partner::Missing => return vals.iter().map(|_| self.c(0)).collect(),
}
self.exchange_sites += 1;
let (xs, base) = self.xs_storage();
let slot = self.xslot;
assert!(vals.len() as u32 <= slot, "exchange of {} words, slot {slot}", vals.len());
Expand Down Expand Up @@ -452,6 +453,7 @@ impl Lw {
/// pairs (per lane allowed), then reads the partner's slot at `loads`.
fn spin_exchange(&mut self, stores: &[(Value, Value)], loads: &[Value]) -> Vec<Value> {
use super::lower::{VAR_XDEAD, VAR_XK};
self.exchange_sites += 1;
let (xs, base) = self.xs.expect("spin slots");
let (xc, cbase) = self.xc.expect("spin counters");
let slot = self.xslot;
Expand Down Expand Up @@ -770,6 +772,7 @@ impl Lw {
let z = self.c(0);
return self.sel(same, own, z);
}
self.exchange_sites += 1;
let (xs, base) = self.xs_storage();
let h = self.half;
let mine = self.shlc(h, 5);
Expand Down
3 changes: 3 additions & 0 deletions crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ pub struct Lw {
pub xw: Option<(super::ops::GroupShared, u32)>,
/// arrival counters of the spin exchange (two per console wave)
pub xc: Option<(super::ops::GroupShared, u32)>,
pub exchange_sites: u32,
/// hardware waves of a compute or mesh thread group (None: another kind of entry), as the
/// HLSL emitter's `compute_or_mesh_hw_waves`
pub barrier_waves: Option<u32>,
Expand Down Expand Up @@ -343,6 +344,8 @@ pub struct Lw {
/// split form: SGPRs whole-live after each instruction (`recomp::x64_masks::by_pc`)
pub whole_live: std::collections::BTreeMap<u64, u128>,
pub(super) mask_batch_end: std::collections::BTreeMap<u64, bool>,
/// split form: `v_readfirstlane`s of a value every lane of EXEC holds (`idioms`)
pub(super) uniform_reads: std::collections::BTreeSet<u64>,
pub(super) waterfall_ssamp: std::collections::BTreeMap<u64, u64>,
pub(super) pending_masks: Vec<(Dst, Value)>,
/// pixel shaders: compares whose mask needs less than the per-quad form (`recomp::ps_masks`)
Expand Down
8 changes: 6 additions & 2 deletions crates/xcl/src/gpu/dxil/lower_valu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1054,8 +1054,12 @@ impl Lw {
}
"v_readfirstlane_b32" => {
let (el, eh) = self.exec_mask();
let l = self.first_lane(el, eh);
let t = self.read_lane_uniform(a, l);
let t = if self.uniform_reads.contains(&d.pc) {
self.read_first_lane_uniform(a, el, eh)?
} else {
let l = self.first_lane(el, eh);
self.read_lane_uniform(a, l)
};
self.write32(&dst, t);
return Ok(());
}
Expand Down
54 changes: 37 additions & 17 deletions crates/xcl/src/gpu/dxil/mask_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,38 +7,39 @@ use std::collections::BTreeMap;
use super::cfg::{Cfg, Term};
use crate::gpu::{rdna2::{self, Decoded, Variant}, recomp::x64_masks};

const EXEC: u128 = 3 << 126;
const SCC: u128 = 1 << 125; // NULL in the ISA operands, SCC in the lowering
pub(super) const EXEC: u128 = 3 << 126;
pub(super) const SCC: u128 = 1 << 125; // NULL in the ISA operands, SCC in the lowering
const VCC: u128 = 3 << 106;

#[derive(Default)]
pub(super) struct Plan {
pub demand: BTreeMap<u64, u128>,
// A member queues its ballot word. The last member exchanges and writes all destinations.
pub batch_end: BTreeMap<u64, bool>,
pub uniform_reads: std::collections::BTreeSet<u64>,
pub words: u32,
}

#[derive(Clone, Copy)]
struct Uses {
read: u128,
written: u128,
#[derive(Clone, Copy, Default)]
pub(super) struct Uses {
pub read: u128,
pub written: u128,
// Transfer inputs whose whole value is required only when these outputs are observed.
if_live: u128,
inputs: u128,
save: u128,
pub if_live: u128,
pub inputs: u128,
pub save: u128,
}

impl Uses {
fn before(self, live: u128) -> u128 {
pub(super) fn before(self, live: u128) -> u128 {
let mut before = self.read | (live & !self.written);
if live & self.if_live != 0 { before |= self.inputs; }
if live & self.save != 0 { before |= EXEC; }
before
}
}

fn uses(d: &Decoded) -> Uses {
pub(super) fn uses(d: &Decoded) -> Uses {
let (mut read, regs) = x64_masks::uses(d);
// A multiword SGPR destination can span NULL (125). write64 skips that
// dword. Only a real SCC definition may kill demand for SCC here.
Expand All @@ -49,7 +50,7 @@ fn uses(d: &Decoded) -> Uses {
let opaque = || Uses { read: !0, written: 0, if_live: 0, inputs: 0, save: 0 };
if name.contains("MOVREL") || name.contains("SETREG") || name.contains("WREXEC")
|| (name.contains("SAVEEXEC") && name != "S_AND_SAVEEXEC_B64")
|| name.starts_with("DS_") || d.enc.name == "ENC_SOPK" {
|| name.starts_with("DS_") || (d.enc.name == "ENC_SOPK" && !super::idioms::plain_sopk(name)) {
return opaque();
}
let field = |f| rdna2::field_value(d.enc, &d.words, f);
Expand All @@ -61,7 +62,7 @@ fn uses(d: &Decoded) -> Uses {
if o.ty == "OPR_SSRC_SPECIAL_SCC" {
if o.input { read |= SCC; }
// Only kill SCC for operations whose lowering unconditionally sets it.
if o.output && (name.starts_with("S_CMP_") || matches!(name, "S_AND_SAVEEXEC_B64"
if o.output && (name.starts_with("S_CMP_") || name.starts_with("S_CMPK_") || matches!(name, "S_ADDK_I32" | "S_AND_SAVEEXEC_B64"
| "S_AND_B64" | "S_OR_B64" | "S_XOR_B64" | "S_ANDN2_B64" | "S_ORN2_B64" | "S_NAND_B64"
| "S_NOR_B64" | "S_XNOR_B64" | "S_NOT_B64" | "S_AND_B32"
| "S_XOR_B32" | "S_ADD_I32" | "S_SUB_I32" | "S_ADD_U32" | "S_ADDC_U32"
Expand Down Expand Up @@ -101,15 +102,15 @@ fn uses(d: &Decoded) -> Uses {
u
}

fn cmp_dst(d: &Decoded, u: Uses) -> Option<u128> {
pub(super) fn cmp_dst(d: &Decoded, u: Uses) -> Option<u128> {
if d.inst.name.starts_with("V_CMPX_") && d.variant == Variant::Plain && u.written == EXEC { return Some(EXEC); }
let r = u.written.trailing_zeros();
(d.inst.name.starts_with("V_CMP_") && d.variant == Variant::Plain &&
r <= 122 && r % 2 == 0 && u.written == 3u128 << r).then_some(u.written)
}

pub(super) fn plan(cfg: &Cfg) -> Plan {
let info: Vec<_> = cfg.insts.iter().map(uses).collect();
/// Whole demand at each block's entry and after each instruction.
pub(super) fn demand(cfg: &Cfg, info: &[Uses]) -> (Vec<u128>, Vec<u128>) {
let mut entry = vec![0; cfg.blocks.len()];
let mut after = vec![0; cfg.insts.len()];
loop {
Expand All @@ -132,7 +133,13 @@ pub(super) fn plan(cfg: &Cfg) -> Plan {
}
if !changed { break; }
}
let mut p = Plan::default();
(entry, after)
}

pub(super) fn plan(cfg: &Cfg) -> Plan {
let mut info: Vec<_> = cfg.insts.iter().map(uses).collect();
let after = super::idioms::local_votes(cfg, &mut info);
let mut p = Plan { uniform_reads: super::idioms::uniform_reads(cfg), ..Default::default() };
for &b in &cfg.rpo {
let mut group = Vec::with_capacity(3);
let (mut read, mut written) = (0, 0);
Expand Down Expand Up @@ -208,6 +215,19 @@ mod tests {
assert_ne!(plan(&program(&across_null)).demand[&0], 0);
}

#[test]
fn split_wave64_scalar_constant_compares_replace_scc() {
for k in ["S_CMPK_EQ_I32", "S_ADDK_I32"] {
let body = [
cmp(106, 130), saveexec(4, 106),
ins(k, "ENC_SOPK", &[("SDST", 8), ("SIMM16", 7)]),
ins("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]),
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 170)]),
];
assert_eq!(plan(&program(&body)).demand[&0], 0, "{k}");
}
}

#[test]
fn split_wave64_compare_batch_requires_independent_operands_and_one_block() {
let mut body = vec![cmp(2, 128), cmp(4, 132), cmp(6, 160), scalar(10, 2), scalar(10, 4), scalar(10, 7)];
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/gpu/dxil/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod coverage;
pub mod graphics;
pub mod kernel;
mod lanes;
mod idioms;
mod mask_exchange;
pub mod lower;
mod lower_geom;
Expand Down
10 changes: 9 additions & 1 deletion crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn semantic_pipeline_setting(name: &str) -> bool {
"XCL_HEAP_WINDOWS" | "XCL_LDS_TOP" | "XCL_LINK_MEM" | "XCL_MEM_ACCESSORS" |
"XCL_MW" | "XCL_PAGE_ALIAS" | "XCL_PER_LANE" | "XCL_PIXEL" |
"XCL_RECOMP_DXIL" | "XCL_RECOMP_NO_STRUCTURED" | "XCL_SAFE_BARRIER" |
"XCL_SPLIT_WAVE64" | "XCL_WAVE64_SPIN" | "XCL_WT" | "XCL_X64_ALL_MASKS" |
"XCL_SPLIT_WAVE64" | "XCL_WAVE64_IDIOMS" | "XCL_WAVE64_SPIN" | "XCL_WT" | "XCL_X64_ALL_MASKS" |
"XCL_XC" | "XCL_XS" | "XCL_XW" | "XCL_X_FAIL" | "XCL_X_LDS_ORDER" |
"XCL_X_LDS_TOP" | "XCL_X_SLOT" | "XCL_X_SPIN" | "XCL_X_THREADS" | "XCL_X_WAVES")
}
Expand Down Expand Up @@ -140,6 +140,14 @@ fn warm_settings_ignore_waits_watchdogs_and_traces_but_keep_pipeline_switches()
assert_eq!(plain, key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_TRACEX", "1")]), "unknown diagnostics stay cache-neutral until reviewed");
}

#[cfg(test)]
#[test]
fn warm_settings_keep_the_wave64_idioms_switch_on_both_backends() {
let key = |entries: &[(&str, &str)]| warm_settings(entries.iter().map(|(k, v)| ((*k).into(), (*v).into())));
assert_ne!(key(&[]), key(&[("XCL_WAVE64_IDIOMS", "0")]));
assert_ne!(key(&[("XCL_DIRECT_DXIL", "1")]), key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_WAVE64_IDIOMS", "0")]));
}

#[cfg(test)]
#[test]
fn warm_settings_are_canonical_and_only_hash_semantic_switches() {
Expand Down
55 changes: 55 additions & 0 deletions docs/wave64-on-wave32.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,61 @@ has no liveness pass: its masks are exchanged as before, except those two kinds
destination, 0 in every lane), which are the same in both halves either way.
`XCL_X64_ALL_MASKS=1` exchanges every mask (for comparison).

### Idioms

Sequences around a whole-wave value that are exact without its exchange (`gpu/dxil/idioms.rs`,
the direct translator's compute and mesh programs without LDS; `XCL_WAVE64_IDIOMS=0` turns them
off, and is part of the translated cache's identity and the warm pipeline library's settings).

**A local vote.** `s_cbranch_execz` forward over lane work: the `if` of a shader
(`v_cmp`, `s_and_saveexec_b64`, `s_cbranch_execz`, the body, `s_or_b64 exec, exec, saved`). A
half with no lane in EXEC loses nothing by skipping the body whatever the other half does, so
the branch reads each half's own word and the compare stays in its half; the halves may take
different sides. It holds when, between the branch and its target,
- every instruction is per-lane work under EXEC, scalar arithmetic or a plain scalar load: no
`v_readlane` / `v_readfirstlane` / `v_writelane`, no `ds_*`, no coherent scalar load, no
`s_barrier`, nothing indirect or relative, and no mask that is itself exchanged (the halves
would meet out of step);
- branches go forward and stay inside, and none comes in from outside;
- EXEC stays within the EXEC at the branch on every path (`s_and_saveexec_b64`, `s_and_b64`,
`s_andn2_b64`, `s_or_b64` / `s_xor_b64` / `s_mov_b64` of pairs known to be within it, compares);
- no SGPR written there, SCC included, is read after the target, and EXEC is not read whole
at the target if it was written.

**The saved EXEC's return.** At the target of such a vote, `s_or_b64 exec, exec, s` with `s`
the EXEC that `s_and_saveexec_b64` saved right before the branch gives `s`: EXEC there is
within it. A whole read of EXEC after the `if` then asks for `s` and not for the compare.

**A uniform first lane.** `v_readfirstlane` of a value every lane of EXEC holds: the compiler's
scalar arithmetic that has no scalar instruction (float conversion, reciprocal, a 0 / 1 from a
scalar condition), done in a VGPR and read back. When both halves have a running lane in EXEC
each reads its own first one, the same value; when one has none the halves exchange as before
(EXEC is still read whole, so both know). A value is known to be in every lane of EXEC when,
in its block and after the last write of EXEC, it came from plain VALU instructions whose
operands (an accumulator's or a 16-bit result's destination included) are scalars or such
values again, and whose lane masks (`v_cndmask_b32`'s, a carry in, `v_div_fmas_f32`'s VCC)
have one bit for all of EXEC's lanes (`s_cselect_b64` of EXEC and constants, bitwise 64-bit
operations and compares of such operands). Not a lane's rank or index (`v_mbcnt`), a
cross-lane read, a carry out, an SDWA / DPP form, nor a memory load: another wave may write
that memory between the halves' loads.

**A scalar constant.** `s_movk_i32`, `s_cmovk_i32`, `s_addk_i32`, `s_mulk_i32` and `s_cmpk_*`
read and write the registers they name, and `s_waitcnt_*cnt` and `s_version` none; the mask
demand took every SOPK instruction for one that may read any register, so a compare before any
of them was exchanged.

On a retail pack's 9 442 distinct wave64 compute and mesh programs without LDS
(`retail_wave64_compute_exchange_census`, ignored, `XCL_SAMPLE_RPF`): 157 393 exchanged compares
without the idioms, 114 214 with the votes, 90 743 with the constants too; 38 702 of 57 884
`v_readfirstlane` are uniform. Of the compares still exchanged, 66 037 are read by an
`s_cbranch_execz` whose side is more than lane work (an export count, another lane's value, a
scalar read later) or holds such a vote.

The decision is made with the mask demand (`mask_exchange.rs`): the votes are assumed local,
and one whose side turns out to exchange a compare, or to be followed by a whole read of the
EXEC it wrote, is taken back until nothing changes. `Kernel::exchange_sites` counts the places
where the halves meet in a translation.

## Cost

A wave64 program pays one exchange per mask write that is read whole (`v_cmp*` feeding
Expand Down
Loading