From 12cd7bc987bf14132b8feceadd9d237889cc10f0 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 22:32:13 -0800 Subject: [PATCH] Translator: mul24 and mad24 are the 32-bit product of their operands' low 24 bits A guest's screen-sharing encoder makes a compute pipeline whose kernel calls air.mul24.u.i32, and the translator refused it as UnknownIntrinsic. The guest's module declares four of the family (air.mul24 and air.mad24, s and u, of i32); Apple's compiler spells sixteen (air.{mul24,mad24}.{s,u}.{i32,v2i32,v3i32,v4i32}, m3-max-82233). All sixteen decode now. The Metal Shading Language specification (4.1, section 6.4, Table 6.2): mul24 "multiplies two 24-bit integer values x and y and returns the 32-bit integer result. x and y are 32-bit integers but only the low 24 bits perform the multiplication"; mad24 "uses mul24 ... adds the 32-bit integer result to the 32-bit integer z". Below the table the product is defined for x and y in [-2^23, 2^23 - 1] signed and [0, 2^24 - 1] unsigned and implementation-defined outside them. The Apple M3 Max (macOS 27.0.1) answers outside that range too with the product of the operands' low 24 bits, zero-extended for u and sign-extended for s: 480 of 480 words of int24-products-outside-24-bits, where the 32-bit product of the whole operands differs at 386 (m3-max-82247). That outside-range equality is measured on the M3 only. Now: - intrinsics::math decodes air.mul24.. and air.mad24.. as MathFn::Mul24 and MathFn::Mad24, for T i32 or a vector of it; any other element width stays undecoded. - canon::routine replaces each call, after SCCP as it does OpenCL C's mad, by plain AIR in T's shape: each operand's low 24 bits (and 0xffffff for u; shl 8 then ashr 8 for s), their 32-bit mul, and for mad24 the 32-bit add of c, all without nsw or nuw. One form on every device and no precision note: it is the table's own wording, and it equals Metal at every word measured. - Lowering takes them as it takes any such instructions; a Mul24 or Mad24 call that survived canonicalization is an invariant failure, as a mad call is. Tests: mul24_and_mad24_decode_on_32_bit_lanes_alone (the sixteen names; i16, i64, i8 lanes, a float, no sign and a prefix stay unknown). The arith sweep's five mul24 and mad24 kernels (cc5adc7e7c), the int24_products inventory rows (617853c57b) and its two validation cases (7fcd661645) are the red tests this turns green. --- crates/metal2vulkan-air/src/canon/mod.rs | 3 +- crates/metal2vulkan-air/src/canon/routine.rs | 73 ++++++++++++++++--- .../metal2vulkan-air/src/intrinsics/math.rs | 22 ++++++ .../metal2vulkan-air/src/intrinsics/tests.rs | 46 ++++++++++++ crates/metal2vulkan/src/lower/arith/mod.rs | 8 +- 5 files changed, 138 insertions(+), 14 deletions(-) diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index b7aa34ea7..024327736 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -806,7 +806,8 @@ pub fn specialize_dynamic( // The AIR 2.7 simdgroup-matrix block loads and stores in their AIR 2.8 form. let body = legacy_matrix::expand(body, &mut parts, m)?; // Metal runtime routines: each `frexp` and `ilogb` call becomes the routine's measured answer - // in plain AIR, and each OpenCL C `mad` call its multiply and addition. + // in plain AIR, each OpenCL C `mad` call its multiply and addition, and each `mul24` and + // `mad24` call the 32-bit product of its operands' low 24 bits (and the addition). let body = routine::expand(body, &mut parts, m)?; // Aggregate loads and stores of buffer and threadgroup memory as their members' accesses. let body = aggregates::expand(body, &mut parts, func, m)?; diff --git a/crates/metal2vulkan-air/src/canon/routine.rs b/crates/metal2vulkan-air/src/canon/routine.rs index 85dc83822..268eace91 100644 --- a/crates/metal2vulkan-air/src/canon/routine.rs +++ b/crates/metal2vulkan-air/src/canon/routine.rs @@ -1,4 +1,4 @@ -//! Metal runtime routines, and OpenCL C's `mad`, as plain AIR. +//! Metal runtime routines, OpenCL C's `mad`, and `mul24` and `mad24`, as plain AIR. //! //! Apple's compiler emits MSL's `frexp` and `ilogb` as calls to routines its backend defines at //! pipeline creation, `___metal_frexp__pthread(T x, thread I *e)` and @@ -36,10 +36,19 @@ //! with no fast-math flags, whatever the call's own: each is rounded on its own and neither is //! fused, as the M3 Max answers `mad` (`intrinsics::math`'s module doc). Lowering takes them as it //! takes any such pair. +//! +//! **`mul24` and `mad24`.** [`expand`] replaces each `air.mul24` and `air.mad24` call +//! ([`MathFn::Mul24`], [`MathFn::Mad24`]) by the 32-bit `mul` of its operands' low 24 bits, each +//! zero-extended (`and` with `0xffffff`) for `u` or sign-extended (`shl` and then `ashr` by 8) for +//! `s`, and for `mad24` the 32-bit `add` of that product and `c`, in `T`'s shape, each wrapping (no +//! `nsw` or `nuw`). That is the specification's wording, "only the low 24 bits perform the +//! multiplication" (MSL section 6.4, Table 6.2), and the M3 Max's answer for every operand +//! measured, inside the range where the specification defines the product and outside it +//! (`intrinsics::math`'s module doc). use crate::budget::Meter; use crate::error::Error; -use crate::intrinsics::{AirIntrinsic, Elem, Math, MathFn}; +use crate::intrinsics::{AirIntrinsic, Elem, Math, MathFn, Sign}; use crate::ir::{ BinOp, Block, Body, Call, Callee, CastOp, Const, FastMath, Idx, Inst, InstId, InstKind, IntFlags, IntPredicate, ModuleParts, Type, TypeId, Value, @@ -53,14 +62,22 @@ enum Kind { Frexp, Ilogb, Mad, + /// `mul24`, `signed` for `s`. + Mul24 { + signed: bool, + }, + /// `mad24`, `signed` for `s`. + Mad24 { + signed: bool, + }, } impl Kind { /// The call's operand count. fn arity(self) -> usize { match self { - Kind::Frexp | Kind::Ilogb => 2, - Kind::Mad => 3, + Kind::Frexp | Kind::Ilogb | Kind::Mul24 { .. } => 2, + Kind::Mad | Kind::Mad24 { .. } => 3, } } } @@ -89,11 +106,19 @@ fn routine(kind: &InstKind) -> Option<(Routine, &Call)> { MathFn::Frexp => Kind::Frexp, MathFn::Ilogb => Kind::Ilogb, MathFn::Mad => Kind::Mad, + MathFn::Mul24(s) => Kind::Mul24 { + signed: s == Sign::Signed, + }, + MathFn::Mad24(s) => Kind::Mad24 { + signed: s == Sign::Signed, + }, _ => return None, }; - let half = match ty.elem { - Elem::F16 => true, - Elem::F32 => false, + let half = match (kind, ty.elem) { + (Kind::Mul24 { .. } | Kind::Mad24 { .. }, Elem::I32) => false, + (Kind::Mul24 { .. } | Kind::Mad24 { .. }, _) => return None, + (_, Elem::F16) => true, + (_, Elem::F32) => false, _ => return None, }; Some(( @@ -321,12 +346,42 @@ impl Sink<'_> { Ok(()) } + /// `x`'s low 24 bits as an `i32`: zero-extended, or sign-extended where `signed`. + fn low24(&mut self, x: Value, signed: bool, m: &mut Meter) -> Result { + if !signed { + return self.bin_k(BinOp::And, x, 0x00ff_ffff, m); + } + let high = self.bin_k(BinOp::Shl, x, 8, m)?; + self.bin_k(BinOp::AShr, high, 8, m) + } + + /// `mul24(a, b)`, and `mad24(a, b, c)` where `c` is given: the 32-bit product of the + /// operands' low 24 bits, then its 32-bit sum with `c`, each wrapping; the last instruction is + /// the result (the module docs). + fn int24( + &mut self, + signed: bool, + [a, b]: [Value; 2], + c: Option, + m: &mut Meter, + ) -> Result<(), Error> { + let a = self.low24(a, signed, m)?; + let b = self.low24(b, signed, m)?; + let product = self.bin(BinOp::Mul, a, b, m)?; + if let Some(c) = c { + self.bin(BinOp::Add, product, c, m)?; + } + Ok(()) + } + /// The instructions of call `r` with operands `args`; the last is the call's result. fn emit(&mut self, r: Routine, args: &[Value], m: &mut Meter) -> Result<(), Error> { match (r.kind, args) { (Kind::Frexp, [x, p]) => self.frexp(r, *x, *p, m), (Kind::Ilogb, [x, _mode]) => self.ilogb(r, *x, m), (Kind::Mad, [a, b, c]) => self.mad(r, [*a, *b, *c], m), + (Kind::Mul24 { signed }, [a, b]) => self.int24(signed, [*a, *b], None, m), + (Kind::Mad24 { signed }, [a, b, c]) => self.int24(signed, [*a, *b], Some(*c), m), _ => Err(invariant("a replaced call without its operands")), } } @@ -350,8 +405,8 @@ fn routine_len(r: Routine, parts: &mut ModuleParts, m: &mut Meter) -> Result Result { if !body.insts.iter().any(|(_, i)| routine(&i.kind).is_some()) { return Ok(body); diff --git a/crates/metal2vulkan-air/src/intrinsics/math.rs b/crates/metal2vulkan-air/src/intrinsics/math.rs index 081f6b3c6..300431e28 100644 --- a/crates/metal2vulkan-air/src/intrinsics/math.rs +++ b/crates/metal2vulkan-air/src/intrinsics/math.rs @@ -24,6 +24,18 @@ //! and on each lane of `float4`, and of `half` at `a = b = 1 + 2^-6`, `c = -(1 + 2^-5)` 0 where //! `fma` answers `2^-12`. It reads as [`MathFn::Mad`], that multiply and addition. //! +//! MSL's and OpenCL C's `mul24` and `mad24` of a 32-bit `int` or `uint` (MSL section 6.4, +//! Table 6.2) are `air.mul24..(T, T)` and `air.mad24..(T, T, T)`, `T` `i32` or a +//! vector of it; Apple's compiler spells MSL's at 1 to 4 lanes (MSL on macOS reserves the 8- and +//! 16-lane types). The specification multiplies "only the low 24 bits" of the two 32-bit operands +//! and returns "the 32-bit integer result", and calls the product implementation-defined for +//! operands outside `[0, 2^24 - 1]` unsigned and `[-2^23, 2^23 - 1]` signed. The M3 Max (macOS +//! 27.0.1) answers outside that range too as the product of the operands' low 24 bits, zero-extended +//! for `u` and sign-extended for `s`, the 32-bit sum with `z` for `mad24` (validation cases +//! `int24-products-in-range` and `int24-products-outside-24-bits`). They read as [`MathFn::Mul24`] +//! and [`MathFn::Mad24`], which canonicalization replaces by that product in plain AIR. A width +//! other than 32 bits stays undecoded. +//! //! Two functions reach AIR as calls to Metal runtime routines instead, declarations Apple's //! compiler emits and its backend defines at pipeline creation: `frexp` as //! `___metal_frexp__pthread(T, thread I*)` (AIR 2.9 spells the same operation @@ -206,6 +218,11 @@ pub enum MathFn { MadHi(Sign), /// `air.mad_sat.`: `a * b + c`, saturated. MadSat(Sign), + /// `air.mul24.` of `i32` lanes: the 32-bit product of the operands' low 24 bits, + /// zero-extended (`u`) or sign-extended (`s`) (module doc). + Mul24(Sign), + /// `air.mad24.` of `i32` lanes: `mul24(a, b) + c` in 32 bits (module doc). + Mad24(Sign), /// `air.add_sat.`: `x + y`, saturated. AddSat(Sign), /// `air.sub_sat.`: `x - y`, saturated. @@ -357,6 +374,8 @@ pub(super) const TABLE: &[(&str, Domain, Shape)] = { ("mul_hi", S(M::MulHi), Same(2)), ("mad_hi", S(M::MadHi), Same(3)), ("mad_sat", S(M::MadSat), Same(3)), + ("mul24", S(M::Mul24), Same(2)), + ("mad24", S(M::Mad24), Same(3)), ("add_sat", S(M::AddSat), Same(2)), ("sub_sat", S(M::SubSat), Same(2)), ("hadd", S(M::HAdd), Same(2)), @@ -433,6 +452,9 @@ impl Math { if f == MathFn::Dot && !ty.is_vector() { return None; } + if matches!(f, MathFn::Mul24(_) | MathFn::Mad24(_)) && ty.elem != Elem::I32 { + return None; + } Some(Math { f, precision, ty }) } diff --git a/crates/metal2vulkan-air/src/intrinsics/tests.rs b/crates/metal2vulkan-air/src/intrinsics/tests.rs index 5c206c95e..7defe593a 100644 --- a/crates/metal2vulkan-air/src/intrinsics/tests.rs +++ b/crates/metal2vulkan-air/src/intrinsics/tests.rs @@ -1268,6 +1268,52 @@ fn opencl_mad_decodes_in_its_measured_types_alone() { } } +/// `mul24` and `mad24` decode in the sixteen names Apple's compiler spells (both signs, `i32` and +/// 2 to 4 of its lanes) as `Mul24` and `Mad24`; a width other than 32 bits, a float, or a +/// spelling without a sign stays unknown. +#[test] +fn mul24_and_mad24_decode_on_32_bit_lanes_alone() { + for (stem, sign) in [ + ("mul24.s", Sign::Signed), + ("mul24.u", Sign::Unsigned), + ("mad24.s", Sign::Signed), + ("mad24.u", Sign::Unsigned), + ] { + for (ty, lanes) in [("i32", 1), ("v2i32", 2), ("v3i32", 3), ("v4i32", 4)] { + let name = format!("air.{stem}.{ty}"); + let AirIntrinsic::Math(m) = air(&name) else { + panic!("{name}"); + }; + let f = match stem.starts_with("mul") { + true => MathFn::Mul24(sign), + false => MathFn::Mad24(sign), + }; + assert_eq!( + (m.f, m.precision, m.ty), + ( + f, + Precision::Precise, + NumTy { + elem: Elem::I32, + lanes + } + ), + "{name}" + ); + } + } + for name in [ + "air.mul24.u.i16", // 32-bit lanes only + "air.mad24.s.i64", // 32-bit lanes only + "air.mul24.s.v2i8", // 32-bit lanes only + "air.mul24.f32", // integer types only + "air.mul24.i32", // a sign token is required + "air.fast_mul24.u.i32", // no prefix + ] { + assert_eq!(classify_self(name), DeclClass::Unknown, "{name}"); + } +} + #[test] fn opencl_vector_data_functions_decode_with_their_strides() { use AddrSpace::{Constant as C, Device as G, Thread as P, Threadgroup as L}; diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 9703c9963..95b540f63 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -1598,12 +1598,12 @@ fn air_math(f: MathFn) -> Result { M::Clz { .. } => Fun::Int(IntFn::Clz), M::Ctz { .. } => Fun::Int(IntFn::Ctz), M::SinCos => Fun::SinCos, - // Canonicalization replaces every runtime routine's call and every `mad` call - // (`air::canon::routine`). - M::Frexp | M::Ilogb | M::Mad => { + // Canonicalization replaces every runtime routine's call and every `mad`, `mul24` and + // `mad24` call (`air::canon::routine`). + M::Frexp | M::Ilogb | M::Mad | M::Mul24(_) | M::Mad24(_) => { return Err(Error::Internal(crate::error::InternalError::new( crate::error::InternalKind::Invariant, - "a runtime routine's or mad's call survived canonicalization", + "a runtime routine's, mad's, mul24's or mad24's call survived canonicalization", ))) } })