diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index 47a7a9d42..c3eca2a09 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -61,7 +61,10 @@ //! as far as those indices reach; one index with no bound keeps its declared type (`reach`). //! Before SCCP, each OpenCL C vector data load //! or store becomes its element accesses (`vector_data`), and in OpenCL mode each operation of -//! a 1D image becomes the 2D texture's that Apple's OpenCL binds for it (`opencl_1d`). +//! a 1D image becomes the 2D texture's that Apple's OpenCL binds for it (`opencl_1d`). After +//! the last SCCP, in OpenCL mode, each `air.wg.barrier`'s flags, bound to its call site's +//! constants where the barrier is out of line, are read as OpenCL C's `cl_mem_fence_flags` +//! ([`opencl`]). //! 8. **Post-check**: no unknown or unbound intrinsic, indirect call, or call to an undefined //! non-intrinsic function survives, and no reachable branch tests `undef`. A table call's refused candidate, //! a table call no linked function answers, and a function pointer used as a value are refused @@ -775,6 +778,14 @@ pub fn specialize_dynamic( // Each private array of nested arrays allocated as far as its accesses reach, where the // constants bound every index of it. let body = reach::narrow(body, &mut parts, func, m)?; + // OpenCL mode: each threadgroup barrier's flags, its call site's now where it is out of line, + // are OpenCL's `cl_mem_fence_flags`, read again as such; the post-check refuses one with a + // flag OpenCL does not name. + let body = if req.open_cl_mode && matches!(ep.stage, Stage::Kernel { .. }) { + opencl::barriers(body, &parts, m)? + } else { + body + }; matmul2d::refuse_left(&body, &parts, &ep.stage, &name, m)?; post_check(&body, &parts, &stubs, &name, &control_points(ep), m)?; // A branch's short arms that Metal's backend speculates, where a group operation in them diff --git a/crates/metal2vulkan-air/src/canon/opencl.rs b/crates/metal2vulkan-air/src/canon/opencl.rs index a506bad33..a8e55de21 100644 --- a/crates/metal2vulkan-air/src/canon/opencl.rs +++ b/crates/metal2vulkan-air/src/canon/opencl.rs @@ -39,6 +39,23 @@ //! as. Measured on an M3 Max (macOS 27.0.1) over `image1d_t`, `image1d_array_t`, `image2d_t` and //! `image3d_t` arguments read as float, int, uint and half, written, only queried and unused. //! +//! **Barrier flags.** OpenCL C's `barrier(flags)` takes `cl_mem_fence_flags`, which Apple's +//! `cl_kernel.h` (OpenCL.framework, "5.9.7 - Synchronization") declares as `CLK_LOCAL_MEM_FENCE = +//! 1U << 0` and `CLK_GLOBAL_MEM_FENCE = 1U << 1`, with no other flag (a member of bit 31 only +//! sizes the enum). Apple's OpenCL compiler passes them to `air.wg.barrier` unconverted: `barrier` +//! is an internal function that passes its parameter on as the barrier's flags, in the +//! two-operand form (flags, scope) and in the three-operand one (flags, order, scope). Metal's +//! `mem_flags` read the same bits as `mem_device` (1) and `mem_threadgroup` (2), so decode reads +//! `CLK_LOCAL_MEM_FENCE` as `mem_device`. In a kernel of OpenCL mode `barriers` reads each +//! `air.wg.barrier`'s flags again as OpenCL's, once SCCP has bound each call site's own flags to +//! an out-of-line barrier: `CLK_LOCAL_MEM_FENCE` orders threadgroup memory and +//! `CLK_GLOBAL_MEM_FENCE` device memory. A barrier whose flags set any other bit is left unknown, +//! and the post-check refuses it (`UnknownIntrinsic`), as it refuses a value outside Metal's +//! `mem_flags`. The header declares no other barrier on these flags (no `work_group_barrier` or +//! `sub_group_barrier`), so an `air.simdgroup.barrier` keeps Metal's reading; `mem_fence(flags)` +//! reaches `air.atomic.fence` through Apple's own conversion of the two bits +//! (`llvm.bitreverse.i2`), which is Metal's mask. +//! //! `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 @@ -58,7 +75,8 @@ use crate::abi::{ }; use crate::budget::Meter; use crate::error::{DiagName, Error}; -use crate::intrinsics::{AirIntrinsic, Elem, GlobalBuiltin, GlobalVar, Query, TexOp, WorkItem}; +use crate::intrinsics::{AirIntrinsic, BarrierName, Elem, GlobalBuiltin, GlobalVar, MemFlags}; +use crate::intrinsics::{Query, Sync, TexOp, 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, @@ -601,6 +619,55 @@ fn rewrite( Ok((out, first)) } +/// Each `air.wg.barrier` of the entry's `body` ordering the memories its flags name as OpenCL C's +/// `cl_mem_fence_flags` (see the module), which decode and SCCP's binding read as Metal's +/// `mem_flags`: the flags of the call's first operand, read again. A barrier whose flags set a bit +/// outside the two becomes an unknown intrinsic, which the post-check refuses. It runs after the +/// last SCCP, so every barrier out of line has its call site's flags. +pub(super) fn barriers(mut body: Body, parts: &ModuleParts, m: &mut Meter) -> Result { + for inst in body.insts.values_mut() { + m.tick(1)?; + let InstKind::Call(call) = &mut inst.kind else { + continue; + }; + let Callee::Air { + decl, + op: + AirIntrinsic::Sync(Sync::Barrier { + name: BarrierName::Threadgroup, + order, + scope, + memory, + .. + }), + } = call.callee + else { + continue; + }; + let raw = match call.args.first() { + Some(Value::Const(c)) => match parts.consts.get(*c).map(|k| &k.value) { + Some(Const::Int(v)) => *v, + _ => return Err(invariant("a barrier's flags are no integer constant")), + }, + _ => return Err(invariant("a barrier's flags are no constant")), + }; + call.callee = match MemFlags::from_cl_mem_fence_flags(raw) { + Some(flags) => Callee::Air { + decl, + op: AirIntrinsic::Sync(Sync::Barrier { + name: BarrierName::Threadgroup, + flags, + order, + scope, + memory, + }), + }, + None => Callee::UnknownIntrinsic(decl), + }; + } + Ok(body) +} + /// 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, diff --git a/crates/metal2vulkan-air/src/intrinsics/sync.rs b/crates/metal2vulkan-air/src/intrinsics/sync.rs index 99d2a3769..945f56f6f 100644 --- a/crates/metal2vulkan-air/src/intrinsics/sync.rs +++ b/crates/metal2vulkan-air/src/intrinsics/sync.rs @@ -19,6 +19,10 @@ //! `threadgroup_barrier(..., thread_scope_simdgroup)` as `air.wg.barrier` with scope 4). Metal's //! headers pass the name's own scope in every language before MSL 4.1, so the two readings agree on //! every barrier those spell. A value outside the modeled enumerations leaves the call unknown. +//! +//! In a kernel of Metal's OpenCL mode an `air.wg.barrier`'s flags are OpenCL C's +//! `cl_mem_fence_flags`, not Metal's mask ([`MemFlags::from_cl_mem_fence_flags`]): decode reads +//! every barrier as Metal's, and specialization reads such a kernel's again (`canon::opencl`). use super::atomic::{MemoryOrder, ThreadScope}; use super::sig::{ImmKind, Immediates, Operand, Signature}; @@ -52,6 +56,19 @@ impl MemFlags { object_data: v & 16 != 0, }) } + + /// The flags of OpenCL C's `cl_mem_fence_flags` mask `v`, which a threadgroup barrier of a + /// kernel of Metal's OpenCL mode takes in place of Metal's mask (`canon::opencl`): + /// `CLK_LOCAL_MEM_FENCE` (1) is `mem_threadgroup` and `CLK_GLOBAL_MEM_FENCE` (2) is + /// `mem_device`. `None` when a bit outside the two is set: Apple's `cl_kernel.h` names no + /// other. + pub(crate) fn from_cl_mem_fence_flags(v: u64) -> Option { + (v & !0x3 == 0).then_some(MemFlags { + device: v & 2 != 0, + threadgroup: v & 1 != 0, + ..MemFlags::default() + }) + } } /// Which intrinsic a barrier was spelled with: its execution scope in the AIR 2.9 form (in the diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 83cfca5bb..d5cbd7424 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 = 2307; +pub const SEMANTICS_VERSION: u32 = 2308; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs index 458de0d6d..adca1d0d1 100644 --- a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs +++ b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs @@ -744,3 +744,265 @@ fn an_opencl_mode_half_store_records_the_devices_nan_encoding() { } assert!(checked > 0); } + +/// `__kernel void b(__global float *x, __local float *t)` in the shape Apple's OpenCL compiler +/// writes it (AIR 2.3): `t[l] = x[i]`, the barriers `calls` makes, then `x[i] = t[l] + 1`, for +/// `i = get_global_id(0)` and `l = get_local_id(0)`; `defs` are the functions and declarations the +/// calls reach. Each thread reads only what it wrote, so the program's barriers are the module's +/// only ones. +fn barrier_kernel(calls: &str, defs: &str) -> String { + format!( + "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_v23-apple-macosx14.0.0\"\n\ +define void @__entry_b(ptr addrspace(1) %0, ptr addrspace(3) %1) #0 {{\n\ +entry:\n\ + tail call fastcc void @b(ptr addrspace(1) %0, ptr addrspace(3) %1)\n\ + ret void\n}}\n\ +define internal fastcc void @b(ptr addrspace(1) %x, ptr addrspace(3) %t) #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\ + %px = getelementptr inbounds float, ptr addrspace(1) %x, i64 %i\n\ + %vx = load float, ptr addrspace(1) %px, align 4\n\ + %pt = getelementptr inbounds float, ptr addrspace(3) %t, i64 %l\n\ + store float %vx, ptr addrspace(3) %pt, align 4\n\ +{calls}\ + %vt = load float, ptr addrspace(3) %pt, align 4\n\ + %r = fadd float %vt, 1.000000e+00\n\ + store float %r, ptr addrspace(1) %px, 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\ +{defs}\ +declare i32 @air.get_global_id.i32(i32) #3\n\ +declare i32 @air.get_local_id.i32(i32) #3\n\ +attributes #0 = {{ nounwind }}\n\ +attributes #1 = {{ convergent nounwind }}\n\ +attributes #2 = {{ nounwind optsize }}\n\ +attributes #3 = {{ nounwind readnone willreturn }}\n\ +attributes #4 = {{ convergent noinline nounwind }}\n\ +attributes #5 = {{ convergent nounwind willreturn }}\n\ +!air.kernel = !{{!0}}\n\ +!air.version = !{{!5}}\n\ +!air.language_version = !{{!6}}\n\ +!0 = !{{ptr @__entry_b, !1, !2}}\n\ +!1 = !{{}}\n\ +!2 = !{{!3, !4}}\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\", !\"float\", !\"air.arg_name\", !\"x\"}}\n\ +!4 = !{{i32 1, !\"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\", !\"t\"}}\n\ +!5 = !{{i32 2, i32 3, i32 0}}\n\ +!6 = !{{!\"Metal\", i32 1, i32 1, i32 0}}\n" + ) +} + +/// OpenCL C's `barrier(flags)` as Apple's OpenCL compiler writes it: an internal function passing +/// its parameter on as `air.wg.barrier`'s flags, in the two-operand form (flags, threadgroup). +const BARRIER_TWO_OPERANDS: &str = "define internal fastcc void @_Z7barrierj(i32 %0) #4 {\n\ + tail call void @air.wg.barrier(i32 %0, i32 1) #5\n\ + ret void\n}\n\ +declare void @air.wg.barrier(i32, i32) #5\n"; + +/// The same in the three-operand form (flags, `seq_cst`, threadgroup). +const BARRIER_THREE_OPERANDS: &str = "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 void @air.wg.barrier(i32, i32, i32) #5\n"; + +/// `barrier(flags)` for each of OpenCL's flags `flags`, through the wrapper. +fn wrapper_calls(flags: &[u32]) -> String { + flags + .iter() + .map(|f| format!(" tail call fastcc void @_Z7barrierj(i32 noundef {f})\n")) + .collect() +} + +/// The barrier routes of a kernel's flags, each `(route, calls, defs)` of [`barrier_kernel`] with +/// barriers of `CLK_LOCAL_MEM_FENCE` (1), `CLK_GLOBAL_MEM_FENCE` (2) and both (3), in that order: +/// `air.wg.barrier` called with the constant; the wrapper of two operands and of three; and a +/// function of the kernel passing its own parameter on to a wrapper (of another name), each of its +/// three call sites binding its own flags. +fn barrier_routes() -> [(&'static str, String, String); 4] { + let passed = "define internal fastcc void @step(i32 %f) #4 {\n\ + tail call fastcc void @wait(i32 %f)\n\ + ret void\n}\n\ +define internal fastcc void @wait(i32 %0) #4 {\n\ + tail call void @air.wg.barrier(i32 %0, i32 1) #5\n\ + ret void\n}\n\ +declare void @air.wg.barrier(i32, i32) #5\n"; + [ + ( + "inline", + (1..=3) + .map(|f| format!(" tail call void @air.wg.barrier(i32 {f}, i32 1) #5\n")) + .collect(), + "declare void @air.wg.barrier(i32, i32) #5\n".to_owned(), + ), + ( + "wrapper of two operands", + wrapper_calls(&[1, 2, 3]), + BARRIER_TWO_OPERANDS.to_owned(), + ), + ( + "wrapper of three operands", + wrapper_calls(&[1, 2, 3]), + BARRIER_THREE_OPERANDS.to_owned(), + ), + ( + "passed through a call site", + (1..=3) + .map(|f| format!(" tail call fastcc void @step(i32 {f})\n")) + .collect(), + passed.to_owned(), + ), + ] +} + +/// `UniformMemory`, `WorkgroupMemory` and `ImageMemory`: the storage classes a barrier's semantics +/// name. +const STORAGE: u32 = 0x40 | 0x100 | 0x800; + +/// Each `OpControlBarrier` of module `words`, in order: its execution scope, its memory scope, the +/// storage classes its semantics name ([`STORAGE`]), and whether its order is `AcquireRelease`. +fn control_barriers(words: &[u32]) -> Vec<(u32, u32, u32, bool)> { + use crate::spirv_binary::{parse_bytes, Operand}; + use crate::spv::Op; + use std::collections::BTreeMap; + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let module = parse_bytes(&bytes).expect("the module parses"); + let constants: BTreeMap = (module.instructions.iter()) + .filter(|i| i.opcode == Op::Constant) + .filter_map(|i| match (i.result_id, i.operands.as_slice()) { + (Some(id), [Operand::Word(v)]) => Some((id, *v)), + _ => None, + }) + .collect(); + let value = |o: &Operand| match o { + Operand::IdScope(id) | Operand::IdMemorySemantics(id) => *constants + .get(id) + .unwrap_or_else(|| panic!("%{id} is no 32-bit constant")), + other => panic!("{other:?} is no scope or semantics"), + }; + (module.instructions.iter()) + .filter(|i| i.opcode == Op::ControlBarrier) + .map(|i| { + let [exec, memory, semantics] = i.operands.as_slice() else { + panic!("{i:?}"); + }; + let s = value(semantics); + (value(exec), value(memory), s & STORAGE, s & 0x8 != 0) + }) + .collect() +} + +/// Every committed profile's device under the runtime's policy (`DevicePolicy::default`), by +/// stem; one the policy refuses is left out. +fn runtime_devices() -> Vec<(String, crate::device::Device)> { + crate::metal::format::tests::committed_descriptions() + .into_iter() + .filter_map(|(stem, desc)| { + let policy = crate::device::DevicePolicy::default(); + Some(( + stem, + crate::device::Device::from_queries(desc, policy).ok()?, + )) + }) + .collect() +} + +/// In OpenCL mode an `air.wg.barrier`'s flags are OpenCL's `cl_mem_fence_flags`, as Apple's +/// `cl_kernel.h` defines them: `CLK_LOCAL_MEM_FENCE` (1) orders threadgroup memory +/// (`WorkgroupMemory`, and no `UniformMemory`), `CLK_GLOBAL_MEM_FENCE` (2) device memory +/// (`UniformMemory`) and both (3) both, by every route the flags reach the barrier: a constant, a +/// wrapper of two operands or of three, and a parameter each call site binds. Without the mode the +/// same AIR's flags are Metal's `mem_flags`: 1 is `mem_device` and 2 `mem_threadgroup`. Each +/// barrier is `OpControlBarrier(Workgroup, Workgroup, AcquireRelease | ..)` in the pipeline's +/// module, on every committed profile that takes threadgroup memory, under the runtime's policy. +#[test] +fn an_opencl_mode_barrier_orders_the_memory_its_opencl_flags_name() { + let b = Budget::standard(); + let devices = runtime_devices(); + let (uniform, workgroup) = (0x40, 0x100); + let barrier = |storage| (2, 2, storage, true); + let opencl = [ + barrier(workgroup), + barrier(uniform), + barrier(uniform | workgroup), + ]; + let metal = [ + barrier(uniform), + barrier(workgroup), + barrier(uniform | workgroup), + ]; + let mut compiled = std::collections::BTreeSet::new(); + for (route, calls, defs) in barrier_routes() { + let Some(k) = function(&barrier_kernel(&calls, &defs), "__entry_b") else { + return; + }; + for (stem, dev) in &devices { + for (open_cl_mode, want) in [(true, &opencl), (false, &metal)] { + let what = format!("{route}, OpenCL mode {open_cl_mode}, on {stem}"); + let d = descriptor(StageSource::Function(k.clone()), open_cl_mode); + let p = match dev.compile_compute_pipeline(&d, &b) { + Ok(p) => p, + Err(e) + if crate::spirv::testing::refuses_threadgroup_memory(&e, dev.profile()) => + { + continue; + } + Err(e) => panic!("{what}: {e}"), + }; + assert_eq!(control_barriers(&p.stage.spirv), want, "{what}"); + compiled.insert(stem.clone()); + } + } + } + for stem in ["amd-780m-radv", "nvidia-rtx50-linux", "lavapipe"] { + assert!(compiled.contains(stem), "{stem}: {compiled:?}"); + } +} + +/// In OpenCL mode a barrier whose flags set a bit `cl_mem_fence_flags` does not name (4, which +/// Metal's `mem_flags` read as `mem_texture`) is refused as an intrinsic outside the modeled set, +/// as a constant and through the wrapper; without the mode the same AIR orders texture memory +/// (`ImageMemory`). +#[test] +fn an_opencl_mode_barrier_of_a_flag_opencl_does_not_name_is_refused() { + let b = Budget::standard(); + let dev = device("amd-780m-radv"); + let routes = [ + ( + "inline", + " tail call void @air.wg.barrier(i32 4, i32 1) #5\n".to_owned(), + "declare void @air.wg.barrier(i32, i32) #5\n", + ), + ("wrapper", wrapper_calls(&[4]), BARRIER_TWO_OPERANDS), + ]; + for (route, calls, defs) in routes { + let Some(k) = function(&barrier_kernel(&calls, defs), "__entry_b") else { + return; + }; + let refused = dev + .compile_compute_pipeline(&descriptor(StageSource::Function(k.clone()), true), &b) + .map(|_| ()); + match refused { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::UnknownIntrinsic, "{route}: {u:?}"); + } + other => panic!("{route}: {other:?}"), + } + let metal = dev + .compile_compute_pipeline(&descriptor(StageSource::Function(k), false), &b) + .unwrap_or_else(|e| panic!("{route} without the mode: {e}")); + assert_eq!( + control_barriers(&metal.stage.spirv), + [(2, 2, 0x800, true)], + "{route} without the mode" + ); + } +} diff --git a/docs/API.md b/docs/API.md index cf91027a4..ba0b1c0b2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -792,9 +792,19 @@ through buffer arguments it reads at any index. 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 + and 1 for a size or a count. OpenCL C's `barrier(flags)` passes OpenCL's + `cl_mem_fence_flags` to `air.wg.barrier` unconverted, and Apple's `cl_kernel.h` defines them + as `CLK_LOCAL_MEM_FENCE = 1U << 0` and `CLK_GLOBAL_MEM_FENCE = 1U << 1`, the bits Metal's + `mem_flags` read as `mem_device` (1) and `mem_threadgroup` (2). In the mode each + `air.wg.barrier`'s flags are read as OpenCL's, its call site's where the barrier is out of + line: `CLK_LOCAL_MEM_FENCE` orders threadgroup memory and `CLK_GLOBAL_MEM_FENCE` device memory. + A barrier whose flags set any other bit is refused (`Unsupported` with `UnknownIntrinsic`, + naming `air.wg.barrier`), as one whose flags fall outside Metal's `mem_flags` is. The header + declares no other barrier on these flags, so `air.simdgroup.barrier` and `air.atomic.fence` + (which `mem_fence` reaches with flags Apple's compiler converts itself) keep Metal's. 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)`). - Images in OpenCL mode. `get_image_channel_order(image)` and diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7dbffd69c..5704b4c04 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -68,7 +68,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 (each `byval` argument's copy made at its call first), function constants, SCCP (a value one of a few constants, from a PHI of literal constants or a `select` between two, folded member by member so a branch every member decides alike is decided; reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` and the scalar `llvm.umin`, `llvm.umax`, `llvm.smin` and `llvm.smax` on constants, settling the float operations a constant operand decides whatever the others hold (a NaN operand, the first in order: as it is beside a value the run computes, quieted where every operand is a constant; a product by a zero under `nnan` and `nsz`, `+0`), 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, the allocation of a private array of nested arrays as far as its indices reach where constants and counted loops bound every one of them (`canon::reach`), a pointer loaded from a constant table at an index only the run knows (a table of constexpr samplers) read as the `select` chain over the table's elements (`canon::const_tables`), each of MSL 4.1's generic pointers made a pointer of the one address space every pointer it may hold comes from, its space queries answered (`canon::generic`), devirtualization, linking, the load of a stack allocation's field that one dominating store wrote read as the stored value (an aggregate holding a pointer excepted), and an allocation no read is left of removed with its stores, so a lambda's closure of captured addresses leaves the captured objects' own (`canon::forward`), 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, OpenCL C's work-item reads made reads of their built-ins or of the first buffer, each image format query a read of the third, and each operation of a 1D image the 2D texture's that Apple's OpenCL binds for it, `canon::opencl` and `canon::opencl_1d`; and OpenCL C's vector data loads and stores made their element accesses, `canon::vector_data`). 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 (each `byval` argument's copy made at its call first), function constants, SCCP (a value one of a few constants, from a PHI of literal constants or a `select` between two, folded member by member so a branch every member decides alike is decided; reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` and the scalar `llvm.umin`, `llvm.umax`, `llvm.smin` and `llvm.smax` on constants, settling the float operations a constant operand decides whatever the others hold (a NaN operand, the first in order: as it is beside a value the run computes, quieted where every operand is a constant; a product by a zero under `nnan` and `nsz`, `+0`), 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, the allocation of a private array of nested arrays as far as its indices reach where constants and counted loops bound every one of them (`canon::reach`), a pointer loaded from a constant table at an index only the run knows (a table of constexpr samplers) read as the `select` chain over the table's elements (`canon::const_tables`), each of MSL 4.1's generic pointers made a pointer of the one address space every pointer it may hold comes from, its space queries answered (`canon::generic`), devirtualization, linking, the load of a stack allocation's field that one dominating store wrote read as the stored value (an aggregate holding a pointer excepted), and an allocation no read is left of removed with its stores, so a lambda's closure of captured addresses leaves the captured objects' own (`canon::forward`), 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, OpenCL C's work-item reads made reads of their built-ins or of the first buffer, each image format query a read of the third, each `air.wg.barrier`'s flags read as OpenCL C's `cl_mem_fence_flags`, and each operation of a 1D image the 2D texture's that Apple's OpenCL binds for it, `canon::opencl` and `canon::opencl_1d`; and OpenCL C's vector data loads and stores made their element accesses, `canon::vector_data`). 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; `memory::views`, a descriptor slot's views: a storage block or a uniform block |