diff --git a/crates/metal2vulkan-air/src/canon/const_hoist.rs b/crates/metal2vulkan-air/src/canon/const_hoist.rs new file mode 100644 index 000000000..50a0312ea --- /dev/null +++ b/crates/metal2vulkan-air/src/canon/const_hoist.rs @@ -0,0 +1,394 @@ +//! A kernel's plain loads of its constant references, made in its entry block. +//! +//! A kernel often reads a `constant T&` parameter only behind its bounds branch (`if (gid >= n) +//! return; out[gid] = in[gid] * scale;`): the load of `scale` lies in a block the threads past the +//! end skip. [`expand`] moves each such load into the entry block, ahead of every branch, its value +//! reaching each use by dominance, where all of the following hold. Each is read from the body's +//! structure and the entry's ABI, never from a name. +//! +//! - **A plain load of a scalar or vector.** Neither volatile nor atomic, of an integer, a float or +//! a vector of them. The load of a pointer or an aggregate stays. +//! - **The reference's own bytes, at an offset fixed at translation time.** Its address is a +//! parameter the ABI binds as a buffer of the constant address space with a stated +//! `air.buffer_size` (a `constant T&`; no function constant gates it), or that parameter plus +//! `getelementptr`s at constant, non-negative indices and bitcasts, which move with the load. The +//! bytes read lie inside the referenced object, `[0, air.buffer_size)`. The address is then one +//! address for every thread of the dispatch, and each form of the access contains it at the +//! entry as it did where it stood: the same slot, a bound storage view under its robust buffer +//! access, or a device address read at a constant offset inside the object, which no check +//! clamps in either place. A pointer parameter (`constant T*`, no size), an offset outside the +//! object, and an offset the run computes stay. +//! - **No write before it.** No instruction on any path from the function's start to the load may +//! write device memory or order another thread's writes before it: a store or memory intrinsic +//! whose destination is not thread or threadgroup memory, an atomic or atomic load of any space, +//! a fence or barrier, a texture write, or a call of any kind but arithmetic, conversions, group +//! operations, built-in reads and texture reads and queries. A device buffer may cover the +//! constant buffer's bytes, so such a write could change what the load reads. +//! +//! Anything else stays where it is. The moved load reads the bytes it read where it stood: a +//! thread that skipped its block reads them too and uses nothing of them. + +use std::collections::BTreeMap; + +use crate::abi::{ParamBinding, ParamRole}; +use crate::budget::Meter; +use crate::error::Error; +use crate::intrinsics::{AirIntrinsic, LlvmIntrinsic, TexOp}; +use crate::ir::{AddrSpace, BlockId, Body, Callee, CastOp, FuncId, Idx, InstId, InstKind}; +use crate::ir::{Layout, ModuleParts, Type, TypeId, TypeLayouts, TypeTable, Value}; + +use super::pieces::gep_offset; +use super::rewrite::{apply, filled, invariant, scoped, BodyEdit}; + +/// The address steps a load's address is followed through to its parameter. +const STEPS: usize = 64; + +/// Make in the entry block each load of `func`'s body that reads a constant reference the +/// entry's `bindings` bind, where nothing before it may write device memory (the module docs). +pub(super) fn expand( + body: Body, + parts: &ModuleParts, + func: FuncId, + bindings: &[ParamBinding], + m: &mut Meter, +) -> Result { + let f = parts + .funcs + .get(func) + .ok_or_else(|| invariant("entry out of range"))?; + let Some(Type::Function { params: tys, .. }) = parts.types.get(f.ty) else { + return Err(invariant("the entry's type is not a function")); + }; + let objects: BTreeMap = bindings + .iter() + .filter_map(|b| reference(b, tys, &parts.types)) + .collect(); + if objects.is_empty() { + return Ok(body); + } + m.charge(objects.len() * std::mem::size_of::<(u32, u64)>() * 2)?; + let next = scoped(m, |m, held| { + let cx = Cx { + body: &body, + parts, + tys, + objects: &objects, + }; + let moved = cx.moves(m, held)?; + if moved.is_empty() { + return Ok(None); + } + let mut edit = BodyEdit::keep_all(&body, m, held)?; + edit.moved = moved; + apply(&body, &edit, &|c| c, m).map(Some) + }); + m.release(objects.len() * std::mem::size_of::<(u32, u64)>() * 2); + match next? { + Some(next) => { + body.release(m); + Ok(next) + } + None => Ok(body), + } +} + +/// The parameter `b` binds and the bytes of the object it references, where it is a constant +/// reference: a buffer of the constant address space with a stated `air.buffer_size`, which no +/// function constant gates, of a constant-space pointer type in `tys`. +fn reference(b: &ParamBinding, tys: &[TypeId], types: &TypeTable) -> Option<(u32, u64)> { + let ParamRole::Buffer(arg) = &b.role else { + return None; + }; + if b.unused || b.predicate.is_some() || arg.space != AddrSpace::Constant { + return None; + } + let ty = types.get(*tys.get(usize::try_from(b.param).ok()?)?)?; + let pointer = matches!( + ty, + Type::Ptr { + space: AddrSpace::Constant + } + ); + pointer.then_some((b.param, u64::from(arg.buffer_size?))) +} + +/// What the walk reads. +struct Cx<'a> { + body: &'a Body, + parts: &'a ModuleParts, + /// The entry's parameter types. + tys: &'a [TypeId], + /// The constant references: parameter, and the bytes of the object it references. + objects: &'a BTreeMap, +} + +impl Cx<'_> { + /// The loads to make in the entry block, each with the address steps it moves with, mapped to + /// the entry block. Its tables are charged to `held`. + fn moves(&self, m: &mut Meter, held: &mut usize) -> Result, Error> { + let mut moved = BTreeMap::new(); + let n = self.body.blocks.len(); + let entry = BlockId::new(0); + if n < 2 { + return Ok(moved); + } + // The blocks the entry reaches, and those a write may precede: every block a block that + // writes leads to. + let mut reached = filled(m, held, n, false)?; + let mut written = filled(m, held, n, false)?; + let mut stack: Vec = filled(m, held, n, entry)?; + stack.clear(); + if let Some(r) = reached.get_mut(entry.index()) { + *r = true; + } + stack.push(entry); + while let Some(b) = stack.pop() { + m.tick(1)?; + for s in self.body.successors(b) { + // A branch back to the entry block: it is no place every path starts from. + if s == entry { + return Ok(moved); + } + if let Some(r) = reached.get_mut(s.index()).filter(|r| !**r) { + *r = true; + stack.push(s); + } + } + } + for (b, _) in self.body.blocks.iter() { + m.tick(1)?; + if !self.body.block_insts(b).any(|(_, i)| self.writes(&i.kind)) { + continue; + } + stack.push(b); + while let Some(b) = stack.pop() { + m.tick(1)?; + for s in self.body.successors(b) { + if let Some(w) = written.get_mut(s.index()).filter(|w| !**w) { + *w = true; + stack.push(s); + } + } + } + } + let mut layouts = None; + for (b, _) in self.body.blocks.iter().skip(1) { + let mut clean = reached.get(b.index()).copied().unwrap_or(false) + && !written.get(b.index()).copied().unwrap_or(true); + for (id, inst) in self.body.block_insts(b) { + m.tick(1)?; + if !clean { + break; + } + if self.writes(&inst.kind) { + clean = false; + continue; + } + let InstKind::Load { + ptr, + volatile: false, + atomic: None, + .. + } = inst.kind + else { + continue; + }; + if !self.plain_value(inst.ty) { + continue; + } + if layouts.is_none() { + let l = TypeLayouts::new(&self.parts.data_layout, &self.parts.types, m)?; + *held = held.saturating_add( + self.parts.types.len() * std::mem::size_of::>(), + ); + layouts = Some(l); + } + let Some(tl) = layouts.as_ref() else { + continue; + }; + let Some(steps) = self.steps(tl, ptr, inst.ty, m)? else { + continue; + }; + // Each step is made before what uses it: the moved instructions arrive in the + // entry block in their old order. + let mut after = id; + if steps.iter().any(|&s| { + let before = s < after; + after = s; + !before + }) { + continue; + } + for s in steps.into_iter().chain([id]) { + if moved.insert(s, entry).is_none() { + let bytes = std::mem::size_of::<(InstId, BlockId)>() * 2; + m.charge(bytes)?; + *held = held.saturating_add(bytes); + } + } + } + } + Ok(moved) + } + + /// Whether a load of type `ty` reads a plain value: an integer, a float, or a vector of them. + fn plain_value(&self, ty: TypeId) -> bool { + let scalar = |t: &Type| { + matches!( + t, + Type::Int(_) | Type::Half | Type::BFloat | Type::Float | Type::Double + ) + }; + match self.parts.types.get(ty) { + Some(Type::Vector { elem, .. }) => self.parts.types.get(*elem).is_some_and(scalar), + Some(t) => scalar(t), + None => false, + } + } + + /// The address steps of a load of `ty` at `ptr`, the nearest first, where `ptr` is a constant + /// reference plus a translation-time offset and the bytes read lie inside its object. + fn steps( + &self, + layouts: &TypeLayouts, + ptr: Value, + ty: TypeId, + m: &mut Meter, + ) -> Result>, Error> { + let mut steps = Vec::new(); + let mut at = 0u64; + let mut v = ptr; + for _ in 0..STEPS { + m.tick(1)?; + let i = match v { + Value::Arg(a) => { + let Some(&size) = u32::try_from(a.index()) + .ok() + .and_then(|p| self.objects.get(&p)) + else { + return Ok(None); + }; + let inside = layouts + .store_size(ty) + .and_then(|n| at.checked_add(n)) + .is_some_and(|end| end <= size); + return Ok(inside.then_some(steps)); + } + Value::Inst(i) => i, + Value::Const(_) => return Ok(None), + }; + let Some(inst) = self.body.insts.get(i) else { + return Ok(None); + }; + match &inst.kind { + InstKind::Gep { + src_ty, + base, + indices, + .. + } => { + let Some(next) = gep_offset(self.parts, layouts, *src_ty, indices) + .and_then(|o| at.checked_add(o)) + else { + return Ok(None); + }; + at = next; + v = *base; + } + InstKind::Cast { + op: CastOp::Bitcast, + v: inner, + } => v = *inner, + _ => return Ok(None), + } + steps.push(i); + } + Ok(None) + } + + /// The type of value `v`. + fn value_ty(&self, v: Value) -> Option { + match v { + Value::Inst(i) => self.body.insts.get(i).map(|n| n.ty), + Value::Arg(a) => self.tys.get(a.index()).copied(), + Value::Const(k) => self.parts.consts.ty(k), + } + } + + /// Whether pointer `v` points into memory of one thread or threadgroup, which no device + /// buffer covers. + fn local(&self, v: Value) -> bool { + match self.value_ty(v).and_then(|t| self.parts.types.get(t)) { + Some(Type::Ptr { space }) => local_space(*space), + _ => false, + } + } + + /// Whether `kind` may write device memory, or order another thread's writes before what + /// follows it (the module docs). + fn writes(&self, kind: &InstKind) -> bool { + match kind { + InstKind::Store { + ptr, atomic: None, .. + } => !self.local(*ptr), + InstKind::Store { .. } + | InstKind::AtomicRmw { .. } + | InstKind::CmpXchg { .. } + | InstKind::Fence(_) + | InstKind::Load { + atomic: Some(_), .. + } => true, + InstKind::Call(c) => match &c.callee { + Callee::Air { op, .. } => !reads_only(op), + Callee::Llvm { op, .. } => match op { + LlvmIntrinsic::Float { .. } + | LlvmIntrinsic::Int { .. } + | LlvmIntrinsic::NarrowInt { .. } + | LlvmIntrinsic::Abs { .. } + | LlvmIntrinsic::Cttz { .. } + | LlvmIntrinsic::Ctlz { .. } => false, + LlvmIntrinsic::Memset { dst, .. } + | LlvmIntrinsic::Memcpy { dst, .. } + | LlvmIntrinsic::Memmove { dst, .. } => !local_space(*dst), + LlvmIntrinsic::Agx(_) => true, + }, + _ => true, + }, + _ => false, + } + } +} + +/// Whether `space` is memory of one thread or threadgroup. +fn local_space(space: AddrSpace) -> bool { + matches!( + space, + AddrSpace::Thread | AddrSpace::Threadgroup | AddrSpace::ThreadgroupImageblock + ) +} + +/// Whether AIR intrinsic `op` neither writes memory nor orders another thread's writes: +/// arithmetic, conversions, group operations, built-in reads, and texture reads and queries. +fn reads_only(op: &AirIntrinsic) -> bool { + match op { + AirIntrinsic::Math(_) + | AirIntrinsic::Convert(_) + | AirIntrinsic::Pack(_) + | AirIntrinsic::BoolReduce(_) + | AirIntrinsic::Group(_) + | AirIntrinsic::IsUniform(_) + | AirIntrinsic::SimdgroupSize(_) + | AirIntrinsic::GlobalBuiltin(_) + | AirIntrinsic::WorkItem(_) + | AirIntrinsic::Sampler(_) => true, + AirIntrinsic::Texture(t) => matches!( + t.op, + TexOp::Read + | TexOp::Sample { .. } + | TexOp::SampleGrad { .. } + | TexOp::Gather { .. } + | TexOp::Query(_) + ), + _ => false, + } +} diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index d1b8e2136..1fa246423 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -86,7 +86,10 @@ //! row, the origin and the constant transpose flag (`legacy_matrix`). **Aggregate accesses**: a //! load or store of a whole array or struct in buffer or threadgroup memory becomes its scalar //! and vector members' accesses, joined by `insertvalue` or split by `extractvalue` -//! (`aggregates`). **Program-scope buffer bindings**: each load of the pointer a bound buffer's +//! (`aggregates`). **Constant references**: in a kernel, each plain load of a scalar or vector +//! from a `constant T&` parameter's object, at an offset fixed at translation time, is made in +//! the entry block where nothing on any path before it may write device memory +//! (`const_hoist`). **Program-scope buffer bindings**: each load of the pointer a bound buffer's //! global holds becomes a read of the entry's parameter of that buffer, its own or one appended //! (`global_binding`). **Global built-in //! variables**: each `air.get_*` read of a program-scope built-in becomes a read of a built-in @@ -109,6 +112,7 @@ mod async_copy; mod block_read; mod byval; mod command_writes; +mod const_hoist; mod const_loads; mod const_tables; mod devirt; @@ -761,6 +765,13 @@ pub fn specialize_dynamic( let body = routine::expand(body, &mut parts, m)?; // Aggregate loads and stores of buffer and threadgroup memory as their members' accesses. let body = aggregates::expand(body, &mut parts, func, m)?; + // A kernel's plain loads of its constant references, made in its entry block where nothing + // before them may write device memory. + let body = if matches!(ep.stage, Stage::Kernel { .. }) { + const_hoist::expand(body, &parts, func, &ep.params, m)? + } else { + body + }; // A simdgroup reduction before a discard that Metal's compiler moves past it is placed after // the discard, where the fragment lowering gives Metal's lanes. let body = if matches!(ep.stage, Stage::Fragment { .. }) { diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 55acdf3e5..e73812345 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -72,7 +72,7 @@ rest is `crates/metal2vulkan/src/`. | Module | Role | |---|---| -| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining (each `byval` argument's copy made at its call first), function constants, SCCP (a value one of a few constants, from a PHI of literal constants or a `select` between two, folded member by member so a branch every member decides alike is decided; reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` and the scalar `llvm.umin`, `llvm.umax`, `llvm.smin` and `llvm.smax` on constants, settling the float operations a constant operand decides whatever the others hold (a NaN operand, the first in order: as it is beside a value the run computes, quieted where every operand is a constant; a product by a zero under `nnan` and `nsz`, `+0`), and reading the immediates of an intrinsic call that its function's parameters gave it once inlining makes them its call site's constants), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, the allocation of a private array of nested arrays as far as its indices reach where constants and counted loops bound every one of them (`canon::reach`), a pointer loaded from a constant table at an index only the run knows (a table of constexpr samplers) read as the `select` chain over the table's elements (`canon::const_tables`), each of MSL 4.1's generic pointers made a pointer of the one address space every pointer it may hold comes from, its space queries answered (`canon::generic`), devirtualization, linking, the load of a stack allocation's field that one dominating store wrote read as the stored value (an aggregate holding a pointer excepted), and an allocation no read is left of removed with its stores, so a lambda's closure of captured addresses leaves the captured objects' own (`canon::forward`), pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses, and a kernel of a pipeline of OpenCL mode linked as Metal links it: the three hidden buffers appended, its buffer indices 3 on, OpenCL C's work-item reads made reads of their built-ins or of the first buffer, each image format query a read of the third, each `air.wg.barrier`'s flags read as OpenCL C's `cl_mem_fence_flags`, and each operation of a 1D image the 2D texture's that Apple's OpenCL binds for it, `canon::opencl` and `canon::opencl_1d`; and OpenCL C's vector data loads and stores made their element accesses, `canon::vector_data`). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data | +| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining (each `byval` argument's copy made at its call first), function constants, SCCP (a value one of a few constants, from a PHI of literal constants or a `select` between two, folded member by member so a branch every member decides alike is decided; reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` and the scalar `llvm.umin`, `llvm.umax`, `llvm.smin` and `llvm.smax` on constants, settling the float operations a constant operand decides whatever the others hold (a NaN operand, the first in order: as it is beside a value the run computes, quieted where every operand is a constant; a product by a zero under `nnan` and `nsz`, `+0`), and reading the immediates of an intrinsic call that its function's parameters gave it once inlining makes them its call site's constants), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, the allocation of a private array of nested arrays as far as its indices reach where constants and counted loops bound every one of them (`canon::reach`), a pointer loaded from a constant table at an index only the run knows (a table of constexpr samplers) read as the `select` chain over the table's elements (`canon::const_tables`), each of MSL 4.1's generic pointers made a pointer of the one address space every pointer it may hold comes from, its space queries answered (`canon::generic`), devirtualization, linking, the load of a stack allocation's field that one dominating store wrote read as the stored value (an aggregate holding a pointer excepted), and an allocation no read is left of removed with its stores, so a lambda's closure of captured addresses leaves the captured objects' own (`canon::forward`), pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses, a kernel's plain loads of a `constant T&` parameter's object at an offset fixed at translation time made in its entry block where nothing on any path before them may write device memory (`canon::const_hoist`), and a kernel of a pipeline of OpenCL mode linked as Metal links it: the three hidden buffers appended, its buffer indices 3 on, OpenCL C's work-item reads made reads of their built-ins or of the first buffer, each image format query a read of the third, each `air.wg.barrier`'s flags read as OpenCL C's `cl_mem_fence_flags`, and each operation of a 1D image the 2D texture's that Apple's OpenCL binds for it, `canon::opencl` and `canon::opencl_1d`; and OpenCL C's vector data loads and stores made their element accesses, `canon::vector_data`). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data | | `graph` | The shared RPO, dominator tree, loop forest and SCC | | `budget` | `Budget`, `CancelToken`, and the per-attempt `Meter`: deadline, cancellation, work units, the byte ledger and every structural cap | | `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 |