diff --git a/crates/metal2vulkan-air/src/canon/fold.rs b/crates/metal2vulkan-air/src/canon/fold.rs index 6f9473c1f..2f247d9c4 100644 --- a/crates/metal2vulkan-air/src/canon/fold.rs +++ b/crates/metal2vulkan-air/src/canon/fold.rs @@ -8,8 +8,9 @@ //! access on constant vectors and aggregates. SCCP does **no float arithmetic folding**: the //! device's denormal and fast-math behavior is the lowering's contract. It reads what a float //! constant is ([`Folder::float_class`]) for the answers an operation's constant operand decides -//! whatever the others hold: a NaN operand, quieted ([`Folder::quiet_nan`]), and a product's -//! `+0` under `nnan` and `nsz` ([`Folder::float_zero`]). Anything else, and any +//! whatever the others hold: a NaN operand, as it is beside a value only the run knows and quieted +//! ([`Folder::quiet_nan`]) where every operand is a constant, and a product's `+0` under `nnan` +//! and `nsz` ([`Folder::float_zero`]). Anything else, and any //! operation whose result would be poison (division by zero, an oversized shift, an out-of-range //! element), is left unfolded. A fold never guesses: `None` means "not a constant here". //! @@ -468,10 +469,11 @@ impl Folder<'_> { self.mk(ty, Const::Float(bits), m).map(Some) } - /// What the float constant `c` is to SCCP's float folds: a scalar, or a vector each lane of - /// which is, a zero of either sign (`zeroinitializer` included) or a NaN. A vector of mixed - /// lanes, or with an `undef` or `poison` lane, is [`FloatClass::Other`], as is anything not a - /// float constant. + /// What the float constant `c` is to SCCP's float folds: a zero of either sign (a scalar, a + /// vector each lane of which is one, `zeroinitializer` included), or a NaN (a scalar, or a + /// vector each lane of which is a NaN or `poison`, at least one a NaN, as LLVM's `m_NaN` + /// matches it). Anything else is [`FloatClass::Other`]: a vector of mixed lanes, one with an + /// `undef` lane, or a zero with a `poison` lane, and anything not a float constant. pub fn float_class(&self, c: ConstId, m: &mut Meter) -> Result { let Some(ty) = self.ty(c) else { return Ok(FloatClass::Other); @@ -485,20 +487,32 @@ impl Folder<'_> { } (Some(Type::Vector { .. }), Some(Const::Aggregate(lanes))) => { m.tick(u32::try_from(lanes.len()).unwrap_or(u32::MAX))?; - let mut class = None; + let (mut zeros, mut nans) = (0, 0); for &lane in lanes.iter() { - let this = self.scalar_class(lane); - if this == FloatClass::Other || class.is_some_and(|c| c != this) { - return Ok(FloatClass::Other); + match self.scalar_class(lane) { + FloatClass::Zero => zeros += 1, + FloatClass::Nan => nans += 1, + FloatClass::Other if self.poison(lane) => {} + FloatClass::Other => return Ok(FloatClass::Other), } - class = Some(this); } - Ok(class.unwrap_or(FloatClass::Other)) + Ok(if zeros == lanes.len() { + FloatClass::Zero + } else if nans > 0 && zeros == 0 { + FloatClass::Nan + } else { + FloatClass::Other + }) } _ => Ok(self.scalar_class(c)), } } + /// Whether `c` is `poison`. + fn poison(&self, c: ConstId) -> bool { + matches!(self.value(c), Some(Const::Poison)) + } + /// [`Folder::float_class`] of a scalar. fn scalar_class(&self, c: ConstId) -> FloatClass { let Some((width, mant)) = self @@ -524,9 +538,9 @@ impl Folder<'_> { } } - /// The NaN constant `c` (a scalar, or a vector each lane of which is one), each NaN quieted: - /// its sign and payload kept and its quiet bit, the top mantissa bit, set. LLVM's - /// `propagateNaN` of a NaN operand. + /// The NaN constant `c` ([`FloatClass::Nan`]) with each NaN quieted, its sign and payload kept + /// and its quiet bit, the top mantissa bit, set; a `poison` lane stays `poison`. What constant + /// folding of an operation whose every operand is a constant makes of its first NaN operand. pub fn quiet_nan(&mut self, c: ConstId, m: &mut Meter) -> Result, Error> { self.transient(m, |f, m| f.quiet_nan_in(c, m)) } @@ -543,6 +557,10 @@ impl Folder<'_> { }; let mut quiet = Vec::with_capacity(lanes.len()); for lane in lanes { + if self.poison(lane) { + quiet.push(lane); + continue; + } match self.quiet_scalar(lane, m)? { Some(q) => quiet.push(q), None => return Ok(None), diff --git a/crates/metal2vulkan-air/src/canon/sccp.rs b/crates/metal2vulkan-air/src/canon/sccp.rs index c5e024b89..c25bcaf69 100644 --- a/crates/metal2vulkan-air/src/canon/sccp.rs +++ b/crates/metal2vulkan-air/src/canon/sccp.rs @@ -20,15 +20,16 @@ //! reads of an undefined constant vary from read to read, zero and the false way among them; its //! predicate gates nothing, whether negated or not (Metal probes). //! - A float operation a constant operand decides, whatever the run computes for the others, is -//! that constant, as LLVM's simplification of the operation decides it but for its poison step +//! that constant, as Metal's compiler decides it once the constants are bound //! ([`Solver::float_fold`]): an `fadd`, `fsub`, `fmul`, `fdiv` or `air.fma` with a NaN operand -//! (every lane a NaN) is the first such operand, quieted, and an `fmul` under `nnan` and `nsz` -//! with an operand every lane of which is a zero is `+0`. SCCP computes no float arithmetic: -//! these are the answers no operand the run computes can change. Metal answers so once the -//! operand is a bound function constant: a NaN, and `+0` for a NaN or an infinity times a zero, -//! on the Apple M3 Max, the AMD Radeon Pro 5300M and the Intel UHD Graphics 630 (macOS 27.0.1), -//! the M3's NaN the operand's, quieted. A device given the operation itself answers otherwise: -//! MoltenVK 1.4.2 `0` for a quotient by a NaN, and MoltenVK and RADV a NaN for the products. +//! (every lane a NaN or `poison`) is the first such operand, as it is beside a value only the +//! run knows and quieted where every operand is a constant, and an `fmul` under `nnan` and +//! `nsz` with an operand every lane of which is a zero is `+0`. SCCP computes no float +//! arithmetic: these are the answers no operand the run computes can change. Under `nnan` such a +//! NaN makes the AIR's value `poison`, which any answer refines; the NaN is Metal's answer for +//! a fragment's output (the Apple M3 Max, the AMD Radeon Pro 5300M and the Intel UHD Graphics +//! 630, macOS 27.0.1), where a device given the operation answers otherwise (MoltenVK 1.4.2 `0` +//! for a quotient by a NaN, MoltenVK and RADV a NaN for an infinity or a NaN times a zero). //! //! Afterwards unreachable blocks are deleted, branches on constants become unconditional, PHIs //! keep one entry per remaining edge, and instructions with a constant value are replaced by it. @@ -898,12 +899,13 @@ impl<'b> Solver<'b> { /// A float operation over `ops` (`fadd`, `fsub`, `fmul`, `fdiv`, or `air.fma`; `product` for /// `fmul`) with the fast-math flags `fmf`, typed `ty`, decided by its constant operands - /// whatever the others hold, as LLVM simplifies the operation (`simplifyFPOp`, - /// `simplifyFMAFMul`) but for its poison step: an operand that is a NaN, the first in operand - /// order, is the result, quieted; then a product under `nnan` and `nsz` with an operand each - /// lane of which is a zero of either sign is `+0`. `Top` while an operand before the deciding - /// one is unknown. `None` where no operand decides it, and wherever one is an unsupplied - /// constant's undefined value, which keeps its own reading. + /// whatever the others hold, as Metal's compiler decides it once the constants are bound. A NaN + /// operand, the first in operand order, is the result: as it is beside an operand only the run + /// knows (LLVM's `propagateNaN` as Metal's compiler has it, with no poison step for `nnan`), + /// and quieted where every operand is a constant (constant folding). Otherwise a product under + /// `nnan` and `nsz` with an operand each lane of which is a zero of either sign is `+0`. `Top` + /// while an operand is unknown. `None` where no operand decides it, and wherever one is an + /// unsupplied constant's undefined value, which keeps its own reading. fn float_fold( &self, (product, fmf): (bool, FastMath), @@ -912,21 +914,27 @@ impl<'b> Solver<'b> { cx: &mut Context<'_>, m: &mut Meter, ) -> Result, Error> { - if ops.iter().any(|&v| matches!(self.lat(v), Lat::Fc(_))) { - return Ok(None); - } - let mut zero = false; + let (mut nan, mut zero, mut run) = (None, false, false); for &v in ops { match self.lat(v) { + Lat::Fc(_) => return Ok(None), Lat::Top => return Ok(Some(Lat::Top)), + Lat::Bottom => run = true, Lat::Const(k) => match cx.folder.float_class(k, m)? { - FloatClass::Nan => return Ok(cx.folder.quiet_nan(k, m)?.map(Lat::Const)), + FloatClass::Nan => { + nan.get_or_insert(k); + } FloatClass::Zero => zero = true, FloatClass::Other => {} }, - Lat::Fc(_) | Lat::Bottom => {} } } + if let Some(k) = nan { + if run { + return Ok(Some(Lat::Const(k))); + } + return Ok(cx.folder.quiet_nan(k, m)?.map(Lat::Const)); + } if product && zero && fmf.contains(FastMath::NNAN) && fmf.contains(FastMath::NSZ) { return Ok(Some(Lat::Const(cx.folder.float_zero(ty, m)?))); } diff --git a/crates/metal2vulkan-air/src/canon/tests/float_folds.rs b/crates/metal2vulkan-air/src/canon/tests/float_folds.rs index ddba6955e..cfb4f7b47 100644 --- a/crates/metal2vulkan-air/src/canon/tests/float_folds.rs +++ b/crates/metal2vulkan-air/src/canon/tests/float_folds.rs @@ -1,7 +1,8 @@ //! SCCP's float folds: a float operation a bound function constant decides whatever its other -//! operands hold. A NaN operand, the first in operand order, is the result, quieted with its sign -//! and payload kept; then a product under `nnan` and `nsz` with a zero operand of either sign is -//! `+0`. No other float operation folds. +//! operands hold. A NaN operand, the first in operand order, is the result: as it is beside a value +//! only the run knows, quieted with its sign and payload kept where every operand is a constant. +//! Otherwise a product under `nnan` and `nsz` with a zero operand of either sign is `+0`. No other +//! float operation folds. use super::*; use crate::intrinsics::{Math, MathFn, Precision}; @@ -14,13 +15,16 @@ enum Op { Fma, } -/// An operand: function constant `n`, or a value only the run knows (the buffer's). +/// An operand: function constant `n`; its lane 0 alone in a vector whose other lanes are `poison` +/// (an `insertelement` into `poison` of its `extractelement`, as Metal's compiler spells an +/// operation of two splatted constants); or a value only the run knows (the buffer's). #[derive(Clone, Copy)] enum Operand { Fc(usize), + Lane0(usize), Run, } -use Operand::{Fc, Run}; +use Operand::{Fc, Lane0, Run}; /// The value type: `half` or `float`, of `lanes` lanes (1 for a scalar). #[derive(Clone, Copy)] @@ -44,13 +48,13 @@ const F16X4: Shape = Shape { /// A kernel storing `op` over `operands` to its buffer, which it also reads the run's operand /// from, specialized with function constant `n` holding the lanes `constants[n]`. The stored -/// lanes where the operation folded, `None` where it survives. +/// lanes where the operation folded (`None` for a `poison` lane), `None` where it survives. fn folded( shape: Shape, (op, fmf): (Op, FastMath), operands: &[Operand], constants: &[&[u64]], -) -> Option> { +) -> Option>> { let mut m = ModuleBuilder::new(); let void = m.void(); let dev = m.ptr(AddrSpace::Device); @@ -74,6 +78,9 @@ fn folded( } Op::Bin(_) => None, }; + let i32t = m.int(32); + let lane0 = m.const_int(i32t, 0); + let poison = Value::Const(m.constant(ty, Const::Poison)); let fty = m.fn_ty(void, &[dev]); let mut f = m.define("k", fty); let run = load(&mut f, ty, arg(0)); @@ -81,6 +88,18 @@ fn folded( .iter() .map(|&o| match o { Fc(n) => load(&mut f, ty, addrs[n]), + Lane0(n) => { + let vec = load(&mut f, ty, addrs[n]); + let elt = f.push(elem, InstKind::ExtractElement { vec, idx: lane0 }); + f.push( + ty, + InstKind::InsertElement { + vec: poison, + elt, + idx: lane0, + }, + ) + } Run => run, }) .collect(); @@ -158,7 +177,36 @@ fn folded( .insts .values() .any(|i| matches!(i.kind, InstKind::BinOp { .. } | InstKind::Call(_))); - (!survives).then(|| stored_lanes(&e)) + if survives { + return None; + } + let c = body + .insts + .values() + .find_map(|i| match i.kind { + InstKind::Store { + val: Value::Const(c), + .. + } => Some(c), + _ => None, + }) + .unwrap(); + let lane = |k| match parts.consts.get(k).unwrap().value { + Const::Float(x) => Some(x), + Const::Null => Some(0), + Const::Poison => None, + ref v => panic!("{v:?}"), + }; + Some(match &parts.consts.get(c).unwrap().value { + Const::Aggregate(lanes) => lanes.iter().map(|&k| lane(k)).collect(), + Const::Null => vec![Some(0); shape.lanes as usize], + _ => vec![lane(c)], + }) +} + +/// Every lane `bits`. +fn all(lanes: u32, bits: u64) -> Option>> { + Some(vec![Some(bits); lanes as usize]) } const FAST: FastMath = FastMath::NNAN @@ -180,26 +228,23 @@ fn fmul(fmf: FastMath) -> (Op, FastMath) { fn a_product_by_a_bound_zero_under_nnan_and_nsz_is_positive_zero() { for zero in [0, NEG_ZERO] { for operands in [[Run, Fc(0)], [Fc(0), Run]] { - assert_eq!( - folded(F32, fmul(FAST), &operands, &[&[zero]]), - Some(vec![0]) - ); + assert_eq!(folded(F32, fmul(FAST), &operands, &[&[zero]]), all(1, 0)); } } let nnan_nsz = FastMath::NNAN.union(FastMath::NSZ); assert_eq!( folded(F32, fmul(nnan_nsz), &[Run, Fc(0)], &[&[NEG_ZERO]]), - Some(vec![0]) + all(1, 0) ); - // Each lane a zero of either sign; `zeroinitializer` is `+0` in every lane. + // Each lane a zero of either sign. let zeros = [0, NEG_ZERO, 0, NEG_ZERO]; assert_eq!( folded(F32X4, fmul(FAST), &[Run, Fc(0)], &[&zeros]), - Some(vec![0]) + all(4, 0) ); assert_eq!( folded(F16X4, fmul(FAST), &[Fc(0), Run], &[&[0x8000; 4]]), - Some(vec![0]) + all(4, 0) ); } @@ -213,6 +258,11 @@ fn a_product_by_a_zero_needs_both_nnan_and_nsz_and_every_lane_zero() { folded(F32X4, fmul(FAST), &[Run, Fc(0)], &[&[0, one, 0, 0]]), None ); + // A zero beside `poison` lanes. + assert_eq!( + folded(F32X4, fmul(FAST), &[Run, Lane0(0)], &[&[0; 4]]), + None + ); // A zero decides no other operation. for op in [BinOp::FAdd, BinOp::FSub, BinOp::FDiv] { assert_eq!( @@ -227,52 +277,71 @@ fn a_product_by_a_zero_needs_both_nnan_and_nsz_and_every_lane_zero() { } #[test] -fn a_nan_operand_is_the_result_quieted_with_its_sign_and_payload() { - let quiet_snan = 0x7fc0_0321; +fn a_nan_beside_a_run_value_is_the_result_as_it_is() { for op in [BinOp::FAdd, BinOp::FSub, BinOp::FMul, BinOp::FDiv] { for fmf in [FAST, FastMath::NONE] { for operands in [[Run, Fc(0)], [Fc(0), Run]] { - let op = (Op::Bin(op), fmf); - assert_eq!(folded(F32, op, &operands, &[&[QNAN]]), Some(vec![QNAN])); - assert_eq!( - folded(F32, op, &operands, &[&[SNAN]]), - Some(vec![quiet_snan]) - ); + for nan in [QNAN, SNAN] { + let op = (Op::Bin(op), fmf); + assert_eq!(folded(F32, op, &operands, &[&[nan]]), all(1, nan)); + } } } } for operands in [[Fc(0), Run, Run], [Run, Run, Fc(0)]] { - assert_eq!( - folded(F32, (Op::Fma, FAST), &operands, &[&[SNAN]]), - Some(vec![quiet_snan]) - ); + for fmf in [FAST, FastMath::NONE] { + assert_eq!( + folded(F32, (Op::Fma, fmf), &operands, &[&[SNAN]]), + all(1, SNAN) + ); + } } // Lane by lane in a vector, each lane its own NaN. let nans = [0x7d01, 0xfe00, 0x7c01, 0xffff]; + let fadd = (Op::Bin(BinOp::FAdd), FAST); assert_eq!( - folded(F16X4, (Op::Bin(BinOp::FAdd), FAST), &[Run, Fc(0)], &[&nans]), - Some(vec![0x7f01, 0xfe00, 0x7e01, 0xffff]) + folded(F16X4, fadd, &[Run, Fc(0)], &[&nans]), + Some(nans.map(Some).to_vec()) ); } #[test] -fn the_first_nan_operand_in_order_decides() { - let fadd = (Op::Bin(BinOp::FAdd), FAST); +fn a_nan_among_constants_alone_is_the_first_one_quieted() { + let quiet_snan = 0x7fc0_0321; + for op in [BinOp::FAdd, BinOp::FSub, BinOp::FMul, BinOp::FDiv] { + let op = (Op::Bin(op), FAST); + assert_eq!( + folded(F32, op, &[Fc(0), Fc(1)], &[&[QNAN], &[SNAN]]), + all(1, QNAN) + ); + assert_eq!( + folded(F32, op, &[Fc(1), Fc(0)], &[&[QNAN], &[SNAN]]), + all(1, quiet_snan) + ); + } assert_eq!( - folded(F32, fadd, &[Fc(0), Fc(1)], &[&[QNAN], &[SNAN]]), - Some(vec![QNAN]) - ); - assert_eq!( - folded(F32, fadd, &[Fc(1), Fc(0)], &[&[QNAN], &[SNAN]]), - Some(vec![0x7fc0_0321]) + folded( + F32, + (Op::Fma, FAST), + &[Fc(1), Fc(0), Fc(0)], + &[&[QNAN], &[SNAN]] + ), + all(1, quiet_snan) ); // Before a product's zero. for operands in [[Fc(0), Fc(1)], [Fc(1), Fc(0)]] { assert_eq!( - folded(F32, fmul(FAST), &operands, &[&[0], &[QNAN]]), - Some(vec![QNAN]) + folded(F32, fmul(FAST), &operands, &[&[0], &[SNAN]]), + all(1, quiet_snan) ); } + // Lane 0 of each constant beside `poison` lanes, which stay `poison`. + let fadd = (Op::Bin(BinOp::FAdd), FAST); + let (q, s) = ([QNAN; 4], [SNAN; 4]); + assert_eq!( + folded(F32X4, fadd, &[Lane0(1), Lane0(0)], &[&q, &s]), + Some(vec![Some(quiet_snan), None, None, None]) + ); } #[test]