From 93d2fc8b95b5f28ec55238aafe0750b45d34f056 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 10:49:31 -0800 Subject: [PATCH] Link a kernel of OpenCL mode as Metal links it: hidden buffers and work-item reads A compute pipeline Metal makes with openCLModeEnabled (Apple SPI) from a kernel of Apple's OpenCL compiler (`__entry_` of a library of sourceLanguage 1) binds three hidden buffers ahead of the kernel's own and reads OpenCL C's work-item functions from the dispatch. Metal refuses a plain pipeline of such a kernel ("Internal compiler error"). Measured on the M3 Max (macOS 27.0.1, jobs m3-max-4483 and m3-max-4504): its reflection lists the kernel's arguments, each buffer 3 past its index and __local memory at its own, then __global_offset_and_num_dims (index 0, read-only uint), __printf_buffer (1, read-write char) and __image_order_data_type_table (2, read-only uint), all used; get_global_id adds buffer 0's offset to the grid position, get_global_offset and get_work_dim read buffer 0, and the other work-item functions are the global built-ins of their names. - ComputePipelineDescriptor::open_cl_mode_enabled, carried into LoweringInputs::open_cl_mode (part of the key) and SpecRequest::open_cl_mode; the stage-entry cache keys on it. - air.get_global_offset.i32 and air.get_work_dim.i32 decode as AirIntrinsic::WorkItem. - canon::opencl, after SCCP and before the global built-ins: appends the three buffers, makes get_global_id(c) the lane plus the offset word, the offset and dimension count loads from buffer 0, a dimension past 2 OpenCL's 0 or 1, and a dimension the kernel reads from its data a select over the three lanes; canon::opencl::entry moves the buffer-indexed arguments 3 on and adds the buffers' bindings, which the reflection's unspecialized path uses too. - Without the mode the kernel compiles as Metal AIR and lowering refuses a WorkItem read (Unsupported, Lowering(Dispatch)). - RuntimeFact::OpenClMode records the mode; a Compiled kernel of the other mode is InvalidDescriptor(OpenClMode). The runtime compiles its variants under the descriptor's mode, and its warm record carries the field (RECORD_FORMAT 5). - SEMANTICS_VERSION 1991, ARTIFACT_FORMAT_VERSION 493 (a fact tag added). Tests: canon::tests::opencl (indices, hidden buffers, the reads' rewrite), the translator's engine_opencl_mode (the M3's reflection, slot writes, key, the mode check), and the runtime's opencl_mode device tests (add, lsum, cmul and every work-item function against the M3's values). (cherry picked from commit e2fdc7b4309c2c239cf1227d0a4c6c54552c1be0) --- .../src/canon/devirt_tests.rs | 1 + .../src/canon/dynamic_tests.rs | 1 + .../metal2vulkan-air/src/canon/link_tests.rs | 1 + crates/metal2vulkan-air/src/canon/mod.rs | 22 +- crates/metal2vulkan-air/src/canon/opencl.rs | 545 ++++++++++++++++++ crates/metal2vulkan-air/src/canon/tests.rs | 3 + .../src/canon/tests/opencl.rs | 260 +++++++++ .../src/intrinsics/families_tests.rs | 4 + crates/metal2vulkan-air/src/intrinsics/mod.rs | 7 +- .../metal2vulkan-air/src/intrinsics/stage.rs | 33 ++ crates/metal2vulkan-air/tests/api_surface.txt | 3 + .../metal2vulkan-runtime/src/pipeline/mod.rs | 3 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/opencl_mode.rs | 492 ++++++++++++++++ crates/metal2vulkan-runtime/src/warm/codec.rs | 4 +- crates/metal2vulkan-validation/src/check.rs | 1 + crates/metal2vulkan/src/cache/codec.rs | 1 + crates/metal2vulkan/src/cache/mod.rs | 4 +- crates/metal2vulkan/src/device/mechanism.rs | 3 + .../src/device/tests/mechanism.rs | 5 +- crates/metal2vulkan/src/error/mod.rs | 5 + crates/metal2vulkan/src/lower/select.rs | 11 +- crates/metal2vulkan/src/memory/plan/tests.rs | 2 + crates/metal2vulkan/src/pipeline/compile.rs | 97 +++- .../metal2vulkan/src/pipeline/compile/api.rs | 18 +- .../metal2vulkan/src/pipeline/compile/key.rs | 4 + .../src/pipeline/compile/partition.rs | 2 + .../metal2vulkan/src/pipeline/descriptor.rs | 17 + crates/metal2vulkan/src/pipeline/facts.rs | 7 + .../metal2vulkan/src/pipeline/lower_inputs.rs | 10 + crates/metal2vulkan/src/reflection/live.rs | 1 + crates/metal2vulkan/src/reflection/mod.rs | 46 +- crates/metal2vulkan/src/tests/air_canon.rs | 2 + .../src/tests/engine_opencl_mode.rs | 289 ++++++++++ crates/metal2vulkan/src/tests/mod.rs | 1 + crates/metal2vulkan/tests/api_signatures.tsv | 10 + docs/API.md | 25 + docs/ARCHITECTURE.md | 2 +- docs/REFUSALS.md | 6 +- 39 files changed, 1913 insertions(+), 37 deletions(-) create mode 100644 crates/metal2vulkan-air/src/canon/opencl.rs create mode 100644 crates/metal2vulkan-air/src/canon/tests/opencl.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/opencl_mode.rs create mode 100644 crates/metal2vulkan/src/tests/engine_opencl_mode.rs diff --git a/crates/metal2vulkan-air/src/canon/devirt_tests.rs b/crates/metal2vulkan-air/src/canon/devirt_tests.rs index 3d27446cf..28bec72f2 100644 --- a/crates/metal2vulkan-air/src/canon/devirt_tests.rs +++ b/crates/metal2vulkan-air/src/canon/devirt_tests.rs @@ -128,6 +128,7 @@ fn arg(i: u32) -> Value { fn request() -> SpecRequest { SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: "k".into(), constants: BTreeMap::new(), } diff --git a/crates/metal2vulkan-air/src/canon/dynamic_tests.rs b/crates/metal2vulkan-air/src/canon/dynamic_tests.rs index 700ba503b..617d53b79 100644 --- a/crates/metal2vulkan-air/src/canon/dynamic_tests.rs +++ b/crates/metal2vulkan-air/src/canon/dynamic_tests.rs @@ -309,6 +309,7 @@ fn store(f: &mut FunctionBuilder<'_>, val: Value, ptr: Value) { fn request() -> SpecRequest { SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: "k".into(), constants: BTreeMap::new(), } diff --git a/crates/metal2vulkan-air/src/canon/link_tests.rs b/crates/metal2vulkan-air/src/canon/link_tests.rs index 10b916c62..52e2473bd 100644 --- a/crates/metal2vulkan-air/src/canon/link_tests.rs +++ b/crates/metal2vulkan-air/src/canon/link_tests.rs @@ -251,6 +251,7 @@ fn code(l: &mut LinkedModule) -> &mut LinkedCode { fn request() -> SpecRequest { SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: "k".into(), constants: BTreeMap::new(), } diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index ba6d60c4e..9bad33195 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -61,7 +61,9 @@ //! and vector members' accesses, joined by `insertvalue` or split by `extractvalue` //! (`aggregates`). **Global built-in //! variables**: each `air.get_*` read of a program-scope built-in becomes a read of a built-in -//! parameter appended to the entry (`global_builtin`). +//! parameter appended to the entry (`global_builtin`); in OpenCL mode, first, the entry takes +//! the three hidden buffers and each OpenCL C work-item read becomes a read of its built-in or +//! of the first buffer ([`opencl`]). //! 10. **ABI resolution and pruning**: predicate-gated parameters and outputs that are off //! disappear from the entry point, a read of an absent argument takes its absent value (the //! null reference of a resource argument) or is refused, global-valued ABI integers become @@ -97,6 +99,7 @@ mod link; #[cfg(test)] mod link_tests; mod matmul2d; +pub mod opencl; mod out; mod pieces; mod prune; @@ -161,6 +164,11 @@ pub struct SpecRequest { /// The pipeline's `maxCallStackDepth`: it sizes the explicit call stack of a recursion through /// visible functions. 0 is taken as 1, Metal's default. pub call_stack_depth: u32, + /// The entry is a kernel of a compute pipeline of OpenCL mode (`openCLModeEnabled`, Apple + /// SPI): it takes three hidden buffers before its own, each of its buffer-indexed arguments + /// sits 3 past its index, and OpenCL C's work-item functions read the dispatch's values + /// ([`opencl`]). Any other entry than a kernel specializes as without it. + pub open_cl_mode: bool, } /// The constexpr samplers of one linked function that a pipeline state numbers @@ -667,6 +675,14 @@ pub fn specialize_dynamic( } else { body }; + // OpenCL mode: the three hidden buffers appended to the entry, and each OpenCL work-item read + // a read of its built-in or of the first buffer, which the global built-ins below take. + let (body, hidden) = if req.open_cl_mode && matches!(ep.stage, Stage::Kernel { .. }) { + let (body, first) = opencl::expand(body, &mut parts, func, m)?; + (body, Some(first)) + } else { + (body, None) + }; // Global built-in variables: each read becomes a read of a built-in parameter added to the // entry, but one Metal refuses in the entry's stage. let (body, global_builtins) = global_builtin::expand(body, &mut parts, func, &ep.stage, m)?; @@ -692,6 +708,10 @@ pub fn specialize_dynamic( if let Some(lanes) = lanes { ep.params.extend(lanes.bindings()); } + // OpenCL mode's indices and hidden buffers. + if let Some(first) = hidden { + ep = opencl::entry(ep, first)?; + } // The built-in parameters the global built-ins' reads became. ep.params.extend(global_builtins); // A table whose every use devirtualization rewrote is read as a buffer of words. diff --git a/crates/metal2vulkan-air/src/canon/opencl.rs b/crates/metal2vulkan-air/src/canon/opencl.rs new file mode 100644 index 000000000..53a49abe3 --- /dev/null +++ b/crates/metal2vulkan-air/src/canon/opencl.rs @@ -0,0 +1,545 @@ +//! Metal's OpenCL mode: a kernel of Apple's OpenCL compiler linked as a compute pipeline made with +//! `openCLModeEnabled` links it ([`SpecRequest::open_cl_mode`](super::SpecRequest)). +//! +//! Apple's OpenCL compiler (`newLibraryWithSource` with `sourceLanguage` 1) writes each kernel as +//! an entry `__entry_` that loads each value passed by value from its constant pointer and +//! calls the kernel, an internal function, which calls OpenCL C's work-item functions as internal +//! wrappers of `air.get_*` intrinsics: `get_global_id(d)` is `air.get_global_id.i32(d)` widened, +//! `get_global_offset(d)` `air.get_global_offset.i32(d)` and `get_work_dim()` +//! `air.get_work_dim.i32()` ([`WorkItem`]); the others are the reads of a global built-in +//! ([`GlobalBuiltin`]). What a pipeline of OpenCL mode answers, measured on an M3 Max (macOS +//! 27.0.1; Metal refuses a plain pipeline of the same function, "Internal compiler error"): +//! +//! - **Hidden buffers.** Three buffers come before the kernel's own: `__global_offset_and_num_dims` +//! at index 0 (`uint`, read-only, constant), four words the dispatcher fills with the dispatch's +//! global offset in each of its dimensions and its dimension count; `__printf_buffer` at 1 +//! (`char`, read-write); and `__image_order_data_type_table` at 2 (`uint`, read-only, +//! constant). The pipeline's reflection lists them after the kernel's arguments, each used. +//! - **Indices.** Each argument bound at a buffer index sits 3 past the index its node states; +//! threadgroup memory (`__local`), textures and samplers keep theirs. +//! - **Work-item functions.** `get_global_id(d)` is the thread's position in the grid plus the +//! offset in `d`, `get_global_offset(d)` the offset, `get_work_dim()` the count, and +//! `get_local_id`, `get_group_id`, `get_local_size`, `get_global_size` and `get_num_groups` the +//! built-ins they read as program-scope variables. A grid of 8 by 4 threads in threadgroups of 4 +//! by 2 at offset (3, 5), of two dimensions, answers each value of every thread, for constant +//! dimensions and for a dimension the kernel is given. +//! +//! [`expand`] runs after SCCP, whose constants name each read's dimension, and before the global +//! built-ins (`global_builtin`) take the reads it leaves. It appends the three buffers to the entry +//! and rewrites each read of a dimension `c` below 3: `get_global_id(c)` becomes the built-in's +//! read of lane `c` plus word `c` of the first buffer, `get_global_offset(c)` that word, and +//! `get_work_dim()` word 3. A read of a dimension past 2 is OpenCL's answer for it, 0 for an id +//! or an offset and 1 for a size or a count (the M3 Max leaves the store of such a value +//! unwritten). A read of a dimension no constant names selects among its reads of the three lanes, +//! with OpenCL's answer past them. [`entry`] then moves the entry's buffer-indexed arguments 3 on +//! and adds the three buffers' bindings. + +use crate::abi::{ + AbiInt, Access, ArgTypeInfo, BufferArg, EntryPoint, ParamBinding, ParamRole, Slot, +}; +use crate::budget::Meter; +use crate::error::{DiagName, Error}; +use crate::intrinsics::{AirIntrinsic, Elem, GlobalBuiltin, GlobalVar, WorkItem}; +use crate::ir::{ + AddrSpace, Align, ArgIdx, BinOp, Block, Body, Call, Callee, CastOp, Const, Constant, FastMath, + FuncId, Idx, Inst, InstId, InstKind, IntFlags, IntPredicate, ModuleParts, Type, TypeId, Value, +}; + +use super::rewrite::{append_params, invariant}; + +/// How far past the index its node states a buffer-indexed argument sits: past the three hidden +/// buffers. +const HIDDEN_BUFFERS: u32 = 3; + +/// The hidden buffers, in index order: their names, element types, sizes, accesses and address +/// spaces, as the M3 Max's reflection states them. +const BUFFERS: [(&str, &str, u32, Access, AddrSpace); 3] = [ + ( + "__global_offset_and_num_dims", + "uint", + 4, + Access::Read, + AddrSpace::Constant, + ), + ( + "__printf_buffer", + "char", + 1, + Access::ReadWrite, + AddrSpace::Device, + ), + ( + "__image_order_data_type_table", + "uint", + 4, + Access::Read, + AddrSpace::Constant, + ), +]; + +/// The word of the first hidden buffer that holds the dispatch's dimension count. +const WORK_DIM_WORD: u64 = 3; + +/// An OpenCL work-item read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Read { + /// A built-in's lane, read as a global built-in. + Builtin(GlobalBuiltin), + /// `get_global_offset(d)`. + Offset, + /// `get_work_dim()`. + WorkDim, +} + +impl Read { + /// The read's element: the built-in's width, or `i32`. + fn elem(self) -> Elem { + match self { + Read::Builtin(g) => g.ty, + Read::Offset | Read::WorkDim => Elem::I32, + } + } + + /// OpenCL's answer for a dimension past 2: 0 for an id or an offset, 1 for a size or a count. + fn past(self) -> u64 { + match self { + Read::Builtin(GlobalBuiltin { + var: + GlobalVar::ThreadsPerThreadgroup + | GlobalVar::ThreadsPerGrid + | GlobalVar::ThreadgroupsPerGrid, + .. + }) => 1, + _ => 0, + } + } + + /// Whether the read takes a dimension. + fn dimensioned(self) -> bool { + self != Read::WorkDim + } +} + +/// The OpenCL work-item read `kind` is, with its call: a read of one of the six built-ins OpenCL C +/// names, `get_global_offset` or `get_work_dim`. +fn read(kind: &InstKind) -> Option<(Read, &Call)> { + let InstKind::Call(call) = kind else { + return None; + }; + let Callee::Air { op, .. } = call.callee else { + return None; + }; + let read = match op { + AirIntrinsic::GlobalBuiltin( + g @ GlobalBuiltin { + var: + GlobalVar::ThreadPositionInGrid + | GlobalVar::ThreadPositionInThreadgroup + | GlobalVar::ThreadgroupPositionInGrid + | GlobalVar::ThreadsPerThreadgroup + | GlobalVar::ThreadsPerGrid + | GlobalVar::ThreadgroupsPerGrid, + .. + }, + ) => Read::Builtin(g), + AirIntrinsic::WorkItem(WorkItem::GlobalOffset) => Read::Offset, + AirIntrinsic::WorkItem(WorkItem::WorkDim) => Read::WorkDim, + _ => return None, + }; + Some((read, call)) +} + +/// The dimension a read names: a constant, or a value no constant gives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Dim { + Const(u64), + Value(Value), +} + +/// The dimension call `call` of `r` names (`Const(WORK_DIM_WORD)` for `get_work_dim`, which +/// names none). +fn dim(parts: &ModuleParts, r: Read, call: &Call) -> Result { + if !r.dimensioned() { + return Ok(Dim::Const(WORK_DIM_WORD)); + } + let [v] = call.args.as_ref() else { + return Err(invariant("a work-item read without its dimension")); + }; + Ok(match v { + Value::Const(c) => match parts.consts.get(*c).map(|k| &k.value) { + Some(Const::Int(n)) => Dim::Const(*n), + _ => Dim::Value(*v), + }, + _ => Dim::Value(*v), + }) +} + +/// An instruction sink over the output body. +struct Sink<'a> { + out: &'a mut Body, + parts: &'a mut ModuleParts, + /// The first hidden buffer's parameter. + offsets: Value, +} + +impl Sink<'_> { + fn ty(&mut self, t: Type, m: &mut Meter) -> Result { + self.parts.types.intern(t, m) + } + + fn elem_ty(&mut self, e: Elem, m: &mut Meter) -> Result { + let bits = match e { + Elem::I16 => 16, + _ => 32, + }; + self.ty(Type::Int(bits), m) + } + + fn int(&mut self, e: Elem, v: u64, m: &mut Meter) -> Result { + let ty = self.elem_ty(e, m)?; + let c = self.parts.consts.intern( + Constant { + ty, + value: Const::Int(v), + }, + m, + )?; + Ok(Value::Const(c)) + } + + fn push(&mut self, ty: TypeId, kind: InstKind, m: &mut Meter) -> Result { + let id = self.out.push_inst(Inst { ty, kind }, m)?; + Ok(Value::Inst(id)) + } + + /// Word `w` of the first hidden buffer, in `e`. + fn word(&mut self, w: u64, e: Elem, m: &mut Meter) -> Result { + let i32t = self.elem_ty(Elem::I32, m)?; + let ptr = self.ty( + Type::Ptr { + space: AddrSpace::Constant, + }, + m, + )?; + let index = self.int(Elem::I32, w, m)?; + let at = self.push( + ptr, + InstKind::Gep { + src_ty: i32t, + base: self.offsets, + indices: Box::new([index]), + inbounds: true, + }, + m, + )?; + let word = self.push( + i32t, + InstKind::Load { + ptr: at, + align: Align::from_bytes(4), + volatile: false, + atomic: None, + range: None, + }, + m, + )?; + if e == Elem::I32 { + return Ok(word); + } + let to = self.elem_ty(e, m)?; + self.push( + to, + InstKind::Cast { + op: CastOp::Trunc, + v: word, + }, + m, + ) + } + + /// Read `r` of the constant dimension `c`, `call` (of result type `ty`) the original read. + fn at( + &mut self, + r: Read, + call: &Call, + ty: TypeId, + c: u64, + m: &mut Meter, + ) -> Result { + let e = r.elem(); + if r.dimensioned() && c > 2 { + return self.int(e, r.past(), m); + } + match r { + Read::Offset | Read::WorkDim => self.word(c, e, m), + Read::Builtin(g) => { + let lane = self.int(e, c, m)?; + let mut lane_read = call.clone(); + lane_read.args = Box::new([lane]); + let v = self.push(ty, InstKind::Call(lane_read), m)?; + if g.var != GlobalVar::ThreadPositionInGrid { + return Ok(v); + } + let offset = self.word(c, e, m)?; + self.push( + ty, + InstKind::BinOp { + op: BinOp::Add, + flags: IntFlags::NONE, + fmf: FastMath::NONE, + a: v, + b: offset, + }, + m, + ) + } + } + } + + /// Whether dimension `d` of read `r` is `c`. + fn is(&mut self, r: Read, d: Value, c: u64, m: &mut Meter) -> Result { + let i1 = self.ty(Type::Int(1), m)?; + let b = self.int(r.elem(), c, m)?; + self.push( + i1, + InstKind::ICmp { + pred: IntPredicate::Eq, + a: d, + b, + }, + m, + ) + } + + /// Read `r` (of result type `ty`) of dimension `d`, `call` the original read. A dimension no + /// constant names selects among the three lanes' reads, OpenCL's answer past them; the last + /// instruction pushed is the result, or the result is a constant and none is pushed. + fn emit( + &mut self, + r: Read, + call: &Call, + ty: TypeId, + d: Dim, + m: &mut Meter, + ) -> Result { + let d = match d { + Dim::Const(c) => return self.at(r, call, ty, c, m), + Dim::Value(d) => d, + }; + let lanes = [ + self.at(r, call, ty, 0, m)?, + self.at(r, call, ty, 1, m)?, + self.at(r, call, ty, 2, m)?, + ]; + let is = [ + self.is(r, d, 0, m)?, + self.is(r, d, 1, m)?, + self.is(r, d, 2, m)?, + ]; + let mut v = self.int(r.elem(), r.past(), m)?; + for (lane, cmp) in lanes.into_iter().zip(is).rev() { + v = self.push( + ty, + InstKind::Select { + c: cmp, + t: lane, + f: v, + fmf: FastMath::NONE, + }, + m, + )?; + } + Ok(v) + } +} + +/// What one instruction of the old body becomes: its read's expansion, `len` instructions whose +/// last is its value, or (`len` 0) a constant. +#[derive(Clone, Copy, Debug)] +struct Expansion { + len: u32, + constant: Option, +} + +/// The expansion of read `r` of dimension `d` (`call`, of result type `ty`), measured by +/// emitting it into a scratch body. +fn measure( + parts: &mut ModuleParts, + offsets: Value, + (r, call, ty, d): (Read, &Call, TypeId, Dim), + m: &mut Meter, +) -> Result { + let mut scratch = Body::default(); + let mut s = Sink { + out: &mut scratch, + parts, + offsets, + }; + let v = s.emit(r, call, ty, d, m)?; + let len = u32::try_from(scratch.insts.len()).map_err(|_| invariant("expansion length"))?; + scratch.release(m); + Ok(Expansion { + len, + constant: (len == 0).then_some(v), + }) +} + +/// Append the three hidden buffers to the entry `func` and make each OpenCL work-item read of its +/// solved `body` a read of a built-in or of the first buffer (see the module), returning the new +/// body and the first buffer's parameter index. +pub(super) fn expand( + body: Body, + parts: &mut ModuleParts, + func: FuncId, + m: &mut Meter, +) -> Result<(Body, u32), Error> { + let [a, b, c] = BUFFERS.map(|(.., space)| Type::Ptr { space }); + let tys = [ + parts.types.intern(a, m)?, + parts.types.intern(b, m)?, + parts.types.intern(c, m)?, + ]; + let first = append_params(parts, func, &tys, m)?; + let offsets = Value::Arg(ArgIdx::new(first)); + if !body.insts.iter().any(|(_, i)| read(&i.kind).is_some()) { + return Ok((body, first)); + } + // Each old instruction's value in the output: an expansion's last instruction, or its + // constant. + let mut result: Vec = Vec::new(); + m.reserve(&mut result, body.insts.len())?; + let mut next = 0u32; + for (_, inst) in body.insts.iter() { + m.tick(1)?; + let e = match read(&inst.kind) { + Some((r, call)) => { + let d = dim(parts, r, call)?; + measure(parts, offsets, (r, call, inst.ty, d), m)? + } + None => Expansion { + len: 1, + constant: None, + }, + }; + next = next + .checked_add(e.len) + .ok_or_else(|| invariant("instruction ids"))?; + result.push(match e.constant { + Some(c) => c, + None => Value::Inst(InstId::new(next - 1)), + }); + } + let map = |val: Value| -> Result { + match val { + Value::Inst(i) => result + .get(i.index()) + .copied() + .ok_or_else(|| invariant("an operand out of range")), + other => Ok(other), + } + }; + let mut out = Body::default(); + for (_, block) in body.blocks.iter() { + m.tick(1)?; + let start = InstId::new(u32::try_from(out.insts.len()).map_err(|_| invariant("ids"))?); + for i in block.inst_ids() { + let inst = body + .insts + .get(i) + .ok_or_else(|| invariant("instruction out of range"))?; + let mut kind = inst.kind.clone(); + let mut failed = None; + kind.for_each_value_mut(|val| match map(*val) { + Ok(n) => *val = n, + Err(e) => { + failed.get_or_insert(e); + } + }); + if let Some(e) = failed { + return Err(e); + } + let found = read(&kind).map(|(r, call)| (r, call.clone())); + let value = match found { + Some((r, call)) => { + let d = dim(parts, r, &call)?; + let mut s = Sink { + out: &mut out, + parts, + offsets, + }; + s.emit(r, &call, inst.ty, d, m)? + } + None => { + let id = out.push_inst(Inst { ty: inst.ty, kind }, m)?; + Value::Inst(id) + } + }; + if result.get(i.index()) != Some(&value) { + return Err(invariant( + "a work-item read's expansion differs from its measure", + )); + } + } + let end = InstId::new(u32::try_from(out.insts.len()).map_err(|_| invariant("ids"))?); + out.blocks.push( + Block { + start, + end, + name: block.name, + }, + m, + )?; + } + m.release(result.len().saturating_mul(std::mem::size_of::())); + // The body the expansions replaced is freed. + body.release(m); + Ok((out, first)) +} + +/// Entry point `ep` as a pipeline of OpenCL mode binds it, the three hidden buffers its parameters +/// `first` to `first + 2`: each argument bound at a buffer index 3 past its own (an argument +/// buffer, a function table and an acceleration structure as a buffer), threadgroup memory, +/// textures and samplers at theirs, and the buffers' bindings after the entry's own. +pub fn entry(mut ep: EntryPoint, first: u32) -> Result { + for p in &mut ep.params { + let slot = match &mut p.role { + ParamRole::Buffer(b) | ParamRole::ArgumentBuffer(b) => &mut b.location, + ParamRole::AccelerationStructure { arg, .. } + | ParamRole::FunctionTable(arg) + | ParamRole::IntersectionTable(arg) => &mut arg.location, + _ => continue, + }; + if let AbiInt::Const(index) = &mut slot.index { + *index = index + .checked_add(HIDDEN_BUFFERS) + .ok_or_else(|| invariant("a buffer index past the index space"))?; + } + } + for (index, (&(name, ty, size, access, space), param)) in + (0u32..).zip(BUFFERS.iter().zip(first..)) + { + ep.params.push(ParamBinding { + param, + role: ParamRole::Buffer(BufferArg { + location: Slot { + index: AbiInt::Const(index), + count: AbiInt::Const(1), + }, + access, + space, + buffer_size: None, + layout: None, + raster_order_group: None, + }), + unused: false, + predicate: None, + ty: ArgTypeInfo { + size: Some(size), + align: Some(size), + name: Some(DiagName::new(ty)), + }, + name: Some(DiagName::new(name)), + }); + } + Ok(ep) +} diff --git a/crates/metal2vulkan-air/src/canon/tests.rs b/crates/metal2vulkan-air/src/canon/tests.rs index 4206df7b8..8e1b0e7c0 100644 --- a/crates/metal2vulkan-air/src/canon/tests.rs +++ b/crates/metal2vulkan-air/src/canon/tests.rs @@ -24,6 +24,7 @@ mod constant_fields; mod conversions; mod float_compares; mod global_builtins; +mod opencl; mod private_memory; mod table_copies; mod texture_writes; @@ -169,6 +170,7 @@ fn int(v: u32) -> ConstValue { fn request(constants: &[(u32, ConstValue)]) -> SpecRequest { SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: "k".into(), constants: constants.iter().cloned().collect::>(), } @@ -2633,6 +2635,7 @@ fn a_static_initializer_branch_on_an_unsupplied_constant_takes_its_false_way() { assert_eq!(on.unwrap(), [Ok(1)]); let r = SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: "k".into(), constants: [(3, boolean(1))].into_iter().collect(), }; diff --git a/crates/metal2vulkan-air/src/canon/tests/opencl.rs b/crates/metal2vulkan-air/src/canon/tests/opencl.rs new file mode 100644 index 000000000..9dde7be37 --- /dev/null +++ b/crates/metal2vulkan-air/src/canon/tests/opencl.rs @@ -0,0 +1,260 @@ +//! OpenCL mode (`SpecRequest::open_cl_mode`): a kernel in the shape Apple's OpenCL compiler writes +//! takes the three hidden buffers after its own parameters, each buffer-indexed argument 3 past its +//! index, and each work-item read a read of its built-in or of the first buffer. Without the mode +//! the same kernel specializes as Metal AIR, its OpenCL-only reads left for lowering to refuse. +//! The modules are LLVM text written here, assembled with `llvm-as`; a run without it skips. + +use super::*; +use crate::abi::Builtin; +use crate::intrinsics::WorkItem; + +const HEAD: &str = "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\"\n\ +target triple = \"air64_v29-apple-macosx27.0.0\"\n"; + +/// `@k(device uint *x [[buffer(0)]], constant uint *c [[buffer(1)]], threadgroup uint *t +/// [[threadgroup(0)]])`: `x[0..6]` take `get_global_id(0)`, `get_global_offset(1)`, +/// `get_work_dim()`, `get_local_size(4)`, `get_global_id(c[0])` and `get_num_groups(c[0])`, and +/// `t[0]` takes 0; each read through an internal wrapper widening it, as the OpenCL compiler +/// writes them. +const KERNEL: &str = "define void @k(ptr addrspace(1) %x, ptr addrspace(2) %c, ptr addrspace(3) %t) #0 {\n\ + %d = load i32, ptr addrspace(2) %c, align 4\n\ + %g = tail call fastcc i64 @gid(i32 0)\n\ + %o = tail call i32 @air.get_global_offset.i32(i32 1)\n\ + %w = tail call i32 @air.get_work_dim.i32()\n\ + %s = tail call i32 @air.get_local_size.i32(i32 4)\n\ + %v = tail call fastcc i64 @gid(i32 %d)\n\ + %n = tail call i32 @air.get_num_groups.i32(i32 %d)\n\ + %g32 = trunc i64 %g to i32\n\ + store i32 %g32, ptr addrspace(1) %x, align 4\n\ + %x1 = getelementptr inbounds i32, ptr addrspace(1) %x, i64 1\n\ + store i32 %o, ptr addrspace(1) %x1, align 4\n\ + %x2 = getelementptr inbounds i32, ptr addrspace(1) %x, i64 2\n\ + store i32 %w, ptr addrspace(1) %x2, align 4\n\ + %x3 = getelementptr inbounds i32, ptr addrspace(1) %x, i64 3\n\ + store i32 %s, ptr addrspace(1) %x3, align 4\n\ + %v32 = trunc i64 %v to i32\n\ + %x4 = getelementptr inbounds i32, ptr addrspace(1) %x, i64 4\n\ + store i32 %v32, ptr addrspace(1) %x4, align 4\n\ + %x5 = getelementptr inbounds i32, ptr addrspace(1) %x, i64 5\n\ + store i32 %n, ptr addrspace(1) %x5, align 4\n\ + store i32 0, ptr addrspace(3) %t, align 4\n\ + ret void\n}\n\ +define internal fastcc i64 @gid(i32 %dim) #1 {\n\ + %r = tail call i32 @air.get_global_id.i32(i32 %dim) #2\n\ + %z = zext i32 %r to i64\n\ + ret i64 %z\n}\n\ +declare i32 @air.get_global_id.i32(i32) #2\n\ +declare i32 @air.get_global_offset.i32(i32) #2\n\ +declare i32 @air.get_work_dim.i32() #2\n\ +declare i32 @air.get_local_size.i32(i32) #2\n\ +declare i32 @air.get_num_groups.i32(i32) #2\n\ +attributes #0 = { nounwind }\n\ +attributes #1 = { nounwind optsize }\n\ +attributes #2 = { nounwind readnone willreturn }\n\ +!air.kernel = !{!0}\n\ +!air.version = !{!6}\n\ +!air.language_version = !{!7}\n\ +!0 = !{ptr @k, !1, !2}\n\ +!1 = !{}\n\ +!2 = !{!3, !4, !5}\n\ +!3 = !{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\", !\"x\"}\n\ +!4 = !{i32 1, !\"air.buffer\", !\"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\", !\"c\"}\n\ +!5 = !{i32 2, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 3, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"t\"}\n\ +!6 = !{i32 2, i32 9, i32 0}\n\ +!7 = !{!\"Metal\", i32 1, i32 1, i32 0}\n"; + +/// [`KERNEL`] specialized, in OpenCL mode where `open_cl_mode`; `None` without `llvm-as`. +fn specialized(test: &str, open_cl_mode: bool) -> Option { + let bitcode = match metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{KERNEL}")) { + Ok(b) => b, + Err(e) => { + eprintln!("SKIP {test}: {e:?}"); + return None; + } + }; + let d = crate::bitcode::decode(&bitcode, &mut meter()).expect("decoded"); + let req = SpecRequest { + entry: "k".into(), + open_cl_mode, + ..SpecRequest::default() + }; + Some(specialize(d.module, &d.abi, &req, &mut meter()).expect("specialized")) +} + +/// The slot index of each of the entry's resource parameters, by parameter and role. +fn slots(e: &Entry) -> Vec<(u32, &'static str, u32)> { + e.ep.params + .iter() + .filter_map(|p| { + let (kind, b) = match &p.role { + ParamRole::Buffer(b) => ("buffer", b), + ParamRole::Threadgroup(b) => ("threadgroup", b), + _ => return None, + }; + let AbiInt::Const(index) = b.location.index else { + panic!("{p:?}"); + }; + Some((p.param, kind, index)) + }) + .collect() +} + +/// The entry's body. +fn body(e: &Entry) -> &crate::ir::Body { + e.module + .func(e.func) + .and_then(|f| f.body.as_ref()) + .expect("the entry's body") +} + +/// The `air.*` calls the entry's body still makes that `keep` selects. +fn calls(e: &Entry, keep: impl Fn(&AirIntrinsic) -> bool) -> usize { + body(e) + .insts + .values() + .filter(|i| matches!(&i.kind, InstKind::Call(c) if matches!(&c.callee, Callee::Air { op, .. } if keep(op)))) + .count() +} + +#[test] +fn opencl_mode_moves_buffer_indices_past_the_three_hidden_buffers() { + let test = "opencl_mode_moves_buffer_indices_past_the_three_hidden_buffers"; + let (Some(plain), Some(cl)) = (specialized(test, false), specialized(test, true)) else { + return; + }; + assert_eq!( + slots(&plain), + [(0, "buffer", 0), (1, "buffer", 1), (2, "threadgroup", 0)] + ); + // The kernel's buffers 3 on, its threadgroup memory where it was, the hidden buffers after + // its own parameters at 0 to 2. + assert_eq!( + slots(&cl), + [ + (0, "buffer", 3), + (1, "buffer", 4), + (2, "threadgroup", 0), + (3, "buffer", 0), + (4, "buffer", 1), + (5, "buffer", 2) + ] + ); + let hidden: Vec<_> = cl.ep.params[3..6] + .iter() + .map(|p| { + let ParamRole::Buffer(b) = &p.role else { + panic!("{p:?}"); + }; + ( + p.name.as_ref().map(ToString::to_string), + p.ty.name.as_ref().map(ToString::to_string), + p.ty.size, + b.access, + b.space, + ) + }) + .collect(); + let named = |name: &str, ty: &str, size, access, space| { + ( + Some(name.to_owned()), + Some(ty.to_owned()), + Some(size), + access, + space, + ) + }; + assert_eq!( + hidden, + [ + named( + "__global_offset_and_num_dims", + "uint", + 4, + Access::Read, + AddrSpace::Constant + ), + named( + "__printf_buffer", + "char", + 1, + Access::ReadWrite, + AddrSpace::Device + ), + named( + "__image_order_data_type_table", + "uint", + 4, + Access::Read, + AddrSpace::Constant + ), + ] + ); +} + +#[test] +fn opencl_work_item_reads_become_built_ins_and_the_first_hidden_buffer() { + let test = "opencl_work_item_reads_become_built_ins_and_the_first_hidden_buffer"; + let (Some(plain), Some(cl)) = (specialized(test, false), specialized(test, true)) else { + return; + }; + let work_item = |op: &AirIntrinsic| matches!(op, AirIntrinsic::WorkItem(_)); + let builtin = |op: &AirIntrinsic| matches!(op, AirIntrinsic::GlobalBuiltin(_)); + // As Metal AIR: the offset and the dimension count stay calls, as do the reads at dimension + // 4 and at the loaded dimension, which lowering refuses. + assert_eq!(calls(&plain, work_item), 2); + assert_eq!(calls(&plain, builtin), 3); + // In OpenCL mode no work-item call is left. + assert_eq!(calls(&cl, work_item), 0); + assert_eq!(calls(&cl, builtin), 0); + // The words of the first hidden buffer (parameter 3) read: the offset `get_global_id(0)` + // adds, `get_global_offset(1)`, the dimension count, and one offset for each lane the loaded + // dimension may name. + let words = body(&cl) + .insts + .values() + .filter(|i| matches!(i.kind, InstKind::Gep { base: Value::Arg(a), .. } if a.index() == 3)) + .count(); + assert_eq!(words, 6); + // `get_local_size(4)` is OpenCL's 1, stored as a constant. + let stored_one = body(&cl).insts.values().any(|i| match i.kind { + InstKind::Store { + val: Value::Const(c), + .. + } => matches!( + cl.module.consts().get(c).map(|k| &k.value), + Some(Const::Int(1)) + ), + _ => false, + }); + assert!(stored_one, "{}", print(&cl.module)); + // The built-ins the lanes read: the grid position and the threadgroup count. + let builtins: Vec<_> = cl + .ep + .params + .iter() + .filter_map(|p| match p.role { + ParamRole::Builtin(b) => Some(b), + _ => None, + }) + .collect(); + assert_eq!( + builtins, + [Builtin::ThreadPositionInGrid, Builtin::ThreadgroupsPerGrid] + ); + // The intrinsic the plain entry leaves is the one OpenCL mode reads from the buffer. + let left: Vec<_> = body(&plain) + .insts + .values() + .filter_map(|i| match &i.kind { + InstKind::Call(c) => match c.callee { + Callee::Air { + op: AirIntrinsic::WorkItem(w), + .. + } => Some(w), + _ => None, + }, + _ => None, + }) + .collect(); + assert_eq!(left, [WorkItem::GlobalOffset, WorkItem::WorkDim]); +} diff --git a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs index 3383c722c..9b62e1e1b 100644 --- a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs +++ b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs @@ -760,6 +760,10 @@ const OBSERVED: &[(&str, &str)] = &[ ("air.get_dispatch_threads_per_threadgroup.i32", "i32 (i32)"), ("air.get_local_linear_id.i32", "i32 ()"), ("air.get_quadgroups_per_threadgroup.i32", "i32 ()"), + // OpenCL C's `get_global_offset(d)` and `get_work_dim()` (Apple's OpenCL compiler, macOS + // 27.0.1). + ("air.get_global_offset.i32", "i32 (i32)"), + ("air.get_work_dim.i32", "i32 ()"), // Simdgroup matrices. ( "air.simdgroup_matrix_8x8_load.v64f32.p3f32", diff --git a/crates/metal2vulkan-air/src/intrinsics/mod.rs b/crates/metal2vulkan-air/src/intrinsics/mod.rs index 075130913..40d8ed3b4 100644 --- a/crates/metal2vulkan-air/src/intrinsics/mod.rs +++ b/crates/metal2vulkan-air/src/intrinsics/mod.rs @@ -76,7 +76,7 @@ pub use sig::{HandleKind, ImageDim, ImageShape, Immediates, Operand, Signature}; pub use simd::{Group, GroupOp, GroupScope, IsUniform, SimdgroupSize}; pub use stage::Imageblock; pub use stage::{AbsentAccess, BoolReduce, Derivative, DerivativeOp, Fragment, FunctionConstant}; -pub use stage::{GlobalBuiltin, GlobalVar}; +pub use stage::{GlobalBuiltin, GlobalVar, WorkItem}; pub use stage::{Interpolate, InterpolateAt}; pub use sync::{BarrierName, MemFlags, Sync}; #[cfg(test)] @@ -121,6 +121,9 @@ pub enum AirIntrinsic { SimdgroupSize(SimdgroupSize), /// `air.get_.`: a kernel built-in a program-scope variable declares. GlobalBuiltin(GlobalBuiltin), + /// `air.get_global_offset.i32` and `air.get_work_dim.i32`: an OpenCL C work-item function no + /// Metal built-in answers. + WorkItem(WorkItem), /// A simdgroup-matrix operation: `air.simdgroup_matrix_{8x8,16x16x16}_*`. SimdMatrix(SimdMatrix), /// A function-constant query, resolved by canonicalization's specialization. @@ -192,6 +195,7 @@ impl AirIntrinsic { .or_else(|| IsUniform::parse(rest).map(A::IsUniform)) .or_else(|| SimdgroupSize::parse(rest).map(A::SimdgroupSize)) .or_else(|| GlobalBuiltin::parse(rest).map(A::GlobalBuiltin)) + .or_else(|| WorkItem::parse(rest).map(A::WorkItem)) .or_else(|| SimdMatrix::parse(rest).map(A::SimdMatrix)) .or_else(|| FunctionConstant::parse(rest).map(A::FunctionConstant)) .or_else(|| Fragment::parse(rest).map(A::Fragment)) @@ -238,6 +242,7 @@ impl AirIntrinsic { AirIntrinsic::IsUniform(u) => u.signature(), AirIntrinsic::SimdgroupSize(s) => s.signature(), AirIntrinsic::GlobalBuiltin(g) => g.signature(), + AirIntrinsic::WorkItem(w) => w.signature(), AirIntrinsic::SimdMatrix(m) => m.signature(), AirIntrinsic::FunctionConstant(f) => f.signature(), AirIntrinsic::Fragment(f) => f.signature(), diff --git a/crates/metal2vulkan-air/src/intrinsics/stage.rs b/crates/metal2vulkan-air/src/intrinsics/stage.rs index 91649509e..8589bd82a 100644 --- a/crates/metal2vulkan-air/src/intrinsics/stage.rs +++ b/crates/metal2vulkan-air/src/intrinsics/stage.rs @@ -503,3 +503,36 @@ impl GlobalBuiltin { } } } + +/// An OpenCL C work-item function no Metal built-in answers, as Apple's OpenCL compiler emits it +/// (`newLibraryWithSource` with `sourceLanguage` 1, macOS 27.0.1): `get_global_offset(d)` is +/// `air.get_global_offset.i32(i32 d)` and `get_work_dim()` is `air.get_work_dim.i32()`, each +/// widened to OpenCL's `size_t` or `uint` in its caller. A pipeline of OpenCL mode reads both from +/// its first hidden buffer (`canon::opencl`); lowering refuses a read any other pipeline keeps. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum WorkItem { + /// `air.get_global_offset.i32`: the dispatch's global offset in the dimension its operand + /// names. + GlobalOffset, + /// `air.get_work_dim.i32`: the dispatch's dimension count. + WorkDim, +} + +impl WorkItem { + pub(super) fn parse(rest: &str) -> Option { + match rest { + "get_global_offset.i32" => Some(WorkItem::GlobalOffset), + "get_work_dim.i32" => Some(WorkItem::WorkDim), + _ => None, + } + } + + /// The typed signature: `i32 (i32)` for the offset, `i32 ()` for the dimension count. + pub fn signature(&self) -> Signature { + let t = num(Elem::I32, 1); + match self { + WorkItem::GlobalOffset => Signature::new(t, &[t]), + WorkItem::WorkDim => Signature::new(t, &[]), + } + } +} diff --git a/crates/metal2vulkan-air/tests/api_surface.txt b/crates/metal2vulkan-air/tests/api_surface.txt index f4b360437..d1331cb93 100644 --- a/crates/metal2vulkan-air/tests/api_surface.txt +++ b/crates/metal2vulkan-air/tests/api_surface.txt @@ -132,6 +132,7 @@ canon constants_read use(reads::constants_read) canon discard_sink mod canon function_table mod canon imports_dynamically use(link::imports_dynamically) +canon opencl mod canon rate_map_data mod canon select fn canon specialize fn @@ -146,6 +147,7 @@ canon::function_table FIRST_ENTRY_WORD const canon::function_table FIRST_FUNCTION_WORD const canon::function_table PRESENT_WORD const canon::function_table SIZE_WORD const +canon::opencl entry fn canon::rate_map_data BYTES const canon::rate_map_data ENTRIES const canon::rate_map_data ENTRY_WORDS const @@ -339,6 +341,7 @@ intrinsics Texture use(texture::Texture) intrinsics ThreadScope use(atomic::ThreadScope) intrinsics UNDECODED const intrinsics UNDECODED_FEATURES const +intrinsics WorkItem use(stage::WorkItem) intrinsics bind fn intrinsics classify fn intrinsics dropped_family use(llvm::dropped_family) diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 3434e65b5..54a6d0531 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -501,7 +501,7 @@ impl Kernel { } /// The lowering inputs of the function's variant `key`: a compute descriptor's stage input - /// descriptor, or a tile descriptor's color attachment formats by index and its + /// descriptor and OpenCL mode, or a tile descriptor's color attachment formats by index and its /// `threadgroupSizeMatchesTileSize`, and either's `maxCallStackDepth` past Metal's default, 1, /// as the compile layer compiles a `Function` stage of each. fn inputs(&self, key: &VariantKey) -> metal2vulkan::pipeline::LoweringInputs { @@ -511,6 +511,7 @@ impl Kernel { inputs.stage_input = descriptor.stage_input.clone(); inputs.max_call_stack_depth = Some(descriptor.max_call_stack_depth).filter(|&k| k > 1); + inputs.open_cl_mode = descriptor.open_cl_mode_enabled; } Kernel::Tile(descriptor) => { inputs.tile_attachments = Some( diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 9ba23db5a..50c93607d 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -259,6 +259,8 @@ mod numbered_samplers; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod opencl_kernels; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod opencl_mode; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod optional_extensions; mod options; mod own; diff --git a/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs b/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs new file mode 100644 index 000000000..e8e554ecd --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs @@ -0,0 +1,492 @@ +//! Compute pipelines of OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`), each +//! kernel in the shape Apple's OpenCL compiler writes for OpenCL C (`__entry_` calling the +//! kernel, an internal function, which calls the work-item functions through internal wrappers of +//! `air.get_*`), run with the three hidden buffers bound as Metal's OpenCL dispatcher binds them, +//! and compared with what the M3 Max (macOS 27.0.1) computes for the same kernels: +//! +//! - **add**: `c[i] = a[i] + b[i]` over 1024 threads, `a[i] = i`, `b[i] = 2i + 1`: `3i + 1`. +//! - **lsum**: each threadgroup of 64 sums its `in[i] = i` through `__local` memory and a barrier: +//! 2016, 6112, 10208, 14304. +//! - **cmul**: `o[i] *= c[i & 3]` through a `__constant` pointer, `o[i] = i + 1`, `c = 1, 2, 3, 4`: +//! 1, 4, 9, 16, 5, 12, ... +//! - **items**: every work-item function, of the dimensions it names and of one it reads from a +//! constant buffer, over a grid of 8 by 4 threads in threadgroups of 4 by 2 at offset (3, 5), of +//! two dimensions. The M3 Max answers each word as OpenCL defines it, but for the store of +//! `get_global_id(3) + get_local_size(4) + get_global_size(5)`, which it leaves unwritten; the +//! crate stores OpenCL's 2. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The modules are LLVM text written here +//! (`llvm-as`). + +use super::blit_holds::{device, Scratch, WAIT}; +use crate::{Buffer, ComputePipelineState, Device, PipelineOptions, ResourceOptions, Size}; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; + +/// The target, the work-item functions' wrappers as the OpenCL compiler writes them, and the +/// module's versions. +const HEAD: &str = "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\"\n\ +target triple = \"air64_v29-apple-macosx27.0.0\"\n\ +define internal fastcc i64 @_Z13get_global_idj(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_global_id.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i64 @_Z12get_local_idj(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_local_id.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i64 @_Z12get_group_idj(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_group_id.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i64 @_Z14get_local_sizej(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_local_size.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i64 @_Z15get_global_sizej(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_global_size.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i64 @_Z14get_num_groupsj(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_num_groups.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i64 @_Z17get_global_offsetj(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_global_offset.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i32 @_Z12get_work_dimv() #2 {\n\ + %1 = tail call i32 @air.get_work_dim.i32() #3\n\ + ret i32 %1\n}\n\ +define internal fastcc void @_Z7barrierj(i32 %0) #4 {\n\ + call void @air.wg.barrier(i32 %0, i32 5, i32 1) #5\n\ + ret void\n}\n\ +declare i32 @air.get_global_id.i32(i32) #3\n\ +declare i32 @air.get_local_id.i32(i32) #3\n\ +declare i32 @air.get_group_id.i32(i32) #3\n\ +declare i32 @air.get_local_size.i32(i32) #3\n\ +declare i32 @air.get_global_size.i32(i32) #3\n\ +declare i32 @air.get_num_groups.i32(i32) #3\n\ +declare i32 @air.get_global_offset.i32(i32) #3\n\ +declare i32 @air.get_work_dim.i32() #3\n\ +declare void @air.wg.barrier(i32, i32, i32) #5\n\ +attributes #0 = { nounwind }\n\ +attributes #1 = { convergent nounwind }\n\ +attributes #2 = { nounwind optsize }\n\ +attributes #3 = { nounwind readnone willreturn }\n\ +attributes #4 = { convergent nounwind }\n\ +attributes #5 = { convergent nounwind willreturn }\n\ +!air.version = !{!90}\n\ +!air.language_version = !{!91}\n\ +!90 = !{i32 2, i32 9, i32 0}\n\ +!91 = !{!\"Metal\", i32 1, i32 1, i32 0}\n"; + +/// The node of argument `n`, a buffer at `index` of address space `space` holding `ty`, `access` +/// one of `read`, `read_write`. +fn buffer(n: u32, index: u32, access: &str, space: u32, ty: &str, name: &str) -> String { + format!( + "!{{i32 {n}, !\"air.buffer\", !\"air.location_index\", i32 {index}, i32 1, !\"air.{access}\", !\"air.address_space\", i32 {space}, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"{ty}\", !\"air.arg_name\", !\"{name}\"}}" + ) +} + +/// The kernel list of `entry` with argument nodes `args`. +fn kernel_list(entry: &str, args: &[String]) -> String { + let refs: Vec = (0..args.len()).map(|i| format!("!{}", 3 + i)).collect(); + let mut out = format!( + "!air.kernel = !{{!0}}\n!0 = !{{ptr @{entry}, !1, !2}}\n!1 = !{{}}\n!2 = !{{{}}}\n", + refs.join(", ") + ); + for (i, a) in args.iter().enumerate() { + out.push_str(&format!("!{} = {a}\n", 3 + i)); + } + out +} + +/// `__kernel void add(__global const float *a, __global const float *b, __global float *c)`. +fn add() -> String { + let body = "define void @__entry_add(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2) #0 {\n\ +entry:\n\ + tail call fastcc void @add(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2)\n\ + ret void\n}\n\ +define internal fastcc void @add(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %c) #1 {\n\ +entry:\n\ + %i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %pa = getelementptr inbounds float, ptr addrspace(1) %a, i64 %i\n\ + %va = load float, ptr addrspace(1) %pa, align 4\n\ + %pb = getelementptr inbounds float, ptr addrspace(1) %b, i64 %i\n\ + %vb = load float, ptr addrspace(1) %pb, align 4\n\ + %s = fadd float %va, %vb\n\ + %pc = getelementptr inbounds float, ptr addrspace(1) %c, i64 %i\n\ + store float %s, ptr addrspace(1) %pc, align 4\n\ + ret void\n}\n"; + let args = [ + buffer(0, 0, "read", 1, "float", "a"), + buffer(1, 1, "read", 1, "float", "b"), + buffer(2, 2, "read_write", 1, "float", "c"), + ]; + format!("{body}{}", kernel_list("__entry_add", &args)) +} + +/// `__kernel void lsum(__global const float *in, __global float *out, __local float *tmp)`: +/// `tmp[l] = in[i]`, `barrier(CLK_LOCAL_MEM_FENCE)`, and thread 0 of each group stores the sum of +/// its group's `tmp` to `out[get_group_id(0)]`. +fn lsum() -> String { + let body = "define void @__entry_lsum(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(3) %2) #0 {\n\ +entry:\n\ + tail call fastcc void @lsum(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(3) %2)\n\ + ret void\n}\n\ +define internal fastcc void @lsum(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(3) %tmp) #1 {\n\ +entry:\n\ + %l = tail call fastcc i64 @_Z12get_local_idj(i32 0)\n\ + %g = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %pi = getelementptr inbounds float, ptr addrspace(1) %in, i64 %g\n\ + %v = load float, ptr addrspace(1) %pi, align 4\n\ + %pt = getelementptr inbounds float, ptr addrspace(3) %tmp, i64 %l\n\ + store float %v, ptr addrspace(3) %pt, align 4\n\ + tail call fastcc void @_Z7barrierj(i32 1)\n\ + %first = icmp eq i64 %l, 0\n\ + br i1 %first, label %loop, label %done\n\ +loop:\n\ + %s = phi float [ %s1, %body ], [ 0.000000e+00, %entry ]\n\ + %j = phi i64 [ %j1, %body ], [ 0, %entry ]\n\ + %n = tail call fastcc i64 @_Z14get_local_sizej(i32 0)\n\ + %more = icmp ult i64 %j, %n\n\ + br i1 %more, label %body, label %exit\n\ +body:\n\ + %pj = getelementptr inbounds float, ptr addrspace(3) %tmp, i64 %j\n\ + %vj = load float, ptr addrspace(3) %pj, align 4\n\ + %s1 = fadd float %s, %vj\n\ + %j1 = add nuw i64 %j, 1\n\ + br label %loop\n\ +exit:\n\ + %grp = tail call fastcc i64 @_Z12get_group_idj(i32 0)\n\ + %po = getelementptr inbounds float, ptr addrspace(1) %out, i64 %grp\n\ + store float %s, ptr addrspace(1) %po, align 4\n\ + br label %done\n\ +done:\n\ + ret void\n}\n"; + let args = [ + buffer(0, 0, "read", 1, "float", "in"), + buffer(1, 1, "read_write", 1, "float", "out"), + buffer(2, 0, "read_write", 3, "float", "tmp"), + ]; + format!("{body}{}", kernel_list("__entry_lsum", &args)) +} + +/// `__kernel void cmul(__global float *o, __constant float *c)`: `o[i] *= c[i & 3]`. +fn cmul() -> String { + let body = "define void @__entry_cmul(ptr addrspace(1) %0, ptr addrspace(2) %1) #0 {\n\ +entry:\n\ + tail call fastcc void @cmul(ptr addrspace(1) %0, ptr addrspace(2) %1)\n\ + ret void\n}\n\ +define internal fastcc void @cmul(ptr addrspace(1) %o, ptr addrspace(2) %c) #1 {\n\ +entry:\n\ + %i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %po = getelementptr inbounds float, ptr addrspace(1) %o, i64 %i\n\ + %vo = load float, ptr addrspace(1) %po, align 4\n\ + %k = and i64 %i, 3\n\ + %pc = getelementptr inbounds float, ptr addrspace(2) %c, i64 %k\n\ + %vc = load float, ptr addrspace(2) %pc, align 4\n\ + %m = fmul float %vo, %vc\n\ + store float %m, ptr addrspace(1) %po, align 4\n\ + ret void\n}\n"; + let args = [ + buffer(0, 0, "read_write", 1, "float", "o"), + buffer(1, 1, "read", 2, "float", "c"), + ]; + format!("{body}{}", kernel_list("__entry_cmul", &args)) +} + +/// `__kernel void items(__global uint *o, __constant uint *dp)`, `d = dp[0]`: thread `i` (its +/// linear index in the grid) stores eight words at `o[8i]`: `get_global_id(0)`, +/// `get_global_id(1)`, the local ids and group ids of dimensions 0 and 1 a byte each, the group +/// counts and local sizes so, the global sizes and `get_work_dim()` so, the sum of +/// `get_global_id`, `get_local_size`, `get_num_groups` and `get_global_offset` of `d`, +/// `get_global_id(3) + get_local_size(4) + get_global_size(5)`, and 7. +fn items() -> String { + let body = "define void @__entry_items(ptr addrspace(1) %0, ptr addrspace(2) %1) #0 {\n\ +entry:\n\ + %2 = load i32, ptr addrspace(2) %1, align 4\n\ + tail call fastcc void @items(ptr addrspace(1) %0, i32 %2)\n\ + ret void\n}\n\ +define internal fastcc void @items(ptr addrspace(1) %o, i32 %d) #1 {\n\ +entry:\n\ + %g1 = tail call fastcc i64 @_Z13get_global_idj(i32 1)\n\ + %f1 = tail call fastcc i64 @_Z17get_global_offsetj(i32 1)\n\ + %y = sub i64 %g1, %f1\n\ + %gs0 = tail call fastcc i64 @_Z15get_global_sizej(i32 0)\n\ + %row = mul i64 %y, %gs0\n\ + %g0 = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %f0 = tail call fastcc i64 @_Z17get_global_offsetj(i32 0)\n\ + %x = sub i64 %g0, %f0\n\ + %i = add i64 %row, %x\n\ + %base = shl i64 %i, 3\n\ + %w0 = trunc i64 %g0 to i32\n\ + %p0 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %base\n\ + store i32 %w0, ptr addrspace(1) %p0, align 4\n\ + %w1 = trunc i64 %g1 to i32\n\ + %a1 = or i64 %base, 1\n\ + %p1 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a1\n\ + store i32 %w1, ptr addrspace(1) %p1, align 4\n\ + %l0 = tail call fastcc i64 @_Z12get_local_idj(i32 0)\n\ + %l1 = tail call fastcc i64 @_Z12get_local_idj(i32 1)\n\ + %l1s = shl i64 %l1, 8\n\ + %q0 = or i64 %l1s, %l0\n\ + %r0 = tail call fastcc i64 @_Z12get_group_idj(i32 0)\n\ + %r0s = shl i64 %r0, 16\n\ + %q1 = or i64 %q0, %r0s\n\ + %r1 = tail call fastcc i64 @_Z12get_group_idj(i32 1)\n\ + %r1s = shl i64 %r1, 24\n\ + %q2 = or i64 %q1, %r1s\n\ + %w2 = trunc i64 %q2 to i32\n\ + %a2 = or i64 %base, 2\n\ + %p2 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a2\n\ + store i32 %w2, ptr addrspace(1) %p2, align 4\n\ + %n0 = tail call fastcc i64 @_Z14get_num_groupsj(i32 0)\n\ + %n1 = tail call fastcc i64 @_Z14get_num_groupsj(i32 1)\n\ + %n1s = shl i64 %n1, 8\n\ + %u0 = or i64 %n1s, %n0\n\ + %z0 = tail call fastcc i64 @_Z14get_local_sizej(i32 0)\n\ + %z0s = shl i64 %z0, 16\n\ + %u1 = or i64 %u0, %z0s\n\ + %z1 = tail call fastcc i64 @_Z14get_local_sizej(i32 1)\n\ + %z1s = shl i64 %z1, 24\n\ + %u2 = or i64 %u1, %z1s\n\ + %w3 = trunc i64 %u2 to i32\n\ + %a3 = or i64 %base, 3\n\ + %p3 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a3\n\ + store i32 %w3, ptr addrspace(1) %p3, align 4\n\ + %gs1 = tail call fastcc i64 @_Z15get_global_sizej(i32 1)\n\ + %gs1s = shl i64 %gs1, 8\n\ + %v0 = or i64 %gs1s, %gs0\n\ + %wd = tail call fastcc i32 @_Z12get_work_dimv()\n\ + %wds = shl i32 %wd, 16\n\ + %v0t = trunc i64 %v0 to i32\n\ + %w4 = or i32 %wds, %v0t\n\ + %a4 = or i64 %base, 4\n\ + %p4 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a4\n\ + store i32 %w4, ptr addrspace(1) %p4, align 4\n\ + %dg = tail call fastcc i64 @_Z13get_global_idj(i32 %d)\n\ + %dl = tail call fastcc i64 @_Z14get_local_sizej(i32 %d)\n\ + %s0 = add i64 %dl, %dg\n\ + %dn = tail call fastcc i64 @_Z14get_num_groupsj(i32 %d)\n\ + %s1 = add i64 %s0, %dn\n\ + %df = tail call fastcc i64 @_Z17get_global_offsetj(i32 %d)\n\ + %s2 = add i64 %s1, %df\n\ + %w5 = trunc i64 %s2 to i32\n\ + %a5 = or i64 %base, 5\n\ + %p5 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a5\n\ + store i32 %w5, ptr addrspace(1) %p5, align 4\n\ + %e0 = tail call fastcc i64 @_Z13get_global_idj(i32 3)\n\ + %e1 = tail call fastcc i64 @_Z14get_local_sizej(i32 4)\n\ + %t0 = add i64 %e1, %e0\n\ + %e2 = tail call fastcc i64 @_Z15get_global_sizej(i32 5)\n\ + %t1 = add i64 %t0, %e2\n\ + %w6 = trunc i64 %t1 to i32\n\ + %a6 = or i64 %base, 6\n\ + %p6 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a6\n\ + store i32 %w6, ptr addrspace(1) %p6, align 4\n\ + tail call fastcc void @_Z7barrierj(i32 2)\n\ + %a7 = or i64 %base, 7\n\ + %p7 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a7\n\ + store i32 7, ptr addrspace(1) %p7, align 4\n\ + ret void\n}\n"; + let args = [ + buffer(0, 0, "read_write", 1, "uint", "o"), + buffer(1, 1, "read", 2, "uint", "dp"), + ]; + format!("{body}{}", kernel_list("__entry_items", &args)) +} + +/// The state of `entry` of the module `text` (after [`HEAD`]), of OpenCL mode. +fn state(device: &Device, text: &str, entry: &str) -> ComputePipelineState { + let air = metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{text}")).unwrap(); + let library = metal2vulkan::library::Library::from_air(&air).unwrap(); + let function = device + .new_library_with_compile_library(library) + .new_function_with_name(entry) + .unwrap(); + let mut descriptor = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + descriptor.open_cl_mode_enabled = true; + device + .new_compute_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// A shared buffer of `words`. +fn words_buffer(device: &Device, words: &[u32]) -> Buffer { + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) + .unwrap() +} + +/// A shared buffer of `floats`. +fn floats_buffer(device: &Device, floats: &[f32]) -> Buffer { + words_buffer( + device, + &floats.iter().map(|f| f.to_bits()).collect::>(), + ) +} + +/// The words of `buffer`, which no command uses now. +fn words(buffer: &Buffer) -> Vec { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command uses now. + let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }; + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|w| u32::from_le_bytes(*w)) + .collect() +} + +/// The floats of `buffer`, which no command uses now. +fn floats(buffer: &Buffer) -> Vec { + words(buffer).into_iter().map(f32::from_bits).collect() +} + +/// `state` dispatched over `grid` threads in threadgroups of `group`, buffer 0 holding the global +/// offset `offset` and the dimension count `dims`, buffers 1 and 2 bound as the dispatcher binds +/// them, `buffers` at 3 and up, and `local` bytes of threadgroup memory at index 0 where `Some`. +fn run( + device: &Device, + state: &ComputePipelineState, + (grid, group): (Size, Size), + (offset, dims): ([u32; 3], u32), + buffers: &[&Buffer], + local: Option, +) { + let hidden = [ + words_buffer(device, &[offset[0], offset[1], offset[2], dims]), + words_buffer(device, &[0; 16]), + words_buffer(device, &[0; 16]), + ]; + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + for (index, b) in (0u32..).zip(hidden.iter().chain(buffers.iter().copied())) { + encoder.set_buffer(Some(b), 0, index).unwrap(); + } + if let Some(bytes) = local { + encoder.set_threadgroup_memory_length(bytes, 0).unwrap(); + } + encoder.dispatch_threads(grid, group).unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); +} + +/// One dimension's grid. +fn line(threads: u64, group: u64) -> (Size, Size) { + (Size::new(threads, 1, 1), Size::new(group, 1, 1)) +} + +#[test] +fn opencl_mode_kernels_compute_what_metal_computes() { + let scratch = Scratch::new("opencl-mode"); + let device = device(&scratch.0); + let one = ([0; 3], 1); + + const N: usize = 1024; + let a = floats_buffer(&device, &(0..N).map(|i| i as f32).collect::>()); + let b = floats_buffer( + &device, + &(0..N).map(|i| (2 * i + 1) as f32).collect::>(), + ); + let c = floats_buffer(&device, &[0.0; N]); + let add_state = state(&device, &add(), "__entry_add"); + run( + &device, + &add_state, + line(N as u64, 64), + one, + &[&a, &b, &c], + None, + ); + let sums: Vec = (0..N).map(|i| (3 * i + 1) as f32).collect(); + assert_eq!(floats(&c), sums, "add"); + + let input = floats_buffer(&device, &(0..256).map(|i| i as f32).collect::>()); + let out = floats_buffer(&device, &[0.0; 4]); + let lsum_state = state(&device, &lsum(), "__entry_lsum"); + run( + &device, + &lsum_state, + line(256, 64), + one, + &[&input, &out], + Some(64 * 4), + ); + assert_eq!(floats(&out), [2016.0, 6112.0, 10208.0, 14304.0], "lsum"); + + let o = floats_buffer( + &device, + &(0..64).map(|i| (i + 1) as f32).collect::>(), + ); + let k = floats_buffer(&device, &[1.0, 2.0, 3.0, 4.0]); + let cmul_state = state(&device, &cmul(), "__entry_cmul"); + run(&device, &cmul_state, line(64, 32), one, &[&o, &k], None); + let products: Vec = (0..64).map(|i| ((i + 1) * (i % 4 + 1)) as f32).collect(); + assert_eq!(floats(&o), products, "cmul"); + assert_eq!(floats(&o)[..6], [1.0, 4.0, 9.0, 16.0, 5.0, 12.0]); +} + +/// The eight words thread `(x, y)` of [`items`] stores over the 8-by-4 grid in groups of 4 by 2 at +/// offset (3, 5), of two dimensions, reading dimension `d` (`dims`, `local`, `groups` and +/// `offset` OpenCL's 1, 1, 1 and 0 past dimension 1). +fn items_words(x: u32, y: u32, d: u32) -> [u32; 8] { + let (offset, global, local) = ([3, 5], [8, 4], [4, 2]); + let id = [x + offset[0], y + offset[1]]; + let lid = [x % local[0], y % local[1]]; + let group = [x / local[0], y / local[1]]; + let groups = [global[0] / local[0], global[1] / local[1]]; + let of = |v: [u32; 2], past: u32| v.get(d as usize).copied().unwrap_or(past); + [ + id[0], + id[1], + lid[0] | lid[1] << 8 | group[0] << 16 | group[1] << 24, + groups[0] | groups[1] << 8 | local[0] << 16 | local[1] << 24, + global[0] | global[1] << 8 | 2 << 16, + of(id, 0) + of(local, 1) + of(groups, 1) + of(offset, 0), + 2, + 7, + ] +} + +#[test] +fn opencl_mode_work_item_functions_read_the_dispatch() { + let scratch = Scratch::new("opencl-mode-items"); + let device = device(&scratch.0); + let items_state = state(&device, &items(), "__entry_items"); + // Dimension 1, as the M3 Max ran it, and dimension 5, past the grid's. + for d in [1u32, 5] { + let o = words_buffer(&device, &[0xEEEE_EEEE; 32 * 8]); + let dp = words_buffer(&device, &[d]); + run( + &device, + &items_state, + (Size::new(8, 4, 1), Size::new(4, 2, 1)), + ([3, 5, 0], 2), + &[&o, &dp], + None, + ); + let got = words(&o); + let want: Vec = (0..4) + .flat_map(|y| (0..8).flat_map(move |x| items_words(x, y, d))) + .collect(); + assert_eq!(got, want, "dimension {d}"); + if d == 1 { + // The M3 Max's first thread, word 6 OpenCL's 2 where it leaves the word unwritten. + assert_eq!( + got[..8], + [3, 5, 0, 0x0204_0202, 0x0002_0408, 0xe, 2, 7], + "the first thread" + ); + } + } +} diff --git a/crates/metal2vulkan-runtime/src/warm/codec.rs b/crates/metal2vulkan-runtime/src/warm/codec.rs index 55c707d89..1e7f07c94 100644 --- a/crates/metal2vulkan-runtime/src/warm/codec.rs +++ b/crates/metal2vulkan-runtime/src/warm/codec.rs @@ -42,7 +42,7 @@ use std::collections::{BTreeMap, HashMap}; pub(crate) const MAGIC: &[u8; 8] = b"M2VPREC\0"; /// The record format: bumped whenever a record's bytes change meaning (the module docs). -pub(crate) const RECORD_FORMAT: u32 = 4; +pub(crate) const RECORD_FORMAT: u32 = 5; /// The length of a record's header (magic and format) and of its checksum. const HEADER: usize = 8 + 4; @@ -447,6 +447,7 @@ impl Writer { self.bool(d.support_adding_binary_functions); self.mutability(&d.buffers)?; self.bool(d.needs_custom_border_color_samplers); + self.bool(d.open_cl_mode_enabled); Ok(()) } @@ -849,6 +850,7 @@ impl<'a> Reader<'a> { d.support_adding_binary_functions = self.bool()?; d.buffers = self.mutability()?; d.needs_custom_border_color_samplers = self.bool()?; + d.open_cl_mode_enabled = self.bool()?; Ok(d) } diff --git a/crates/metal2vulkan-validation/src/check.rs b/crates/metal2vulkan-validation/src/check.rs index acd408246..e499e32f7 100644 --- a/crates/metal2vulkan-validation/src/check.rs +++ b/crates/metal2vulkan-validation/src/check.rs @@ -571,6 +571,7 @@ fn omitted_constants_error( ) -> Option { let request = metal2vulkan_air::canon::SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: entry.to_string(), constants, }; diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 3409983b8..5ac28b353 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1232,6 +1232,7 @@ codec_enum! { ViewportCount, AliasedImageblock { data_size }, CallStackDepth { depth }, + OpenClMode, FlatGrid, SparseTextureWrites { slot, atomic }, TileThreadgroupMemory { index }, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 053c68c51..92d6992cc 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 = 1990; +pub const SEMANTICS_VERSION: u32 = 1991; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1990; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 492; +pub const ARTIFACT_FORMAT_VERSION: u32 = 493; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index d28b5a12f..beb53cb77 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -150,6 +150,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // The depth a kernel's call stack was sized for: the compile layer checks it against the // pipeline's; nothing on the device reads it. RuntimeFact::CallStackDepth { .. } => Mechanism::None, + // The mode a kernel was compiled in: the compile layer checks it against the pipeline's; + // nothing on the device reads it. + RuntimeFact::OpenClMode => Mechanism::None, // A pipeline compiled under the flat-grid variant; its plans state it. RuntimeFact::FlatGrid => Mechanism::Variant, // A sparse texture's writes are dropped under the slot's `SparseTexture` specialization; diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 97f3dfef5..1a5e00896 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -128,6 +128,7 @@ fn every_fact() -> Vec { RuntimeFact::ViewportCount, RuntimeFact::AliasedImageblock { data_size: 24 }, RuntimeFact::CallStackDepth { depth: 8 }, + RuntimeFact::OpenClMode, RuntimeFact::FlatGrid, RuntimeFact::SparseTextureWrites { slot, @@ -370,6 +371,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::YCbCrInPlace { .. } => 65, RuntimeFact::PartialObjectThreadgroups => 89, RuntimeFact::RotatedInputBlend { .. } => 90, + RuntimeFact::OpenClMode => 91, } } @@ -377,7 +379,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..91).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..92).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -512,6 +514,7 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::TexelFormat { .. } => Mechanism::PushConstant, RuntimeFact::AliasedImageblock { .. } => Mechanism::None, RuntimeFact::CallStackDepth { .. } + | RuntimeFact::OpenClMode | RuntimeFact::AbsentArgumentRead { .. } | RuntimeFact::SynthesizedGeometry { .. } => Mechanism::None, }; diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index bf9de1a56..f33e87fe0 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -1927,6 +1927,11 @@ pub enum DescriptorError { /// pipeline's vertex or fragment depth. The stack would hold another number of frames than the /// pipeline's Metal stage has. Compile the stage under the pipeline's depth. MaxCallStackDepth { compiled: u32, given: u32 }, + /// A `StageSource::Compiled` kernel compiled in another OpenCL mode than its compute + /// pipeline's (`RuntimeFact::OpenClMode`; `compiled` says whether it was compiled in OpenCL + /// mode): its arguments sit at other indices than the pipeline's Metal kernel takes them at. + /// Compile the kernel under the pipeline's `open_cl_mode_enabled`. + OpenClMode { compiled: bool }, /// A tile function that declares threadgroup variables: Metal refuses its tile pipeline /// state ("Tile shaders do not support shader declared threadgroup variables", measured on an /// M4 and an M3 Max). Its threadgroup memory is its `[[threadgroup(n)]]` arguments alone. diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 71df6f5cb..2b623b3f5 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -891,6 +891,14 @@ fn route_air(cx: &SelectCx<'_>, op: &AirIntrinsic, decl: FuncId) -> Route { A::GlobalBuiltin(_) => Route::Refuse( Unsupported::not_implemented(Feature::Lowering(LowerFamily::Dispatch)).into(), ), + // Canonicalization reads each of them from the hidden buffer of a kernel compiled in + // OpenCL mode; no other pipeline has the values, and Metal makes no other pipeline of a + // function that reads them. + A::WorkItem(_) => Route::Refuse( + Unsupported::not_implemented(Feature::Lowering(LowerFamily::Dispatch)) + .naming(decl_name(cx, decl)) + .into(), + ), } } @@ -1198,9 +1206,10 @@ pub fn select( stage, values: mp.values, push: BTreeSet::new(), - // A call stack's depth, which a compiled kernel's pipeline must match. + // A call stack's depth, and OpenCL mode, which a compiled kernel's pipeline must match. facts: (e.call_stack.into_iter()) .map(|stack| RuntimeFact::CallStackDepth { depth: stack.depth }) + .chain(inputs.open_cl_mode.then_some(RuntimeFact::OpenClMode)) .collect(), // Private memory past the floor of a device not measured rests on no measurement, as // does a group operation in a branch no measurement says Metal speculates. A rate-map diff --git a/crates/metal2vulkan/src/memory/plan/tests.rs b/crates/metal2vulkan/src/memory/plan/tests.rs index c89c08dab..695f84a4b 100644 --- a/crates/metal2vulkan/src/memory/plan/tests.rs +++ b/crates/metal2vulkan/src/memory/plan/tests.rs @@ -1393,6 +1393,7 @@ fn every_public_fixture_analyzes_without_an_internal_error() { let d = crate::air::decode(&bitcode, &mut meter()).expect("decode"); let req = crate::air::SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: name.clone(), constants: Default::default(), }; @@ -1445,6 +1446,7 @@ fn hand_checked_fixtures() { let d = crate::air::decode(&bitcode, &mut meter()).expect("decode"); let req = crate::air::SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: stem.to_owned(), constants: Default::default(), }; diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 042105b45..09672ddfa 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -224,6 +224,16 @@ impl<'a> InputsFrom<'a> { } } + /// Whether the stage compiles as the kernel of a compute pipeline of OpenCL mode + /// (`LoweringInputs::open_cl_mode`): the given inputs' say; a render pipeline's stage never + /// does. + fn open_cl_mode(&self) -> bool { + match self { + InputsFrom::Given(i) => i.open_cl_mode, + InputsFrom::Vertex(..) | InputsFrom::Fragment(..) => false, + } + } + /// The group of its pipeline's color attachments a fragment stage compiles for /// (`LoweringInputs::color_group`): the given inputs', or the render pipeline variant's. fn color_group(&self) -> Option<&'a crate::pipeline::lower_inputs::ColorGroup> { @@ -558,7 +568,8 @@ pub fn stage_inputs( m: &mut Meter, ) -> Result { guarded(|| { - let specialized = entries.specialized(fd, inputs.call_stack_depth(), m)?; + let specialized = + entries.specialized(fd, inputs.call_stack_depth(), inputs.open_cl_mode(), m)?; // A color group's variant reads its own renumbering of the entry the creation shares. let grouped = match inputs.color_group() { Some(_) => Some(grouped_entry(specialized.spec.clone(), inputs, p)?), @@ -633,18 +644,44 @@ pub(crate) fn argument_buffer_layout( } } +/// Entry point `ep` of `module` as its pipeline binds it: where `open_cl_mode`, a kernel as a +/// pipeline of OpenCL mode binds it (`air::canon::opencl::entry`), its hidden buffers the +/// parameters past the function's own, as specialization appends them; else `ep` itself. +fn bound_entry<'a>( + module: &air::ir::Module, + ep: &'a air::abi::EntryPoint, + open_cl_mode: bool, +) -> Result, Error> { + if !open_cl_mode || !matches!(ep.stage, AbiStage::Kernel { .. }) { + return Ok(std::borrow::Cow::Borrowed(ep)); + } + let params = module.func(ep.func).map(|f| f.params.len()); + let first = params.and_then(|n| u32::try_from(n).ok()).ok_or_else(|| { + Error::Internal(InternalError::new( + InternalKind::Invariant, + "the entry's function is not in its module", + )) + })?; + Ok(std::borrow::Cow::Owned(air::canon::opencl::entry( + ep.clone(), + first, + )?)) +} + /// What a pipeline's reflection states for its stage `fd`, its calls nesting `depth` deep through -/// visible functions: the entry's bindings and the attributes it reads, from the entry its +/// visible functions (a kernel of OpenCL mode where `open_cl_mode`): the entry's bindings and the attributes it reads, from the entry its /// constants and linked functions specialize where they decide a binding /// (`reflection::needs_resolution`) or which arguments it reads /// (`reflection::specialization_decides_reads`), else from the decoded entry. pub(crate) fn stage_reflection( fd: &FunctionDescriptor, depth: u32, + open_cl_mode: bool, m: &mut Meter, ) -> Result { let mut inputs = LowerInputs::new(); inputs.max_call_stack_depth = call_stack_input(depth); + inputs.open_cl_mode = open_cl_mode; guarded(|| { with_request( &fd.function, @@ -658,18 +695,20 @@ pub(crate) fn stage_reflection( } let mut req = spec_request(&decoded, r.entry, r.consts)?; req.call_stack_depth = r.inputs.call_stack_depth(); + req.open_cl_mode = r.inputs.open_cl_mode(); let ep = air::canon::select(&decoded.module, &decoded.abi, &req.entry)?; if !reflection::needs_resolution(ep, &decoded.abi.structs) && !reflection::specialization_decides_reads(&decoded.abi) { + let ep = bound_entry(&decoded.module, ep, req.open_cl_mode)?; return Ok(reflection::StageReflection { bindings: reflection::bindings( - ep, + &ep, &decoded.abi.structs, reflection::Channel::Pipeline, &BTreeSet::new(), )?, - attributes: reflection::read_attributes(ep)?, + attributes: reflection::read_attributes(&ep)?, }); } let before = reflection::UnspecializedReads::of(&decoded.module, &decoded.abi, ep); @@ -689,18 +728,20 @@ pub(crate) fn stage_reflection( }) } -/// What stage `fd`, its calls nesting `depth` deep through visible functions, may store through -/// each slot its arguments bind: of the entry [`stage_reflection`] reads, its parameters' roles, +/// What stage `fd`, its calls nesting `depth` deep through visible functions (a kernel of OpenCL +/// mode where `open_cl_mode`), may store through each slot its arguments bind: of the entry [`stage_reflection`] reads, its parameters' roles, /// declared accesses and slots alone (`reflection::entry_slot_writes`). It derives no type /// description, so an argument whose reflection Metal's answer has not been measured for does not /// refuse it: only the decode and the specialization can. pub(crate) fn stage_slot_writes( fd: &FunctionDescriptor, depth: u32, + open_cl_mode: bool, m: &mut Meter, ) -> Result, Error> { let mut inputs = LowerInputs::new(); inputs.max_call_stack_depth = call_stack_input(depth); + inputs.open_cl_mode = open_cl_mode; guarded(|| { with_request( &fd.function, @@ -714,11 +755,13 @@ pub(crate) fn stage_slot_writes( } let mut req = spec_request(&decoded, r.entry, r.consts)?; req.call_stack_depth = r.inputs.call_stack_depth(); + req.open_cl_mode = r.inputs.open_cl_mode(); let ep = air::canon::select(&decoded.module, &decoded.abi, &req.entry)?; if !reflection::needs_resolution(ep, &decoded.abi.structs) && !reflection::specialization_decides_reads(&decoded.abi) { - return Ok(reflection::entry_slot_writes(ep)); + let ep = bound_entry(&decoded.module, ep, req.open_cl_mode)?; + return Ok(reflection::entry_slot_writes(&ep)); } let before = reflection::UnspecializedReads::of(&decoded.module, &decoded.abi, ep); let spec = specialize_request(decoded, &req, r, m)?; @@ -896,6 +939,8 @@ struct StageEntry { air_hash: Hash256, function: FunctionDescriptor, depth: u32, + /// Specialized as the kernel of a compute pipeline of OpenCL mode. + open_cl_mode: bool, /// What specializing it charged the ledger, which the byte bound counts. bytes: u64, specialized: Arc, @@ -1015,17 +1060,19 @@ impl StageEntries { &self, fd: &FunctionDescriptor, depth: u32, + open_cl_mode: bool, m: &mut Meter, ) -> Result, Error> { let depth = depth.max(1); // The library's table states it without decoding (`Function::info`). let air_hash = fd.function.info().air_hash; let lock = || self.kept.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(specialized) = lock().take(&air_hash, fd, depth) { + if let Some(specialized) = lock().take(&air_hash, fd, depth, open_cl_mode) { return Ok(specialized); } let mut inputs = LowerInputs::new(); inputs.max_call_stack_depth = call_stack_input(depth); + inputs.open_cl_mode = open_cl_mode; // What the specialization charged the ledger, which the byte bound counts: the entry is // what the charge is still held for once this returns. let before = m.ledger(); @@ -1041,7 +1088,7 @@ impl StageEntries { let mut kept = lock(); // Another caller may have specialized the same stage meanwhile: its entry is this one, so // the two share one. - if let Some(theirs) = kept.take(&air_hash, fd, depth) { + if let Some(theirs) = kept.take(&air_hash, fd, depth, open_cl_mode) { return Ok(theirs); } kept.made += 1; @@ -1050,6 +1097,7 @@ impl StageEntries { air_hash, function: fd.clone(), depth, + open_cl_mode, bytes, specialized: Arc::clone(&specialized), }); @@ -1067,11 +1115,14 @@ impl Kept { air_hash: &Hash256, fd: &FunctionDescriptor, depth: u32, + open_cl_mode: bool, ) -> Option> { - let at = self - .entries - .iter() - .position(|e| e.depth == depth && e.air_hash == *air_hash && e.function == *fd)?; + let at = self.entries.iter().position(|e| { + e.depth == depth + && e.open_cl_mode == open_cl_mode + && e.air_hash == *air_hash + && e.function == *fd + })?; let entry = self.entries.remove(at); let specialized = Arc::clone(&entry.specialized); self.entries.push(entry); @@ -1138,7 +1189,8 @@ pub(crate) fn stage_entry( f: impl FnOnce(&air::Entry, &mut Meter) -> Result, ) -> Result { guarded(|| { - let specialized = entries.specialized(fd, depth, m)?; + // A render or mesh pipeline's stage, never a kernel of OpenCL mode. + let specialized = entries.specialized(fd, depth, false, m)?; f(&specialized.spec, m) }) } @@ -1377,7 +1429,7 @@ pub(crate) fn reads_primitive_id_varying( use crate::pipeline::descriptor::StageSource; Ok(match fragment { Some(StageSource::Function(fd)) => entries - .specialized(fd, depth, m)? + .specialized(fd, depth, false, m)? .spec .ep .params @@ -1913,6 +1965,7 @@ pub(crate) fn spec_request( entry: name, constants: constant_values(&decoded.abi, consts)?, call_stack_depth: 1, + open_cl_mode: false, }) } @@ -2025,7 +2078,8 @@ pub(crate) fn kernel_inputs_read( let Some(given) = inputs.stage_input.as_ref() else { return Ok(inputs.clone()); }; - let specialized = entries.specialized(fd, inputs.max_call_stack_depth.unwrap_or(1), m)?; + let depth = inputs.max_call_stack_depth.unwrap_or(1); + let specialized = entries.specialized(fd, depth, inputs.open_cl_mode, m)?; let read = stage_in_attributes(&specialized.spec); let mut out = inputs.clone(); out.stage_input = Some(given.narrowed_to(&read)); @@ -2334,9 +2388,11 @@ fn instanced_attributes( /// The caller's inputs `i` for the specialized entry `spec`, its object payload kept only where it /// widens an object or mesh function's payload arena (`LoweringInputs::object_payload`): any other -/// function, and one whose own arena holds it, compiles as without it. +/// function, and one whose own arena holds it, compiles as without it. OpenCL mode is kept for a +/// kernel alone (`LoweringInputs::open_cl_mode`). fn given_inputs(spec: &air::Entry, i: &LowerInputs) -> LowerInputs { let mut out = i.clone(); + out.open_cl_mode = i.open_cl_mode && matches!(spec.ep.stage, AbiStage::Kernel { .. }); out.object_payload = i.object_payload.filter(|&bytes| { matches!( spec.ep.stage, @@ -2474,7 +2530,8 @@ fn specialize_one(r: &Request<'_>, m: &mut Meter) -> Result // The creation's entry of this stage: the same request's, made by a check or key of the // creation, else made there now. if let Shared::Entry(entries, fd) = r.shared { - let kept = entries.specialized(fd, r.inputs.call_stack_depth(), m)?; + let kept = + entries.specialized(fd, r.inputs.call_stack_depth(), r.inputs.open_cl_mode(), m)?; return Ok(Specialized::clone(&kept)); } let mut decoded = decoded_module(r, m)?; @@ -2482,8 +2539,10 @@ fn specialize_one(r: &Request<'_>, m: &mut Meter) -> Result decoded.abi.check_container(&decoded.module, f, m)?; } let mut req = spec_request(&decoded, r.entry, r.consts)?; - // A stage compiles under its pipeline's `maxCallStackDepth` for it. + // A stage compiles under its pipeline's `maxCallStackDepth` for it, and a kernel under its + // pipeline's OpenCL mode. req.call_stack_depth = r.inputs.call_stack_depth(); + req.open_cl_mode = r.inputs.open_cl_mode(); // Only a module that declares function constants needs them; specialization selects the // entry the same way. let before = if reflection::specialization_decides_reads(&decoded.abi) { diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index e093b3f45..ba1b9af49 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -792,6 +792,7 @@ impl Device { check_compute_maxima(d, a)?; check_stage_in(a, d)?; check_call_stack(a, d.max_call_stack_depth)?; + check_open_cl_mode(a, d.open_cl_mode_enabled)?; let linked = link(&[a], &LinkInputs::compute(), p)?; let stage = stage_module(&kernel, &linked, 0)?; let profile = self.profile_fingerprint(); @@ -1337,11 +1338,13 @@ fn invariant(detail: &str) -> Error { } /// The lowering inputs a `Function` kernel of compute pipeline `d` compiles under: its -/// stage-input descriptor and its `maxCallStackDepth` when not Metal's default, 1. +/// stage-input descriptor, its `maxCallStackDepth` when not Metal's default, 1, and its OpenCL +/// mode. fn kernel_inputs(d: &ComputePipelineDescriptor) -> LoweringInputs { LoweringInputs { stage_input: d.stage_input.clone(), max_call_stack_depth: (d.max_call_stack_depth > 1).then_some(d.max_call_stack_depth), + open_cl_mode: d.open_cl_mode_enabled, ..LowerInputs::new() } } @@ -1637,6 +1640,19 @@ fn check_stage_in(a: &FunctionArtifact, d: &ComputePipelineDescriptor) -> Result Ok(()) } +/// The kernel of artifact `a` was compiled in its compute pipeline's OpenCL mode, `given` +/// (`RuntimeFact::OpenClMode`): a `Compiled` kernel of the other mode is +/// `InvalidDescriptor(OpenClMode)` (a `Function` kernel is compiled under `given`). +fn check_open_cl_mode(a: &FunctionArtifact, given: bool) -> Result<(), Error> { + let compiled = a.facts.contains(&RuntimeFact::OpenClMode); + if compiled != given { + return Err(Error::InvalidDescriptor(DescriptorError::OpenClMode { + compiled, + })); + } + Ok(()) +} + /// The stage of artifact `a` has the call stack its pipeline's `maxCallStackDepth` for it, /// `given`, sizes: a `Compiled` stage whose stack was sized for another depth is /// `InvalidDescriptor(MaxCallStackDepth)` (a `Function` stage is compiled under `given`). diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index e899f6fa6..8df930cee 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -310,6 +310,10 @@ pub fn function_key( h.bytes(b"max-call-stack-depth").u64(u64::from(k)); } // Appended only when set. + if inputs.open_cl_mode { + h.bytes(b"open-cl-mode"); + } + // Appended only when set. if inputs.flat_grid { h.bytes(b"flat-grid"); } diff --git a/crates/metal2vulkan/src/pipeline/compile/partition.rs b/crates/metal2vulkan/src/pipeline/compile/partition.rs index 647bf1524..e94535606 100644 --- a/crates/metal2vulkan/src/pipeline/compile/partition.rs +++ b/crates/metal2vulkan/src/pipeline/compile/partition.rs @@ -174,6 +174,8 @@ fn observes(callee: &Callee) -> bool { | AirIntrinsic::FunctionConstant(_) | AirIntrinsic::FunctionTable(_) | AirIntrinsic::IndirectCommand(_) => false, + // The dispatch's offset and dimension count, which every threadgroup reads alike. + AirIntrinsic::WorkItem(_) => false, // A global built-in read canonicalization left a call (its lane is no constant, and // lowering refuses it) reads its built-in as the parameter would. AirIntrinsic::GlobalBuiltin(g) => partition_builtin(g.var.builtin()), diff --git a/crates/metal2vulkan/src/pipeline/descriptor.rs b/crates/metal2vulkan/src/pipeline/descriptor.rs index 330a5790d..653d9c9e9 100644 --- a/crates/metal2vulkan/src/pipeline/descriptor.rs +++ b/crates/metal2vulkan/src/pipeline/descriptor.rs @@ -678,6 +678,22 @@ pub struct ComputePipelineDescriptor { /// `needsCustomBorderColorSamplers` (Apple SPI, default off): changes nothing Metal runs, as /// the render descriptor's ([`PrivateRenderState::needs_custom_border_color_samplers`]). pub needs_custom_border_color_samplers: bool, + /// `openCLModeEnabled` (Apple SPI, `setOpenCLModeEnabled:`, default off): the kernel is a + /// kernel of Apple's OpenCL compiler (`__entry_` of a library of `sourceLanguage` 1), + /// linked as Metal links it for OpenCL C. Metal binds three hidden buffers ahead of the + /// kernel's own: `__global_offset_and_num_dims` at index 0, four `uint`s the dispatcher fills + /// with the dispatch's global offset in each of its dimensions and its dimension count; + /// `__printf_buffer` at 1; and `__image_order_data_type_table` at 2. Each of the kernel's + /// arguments bound at a buffer index sits 3 past its own; threadgroup memory, textures and + /// samplers keep theirs. OpenCL C's work-item functions read the dispatch: `get_global_id` + /// adds the offset to the thread's position in the grid, `get_global_offset` and + /// `get_work_dim` read buffer 0, and a dimension past 2 answers OpenCL's 0 or 1 (where the M3 + /// Max leaves a store of such a value unwritten). The pipeline's reflection lists the three + /// buffers after the kernel's arguments. The kernel compiles under it + /// (`LoweringInputs::open_cl_mode`), so it is part of the key. Without it Metal refuses a + /// pipeline of such a kernel ("Internal compiler error"); the crate compiles it as the AIR's + /// own Metal reading, refusing a read of `get_global_offset` or `get_work_dim`. + pub open_cl_mode_enabled: bool, } impl ComputePipelineDescriptor { @@ -694,6 +710,7 @@ impl ComputePipelineDescriptor { support_adding_binary_functions: false, buffers: BTreeMap::new(), needs_custom_border_color_samplers: false, + open_cl_mode_enabled: false, } } } diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 6ed17c458..0814e32a3 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -329,6 +329,13 @@ pub enum RuntimeFact { /// (`InvalidDescriptor(MaxCallStackDepth)` otherwise); a `Function` stage is compiled under /// its pipeline's. Nothing on the device reads it. CallStackDepth { depth: u32 }, + /// The kernel was compiled as the kernel of a compute pipeline of OpenCL mode + /// (`LoweringInputs::open_cl_mode`): it takes the three hidden buffers at indices 0 to 2 and + /// its own buffer-indexed arguments 3 past their indices. A `StageSource::Compiled` kernel + /// serves only a pipeline of the mode it was compiled in (`InvalidDescriptor(OpenClMode)` + /// otherwise); a `Function` kernel is compiled under its pipeline's. Nothing on the device + /// reads it. + OpenClMode, /// The kernel was compiled under `VariantKey::flat_grid` (`LoweringInputs::flat_grid`): it /// runs any grid in threadgroups of its own size, reading the grid from the 32-byte region /// record at its `PushField::ReplayRegionAddress`, which a preprocess writes beside the diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index c00992424..002b9e71d 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -206,6 +206,16 @@ pub struct LoweringInputs { /// `max_fragment_call_stack_depth`. Any other function compiles as without it. #[cfg_attr(feature = "serde", serde(default))] pub max_call_stack_depth: Option, + /// The kernel is the kernel of a compute pipeline of OpenCL mode + /// (`ComputePipelineDescriptor::open_cl_mode_enabled`): it takes Metal's three hidden buffers + /// at indices 0 to 2, each of its arguments bound at a buffer index sits 3 past its own, and + /// OpenCL C's work-item functions read the dispatch's values (`air::canon::opencl`). + /// `Device::compile_compute_pipeline` compiles a `Function` kernel under the pipeline's, and a + /// kernel compiled on its own for such a pipeline compiles under it too: the pipeline refuses + /// a kernel compiled under the other mode (`InvalidDescriptor(OpenClMode)`). Any other + /// function compiles as without it. + #[cfg_attr(feature = "serde", serde(default))] + pub open_cl_mode: bool, /// The kernel runs its dispatch's grid flat (`VariantKey::flat_grid`): the dispatch is any /// number of threadgroups of the variant's local size, whose invocations count the grid's /// threads in order (`x` fastest) from the `threads_per_grid` of the 32-byte region record at diff --git a/crates/metal2vulkan/src/reflection/live.rs b/crates/metal2vulkan/src/reflection/live.rs index 017b66fe8..4c4950c60 100644 --- a/crates/metal2vulkan/src/reflection/live.rs +++ b/crates/metal2vulkan/src/reflection/live.rs @@ -628,6 +628,7 @@ impl<'a> Engine<'a> { | AirIntrinsic::IsUniform(_) | AirIntrinsic::SimdgroupSize(_) | AirIntrinsic::GlobalBuiltin(_) + | AirIntrinsic::WorkItem(_) | AirIntrinsic::FunctionConstant(_) | AirIntrinsic::Interpolate(_) | AirIntrinsic::AccelerationStructure(_) => false, diff --git a/crates/metal2vulkan/src/reflection/mod.rs b/crates/metal2vulkan/src/reflection/mod.rs index 1eb63b3df..b1e943234 100644 --- a/crates/metal2vulkan/src/reflection/mod.rs +++ b/crates/metal2vulkan/src/reflection/mod.rs @@ -247,8 +247,21 @@ pub(crate) struct StageReflection { /// entry it compiled (`FunctionArtifact::reflection`); one whose answer was unmeasured kept none /// and is refused (its library function's reflection names the binding). fn stage(source: &StageSource, depth: u32, m: &mut Meter) -> Result { + kernel_stage(source, depth, false, m) +} + +/// [`stage`], a kernel of a compute pipeline of OpenCL mode where `open_cl_mode` +/// (`ComputePipelineDescriptor::open_cl_mode_enabled`). +fn kernel_stage( + source: &StageSource, + depth: u32, + open_cl_mode: bool, + m: &mut Meter, +) -> Result { match source { - StageSource::Function(fd) => crate::pipeline::compile::stage_reflection(fd, depth, m), + StageSource::Function(fd) => { + crate::pipeline::compile::stage_reflection(fd, depth, open_cl_mode, m) + } StageSource::Compiled(c) => { c.artifact().reflection.clone().ok_or_else(|| { Error::Unsupported(Unsupported::not_implemented(Feature::Reflection)) @@ -266,8 +279,20 @@ fn stage(source: &StageSource, depth: u32, m: &mut Meter) -> Result Result, Error> { + kernel_stage_writes(source, depth, false, m) +} + +/// [`stage_writes`], a kernel of a compute pipeline of OpenCL mode where `open_cl_mode`. +fn kernel_stage_writes( + source: &StageSource, + depth: u32, + open_cl_mode: bool, + m: &mut Meter, +) -> Result, Error> { match source { - StageSource::Function(fd) => crate::pipeline::compile::stage_slot_writes(fd, depth, m), + StageSource::Function(fd) => { + crate::pipeline::compile::stage_slot_writes(fd, depth, open_cl_mode, m) + } StageSource::Compiled(c) => Ok(c.artifact().slot_writes.clone()), } } @@ -346,7 +371,8 @@ impl ComputePipelineDescriptor { /// out-parameter of `newComputePipelineStateWithDescriptor:options:reflection:error:` answers /// it (the rules are [`reflection`](crate::reflection)'s): the stage input descriptor's /// buffers, then the kernel's arguments, of the entry the kernel's constants specialize where - /// they decide one. It decodes the kernel's AIR under `budget`; a kernel the compile layer + /// they decide one; in OpenCL mode ([`open_cl_mode_enabled`](Self::open_cl_mode_enabled)) each + /// buffer-indexed argument 3 past its index, then the three hidden buffers. It decodes the kernel's AIR under `budget`; a kernel the compile layer /// already compiled (`StageSource::Compiled`) answers what its compile kept of the same entry, /// decoding nothing. /// @@ -356,7 +382,12 @@ impl ComputePipelineDescriptor { /// decode's and specialization's own errors. pub fn reflection(&self, budget: &crate::Budget) -> Result { let mut m = Meter::new(budget); - let kernel = stage(&self.kernel, self.max_call_stack_depth, &mut m)?; + let kernel = kernel_stage( + &self.kernel, + self.max_call_stack_depth, + self.open_cl_mode_enabled, + &mut m, + )?; let mut bindings = match &self.stage_input { Some(s) => { s.check_layouts()?; @@ -408,7 +439,12 @@ impl ComputePipelineDescriptor { pub fn slot_writes(&self, budget: &crate::Budget) -> Result { let mut m = Meter::new(budget); Ok(SlotWrites { - kernel: stage_writes(&self.kernel, self.max_call_stack_depth, &mut m)?, + kernel: kernel_stage_writes( + &self.kernel, + self.max_call_stack_depth, + self.open_cl_mode_enabled, + &mut m, + )?, ..SlotWrites::default() }) } diff --git a/crates/metal2vulkan/src/tests/air_canon.rs b/crates/metal2vulkan/src/tests/air_canon.rs index f92d2d285..9475b6726 100644 --- a/crates/metal2vulkan/src/tests/air_canon.rs +++ b/crates/metal2vulkan/src/tests/air_canon.rs @@ -309,6 +309,7 @@ fn a_static_initializer_fixture_specializes_with_its_constant() { let mut m = meter(); let r = SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: "fcfold".into(), constants: [( 0, @@ -357,6 +358,7 @@ fn a_vector_function_constant_bakes_through_the_static_initializer() { let mut m = meter(); let r = SpecRequest { call_stack_depth: 1, + open_cl_mode: false, entry: entry.into(), constants: [( 0, diff --git a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs new file mode 100644 index 000000000..54471a095 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs @@ -0,0 +1,289 @@ +//! OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`): a kernel in the shape Apple's +//! OpenCL compiler writes (`__entry_` calling the kernel, an internal function, which calls +//! the work-item functions through internal wrappers) compiles, reflects and records its mode as a +//! pipeline of OpenCL mode binds it, on every committed profile that compiles it. +//! +//! The reflection is the M3 Max's (macOS 27.0.1) for kernels of these shapes: the kernel's +//! arguments, each buffer 3 past its index and threadgroup memory at its own, then +//! `__global_offset_and_num_dims` (index 0, read-only `uint`, 4 bytes aligned to 4), +//! `__printf_buffer` (1, read-write `char`, 1 byte aligned to 1) and +//! `__image_order_data_type_table` (2, read-only `uint`), every binding used. The module is LLVM +//! text written here (`llvm-as`). + +use crate::budget::Budget; +use crate::error::{DescriptorError, Error, Feature, LowerFamily}; +use crate::library::Library; +use crate::lower::select::LowerInputs; +use crate::metal::{BindingAccess, BindingType, DataType}; +use crate::pipeline::facts::RuntimeFact; +use crate::pipeline::testing::AssembleError; +use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; + +use super::engine_argument_tables::device; + +/// `__kernel void k(__global const float *a, __global float *c, __local float *tmp, +/// __constant uint *n)`: `tmp[l] = a[i]`, a barrier, `c[i] = tmp[l] + get_global_offset(0) + +/// get_work_dim() + n[0]` for `i = get_global_id(0)` and `l = get_local_id(0)`, in the shape the +/// OpenCL compiler writes it. +const MODULE: &str = "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\"\n\ +target triple = \"air64_v29-apple-macosx27.0.0\"\n\ +define void @__entry_k(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(3) %2, ptr addrspace(2) %3) #0 {\n\ +entry:\n\ + tail call fastcc void @k(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(3) %2, ptr addrspace(2) %3)\n\ + ret void\n}\n\ +define internal fastcc void @k(ptr addrspace(1) %a, ptr addrspace(1) %c, ptr addrspace(3) %tmp, ptr addrspace(2) %n) #1 {\n\ +entry:\n\ + %i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %l = tail call fastcc i64 @_Z12get_local_idj(i32 0)\n\ + %pa = getelementptr inbounds float, ptr addrspace(1) %a, i64 %i\n\ + %va = load float, ptr addrspace(1) %pa, align 4\n\ + %pt = getelementptr inbounds float, ptr addrspace(3) %tmp, i64 %l\n\ + store float %va, ptr addrspace(3) %pt, align 4\n\ + tail call fastcc void @_Z7barrierj(i32 1)\n\ + %vt = load float, ptr addrspace(3) %pt, align 4\n\ + %o = tail call fastcc i64 @_Z17get_global_offsetj(i32 0)\n\ + %w = tail call fastcc i32 @_Z12get_work_dimv()\n\ + %vn = load i32, ptr addrspace(2) %n, align 4\n\ + %ow = trunc i64 %o to i32\n\ + %s1 = add i32 %ow, %w\n\ + %s2 = add i32 %s1, %vn\n\ + %f = uitofp i32 %s2 to float\n\ + %r = fadd float %vt, %f\n\ + %pc = getelementptr inbounds float, ptr addrspace(1) %c, i64 %i\n\ + store float %r, ptr addrspace(1) %pc, align 4\n\ + ret void\n}\n\ +define internal fastcc i64 @_Z13get_global_idj(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_global_id.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i64 @_Z12get_local_idj(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_local_id.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i64 @_Z17get_global_offsetj(i32 %0) #2 {\n\ + %2 = tail call i32 @air.get_global_offset.i32(i32 %0) #3\n\ + %3 = zext i32 %2 to i64\n\ + ret i64 %3\n}\n\ +define internal fastcc i32 @_Z12get_work_dimv() #2 {\n\ + %1 = tail call i32 @air.get_work_dim.i32() #3\n\ + ret i32 %1\n}\n\ +define internal fastcc void @_Z7barrierj(i32 %0) #4 {\n\ + call void @air.wg.barrier(i32 %0, i32 5, i32 1) #5\n\ + ret void\n}\n\ +declare i32 @air.get_global_id.i32(i32) #3\n\ +declare i32 @air.get_local_id.i32(i32) #3\n\ +declare i32 @air.get_global_offset.i32(i32) #3\n\ +declare i32 @air.get_work_dim.i32() #3\n\ +declare void @air.wg.barrier(i32, i32, i32) #5\n\ +attributes #0 = { nounwind }\n\ +attributes #1 = { convergent nounwind }\n\ +attributes #2 = { nounwind optsize }\n\ +attributes #3 = { nounwind readnone willreturn }\n\ +attributes #4 = { convergent nounwind }\n\ +attributes #5 = { convergent nounwind willreturn }\n\ +!air.kernel = !{!0}\n\ +!air.version = !{!7}\n\ +!air.language_version = !{!8}\n\ +!0 = !{ptr @__entry_k, !1, !2}\n\ +!1 = !{}\n\ +!2 = !{!3, !4, !5, !6}\n\ +!3 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"float\", !\"air.arg_name\", !\"a\"}\n\ +!4 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 1, 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\", !\"float\", !\"air.arg_name\", !\"c\"}\n\ +!5 = !{i32 2, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 3, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"float\", !\"air.arg_name\", !\"tmp\"}\n\ +!6 = !{i32 3, !\"air.buffer\", !\"air.location_index\", i32 2, 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\"}\n\ +!7 = !{i32 2, i32 9, i32 0}\n\ +!8 = !{!\"Metal\", i32 1, i32 1, i32 0}\n"; + +/// The kernel's function, or `None` (a skip) without `llvm-as`. +fn kernel() -> Option { + let bitcode = match metal2vulkan_devtools::llvm_assemble_text(MODULE) { + Ok(b) => b, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return None; + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the module: {why}"), + }; + let lib = Library::from_air(&bitcode).expect("library"); + Some(FunctionDescriptor::new( + lib.function("__entry_k").expect("__entry_k"), + )) +} + +/// The compute descriptor of `kernel`, in OpenCL mode where `open_cl_mode`. +fn descriptor(kernel: StageSource, open_cl_mode: bool) -> ComputePipelineDescriptor { + let mut d = ComputePipelineDescriptor::new(kernel); + d.open_cl_mode_enabled = open_cl_mode; + d +} + +/// Each binding's name, type, index, access and use, and a buffer's data size, alignment and +/// data type. +type Row = ( + String, + BindingType, + u32, + BindingAccess, + bool, + Option<(u64, u64, DataType)>, +); + +fn rows(d: &ComputePipelineDescriptor) -> Vec { + let r = d.reflection(&Budget::standard()).expect("reflection"); + r.bindings() + .iter() + .map(|b| { + ( + b.name().to_owned(), + b.binding_type(), + b.index(), + b.access(), + b.is_used(), + b.buffer().map(|x| { + ( + x.buffer_data_size(), + x.buffer_alignment(), + x.buffer_data_type(), + ) + }), + ) + }) + .collect() +} + +#[test] +fn an_opencl_mode_pipeline_reflects_its_arguments_past_the_hidden_buffers() { + let Some(k) = kernel() else { + return; + }; + let buffer = |name: &str, index, access, size, align, ty| { + ( + name.to_owned(), + BindingType::Buffer, + index, + access, + true, + Some((size, align, ty)), + ) + }; + let tmp = ( + "tmp".to_owned(), + BindingType::ThreadgroupMemory, + 0, + BindingAccess::ReadWrite, + true, + None, + ); + let float = DataType::Float; + assert_eq!( + rows(&descriptor(StageSource::Function(k.clone()), true)), + [ + buffer("a", 3, BindingAccess::ReadOnly, 4, 4, float), + buffer("c", 4, BindingAccess::ReadWrite, 4, 4, float), + tmp.clone(), + buffer("n", 5, BindingAccess::ReadOnly, 4, 4, DataType::UInt), + buffer( + "__global_offset_and_num_dims", + 0, + BindingAccess::ReadOnly, + 4, + 4, + DataType::UInt + ), + buffer( + "__printf_buffer", + 1, + BindingAccess::ReadWrite, + 1, + 1, + DataType::Char + ), + buffer( + "__image_order_data_type_table", + 2, + BindingAccess::ReadOnly, + 4, + 4, + DataType::UInt + ), + ] + ); + // Without the mode the arguments are where their nodes put them, and no buffer is hidden. + assert_eq!( + rows(&descriptor(StageSource::Function(k.clone()), false)), + [ + buffer("a", 0, BindingAccess::ReadOnly, 4, 4, float), + buffer("c", 1, BindingAccess::ReadWrite, 4, 4, float), + tmp, + buffer("n", 2, BindingAccess::ReadOnly, 4, 4, DataType::UInt), + ] + ); + // Its slot writes name the same slots: the kernel's at their moved indices, then the hidden + // buffers'. + let writes = descriptor(StageSource::Function(k), true) + .slot_writes(&Budget::standard()) + .expect("slot writes"); + let indices: Vec<_> = writes + .kernel_slots() + .iter() + .map(|w| (w.name.clone(), w.index)) + .collect(); + assert_eq!( + indices, + [ + ("a".to_owned(), Some(3)), + ("c".to_owned(), Some(4)), + ("tmp".to_owned(), Some(0)), + ("n".to_owned(), Some(5)), + ("__global_offset_and_num_dims".to_owned(), Some(0)), + ("__printf_buffer".to_owned(), Some(1)), + ("__image_order_data_type_table".to_owned(), Some(2)), + ] + ); +} + +/// In OpenCL mode the kernel compiles, its key apart from the plain one's, and its artifact +/// records the mode; a compiled kernel serves only a pipeline of the mode it was compiled in +/// (`InvalidDescriptor(OpenClMode)`). Without the mode, `get_global_offset` and `get_work_dim` +/// have no value to read, and the compile refuses them, as Metal refuses a plain pipeline of the +/// kernel. +#[test] +fn an_opencl_mode_kernel_compiles_in_its_mode_alone() { + let Some(k) = kernel() else { + return; + }; + let dev = device("moltenvk-m3"); + let b = Budget::standard(); + let cl = dev + .compile_compute_pipeline(&descriptor(StageSource::Function(k.clone()), true), &b) + .expect("an OpenCL-mode pipeline"); + let plain_key = dev.compute_pipeline_key(&descriptor(StageSource::Function(k.clone()), false)); + assert_ne!(cl.key, plain_key); + let refused = dev + .compile_compute_pipeline(&descriptor(StageSource::Function(k.clone()), false), &b) + .map(|_| ()); + match refused { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::Lowering(LowerFamily::Dispatch), "{u:?}"); + } + other => panic!("{other:?}"), + } + let mut inputs = LowerInputs::new(); + inputs.open_cl_mode = true; + let compiled = dev.compile_function(&k, &inputs, &b).expect("compiled"); + assert!(compiled.artifact().facts.contains(&RuntimeFact::OpenClMode)); + let pipeline = |open_cl_mode| { + dev.compile_compute_pipeline( + &descriptor(StageSource::Compiled(compiled.clone()), open_cl_mode), + &b, + ) + .map(|_| ()) + }; + assert_eq!(pipeline(true), Ok(())); + assert_eq!( + pipeline(false), + Err(Error::InvalidDescriptor(DescriptorError::OpenClMode { + compiled: true + })) + ); +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 92244a672..23f9f23d7 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -101,6 +101,7 @@ mod engine_native_maths; mod engine_nonwritable; mod engine_not_mipmapped_anisotropic; mod engine_offset_arms; +mod engine_opencl_mode; mod engine_places; mod engine_pointer_cells; mod engine_pointer_memory; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index fdebef5f9..bc0b1c444 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1196,6 +1196,7 @@ enum metal2vulkan-air::intrinsics::Tensor #[derive(Clone, Copy, Debug, PartialEq enum metal2vulkan-air::intrinsics::TexOp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum TexOp enum metal2vulkan-air::intrinsics::TexRole #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum TexRole enum metal2vulkan-air::intrinsics::ThreadScope #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ThreadScope +enum metal2vulkan-air::intrinsics::WorkItem #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum WorkItem enum metal2vulkan-air::ir::AddrSpace #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AddrSpace enum metal2vulkan-air::ir::AtomicRmwOp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AtomicRmwOp enum metal2vulkan-air::ir::BinOp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum BinOp @@ -1583,6 +1584,7 @@ field metal2vulkan-air::Lockstep.emulated pub emulated: bool field metal2vulkan-air::SpecRequest.call_stack_depth pub call_stack_depth: u32 field metal2vulkan-air::SpecRequest.constants pub constants: BTreeMap field metal2vulkan-air::SpecRequest.entry pub entry: String +field metal2vulkan-air::SpecRequest.open_cl_mode pub open_cl_mode: bool field metal2vulkan-air::abi::AirAbi.air_version pub air_version: Option field metal2vulkan-air::abi::AirAbi.compile pub compile: CompileOptions field metal2vulkan-air::abi::AirAbi.core_image_kernels pub core_image_kernels: Vec @@ -4229,6 +4231,7 @@ field metal2vulkan::pipeline::ComputePipelineDescriptor.kernel pub kernel: Stage field metal2vulkan::pipeline::ComputePipelineDescriptor.max_call_stack_depth pub max_call_stack_depth: u32 field metal2vulkan::pipeline::ComputePipelineDescriptor.max_total_threads_per_threadgroup pub max_total_threads_per_threadgroup: Option field metal2vulkan::pipeline::ComputePipelineDescriptor.needs_custom_border_color_samplers pub needs_custom_border_color_samplers: bool +field metal2vulkan::pipeline::ComputePipelineDescriptor.open_cl_mode_enabled pub open_cl_mode_enabled: bool field metal2vulkan::pipeline::ComputePipelineDescriptor.required_threads_per_threadgroup pub required_threads_per_threadgroup: Option<[u32; 3]> field metal2vulkan::pipeline::ComputePipelineDescriptor.stage_input pub stage_input: Option field metal2vulkan::pipeline::ComputePipelineDescriptor.support_adding_binary_functions pub support_adding_binary_functions: bool @@ -4373,6 +4376,7 @@ field metal2vulkan::pipeline::LoweringInputs.max_call_stack_depth pub max_call_s field metal2vulkan::pipeline::LoweringInputs.merged_draws pub merged_draws: bool field metal2vulkan::pipeline::LoweringInputs.multisampled pub multisampled: bool field metal2vulkan::pipeline::LoweringInputs.object_payload pub object_payload: Option +field metal2vulkan::pipeline::LoweringInputs.open_cl_mode pub open_cl_mode: bool field metal2vulkan::pipeline::LoweringInputs.primitive_id_indices pub primitive_id_indices: Option field metal2vulkan::pipeline::LoweringInputs.primitive_id_varying pub primitive_id_varying: bool field metal2vulkan::pipeline::LoweringInputs.primitive_varyings pub primitive_varyings: BTreeSet @@ -7521,6 +7525,7 @@ method metal2vulkan-air::intrinsics::Texture::layout pub fn layout(&self) -> Lay method metal2vulkan-air::intrinsics::Texture::signature pub fn signature(&self) -> Signature method metal2vulkan-air::intrinsics::Texture::ulong pub fn ulong(&self) -> bool method metal2vulkan-air::intrinsics::ThreadScope::from_raw pub fn from_raw(v: u64) -> Option +method metal2vulkan-air::intrinsics::WorkItem::signature pub fn signature(&self) -> Signature method metal2vulkan-air::ir::AddrSpace::from_raw pub fn from_raw(n: u32) -> Result method metal2vulkan-air::ir::AddrSpace::raw pub const fn raw(self) -> u32 method metal2vulkan-air::ir::Align::bytes pub fn bytes(self) -> u64 @@ -10675,6 +10680,7 @@ variant metal2vulkan-air::intrinsics::AirIntrinsic::SimdgroupSize SimdgroupSize( variant metal2vulkan-air::intrinsics::AirIntrinsic::Sync Sync(Sync) variant metal2vulkan-air::intrinsics::AirIntrinsic::Tensor Tensor(Tensor) variant metal2vulkan-air::intrinsics::AirIntrinsic::Texture Texture(Texture) +variant metal2vulkan-air::intrinsics::AirIntrinsic::WorkItem WorkItem(WorkItem) variant metal2vulkan-air::intrinsics::AsyncCopy::Copy2d Copy2d { dst: AddrSpace, src: AddrSpace } variant metal2vulkan-air::intrinsics::AsyncCopy::IsNullEvent IsNullEvent variant metal2vulkan-air::intrinsics::AsyncCopy::NullEvent NullEvent @@ -11109,6 +11115,8 @@ variant metal2vulkan-air::intrinsics::ThreadScope::Device Device variant metal2vulkan-air::intrinsics::ThreadScope::Simdgroup Simdgroup variant metal2vulkan-air::intrinsics::ThreadScope::Thread Thread variant metal2vulkan-air::intrinsics::ThreadScope::Threadgroup Threadgroup +variant metal2vulkan-air::intrinsics::WorkItem::GlobalOffset GlobalOffset +variant metal2vulkan-air::intrinsics::WorkItem::WorkDim WorkDim variant metal2vulkan-air::ir::AddrSpace::Constant Constant = 2 variant metal2vulkan-air::ir::AddrSpace::Device Device = 1 variant metal2vulkan-air::ir::AddrSpace::MeshOutput MeshOutput = 7 @@ -13376,6 +13384,7 @@ variant metal2vulkan::error::DescriptorError::MaxCallStackDepth MaxCallStackDept variant metal2vulkan::error::DescriptorError::MaxTessellationFactor MaxTessellationFactor { factor: u32, partition_mode: crate::metal::TessellationPartitionMode } variant metal2vulkan::error::DescriptorError::MeshPipeline MeshPipeline { problem: MeshPipelineProblem } variant metal2vulkan::error::DescriptorError::MissingStage MissingStage { stage: Stage } +variant metal2vulkan::error::DescriptorError::OpenClMode OpenClMode { compiled: bool } variant metal2vulkan::error::DescriptorError::PixelFormatUsage PixelFormatUsage { format: u32, usage: FormatUsage } variant metal2vulkan::error::DescriptorError::PlaceholderEnumValue PlaceholderEnumValue { ty: &'static str, value: u32 } variant metal2vulkan::error::DescriptorError::SamplerLodClamp SamplerLodClamp @@ -14066,6 +14075,7 @@ variant metal2vulkan::pipeline::RuntimeFact::MergedDraws MergedDraws variant metal2vulkan::pipeline::RuntimeFact::MeshLastFirst MeshLastFirst variant metal2vulkan::pipeline::RuntimeFact::MovableStorageWrites MovableStorageWrites { early_variant: bool } variant metal2vulkan::pipeline::RuntimeFact::ObjectThreadgroupArena ObjectThreadgroupArena { static_bytes: u32, payload: Option } +variant metal2vulkan::pipeline::RuntimeFact::OpenClMode OpenClMode variant metal2vulkan::pipeline::RuntimeFact::OutOfBoundsAlpha OutOfBoundsAlpha { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::PartialObjectThreadgroups PartialObjectThreadgroups variant metal2vulkan::pipeline::RuntimeFact::PredicationVote PredicationVote diff --git a/docs/API.md b/docs/API.md index 73b9bb8a0..0c199c777 100644 --- a/docs/API.md +++ b/docs/API.md @@ -607,6 +607,26 @@ layout stride of `None` is `MTLBufferLayoutStrideDynamic`: the stride comes from `InvalidInput(Intrinsic(ImmediateNotConstant))` at the call. `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` are folded over constants, on a width no SPIR-V type has (`i2`) too; an integer `llvm.*` operation on such a width that is not folded is refused (`Lowering(Arith)`). + - OpenCL mode. Metal makes a pipeline of such a kernel only with + `ComputePipelineDescriptor::open_cl_mode_enabled` (`openCLModeEnabled`, Apple SPI), and the + crate compiles the kernel as Metal links it then (`LoweringInputs::open_cl_mode`, part of the + key). Three hidden buffers come before the kernel's own: `__global_offset_and_num_dims` at + index 0, four `uint`s the dispatcher fills with the dispatch's global offset in each of its + dimensions and its dimension count, `__printf_buffer` at 1 and + `__image_order_data_type_table` at 2. Each argument the kernel binds at a buffer index sits 3 + past its own; threadgroup memory (`__local`), textures and samplers keep theirs. The + reflection lists the kernel's arguments at those indices, then the three buffers (read-only + `uint` 4 bytes, read-write `char` 1 byte, read-only `uint` 4 bytes), each used, as the M3 Max + answers. OpenCL C's work-item functions read the dispatch: `get_global_id(d)` is the thread's + position in the grid plus the offset in `d`, `get_global_offset(d)` and `get_work_dim()` read + buffer 0, `get_local_id`, `get_group_id`, `get_local_size`, `get_global_size` and + `get_num_groups` are the built-ins of those names, and a dimension the kernel reads from its + data selects among the three. A dimension past 2 answers OpenCL's 0 for an id or an offset + and 1 for a size or a count. A compiled kernel serves only a pipeline of the mode it was + compiled in (`RuntimeFact::OpenClMode`, `InvalidDescriptor(OpenClMode)` otherwise). Without + the mode Metal refuses the pipeline ("Internal compiler error"); the crate compiles the AIR as + Metal AIR, its buffers at their own indices, and refuses a read of `get_global_offset` or + `get_work_dim` (`Unsupported` with `Lowering(Dispatch)`). ## 4. A render pipeline @@ -4392,6 +4412,11 @@ each item named states the rule in full. `requiredThreadsPerThreadgroup` (true, 96 and 8 by 6 by 2 in `compute-descriptor-reset`, where the runtime answers false, 0 and 0 by 0 by 0). The tile and mesh render pipeline descriptors' resets restore every field on the same machine. +- **An OpenCL work-item read of a dimension past 2 answers OpenCL's value** in a pipeline of + OpenCL mode: 0 for `get_global_id`, `get_local_id`, `get_group_id` and `get_global_offset`, 1 + for `get_local_size`, `get_global_size` and `get_num_groups`, as OpenCL C defines them. The M3 + Max (macOS 27.0.1) leaves unwritten the store of `get_global_id(3) + get_local_size(4) + + get_global_size(5)`, where the runtime stores 2. **Mesh render pipelines** diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c4b2e6514..3cafac9d6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -67,7 +67,7 @@ rest is `crates/metal2vulkan/src/`. | Module | Role | |---|---| -| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining, function constants, SCCP (reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` on constants, and reading the immediates of an intrinsic call that its function's parameters gave it once inlining makes them its call site's constants), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, devirtualization, linking, pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, and the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data | +| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining, function constants, SCCP (reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` on constants, and reading the immediates of an intrinsic call that its function's parameters gave it once inlining makes them its call site's constants), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, devirtualization, linking, pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses, and a kernel of a pipeline of OpenCL mode linked as Metal links it: the three hidden buffers appended, its buffer indices 3 on, and OpenCL C's work-item reads made reads of their built-ins or of the first buffer, `canon::opencl`). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data | | `graph` | The shared RPO, dominator tree, loop forest and SCC | | `budget` | `Budget`, `CancelToken`, and the per-attempt `Meter`: deadline, cancellation, work units, the byte ledger and every structural cap | | `memory/` | Pointer provenance, the `MemoryPlan`, leaf access emitters, arenas, root and handle lookups, word composition, atomics | diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index bca5ea5a5..f4dce1d58 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -140,7 +140,7 @@ Columns: | `SubgroupOperations` | Simdgroup operations of a class the stage's subgroups do not support (the stage is not in `subgroupSupportedStages`, or an operation class is... | devices without VkFeature::ShaderQuadControl; devices without VkFeature::ShaderSubgroupExtendedTypes; devices without VkProperty::SubgroupStage | `device` | 4: `crates/metal2vulkan-runtime/src/families/features.rs (simd)`, `crates/metal2vulkan/src/lower/simd/mod.rs (finish)` (+2) | `app`: simdgroup functions in a stage a device's subgroups do not support | | `DirectCall` | A call to a defined function the inliner cannot take | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` | `rare`: variadic or byval calls the inliner cannot take | | `WideSwitchLiteral` | A switch case literal wider than 32 bits | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/structurize/emit.rs (check_tree)` | `rare`: 64-bit switch literals | -| `Lowering` | An instruction, intrinsic, or interface element of a lowering family whose lowering has not landed yet (each family narrows its refusals as it lands) | devices short of a device limit the site names; devices without VkFeature::ShaderDemoteToHelperInvocation; every device (not implemented) | `ours` | 35: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`, `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)` (+33) | `system`: the catch-all of lowering families not landed: any shader can meet one | +| `Lowering` | An instruction, intrinsic, or interface element of a lowering family whose lowering has not landed yet (each family narrows its refusals as it lands) | devices short of a device limit the site names; devices without VkFeature::ShaderDemoteToHelperInvocation; every device (not implemented) | `ours` | 36: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`, `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)` (+33) | `system`: the catch-all of lowering families not landed: any shader can meet one | | `SamplerAddressMode` | A sampler address mode the device lacks (`MirrorClampToEdge`) | devices without VkFeature::SamplerMirrorClampToEdge; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/sampler/constexpr.rs`, `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` | `app`: mirror-clamp-to-edge on a device without it | | `AlphaToOne` | `alphaToOneEnabled` on a device without Vulkan's `alphaToOne` feature, the exact counterpart... | devices without VkFeature::AlphaToOne | `device` | 1: `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)` | `rare`: alphaToOneEnabled on a device without alphaToOne | | `StageStoresAndAtomics` | Buffer or image stores or atomics in a vertex or fragment function without the stage's store feature (`vertexPipelineStoresAndAtomics`,... | devices without VkFeature::FragmentStoresAndAtomics | `device` | 1: `crates/metal2vulkan/src/lower/access/tile_memory.rs (written)` | `app`: stores or atomics in vertex or fragment functions on a device without the feature | @@ -651,7 +651,7 @@ Each refusal's sites, with the function that builds it. - `feature::SubgroupOperations`: `crates/metal2vulkan-runtime/src/families/features.rs (simd)`; `crates/metal2vulkan/src/lower/simd/mod.rs (finish)`; `crates/metal2vulkan/src/lower/simd/mod.rs (full_quads)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_group)` - `feature::DirectCall`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` - `feature::WideSwitchLiteral`: `crates/metal2vulkan/src/structurize/emit.rs (check_tree)` -- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`; `crates/metal2vulkan/src/lower/access/handle.rs (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs (texture_target)`; `crates/metal2vulkan/src/lower/access/imageblock.rs (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/snapshot.rs (finish)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs (route_air)`; `crates/metal2vulkan/src/lower/simd/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (patch_fetch_projection)` +- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`; `crates/metal2vulkan/src/lower/access/handle.rs (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs (texture_target)`; `crates/metal2vulkan/src/lower/access/imageblock.rs (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/snapshot.rs (finish)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs (route_air, 2 sites)`; `crates/metal2vulkan/src/lower/simd/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (patch_fetch_projection)` - `feature::SamplerAddressMode`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs`; `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` - `feature::AlphaToOne`: `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)` - `feature::StageStoresAndAtomics`: `crates/metal2vulkan/src/lower/access/tile_memory.rs (written)` @@ -681,7 +681,7 @@ Each refusal's sites, with the function that builds it. - `feature::PrivateMemory`: `crates/metal2vulkan/src/lower/select.rs (function_storage)` - `feature::SparseTextures`: `crates/metal2vulkan-runtime/src/sparse/texture.rs (sparse_refusal, 2 sites)` - `feature::TimelineSemaphores`: `crates/metal2vulkan-runtime/src/device/create.rs (timeline_difference)` -- `feature::Reflection`: `crates/metal2vulkan-runtime/src/pipeline/texture_access.rs (at)`; `crates/metal2vulkan/src/bind/argument_buffer.rs (unmeasured)`; `crates/metal2vulkan/src/reflection/derive.rs (gap_at)`; `crates/metal2vulkan/src/reflection/derive.rs (read_attributes)`; `crates/metal2vulkan/src/reflection/derive.rs (specialized_reads)`; `crates/metal2vulkan/src/reflection/function.rs (attribute)`; `crates/metal2vulkan/src/reflection/function.rs (module_constants)`; `crates/metal2vulkan/src/reflection/function.rs (unmeasured)`; `crates/metal2vulkan/src/reflection/linked.rs (function)`; `crates/metal2vulkan/src/reflection/mod.rs (stage)` +- `feature::Reflection`: `crates/metal2vulkan-runtime/src/pipeline/texture_access.rs (at)`; `crates/metal2vulkan/src/bind/argument_buffer.rs (unmeasured)`; `crates/metal2vulkan/src/reflection/derive.rs (gap_at)`; `crates/metal2vulkan/src/reflection/derive.rs (read_attributes)`; `crates/metal2vulkan/src/reflection/derive.rs (specialized_reads)`; `crates/metal2vulkan/src/reflection/function.rs (attribute)`; `crates/metal2vulkan/src/reflection/function.rs (module_constants)`; `crates/metal2vulkan/src/reflection/function.rs (unmeasured)`; `crates/metal2vulkan/src/reflection/linked.rs (function)`; `crates/metal2vulkan/src/reflection/mod.rs (kernel_stage)` - `feature::HeapTextureTiling`: `crates/metal2vulkan-runtime/src/texture/heap.rs (tiling_refusal)` - `feature::ViewportDepthRange`: `crates/metal2vulkan-runtime/src/render_state.rs (depth_ranges_refused)` - `feature::UndeclaredTextureUsage`: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`; `crates/metal2vulkan-runtime/src/texture/usage_shadow.rs (refused)`