A narrow integer operation the AIR marks nuw keeps no mask

A narrow integer is held zero-extended in a u32 or u64 container, and an add, sub, mul or shl
that can carry above its width masks its result. One the AIR marks `nuw` no longer does: each
result that would carry is poison, so every other already fits the width. The common case is a
loop counter's increment: an i16-counted loop's latch read `((i + 1) & 0xFFFF) == N`, which hides
the trip count from RADV's loop analysis, so the loop stayed rolled and a private array it indexes
stayed in scratch. In the Super Resolution conv kernel 199ed62a647fd6f2 (a perfscout2 dump, read
on um790 only), removing those masks from the dumped module took the XTX from 12.5 to 0.69 ms a
dispatch and its scratch from 32768 to 0 bytes (job 25066), and the 780M from over 6 s to 6.0 ms
(25114). The inputs were synthetic and the kernel's stores never ran under them (25112, 25131),
so those times are loop cost only. `nsw` alone keeps the mask: `-1 + 1` carries out of the
zero-extended bits.

With that, a value's bits above its width are zero unless the value is poison. Where a poison
value meets something that must stay defined, it is masked:
- `freeze` of a narrow integer, which must answer a value of its type;
- the words a store writes (memory/leaf.rs words_of and vector_words), so a poison lane reaches
  no neighbouring byte or lane;
- a narrow atomic's operand (atomic/narrow.rs);
- a bitcast's packed integer lanes (ops::lane_bits, chunk::words_of).
The two-word form of i33..i63 without shaderInt64 keeps its masks.

Tests: engine_nuw, an i16 and an i8 loop counted by `add nuw` over a private array, with no
mask to the width in the module, against the same loops with a plain `add`, which keep it; both
sum to 18 on the interpreter, on four profiles. Kernels of a poison `add nuw`: its freeze stays in
range, and a store, a vector store, an atomic exchange and a bitcast of it keep the neighbouring
i16 0x1234. arith tests: nuw add, sub, mul and shl match LLVM wherever they are defined, at i5, i8,
i16 and i40.
This commit is contained in:
Anees Iqbal committed 2026-11-13 03:47:10 -08:00
1 parent bfd9a3cf02
commit feba32b81f
9 files changed
+436 -28

No files matched your search

@@ -3,8 +3,9 @@
//! atomics are not core Vulkan), so a narrow atomic operates on the field of its containing `u32`
//! word: the word at `offset & ~3`, the field `bits` wide at bit `(offset & 3) * 8` (an LLVM
//! atomic's alignment is at least its size, so the field never straddles two words; selection
//! refuses an under-aligned one). Values are held zero-extended in a `u32`, so an operand shifted
//! into place sets no bit outside its field.
//! refuses an under-aligned one). Values are held zero-extended in a `u32`; the operand is masked
//! to the field first (a poison operand, a `nuw` operation's, `ops::int_binary`, may carry bits
//! above its width), so an operand shifted into place sets no bit outside its field.
//!
//! - `load` is `OpAtomicLoad` of the word and the field extracted from it.
//! - `and`, `or`, and `xor` are one word atomic each, whose operand leaves the other fields
@@ -96,6 +97,11 @@ pub(super) fn apply(
) -> BResult<Option<SValue>> {
let lane = k32(fb, (1u32 << bits) - 1)?;
let mask = fb.binary(BinOp::ShiftLeftLogical, lane, shift)?;
let value = match o.value {
Some(x) => Some(fb.binary(BinOp::BitwiseAnd, x, lane)?),
None => None,
};
let o = Op { value, ..o };
let f = Field {
shift,
bits,
+3 -1
View File
@@ -881,10 +881,12 @@ fn words_of(fb: &mut FunctionBuilder<'_>, s: Shape, v: SValue) -> BResult<Vec<SV
(32, Held::Float(_)) => words.push(fb.convert(ConvOp::Bitcast, x, ut)?),
(32, _) => words.push(x),
_ => {
// An integer lane masked to its width: a poison lane (a `nuw` operation's,
// `ops::int_binary`) may exceed it, and never reaches its neighbour's bits.
let b = if lane.is_narrow() {
narrow::to_bits(fb, lane, x)?
} else {
x
ops::mask(fb, lane, x)?
};
let placed = if at == 0 {
b
+8 -3
View File
@@ -7,9 +7,14 @@
//! - `i1` is `bool`; every other integer is held **zero-extended** in an unsigned 32-bit
//! container (`i2`..`i32`) or 64-bit container (`i33`..`i64`), or, without `shaderInt64`, as
//! two `u32` words ([`Held::Wide`], [`widen`], `super::wide`). The bits above the AIR width are
//! always zero, so an operation that can set them (add, sub, mul, shl, signed results) masks
//! its result, and a signed operation sign-extends its operands first. `i8`/`i16` therefore
//! never need `Int8`/`Int16`.
//! zero in every value that is not poison, so an operation that can set them (add, sub, mul,
//! shl, signed results) masks its result, and a signed operation sign-extends its operands
//! first. An add, sub, mul or shl the AIR marks `nuw` in a container is not masked: its only
//! results that would set them are poison (`super::ops::int_binary`; a loop counter's
//! increment is one, and a masked latch hides the loop's trip count from the driver). Where a
//! value must be defined although its operand is poison, it is masked: `freeze`, the bytes a
//! store writes (`memory::leaf`), a narrow atomic's operand, and a bitcast's packed lanes. The
//! two-word form keeps its masks. `i8`/`i16` therefore never need `Int8`/`Int16`.
//! - `float` is `f32` and `double` is `f64` (needs `shaderFloat64`, else refused). `half` and
//! `bfloat` are **held widened** in an `f32` that is always exactly a value of the narrow format,
//! on every profile ([`super::narrow`]): no profile needs `shaderFloat16`, and a constant
+50 -7
View File
@@ -96,7 +96,7 @@ use crate::air::intrinsics::{
use crate::air::intrinsics::{Elem, Math};
use crate::air::ir::{
BinOp as AirBin, BlockId, CastOp, Const, FastMath, FloatPredicate, Inst, InstId, InstKind,
IntPredicate, Type, TypeId as AirTypeId, Value, ValueId,
IntFlags, IntPredicate, Type, TypeId as AirTypeId, Value, ValueId,
};
use crate::air::Entry;
use crate::budget::Meter;
@@ -179,9 +179,11 @@ pub fn materialize(fb: &mut FunctionBuilder<'_>, k: &LoweredConst) -> BResult<Op
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ArithStrategy {
/// An integer binary operator on held integers.
/// An integer binary operator on held integers, with the instruction's wrap flags
/// ([`ops::int_binary`]).
Int {
op: AirBin,
flags: IntFlags,
form: Form,
},
/// A binary operator on `i1` values.
@@ -236,6 +238,10 @@ pub enum ArithStrategy {
Select,
/// The first operand itself (`freeze` of a value, unsigned `abs`).
Copy,
/// `freeze` of a held integer narrower than its container: the operand masked to its width
/// ([`ops::mask`]). A poison operand (a `nuw` operation's, [`ops::int_binary`]) may carry
/// bits above the width; the frozen value is one value of the type.
Freeze(Form),
/// The zero of the result's representation (`freeze` of `undef`/`poison`).
Zero(DemoteTy),
/// `OpUndef` of the result's representation (an element index known out of range).
@@ -431,6 +437,7 @@ impl FamilyStrategy for ArithStrategy {
S::Bitcast { .. } => "arith.bitcast",
S::Select => "arith.select",
S::Copy | S::Zero(_) | S::Undef(_) => "arith.copy",
S::Freeze(_) => "arith.int.legalized",
S::ExtractConst(_)
| S::ExtractDynamic { .. }
| S::InsertConst(_)
@@ -510,6 +517,8 @@ impl FamilyStrategy for ArithStrategy {
// Two operand conversions (a shift pair or a select each) and the operation.
S::IndexWord(_) => 32,
S::Copy => 4,
// The mask and its constant.
S::Freeze(_) => 16,
S::Zero(d) | S::Undef(d) | S::Null(d) => {
8u32.saturating_add(8u32.saturating_mul(leaves(d)))
}
@@ -1409,6 +1418,22 @@ fn form_in(cx: &SelectCx<'_>, v: Value, chunk: Option<u8>) -> Result<Form, Error
chunk_form(cx, t, chunk)
}
/// The form of `v` when it is an integer (or integer vector) held narrower than its container
/// ([`Form::legalized`]).
fn padded_int(cx: &SelectCx<'_>, v: Value, chunk: Option<u8>) -> Result<Option<Form>, Error> {
let t = ty_of(cx, v)?;
let types = cx.entry.module.types();
let elem = match types.get(t) {
Some(Type::Vector { elem, .. }) => *elem,
_ => t,
};
if !matches!(types.get(elem), Some(Type::Int(w)) if *w != 1) {
return Ok(None);
}
let f = chunk_form(cx, t, chunk)?;
Ok(f.legalized().then_some(f))
}
/// [`form_in`] of the instruction's result.
fn result_form_in(cx: &SelectCx<'_>, inst: &Inst, chunk: Option<u8>) -> Result<Form, Error> {
chunk_form(cx, inst.ty, chunk)
@@ -1448,11 +1473,21 @@ fn select_in(
// The result is a value of a lowered type (or the operation is refused).
let result = cx.lowered_repr(Value::Inst(at), inst.ty)?;
Ok(match &inst.kind {
InstKind::BinOp { op, a, b, fmf, .. } => {
InstKind::BinOp {
op,
flags,
a,
b,
fmf,
} => {
let f = form_in(cx, *a, chunk)?;
match f.held {
Held::Bool if !op.is_float() => S::Bool { op: *op, form: f },
Held::Int { .. } if !op.is_float() => S::Int { op: *op, form: f },
Held::Int { .. } if !op.is_float() => S::Int {
op: *op,
flags: *flags,
form: f,
},
// LLVM's `frem` on `float` is Metal's (measured on the M3 Max): with every
// fast-math flag its `fast::fmod`, as `air.fast_fmod` is lowered; otherwise
// `x - y * trunc(x / y)` of its precise quotient, which the device's `OpFRem` is at
@@ -1584,7 +1619,10 @@ fn select_in(
InstKind::Select { .. } => S::Select,
InstKind::Freeze(v) => match cx.constant(*v) {
Some(LoweredConst::Undef(_)) => S::Zero(result),
_ => S::Copy,
_ => match padded_int(cx, *v, chunk)? {
Some(f) => S::Freeze(f),
None => S::Copy,
},
},
// A constant index out of range (or `undef`) gives poison.
InstKind::ExtractElement { vec, idx } => match (idx, const_int(cx, *idx)) {
@@ -3003,6 +3041,7 @@ fn arity(s: &ArithStrategy) -> Option<usize> {
S::FloatFn { f, .. } => Some(f.arity()),
// A constant element index is a literal, never materialized.
S::Copy
| S::Freeze(_)
| S::Convert { .. }
| S::Pack { .. }
| S::ExtractConst(_)
@@ -3076,9 +3115,9 @@ fn value(
let p = nth(cx, xs, 0)?;
chunk::bitcast(fb, *from, *to, p)?
}
S::Int { op, form } => {
S::Int { op, flags, form } => {
let (p, q) = (a(cx, 0)?, a(cx, 1)?);
ops::int_binary(fb, *op, *form, p, q)?
ops::int_binary(fb, *op, *flags, *form, p, q)?
}
S::Bool { op, form } => {
let (p, q) = (a(cx, 0)?, a(cx, 1)?);
@@ -3129,6 +3168,10 @@ fn value(
fb.select(c, t, f)?
}
S::Copy => a(cx, 0)?,
S::Freeze(f) => {
let p = a(cx, 0)?;
ops::mask(fb, *f, p)?
}
S::Zero(d) => match legal::zero(d) {
Some(k) => match legal::materialize(fb, &k)? {
Some(x) => x,
+23 -10
View File
@@ -1,9 +1,10 @@
//! The emission core of the LLVM instruction set on held values: integer, boolean, and float
//! operators, comparisons, and casts. Every function takes and returns SPIR-V values in their
//! lowered representation ([`Form`]) and keeps the zero-extension invariant, so the functions are
//! testable on the CPU interpreter without an AIR module (`tests`).
//! lowered representation ([`Form`]) and keeps the zero-extension invariant (a value that is not
//! poison has no bit above its width, `legal`), so the functions are testable on the CPU
//! interpreter without an AIR module (`tests`).
use crate::air::ir::{BinOp as AirBin, FloatPredicate, IntPredicate};
use crate::air::ir::{BinOp as AirBin, FloatPredicate, IntFlags, IntPredicate};
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::narrow;
use crate::spirv::builder::{FunctionBuilder, MaskForm};
@@ -159,31 +160,42 @@ pub fn sext(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
fb.binary(BinOp::ShiftRightArithmetic, up, sh)
}
/// An integer binary operator on two held integers of form `f`.
/// An integer binary operator with the AIR instruction's `flags` on two held integers of form
/// `f`. An add, sub, mul or shl marked `nuw` is not masked: a result that would carry above the
/// width is poison, so every other result already fits it. (`nsw` alone says nothing of the
/// zero-extended bits: `-1 + 1` carries out of them.)
pub fn int_binary(
fb: &mut FunctionBuilder<'_>,
op: AirBin,
flags: IntFlags,
f: Form,
a: Value,
b: Value,
) -> BResult<Value> {
let bin = |fb: &mut FunctionBuilder<'_>, o, x, y| fb.binary(o, x, y);
let wrap = |fb: &mut FunctionBuilder<'_>, r| {
if flags.contains(IntFlags::NUW) {
Ok(r)
} else {
mask(fb, f, r)
}
};
match op {
AirBin::Add => {
let r = bin(fb, BinOp::IAdd, a, b)?;
mask(fb, f, r)
wrap(fb, r)
}
AirBin::Sub => {
let r = bin(fb, BinOp::ISub, a, b)?;
mask(fb, f, r)
wrap(fb, r)
}
AirBin::Mul => {
let r = bin(fb, BinOp::IMul, a, b)?;
mask(fb, f, r)
wrap(fb, r)
}
AirBin::Shl => {
let r = bin(fb, BinOp::ShiftLeftLogical, a, b)?;
mask(fb, f, r)
wrap(fb, r)
}
AirBin::UDiv => bin(fb, BinOp::UDiv, a, b),
AirBin::URem => bin(fb, BinOp::UMod, a, b),
@@ -775,7 +787,8 @@ fn lane(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, i: u8) -> BResult<Value
/// A lane of form `lane` as its AIR bits in an unsigned integer of its container's width
/// (a narrow float through its format bits, a `half`'s by the device's narrowing,
/// `narrow::to_bits`).
/// `narrow::to_bits`; an integer masked to its width, which a poison lane of a `nuw` operation
/// may exceed, [`int_binary`], so it never reaches a neighbouring lane's bits).
fn lane_bits(fb: &mut FunctionBuilder<'_>, lane: Form, v: Value) -> BResult<Value> {
if lane.is_narrow() {
narrow::to_bits(fb, lane, v)
@@ -783,7 +796,7 @@ fn lane_bits(fb: &mut FunctionBuilder<'_>, lane: Form, v: Value) -> BResult<Valu
let it = ty(fb, lane.int_of())?;
fb.convert(ConvOp::Bitcast, v, it)
} else {
Ok(v)
mask(fb, lane, v)
}
}
+42 -3
View File
@@ -19,7 +19,7 @@ use super::libm::Lib;
use super::math::{self, ConvertKind, FloatFn, IntFn, Sign};
use super::nan::NanTest;
use super::ops::{self, BitcastPlan, CastKind};
use crate::air::ir::{BinOp as AirBin, FloatPredicate, IntPredicate};
use crate::air::ir::{BinOp as AirBin, FloatPredicate, IntFlags, IntPredicate};
use crate::device::DeviceProfile;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::spirv::builder::{FunctionBuilder, MaskForm, ModuleBuilder, ProductForm, QuantizeForm};
@@ -831,7 +831,7 @@ fn integer_operators_match_llvm_at_every_width() {
&format!("{op:?} i{bits}"),
&[f, f],
f,
&|fb, x| ops::int_binary(fb, op, f, x[0], x[1]),
&|fb, x| ops::int_binary(fb, op, IntFlags::NONE, f, x[0], x[1]),
&pairs(&vals, b),
&|c| Some(vec![llvm_int(op, bits, arg(c, 0), arg(c, 1))?]),
false,
@@ -840,6 +840,45 @@ fn integer_operators_match_llvm_at_every_width() {
}
}
/// LLVM's `op nuw` on `bits`-bit operands: `None` where the unsigned result leaves the width
/// (poison).
fn llvm_nuw(op: AirBin, bits: u8, a: u64, b: u64) -> Option<u64> {
let (a, b) = (u128::from(a), u128::from(b));
let r = match op {
AirBin::Add => a + b,
AirBin::Sub => a.checked_sub(b)?,
AirBin::Mul => a * b,
AirBin::Shl if b < u128::from(bits) => a << b,
_ => return None,
};
u64::try_from(r).ok().filter(|r| *r <= mask(bits))
}
/// An add, sub, mul or shl marked `nuw` is left unmasked, and answers LLVM's result wherever it
/// is defined, at every width held in a container.
#[test]
fn nuw_operators_match_llvm_where_defined() {
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
for bits in [5, 8, 16, 40] {
let vals = int_values(bits, &mut rng, 6);
let mut shifts = vals.clone();
shifts.extend(0..u64::from(bits));
let f = int(bits);
for op in [AirBin::Add, AirBin::Sub, AirBin::Mul, AirBin::Shl] {
let b: &[u64] = if op == AirBin::Shl { &shifts } else { &vals };
check(
&format!("{op:?} nuw i{bits}"),
&[f, f],
f,
&|fb, x| ops::int_binary(fb, op, IntFlags::NUW, f, x[0], x[1]),
&pairs(&vals, b),
&|c| Some(vec![llvm_nuw(op, bits, arg(c, 0), arg(c, 1))?]),
false,
);
}
}
}
#[test]
fn integer_operators_on_vectors_work_per_lane() {
let f = vec(int(8), 4);
@@ -853,7 +892,7 @@ fn integer_operators_on_vectors_work_per_lane() {
&format!("{op:?} <4 x i8>"),
&[f, f],
f,
&|fb, x| ops::int_binary(fb, op, f, x[0], x[1]),
&|fb, x| ops::int_binary(fb, op, IntFlags::NONE, f, x[0], x[1]),
&cases,
&|c| {
(0..4)
+10 -2
View File
@@ -5,7 +5,9 @@
//! ([`WordMem`]: a descriptor view, later the PSB and arena forms). Memory holds the
//! little-endian bytes of the value under the AIR datalayout; the register value is the
//! arithmetic family's representation ([`Form`]): an `iN` zero-extended in a `u32` or `u64`, `i1`
//! as `bool` (one byte, `byte != 0`), floats native.
//! as `bool` (one byte, `byte != 0`), floats native. A store masks an integer narrower than its
//! container to its width before placing it ([`words_of`]): a poison value (a `nuw` operation's,
//! `ops::int_binary`) may carry bits above the width, and the store writes only its own bytes.
//!
//! A vector of more than four whole-byte lanes is held **chunked**: its register value is the
//! arithmetic family's composite of 4-lane chunks, the last holding the remaining 1 to 4 lanes.
@@ -907,10 +909,12 @@ pub fn words_of(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, v: Value) -> BResult<
} else {
u32::from(bits / 8)
};
let x = ops::mask(fb, scalar, x)?;
put(fb, &mut out, i * lane_bytes, x)?;
}
Held::Wide { .. } => return Err(dangling()),
Held::Int { .. } | Held::Float(FloatFmt::F64) => {
let x = ops::mask(fb, scalar, x)?;
let (lo, hi) = split64(fb, x)?;
put(fb, &mut out, 8 * i, lo)?;
if 8 * i + 4 < leaf.bytes {
@@ -994,7 +998,10 @@ fn vector_words(
filled(fb, out)
};
Ok(Some(match form.held {
Held::Int { container: 32, .. } => placed(fb, v)?,
Held::Int { container: 32, .. } => {
let v = ops::mask(fb, form, v)?;
placed(fb, v)?
}
Held::Float(FloatFmt::Half | FloatFmt::BFloat) => {
// A narrow float is held widened: one encode of every lane, a `half`'s by the
// device's narrowing (`narrow::to_bits`).
@@ -1007,6 +1014,7 @@ fn vector_words(
placed(fb, u)?
}
Held::Int { container: 64, .. } | Held::Float(FloatFmt::F64) if n == 2 => {
let v = ops::mask(fb, form, v)?;
let ty = uvec_ty(fb, 4)?;
let u = fb.convert(ConvOp::Bitcast, v, ty)?;
let mut out = Vec::with_capacity(4);
+291
View File
@@ -0,0 +1,291 @@
//! An integer operation the AIR marks `nuw` end to end. A narrow integer is held zero-extended in
//! a container, and an add, sub, mul or shl that can carry above its width masks its result;
//! one marked `nuw` does not (`ops::int_binary`): every result that would carry is poison. A loop
//! counter's increment is the common one, and its latch then reads the add itself, as the
//! driver's loop analysis needs to find the trip count (a masked `(i + 1) & 0xFFFF` hides it,
//! which keeps an `i16`-counted loop over a private array rolled and the array in scratch on
//! RADV). A plain `add` keeps its mask.
//!
//! Where a poison value meets something that must stay defined, it is masked: a `freeze` answers
//! a value of its type, and a store, a narrow atomic and a bitcast's packing change no byte or
//! lane but the poison one's. Each kernel loads its operand from the buffer (bytes 8 and 9 hold
//! `0xFF`), so nothing folds it. `llvm-as` assembles the module; without it the test skips
//! visibly.
use crate::air::{self, SpecRequest};
use crate::device::DevicePolicy;
use crate::lower::emit::emit_module;
use crate::lower::select::{select, LowerInputs};
use crate::memory::static_root::analyze_memory;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::pipeline::testing::{
compile, link_and_validate, llvm_assemble, meter, profile, AssembleError, Scratch,
};
use crate::spirv::interp::{run, Buffer, Config, Resources};
use crate::spv::Op;
const PROFILES: [&str; 4] = ["amd-rdna3-radv", "lavapipe", "vk12-floor", "moltenvk-m3"];
/// Two loops over a private `[4 x i32]`, each counted by an `i<bits>` whose increment carries
/// `flag`: the first stores `3 * i`, the second sums the elements (18).
fn loops(name: &str, bits: u8, flag: &str) -> String {
format!(
"define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0) {{
entry:
%arr = alloca [4 x i32], align 4
br label %fill
fill:
%i = phi i{bits} [ 0, %entry ], [ %i.next, %fill ]
%iw = zext i{bits} %i to i64
%p = getelementptr inbounds [4 x i32], ptr %arr, i64 0, i64 %iw
%iv = zext i{bits} %i to i32
%v = mul i32 %iv, 3
store i32 %v, ptr %p, align 4
%i.next = add {flag} i{bits} %i, 1
%i.done = icmp eq i{bits} %i.next, 4
br i1 %i.done, label %sum, label %fill
sum:
%j = phi i{bits} [ 0, %fill ], [ %j.next, %sum ]
%acc = phi i32 [ 0, %fill ], [ %acc.next, %sum ]
%jw = zext i{bits} %j to i64
%q = getelementptr inbounds [4 x i32], ptr %arr, i64 0, i64 %jw
%x = load i32, ptr %q, align 4
%acc.next = add i32 %acc, %x
%j.next = add {flag} i{bits} %j, 1
%j.done = icmp eq i{bits} %j.next, 4
br i1 %j.done, label %exit, label %sum
exit:
store i32 %acc.next, ptr addrspace(1) %0, align 4
ret void
}}
"
)
}
/// A kernel whose body (`%0` is the buffer) ends in `ret void`.
fn kernel(name: &str, body: &str) -> String {
format!(
"define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0) {{
entry:
{body} ret void
}}
"
)
}
/// `%s` = `add nuw i<bits>` of the buffer's `0xFF..` at byte 8 and 1: poison.
fn wrapped(bits: u8) -> String {
format!(
" %ip = getelementptr inbounds i8, ptr addrspace(1) %0, i64 8
%a = load i{bits}, ptr addrspace(1) %ip, align 4
%s = add nuw i{bits} %a, 1
"
)
}
/// The `i16` 0x1234 at byte 2 (the neighbour of the field at byte 0).
const NEIGHBOUR: &str = " %hp = getelementptr inbounds i8, ptr addrspace(1) %0, i64 2
store i16 4660, ptr addrspace(1) %hp, align 2
";
const KERNELS: [&str; 9] = [
"nuw_i16_loops",
"plain_i16_loops",
"nuw_i8_loops",
"plain_i8_loops",
"frozen_wrap",
"stored_wrap_lane",
"stored_wrap_scalar",
"atomic_wrap",
"bitcast_wrap",
];
fn module() -> String {
let mut s = String::from(
"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\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n",
);
s.push_str(&loops("nuw_i16_loops", 16, "nuw"));
s.push_str(&loops("plain_i16_loops", 16, ""));
s.push_str(&loops("nuw_i8_loops", 8, "nuw"));
s.push_str(&loops("plain_i8_loops", 8, ""));
s.push_str(&kernel(
"frozen_wrap",
&format!(
"{} %f = freeze i16 %s\n %r = zext i16 %f to i32\n store i32 %r, ptr addrspace(1) %0, align 4\n",
wrapped(16)
),
));
s.push_str(&kernel(
"stored_wrap_lane",
&format!(
"{} %v = insertelement <2 x i16> <i16 0, i16 4660>, i16 %s, i32 0\n store <2 x i16> %v, ptr addrspace(1) %0, align 4\n",
wrapped(16)
),
));
s.push_str(&kernel(
"stored_wrap_scalar",
&format!(
"{NEIGHBOUR}{} store i16 %s, ptr addrspace(1) %0, align 4\n",
wrapped(16)
),
));
s.push_str(&kernel(
"atomic_wrap",
&format!(
"{NEIGHBOUR}{} %o = atomicrmw xchg ptr addrspace(1) %0, i16 %s monotonic, align 4\n",
wrapped(16)
),
));
s.push_str(&kernel(
"bitcast_wrap",
&format!(
"{} %v = insertelement <4 x i8> <i8 1, i8 0, i8 52, i8 18>, i8 %s, i32 1\n %h = bitcast <4 x i8> %v to <2 x i16>\n %e = extractelement <2 x i16> %h, i32 1\n %r = zext i16 %e to i32\n store i32 %r, ptr addrspace(1) %0, align 4\n",
wrapped(8)
),
));
let refs: Vec<String> = (0..KERNELS.len()).map(|i| format!("!{}", 20 + i)).collect();
s.push_str(&format!(
"!llvm.module.flags = !{{!0}}\n!air.kernel = !{{{}}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\n",
refs.join(", ")
));
s.push_str("!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n!10 = !{}\n!11 = !{!12}\n!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\", !\"uint\", !\"air.arg_name\", !\"buf\"}\n!17 = !{i32 2, i32 8, i32 0}\n!18 = !{!\"Metal\", i32 4, i32 0, i32 0}\n");
for (i, k) in KERNELS.iter().enumerate() {
s.push_str(&format!("!{} = !{{ptr @{k}, !10, !11}}\n", 20 + i));
}
s
}
/// Assemble the module, or `None` (skipped visibly) without `llvm-as`.
fn assemble() -> Option<Vec<u8>> {
let scratch = Scratch::new("m2v-nuw");
let ll = scratch.path().join("nuw.ll");
std::fs::write(&ll, module()).expect("write");
match llvm_assemble(&ll) {
Ok(b) => Some(b),
Err(AssembleError::Missing(t)) => {
eprintln!("SKIPPED: {t}");
None
}
Err(AssembleError::Rejected(e)) => panic!("llvm-as rejected the module: {e}"),
}
}
/// The masks to `width` bits in module `words`: `OpBitwiseAnd` with the constant `2^width - 1`,
/// and `OpBitFieldUExtract` of `width` bits from bit 0.
fn masks(words: &[u32], width: u32) -> usize {
let mut consts = std::collections::HashMap::new();
let mut ins = Vec::new();
let mut i = 5;
while i < words.len() {
let (len, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF);
assert!(len > 0 && i + len <= words.len(), "malformed module");
let a = &words[i + 1..i + len];
if op == Op::Constant as u32 && a.len() == 3 {
consts.insert(a[1], a[2]);
}
ins.push((op, a));
i += len;
}
let ones = (1u32 << width) - 1;
let is = |id: u32, v: u32| consts.get(&id) == Some(&v);
ins.iter()
.filter(|(op, a)| match *op {
o if o == Op::BitwiseAnd as u32 => a.len() == 4 && (is(a[2], ones) || is(a[3], ones)),
o if o == Op::BitFieldUExtract as u32 => a.len() == 5 && is(a[3], 0) && is(a[4], width),
_ => false,
})
.count()
}
/// Kernel `entry`'s typed module on `p`, run on the interpreter over a 16-byte buffer whose bytes
/// 8 and 9 are `0xFF`: the buffer's first word.
fn interpret(bitcode: &[u8], entry: &str, p: &crate::device::DeviceProfile) -> u32 {
let mut m = meter();
let decoded = air::decode(bitcode, &mut m).expect("decode");
let req = SpecRequest {
call_stack_depth: 1,
entry: entry.to_owned(),
..SpecRequest::default()
};
let spec = air::specialize(decoded, &req, &mut m).expect("specialize");
let memory = analyze_memory(&spec, p, &mut m).expect("memory");
let plan = select(&spec, &memory, p, &LowerInputs::new(), &mut m).expect("select");
let module = emit_module(&spec, &plan, &mut m).expect("emit").module;
let mut bytes = vec![0u8; 16];
bytes[8] = 0xFF;
bytes[9] = 0xFF;
let res = Resources {
buffers: vec![Buffer {
slot: Some(ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 0,
}),
address: None,
bytes,
}],
push: vec![0; 4],
spec: Default::default(),
};
let out = run(&module, &Config::default(), res)
.unwrap_or_else(|e| panic!("{entry}: interpreter: {e}"));
let b = out.buffers.first().expect("buffer");
u32::from_le_bytes([b[0], b[1], b[2], b[3]])
}
/// A loop counted by an `i16` or `i8` whose increment is `add nuw` exits on the add itself, with
/// no mask in the module; a plain `add` keeps its mask. Both sum the private array to 18.
#[test]
fn a_nuw_loop_counter_is_not_masked() {
let Some(bitcode) = assemble() else {
return;
};
for stem in PROFILES {
let p = profile(stem, DevicePolicy::default()).expect("profile");
for (entry, width, masked) in [
("nuw_i16_loops", 16, false),
("plain_i16_loops", 16, true),
("nuw_i8_loops", 8, false),
("plain_i8_loops", 8, true),
] {
let what = format!("{entry} on {stem}");
let a = compile(&bitcode, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let n = masks(&a.module.words, width);
assert_eq!(n > 0, masked, "{what}: {n} masks to {width} bits");
let got = interpret(&bitcode, entry, &p);
assert_eq!(got, 18, "{what}");
}
}
}
/// A poison value of a `nuw` add stays its own: a `freeze` of it is a value of `i16`, and a
/// store, an atomic exchange and a bitcast's packing of it leave the neighbouring `i16` 0x1234.
#[test]
fn a_poison_nuw_result_reaches_no_neighbour() {
let Some(bitcode) = assemble() else {
return;
};
for stem in PROFILES {
let p = profile(stem, DevicePolicy::default()).expect("profile");
for entry in [
"frozen_wrap",
"stored_wrap_lane",
"stored_wrap_scalar",
"atomic_wrap",
"bitcast_wrap",
] {
let what = format!("{entry} on {stem}");
let a = compile(&bitcode, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let got = interpret(&bitcode, entry, &p);
match entry {
"frozen_wrap" => assert!(got <= 0xFFFF, "{what}: {got:#x}"),
"bitcast_wrap" => assert_eq!(got, 0x1234, "{what}: {got:#x}"),
_ => assert_eq!(got >> 16, 0x1234, "{what}: {got:#x}"),
}
}
}
}
+1
View File
@@ -110,6 +110,7 @@ mod engine_native_maths;
mod engine_nonwritable;
mod engine_not_mipmapped_anisotropic;
mod engine_nullable_private;
mod engine_nuw;
mod engine_offset_arms;
mod engine_opencl_mode;
mod engine_padded_blends;