Take a 16-byte leaf's uvec4 unit only at an offset proven a multiple of 16

A 16-byte leaf whose AIR says align 16 was one uvec4 unit at off / 16 of its slot's uvec4 view
(or of a UniformVec4 view), and a memcpy whose call sites say align 16 moved such units. Metal
does not place an access at the alignment its AIR states. A float4 cast from a float pointer at
a row start 84 p bytes in is only 4-byte aligned, and Metal reads and writes it there; the unit
put it k floats low, losing the first k values and leaving k stale floats at classes 16 - k to
15 (a softmax over 21 classes, 728,687 of 774,144 outputs wrong).

Measured on an Apple M3 Max under macOS 27.0.1, rows of 21 elements one thread a row
(crates/metal2vulkan-conformance/probes/vector_access_placement.m, job m3-max-23317):

  float4 (align 16), device, threadgroup and constant memory, loads and stores,
    at 4, 8 or 12 mod 16                        -> at the address
  half4 store (align 8), device, at 2 mod 4     -> the multiple of 4 below
  uchar4 store (align 4), device, at an odd one -> the multiple of 4 below
  float4 * buffer bound at offset 4             -> at the address; API validation fails the
                                                   bind: "must be a multiple of 16"

So the words at off / 4, which every other path reads, are Metal's in each row, and only the
uvec4 unit at off / 16 was wrong.

Provenance's PtrFact gains `align`, the base-2 log (at most 4) of a power of two dividing every
offset a pointer value may take from its roots: a GEP's base and terms (a constant's
displacement, a dynamic index's stride times the factor of two its index carries through shl,
mul, and, add, sub, or, xor, select and extensions), the least over a phi's or select's values
and a cell's stored pointers. It only falls and is never widened; only offset changes count
toward widening. MemoryPlan::proven_align is the least of that and its roots' bases: a buffer
parameter's residual is congruent to its bind offset modulo 16, a multiple of its
air.arg_type_align_size by Metal's bind contract (the validation message above); an arena
object's or blob constant's base is its offset; a threadgroup region's 16; any other root's 1.
leaf_of takes the proven alignment, and Path::Vec4 needs it at 16 as well as align 16; memcpy's
16-byte units need it on every buffer endpoint. Every other path is unchanged, so a kernel whose
offsets are proven (a float4 buffer at its own indices, 16-aligned struct members, constant
offsets from a 16-aligned argument) keeps its uvec4 unit.

Tests: engine_access's a_float4_aligned_only_to_its_lanes_is_placed_at_its_address runs the
rows kernel as Apple's compiler emits it (loops kept) in the interpreter on four profiles in both
encodings at residuals 0 and 4, and must equal Metal's rows; a float4 grid keeps its uvec4 view.
sixteen_byte_leaves_move_as_one_uvec4 now runs each 16-byte leaf at a byte offset read from a
buffer (words, whatever its align) and at an offset in 16-byte units over uint4 buffers (the
uvec4 unit where align is 16).
This commit is contained in:
Anees Iqbal committed 2026-11-12 17:48:37 -08:00
1 parent e4d00d2c21
commit 786bae34a5
14 files changed
+619 -134

No files matched your search

+2 -1
View File
@@ -187,7 +187,8 @@ pub fn load(
) -> Result<BlobLoad, Error> {
use_blob(cx)?;
let align = align.map_or(1, |a| a.bytes());
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align)?;
let proven = cx.memory.proven_align(cx.entry, ptr);
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align, proven)?;
Ok(BlobLoad {
ptr: blob_ptr(cx, ptr)?,
leaf,
+28 -16
View File
@@ -14,9 +14,11 @@
//! least 4, or when it is an arena or blob pointer whose offset is a translation-time constant
//! multiple of 4 (an object's placed offset displaced by constant GEPs; both memories start at a
//! word). A `memcpy` or `memmove` of a constant multiple of 16 bytes with a static buffer endpoint,
//! every buffer endpoint's call-site `align` at least 16 and every other endpoint word-aligned,
//! moves 16-byte `uvec4` units instead: a buffer slot with a `uvec4` view moves each unit as one
//! element of it, and every other memory as its four words. Every unit is one leaf load and store
//! every buffer endpoint's call-site `align` at least 16 and its offset proven a multiple of 16
//! (`MemoryPlan::proven_align`: the call-site `align` alone is no proof, `memory::leaf`'s
//! placement), and every other endpoint word-aligned, moves 16-byte `uvec4` units instead: a
//! buffer slot with a `uvec4` view moves each unit as one element of it, and every other memory as
//! its four words. Every unit is one leaf load and store
//! (`memory::leaf`), each contained exactly as a plain access of that leaf, so a byte store never
//! disturbs a neighbour (the sub-word atomics); an arena unit at a constant offset that ends inside
//! the arena's translation-time size has no check, which could only pass. `memset` stores the byte
@@ -557,8 +559,17 @@ pub fn select(
Some(intrinsic_endpoint(cx, arg(cx, 1)?, false, m)?.with_volatile(volatile))
};
let unit = unit_of(
(&dst, arg_align(call, 0)),
from.as_ref().map(|f| (f, arg_align(call, 1))),
(
&dst,
arg_align(call, 0),
cx.memory.proven_align(cx.entry, d),
),
from.as_ref()
.map(|f| -> Result<_, Error> {
let s = arg(cx, 1)?;
Ok((f, arg_align(call, 1), cx.memory.proven_align(cx.entry, s)))
})
.transpose()?,
&span,
);
let length = match span {
@@ -625,24 +636,25 @@ enum Span {
}
/// The bytes of each unit of a copy or fill to `dst` from `from` (each with its call-site
/// `align`) of length `span` (module doc). A copy of a constant nonzero multiple of 16 bytes with
/// a static buffer endpoint, every buffer endpoint's call-site `align` at least 16 and every other
/// endpoint word-aligned, moves 16: a buffer endpoint's call-site `align` of 16 makes each unit's
/// descriptor offset a multiple of 16, so a `uvec4` view element holds exactly its bytes, and every
/// other memory moves a 16-byte unit as its four words, which needs only word alignment. Otherwise
/// a unit is a word when both endpoints are word-aligned, else a byte.
fn unit_of(dst: (&Endpoint, u64), from: Option<(&Endpoint, u64)>, span: &Span) -> u32 {
/// `align` and the alignment its offset is proven to have) of length `span` (module doc). A copy
/// of a constant nonzero multiple of 16 bytes with a static buffer endpoint, every buffer
/// endpoint's call-site `align` at least 16 and its offset proven a multiple of 16, and every
/// other endpoint word-aligned, moves 16: each unit's descriptor offset is a multiple of 16, so a
/// `uvec4` view element holds exactly its bytes, and every other memory moves a 16-byte unit as
/// its four words, which needs only word alignment. Otherwise a unit is a word when both endpoints
/// are word-aligned, else a byte.
fn unit_of(dst: (&Endpoint, u64, u64), from: Option<(&Endpoint, u64, u64)>, span: &Span) -> u32 {
let ends = || std::iter::once(dst).chain(from);
let vec4 = from.is_some()
&& matches!(*span, Span::Bytes(len) if len > 0 && len % 16 == 0)
&& ends().any(|(e, _)| matches!(e, Endpoint::Buffer(_)))
&& ends().all(|(e, call)| match e {
Endpoint::Buffer(_) => call >= 16,
&& ends().any(|(e, _, _)| matches!(e, Endpoint::Buffer(_)))
&& ends().all(|(e, call, proven)| match e {
Endpoint::Buffer(_) => call >= 16 && proven >= 16,
_ => known_align(e, call) >= 4,
});
if vec4 {
16
} else if ends().all(|(e, call)| known_align(e, call) >= 4) {
} else if ends().all(|(e, call, _)| known_align(e, call) >= 4) {
4
} else {
1
@@ -769,6 +769,7 @@ pub fn select(
&cx.memory.layouts,
inst.ty,
align_of(*align),
cx.memory.proven_align(cx.entry, *ptr),
)?;
DynStrategy::Load(WideAccess {
ptr: plan_deref(cx, *ptr)?,
@@ -797,6 +798,7 @@ pub fn select(
&cx.memory.layouts,
ty,
align_of(*align),
cx.memory.proven_align(cx.entry, *ptr),
)?;
let value = stored_value(cx, *val)?;
DynStrategy::Store(WideAccess {
@@ -857,7 +859,8 @@ fn coherent(
};
// The intrinsic states no alignment: the value's natural (ABI) one.
let align = cx.memory.layouts.abi_align(ty).unwrap_or(1);
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align)?;
let proven = cx.memory.proven_align(cx.entry, ptr);
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align, proven)?;
let value = match value {
Some(v) => Some(stored_value(cx, v)?),
None => None,
@@ -1089,7 +1089,8 @@ pub(crate) fn access(
super::tile_memory::written(cx)?;
}
let align = align.map_or(1, |a| a.bytes());
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align)?;
let proven = cx.memory.proven_align(cx.entry, ptr);
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align, proven)?;
let ptr = access_ptr(cx, ptr, arena, u64::from(leaf.bytes))?;
let value = stored_value(cx, value)?;
Ok(LocalAccess {
+2 -1
View File
@@ -1986,7 +1986,8 @@ fn select_access(
) -> Result<Access, Error> {
let (targets, null, blob_check) = blob_roots(cx, ptr, value.is_some(), m)?;
let align = align.map_or(1, |a| a.bytes());
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align)?;
let proven = cx.memory.proven_align(cx.entry, ptr);
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align, proven)?;
access_with_leaf(cx, ptr, value, leaf, targets, null, blob_check)
}
+1 -1
View File
@@ -844,7 +844,7 @@ pub(super) fn select_texel(
.ok_or_else(|| cx.invariant("an implicit imageblock value without a type"))?,
None => ty,
};
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, access_ty, 1)?;
let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, access_ty, 1, 1)?;
let contained = imageblock::contained(cx);
let p = plan(cx)?;
let cell_bytes = p.cell_bytes;
@@ -351,6 +351,7 @@ fn view(
&cx.memory.layouts,
field_ty,
offset_align(at.offset),
offset_align(at.offset),
)?;
// A value wider than its slot is a packed pixel-format member, which Metal converts.
if leaf.bytes > at.size
+32 -13
View File
@@ -15,9 +15,10 @@
//! and the register value goes chunk by chunk.
//!
//! No narrow storage type is used: a leaf is composed from the 32-bit words covering it. The
//! **path** depends only on the access's alignment `a` ([`Path`]):
//! **path** depends only on the access's alignment `a` and, for a 16-byte leaf, the alignment its
//! offset is proven to have ([`Path`]):
//!
//! - [`Path::Vec4`] (`n == 16` and `a >= 16`): the offset is a multiple of 16, so the leaf is
//! - [`Path::Vec4`] (`n == 16`, `a >= 16`, and the offset proven a multiple of 16): the leaf is
//! `uvec4` unit `off/16` where the memory has one ([`Units::vec4`]), else [`Path::Aligned`]'s
//! four words.
//! - [`Path::Aligned`] (`a >= 4`): the offset is a multiple of 4, so the leaf is words
@@ -73,10 +74,26 @@
//! **Volatile**. A volatile access is the same leaf through a word memory whose [`WordOps`] carry
//! `volatile`: every word or unit it loads or stores has the `Volatile` memory operand.
//!
//! The alignment is a promise about the Metal address; it carries to the offset in a word memory
//! because every word memory's base is 4-byte aligned in the Metal address space (the binder's
//! descriptor bases are), and to a `uvec4` unit's index because a descriptor view's base is 16-byte
//! aligned there.
//! **Placement**. Metal does not place an access at the alignment its AIR states. Measured on an
//! Apple M3 Max under macOS 27.0.1, rows of 21 elements one thread a row
//! (`probes/vector_access_placement.m` in the conformance crate):
//!
//! | Access | Its address | Where Metal reads or writes it |
//! |---|---|---|
//! | `float4` (`align 16`): device, threadgroup, constant | 4, 8 or 12 mod 16 | at the address |
//! | `half4` store (`align 8`): device | 2 mod 4 | the multiple of 4 below |
//! | `uchar4` store (`align 4`): device | odd | the multiple of 4 below |
//! | `float4 *` buffer bound at offset 4 | 4 mod 16 | at the address |
//!
//! Metal's API validation fails that last bind ("must be a multiple of 16"): a buffer's bind
//! offset is a multiple of its argument's `air.arg_type_align_size`. An alignment of at least 4
//! carries to the offset in a word memory, because every word memory's base is 4-byte aligned in
//! the Metal address space (the binder's descriptor bases are): the words at `off/4` are those
//! Metal reads, for each row of the table. A `uvec4` unit at `off/16` is exact only where `off` is
//! a multiple of 16, which the access's `align` does not say, so it is taken only where the offset
//! is proven one (`MemoryPlan::proven_align`: the structure of the pointer's offset and its roots'
//! bases, a buffer's from its argument's alignment); elsewhere the leaf is the four words at
//! `off/4`.
use crate::air::ir::{Type, TypeId as AirTypeId, TypeLayouts};
use crate::air::Entry;
@@ -187,7 +204,7 @@ fn not_lowered() -> Error {
/// How a leaf is composed from words.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Path {
/// A 16-byte leaf at an offset that is a multiple of 16: one `uvec4` unit where the memory
/// A 16-byte leaf at an offset proven a multiple of 16: one `uvec4` unit where the memory
/// has one ([`Units::vec4`]), else [`Path::Aligned`]'s four words.
Vec4,
/// The offset is a multiple of 4.
@@ -271,17 +288,19 @@ impl Leaf {
}
}
/// The leaf of an access of AIR type `ty` with alignment `align` bytes (1 when unstated), or the
/// refusal of a type that is not a scalar or vector the arithmetic family holds on `p`. A
/// vector's lanes must be whole bytes (`<N x i1>` and odd widths are bit-packed in LLVM); one of
/// 5 to 255 lanes is chunked, and a `<1 x T>` (a chunked composite of one scalar) or a vector of
/// more lanes is not implemented.
/// The leaf of an access of AIR type `ty` with alignment `align` bytes (1 when unstated) at an
/// offset proven a multiple of `proven` bytes (`MemoryPlan::proven_align`; the module doc's
/// placement), or the refusal of a type that is not a scalar or vector the arithmetic family holds
/// on `p`. A vector's lanes must be whole bytes (`<N x i1>` and odd widths are bit-packed in LLVM);
/// one of 5 to 255 lanes is chunked, and a `<1 x T>` (a chunked composite of one scalar) or a
/// vector of more lanes is not implemented.
pub fn leaf_of(
e: &Entry,
p: &DeviceProfile,
layouts: &TypeLayouts,
ty: AirTypeId,
align: u64,
proven: u64,
) -> Result<Leaf, Error> {
// A 64-bit integer is two words on a profile without `shaderInt64`, in a chunk too.
let form = match legal::chunked(e.module.types(), ty) {
@@ -330,7 +349,7 @@ pub fn leaf_of(
) {
return Err(not_lowered());
}
let path = if bytes == 16 && align >= 16 {
let path = if bytes == 16 && align >= 16 && proven >= 16 {
Path::Vec4
} else if align >= 4 {
Path::Aligned
+88 -10
View File
@@ -48,8 +48,9 @@ use std::sync::Arc;
use super::abi_index::AbiIndex;
use super::provenance::{
self, grow, imageblock_cell, CellFacts, Class, ConstForm, Extent, HandleClass, OffsetRange,
PrivForm, Provenance, Repr, Root, RootSetId, RootSets, RootUse, Shape,
self, grow, imageblock_cell, twos, CellFacts, Class, ConstForm, Extent, HandleClass,
OffsetRange, PrivForm, Provenance, Repr, Root, RootSetId, RootSets, RootUse, Shape,
ALIGN_LOG_CAP,
};
use super::window;
use crate::air::abi::{AbiInt, Access, ImageblockKind, ParamRole};
@@ -323,8 +324,9 @@ pub struct MemoryPlan {
pub repr: Vec<Option<Repr>>,
/// The interned root sets `repr` names.
pub sets: RootSets,
/// The offset range of every pointer value, sorted by value.
pub offsets: Vec<(ValueId, OffsetRange)>,
/// The offset range of every pointer value and the base-2 logarithm of the alignment its
/// offset is known to have (`PtrFact::align`), sorted by value.
pub offsets: Vec<(ValueId, OffsetRange, u8)>,
/// The device and constant pointer values whose offset is a constant plus one dynamic
/// multiple of a stride (`Shape::Strided`: one dynamic element index), with that base and
/// stride, sorted by value.
@@ -391,8 +393,84 @@ impl MemoryPlan {
/// The offset range of pointer value `v` from its root.
pub fn offset(&self, v: Value) -> Option<OffsetRange> {
let id = self.values.id(v)?;
let at = self.offsets.binary_search_by_key(&id, |(v, _)| *v).ok()?;
self.offsets.get(at).map(|(_, r)| *r)
let at = self
.offsets
.binary_search_by_key(&id, |(v, _, _)| *v)
.ok()?;
self.offsets.get(at).map(|(_, r, _)| *r)
}
/// The base-2 logarithm of a power of two (at most `ALIGN_LOG_CAP`) that divides every
/// offset pointer value `v` may take from its roots (`PtrFact::align`); 0 for a value without
/// a fact.
pub fn offset_twos(&self, v: Value) -> u8 {
let Some(id) = self.values.id(v) else {
return 0;
};
self.offsets
.binary_search_by_key(&id, |(v, _, _)| *v)
.ok()
.and_then(|at| self.offsets.get(at))
.map_or(0, |(_, _, a)| *a)
}
/// The base-2 logarithm of a power of two (at most `ALIGN_LOG_CAP`) that divides the byte
/// offset of root `r`'s first byte in the word memory an access of it reaches:
///
/// - a buffer parameter's, its descriptor view's residual, which is congruent to the bind
/// offset modulo 16 (`memory::views::BASE_ALIGNMENT`): Metal binds a buffer at an offset that
/// is a multiple of the alignment of the data its function consumes, which AIR states as
/// `air.arg_type_align_size` (Metal's API validation fails a `float4 *` buffer bound at
/// offset 4: "must be a multiple of 16", `probes/vector_access_placement.m` in the
/// conformance crate);
/// - a `[[threadgroup(n)]]` region's, its region's alignment;
/// - an arena object's or a blob constant's, its offset;
/// - the null root's, the cap: nothing is accessed there;
/// - any other root's (a buffer table's element, a dynamic or an intrinsic's root), 0.
pub fn base_twos(&self, e: &Entry, r: Root) -> u8 {
match r {
Root::Null => ALIGN_LOG_CAP,
Root::Param(p) => match self.tg_arena.dynamic.iter().find(|d| d.param == p) {
Some(d) => twos(i128::from(d.align)),
None => self
.abi
.binding(e, p)
.and_then(|b| b.ty.align)
.map_or(0, |a| twos(i128::from(a))),
},
Root::Global(g) => {
let object = ArenaObject::Global(g);
let entry = self
.tg_arena
.entry(object)
.or_else(|| self.priv_arena.entry(object));
match (entry, self.const_global(g).map(|c| c.form)) {
(Some(entry), _) => twos(i128::from(entry.offset)),
(None, Some(ConstGlobalForm::Blob { offset })) => twos(i128::from(offset)),
_ => 0,
}
}
Root::Alloca(id) => self
.priv_arena
.entry(ArenaObject::Alloca(id))
.map_or(0, |entry| twos(i128::from(entry.offset))),
_ => 0,
}
}
/// The alignment in bytes (at most 16) proven for every byte offset at which pointer value `v`
/// reaches its word memory: the least over its roots' bases ([`MemoryPlan::base_twos`]) and
/// its offset from them ([`MemoryPlan::offset_twos`]). An access's own `align` is not a proof:
/// Metal places a `float4` whose address is a multiple of 4 and not of 16 at that address,
/// though its AIR states `align 16`.
pub fn proven_align(&self, e: &Entry, v: Value) -> u64 {
let roots = self.roots_of(v).unwrap_or(&[]);
let base = roots
.iter()
.map(|r| self.base_twos(e, *r))
.min()
.unwrap_or(0);
1 << base.min(self.offset_twos(v))
}
/// `(base, stride)` when the offset of device or constant pointer value `v` is `base + k ·
@@ -457,7 +535,7 @@ impl MemoryPlan {
/// The bytes the plan's tables hold, as the ledger charges them.
pub fn retained_bytes(&self) -> usize {
self.repr.capacity() * std::mem::size_of::<Option<Repr>>()
+ self.offsets.capacity() * std::mem::size_of::<(ValueId, OffsetRange)>()
+ self.offsets.capacity() * std::mem::size_of::<(ValueId, OffsetRange, u8)>()
+ self.strided.capacity() * std::mem::size_of::<(ValueId, i64, u64)>()
+ self.root_sets.capacity() * std::mem::size_of::<(ValueId, RootSetId)>()
+ self.sets.retained_bytes()
@@ -616,7 +694,7 @@ fn analyze(e: &Entry, p: &DeviceProfile, m: &mut Meter) -> Result<MemoryPlan, Er
/// What [`Planner::reprs`] derives.
struct Reprs {
repr: Vec<Option<Repr>>,
offsets: Vec<(ValueId, OffsetRange)>,
offsets: Vec<(ValueId, OffsetRange, u8)>,
strided: Vec<(ValueId, i64, u64)>,
root_sets: Vec<(ValueId, RootSetId)>,
handle_table: Option<Vec<HandleClass>>,
@@ -2161,10 +2239,10 @@ impl Planner<'_> {
strided.push((v, base, stride));
}
}
offsets.push((v, f.range));
offsets.push((v, f.range, f.align));
root_sets.push((v, f.roots));
}
offsets.sort_unstable_by_key(|(v, _)| *v);
offsets.sort_unstable_by_key(|(v, _, _)| *v);
strided.sort_unstable_by_key(|(v, _, _)| *v);
root_sets.sort_unstable_by_key(|(v, _)| *v);
let handle_table = (!handles.is_empty()).then(|| handles.into_iter().collect());
+144 -1
View File
@@ -254,12 +254,32 @@ impl Shape {
}
}
/// The base-2 logarithm of the widest alignment an offset's [`PtrFact::align`] tracks: 16 bytes,
/// the widest unit an access moves (`memory::leaf`'s `uvec4`).
pub const ALIGN_LOG_CAP: u8 = 4;
/// The base-2 logarithm of the greatest power of two, up to [`ALIGN_LOG_CAP`], that divides `x`
/// (the cap for 0, which every power divides).
pub fn twos(x: i128) -> u8 {
if x == 0 {
ALIGN_LOG_CAP
} else {
(x.trailing_zeros() as u8).min(ALIGN_LOG_CAP)
}
}
/// The analysis fact of one pointer value.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PtrFact {
pub roots: RootSetId,
pub range: OffsetRange,
pub shape: Shape,
/// The base-2 logarithm of a power of two (at most [`ALIGN_LOG_CAP`]) that divides every
/// offset the value may take from its root: the least over the values a `phi` or `select`
/// merges, and over a GEP's base and terms, a dynamic index's stride times the factor of two
/// its index is known to carry ([`known_twos`]). It is never widened: it only falls, and has
/// five values.
pub align: u8,
}
impl PtrFact {
@@ -267,6 +287,7 @@ impl PtrFact {
roots: RootSetId::EMPTY,
range: OffsetRange::Empty,
shape: Shape::Empty,
align: ALIGN_LOG_CAP,
};
fn at(roots: RootSetId, offset: i64) -> PtrFact {
@@ -277,6 +298,7 @@ impl PtrFact {
hi: offset,
},
shape: Shape::Exact(offset),
align: twos(i128::from(offset)),
}
}
@@ -285,6 +307,7 @@ impl PtrFact {
roots,
range: OffsetRange::Top,
shape: Shape::Top,
align: 0,
}
}
}
@@ -744,6 +767,115 @@ pub(crate) fn gep_displacement(
Ok((konst.and_then(|c| i64::try_from(c).ok()), strides))
}
/// The base-2 logarithm of the alignment (at most [`ALIGN_LOG_CAP`]) that the displacement of
/// `getelementptr src_ty, _, idx..` is known to have: the least over its terms, a constant index's
/// displacement and a dynamic index's stride times the factor of two its index carries
/// ([`known_twos`]). The walk is [`gep_displacement`]'s, which refuses what it cannot size first; a
/// term it cannot read here counts as unaligned.
fn gep_twos(e: &Entry, layouts: &TypeLayouts, src_ty: TypeId, idx: &[Value]) -> u8 {
let mut least = ALIGN_LOG_CAP;
let mut cur = src_ty;
for (n, &i) in idx.iter().enumerate() {
let scale = if n == 0 {
layouts.alloc_size(src_ty)
} else {
match e.module.types().get(cur) {
Some(Type::Struct { fields, .. }) => {
let field = const_index(e, i).and_then(|k| usize::try_from(k).ok());
let off = field.and_then(|k| layouts.field_offsets(cur)?.get(k).copied());
match (field.and_then(|k| fields.get(k)), off) {
(Some(f), Some(off)) => {
least = least.min(twos(i128::from(off)));
cur = *f;
continue;
}
_ => return 0,
}
}
Some(Type::Array { elem, .. } | Type::Vector { elem, .. }) => {
cur = *elem;
layouts.alloc_size(*elem)
}
_ => None,
}
};
let Some(scale) = scale else { return 0 };
let term = match const_index(e, i) {
Some(k) => twos(i128::from(k) * i128::from(scale)),
None => twos(i128::from(scale))
.saturating_add(known_twos(e, i, KNOWN_TWOS_DEPTH))
.min(ALIGN_LOG_CAP),
};
least = least.min(term);
}
least
}
/// How deep [`known_twos`] reads an index's definition.
const KNOWN_TWOS_DEPTH: u8 = 4;
/// The base-2 logarithm of a power of two (at most [`ALIGN_LOG_CAP`]) that divides integer `v` in
/// every execution, read from its definition up to `depth` instructions deep: a constant's own; a
/// shift left by a constant adds the shift and a product adds its factors'; an `and` keeps the
/// larger of its operands', a sum, difference, `or`, `xor` or `select` the smaller; an extension or
/// truncation keeps its operand's (the cap is below every integer width but `i1`, whose values
/// 0 and 1 a truncation to it would not keep, so that one is 0). Anything else is 0.
fn known_twos(e: &Entry, v: Value, depth: u8) -> u8 {
use crate::air::ir::BinOp as IntOp;
if let Some(k) = const_index(e, v) {
return twos(i128::from(k));
}
let Value::Inst(id) = v else { return 0 };
if depth == 0 {
return 0;
}
let body = e.module.func(e.func).and_then(|f| f.body.as_ref());
let Some(inst) = body.and_then(|b| b.insts.get(id)) else {
return 0;
};
let d = depth - 1;
let of = |x: Value| known_twos(e, x, d);
match &inst.kind {
InstKind::BinOp {
op: IntOp::Shl,
a,
b,
..
} => match const_index(e, *b).and_then(|s| u8::try_from(s).ok()) {
Some(s) => of(*a).saturating_add(s).min(ALIGN_LOG_CAP),
None => 0,
},
InstKind::BinOp {
op: IntOp::Mul,
a,
b,
..
} => of(*a).saturating_add(of(*b)).min(ALIGN_LOG_CAP),
InstKind::BinOp {
op: IntOp::And,
a,
b,
..
} => of(*a).max(of(*b)),
InstKind::BinOp {
op: IntOp::Add | IntOp::Sub | IntOp::Or | IntOp::Xor,
a,
b,
..
} => of(*a).min(of(*b)),
InstKind::Select { t, f, .. } => of(*t).min(of(*f)),
InstKind::Cast {
op: CastOp::ZExt | CastOp::SExt,
v,
} => of(*v),
InstKind::Cast {
op: CastOp::Trunc,
v,
} if !matches!(e.module.types().get(inst.ty), Some(Type::Int(1))) => of(*v),
_ => 0,
}
}
/// The dense index of a pointer-typed argument or instruction.
const NONE: u32 = u32::MAX;
@@ -1239,10 +1371,12 @@ impl<'a> Cx<'a> {
}
(Shape::Top, _, _) => Shape::Top,
};
let align = base.align.min(gep_twos(self.e, self.layouts, src_ty, idx));
Ok(PtrFact {
roots: base.roots,
range,
shape,
align,
})
}
@@ -1480,6 +1614,7 @@ impl<'a> Cx<'a> {
roots: self.sets.join(a.roots, b.roots, m)?,
range: a.range.join(b.range),
shape: a.shape.join(b.shape),
align: a.align.min(b.align),
})
}
}
@@ -2353,7 +2488,15 @@ fn fixpoint(
if new == old {
continue;
}
let changes = cx.changes.get(i).copied().unwrap_or(0).saturating_add(1);
// Only the offsets widen, so only their changes count: the alignment falls at most
// `ALIGN_LOG_CAP` times on its own.
let moved = new.range != old.range || new.shape != old.shape;
let changes = cx
.changes
.get(i)
.copied()
.unwrap_or(0)
.saturating_add(u8::from(moved));
if changes > WIDEN_AFTER {
if new.range != OffsetRange::Empty {
new.range = OffsetRange::Top;
@@ -425,6 +425,7 @@ impl Cx<'_> {
roots: self.sets.join(out.roots, x.roots, m)?,
range: out.range.join(x.range),
shape: out.shape.join(x.shape),
align: out.align.min(x.align),
};
}
}
@@ -664,6 +665,7 @@ impl Cx<'_> {
roots: self.sets.join(held.roots, x.roots, m)?,
range: held.range.join(x.range),
shape: held.shape.join(x.shape),
align: held.align.min(x.align),
};
}
self.leak(held, m)?;
@@ -214,6 +214,7 @@ fn an_access_as_wide_as_its_step_is_one_test() {
roots: super::super::RootSetId::EMPTY,
range: OffsetRange::Span { lo: 0, hi: last },
shape,
align: 0,
};
let before = m.work();
let touched =
+8 -6
View File
@@ -30,11 +30,13 @@
//!
//! A storage or uniform slot may also have a **`uvec4` view** ([`Vec4View`]): `StorageBuffer {
//! uvec4[] }` or `Uniform { uvec4[N] }` at the slot's binding, declared where an access of the slot
//! moves a 16-byte leaf whose AIR alignment is at least 16 (a `UniformVec4` word view is its own).
//! The binder's 16-byte-aligned descriptor bases carry that alignment to the unit index
//! `(residual + m) / 16`, and a 16-aligned 16-byte leaf lies wholly inside or wholly outside a
//! bound range (every range is a whole number of 16-byte units), so the word view's containment
//! check of the leaf's 16 bytes is the unit's. `u64[]` views are not declared.
//! moves a 16-byte leaf whose AIR alignment is at least 16 at an offset `residual + m` proven a
//! multiple of 16 (`memory::leaf`'s placement: the residual's alignment is the bind offset's, and
//! `m`'s is its structure's; a `UniformVec4` word view is its own). The binder's 16-byte-aligned
//! descriptor bases carry that alignment to the unit index `(residual + m) / 16`, and a 16-aligned
//! 16-byte leaf lies wholly inside or wholly outside a bound range (every range is a whole number
//! of 16-byte units), so the word view's containment check of the leaf's 16 bytes is the unit's.
//! `u64[]` views are not declared.
use crate::pipeline::sym::{ResourceKind, ResourceSlot, SlotRef};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
@@ -68,7 +70,7 @@ pub struct View {
/// and uniform view's range at a multiple of `max(min*BufferOffsetAlignment, 16)` bytes from the
/// allocation's start ([`base_alignment`]), so with the allocation's first byte at a
/// 16-byte-aligned Metal address, a descriptor byte is congruent to its Metal address modulo 16
/// and a 16-byte leaf whose AIR alignment is at least 16 is one `uvec4` element.
/// and a 16-byte leaf whose Metal address is a multiple of 16 is one `uvec4` element.
pub const BASE_ALIGNMENT: u64 = 16;
/// The alignment of a Metal buffer slot's descriptor base for a view whose minimum offset
+304 -83
View File
@@ -20,9 +20,13 @@
//! below the bind offset and reaches 2³¹ or more above it is exact on both sides; a `Psb`
//! window longer than 2³² is refused.
//! - Constant GEP indices whose products exceed 128 bits wrap to the offset's low word.
//! - A 16-byte leaf is one element of its slot's `uvec4` view only at an offset proven a multiple
//! of 16; a `float4` whose offset is a multiple of 4 and not of 16 is read and written at that
//! offset, as Metal does, whatever the `align 16` its AIR states.
//!
//! `llvm-as` assembles the fixtures; without it the tests skip visibly.
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -40,7 +44,7 @@ use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::facts::{RuntimeFact, UniformViewChoice};
use crate::pipeline::interface::{BufferForm, DescriptorView, PushLoc, SlotInterface, Window};
use crate::pipeline::sym::{
PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, Symbol,
Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, Symbol,
};
use crate::pipeline::testing::{
compile, device_nan_bits, engine_dir, link_and_validate, llvm_assemble, meter, typed_module,
@@ -493,6 +497,28 @@ fn leaf_kernel(k: &LeafKernel) -> String {
)
}
/// [`leaf_kernel`] with its offset proven a multiple of 16: `params[0]` counts 16-byte units
/// (a GEP over `<4 x i32>`), and `data` and `out` are `uint4` buffers (`air.arg_type_align_size`
/// 16, so Metal binds them at multiples of 16).
fn leaf_kernel_in_units(k: &LeafKernel) -> String {
let name = k.name;
let ty = k.ty;
let a = k.align;
let body = match &k.store {
None => format!(
" %v = load {ty}, ptr addrspace(1) %p, align {a}\n store {ty} %v, ptr addrspace(1) %1, align 16\n"
),
Some((c, _)) => format!(" store {ty} {c}, ptr addrspace(1) %p, align {a}\n"),
};
let meta = meta(name).replace(
"!\"air.arg_type_size\", i32 1, !\"air.arg_type_align_size\", i32 1, !\"air.arg_type_name\", !\"uchar\"",
"!\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"uint4\"",
);
format!(
"{HEADER}define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, ptr addrspace(1) noundef \"air-buffer-no-alias\" %1, ptr addrspace(1) noundef \"air-buffer-no-alias\" %2) {{\nentry:\n %o = load i32, ptr addrspace(1) %2, align 4\n %p = getelementptr <4 x i32>, ptr addrspace(1) %0, i32 %o\n{body} ret void\n}}\n\n{meta}"
)
}
fn leaf_kernels() -> Vec<LeafKernel> {
let k = |name, ty, bytes, align| LeafKernel {
name,
@@ -2103,17 +2129,19 @@ fn every_view_of_a_written_slot_stays_writable() {
}
}
/// The `uvec4` residuals the 16-byte units are checked at: zero, below 16, a multiple of 16, past
/// 32, and wrapped.
/// The residuals the 16-byte leaves are checked at: zero, below 16, a multiple of 16, past 32, and
/// wrapped.
const VEC4_RESIDUALS: [u32; 6] = [0, 4, 12, 16, 36, 0xFFFF_FFF0];
/// A 16-byte leaf whose alignment is at least 16 is one element of the slot's `uvec4` view
/// (declared beside the word view, and stored with one `OpStore`), in both encodings, on every
/// tested profile; aligned to 4 it moves word by word (four stores, no `uvec4` view of the slot it
/// stores to). At every residual a descriptor offset that is a multiple of 16 reads and writes
/// exactly the leaf's 16 bytes of a 48-byte range (a `half` NaN stored from a constant a NaN where
/// the module encodes it by the device's narrowing, `device_nan_bits`), and with
/// the in-shader check the offset past the range reads 0 and writes nothing.
/// A 16-byte leaf whose alignment is at least 16 at an offset proven a multiple of 16
/// ([`leaf_kernel_in_units`]) is one element of the slot's `uvec4` view (declared beside the word
/// view, and stored with one `OpStore`), in both encodings, on every tested profile; aligned to 4,
/// or at an offset nothing proves a multiple of 16 ([`leaf_kernel`]'s byte offset from a buffer,
/// whatever its `align`), it moves word by word (four stores, no `uvec4` view of the slot it stores
/// to). At every residual its buffer's alignment allows, a descriptor offset that is a multiple of
/// 16 reads and writes exactly the leaf's 16 bytes of a 48-byte range (a `half` NaN stored from a
/// constant a NaN where the module encodes it by the device's narrowing, `device_nan_bits`), and
/// with the in-shader check the offset past the range reads 0 and writes nothing.
#[test]
fn sixteen_byte_leaves_move_as_one_uvec4() {
const OP_STORE: u16 = 62;
@@ -2126,83 +2154,107 @@ fn sixteen_byte_leaves_move_as_one_uvec4() {
for (what, p) in encodings() {
let robust = what.ends_with("robust=true");
for k in &sixteen {
let what = format!("{what} {}", k.name);
let Some(bc) = assemble_text(k.name, &leaf_kernel(k)) else {
return;
};
check_l3(&bc, k.name, &p, &what);
let (plan, m) = typed_module(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
let vec4 = k.align >= 16;
// A load kernel stores the loaded leaf to `out` at alignment 16.
assert_eq!(
views_of(&m, 0),
if vec4 { 2 } else { 1 },
"{what}: views of data"
);
assert_eq!(
views_of(&m, 1),
if k.store.is_none() { 2 } else { 0 },
"{what}: views of out"
);
let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
let native_halves = k.ty.contains("half") && device_nan_bits(&a);
let stores = opcodes(&a.module.words)
.iter()
.filter(|o| **o == OP_STORE)
.count();
let want = if k.store.is_some() && !vec4 { 4 } else { 1 };
assert_eq!(stores, want, "{what}: stores");
let data = pattern(48);
for r in VEC4_RESIDUALS {
// The interpreter models no robustness: robust encodings run in bounds only.
let descs: &[u32] = if robust {
&[0, 16, 32]
for units in [true, false] {
let what = format!("{what} {} units={units}", k.name);
let text = if units {
leaf_kernel_in_units(k)
} else {
&[0, 16, 32, 48]
leaf_kernel(k)
};
for &desc in descs {
let o = desc.wrapping_sub(r);
let mut params = vec![0u8; 16];
params[..4].copy_from_slice(&o.to_le_bytes());
let res = Resources {
buffers: vec![
Buffer {
slot: Some(kslot(0)),
address: None,
bytes: data.clone(),
},
bound(1, 0, &[0; 32], 0),
bound(2, 0, &params, 0),
],
push: push_bytes(&plan, &[(0, r)]),
spec: Default::default(),
let Some(bc) = assemble_text(k.name, &text) else {
return;
};
check_l3(&bc, k.name, &p, &what);
let (plan, m) =
typed_module(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
let vec4 = units && k.align >= 16;
// A load kernel stores the loaded leaf to `out` at alignment 16, at offset 0 of a
// buffer whose bind offset is a multiple of 16 where it is a `uint4` buffer.
assert_eq!(
views_of(&m, 0),
if vec4 { 2 } else { 1 },
"{what}: views of data"
);
assert_eq!(
views_of(&m, 1),
match (&k.store, units) {
(Some(_), _) => 0,
(None, true) => 2,
(None, false) => 1,
},
"{what}: views of out"
);
let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
let native_halves = k.ty.contains("half") && device_nan_bits(&a);
let stores = opcodes(&a.module.words)
.iter()
.filter(|o| **o == OP_STORE)
.count();
let want = match (&k.store, units) {
(Some(_), _) if !vec4 => 4,
(None, false) => 4,
_ => 1,
};
assert_eq!(stores, want, "{what}: stores");
let data = pattern(48);
// A `uint4` buffer is bound at a multiple of 16.
let residuals = VEC4_RESIDUALS.iter().filter(|r| !units || *r % 16 == 0);
for &r in residuals {
// The interpreter models no robustness: robust encodings run in bounds only.
let descs: &[u32] = if robust {
&[0, 16, 32]
} else {
&[0, 16, 32, 48]
};
let out = run(&m, &Config::default(), res)
.unwrap_or_else(|e| panic!("{what} r={r:#x} desc={desc}: {e:?}"));
let at = desc as usize;
let inb = at + 16 <= data.len();
match &k.store {
None => {
let want: Vec<u8> = if inb {
data[at..at + 16].to_vec()
} else {
vec![0; 16]
};
assert_eq!(out.buffers[1][..16], want[..], "{what} r={r:#x} {desc}");
}
Some((_, bytes)) => {
let mut want = data.clone();
if inb {
want[at..at + 16].copy_from_slice(bytes);
}
if native_halves {
assert!(
same_halves(&out.buffers[0], &want),
"{what} r={r:#x} {desc}: {:?}",
out.buffers[0]
for &desc in descs {
let o = desc.wrapping_sub(r);
let o = if units { o / 16 } else { o };
let mut params = vec![0u8; 16];
params[..4].copy_from_slice(&o.to_le_bytes());
let res = Resources {
buffers: vec![
Buffer {
slot: Some(kslot(0)),
address: None,
bytes: data.clone(),
},
bound(1, 0, &[0; 32], 0),
bound(2, 0, &params, 0),
],
push: push_bytes(&plan, &[(0, r)]),
spec: Default::default(),
};
let out = run(&m, &Config::default(), res)
.unwrap_or_else(|e| panic!("{what} r={r:#x} desc={desc}: {e:?}"));
let at = desc as usize;
let inb = at + 16 <= data.len();
match &k.store {
None => {
let want: Vec<u8> = if inb {
data[at..at + 16].to_vec()
} else {
vec![0; 16]
};
assert_eq!(
out.buffers[1][..16],
want[..],
"{what} r={r:#x} {desc}"
);
} else {
assert_eq!(out.buffers[0], want, "{what} r={r:#x} {desc}");
}
Some((_, bytes)) => {
let mut want = data.clone();
if inb {
want[at..at + 16].copy_from_slice(bytes);
}
if native_halves {
assert!(
same_halves(&out.buffers[0], &want),
"{what} r={r:#x} {desc}: {:?}",
out.buffers[0]
);
} else {
assert_eq!(out.buffers[0], want, "{what} r={r:#x} {desc}");
}
}
}
}
@@ -2212,6 +2264,175 @@ fn sixteen_byte_leaves_move_as_one_uvec4() {
}
}
/// Rows of 21 `float`s, one thread a row, each row written as four `float4`s and five `float`s as
/// Apple's compiler emits `device float4 *v = (device float4 *)(out + 21 * p); v[i] = float4(p, 4i,
/// 4i + 1, 4i + 2)` and `out[21 * p + c] = c` (its loops kept): row `p` starts at byte `84 p`, so 3
/// rows in 4 start 4, 8 or 12 bytes past a multiple of 16, while the vectors' AIR says `align 16`.
const FLOAT4_ROWS: &str = r#"define void @float4_rows(ptr addrspace(1) noundef "air-buffer-no-alias" %0, i32 noundef %1) {
entry:
%r = mul i32 %1, 21
%rz = zext i32 %r to i64
%row = getelementptr inbounds float, ptr addrspace(1) %0, i64 %rz
%pf = tail call fast float @air.convert.f.f32.u.i32(i32 %1)
%v0 = insertelement <4 x float> undef, float %pf, i64 0
br label %vectors
vectors:
%i = phi i32 [ 0, %entry ], [ %in, %vectors ]
%f = shl nuw nsw i32 %i, 2
%f1 = tail call fast float @air.convert.f.f32.u.i32(i32 %f)
%v1 = insertelement <4 x float> %v0, float %f1, i64 1
%g = or i32 %f, 1
%g1 = tail call fast float @air.convert.f.f32.u.i32(i32 %g)
%v2 = insertelement <4 x float> %v1, float %g1, i64 2
%h = or i32 %f, 2
%h1 = tail call fast float @air.convert.f.f32.u.i32(i32 %h)
%v3 = insertelement <4 x float> %v2, float %h1, i64 3
%iz = zext i32 %i to i64
%at = getelementptr inbounds <4 x float>, ptr addrspace(1) %row, i64 %iz
store <4 x float> %v3, ptr addrspace(1) %at, align 16
%in = add nuw nsw i32 %i, 1
%vdone = icmp eq i32 %in, 4
br i1 %vdone, label %scalars, label %vectors
scalars:
%c = phi i32 [ 16, %vectors ], [ %cn, %scalars ]
%cf = tail call fast float @air.convert.f.f32.u.i32(i32 %c)
%e = add i32 %c, %r
%ez = zext i32 %e to i64
%ep = getelementptr inbounds float, ptr addrspace(1) %0, i64 %ez
store float %cf, ptr addrspace(1) %ep, align 4
%cn = add nuw nsw i32 %c, 1
%sdone = icmp eq i32 %cn, 21
br i1 %sdone, label %exit, label %scalars
exit:
ret void
}
declare float @air.convert.f.f32.u.i32(i32)
!air.kernel = !{!9}
!air.version = !{!17}
!air.language_version = !{!18}
!9 = !{ptr @float4_rows, !10, !11}
!10 = !{}
!11 = !{!12, !13}
!12 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"out"}
!13 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"p"}
!17 = !{i32 2, i32 8, i32 0}
!18 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
/// `float4`s at their own indices, `v[p] = float4(p, 1, 2, 3)` over a `device float4 *`: every
/// offset a multiple of 16, as the binding's is.
const FLOAT4_GRID: &str = r#"define void @float4_grid(ptr addrspace(1) noundef "air-buffer-no-alias" %0, i32 noundef %1) {
entry:
%pf = tail call fast float @air.convert.f.f32.u.i32(i32 %1)
%v = insertelement <4 x float> <float undef, float 1.0, float 2.0, float 3.0>, float %pf, i64 0
%iz = zext i32 %1 to i64
%at = getelementptr inbounds <4 x float>, ptr addrspace(1) %0, i64 %iz
store <4 x float> %v, ptr addrspace(1) %at, align 16
ret void
}
declare float @air.convert.f.f32.u.i32(i32)
!air.kernel = !{!9}
!air.version = !{!17}
!air.language_version = !{!18}
!9 = !{ptr @float4_grid, !10, !11}
!10 = !{}
!11 = !{!12, !13}
!12 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"v"}
!13 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"p"}
!17 = !{i32 2, i32 8, i32 0}
!18 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
/// Eight threads, one threadgroup: the spec the interpreter runs a kernel's grid of 8 at.
fn eight_threads() -> BTreeMap<SpecKey, u64> {
let mut spec = BTreeMap::new();
spec.insert(SpecKey::LocalSize(Axis::X), 8);
spec.insert(SpecKey::LocalSize(Axis::Y), 1);
spec.insert(SpecKey::LocalSize(Axis::Z), 1);
spec.insert(SpecKey::FlatLocalSize, 8);
spec
}
/// A `float4` whose address is a multiple of 4 and not of 16 is read and written at that address,
/// whatever the `align 16` its AIR states: Metal's answer for [`FLOAT4_ROWS`] over 8 threads on an
/// Apple M3 Max (`probes/vector_access_placement.m` in the conformance crate) is every row exact,
/// `p 0 1 2 p 4 5 6 p 8 9 10 p 12 13 14 16 17 18 19 20`. Nothing proves those offsets multiples of
/// 16 (the row's stride is 84 bytes and its buffer a `float` buffer, bound at any multiple of 4), so
/// the slot has no `uvec4` view and the vectors move as words, at residuals 0 and 4, on every tested
/// profile in both encodings. Where the offsets are proven multiples of 16 ([`FLOAT4_GRID`], a
/// `float4` buffer at its own indices) the vector is one element of the slot's `uvec4` view.
#[test]
fn a_float4_aligned_only_to_its_lanes_is_placed_at_its_address() {
let (Some(rows), Some(grid)) = (
assemble_text("float4_rows", &format!("{HEADER}{FLOAT4_ROWS}")),
assemble_text("float4_grid", &format!("{HEADER}{FLOAT4_GRID}")),
) else {
return;
};
let metal: Vec<f32> = (0..8u32)
.flat_map(|p| {
let p = p as f32;
let mut row = Vec::new();
for i in 0..4u32 {
let f = (4 * i) as f32;
row.extend([p, f, f + 1.0, f + 2.0]);
}
row.extend((16..21).map(|c| c as f32));
row
})
.collect();
for (what, p) in encodings() {
check_l3(&rows, "float4_rows", &p, &what);
let (plan, m) =
typed_module(&rows, "float4_rows", &p).unwrap_or_else(|e| panic!("{what}: {e}"));
for r in [0u32, 4] {
let res = Resources {
buffers: vec![bound(0, r, &[0xEE; 8 * 84], 0xEE)],
push: push_bytes(&plan, &[(0, r)]),
spec: eight_threads(),
};
let out =
run(&m, &Config::default(), res).unwrap_or_else(|e| panic!("{what} r={r}: {e:?}"));
let got: Vec<f32> = out.buffers[0][r as usize..r as usize + 8 * 84]
.as_chunks::<4>()
.0
.iter()
.map(|w| f32::from_le_bytes(*w))
.collect();
assert_eq!(got, metal, "{what} r={r}");
}
assert_eq!(views_of(&m, 0), 1, "{what}: views of the rows");
check_l3(&grid, "float4_grid", &p, &what);
let (plan, m) =
typed_module(&grid, "float4_grid", &p).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(views_of(&m, 0), 2, "{what}: views of the grid");
for r in [0u32, 16] {
let res = Resources {
buffers: vec![bound(0, r, &[0xEE; 8 * 16], 0xEE)],
push: push_bytes(&plan, &[(0, r)]),
spec: eight_threads(),
};
let out =
run(&m, &Config::default(), res).unwrap_or_else(|e| panic!("{what} r={r}: {e:?}"));
let got: Vec<f32> = out.buffers[0][r as usize..r as usize + 8 * 16]
.as_chunks::<4>()
.0
.iter()
.map(|w| f32::from_le_bytes(*w))
.collect();
let want: Vec<f32> = (0..8u32).flat_map(|p| [p as f32, 1.0, 2.0, 3.0]).collect();
assert_eq!(got, want, "{what} r={r}");
}
}
}
/// A kernel reading the `float4` at byte 32 of a `constant` buffer (a `Bounded` window, so a
/// uniform view under robust descriptors) into `out`.
const CONSTANT_VEC4: &str = r#"define void @constant_vec4(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1) {