Arithmetic, rung 1: a narrow integer's high bits are cleared by OpBitFieldUExtract on every device

The planner's ruling (rung 1). ops::mask cleared the bits above a narrow width with
OpBitwiseAnd by the width's mask, and took OpBitFieldUExtract(x, 0, N) only on a driver whose
compiler dropped the mask after a signed clamp (MaskForm::Extract, NVIDIA 615.71.09 on Ampere
GA10x answered sign-extended words). The extract is right on every device and the fact that chose
it is gone, so it is the one form.

- lower/arith/ops.rs: mask always extracts in a 32-bit container; MaskForm, ArithPlan::mask and
  the builder's choice deleted.
- Tests: lower/arith/tests.rs's a_narrow_mask_after_a_signed_clamp_is_an_extract; rt's
  every_device_zero_extends_a_narrow_clamped_sum also asserts the translated kernel's narrow
  results are cleared by four or more extracts and no OpBitwiseAnd by a 16- or 8-bit mask.

SEMANTICS_VERSION is bumped once at the end of this follow-up batch.
This commit is contained in:
Anees Iqbal committed 2026-11-20 10:35:27 -08:00
1 parent f2e00db52c
commit e709d20810
7 files changed
+55 -84

No files matched your search

@@ -1,19 +1,22 @@
//! A narrow integer's mask over a signed clamp, under a device cfg on every device of the cfg's
//! kind: a kernel the translator compiles adds and subtracts two values sign-extended from 16 and
//! from 8 bits, clamps each result signed to exactly its width's range, truncates it and
//! zero-extends it. The runtime's profile keeps the plain mask on every device, so a driver whose
//! compiler drops that mask after the clamp (NVIDIA 615.71.09 on Ampere GA10x did; 620.70.06 does
//! not) answers sign-extended words and fails here.
//! zero-extends it. On every device the module clears the bits above each width with
//! `OpBitFieldUExtract(x, 0, N)`, never `OpBitwiseAnd` by the width's mask, which a driver's
//! compiler dropped after the clamp (NVIDIA 615.71.09 on Ampere GA10x answered sign-extended words;
//! 620.70.06 does not), and every word is zero-extended.
//!
//! `llvm-as` assembles the kernel; without it the test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::tests::spirv_instructions;
use crate::{
ComputePipelineDescriptor, DispatchType, FunctionDescriptor, Library, MemoryClass,
StageSource,
};
use metal2vulkan::Budget;
use metal2vulkan_devtools::{llvm_assemble_text, AssembleError};
/// The edge values, as words: each lane reads its low 16 or 8 bits.
@@ -132,7 +135,29 @@ entry:
]
}
/// The kernel, translated, answers every word zero-extended on every device.
/// The extracts of `words` (`OpBitFieldUExtract`), and its `OpBitwiseAnd`s by a constant
/// 16-bit or 8-bit mask.
fn masks(words: &[u32]) -> (usize, usize) {
const CONSTANT: u32 = 43;
const BITWISE_AND: u32 = 199;
const BIT_FIELD_U_EXTRACT: u32 = 203;
let mut narrow = std::collections::BTreeSet::new();
let (mut extracts, mut ands) = (0, 0);
for inst in spirv_instructions(words) {
match inst[0] & 0xffff {
CONSTANT if inst.len() == 4 && [0xffff, 0xff].contains(&inst[3]) => {
narrow.insert(inst[2]);
}
BIT_FIELD_U_EXTRACT => extracts += 1,
BITWISE_AND if inst[3..5].iter().any(|v| narrow.contains(v)) => ands += 1,
_ => {}
}
}
(extracts, ands)
}
/// The kernel, translated, clears its narrow results' high bits by extracts and answers every
/// word zero-extended on every device.
#[test]
fn every_device_zero_extends_a_narrow_clamped_sum() {
let bitcode = match llvm_assemble_text(KERNEL) {
@@ -150,6 +175,12 @@ entry:
));
let out_len = u64::from(THREADS * WORDS * 4);
each_device("narrow_clamps", |name, _, device| {
let pipeline = (device.core().translator)
.compile_compute_pipeline(&descriptor, &Budget::standard())
.unwrap_or_else(|error| panic!("{name}: {error}"));
let (extracts, ands) = masks(&pipeline.stage.spirv);
assert!(extracts >= 4, "{name}: {extracts} extracts");
assert_eq!(ands, 0, "{name}: masks by a narrow width's bits");
let state = device
.new_compute_pipeline_state(&descriptor, crate::tests::no_constexpr_samplers)
.unwrap_or_else(|error| panic!("{name}: {error}"));
+2 -18
View File
@@ -109,7 +109,7 @@ use crate::lower::emit::EmitCx;
use crate::lower::select::{FamilyPlans, Plan, SelectCx};
use crate::lower::strategy::FamilyStrategy;
use crate::pipeline::artifact::{EntryMath, PrecisionNote};
use crate::spirv::builder::{FunctionBuilder, MaskForm, ModuleBuilder, ProductForm, QuantizeForm};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, ProductForm, QuantizeForm};
use crate::spirv::error::BResult;
use crate::spirv::ids::{DemoteTy, FuncId, TypeId, Value as SValue};
use crate::spirv::ir::{Contraction, ExecMode, UnOp};
@@ -725,11 +725,6 @@ pub struct ArithPlan {
/// `-0.0` addend for it to answer. In either form a constant factor's `-0.0` components are
/// multiplied as `+0.0` and negated (`FunctionBuilder::binary`).
pub product: ProductForm,
/// How the module clears the bits above a narrow integer's width in a 32-bit container
/// ([`ops::mask`]), decided by [`finish`] from the profile's driver workarounds:
/// `OpBitFieldUExtract` on a driver whose compiler drops the mask after a signed clamp
/// (`DriverWorkaround::NarrowMaskAfterSignedClamp`), else the mask.
pub mask: MaskForm,
/// Whether a function converts the texels of a slot or attachment bound in an extended-range,
/// padded or bfloat form ([`ArithPlan::converts`]) by the device's arithmetic
/// ([`extended_range`]): [`finish`] then records `PrecisionNote::DevicePackConversion`.
@@ -836,8 +831,7 @@ pub const FAST_DIVIDE: &str = "arith.fdiv.fast";
/// entry Metal compiles with precise functions, [`libm::module_mode`]), record the notes of the
/// operations that are Metal's own in a fast-math entry only where it is not
/// ([`ArithPlan::unless_metal_fast`]), and choose the form of a multiply the device must round on
/// its own by the same fact ([`ArithPlan::product`]), and the form of
/// a narrow integer's mask by the driver's workarounds ([`ArithPlan::mask`]).
/// its own by the same fact ([`ArithPlan::product`]).
pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
cx.families.arith.wide = legal::holds_wide(cx.profile);
cx.families.arith.quantize = narrow::quantize_form(cx.profile);
@@ -849,16 +843,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
if cx.families.arith.extended_range {
cx.precision.insert(PrecisionNote::DevicePackConversion);
}
cx.families.arith.mask = if cx
.profile
.fields()
.workarounds
.contains(&DriverWorkaround::NarrowMaskAfterSignedClamp)
{
MaskForm::Extract
} else {
MaskForm::And
};
let fc = cx.profile.fields().float_controls;
let widths: Vec<u8> = cx.families.arith.preserve.iter().copied().collect();
for w in widths {
+6 -5
View File
@@ -7,7 +7,7 @@
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};
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::{BResult, BuildError, TypeRule};
use crate::spirv::ids::{TypeId, Value};
use crate::spirv::ir::{BinOp, ConstBits, Constant, Contraction, ConvOp, GlslOp, Type, UnOp};
@@ -127,14 +127,15 @@ pub fn fsplat(fb: &mut FunctionBuilder<'_>, f: Form, x: f64) -> BResult<Value> {
splat(fb, f, f.const_bits(x))
}
/// `x` with the bits above its AIR width cleared (a no-op for a full-width integer): `x & (2^N -
/// 1)`, or in a 32-bit container under [`MaskForm::Extract`] `OpBitFieldUExtract(x, 0, N)`, the
/// same bits, for a driver whose compiler drops the mask after a signed clamp.
/// `x` with the bits above its AIR width cleared (a no-op for a full-width integer): in a 32-bit
/// container `OpBitFieldUExtract(x, 0, N)`, on every device, else `x & (2^N - 1)`, the same bits.
/// No driver can drop the extract as one did the mask after a signed clamp to exactly the narrow
/// range (NVIDIA 615.71.09 on Ampere GA10x answered the clamp's sign-extended words).
pub fn mask(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
if !f.legalized() {
return Ok(x);
}
if f.container() == 32 && fb.module().mask_form() == MaskForm::Extract {
if f.container() == 32 {
let u32_ = Form {
held: Held::Int {
bits: 32,
+11 -25
View File
@@ -22,7 +22,7 @@ use super::ops::{self, BitcastPlan, CastKind};
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};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, ProductForm, QuantizeForm};
use crate::spirv::error::BResult;
use crate::spirv::ids::{FuncId, GlobalId, TypeId, Value};
use crate::spirv::interp::{run, Buffer, Config, Resources};
@@ -1946,31 +1946,25 @@ fn signed_narrow_saturation_clamps_without_signed_min_or_max() {
}
}
/// Under [`MaskForm::Extract`], the form a driver with
/// `DriverWorkaround::NarrowMaskAfterSignedClamp` takes (the RTX 3090), a narrow integer's mask
/// in a 32-bit container is `OpBitFieldUExtract(x, 0, N)` and never `OpBitwiseAnd`, and the
/// source-arithmetic shape whose mask that driver drops answers its definition at every edge:
/// two values sign-extended from `N` bits, added or subtracted, clamped signed to exactly `N`
/// bits' range (`SClamp`, and `SMin` then `SMax`), truncated to `N` bits. At 8 and 16 bits, scalar
/// and three lanes. Under [`MaskForm::And`] the same body keeps the mask and emits no extract.
/// A narrow integer's mask in a 32-bit container is `OpBitFieldUExtract(x, 0, N)` and never
/// `OpBitwiseAnd`, and the source-arithmetic shape whose mask a driver dropped (NVIDIA 615.71.09
/// on Ampere GA10x) answers its definition at every edge: two values sign-extended from `N` bits,
/// added or subtracted, clamped signed to exactly `N` bits' range (`SClamp`, and `SMin` then
/// `SMax`), truncated to `N` bits. At 8 and 16 bits, scalar and three lanes.
#[test]
fn a_narrow_mask_after_a_signed_clamp_is_an_extract_under_the_workaround() {
fn a_narrow_mask_after_a_signed_clamp_is_an_extract() {
let mut rng = Rng(0x0D0D_0D0E);
for bits in [8u8, 16] {
let vals = int_values(bits, &mut rng, 3);
for lanes in [1u8, 3] {
let f = vec(int(bits), lanes);
let wide = vec(int(32), lanes);
for (sub, chained, form) in [false, true]
for (sub, chained) in [false, true]
.into_iter()
.flat_map(|sub| [false, true].map(|chained| (sub, chained)))
.flat_map(|(sub, chained)| {
[MaskForm::And, MaskForm::Extract].map(|form| (sub, chained, form))
})
{
let what = format!("i{bits} x{lanes} sub {sub} chained {chained} {form:?}");
let what = format!("i{bits} x{lanes} sub {sub} chained {chained}");
let body = |fb: &mut FunctionBuilder<'_>, xs: &[Value]| -> BResult<Value> {
fb.module().set_mask_form(form);
let a = ops::cast(fb, CastKind::SExt, f, wide, xs[0])?;
let b = ops::cast(fb, CastKind::SExt, f, wide, xs[1])?;
let op = if sub { BinOp::ISub } else { BinOp::IAdd };
@@ -2002,16 +1996,8 @@ fn a_narrow_mask_after_a_signed_clamp_is_an_extract_under_the_workaround() {
)
})
.count();
match form {
MaskForm::Extract => {
assert!(extracts > 0, "{what}: no extract");
assert_eq!(ands, 0, "{what}: a mask");
}
MaskForm::And => {
assert!(ands > 0, "{what}: no mask");
assert_eq!(extracts, 0, "{what}: an extract");
}
}
assert!(extracts > 0, "{what}: no extract");
assert_eq!(ands, 0, "{what}: a mask");
let usize_lanes = usize::from(lanes);
let mut cases: Vec<Case> = Vec::new();
for (i, x) in vals.iter().enumerate() {
-2
View File
@@ -102,8 +102,6 @@ fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult<Declared> {
// Before any instruction: every multiply the device must round on its own takes the
// profile's form.
mb.product_form(plan.families.arith.product);
// And every narrow integer's mask the driver's form.
mb.set_mask_form(plan.families.arith.mask);
// And every `half` rounding's quantize the device's form.
mb.set_quantize_form(plan.families.arith.quantize);
mb.set_native_half(plan.families.arith.native_half);
+1 -1
View File
@@ -11,7 +11,7 @@ pub mod ops;
pub use function::FunctionBuilder;
pub(crate) use module::{geometry_per_vertex, mesh_arrayed, mesh_per_primitive};
pub use module::{MaskForm, ModuleBuilder, NarrowFmt, ProductForm, QuantizeForm};
pub use module::{ModuleBuilder, NarrowFmt, ProductForm, QuantizeForm};
#[cfg(test)]
mod tests;
@@ -172,9 +172,6 @@ pub struct ModuleBuilder {
/// How a float multiply the device must round on its own is emitted
/// ([`ModuleBuilder::product_form`]).
pub(super) product_form: ProductForm,
/// How the lowering clears the bits above a narrow integer's width
/// ([`ModuleBuilder::mask_form`]).
mask_form: MaskForm,
/// How the lowering rounds an `f32` to `half` ([`ModuleBuilder::quantize_form`]).
quantize_form: QuantizeForm,
/// Whether that rounding is the device's own rather than one measured to be Metal's
@@ -209,19 +206,6 @@ pub enum ProductForm {
NegativeZeroFma,
}
/// How the lowering clears the bits above a narrow integer's width `N` in a 32-bit container
/// (`lower::arith::ops::mask`). Lowering takes it from the profile's driver workarounds
/// (`ArithPlan::mask`). Both forms are the same bits on every device.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MaskForm {
/// `OpBitwiseAnd` with `2^N - 1`.
#[default]
And,
/// `OpBitFieldUExtract(x, 0, N)`, for a driver whose compiler drops the mask after a signed
/// clamp to exactly the narrow range (`DriverWorkaround::NarrowMaskAfterSignedClamp`).
Extract,
}
/// How the lowering rounds an `f32` to `half` (`lower::arith::narrow`): the device's own
/// rounding. Lowering takes it from the profile's `shaderFloat16` and float-controls properties
/// (`ArithPlan::quantize`). `Controlled` gives Metal's conversion to `half` (to nearest even on the
@@ -296,19 +280,6 @@ impl ModuleBuilder {
self.product_form = form;
}
/// Clear the bits above a narrow integer's width in `form`. Emission sets it before any
/// instruction, from the profile's driver workarounds; a builder that never sets it emits
/// [`MaskForm::And`].
pub fn set_mask_form(&mut self, form: MaskForm) {
self.mask_form = form;
}
/// How the lowering clears the bits above a narrow integer's width
/// ([`ModuleBuilder::set_mask_form`]).
pub fn mask_form(&self) -> MaskForm {
self.mask_form
}
/// Round an `f32` to `half` in `form`. Emission sets it before any instruction, from the
/// profile; a builder that never sets it emits [`QuantizeForm::Device`].
pub fn set_quantize_form(&mut self, form: QuantizeForm) {