diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 776c185fe..9bf4ed08f 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2263; +pub const SEMANTICS_VERSION: u32 = 2264; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs b/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs index 9f660171e..e060026c6 100644 --- a/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs +++ b/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs @@ -85,6 +85,9 @@ pub(super) fn emit( m.weighted(crate::pipeline::compile::weights::HOIST, |m| { crate::spirv::hoist::hoist_uniform_loads(&mut emitted.module, p.robustness(), m) })?; + // A structurizer variable whose value no later trip of a loop reads is ended at each + // trip's top, so the driver carries none of it around the loop. + crate::spirv::carry::end_dead_carries(&mut emitted.module, m)?; let weight = crate::spirv::roll::entry_weight(&emitted.module, m)?; if weight <= bounds.compiled || widest == WidestPin::Kept || !plan.families.simd.widest_pin { diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index ca2fe4ec4..5675d9b99 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -414,6 +414,7 @@ fn typed_module_of( crate::lower::emit::emit_module(&spec, &plan, m)?; crate::spirv::roll::roll_entry(&mut module, m)?; crate::spirv::hoist::hoist_uniform_loads(&mut module, p.robustness(), m)?; + crate::spirv::carry::end_dead_carries(&mut module, m)?; crate::spirv::verify::verify(&module, p, m)?; Ok((plan, module)) } diff --git a/crates/metal2vulkan/src/spirv/builder/function.rs b/crates/metal2vulkan/src/spirv/builder/function.rs index 3bfa08ef8..455c33a57 100644 --- a/crates/metal2vulkan/src/spirv/builder/function.rs +++ b/crates/metal2vulkan/src/spirv/builder/function.rs @@ -344,11 +344,24 @@ impl<'m> FunctionBuilder<'m> { ptr_ty, value, init, + trip_local: false, }); self.draft_mut()?.vars.push(id); Ok(id) } + /// Mark `Function` variable `var` of this function [`LocalVar::trip_local`]: no trip of a + /// loop whose body holds all of its whole stores reads the value an earlier trip left in it. + pub fn mark_trip_local(&mut self, var: VarId) -> BResult<()> { + match self.m.vars.get_mut(var.index()) { + Some(v) if v.func == self.func => { + v.trip_local = true; + Ok(()) + } + Some(_) | None => Err(BuildError::Dangling(Dangling::Var(var))), + } + } + /// The pointer value of a `Function` variable of this function. pub fn var_ptr(&self, var: VarId) -> BResult { match self.m.vars.get(var.index()) { diff --git a/crates/metal2vulkan/src/spirv/carry.rs b/crates/metal2vulkan/src/spirv/carry.rs new file mode 100644 index 000000000..f3f6b2fc7 --- /dev/null +++ b/crates/metal2vulkan/src/spirv/carry.rs @@ -0,0 +1,461 @@ +//! Stores of an undefined value at the top of each loop trip, which end the structurizer variables +//! whose values no later trip reads. +//! +//! P4 gives every block-crossing value and every phi of the source a `Function` variable +//! (`structurize::demote`): a demoted value's variable is stored where the value is defined, a +//! phi's at the end of each block that enters the phi. P5 to P7 add exit dispatches and pending +//! guards, whose paths lead from a loop's back edge to a read of such a variable (after the loop, +//! or later in its body) without passing its store. No execution takes such a path to read the +//! value an earlier trip left, but a driver's compiler cannot know that: it keeps the variable's +//! value around the back edge, a phi at the loop's header live through the whole loop. +//! +//! Where a loop's body holds every store of such a variable, no trip reads the value an earlier +//! trip left in it. In the source, the value's definition dominates each of its uses and the +//! loop's header dominates the definition, so every path from the header to a use passes the +//! definition again; a phi's variable is read only at its block, which is entered from one of the +//! blocks that store it. [`end_dead_carries`] stores an undefined value into the variable at the +//! top of each trip, so the driver keeps nothing of it around the back edge. +//! +//! The variables it ends are the ones P8 marks [`LocalVar::trip_local`]: the demoted values' and +//! the phis' of a walk that is not predicated. The predicated walk runs a loop while any +//! invocation of the workgroup is live in it, so an invocation that has left the loop still runs +//! the next trip's top, where such a store would end the value it reads after the loop. +//! +//! A store is written for a marked variable `v` of a function and a loop of it when all of the +//! following hold, read from the function's blocks, their merges and terminators, and the accesses +//! of `v`: +//! +//! - **The loop's body holds every whole store of `v`.** The body is the header and the blocks +//! that reach its continue target without passing the header. A whole store is an `OpStore` +//! through `v`'s own pointer, or `v`'s initializer, which counts as a store in the function's +//! first block. +//! - **`v` is live into the body's first block**, the block the header branches to (the header +//! holds only its merge and its branch): a read of `v` is reachable from the block's top before +//! a whole store. A read is a load through `v` or a pointer into it, a store of such a pointer, +//! or any other instruction that takes one. +//! - **The first block does not read `v` before it stores it.** +//! +//! The stores go at the top of the first block: variable after variable in the function's order +//! of variables, and each variable's loops in the function's block order. In one block, a store +//! written later stands before the earlier ones. + +use std::collections::BTreeMap; + +use crate::budget::Meter; +use crate::error::{Error, InternalError, InternalKind}; +use crate::spirv::ids::{BlockId, FuncId, TypeId, Value}; +use crate::spirv::ir::{ + Block, Function, Inst, InstNode, LocalVar, MemAccess, Merge, Terminator, TypedModule, ValueDef, + ValueOrigin, +}; + +/// No block, or no variable: the sentinel of the per-block tables. +const NONE: u32 = u32::MAX; + +/// The bytes one entry of a `BTreeMap` is charged. +const MAP_ENTRY: usize = 32; + +fn invariant(detail: impl Into) -> Error { + Error::Internal(InternalError::new(InternalKind::Invariant, detail)) +} + +/// Write the stores of the module docs into every function of `m` that has a marked variable. +/// Returns the stores written. +pub fn end_dead_carries(m: &mut TypedModule, meter: &mut Meter) -> Result { + let mut written = 0u32; + for f in 0..m.functions.len() { + let f = FuncId::new(u32::try_from(f).map_err(|_| invariant("function ids"))?); + let ends = ends(m, f, meter)?; + // The module keeps what it gains: two instructions and a value for each store. + let bytes = ends + .len() + .saturating_mul(2 * std::mem::size_of::() + std::mem::size_of::()); + meter.charge(bytes)?; + for (ptr, ty, first) in ends { + let undef = + Value::new(u32::try_from(m.values.len()).map_err(|_| invariant("value ids"))?); + m.values.push(ValueDef { + ty, + origin: ValueOrigin::Inst(first), + }); + let block = m + .blocks + .get_mut(first.index()) + .ok_or_else(|| invariant("a loop's first block"))?; + block.insts.insert( + 0, + InstNode { + result: None, + inst: Inst::Store { + ptr, + value: undef, + access: MemAccess::default(), + }, + }, + ); + block.insts.insert( + 0, + InstNode { + result: Some(undef), + inst: Inst::Undef, + }, + ); + written = written.saturating_add(1); + } + } + Ok(written) +} + +/// The number of (variable, loop) pairs of `m` that the rule of the module docs selects: each a +/// marked variable whose value the driver would keep around the loop's back edge though no trip +/// reads it. None is left once [`end_dead_carries`] has run. +#[cfg(test)] +pub(crate) fn dead_carries(m: &TypedModule) -> usize { + let mut meter = Meter::new(&crate::budget::Budget::standard()); + (0..m.functions.len()) + .map(|f| { + let f = FuncId::new(u32::try_from(f).expect("function ids")); + ends(m, f, &mut meter).expect("dead carries").len() + }) + .sum() +} + +/// The stores function `f` of `m` takes, in the order the module docs give: for each, the +/// variable's pointer, its pointee and the loop's first block. +fn ends( + m: &TypedModule, + f: FuncId, + meter: &mut Meter, +) -> Result, Error> { + let func = m + .functions + .get(f.index()) + .ok_or_else(|| invariant("function"))?; + let marked: Vec<&LocalVar> = func + .vars + .iter() + .filter_map(|v| m.vars.get(v.index())) + .filter(|v| v.trip_local) + .collect(); + if marked.is_empty() { + return Ok(Vec::new()); + } + let mut held = 0usize; + let r = select(m, func, &marked, meter, &mut held); + meter.release(held); + r +} + +/// Charge `bytes` to `meter`, held until [`ends`] returns. +fn hold(meter: &mut Meter, held: &mut usize, bytes: usize) -> Result<(), Error> { + meter.charge(bytes)?; + *held = held.saturating_add(bytes); + Ok(()) +} + +fn tick(meter: &mut Meter, units: usize) -> Result<(), Error> { + meter.tick(u32::try_from(units).unwrap_or(u32::MAX)) +} + +/// What one marked variable does in one block: its first access there is a read (else a whole +/// store). +#[derive(Clone, Copy)] +struct Event { + block: u32, + read_first: bool, +} + +/// One marked variable's accesses, in block order. +#[derive(Default)] +struct Accesses { + /// Each block that reads or wholly stores the variable, once. + events: Vec, + /// Each block that wholly stores it, once. + stores: Vec, +} + +impl Accesses { + fn note(&mut self, block: u32, read: bool) { + if self.events.last().map(|e| e.block) != Some(block) { + self.events.push(Event { + block, + read_first: read, + }); + } + if !read && self.stores.last() != Some(&block) { + self.stores.push(block); + } + } +} + +fn block_of<'m>(m: &'m TypedModule, func: &Function, i: usize) -> Result<&'m Block, Error> { + func.blocks + .get(i) + .and_then(|b| m.blocks.get(b.index())) + .ok_or_else(|| invariant("block")) +} + +/// [`ends`]'s selection over `func`'s blocks for its marked variables `marked`. +fn select( + m: &TypedModule, + func: &Function, + marked: &[&LocalVar], + meter: &mut Meter, + held: &mut usize, +) -> Result, Error> { + let n = func.blocks.len(); + if u32::try_from(n).is_err() { + return Err(invariant("block count")); + } + let u32_of = |i: usize| u32::try_from(i).unwrap_or(NONE); + // What the tables below hold, charged before they are built. + let (mut edges, mut insts, mut chains) = (0usize, 0usize, 0usize); + for i in 0..n { + let b = block_of(m, func, i)?; + b.term.for_each_target(|_| edges += 1); + insts += b.insts.len(); + chains += b + .insts + .iter() + .filter(|node| matches!(node.inst, Inst::AccessChain { .. })) + .count(); + } + tick(meter, n.saturating_add(insts))?; + let vec = std::mem::size_of::>(); + let bytes = m + .blocks + .len() + .saturating_mul(4) + .saturating_add(n.saturating_mul(1 + 3 * 4 + 2 * vec)) + .saturating_add(edges.saturating_mul(2 * 4)) + .saturating_add(insts.saturating_mul(std::mem::size_of::() + 4)) + .saturating_add(chains.saturating_mul(2 * std::mem::size_of::() + MAP_ENTRY)) + .saturating_add(marked.len().saturating_mul(MAP_ENTRY + 2 * vec)); + hold(meter, held, bytes)?; + + // Local block numbers, in layout order. + let mut local = vec![NONE; m.blocks.len()]; + for (i, b) in func.blocks.iter().enumerate() { + if let Some(x) = local.get_mut(b.index()) { + *x = u32_of(i); + } + } + let at = |b: BlockId| { + local + .get(b.index()) + .copied() + .filter(|&x| x != NONE) + .map(|x| x as usize) + }; + // The blocks reachable from the first, and each one's reachable predecessors. + let mut reach = vec![false; n]; + let mut stack: Vec = Vec::new(); + if n > 0 { + stack.push(0); + } + while let Some(i) = stack.pop() { + match reach.get_mut(i) { + Some(r) if !*r => *r = true, + _ => continue, + } + block_of(m, func, i)?.term.for_each_target(|t| { + if let Some(j) = at(t) { + stack.push(j); + } + }); + } + let reached = |i: usize| reach.get(i).copied().unwrap_or(false); + let mut preds: Vec> = vec![Vec::new(); n]; + for i in (0..n).filter(|&i| reached(i)) { + block_of(m, func, i)?.term.for_each_target(|t| { + if let Some(p) = at(t).and_then(|j| preds.get_mut(j)) { + p.push(u32_of(i)); + } + }); + } + let preds_of = |i: usize| preds.get(i).map_or(&[][..], Vec::as_slice); + + // The loops, by header in layout order: each one's first block and the loops each block is in. + let mut firsts: Vec = Vec::new(); + let mut loops_of: Vec> = vec![Vec::new(); n]; + let mut seen = vec![NONE; n]; + for i in (0..n).filter(|&i| reached(i)) { + let b = block_of(m, func, i)?; + let Some(Merge::Loop { cont, .. }) = b.merge else { + continue; + }; + let (Some(c), Terminator::Branch(first)) = (at(cont), &b.term) else { + continue; + }; + let Some(first) = at(*first) else { + continue; + }; + if !reached(c) { + continue; + } + let l = u32_of(firsts.len()); + let mut body = vec![i]; + if let Some(s) = seen.get_mut(i) { + *s = l; + } + stack.clear(); + stack.push(c); + while let Some(x) = stack.pop() { + match seen.get_mut(x) { + Some(s) if *s != l => *s = l, + _ => continue, + } + body.push(x); + let p = preds_of(x); + tick(meter, 1 + p.len())?; + stack.extend(p.iter().map(|&p| p as usize)); + } + hold(meter, held, body.len().saturating_mul(4))?; + for x in body { + if let Some(of) = loops_of.get_mut(x) { + of.push(l); + } + } + firsts.push(first); + } + if firsts.is_empty() { + return Ok(Vec::new()); + } + let in_loop = |b: u32, l: u32| { + loops_of + .get(b as usize) + .is_some_and(|of| of.binary_search(&l).is_ok()) + }; + + // The marked variables' pointers and the pointers into them. + let mut root: BTreeMap = marked + .iter() + .enumerate() + .map(|(k, v)| (v.value, u32_of(k))) + .collect(); + let chain_list: Vec<(Value, Value)> = func + .blocks + .iter() + .filter_map(|b| m.blocks.get(b.index())) + .flat_map(|b| b.insts.iter()) + .filter_map(|node| match (&node.inst, node.result) { + (Inst::AccessChain { base, .. }, Some(r)) => Some((*base, r)), + _ => None, + }) + .collect(); + loop { + let before = root.len(); + tick(meter, chain_list.len())?; + for (base, r) in &chain_list { + if let Some(&k) = root.get(base) { + root.insert(*r, k); + } + } + if root.len() == before { + break; + } + } + + // Each marked variable's reads and whole stores, block by block. + let mut acc: Vec = marked + .iter() + .map(|v| { + let mut a = Accesses::default(); + if v.init.is_some() { + a.note(0, false); + } + a + }) + .collect(); + for i in (0..n).filter(|&i| reached(i)) { + let bi = u32_of(i); + let mut note = |k: u32, read: bool| { + if let Some(a) = acc.get_mut(k as usize) { + a.note(bi, read); + } + }; + for node in &block_of(m, func, i)?.insts { + match &node.inst { + Inst::Load { ptr, .. } => { + if let Some(&k) = root.get(ptr) { + note(k, true); + } + } + Inst::Store { ptr, value, .. } => { + if let Some(&k) = root.get(value) { + note(k, true); + } + if let Some(&k) = root.get(ptr) { + if marked.get(k as usize).is_some_and(|v| v.value == *ptr) { + note(k, false); + } + } + } + Inst::AccessChain { .. } => {} + other => other.for_each_value(|v| { + if let Some(&k) = root.get(&v) { + note(k, true); + } + }), + } + } + } + + // Each variable's live blocks, and the loops it is ended at. + let mut live = vec![NONE; n]; + let mut kills = vec![NONE; n]; + let mut reads = vec![NONE; n]; + let stamped = |table: &[u32], b: usize, k: u32| table.get(b) == Some(&k); + let mut out = Vec::new(); + for (k, (v, a)) in marked.iter().zip(&acc).enumerate() { + let Some(&s0) = a.stores.first() else { + continue; + }; + let k = u32_of(k); + stack.clear(); + for e in &a.events { + let b = e.block as usize; + let table = if e.read_first { &mut reads } else { &mut kills }; + if let Some(x) = table.get_mut(b) { + *x = k; + } + if e.read_first && reached(b) { + if let Some(x) = live.get_mut(b) { + *x = k; + } + stack.push(b); + } + } + while let Some(b) = stack.pop() { + let p = preds_of(b); + tick(meter, 1 + p.len())?; + for &p in p { + let p = p as usize; + if stamped(&live, p, k) || stamped(&kills, p, k) { + continue; + } + if let Some(x) = live.get_mut(p) { + *x = k; + } + stack.push(p); + } + } + for &l in loops_of.get(s0 as usize).map_or(&[][..], Vec::as_slice) { + let Some(&first) = firsts.get(l as usize) else { + continue; + }; + if a.stores.iter().all(|&s| in_loop(s, l)) + && stamped(&live, first, k) + && !stamped(&reads, first, k) + { + let b = func + .blocks + .get(first) + .copied() + .ok_or_else(|| invariant("block"))?; + out.push((v.value, v.pointee, b)); + } + } + } + Ok(out) +} diff --git a/crates/metal2vulkan/src/spirv/ir/module.rs b/crates/metal2vulkan/src/spirv/ir/module.rs index 5e49e81b4..b0ef532a9 100644 --- a/crates/metal2vulkan/src/spirv/ir/module.rs +++ b/crates/metal2vulkan/src/spirv/ir/module.rs @@ -139,6 +139,11 @@ pub struct LocalVar { pub ptr_ty: TypeId, pub value: Value, pub init: Option, + /// Whether no trip of a loop whose body holds every whole store of the variable reads the + /// value an earlier trip left in it: a demoted value's or a phi's variable of a walk that is + /// not predicated, which P8 marks. [`crate::spirv::carry`] ends such a value at each trip's + /// top. + pub trip_local: bool, } /// One member of the push-constant block, placed by `select`. @@ -1160,6 +1165,29 @@ impl Terminator { } } + /// Call `f` on every block the terminator may branch to, in operand order. + pub fn for_each_target(&self, mut f: impl FnMut(BlockId)) { + match self { + Terminator::Branch(t) => f(*t), + Terminator::CondBranch { t, f: e, .. } => { + f(*t); + f(*e); + } + Terminator::Switch { default, cases, .. } => { + f(*default); + for (_, c) in cases { + f(*c); + } + } + Terminator::Return + | Terminator::ReturnValue(_) + | Terminator::Kill + | Terminator::TerminateInvocation + | Terminator::Unreachable + | Terminator::EmitMeshTasks { .. } => {} + } + } + /// Call `f` on every block the terminator may branch to, in operand order. pub fn for_each_target_mut(&mut self, mut f: impl FnMut(&mut BlockId)) { match self { diff --git a/crates/metal2vulkan/src/spirv/mod.rs b/crates/metal2vulkan/src/spirv/mod.rs index 2ce2592cc..8bb0f8f56 100644 --- a/crates/metal2vulkan/src/spirv/mod.rs +++ b/crates/metal2vulkan/src/spirv/mod.rs @@ -5,6 +5,7 @@ #![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::indexing_slicing))] pub mod builder; +pub mod carry; pub mod dead; pub mod error; pub mod half_hold; diff --git a/crates/metal2vulkan/src/spirv/roll/mod.rs b/crates/metal2vulkan/src/spirv/roll/mod.rs index 315aa43f3..06c42e37b 100644 --- a/crates/metal2vulkan/src/spirv/roll/mod.rs +++ b/crates/metal2vulkan/src/spirv/roll/mod.rs @@ -2225,6 +2225,7 @@ fn local(m: &mut TypedModule, entry: FuncId, pointee: TypeId) -> Result Result { check_tree(s, meter)?; let vars = allocate(s, fb, c)?; + // A walk that is not predicated runs each invocation's trips of a loop as the source does, so + // no trip reads a value an earlier one left in a demoted value's or a phi's variable where + // the loop holds all of its stores (`spirv::carry`). The predicated walk runs a trip for an + // invocation that has left the loop, which reads such a value after it. + if !c.predicated() { + for (_, v) in vars.demoted.iter().chain(&vars.phis) { + fb.mark_trip_local(*v)?; + } + } c.bind(&vars)?; let u32_ty = u32_type(fb.module())?; // The builder's growth during this walk is charged after each block's code and returned when diff --git a/crates/metal2vulkan/src/tests/engine_divergent_barriers.rs b/crates/metal2vulkan/src/tests/engine_divergent_barriers.rs index a149b7e65..86d7272c0 100644 --- a/crates/metal2vulkan/src/tests/engine_divergent_barriers.rs +++ b/crates/metal2vulkan/src/tests/engine_divergent_barriers.rs @@ -13,7 +13,9 @@ //! barrier rule (`BarrierRule::Vulkan`: a returned invocation while others wait at a barrier //! traps), in both scheduling orders, at several threadgroup sizes and subgroup widths, giving //! the words the predicated reading predicts. A kernel whose barriers are all uniform is not -//! predicated. No GPU is used. +//! predicated. An invocation that leaves a predicated loop before the others keeps the value it +//! reads after the loop: the walk runs the loop's later trips for it too, so `spirv::carry` ends +//! no value at their tops. No GPU is used. //! //! `llvm-as` assembles the kernels; a missing tool skips visibly. @@ -61,7 +63,7 @@ fn assemble_file(path: &std::path::Path, what: &str) -> Option> { /// `body` (the kernel `name`'s definition, parameters `%limits`, `%out`, `%t`) in a module with /// the threadgroup arrays `@a` and `@b`, the barrier and simd declarations, and the kernel's AIR /// metadata, assembled. -fn kernel(name: &str, body: &str) -> Option> { +pub(super) fn kernel(name: &str, body: &str) -> Option> { let text = format!( r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" target triple = "air64_v28-apple-macosx26.0.0" @@ -219,6 +221,36 @@ done: store i32 %r, ptr addrspace(1) %po, align 4 ret void"#; +/// `i = 0; do { a[t] = 16t + i; barrier; x = a[t ^ 4]; barrier; v = (x + i) | 1 << 31; i++; } +/// while (i <= (t & 3)); out[t] = v;`: a loop with a per-thread trip count whose last trip's value +/// is read after it. Thread `t` leaves the loop after `(t & 3) + 1` trips and the walk runs the +/// other trips for it, not live; it reads `v` of its own last trip. +const LOOP_LEAVER: &str = r#"entry: + %k = and i32 %t, 3 + %tz = zext i32 %t to i64 + %pa = getelementptr inbounds [128 x i32], ptr addrspace(3) @a, i64 0, i64 %tz + %p = xor i32 %t, 4 + %pz = zext i32 %p to i64 + %pp = getelementptr inbounds [128 x i32], ptr addrspace(3) @a, i64 0, i64 %pz + %w0 = shl i32 %t, 4 + br label %body +body: + %i = phi i32 [ 0, %entry ], [ %i1, %body ] + %w = add i32 %w0, %i + store i32 %w, ptr addrspace(3) %pa, align 4 + tail call void @air.wg.barrier(i32 2, i32 1) #1 + %x = load i32, ptr addrspace(3) %pp, align 4 + tail call void @air.wg.barrier(i32 2, i32 1) #1 + %v0 = add i32 %x, %i + %v = or i32 %v0, -2147483648 + %i1 = add i32 %i, 1 + %more = icmp ule i32 %i1, %k + br i1 %more, label %body, label %done +done: + %po = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %tz + store i32 %v, ptr addrspace(1) %po, align 4 + ret void"#; + /// `s = simd_sum(1); if (t < limits[0]) { a[t] = s + t; barrier; out[t] = a[(t + 1) % /// limits[0]]; } else out[t] = 0xE0000000 | t;`: a simdgroup operation every thread runs, then a /// threadgroup barrier under a thread-dependent condition (on an emulating profile the kernel's @@ -280,9 +312,9 @@ done: /// The threads of a threadgroup of `n`, and the limits each case passes. #[derive(Clone, Copy, Debug)] -struct Case { - n: u32, - limits: [u32; 2], +pub(super) struct Case { + pub(super) n: u32, + pub(super) limits: [u32; 2], } /// Thread `t`'s expected word of `kernel` in `c`, by the predicated reading: the threads that @@ -298,6 +330,7 @@ fn expected(kernel: &str, c: Case, t: u32) -> u32 { } } "loop_barrier_k" => (0..(t & 3)).map(|i| ((t ^ 4) << 4) + i).sum(), + "loop_leaver_k" => (((t ^ 4) << 4) + 2 * (t & 3)) | 1 << 31, "continue_barrier_k" => { if t & 3 == 3 { 0 @@ -345,7 +378,7 @@ fn cases(kernel: &str, tier: Tier) -> Vec { let limits: Vec<[u32; 2]> = match kernel { "continue_barrier_k" => vec![[0, 0], [1, 0], [3, 0]], "uniform_barriers_k" => vec![[0, n]], - "loop_barrier_k" => vec![[0, 0]], + "loop_barrier_k" | "loop_leaver_k" => vec![[0, 0]], "a3_early_return_barrier" => { vec![[n, n], [n - n / 4, n / 3 + 1], [n, 1], [n / 2 + 1, n / 2]] } @@ -370,7 +403,7 @@ fn words(b: &[u8]) -> Vec { /// The output words after one workgroup of `c.n` threads ran `m` (planned as `plan`) with /// `lanes`-wide subgroups under Vulkan's barrier rule, identical in both scheduling orders. -fn run_case(plan: &Plan, m: &TypedModule, c: Case, lanes: SubgroupSize) -> Vec { +pub(super) fn run_case(plan: &Plan, m: &TypedModule, c: Case, lanes: SubgroupSize) -> Vec { let mut spec = BTreeMap::new(); for (a, v) in [Axis::X, Axis::Y, Axis::Z].into_iter().zip([c.n, 1, 1]) { spec.insert(SpecKey::LocalSize(a), u64::from(v)); @@ -483,6 +516,18 @@ fn divergent_barriers_run_predicated_on_every_profile() { } } +/// A thread that leaves a predicated loop before the others reads the value of its own last trip +/// after the loop: no store at a later trip's top, which it runs not live, ends that value. +#[test] +fn a_thread_that_leaves_a_vote_loop_early_keeps_its_last_trips_value() { + let Some(bc) = kernel("loop_leaver_k", LOOP_LEAVER) else { + return; + }; + for stem in PROFILES { + check(stem, &bc, "loop_leaver_k", true); + } +} + /// The owned fixture: threads returning before the first and between the two barriers. #[test] fn early_returns_before_barriers_run_predicated_on_every_profile() { diff --git a/crates/metal2vulkan/src/tests/engine_trip_carries.rs b/crates/metal2vulkan/src/tests/engine_trip_carries.rs new file mode 100644 index 000000000..27e2434da --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_trip_carries.rs @@ -0,0 +1,136 @@ +//! A structurizer variable whose value no later trip reads is ended at each trip's top +//! (`spirv::carry`). +//! +//! The kernel below (inline AIR text, assembled by `llvm-as`) leaves its loop by three exits, and +//! the second one reads a value its trip defined. The exit dispatch after the loop reads that +//! value's variable in one arm, so a path from the loop's back edge reaches the read without +//! passing the store, and a driver would keep the variable around the loop. On every profile the +//! module ends the variable at the top of each trip, no variable is left that a later trip never +//! reads but the module keeps around a back edge, the module passes `spirv-val`, and it runs on +//! the CPU interpreter giving the words the source computes. No GPU is used. +//! +//! `llvm-as` assembles the kernel; a missing tool skips visibly. + +use std::collections::BTreeSet; + +use super::engine_divergent_barriers::{kernel, run_case, Case}; +use crate::device::DevicePolicy; +use crate::pipeline::testing::{compile, link_and_validate, profile, typed_module}; +use crate::spirv::carry::dead_carries; +use crate::spirv::interp::SubgroupSize; +use crate::spirv::ir::{Inst, TypedModule}; + +/// Profiles of every vendor, and the emulating ones. +const PROFILES: [&str; 6] = [ + "moltenvk-m3", + "intel-irisxe-rplp-anv", + "amd-rdna3-radv", + "nvidia-rtx50-linux", + "lavapipe", + "runtime-floor", +]; + +/// `for (i = 0; i < limits[0]; i++) { x = (7i + t) & 15; if (x == 3) { out[t] = 100i + x; +/// return; } if (x > 12) { out[t] = i + 50; return; } } out[t] = 999;`: `x` is defined after the +/// loop's first exit and read after the loop by its second. +const TRIP_EXITS: &str = r#"entry: + %n = load i32, ptr addrspace(1) %limits, align 4 + %tz = zext i32 %t to i64 + %po = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %tz + br label %header +header: + %i = phi i32 [ 0, %entry ], [ %i1, %latch ] + %more = icmp ult i32 %i, %n + br i1 %more, label %b1, label %none +b1: + %i7 = mul i32 %i, 7 + %s = add i32 %i7, %t + %x = and i32 %s, 15 + %hit = icmp eq i32 %x, 3 + br i1 %hit, label %found, label %b2 +b2: + %big = icmp ugt i32 %x, 12 + br i1 %big, label %large, label %latch +latch: + %i1 = add i32 %i, 1 + br label %header +found: + %ih = mul i32 %i, 100 + %r = add i32 %ih, %x + store i32 %r, ptr addrspace(1) %po, align 4 + br label %done +large: + %rl = add i32 %i, 50 + store i32 %rl, ptr addrspace(1) %po, align 4 + br label %done +none: + store i32 999, ptr addrspace(1) %po, align 4 + br label %done +done: + ret void"#; + +/// Thread `t`'s word for a trip bound of `n`, as the source computes it. +fn expected(n: u32, t: u32) -> u32 { + for i in 0..n { + let x = (7 * i + t) & 15; + if x == 3 { + return 100 * i + x; + } + if x > 12 { + return i + 50; + } + } + 999 +} + +/// The stores of an undefined value in `m`. +fn undefined_stores(m: &TypedModule) -> usize { + let insts = || m.blocks().iter().flat_map(|b| b.insts.iter()); + let undefs: BTreeSet<_> = insts() + .filter(|node| matches!(node.inst, Inst::Undef)) + .filter_map(|node| node.result) + .collect(); + insts() + .filter(|node| matches!(&node.inst, Inst::Store { value, .. } if undefs.contains(value))) + .count() +} + +/// The value the second exit reads is ended at each trip's top, and none is kept around the back +/// edge that no later trip reads; the kernel computes what its source does. +#[test] +fn a_value_no_later_trip_reads_is_ended_at_each_trips_top() { + let Some(bc) = kernel("trip_exits_k", TRIP_EXITS) else { + return; + }; + for stem in PROFILES { + let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile"); + let a = compile(&bc, "trip_exits_k", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + let (plan, m) = + typed_module(&bc, "trip_exits_k", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert!( + plan.families.simd.predication.is_none(), + "{stem}: the walk is not predicated" + ); + let ended = undefined_stores(&m); + eprintln!("{stem}: {ended} values ended at a trip's top"); + assert!(ended > 0, "{stem}: no value is ended at a trip's top"); + assert_eq!( + dead_carries(&m), + 0, + "{stem}: a value no later trip reads is kept around the loop" + ); + for n in [32, 64] { + for bound in [0, 1, 2, 5, 16] { + let c = Case { + n, + limits: [bound, 0], + }; + let out = run_case(&plan, &m, c, SubgroupSize::W32); + for (t, got) in out.iter().enumerate() { + assert_eq!(*got, expected(bound, t as u32), "{stem} {c:?} thread {t}"); + } + } + } + } +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 9a2a9d7c1..537d077e9 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -194,6 +194,7 @@ mod engine_texture_unk; mod engine_threadgroup_floats; mod engine_tile; mod engine_tiny_products; +mod engine_trip_carries; mod engine_typed_clamp; mod engine_typed_threadgroup; mod engine_uniform_varyings; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ab7bddbeb..5ce6e4066 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -23,10 +23,11 @@ metallib | AIR bitcode ── structurize ─► a structured tree over the AIR CFG structurize ── emit ────────► a typed SPIR-V module through the builder structurize::emit, lower::*, spirv::builder ── tidy ────────► single-store promotion, dead values removed, structurize::promote, spirv::{dead, roll, - half values held at 16 bits under the 16-bit float hoist, half_hold} + half values held at 16 bits under the 16-bit float hoist, carry, half_hold} controls, repeated regions of large entries rolled into loops, loop-invariant loads of uniform views - moved before their loops + moved before their loops, structurizer variables + no later trip reads ended at each loop trip's top ── verify ──────► the full verifier; requirements within the profile spirv::verify, spirv::requirements ── serialize ───► SPIR-V 1.5 words with typed relocations, held to spirv::serialize the word cap @@ -75,7 +76,7 @@ rest is `crates/metal2vulkan/src/`. | `memory/` | Pointer provenance, the `MemoryPlan`, leaf access emitters, arenas, root and handle lookups, word composition, atomics; `memory::views`, a descriptor slot's views: a storage block or a uniform block | | `lower/` | `select` (routing every instruction, intrinsic and parameter into the `Plan`), `strategy`, `push` (push-constant placement), `specialized` (bound-texture values read as push data), and one module per family: `arith` (each float operation in the AIR's order, decorated by its own fast-math flags, so the device's compiler groups and fuses only what they allow; `half_chain`, a fast-math `half` chain held at `float` precision between its roundings where the device has no 16-bit floats), `access`, `texture`, `sampler`, `simd`, `sync`, `fragment`, `stage_io`, `dispatch`, `tessellation`, `mesh`, `raytracing` | | `structurize/` | The structurizer over the AIR CFG, the emit walk that drives the families, and single-store promotion | -| `spirv/` | The typed SPIR-V IR and interners, the module and function builders, dead-value removal, the roll pass, the move of loop-invariant loads of uniform views out of their loops (`hoist`), the 16-bit holding of `half` values under the 16-bit float controls (`half_hold`), the verifier, requirement derivation and the serializer. `spirv::interp` is a CPU interpreter used only by tests | +| `spirv/` | The typed SPIR-V IR and interners, the module and function builders, dead-value removal, the roll pass, the move of loop-invariant loads of uniform views out of their loops (`hoist`), the stores of an undefined value at each loop trip's top that end the structurizer variables no later trip reads (`carry`), the 16-bit holding of `half` values under the 16-bit float controls (`half_hold`), the verifier, requirement derivation and the serializer. `spirv::interp` is a CPU interpreter used only by tests | | `spv.rs` | The SPIR-V grammar's opcodes and enumerants the translator names, generated from Khronos's grammar (`scripts/regen-spirv-grammar/`) | | `spirv_binary/` | A reader of SPIR-V's binary form over the grammar's instruction table, used only by tests | | `device/` | `DeviceDescription` (from a Khronos profile, or from `ash`), `DevicePolicy`, and the derived `DeviceProfile` every decision reads |