From 6e67fd2a08e7ded7de3357e597bb06cc4e0c9e73 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 2 Nov 2026 23:51:04 -0800 Subject: [PATCH] Decode inline assembly constants; refuse a reached call of one as InlineAsm What: the bitcode reader now decodes CONSTANTS_BLOCK record 30 (INLINEASM, LLVM 13+, which names its function type) and the older spellings 18, 23 and 28 (typed by their pointer's pointee) into a new constant, Const::InlineAsm, which keeps the template, the constraint string and the four flags as written. A call through it stays Callee::Indirect. Canon's post_check refuses such a call that an entry reaches as Unsupported(InlineAsm), not implemented, naming the expression (`asm sideeffect "", ""`). An entry that reaches none translates, even when other functions of its module call assembly. - The verifier holds the constant to LLVM's rules: a `ptr` in address space 0, never another constant's operand or a global's initializer, and only ever a call's callee. - A record that does not fit its spelling is MalformedRecord: an undefined flag bit, a function type that is none, a string past the record, a byte above 255, a trailing operand, or an old spelling over an opaque pointer. - Feature::InlineAsm is new in both crates (REFUSALS.md regenerated, reach mark `app`). - The validation AIR writer spells the constant back. - The constant interner charges the strings to the ledger. Why: the consumer's sweep refused a whole render pipeline as `Constant { code: 30 }` (a WebGPU deferred-rendering page in Safari), so the pass drew nothing. The record was refused as it was read, so every entry of the module was lost, whether or not it called the assembly. MSL accepts exactly one asm statement: an empty template with no operands and no clobbers. `asm("nop")`, `asm volatile("" ::: "memory")` and `asm volatile("" : "+r"(x))` are all "illegal asm statement" (Metal 32023.922). It always compiles to `call void asm sideeffect "", ""()`, attributes `convergent nounwind`. Fixture: engine/kernel_inline_asm, our own MSL, holds three entries. - asm_in_loop: the statement in a loop body. - asm_in_helper: the statement in a noinline helper. - asm_free: no assembly of its own. Its .ll and .air.ll are from scripts/regen-air-fixtures (LLVM 21), and its golden printout is blessed (tests/air_input/kernel_inline_asm.txt, only that file changed). Verified (M3, macOS 27): - New reader tests: every spelling decodes, every malformed form is typed, and an aggregate holding the asm fails verification. - New engine tests, through both llvm-as and xcrun metal-as: asm_free translates, links and validates on all 19 committed profiles; asm_in_loop and asm_in_helper refuse as InlineAsm by name. - Negative control: with record 30 refused as before, all four tests fail. - metal2vulkan-air suite: 492 tests pass. - metal2vulkan: the air_input, air_canon and air_abi sweeps and the api surface and signatures checks pass. - metal2vulkan-validation fixture, writer and audit tests: 74 pass. - clippy -D warnings in both configurations, plain and --cfg m2v_gpu. Tables owed a bless on development, new rows only: - golden_hashes.tsv: 114 new cells, 3 entries x 19 profiles x 2 spellings. - public_fixture_expectations_engine.tsv: 2 new fixtures. SEMANTICS_VERSION 1950: refusals change class (Constant -> InlineAsm, or a translation). api_signatures.tsv is blessed: additive (the InlineAsm struct and variants). A consumer that matches Const or Feature exhaustively must add the new variants. On the lane: SEMANTICS_VERSION is 1953 here, after the specialization folding's 1952. (cherry picked from commit 8b418fbd6c) (cherry picked from commit c8a7e910204a6cedad2b257a10cb095d83c213e3) --- crates/metal2vulkan-air/src/bitcode/codes.rs | 20 ++- .../metal2vulkan-air/src/bitcode/constants.rs | 95 ++++++++++- .../metal2vulkan-air/src/bitcode/markers.rs | 3 +- crates/metal2vulkan-air/src/bitcode/tests.rs | 125 ++++++++++++++ crates/metal2vulkan-air/src/canon/mod.rs | 6 +- crates/metal2vulkan-air/src/error.rs | 3 + crates/metal2vulkan-air/src/ir/constant.rs | 85 +++++++++- crates/metal2vulkan-air/src/ir/mod.rs | 2 +- crates/metal2vulkan-air/src/ir/print.rs | 3 +- crates/metal2vulkan-air/src/ir/verify.rs | 27 ++- crates/metal2vulkan-air/tests/api_surface.txt | 2 + .../fixtures/public/engine/TOOLCHAIN | 1 + .../public/engine/kernel_inline_asm.air.ll | 130 +++++++++++++++ .../public/engine/kernel_inline_asm.ll | 130 +++++++++++++++ .../public/engine/kernel_inline_asm.metal | 41 +++++ .../src/air_writer/infer.rs | 9 +- .../src/air_writer/text.rs | 2 + crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/error/mod.rs | 4 + crates/metal2vulkan/src/memory/plan.rs | 14 +- .../src/tests/engine_inline_asm.rs | 79 +++++++++ crates/metal2vulkan/src/tests/mod.rs | 1 + .../tests/air_input/kernel_inline_asm.txt | 155 ++++++++++++++++++ crates/metal2vulkan/tests/api_signatures.tsv | 11 ++ docs/REFUSALS.md | 6 +- scripts/refusal-surface/reach.tsv | 1 + 26 files changed, 923 insertions(+), 34 deletions(-) create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.air.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.metal create mode 100644 crates/metal2vulkan/src/tests/engine_inline_asm.rs create mode 100644 crates/metal2vulkan/tests/air_input/kernel_inline_asm.txt diff --git a/crates/metal2vulkan-air/src/bitcode/codes.rs b/crates/metal2vulkan-air/src/bitcode/codes.rs index da00db89e..3e1f48921 100644 --- a/crates/metal2vulkan-air/src/bitcode/codes.rs +++ b/crates/metal2vulkan-air/src/bitcode/codes.rs @@ -89,17 +89,23 @@ pub(crate) const CST_CE_CAST: u32 = 11; pub(crate) const CST_CE_GEP_OLD: u32 = 12; pub(crate) const CST_CE_INBOUNDS_GEP: u32 = 20; pub(crate) const CST_DATA: u32 = 22; +/// `INLINEASM_OLD`: `[sideeffect|alignstack, asmstr, conststr]`, typed by its pointer's pointee. +pub(crate) const CST_INLINEASM_OLD: u32 = 18; +/// `INLINEASM_OLD2`: as `INLINEASM_OLD`, with the dialect bit. +pub(crate) const CST_INLINEASM_OLD2: u32 = 23; pub(crate) const CST_CE_GEP_WITH_INRANGE_INDEX_OLD: u32 = 24; pub(crate) const CST_POISON: u32 = 26; +/// `INLINEASM_OLD3`: as `INLINEASM_OLD2`, with the unwind bit. +pub(crate) const CST_INLINEASM_OLD3: u32 = 28; +/// `INLINEASM`: `[fnty, sideeffect|alignstack|asmdialect|unwind, asmstr, conststr]` (LLVM 13+). +pub(crate) const CST_INLINEASM: u32 = 30; pub(crate) const CST_CE_GEP: u32 = 32; /// Constant codes LLVM defines that the typed model refuses: CE_SELECT, CE_EXTRACTELT, -/// CE_INSERTELT, CE_SHUFFLEVEC, CE_CMP, INLINEASM_OLD, CE_SHUFVEC_EX, BLOCKADDRESS, -/// INLINEASM_OLD2, CE_UNOP, DSO_LOCAL_EQUIVALENT, INLINEASM_OLD3, NO_CFI_VALUE, INLINEASM, -/// CE_GEP_WITH_INRANGE, PTRAUTH, PTRAUTH2, BYTE and WIDE_BYTE (LLVM 23: constants of the -/// refused byte type). -pub(crate) const CST_UNSUPPORTED: &[u32] = &[ - 13, 14, 15, 16, 17, 18, 19, 21, 23, 25, 27, 28, 29, 30, 31, 33, 34, 35, 36, -]; +/// CE_INSERTELT, CE_SHUFFLEVEC, CE_CMP, CE_SHUFVEC_EX, BLOCKADDRESS, CE_UNOP, +/// DSO_LOCAL_EQUIVALENT, NO_CFI_VALUE, CE_GEP_WITH_INRANGE, PTRAUTH, PTRAUTH2, BYTE and WIDE_BYTE +/// (LLVM 23: constants of the refused byte type). +pub(crate) const CST_UNSUPPORTED: &[u32] = + &[13, 14, 15, 16, 17, 19, 21, 25, 27, 29, 31, 33, 34, 35, 36]; // ---- METADATA ---- pub(crate) const METADATA_VALUE: u32 = 2; diff --git a/crates/metal2vulkan-air/src/bitcode/constants.rs b/crates/metal2vulkan-air/src/bitcode/constants.rs index a1bfdc310..c8d9d8a89 100644 --- a/crates/metal2vulkan-air/src/bitcode/constants.rs +++ b/crates/metal2vulkan-air/src/bitcode/constants.rs @@ -18,8 +18,8 @@ use crate::budget::Meter; use crate::error::{BitcodeError, InputError, InputErrorKind, Location}; use crate::error::{Error, Feature}; use crate::ir::{ - BinOp, CastOp, Const, ConstExpr, ConstId, ConstTable, Constant, IntFlags, Type, TypeId, - TypeTable, + BinOp, CastOp, Const, ConstExpr, ConstId, ConstTable, Constant, InlineAsm, IntFlags, Type, + TypeId, TypeTable, }; /// One decoded constant: its id and the bitcode type index it was declared with. @@ -106,7 +106,7 @@ pub(crate) fn decode( return Ok(()); } let (bc, ty) = cur.ok_or_else(|| s.malformed(B, code))?; - let entry = record(s, cx.consts, bc_types, types, code, ty, m)?; + let entry = record(s, cx.consts, bc_types, types, code, (bc, ty), m)?; grow(m, &mut raw)?; raw.push((entry, bc)); Ok(()) @@ -124,14 +124,14 @@ pub(crate) fn decode( Ok(out) } -/// Decode one constant record of type `ty` (not `SETTYPE`). +/// Decode one constant record of type `ty` (bitcode type index `bc`; not `SETTYPE`). fn record( s: &Stream<'_>, consts: &mut ConstTable, bc_types: &BitcodeTypes, types: &TypeTable, code: u32, - ty: TypeId, + (bc, ty): (u32, TypeId), m: &mut Meter, ) -> Result { const B: u32 = CONSTANTS_BLOCK; @@ -265,11 +265,96 @@ fn record( ops: vals.into_boxed_slice(), }) } + CST_INLINEASM_OLD | CST_INLINEASM_OLD2 | CST_INLINEASM_OLD3 | CST_INLINEASM => { + inline_asm(s, bc_types, types, code, (bc, ty), m) + } c if CST_UNSUPPORTED.contains(&c) => Err(s.unsupported(Feature::Constant { code })), _ => Err(s.err(BitcodeError::UnknownRecord { block: B, code })), } } +/// An inline assembly record of type `ty` (bitcode index `bc`), in any of LLVM's four +/// spellings: `[fnty?, flags, asmlen, asm..., conslen, cons...]`, one byte per operand. `INLINEASM` +/// names its function type; the older three take it from the pointee of their typed pointer. +/// The flags are `sideeffect` (bit 0), `alignstack` (1), `inteldialect` (2, from `INLINEASM_OLD2`) +/// and `unwind` (3, from `INLINEASM_OLD3`); a bit the spelling does not define is malformed, as is +/// a type other than a pointer, a function type that is none, or a byte operand above 255. +fn inline_asm( + s: &Stream<'_>, + bc_types: &BitcodeTypes, + types: &TypeTable, + code: u32, + (bc, ty): (u32, TypeId), + m: &mut Meter, +) -> Result { + let bad = || s.malformed(CONSTANTS_BLOCK, code); + let ops = s.ops(); + let (fn_bc, rest) = match code { + CST_INLINEASM => { + let (&f, rest) = ops.split_first().ok_or_else(bad)?; + (f, rest) + } + _ => ( + u64::from(bc_types.pointee(u64::from(bc)).ok_or_else(bad)?), + ops, + ), + }; + let is_fn = bc_types + .ty(fn_bc) + .is_some_and(|f| matches!(types.get(f), Some(Type::Function { .. }))); + if !is_fn || !matches!(types.get(ty), Some(Type::Ptr { .. })) { + return Err(bad()); + } + let (&flags, rest) = rest.split_first().ok_or_else(bad)?; + let defined: u64 = match code { + CST_INLINEASM_OLD => 0b11, + CST_INLINEASM_OLD2 => 0b111, + _ => 0b1111, + }; + if flags & !defined != 0 { + return Err(bad()); + } + let (template, rest) = asm_bytes(rest, &bad, m)?; + let (constraints, rest) = asm_bytes(rest, &bad, m)?; + if !rest.is_empty() { + return Err(bad()); + } + let asm = InlineAsm { + template, + constraints, + side_effects: flags & 1 != 0, + align_stack: flags & 2 != 0, + intel_dialect: flags & 4 != 0, + can_throw: flags & 8 != 0, + }; + m.charge(std::mem::size_of::())?; + Ok(Raw::Ready(Constant { + ty, + value: Const::InlineAsm(Box::new(asm)), + })) +} + +/// A length-prefixed string of one byte per operand at the front of `ops`, and the operands after +/// it; `bad()` when the length runs past the record or a byte is above 255. +fn asm_bytes<'o>( + ops: &'o [u64], + bad: &dyn Fn() -> Error, + m: &mut Meter, +) -> Result<(Box<[u8]>, &'o [u64]), Error> { + let (&len, rest) = ops.split_first().ok_or_else(bad)?; + let len = usize::try_from(len) + .ok() + .filter(|&n| n <= rest.len()) + .ok_or_else(bad)?; + let (text, rest) = rest.split_at(len); + let mut out = Vec::new(); + m.reserve(&mut out, len)?; + for &b in text { + out.push(u8::try_from(b).map_err(|_| bad())?); + } + Ok((out.into_boxed_slice(), rest)) +} + /// The scalar constant `value` of type `ty`, or, for a vector `ty`, the aggregate holding /// `value` in every lane (the vector `INTEGER`/`FLOAT` splat spelling). fn splat( diff --git a/crates/metal2vulkan-air/src/bitcode/markers.rs b/crates/metal2vulkan-air/src/bitcode/markers.rs index a3bf1c832..ff3e9386d 100644 --- a/crates/metal2vulkan-air/src/bitcode/markers.rs +++ b/crates/metal2vulkan-air/src/bitcode/markers.rs @@ -476,7 +476,8 @@ impl Plan { | Const::Null | Const::Undef | Const::Poison - | Const::GlobalAddr(_) => c.value.clone(), + | Const::GlobalAddr(_) + | Const::InlineAsm(_) => c.value.clone(), }; Ok(Constant { ty: self.ty(c.ty)?, diff --git a/crates/metal2vulkan-air/src/bitcode/tests.rs b/crates/metal2vulkan-air/src/bitcode/tests.rs index 049e47e23..4bef9da69 100644 --- a/crates/metal2vulkan-air/src/bitcode/tests.rs +++ b/crates/metal2vulkan-air/src/bitcode/tests.rs @@ -1036,6 +1036,131 @@ fn constant_errors_are_typed() { ); } +/// `records` in a module-level constants block over [`good_types`] and three more: 6 `void ()`, +/// 7 `void ()*` (a typed pointer in address space 0), 8 `ptr` (opaque, address space 0). +fn asm_constants(records: &[(u64, Vec)]) -> Result { + let mut types = good_types(); + types[0] = (1, vec![9]); + types.extend([(21, vec![0, 3]), (8, vec![6, 0]), (25, vec![0])]); + decode(&stream(2, 0, b"", |w| { + block(w, codes::TYPE_BLOCK, &types); + block(w, codes::CONSTANTS_BLOCK, records); + })) +} + +/// `[len, bytes...]`: an inline assembly string's operands. +fn asm_text(s: &str) -> Vec { + [vec![s.len() as u64], chars(s)].concat() +} + +/// Every spelling of LLVM's inline assembly record decodes to its text and flags: `INLINEASM` +/// (code 30, naming its function type), and the typed-pointer `INLINEASM_OLD3` (28), +/// `INLINEASM_OLD2` (23) and `INLINEASM_OLD` (18), typed by their pointer's pointee. The constant +/// is a `ptr` in address space 0, and the module verifies. +#[test] +fn inline_asm_records_decode_in_every_spelling() { + let empty = [asm_text(""), asm_text("")].concat(); + let text = [asm_text("nop \"x\""), asm_text("~{memory}")].concat(); + let t = asm_constants(&[ + (1, vec![8]), + // asm sideeffect "", "" of type void (): what an MSL `asm volatile("")` compiles to. + (30, [vec![6, 1], empty.clone()].concat()), + // Every flag. + (30, [vec![6, 0b1111], text.clone()].concat()), + (1, vec![7]), + (28, [vec![0b1010], text.clone()].concat()), + (23, [vec![0b100], empty.clone()].concat()), + (18, [vec![0b11], text.clone()].concat()), + ]) + .unwrap(); + let asm = |i: u64| match &t.parts.consts.get(t.value(i).unwrap()).unwrap().value { + Const::InlineAsm(a) => (**a).clone(), + other => panic!("value {i}: {other:?}"), + }; + let flags = + |a: &crate::ir::InlineAsm| [a.side_effects, a.align_stack, a.intel_dialect, a.can_throw]; + assert_eq!(asm(0).spelling(), r#"asm sideeffect "", """#); + assert_eq!(flags(&asm(0)), [true, false, false, false]); + assert_eq!(&*asm(1).template, b"nop \"x\""); + assert_eq!(&*asm(1).constraints, b"~{memory}"); + assert_eq!( + asm(1).spelling(), + r#"asm sideeffect alignstack inteldialect unwind "nop \22x\22", "~{memory}""# + ); + assert_eq!(flags(&asm(2)), [false, true, false, true]); + assert_eq!(flags(&asm(3)), [false, false, true, false]); + assert_eq!(&*asm(3).template, b""); + assert_eq!(flags(&asm(4)), [true, true, false, false]); + assert_eq!(&*asm(4).constraints, b"~{memory}"); + let ptr0 = |i: u64| t.parts.consts.ty(t.value(i).unwrap()).unwrap(); + assert_eq!(ptr0(0), ptr0(2), "both pointer spellings erase to one ptr"); + verify_module_level(&t).unwrap(); +} + +/// An inline assembly record that does not fit its spelling is malformed: a flag bit the spelling +/// does not define, a function type that is none, a string running past the record, a byte above +/// 255, an operand after the constraints, an old spelling over an opaque pointer (no pointee to +/// type it), and a type other than a pointer. Inline assembly as another constant's operand fails +/// verification: LLVM has no such constant. +#[test] +fn malformed_inline_asm_records_are_typed() { + let empty = [asm_text(""), asm_text("")].concat(); + for records in [ + vec![ + (1, vec![8]), + (30, [vec![6, 1 << 4], empty.clone()].concat()), + ], + vec![(1, vec![7]), (28, [vec![1 << 4], empty.clone()].concat())], + vec![(1, vec![7]), (23, [vec![1 << 3], empty.clone()].concat())], + vec![(1, vec![7]), (18, [vec![1 << 2], empty.clone()].concat())], + vec![(1, vec![8]), (30, [vec![0, 1], empty.clone()].concat())], + vec![(1, vec![8]), (30, vec![6, 1, 3, 1, 2])], + vec![(1, vec![8]), (30, vec![6, 1, 1, 256, 0])], + vec![ + (1, vec![8]), + (30, [vec![6, 1], empty.clone(), vec![0]].concat()), + ], + vec![(1, vec![8]), (30, vec![6, 1, 0])], + vec![(1, vec![8]), (28, [vec![1], empty.clone()].concat())], + vec![(1, vec![0]), (30, [vec![6, 1], empty.clone()].concat())], + ] { + let e = asm_constants(&records).unwrap_err(); + assert!( + matches!(bitcode_kind(&e), Some(BitcodeError::MalformedRecord { .. })), + "{records:?}: {e:?}" + ); + } + // A struct `{ ptr }` (type 9) holding an inline assembly expression. + let mut types = good_types(); + types[0] = (1, vec![10]); + types.extend([ + (21, vec![0, 3]), + (8, vec![6, 0]), + (25, vec![0]), + (18, vec![0, 8]), + ]); + let t = decode(&stream(2, 0, b"", |w| { + block(w, codes::TYPE_BLOCK, &types); + block( + w, + codes::CONSTANTS_BLOCK, + &[ + (1, vec![8]), + (30, [vec![6, 1], empty.clone()].concat()), + (1, vec![9]), + (7, vec![0]), + ], + ); + })) + .unwrap(); + let e = verify_module_level(&t).unwrap_err(); + assert!( + matches!(&e, Error::InvalidInput(i) + if i.kind == InputErrorKind::Verify(crate::error::VerifyError::MalformedConstant)), + "{e:?}" + ); +} + #[test] fn metadata_and_string_table_errors_are_typed() { // A node referring past the metadata. diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index adab00a71..18909066e 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -1358,7 +1358,11 @@ fn post_check( _ => undefined(f)?, } } - None => Unsupported::not_implemented(Feature::DynamicCall), + None => match parts.consts.inline_asm(callee) { + Some(asm) => Unsupported::not_implemented(Feature::InlineAsm) + .naming(DiagName::new(asm.spelling())), + None => Unsupported::not_implemented(Feature::DynamicCall), + }, } } Callee::Direct(f) => match parts.funcs.get(f) { diff --git a/crates/metal2vulkan-air/src/error.rs b/crates/metal2vulkan-air/src/error.rs index 32868c0f7..92169f7a8 100644 --- a/crates/metal2vulkan-air/src/error.rs +++ b/crates/metal2vulkan-air/src/error.rs @@ -746,6 +746,9 @@ pub enum Feature { Recursion, /// Indirect calls, function pointers, visible/intersection function tables (one variant). DynamicCall, + /// A call to inline assembly (`asm`) that an entry reaches: the IR gives no assembly a + /// meaning. The refusal names the expression (`asm sideeffect "", ""`). + InlineAsm, /// Linkage signatures / stitching / dynamic libraries. Linking, /// A bitcode constant record outside the typed model (block address, inline asm, `select` diff --git a/crates/metal2vulkan-air/src/ir/constant.rs b/crates/metal2vulkan-air/src/ir/constant.rs index f819809e9..aa9f87f94 100644 --- a/crates/metal2vulkan-air/src/ir/constant.rs +++ b/crates/metal2vulkan-air/src/ir/constant.rs @@ -6,7 +6,7 @@ //! [`Const::GlobalAddr`] / [`Const::FuncAddr`], so every non-local operand is one `ConstId`. use super::id::{Arena, ConstId, FuncId, GlobalId, TypeId}; -use super::inst::{BinOp, CastOp, IntFlags}; +use super::inst::{BinOp, CastOp, IntFlags, Value}; use super::intern::FxHashMap; use crate::budget::Meter; use crate::error::Error; @@ -42,6 +42,63 @@ pub enum Const { FuncAddr(FuncId), /// A constant expression. Expr(ConstExpr), + /// An inline assembly expression (`asm`), typed `ptr`: only ever the callee of a call, at the + /// call's function type. The IR keeps its strings and flags as written and gives it no + /// meaning; canonicalization refuses a call to it that an entry reaches. + InlineAsm(Box), +} + +/// The text and flags of an inline assembly expression ([`Const::InlineAsm`]), as LLVM's +/// `CST_CODE_INLINEASM` records spell them. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct InlineAsm { + /// The assembly template. + pub template: Box<[u8]>, + /// The constraint string: the operands, results and clobbers. + pub constraints: Box<[u8]>, + /// `sideeffect`: the expression has effects its constraints do not list. + pub side_effects: bool, + /// `alignstack`: the stack is aligned for it. + pub align_stack: bool, + /// `inteldialect`: the template is in Intel syntax rather than AT&T. + pub intel_dialect: bool, + /// `unwind`: it may throw. + pub can_throw: bool, +} + +impl InlineAsm { + /// The bytes it holds outside its box. + pub(crate) fn heap_bytes(&self) -> usize { + self.template.len().saturating_add(self.constraints.len()) + } + + /// Its LLVM spelling: `asm`, the flags, then the quoted template and constraints, with LLVM's + /// `\XX` escapes (`asm sideeffect "", ""`). + pub fn spelling(&self) -> String { + let mut out = String::from("asm"); + for (on, word) in [ + (self.side_effects, " sideeffect"), + (self.align_stack, " alignstack"), + (self.intel_dialect, " inteldialect"), + (self.can_throw, " unwind"), + ] { + if on { + out.push_str(word); + } + } + for (i, text) in [&self.template, &self.constraints].into_iter().enumerate() { + out.push_str(if i == 0 { " \"" } else { ", \"" }); + for &b in text.iter() { + if (b.is_ascii_graphic() || b == b' ') && b != b'"' && b != b'\\' { + out.push(char::from(b)); + } else { + out.push_str(&format!("\\{b:02X}")); + } + } + out.push('"'); + } + out + } } impl Const { @@ -56,7 +113,17 @@ impl Const { | Const::Undef | Const::Poison | Const::GlobalAddr(_) - | Const::FuncAddr(_) => &[], + | Const::FuncAddr(_) + | Const::InlineAsm(_) => &[], + } + } + + /// The bytes it holds outside its slot: its children's ids, or an inline assembly + /// expression's box and strings. + pub(crate) fn heap_bytes(&self) -> usize { + match self { + Const::InlineAsm(a) => std::mem::size_of::().saturating_add(a.heap_bytes()), + other => std::mem::size_of::().saturating_mul(other.children().len()), } } } @@ -133,8 +200,7 @@ impl ConstTable { return Err(malformed_constant()); } // Stored twice: once in the arena, once as the lookup key. - let payload = std::mem::size_of::().saturating_mul(c.value.children().len()); - meter.charge(payload.saturating_mul(2))?; + meter.charge(c.value.heap_bytes().saturating_mul(2))?; meter.charge(std::mem::size_of::())?; let id = self.consts.push(c.clone(), meter)?; self.index.insert(c, id); @@ -152,6 +218,17 @@ impl ConstTable { self.consts.get(id) } + /// The inline assembly expression `v` is, if it is one. + pub(crate) fn inline_asm(&self, v: Value) -> Option<&InlineAsm> { + match v { + Value::Const(c) => match &self.get(c)?.value { + Const::InlineAsm(asm) => Some(asm), + _ => None, + }, + Value::Arg(_) | Value::Inst(_) => None, + } + } + /// The type of the constant at `id`. pub fn ty(&self, id: ConstId) -> Option { self.get(id).map(|c| c.ty) diff --git a/crates/metal2vulkan-air/src/ir/mod.rs b/crates/metal2vulkan-air/src/ir/mod.rs index ab31e02f4..1f9b400f7 100644 --- a/crates/metal2vulkan-air/src/ir/mod.rs +++ b/crates/metal2vulkan-air/src/ir/mod.rs @@ -24,7 +24,7 @@ pub mod value; pub mod verify; pub use attrs::{CallAttrs, FnAttrs, MemoryEffects, ModRef, ParamAttrs}; -pub use constant::{Const, ConstExpr, ConstTable, Constant}; +pub use constant::{Const, ConstExpr, ConstTable, Constant, InlineAsm}; pub use id::{Arena, ArgIdx, BlockId, ConstId, FuncId, GlobalId, Idx, InstId, MdId, Sym, TypeId}; #[cfg(test)] pub use inst::Opcode; diff --git a/crates/metal2vulkan-air/src/ir/print.rs b/crates/metal2vulkan-air/src/ir/print.rs index cf5fcd8b0..c6a6c2f62 100644 --- a/crates/metal2vulkan-air/src/ir/print.rs +++ b/crates/metal2vulkan-air/src/ir/print.rs @@ -104,6 +104,7 @@ impl Printer<'_> { self.const_list(ops); self.out.push(')'); } + Const::InlineAsm(a) => self.out.push_str(&a.spelling()), Const::Int(_) | Const::Float(_) | Const::Null @@ -693,7 +694,7 @@ impl Printer<'_> { Const::Poison => "poison".into(), Const::GlobalAddr(g) => format!("@g{}", g.raw()), Const::FuncAddr(f) => format!("@f{}", f.raw()), - Const::Aggregate(_) | Const::Expr(_) => return None, + Const::Aggregate(_) | Const::Expr(_) | Const::InlineAsm(_) => return None, }) } diff --git a/crates/metal2vulkan-air/src/ir/verify.rs b/crates/metal2vulkan-air/src/ir/verify.rs index b5ba0f2cf..6152dc4d8 100644 --- a/crates/metal2vulkan-air/src/ir/verify.rs +++ b/crates/metal2vulkan-air/src/ir/verify.rs @@ -321,7 +321,10 @@ impl<'a> Verifier<'a> { && self.types().is_sized(g.value_ty) && self.section_ok(g.section) && match g.init { - Some(c) => self.p.consts.ty(c) == Some(g.value_ty), + Some(c) => { + self.p.consts.ty(c) == Some(g.value_ty) + && self.p.consts.inline_asm(Value::Const(c)).is_none() + } None => declaration_linkage, } } @@ -330,6 +333,15 @@ impl<'a> Verifier<'a> { let Some(ty) = self.ty(c.ty) else { return false; }; + // Inline assembly is no LLVM constant: it is never another constant's operand. + let asm_child = c + .value + .children() + .iter() + .any(|&k| self.p.consts.inline_asm(Value::Const(k)).is_some()); + if asm_child { + return false; + } let child_ty = |id: ConstId| self.p.consts.ty(id); match &c.value { Const::Int(bits) => match ty { @@ -365,6 +377,10 @@ impl<'a> Verifier<'a> { .space(self.p.data_layout.program_space) .is_some_and(|space| *ty == Type::Ptr { space }) } + // LLVM types an inline assembly expression `ptr` in address space 0. + Const::InlineAsm(_) => self + .space(0) + .is_some_and(|space| *ty == Type::Ptr { space }), Const::Expr(ConstExpr::Cast { op, ops: [v] }) => { child_ty(*v).is_some_and(|src| self.cast_ok(*op, src, c.ty)) } @@ -576,7 +592,14 @@ impl<'a> Verifier<'a> { /// Every operand exists and is a non-void value. fn operands(&self, cx: &FnCtx<'a>, inst: &Inst) -> Result<(), Error> { let mut ok = true; + // Inline assembly is only ever a call's callee (LLVM: "Cannot take the address of an + // inline asm!"). + let mut asm_uses = 0usize; + let asm_callee = matches!(&inst.kind, InstKind::Call(call) + if matches!(call.callee, Callee::Indirect { callee, .. } + if self.p.consts.inline_asm(callee).is_some())); inst.kind.for_each_value(|v| { + asm_uses += usize::from(self.p.consts.inline_asm(v).is_some()); ok &= match v { Value::Arg(a) => a.index() < cx.params.len(), Value::Const(c) => self.p.consts.contains(c), @@ -587,7 +610,7 @@ impl<'a> Verifier<'a> { .is_some_and(|def| !self.is_void(def.ty)), }; }); - if !ok { + if !ok || asm_uses > usize::from(asm_callee) { return Err(cx.err(VerifyError::BadValueRef)); } if let InstKind::Call(call) = &inst.kind { diff --git a/crates/metal2vulkan-air/tests/api_surface.txt b/crates/metal2vulkan-air/tests/api_surface.txt index 6120cf224..08a4d69df 100644 --- a/crates/metal2vulkan-air/tests/api_surface.txt +++ b/crates/metal2vulkan-air/tests/api_surface.txt @@ -372,6 +372,7 @@ ir Function use(module::Function) ir Global use(module::Global) ir GlobalId use(id::GlobalId) ir Idx use(id::Idx) +ir InlineAsm use(constant::InlineAsm) ir Inst use(inst::Inst) ir InstId use(id::InstId) ir InstKind use(inst::InstKind) @@ -431,6 +432,7 @@ ir::constant Const enum(E) ir::constant ConstExpr enum(E) ir::constant ConstTable struct(O) ir::constant Constant struct(E) +ir::constant InlineAsm struct(E) ir::id Arena struct(O) ir::id ArgIdx struct(O) ir::id BlockId struct(O) diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN index 1493dd034..c9de3a99e 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN @@ -165,6 +165,7 @@ fixture icb_stage_in_encode: metal: Apple metal version 32023.921 (metalfe-32023 fixture icb_stage_in_template: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture ido_draw_order: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture kernel_frexp_ilogb: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) +fixture kernel_inline_asm: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) fixture kernel_spin_on_an_unraised_word: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture kernel_stage_in: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture linked_mps_callbacks: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.air.ll b/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.air.ll new file mode 100644 index 000000000..3d6ca35d1 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.air.ll @@ -0,0 +1,130 @@ +; Generated by scripts/regen-air-fixtures from kernel_inline_asm.metal (typed pointers; xcrun metal-as reassembles it). Do not edit. +; ModuleID = '-' +source_filename = "-" +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" +target triple = "air64_v28-apple-macosx26.0.0" + +; Function Attrs: convergent mustprogress nounwind +define void @asm_in_loop(i32 addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %0, i32 addrspace(2)* nocapture noundef readonly align 4 dereferenceable(4) "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #0 { + %4 = load i32, i32 addrspace(2)* %1, align 4, !tbaa !25, !alias.scope !29, !noalias !32 + %5 = icmp eq i32 %4, 0 + br i1 %5, label %6, label %10 + +6: ; preds = %10, %3 + %7 = phi i32 [ 0, %3 ], [ %14, %10 ] + %8 = zext i32 %2 to i64 + %9 = getelementptr inbounds i32, i32 addrspace(1)* %0, i64 %8 + store i32 %7, i32 addrspace(1)* %9, align 4, !tbaa !25, !alias.scope !32, !noalias !29 + ret void + +10: ; preds = %3, %10 + %11 = phi i32 [ %15, %10 ], [ 0, %3 ] + %12 = phi i32 [ %14, %10 ], [ 0, %3 ] + tail call void asm sideeffect "", ""() #3, !srcloc !34 + %13 = xor i32 %11, %2 + %14 = add i32 %12, %13 + %15 = add nuw i32 %11, 1 + %16 = icmp eq i32 %15, %4 + br i1 %16, label %6, label %10, !llvm.loop !35 +} + +; Function Attrs: convergent mustprogress nounwind +define void @asm_in_helper(i32 addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %0, i32 noundef %1) local_unnamed_addr #0 { + %3 = tail call fastcc i32 @_ZL10asm_helperj(i32 noundef %1) #4 + %4 = zext i32 %1 to i64 + %5 = getelementptr inbounds i32, i32 addrspace(1)* %0, i64 %4 + store i32 %3, i32 addrspace(1)* %5, align 4, !tbaa !25, !alias.scope !37 + ret void +} + +; Function Attrs: convergent mustprogress noinline nounwind +define internal fastcc i32 @_ZL10asm_helperj(i32 noundef %0) unnamed_addr #1 { + tail call void asm sideeffect "", ""() #3, !srcloc !40 + %2 = mul i32 %0, 3 + %3 = add i32 %2, 1 + ret i32 %3 +} + +; Function Attrs: argmemonly mustprogress nofree norecurse nosync nounwind writeonly +define void @asm_free(i32 addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %0, i32 addrspace(2)* nocapture noundef readonly align 4 dereferenceable(4) "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #2 { + %4 = load i32, i32 addrspace(2)* %1, align 4, !tbaa !25, !alias.scope !41, !noalias !44 + %5 = icmp eq i32 %4, 0 + br i1 %5, label %6, label %10 + +6: ; preds = %10, %3 + %7 = phi i32 [ 0, %3 ], [ %14, %10 ] + %8 = zext i32 %2 to i64 + %9 = getelementptr inbounds i32, i32 addrspace(1)* %0, i64 %8 + store i32 %7, i32 addrspace(1)* %9, align 4, !tbaa !25, !alias.scope !44, !noalias !41 + ret void + +10: ; preds = %3, %10 + %11 = phi i32 [ %15, %10 ], [ 0, %3 ] + %12 = phi i32 [ %14, %10 ], [ 0, %3 ] + %13 = xor i32 %11, %2 + %14 = add i32 %12, %13 + %15 = add nuw i32 %11, 1 + %16 = icmp eq i32 %15, %4 + br i1 %16, label %6, label %10, !llvm.loop !46 +} + +attributes #0 = { convergent mustprogress nounwind "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { convergent mustprogress noinline nounwind "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { argmemonly mustprogress nofree norecurse nosync nounwind writeonly "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { convergent nounwind } +attributes #4 = { convergent nobuiltin "no-builtins" } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.kernel = !{!9, !15, !18} +!air.compile_options = !{!19, !20, !21} +!llvm.ident = !{!22} +!air.version = !{!23} +!air.language_version = !{!24} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{void (i32 addrspace(1)*, i32 addrspace(2)*, i32)* @asm_in_loop, !10, !11} +!10 = !{} +!11 = !{!12, !13, !14} +!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", !"o"} +!13 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"n"} +!14 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} +!15 = !{void (i32 addrspace(1)*, i32)* @asm_in_helper, !10, !16} +!16 = !{!12, !17} +!17 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} +!18 = !{void (i32 addrspace(1)*, i32 addrspace(2)*, i32)* @asm_free, !10, !11} +!19 = !{!"air.compile.denorms_disable"} +!20 = !{!"air.compile.fast_math_enable"} +!21 = !{!"air.compile.framebuffer_fetch_enable"} +!22 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!23 = !{i32 2, i32 8, i32 0} +!24 = !{!"Metal", i32 4, i32 0, i32 0} +!25 = !{!26, !26, i64 0} +!26 = !{!"int", !27, i64 0} +!27 = !{!"omnipotent char", !28, i64 0} +!28 = !{!"Simple C++ TBAA"} +!29 = !{!30} +!30 = distinct !{!30, !31, !"air-alias-scope-arg(1)"} +!31 = distinct !{!31, !"air-alias-scopes(asm_in_loop)"} +!32 = !{!33} +!33 = distinct !{!33, !31, !"air-alias-scope-arg(0)"} +!34 = !{i64 978} +!35 = distinct !{!35, !36} +!36 = !{!"llvm.loop.mustprogress"} +!37 = !{!38} +!38 = distinct !{!38, !39, !"air-alias-scope-arg(0)"} +!39 = distinct !{!39, !"air-alias-scopes(asm_in_helper)"} +!40 = !{i64 1110} +!41 = !{!42} +!42 = distinct !{!42, !43, !"air-alias-scope-arg(1)"} +!43 = distinct !{!43, !"air-alias-scopes(asm_free)"} +!44 = !{!45} +!45 = distinct !{!45, !43, !"air-alias-scope-arg(0)"} +!46 = distinct !{!46, !36} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.ll b/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.ll new file mode 100644 index 000000000..6383be868 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.ll @@ -0,0 +1,130 @@ +; Generated by scripts/regen-air-fixtures from kernel_inline_asm.metal (llvm-dis of kernel_inline_asm.air). Do not edit. +; ModuleID = '' +source_filename = "-" +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" +target triple = "air64_v28-apple-macosx26.0.0" + +; Function Attrs: convergent mustprogress nounwind +define void @asm_in_loop(ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %0, ptr addrspace(2) noundef readonly align 4 captures(none) dereferenceable(4) "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #0 { + %4 = load i32, ptr addrspace(2) %1, align 4, !tbaa !25, !alias.scope !29, !noalias !32 + %5 = icmp eq i32 %4, 0 + br i1 %5, label %6, label %10 + +6: ; preds = %10, %3 + %7 = phi i32 [ 0, %3 ], [ %14, %10 ] + %8 = zext i32 %2 to i64 + %9 = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %8 + store i32 %7, ptr addrspace(1) %9, align 4, !tbaa !25, !alias.scope !32, !noalias !29 + ret void + +10: ; preds = %10, %3 + %11 = phi i32 [ %15, %10 ], [ 0, %3 ] + %12 = phi i32 [ %14, %10 ], [ 0, %3 ] + tail call void asm sideeffect "", ""() #3, !srcloc !34 + %13 = xor i32 %11, %2 + %14 = add i32 %12, %13 + %15 = add nuw i32 %11, 1 + %16 = icmp eq i32 %15, %4 + br i1 %16, label %6, label %10, !llvm.loop !35 +} + +; Function Attrs: convergent mustprogress nounwind +define void @asm_in_helper(ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %0, i32 noundef %1) local_unnamed_addr #0 { + %3 = tail call fastcc i32 @_ZL10asm_helperj(i32 noundef %1) #4 + %4 = zext i32 %1 to i64 + %5 = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %4 + store i32 %3, ptr addrspace(1) %5, align 4, !tbaa !25, !alias.scope !37 + ret void +} + +; Function Attrs: convergent mustprogress noinline nounwind +define internal fastcc i32 @_ZL10asm_helperj(i32 noundef %0) unnamed_addr #1 { + tail call void asm sideeffect "", ""() #3, !srcloc !40 + %2 = mul i32 %0, 3 + %3 = add i32 %2, 1 + ret i32 %3 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind memory(argmem: write) +define void @asm_free(ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %0, ptr addrspace(2) noundef readonly align 4 captures(none) dereferenceable(4) "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #2 { + %4 = load i32, ptr addrspace(2) %1, align 4, !tbaa !25, !alias.scope !41, !noalias !44 + %5 = icmp eq i32 %4, 0 + br i1 %5, label %6, label %10 + +6: ; preds = %10, %3 + %7 = phi i32 [ 0, %3 ], [ %14, %10 ] + %8 = zext i32 %2 to i64 + %9 = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %8 + store i32 %7, ptr addrspace(1) %9, align 4, !tbaa !25, !alias.scope !44, !noalias !41 + ret void + +10: ; preds = %10, %3 + %11 = phi i32 [ %15, %10 ], [ 0, %3 ] + %12 = phi i32 [ %14, %10 ], [ 0, %3 ] + %13 = xor i32 %11, %2 + %14 = add i32 %12, %13 + %15 = add nuw i32 %11, 1 + %16 = icmp eq i32 %15, %4 + br i1 %16, label %6, label %10, !llvm.loop !46 +} + +attributes #0 = { convergent mustprogress nounwind "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { convergent mustprogress noinline nounwind "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { mustprogress nofree norecurse nosync nounwind memory(argmem: write) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { convergent nounwind } +attributes #4 = { convergent nobuiltin "no-builtins" } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.kernel = !{!9, !15, !18} +!air.compile_options = !{!19, !20, !21} +!llvm.ident = !{!22} +!air.version = !{!23} +!air.language_version = !{!24} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{ptr @asm_in_loop, !10, !11} +!10 = !{} +!11 = !{!12, !13, !14} +!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", !"o"} +!13 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"n"} +!14 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} +!15 = !{ptr @asm_in_helper, !10, !16} +!16 = !{!12, !17} +!17 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} +!18 = !{ptr @asm_free, !10, !11} +!19 = !{!"air.compile.denorms_disable"} +!20 = !{!"air.compile.fast_math_enable"} +!21 = !{!"air.compile.framebuffer_fetch_enable"} +!22 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!23 = !{i32 2, i32 8, i32 0} +!24 = !{!"Metal", i32 4, i32 0, i32 0} +!25 = !{!26, !26, i64 0} +!26 = !{!"int", !27, i64 0} +!27 = !{!"omnipotent char", !28, i64 0} +!28 = !{!"Simple C++ TBAA"} +!29 = !{!30} +!30 = distinct !{!30, !31, !"air-alias-scope-arg(1)"} +!31 = distinct !{!31, !"air-alias-scopes(asm_in_loop)"} +!32 = !{!33} +!33 = distinct !{!33, !31, !"air-alias-scope-arg(0)"} +!34 = !{i64 978} +!35 = distinct !{!35, !36} +!36 = !{!"llvm.loop.mustprogress"} +!37 = !{!38} +!38 = distinct !{!38, !39, !"air-alias-scope-arg(0)"} +!39 = distinct !{!39, !"air-alias-scopes(asm_in_helper)"} +!40 = !{i64 1110} +!41 = !{!42} +!42 = distinct !{!42, !43, !"air-alias-scope-arg(1)"} +!43 = distinct !{!43, !"air-alias-scopes(asm_free)"} +!44 = !{!45} +!45 = distinct !{!45, !43, !"air-alias-scope-arg(0)"} +!46 = distinct !{!46, !36} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.metal b/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.metal new file mode 100644 index 000000000..c2b141c50 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/kernel_inline_asm.metal @@ -0,0 +1,41 @@ +// Owned fixture: inline assembly. An `asm volatile("")` statement in a loop body (the shape a +// shader generator writes so that the compiler keeps a loop) compiles to a call of +// `asm sideeffect "", ""`, a function-local INLINEASM constant (CONSTANTS_BLOCK record 30). MSL +// accepts only that statement: an empty template without operands or clobbers (any other is +// "illegal asm statement"). `asm_in_loop` and `asm_in_helper` call it where their entry reaches +// it; `asm_free` has none of its own, and translates although the module holds the others. +// Written for this repository; no third-party source. +#include +using namespace metal; + +// Each thread stores the xor of its index with every i below n. +kernel void asm_in_loop(device uint *o [[buffer(0)]], + constant uint &n [[buffer(1)]], + uint t [[thread_position_in_grid]]) { + uint acc = 0; + for (uint i = 0; i < n; i++) { + __asm__ volatile(""); + acc += i ^ t; + } + o[t] = acc; +} + +__attribute__((noinline)) static uint asm_helper(uint x) { + __asm__ volatile(""); + return x * 3u + 1u; +} + +kernel void asm_in_helper(device uint *o [[buffer(0)]], uint t [[thread_position_in_grid]]) { + o[t] = asm_helper(t); +} + +// The same store as asm_in_loop, without assembly. +kernel void asm_free(device uint *o [[buffer(0)]], + constant uint &n [[buffer(1)]], + uint t [[thread_position_in_grid]]) { + uint acc = 0; + for (uint i = 0; i < n; i++) { + acc += i ^ t; + } + o[t] = acc; +} diff --git a/crates/metal2vulkan-validation/src/air_writer/infer.rs b/crates/metal2vulkan-validation/src/air_writer/infer.rs index ec9e3c72d..fe06ec94a 100644 --- a/crates/metal2vulkan-validation/src/air_writer/infer.rs +++ b/crates/metal2vulkan-validation/src/air_writer/infer.rs @@ -262,9 +262,12 @@ impl Infer<'_, '_> { return Ok(leaf(node)); } Ok(match &k.value { - Const::Int(_) | Const::Float(_) | Const::Null | Const::Undef | Const::Poison => { - leaf(node) - } + Const::Int(_) + | Const::Float(_) + | Const::Null + | Const::Undef + | Const::Poison + | Const::InlineAsm(_) => leaf(node), Const::Aggregate(elems) => { let mut kids = Vec::with_capacity(elems.len()); for (i, &e) in elems.iter().enumerate() { diff --git a/crates/metal2vulkan-validation/src/air_writer/text.rs b/crates/metal2vulkan-validation/src/air_writer/text.rs index c21018dec..d23f3ab9a 100644 --- a/crates/metal2vulkan-validation/src/air_writer/text.rs +++ b/crates/metal2vulkan-validation/src/air_writer/text.rs @@ -488,6 +488,8 @@ impl Printer<'_, '_> { }, Const::Undef => "undef".into(), Const::Poison => "poison".into(), + // A call's callee: `asm "template", "constraints"`. + Const::InlineAsm(a) => a.spelling(), Const::GlobalAddr(g) => { let g = self.m.global(*g).ok_or_else(|| bad("global"))?; format!("@{}", self.sym(g.name)?) diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 2da383aab..47d9842b4 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 1952; +pub const SEMANTICS_VERSION: u32 = 1953; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index a1c59ca01..af95c4897 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -252,6 +252,7 @@ impl From for Feature { Air::StaticInitializer => Feature::StaticInitializer, Air::Recursion => Feature::Recursion, Air::DynamicCall => Feature::DynamicCall, + Air::InlineAsm => Feature::InlineAsm, Air::Linking => Feature::Linking, Air::Constant { code } => Feature::Constant { code }, Air::Attribute { kind } => Feature::Attribute { kind }, @@ -1123,6 +1124,9 @@ pub enum Feature { Recursion, /// Indirect calls, function pointers, visible/intersection function tables (one variant). DynamicCall, + /// A call to inline assembly (`asm`) that an entry reaches: the IR gives no assembly a + /// meaning. The refusal names the expression (`asm sideeffect "", ""`). + InlineAsm, /// Linkage signatures / stitching / dynamic libraries. Linking, diff --git a/crates/metal2vulkan/src/memory/plan.rs b/crates/metal2vulkan/src/memory/plan.rs index 02a23865d..46543cc0c 100644 --- a/crates/metal2vulkan/src/memory/plan.rs +++ b/crates/metal2vulkan/src/memory/plan.rs @@ -1163,9 +1163,10 @@ impl Planner<'_> { .collect::>() .ok_or_else(|| invariant("a constant's part out of range"))? } - Const::GlobalAddr(_) | Const::FuncAddr(_) | Const::Expr(_) => { - return Err(escaping()) - } + Const::GlobalAddr(_) + | Const::FuncAddr(_) + | Const::Expr(_) + | Const::InlineAsm(_) => return Err(escaping()), }; grow(&mut stack, parts.len().saturating_add(1), m)?; stack.push(Step::Exit((c, ty), parts.clone())); @@ -1310,9 +1311,10 @@ impl Planner<'_> { } m.release(placed_bytes); } - Const::GlobalAddr(_) | Const::FuncAddr(_) | Const::Expr(_) => { - return Err(escaping()) - } + Const::GlobalAddr(_) + | Const::FuncAddr(_) + | Const::Expr(_) + | Const::InlineAsm(_) => return Err(escaping()), } } Ok(()) diff --git a/crates/metal2vulkan/src/tests/engine_inline_asm.rs b/crates/metal2vulkan/src/tests/engine_inline_asm.rs new file mode 100644 index 000000000..14c0f01d3 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_inline_asm.rs @@ -0,0 +1,79 @@ +//! Inline assembly: the owned fixture `engine/kernel_inline_asm`. +//! +//! An MSL `asm volatile("")` compiles to a call of `asm sideeffect "", ""`, whose callee is a +//! function-local INLINEASM constant (CONSTANTS_BLOCK record 30). The module decodes whatever its +//! entries call: `asm_free`, which reaches no assembly although its module holds two calls of it, +//! translates; `asm_in_loop` (a call in a loop body) and `asm_in_helper` (in a helper the entry +//! inlines) are refused as `InlineAsm`, naming the expression. Both spellings are checked: the +//! opaque-pointer `.ll` (`llvm-as`) and the typed-pointer `.air.ll` (`xcrun metal-as`, which +//! writes the record as Apple's compiler does). A missing tool skips visibly. No GPU is used. + +use crate::air::error::DiagName; +use crate::device::DevicePolicy; +use crate::error::{Error, Feature, Needs}; +use crate::pipeline::testing::{ + compile, engine_dir, link_and_validate, llvm_assemble, metal_assemble, profile, AssembleError, +}; +use crate::spirv::testing::committed_profiles; + +const STEM: &str = "kernel_inline_asm"; + +/// The fixture under each available assembler: `(spelling, bitcode)`. +fn spellings() -> Vec<(&'static str, Vec)> { + let mut out = Vec::new(); + for (what, assembled) in [ + ( + "llvm-as", + llvm_assemble(&engine_dir().join(format!("{STEM}.ll"))), + ), + ( + "metal-as", + metal_assemble(&engine_dir().join(format!("{STEM}.air.ll"))), + ), + ] { + match assembled { + Ok(bc) => out.push((what, bc)), + Err(AssembleError::Missing(why)) => eprintln!("SKIPPED {what}: {why}"), + Err(AssembleError::Rejected(why)) => panic!("{what} rejected {STEM}: {why}"), + } + } + out +} + +/// An entry that reaches no assembly translates, and links and validates, on every committed +/// profile, in both spellings: the module's other calls of `asm sideeffect "", ""` cost it +/// nothing. +#[test] +fn an_entry_that_reaches_no_inline_asm_translates() { + let profiles = committed_profiles().expect("profiles"); + for (what, bc) in spellings() { + for (stem, p) in &profiles { + let a = compile(&bc, "asm_free", p) + .unwrap_or_else(|e| panic!("{what} asm_free on {stem}: {e:?}")); + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what} asm_free on {stem}: {e}")); + } + } +} + +/// A call of inline assembly that the entry reaches, in its own body or in a helper it inlines, +/// is refused as `InlineAsm`, not implemented, naming the expression. +#[test] +fn a_reached_inline_asm_call_is_refused_by_name() { + let p = profile("moltenvk-m3", DevicePolicy::default()).expect("profile"); + for (what, bc) in spellings() { + for entry in ["asm_in_loop", "asm_in_helper"] { + match compile(&bc, entry, &p) { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::InlineAsm, "{what} {entry}: {u:?}"); + assert_eq!(u.needs, Needs::NotImplemented, "{what} {entry}"); + assert_eq!( + u.symbol, + Some(DiagName::new(r#"asm sideeffect "", """#)), + "{what} {entry}" + ); + } + other => panic!("{what} {entry}: {other:?}"), + } + } + } +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 84701e2e0..be9d12c4c 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -73,6 +73,7 @@ mod engine_image_shapes; mod engine_imageblock; mod engine_index_words; mod engine_indirect_commands; +mod engine_inline_asm; mod engine_kernel_lod; mod engine_kernel_stage_in; mod engine_lazy_operands; diff --git a/crates/metal2vulkan/tests/air_input/kernel_inline_asm.txt b/crates/metal2vulkan/tests/air_input/kernel_inline_asm.txt new file mode 100644 index 000000000..ce9f1589b --- /dev/null +++ b/crates/metal2vulkan/tests/air_input/kernel_inline_asm.txt @@ -0,0 +1,155 @@ +target triple = "air64_v28-apple-macosx26.0.0" +source_filename = "-" +; datalayout DataLayout { endian: Little, pointers: {0: PointerSpec { size_bits: 64, abi_bits: 64, pref_bits: 64, index_bits: 64 }}, ints: {1: AlignSpec { abi_bits: 8, pref_bits: 8 }, 8: AlignSpec { abi_bits: 8, pref_bits: 8 }, 16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }}, floats: {16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }, 128: AlignSpec { abi_bits: 128, pref_bits: 128 }}, vectors: {16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 24: AlignSpec { abi_bits: 32, pref_bits: 32 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 48: AlignSpec { abi_bits: 64, pref_bits: 64 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }, 96: AlignSpec { abi_bits: 128, pref_bits: 128 }, 128: AlignSpec { abi_bits: 128, pref_bits: 128 }, 192: AlignSpec { abi_bits: 256, pref_bits: 256 }, 256: AlignSpec { abi_bits: 256, pref_bits: 256 }, 512: AlignSpec { abi_bits: 512, pref_bits: 512 }, 1024: AlignSpec { abi_bits: 1024, pref_bits: 1024 }}, aggregate: AlignSpec { abi_bits: 0, pref_bits: 64 }, native_ints: [8, 16, 32], stack_align_bits: None, alloca_space: 0, program_space: 0, globals_space: 0, mangling: None, fn_ptr_align: None, non_integral: [] } +%t5 = type void (ptr addrspace(1), ptr addrspace(2), i32) +%t6 = type void (ptr addrspace(1), i32) +%t7 = type i32 (i32) +%t9 = type [2 x i32] +%t13 = type void () +c6 = %t9 [27, 2] +c18 = ptr addrspace(0) asm sideeffect "", "" + +define %t5 @f0 "asm_in_loop" convergent "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( Mod nocapture "air-buffer-no-alias"="" ) %a1( align 4 dereferenceable(4) Ref nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = load i32, %a1, align 4 + %i1 = icmp eq %i0, i32 0 + br %i1, bb1, bb2 +bb1: + %i3 = phi i32 [i32 0, bb0], [%i12, bb2] + %i4 = zext %a2 to i64 + %i5 = getelementptr inbounds i32, %a0, %i4 + store %i3, %i5, align 4 + ret void +bb2: + %i8 = phi i32 [%i13, bb2], [i32 0, bb0] + %i9 = phi i32 [%i12, bb2], [i32 0, bb0] + tail call void %t13 ptr addrspace(0) c18() convergent + %i11 = xor i32 %i8, %a2 + %i12 = add i32 %i9, %i11 + %i13 = add nuw i32 %i8, i32 1 + %i14 = icmp eq %i13, %i0 + br %i14, bb1, bb2, !llvm.loop LoopHints { unroll: Default, must_progress: true } +} + +define %t6 @f1 "asm_in_helper" convergent "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = tail call i32 @f2(%a1) convergent "no-builtins"="" + %i1 = zext %a1 to i64 + %i2 = getelementptr inbounds i32, %a0, %i1 + store %i0, %i2, align 4 + ret void +} + +define internal %t7 @f2 "_ZL10asm_helperj" fastcc convergent "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" { +bb0: + tail call void %t13 ptr addrspace(0) c18() convergent + %i1 = mul i32 %a0, i32 3 + %i2 = add i32 %i1, i32 1 + ret %i2 +} + +define %t5 @f3 "asm_free" memory(Mod, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( Mod nocapture "air-buffer-no-alias"="" ) %a1( align 4 dereferenceable(4) Ref nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = load i32, %a1, align 4 + %i1 = icmp eq %i0, i32 0 + br %i1, bb1, bb2 +bb1: + %i3 = phi i32 [i32 0, bb0], [%i11, bb2] + %i4 = zext %a2 to i64 + %i5 = getelementptr inbounds i32, %a0, %i4 + store %i3, %i5, align 4 + ret void +bb2: + %i8 = phi i32 [%i12, bb2], [i32 0, bb0] + %i9 = phi i32 [%i11, bb2], [i32 0, bb0] + %i10 = xor i32 %i8, %a2 + %i11 = add i32 %i9, %i10 + %i12 = add nuw i32 %i8, i32 1 + %i13 = icmp eq %i12, %i0 + br %i13, bb1, bb2, !llvm.loop LoopHints { unroll: Default, must_progress: true } +} +!md0 = !"SDK Version" +!md1 = !"wchar_size" +!md2 = !"frame-pointer" +!md3 = !"air.max_device_buffers" +!md4 = !"air.max_constant_buffers" +!md5 = !"air.max_threadgroup_buffers" +!md6 = !"air.max_textures" +!md7 = !"air.max_read_write_textures" +!md8 = !"air.max_samplers" +!md9 = !"air.buffer" +!md10 = !"air.location_index" +!md11 = !"air.read_write" +!md12 = !"air.address_space" +!md13 = !"air.arg_type_size" +!md14 = !"air.arg_type_align_size" +!md15 = !"air.arg_type_name" +!md16 = !"uint" +!md17 = !"air.arg_name" +!md18 = !"o" +!md19 = !"air.buffer_size" +!md20 = !"air.read" +!md21 = !"n" +!md22 = !"air.thread_position_in_grid" +!md23 = !"t" +!md24 = !"air.compile.denorms_disable" +!md25 = !"air.compile.fast_math_enable" +!md26 = !"air.compile.framebuffer_fetch_enable" +!md27 = !"Apple metal version 32023.922 (metalfe-32023.922.4)" +!md28 = !"Metal" +!md29 = !"int" +!md30 = !"omnipotent char" +!md31 = !"Simple C++ TBAA" +!md32 = !"air-alias-scope-arg(1)" +!md33 = !"air-alias-scope-arg(0)" +!md34 = !"llvm.loop.mustprogress" +!md35 = i32 2 +!md36 = %t9 c6 +!md37 = i32 1 +!md38 = i32 4 +!md39 = i32 7 +!md40 = i32 31 +!md41 = i32 128 +!md42 = i32 8 +!md43 = i32 16 +!md44 = ptr addrspace(0) @f0 +!md45 = i32 0 +!md46 = ptr addrspace(0) @f1 +!md47 = ptr addrspace(0) @f3 +!md48 = i64 0 +!md49 = !{!md35, !md0, !md36} +!md50 = !{!md37, !md1, !md38} +!md51 = !{!md39, !md2, !md35} +!md52 = !{!md39, !md3, !md40} +!md53 = !{!md39, !md4, !md40} +!md54 = !{!md39, !md5, !md40} +!md55 = !{!md39, !md6, !md41} +!md56 = !{!md39, !md7, !md42} +!md57 = !{!md39, !md8, !md43} +!md58 = !{} +!md59 = !{!md45, !md9, !md10, !md45, !md37, !md11, !md12, !md37, !md13, !md38, !md14, !md38, !md15, !md16, !md17, !md18} +!md60 = !{!md37, !md9, !md19, !md38, !md10, !md37, !md37, !md20, !md12, !md35, !md13, !md38, !md14, !md38, !md15, !md16, !md17, !md21} +!md61 = !{!md35, !md22, !md15, !md16, !md17, !md23} +!md62 = !{!md59, !md60, !md61} +!md63 = !{!md44, !md58, !md62} +!md64 = !{!md37, !md22, !md15, !md16, !md17, !md23} +!md65 = !{!md59, !md64} +!md66 = !{!md46, !md58, !md65} +!md67 = !{!md47, !md58, !md62} +!md68 = !{!md24} +!md69 = !{!md25} +!md70 = !{!md26} +!md71 = !{!md27} +!md72 = !{!md35, !md42, !md45} +!md73 = !{!md28, !md38, !md45, !md45} +!md74 = !{!md31} +!md75 = !{!md30, !md74, !md48} +!md76 = !{!md29, !md75, !md48} +!md77 = !{!md76, !md76, !md48} +!md78 = !{!md34} +!"llvm.module.flags" = !{!md49, !md50, !md51, !md52, !md53, !md54, !md55, !md56, !md57} +!"air.kernel" = !{!md63, !md66, !md67} +!"air.compile_options" = !{!md68, !md69, !md70} +!"llvm.ident" = !{!md71} +!"air.version" = !{!md72} +!"air.language_version" = !{!md73} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 5a592adc2..2188ce9d2 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1921,6 +1921,12 @@ field metal2vulkan-air::ir::Global.space pub space: AddrSpace field metal2vulkan-air::ir::Global.unnamed_addr pub unnamed_addr: UnnamedAddr field metal2vulkan-air::ir::Global.value_ty pub value_ty: TypeId field metal2vulkan-air::ir::Global.visibility pub visibility: Visibility +field metal2vulkan-air::ir::InlineAsm.align_stack pub align_stack: bool +field metal2vulkan-air::ir::InlineAsm.can_throw pub can_throw: bool +field metal2vulkan-air::ir::InlineAsm.constraints pub constraints: Box<[u8]> +field metal2vulkan-air::ir::InlineAsm.intel_dialect pub intel_dialect: bool +field metal2vulkan-air::ir::InlineAsm.side_effects pub side_effects: bool +field metal2vulkan-air::ir::InlineAsm.template pub template: Box<[u8]> field metal2vulkan-air::ir::Inst.kind pub kind: InstKind field metal2vulkan-air::ir::Inst.ty pub ty: TypeId field metal2vulkan-air::ir::LoopHints.must_progress pub must_progress: bool @@ -7419,6 +7425,7 @@ method metal2vulkan-air::ir::DataLayout::pointer pub fn pointer(&self, space: u3 method metal2vulkan-air::ir::FastMath::is_empty pub const fn is_empty(self) -> bool method metal2vulkan-air::ir::FloatPredicate::mnemonic pub fn mnemonic(self) -> &'static str method metal2vulkan-air::ir::FnAttrs::heap_bytes pub fn heap_bytes(&self) -> usize +method metal2vulkan-air::ir::InlineAsm::spelling pub fn spelling(&self) -> String method metal2vulkan-air::ir::InstKind::for_each_value pub fn for_each_value(&self, mut f: impl FnMut(Value)) method metal2vulkan-air::ir::InstKind::for_each_value_mut pub fn for_each_value_mut(&mut self, mut f: impl FnMut(&mut Value)) method metal2vulkan-air::ir::InstKind::heap_bytes pub fn heap_bytes(&self) -> usize @@ -9340,6 +9347,7 @@ struct metal2vulkan-air::ir::DataLayout #[derive(Clone, Debug, PartialEq, Eq, Ha struct metal2vulkan-air::ir::FnAttrs #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct FnAttrs struct metal2vulkan-air::ir::Function #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Function struct metal2vulkan-air::ir::Global #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Global +struct metal2vulkan-air::ir::InlineAsm #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct InlineAsm struct metal2vulkan-air::ir::Inst #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Inst struct metal2vulkan-air::ir::LoopHints #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct LoopHints struct metal2vulkan-air::ir::MemoryEffects #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct MemoryEffects @@ -10342,6 +10350,7 @@ variant metal2vulkan-air::error::Feature::DynamicCall DynamicCall variant metal2vulkan-air::error::Feature::FunctionConstantArgument FunctionConstantArgument variant metal2vulkan-air::error::Feature::GpuEncodedIndirectCommands GpuEncodedIndirectCommands variant metal2vulkan-air::error::Feature::Imageblocks Imageblocks +variant metal2vulkan-air::error::Feature::InlineAsm InlineAsm variant metal2vulkan-air::error::Feature::Instruction Instruction { code: u32 } variant metal2vulkan-air::error::Feature::IntersectionFunctionTable IntersectionFunctionTable variant metal2vulkan-air::error::Feature::LibraryKind LibraryKind(u8) @@ -10957,6 +10966,7 @@ variant metal2vulkan-air::ir::Const::Expr Expr(ConstExpr) variant metal2vulkan-air::ir::Const::Float Float(u64) variant metal2vulkan-air::ir::Const::FuncAddr FuncAddr(FuncId) variant metal2vulkan-air::ir::Const::GlobalAddr GlobalAddr(GlobalId) +variant metal2vulkan-air::ir::Const::InlineAsm InlineAsm(Box) variant metal2vulkan-air::ir::Const::Int Int(u64) variant metal2vulkan-air::ir::Const::Null Null variant metal2vulkan-air::ir::Const::Poison Poison @@ -13241,6 +13251,7 @@ variant metal2vulkan::error::Feature::Imageblocks Imageblocks variant metal2vulkan::error::Feature::ImplicitLodOutsideFragment ImplicitLodOutsideFragment variant metal2vulkan::error::Feature::IndependentBlending IndependentBlending variant metal2vulkan::error::Feature::IndirectRenderState IndirectRenderState +variant metal2vulkan::error::Feature::InlineAsm InlineAsm variant metal2vulkan::error::Feature::Instruction Instruction { code: u32 } variant metal2vulkan::error::Feature::Int64Arithmetic Int64Arithmetic variant metal2vulkan::error::Feature::Int64Atomics Int64Atomics diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 2e0794c1d..da3ddd4c2 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -27,7 +27,7 @@ Columns: | Kind | Variants | With a site | Reach system | Reach app | Reach rare | Reach none | Unassessed | |---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 127 | 127 | 6 | 32 | 71 | 18 | 0 | +| Translator and front-end refusals | 128 | 128 | 6 | 33 | 71 | 18 | 0 | | Runtime gaps | 73 | 73 | 1 | 8 | 46 | 18 | 0 | | Apple-only calls | 4 | 4 | 0 | 0 | 0 | 4 | 0 | | Binder refusals at a device limit | 9 | 9 | 0 | 1 | 7 | 1 | 0 | @@ -41,7 +41,7 @@ Columns: | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 0 | 48 | 56 | 0 | 0 | 23 | +| Translator and front-end refusals | 0 | 0 | 0 | 48 | 57 | 0 | 0 | 23 | | Runtime gaps | 0 | 0 | 0 | 0 | 73 | 0 | 0 | 0 | | Apple-only calls | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | | Binder refusals at a device limit | 0 | 0 | 0 | 9 | 0 | 0 | 0 | 0 | @@ -67,6 +67,7 @@ Columns: | `StaticInitializer` | A static initializer that cannot be evaluated | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/error.rs (from)` | `none`: LLVM initializers AIR does not emit | | `Recursion` | Recursion (one variant) | every device (not implemented) | `ours` | 4: `crates/metal2vulkan-air/src/canon/mod.rs (recursion, 2 sites)`, `crates/metal2vulkan-air/src/canon/recursion.rs (dynamic_alloca)` (+1) | `rare`: recursion through visible functions | | `DynamicCall` | Indirect calls, function pointers, visible/intersection function tables (one variant) | every device (no Vulkan mechanism); every device (not implemented) | `ours` | 9: `crates/metal2vulkan-air/src/canon/devirt.rs (record)`, `crates/metal2vulkan-air/src/canon/devirt.rs (site)` (+5) | `rare`: function pointers and function tables | +| `InlineAsm` | A call to inline assembly (`asm`) that an entry reaches | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` | `app`: the one inline assembly MSL accepts, an empty asm("") statement, which shader generators write into loop bodies | | `Linking` | Linkage signatures / stitching / dynamic libraries | every device (not implemented) | `ours` | 3: `crates/metal2vulkan-air/src/canon/link.rs (not_implemented)`, `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` (+1) | `rare`: dynamic libraries and linked functions | | `SimdWidth` | Simdgroup width 32 is not achievable for this usage, stage, and device | devices without VkProperty::MetalFragmentSimdgroups; devices without a capability the site computes (`width_needs(stage, st)`) | `device` | 2: `crates/metal2vulkan/src/device/subgroup.rs (subgroup_tier)`, `crates/metal2vulkan/src/lower/simd/mod.rs (finish)` | `app`: simdgroup functions on a device whose subgroups cannot run 32 wide for the use | | `LocalSize` | A local size beyond a device limit on this axis (`None` | every device (no Vulkan mechanism) | `device` | 1: `crates/metal2vulkan/src/bind/dispatch.rs (regions)` | `app`: a threadgroup size past a smaller device's limit | @@ -577,6 +578,7 @@ Each refusal's sites, with the function that builds it. - `feature::StaticInitializer`: `crates/metal2vulkan-air/src/error.rs (from)` - `feature::Recursion`: `crates/metal2vulkan-air/src/canon/mod.rs (recursion, 2 sites)`; `crates/metal2vulkan-air/src/canon/recursion.rs (dynamic_alloca)`; `crates/metal2vulkan-air/src/canon/static_init.rs (run)` - `feature::DynamicCall`: `crates/metal2vulkan-air/src/canon/devirt.rs (record)`; `crates/metal2vulkan-air/src/canon/devirt.rs (site)`; `crates/metal2vulkan-air/src/canon/devirt.rs (unfolded_decl)`; `crates/metal2vulkan-air/src/canon/mod.rs (post_check)`; `crates/metal2vulkan-air/src/canon/prune.rs (prune_in)`; `crates/metal2vulkan/src/bind/heap.rs (directory_bytes, 3 sites)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` +- `feature::InlineAsm`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` - `feature::Linking`: `crates/metal2vulkan-air/src/canon/link.rs (not_implemented)`; `crates/metal2vulkan-air/src/canon/mod.rs (post_check)`; `crates/metal2vulkan-air/src/canon/mod.rs (specialize_dynamic)` - `feature::SimdWidth`: `crates/metal2vulkan/src/device/subgroup.rs (subgroup_tier)`; `crates/metal2vulkan/src/lower/simd/mod.rs (finish)` - `feature::LocalSize`: `crates/metal2vulkan/src/bind/dispatch.rs (regions)` diff --git a/scripts/refusal-surface/reach.tsv b/scripts/refusal-surface/reach.tsv index 27737208b..5922f8505 100644 --- a/scripts/refusal-surface/reach.tsv +++ b/scripts/refusal-surface/reach.tsv @@ -14,6 +14,7 @@ feature AgxUnmodeled rare Apple's own libraries' AGX intrinsics feature StaticInitializer none LLVM initializers AIR does not emit feature Recursion rare recursion through visible functions feature DynamicCall rare function pointers and function tables +feature InlineAsm app the one inline assembly MSL accepts, an empty asm("") statement, which shader generators write into loop bodies feature Linking rare dynamic libraries and linked functions feature SimdWidth app simdgroup functions on a device whose subgroups cannot run 32 wide for the use feature LocalSize app a threadgroup size past a smaller device's limit