From 7f837c636d45fac55b9a2f020010eec39a3c0f7a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 11 Nov 2026 06:40:10 -0800 Subject: [PATCH] OpenCL C's native_/half_ functions and vector data loads and stores Apple's OpenCL compiler spells OpenCL C's native_ and half_ of float types air.native_. and air.half_., and vload, vstore, vload_half[], vloada_half, vstore_half[][_] and vstorea_half[_] air.vload[a][_half].. and air.vstore[a][_half].[.].. None decoded, so pipelines of real OpenCL workloads were refused as UnknownIntrinsic (air.native_powr.v4f32, air.vload.global.v3i32, air.vstore_half.global.rtz.f32). - The math family reads native_ and half_ of the twelve stems Apple spells (cos, exp, exp10, exp2, log, log10, log2, powr, rsqrt, sin, sqrt, tan), f32 scalar and every vector width, as the function at Precision::Fast. Metal's devices answer native_powr apart (powr(100, 0.5): 0x1.400002p+3 on the M3 Max, 0x1.4p+3 on the 5300M), so it is the device's fast form. - A new family, AirIntrinsic::VectorData (VectorData, VectorDataOp, HalfRounding), decodes every address space and element type the compiler spells. canon::vector_data makes each call its element accesses before SCCP: lane i at element offset * stride + i, at the element's own alignment (stride 4 for vloada_half3 / vstorea_half3), a half widened by fpext or narrowed by fptrunc. - vstore_half's rounding suffixes store as the device converts (nearest even): the 5300M and the UHD 630 store every suffix as _rte, word for word over 32 values, where the M3 Max honours them; agreed with main. docs/API.md records the row beside the convert entry. Measured with an OpenCL-mode probe (owned kernels): vload3(i, g + 1) of uint reads the 3 words that follow on the M3 Max, the 5300M and the 630; vloada_half3 / vstorea_half3 step 4 halves, vload_half3 3, on the M3. Public surface (api_signatures.tsv blessed): AirIntrinsic gains VectorData; Query gains ChannelOrder and ChannelDataType (previous commit); new types VectorData, VectorDataOp, HalfRounding. An exhaustive match over AirIntrinsic or Query in a consumer breaks. Tests: intrinsics decode tests for both grammars (and their refusals), observed declarations, canon::tests::vector_data (element accesses at folded indices), runtime device tests in OpenCL mode (tests::opencl_data: vload3 past an unaligned pointer, uchar3/short2 at odd elements, half3 strides, vstore_half's suffixes, native_powr). SEMANTICS_VERSION stays 2030 (this branch's bump). --- crates/metal2vulkan-air/src/canon/mod.rs | 8 +- crates/metal2vulkan-air/src/canon/opencl.rs | 1 - crates/metal2vulkan-air/src/canon/tests.rs | 1 + .../src/canon/tests/vector_data.rs | 164 +++++++ .../metal2vulkan-air/src/canon/vector_data.rs | 263 ++++++++++++ .../src/intrinsics/families_tests.rs | 25 ++ .../metal2vulkan-air/src/intrinsics/math.rs | 42 +- crates/metal2vulkan-air/src/intrinsics/mod.rs | 10 +- .../metal2vulkan-air/src/intrinsics/tests.rs | 178 ++++++++ .../src/intrinsics/vector_data.rs | 167 +++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/opencl_data.rs | 406 ++++++++++++++++++ .../src/tests/opencl_mode.rs | 8 +- crates/metal2vulkan/src/lower/select.rs | 4 + .../src/pipeline/compile/partition.rs | 1 + crates/metal2vulkan/src/reflection/live.rs | 1 + crates/metal2vulkan/tests/api_signatures.tsv | 21 + docs/API.md | 39 ++ docs/ARCHITECTURE.md | 2 +- 19 files changed, 1328 insertions(+), 15 deletions(-) create mode 100644 crates/metal2vulkan-air/src/canon/tests/vector_data.rs create mode 100644 crates/metal2vulkan-air/src/canon/vector_data.rs create mode 100644 crates/metal2vulkan-air/src/intrinsics/vector_data.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/opencl_data.rs diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index a4ed4b78e..d57e47963 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -40,8 +40,9 @@ //! constant that survives is `Error::NeedsInput(FunctionConstant)`. **Unrolling**: a loop whose //! trip count SCCP made constant, and whose counter decides a branch of its body, is unrolled //! within fixed ceilings, and SCCP runs again over the copies; the result is kept where it is -//! no larger than the loops it replaces (`unroll`). Before SCCP, in OpenCL mode, each operation -//! of a 1D image becomes the 2D texture's that Apple's OpenCL binds for it (`opencl_1d`). +//! no larger than the loops it replaces (`unroll`). 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`). //! 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 @@ -126,6 +127,7 @@ mod table_copy; #[cfg(test)] mod tests; mod unroll; +mod vector_data; use std::collections::{BTreeMap, BTreeSet, HashMap}; @@ -612,6 +614,8 @@ pub fn specialize_dynamic( let body = async_copy::expand(body, &mut parts, ep, m)?; // Metal 4.1's block reads are the reads of their texels. let body = block_read::expand(body, &mut parts, ep.func, m)?; + // OpenCL C's vector data loads and stores are their element accesses. + let body = vector_data::expand(body, &mut parts, ep.func, m)?; // OpenCL mode: a 1D image's operations are the 2D texture's that Apple's OpenCL binds for it. let body = if req.open_cl_mode && matches!(ep.stage, Stage::Kernel { .. }) { opencl_1d::expand(body, &mut parts, ep.func, m)? diff --git a/crates/metal2vulkan-air/src/canon/opencl.rs b/crates/metal2vulkan-air/src/canon/opencl.rs index 431107348..d4dfc4e06 100644 --- a/crates/metal2vulkan-air/src/canon/opencl.rs +++ b/crates/metal2vulkan-air/src/canon/opencl.rs @@ -23,7 +23,6 @@ //! 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. -//! //! - **Image formats.** `get_image_channel_order(image)` is `air.get_channel_order_texture_` //! and `get_image_channel_data_type(image)` `air.get_channel_data_type_texture_` //! ([`Query::ChannelOrder`], [`Query::ChannelDataType`]), each of the image argument. The third diff --git a/crates/metal2vulkan-air/src/canon/tests.rs b/crates/metal2vulkan-air/src/canon/tests.rs index 74bce3a52..8ff4a4397 100644 --- a/crates/metal2vulkan-air/src/canon/tests.rs +++ b/crates/metal2vulkan-air/src/canon/tests.rs @@ -32,6 +32,7 @@ mod texture_writes; mod unbound_immediates; mod unobserved; mod unrolling; +mod vector_data; fn meter() -> Meter { Meter::new(&Budget::default()) diff --git a/crates/metal2vulkan-air/src/canon/tests/vector_data.rs b/crates/metal2vulkan-air/src/canon/tests/vector_data.rs new file mode 100644 index 000000000..11dd02fd8 --- /dev/null +++ b/crates/metal2vulkan-air/src/canon/tests/vector_data.rs @@ -0,0 +1,164 @@ +//! OpenCL C's vector data functions (`air.vload*`, `air.vstore*`) become their element accesses: +//! lane `i` at element `offset * stride + i` of the data, a `half` widened or narrowed for the +//! `half` forms. The module is LLVM text written here, assembled with `llvm-as`; a run without it +//! skips. + +use super::*; + +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"; + +/// `@vd(device const uint *g, device half *h, device uint *o, threadgroup char *t)` at constant +/// offsets: `vload3(5, g)` stored by `vstore3(_, 1, o)`; `vload_half3(2, h) + vloada_half3(2, h)` +/// stored by `vstorea_half3_rtz(_, 3, h)`; `vload_half(7, h) + 1` stored by `vstore_half_rtp(_, 20, +/// h)`; a `char2` through `vstore2(vload2(1, t), 4, t)`. +const KERNEL: &str = "define void @vd(ptr addrspace(1) %g, ptr addrspace(1) %h, ptr addrspace(1) %o, ptr addrspace(3) %t) #0 {\n\ + %a = tail call <3 x i32> @air.vload.global.v3i32(i64 5, ptr addrspace(1) %g) #1\n\ + tail call void @air.vstore.global.v3i32(<3 x i32> %a, i64 1, ptr addrspace(1) %o) #2\n\ + %b = tail call <3 x float> @air.vload_half.global.v3f32(i64 2, ptr addrspace(1) %h) #1\n\ + %c = tail call <3 x float> @air.vloada_half.global.v3f32(i64 2, ptr addrspace(1) %h) #1\n\ + %s = fadd <3 x float> %b, %c\n\ + tail call void @air.vstorea_half.global.rtz.v3f32(<3 x float> %s, i64 3, ptr addrspace(1) %h) #2\n\ + %x = tail call float @air.vload_half.global.f32(i64 7, ptr addrspace(1) %h) #1\n\ + %x1 = fadd float %x, 1.0\n\ + tail call void @air.vstore_half.global.rtp.f32(float %x1, i64 20, ptr addrspace(1) %h) #2\n\ + %y = tail call <2 x i8> @air.vload.local.v2i8(i64 1, ptr addrspace(3) %t) #1\n\ + tail call void @air.vstore.local.v2i8(<2 x i8> %y, i64 4, ptr addrspace(3) %t) #2\n\ + ret void\n}\n\ +declare <3 x i32> @air.vload.global.v3i32(i64, ptr addrspace(1)) #1\n\ +declare void @air.vstore.global.v3i32(<3 x i32>, i64, ptr addrspace(1)) #2\n\ +declare <3 x float> @air.vload_half.global.v3f32(i64, ptr addrspace(1)) #1\n\ +declare <3 x float> @air.vloada_half.global.v3f32(i64, ptr addrspace(1)) #1\n\ +declare void @air.vstorea_half.global.rtz.v3f32(<3 x float>, i64, ptr addrspace(1)) #2\n\ +declare float @air.vload_half.global.f32(i64, ptr addrspace(1)) #1\n\ +declare void @air.vstore_half.global.rtp.f32(float, i64, ptr addrspace(1)) #2\n\ +declare <2 x i8> @air.vload.local.v2i8(i64, ptr addrspace(3)) #1\n\ +declare void @air.vstore.local.v2i8(<2 x i8>, i64, ptr addrspace(3)) #2\n\ +attributes #0 = { nounwind }\n\ +attributes #1 = { nounwind willreturn memory(argmem: read) }\n\ +attributes #2 = { nounwind willreturn memory(argmem: write) }\n\ +!air.kernel = !{!0}\n\ +!air.version = !{!7}\n\ +!air.language_version = !{!8}\n\ +!0 = !{ptr @vd, !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\", !\"uint\", !\"air.arg_name\", !\"g\"}\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 2, !\"air.arg_type_align_size\", i32 2, !\"air.arg_type_name\", !\"half\", !\"air.arg_name\", !\"h\"}\n\ +!5 = !{i32 2, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"o\"}\n\ +!6 = !{i32 3, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 3, !\"air.arg_type_size\", i32 1, !\"air.arg_type_align_size\", i32 1, !\"air.arg_type_name\", !\"char\", !\"air.arg_name\", !\"t\"}\n\ +!7 = !{i32 2, i32 9, i32 0}\n\ +!8 = !{!\"Metal\", i32 1, i32 1, i32 0}\n"; + +/// The type of an access's element, as a token. +fn element(ty: Option<&Type>) -> &'static str { + match ty { + Some(Type::Int(8)) => "i8", + Some(Type::Int(32)) => "i32", + Some(Type::Half) => "half", + other => panic!("{other:?}"), + } +} + +#[test] +fn opencl_vector_data_functions_become_their_element_accesses() { + let test = "opencl_vector_data_functions_become_their_element_accesses"; + let bitcode = match metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{KERNEL}")) { + Ok(b) => b, + Err(e) => { + eprintln!("SKIP {test}: {e:?}"); + return; + } + }; + let d = crate::bitcode::decode(&bitcode, &mut meter()).expect("decoded"); + let req = SpecRequest { + entry: "vd".into(), + ..SpecRequest::default() + }; + let e = specialize(d.module, &d.abi, &req, &mut meter()).expect("specialized"); + let body = e + .module + .func(e.func) + .and_then(|f| f.body.as_ref()) + .expect("the entry's body"); + let consts = e.module.consts(); + let types = e.module.types(); + // Each access as (store, parameter, element, index): its pointer a GEP of the element from + // a parameter at a folded constant index. + let at = |ptr: Value| -> (usize, &'static str, u64) { + let Value::Inst(id) = ptr else { + panic!("{ptr:?}"); + }; + match body.insts.get(id).map(|i| &i.kind) { + Some(InstKind::Gep { + src_ty, + base: Value::Arg(a), + indices, + .. + }) => match indices.as_ref() { + [Value::Const(c)] => match consts.get(*c).map(|k| &k.value) { + Some(Const::Int(i)) => (a.index(), element(types.get(*src_ty)), *i), + other => panic!("{other:?}"), + }, + other => panic!("{other:?}\n{}", print(&e.module)), + }, + other => panic!("{other:?}\n{}", print(&e.module)), + } + }; + let mut accesses = Vec::new(); + let (mut widened, mut narrowed) = (0, 0); + for inst in body.insts.values() { + match &inst.kind { + InstKind::Load { ptr, align, .. } => { + accesses.push((false, at(*ptr), align.map(Align::bytes))); + } + InstKind::Store { ptr, align, .. } => { + accesses.push((true, at(*ptr), align.map(Align::bytes))); + } + InstKind::Cast { + op: CastOp::FPExt, .. + } => widened += 1, + InstKind::Cast { + op: CastOp::FPTrunc, + .. + } => narrowed += 1, + InstKind::Call(c) => assert!( + !matches!( + c.callee, + Callee::Air { + op: AirIntrinsic::VectorData(_), + .. + } + ), + "{}", + print(&e.module) + ), + _ => {} + } + } + accesses.sort(); + let (load, store) = (false, true); + #[rustfmt::skip] + let expected = vec![ + // `vload3(5, g)`: `uint`s 15, 16 and 17, each at its own alignment. + (load, (0, "i32", 15), Some(4)), (load, (0, "i32", 16), Some(4)), (load, (0, "i32", 17), Some(4)), + // `vload_half3(2, h)`: halves 6, 7 and 8; `vloada_half3(2, h)`: 8, 9 and 10 (a stride of + // 4); `vload_half(7, h)`: half 7. + (load, (1, "half", 6), Some(2)), (load, (1, "half", 7), Some(2)), (load, (1, "half", 7), Some(2)), + (load, (1, "half", 8), Some(2)), (load, (1, "half", 8), Some(2)), (load, (1, "half", 9), Some(2)), + (load, (1, "half", 10), Some(2)), + // `vload2(1, t)`: `char`s 2 and 3. + (load, (3, "i8", 2), Some(1)), (load, (3, "i8", 3), Some(1)), + // `vstorea_half3_rtz(_, 3, h)`: halves 12, 13 and 14; `vstore_half_rtp(_, 20, h)`: 20. + (store, (1, "half", 12), Some(2)), (store, (1, "half", 13), Some(2)), (store, (1, "half", 14), Some(2)), + (store, (1, "half", 20), Some(2)), + // `vstore3(_, 1, o)`: `uint`s 3, 4 and 5. + (store, (2, "i32", 3), Some(4)), (store, (2, "i32", 4), Some(4)), (store, (2, "i32", 5), Some(4)), + // `vstore2(_, 4, t)`: `char`s 8 and 9. + (store, (3, "i8", 8), Some(1)), (store, (3, "i8", 9), Some(1)), + ]; + assert_eq!(accesses, expected, "{}", print(&e.module)); + // Seven halves read are widened, four stored narrowed: the device's conversion for every + // rounding the names spell. + assert_eq!((widened, narrowed), (7, 4), "{}", print(&e.module)); +} diff --git a/crates/metal2vulkan-air/src/canon/vector_data.rs b/crates/metal2vulkan-air/src/canon/vector_data.rs new file mode 100644 index 000000000..f41021f0f --- /dev/null +++ b/crates/metal2vulkan-air/src/canon/vector_data.rs @@ -0,0 +1,263 @@ +//! OpenCL C's vector data functions as their element accesses. +//! +//! `vload`, `vstore`, `vload_half[]`, `vloada_half`, `vstore_half[][_]` +//! and `vstorea_half[_]` reach AIR as calls of [`VectorData`] intrinsics. [`expand`] +//! makes each call a call of a function built here, and inlines it: lane `i` of the value is +//! element `offset * s + i` of the data `p` points at, `s` the function's stride +//! ([`VectorData::stride`]: `n`, but 4 for the aligned `half3` forms), read or written as the +//! data's own element: a `half` for the `half` forms, widened to `float` by a load and narrowed to +//! `half` by a store. An access asks no more alignment than its element's. +//! +//! **Measured** on an M3 Max (macOS 27.0.1), a Radeon Pro 5300M and a UHD Graphics 630 (macOS +//! 26.7.1), in OpenCL mode: +//! +//! - `vload3` of a `uint` pointer one element past a buffer's start reads the three elements that +//! follow it at each offset (no 16-byte alignment), and `vstore3` writes three; +//! - a store narrows each lane to `half` as the device converts, whatever rounding the name spells: +//! the Radeon Pro 5300M and the UHD Graphics 630 store each of `vstore_half_rtz`, `_rtp` and +//! `_rtn` (and their `vstore_half4` forms) as `vstore_half_rte`, word for word over 32 values +//! among them ties, overflows past the largest `half`, subnormals and zeros, where the M3 Max +//! rounds as named. What no Mac guarantees is no part of the store. + +use crate::budget::Meter; +use crate::error::Error; +use crate::intrinsics::{AirIntrinsic, Elem, VectorData}; +use crate::ir::{ + ArgIdx, BinOp, Body, CallConv, Callee, CastOp, Const, FnAttrs, FuncId, Function, InstId, + InstKind, Linkage, ModuleParts, Param, ParamAttrs, Type, TypeId, UnnamedAddr, Value, + Visibility, +}; + +use super::inline; +use super::out::Out; +use super::rewrite::invariant; + +/// The vector data function `kind` calls, with its declaration. +fn site(kind: &InstKind) -> Option<(VectorData, FuncId)> { + let InstKind::Call(call) = kind else { + return None; + }; + match call.callee { + Callee::Air { + decl, + op: AirIntrinsic::VectorData(v), + } => Some((v, decl)), + _ => None, + } +} + +/// Whether `parts` declares a vector data function. Every site calls one, so a module that +/// declares none has none, and [`expand`] need not read its instructions. +fn declares_sites(parts: &ModuleParts, m: &mut Meter) -> Result { + for f in parts.funcs.values() { + m.tick(1)?; + if f.body.is_some() { + continue; + } + let air = parts + .symbols + .get(f.name) + .and_then(|n| std::str::from_utf8(n).ok()) + .and_then(AirIntrinsic::parse); + if matches!(air, Some(AirIntrinsic::VectorData(_))) { + return Ok(true); + } + } + Ok(false) +} + +/// Make each vector data call of the entry `func`'s inlined `body` a call of a function built for +/// it, and inline the result. +pub(super) fn expand( + body: Body, + parts: &mut ModuleParts, + func: FuncId, + m: &mut Meter, +) -> Result { + if !declares_sites(parts, m)? { + return Ok(body); + } + // One function per operation and declaration, and each call's. + let mut made: Vec<((VectorData, FuncId), FuncId)> = Vec::new(); + let mut calls: Vec<(InstId, FuncId)> = Vec::new(); + for (id, inst) in body.insts.iter() { + m.tick(1)?; + let Some(key) = site(&inst.kind) else { + continue; + }; + let f = match made.iter().find(|(k, _)| *k == key) { + Some(&(_, f)) => f, + None => { + let f = function(parts, key, m)?; + m.reserve(&mut made, 1)?; + made.push((key, f)); + f + } + }; + m.reserve(&mut calls, 1)?; + calls.push((id, f)); + } + m.release(made.capacity() * std::mem::size_of::<((VectorData, FuncId), FuncId)>()); + drop(made); + if calls.is_empty() { + m.release(calls.capacity() * std::mem::size_of::<(InstId, FuncId)>()); + return Ok(body); + } + inline::inline_calls( + body, + parts, + func, + calls, + "an expanded vector data function was not inlined", + m, + ) +} + +/// The IR type of an element `e` of vector data. +fn element(e: Elem) -> Result { + Ok(match e { + Elem::I8 | Elem::I16 | Elem::I32 | Elem::I64 => { + Type::Int(u8::try_from(e.bits()).map_err(|_| invariant("an element's width"))?) + } + Elem::F16 => Type::Half, + Elem::F32 => Type::Float, + _ => return Err(invariant("a vector data element")), + }) +} + +/// The function of vector data function `v` declared by `decl`, whose parameters are the call's +/// operands: its element accesses (module doc). +fn function( + parts: &mut ModuleParts, + (v, decl): (VectorData, FuncId), + m: &mut Meter, +) -> Result { + let ty = parts + .funcs + .get(decl) + .map(|f| f.ty) + .ok_or_else(|| invariant("a declaration out of range"))?; + let (ret, params): (TypeId, Vec) = match parts.types.get(ty) { + Some(Type::Function { + ret, + params, + vararg: false, + }) => (*ret, params.to_vec()), + _ => return Err(invariant("a vector data function is not a function")), + }; + let arg = |i: u32| Value::Arg(ArgIdx::new(i)); + // A store's value comes first; then the offset and the pointer. + let (value, offset, p) = if v.stores() { + (Some(arg(0)), arg(1), arg(2)) + } else { + (None, arg(0), arg(1)) + }; + let value_ty = match value { + Some(_) => *params + .first() + .ok_or_else(|| invariant("a vector data store's parameters"))?, + None => ret, + }; + let lanes = v.ty.lanes; + let widened = v.data() != v.ty.elem; + let bytes = u64::from(v.data().bits() / 8); + let mut out = Out::new(parts); + out.open(None)?; + let lane_ty = out.ty(element(v.ty.elem)?, m)?; + let data_ty = out.ty(element(v.data())?, m)?; + let i64t = out.int_ty(64, m)?; + let ptr_ty = out.ptr_ty(v.space, m)?; + let stride = out.k64(u64::from(v.stride()), m)?; + let first = out.bin(i64t, BinOp::Mul, offset, stride, m)?; + let mut loaded = match lanes { + 1 => None, + _ => Some(out.constant(value_ty, Const::Undef, m)?), + }; + for i in 0..lanes { + let index = match i { + 0 => first, + _ => { + let k = out.k64(u64::from(i), m)?; + out.bin(i64t, BinOp::Add, first, k, m)? + } + }; + let at = out.push( + ptr_ty, + InstKind::Gep { + src_ty: data_ty, + base: p, + indices: Box::new([index]), + inbounds: false, + }, + m, + )?; + let lane = out.k32(i, m)?; + match value { + Some(value) => { + let x = match lanes { + 1 => value, + _ => out.push( + lane_ty, + InstKind::ExtractElement { + vec: value, + idx: lane, + }, + m, + )?, + }; + let x = if widened { + out.cast(CastOp::FPTrunc, x, data_ty, m)? + } else { + x + }; + out.store(x, at, bytes, m)?; + } + None => { + let x = out.load(data_ty, at, bytes, m)?; + let x = if widened { + out.cast(CastOp::FPExt, x, lane_ty, m)? + } else { + x + }; + loaded = Some(match loaded { + Some(vec) => out.push( + value_ty, + InstKind::InsertElement { + vec, + elt: x, + idx: lane, + }, + m, + )?, + None => x, + }); + } + } + } + let result = match value { + Some(_) => None, + None => Some(loaded.ok_or_else(|| invariant("a vector data load of no lane"))?), + }; + out.ret(result, m)?; + let Out { body, parts, .. } = out; + let name = format!("__m2v.vector_data.{}", parts.funcs.len()); + let name = parts.symbols.intern(name.as_bytes(), m)?; + let mut ps = Vec::new(); + m.reserve(&mut ps, params.len())?; + ps.resize(params.len(), Param::default()); + let f = Function { + name, + ty, + linkage: Linkage::Internal, + visibility: Visibility::Default, + unnamed_addr: UnnamedAddr::Significant, + cconv: CallConv::C, + attrs: FnAttrs::default(), + ret_attrs: ParamAttrs::default(), + params: ps.into_boxed_slice(), + body: Some(body), + section: None, + align: None, + }; + parts.funcs.push(f, m) +} diff --git a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs index 06f500d1b..ce7ac9280 100644 --- a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs +++ b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs @@ -768,6 +768,31 @@ const OBSERVED: &[(&str, &str)] = &[ // 27.0.1). ("air.get_global_offset.i32", "i32 (i32)"), ("air.get_work_dim.i32", "i32 ()"), + // OpenCL C's `native_` and `half_` (Apple's OpenCL compiler, macOS 27.0.1 + // and 26.7.1). + ("air.native_powr.v4f32", "v4f32 (v4f32, v4f32)"), + ("air.native_powr.f32", "f32 (f32, f32)"), + ("air.native_sqrt.v16f32", "v16f32 (v16f32)"), + ("air.native_exp10.v3f32", "v3f32 (v3f32)"), + ("air.half_cos.v4f32", "v4f32 (v4f32)"), + ("air.half_powr.v4f32", "v4f32 (v4f32, v4f32)"), + // OpenCL C's vector data functions (the same compilers). + ("air.vload.global.v3i32", "v3i32 (i64, p1)"), + ("air.vload.constant.v16i8", "v16i8 (i64, p2)"), + ("air.vload.local.v2i64", "v2i64 (i64, p3)"), + ("air.vload.private.v3f32", "v3f32 (i64, p0)"), + ("air.vstore.global.v3i32", "void (v3i32, i64, p1)"), + ("air.vstore.private.v16i8", "void (v16i8, i64, p0)"), + ("air.vload_half.constant.f32", "f32 (i64, p2)"), + ("air.vload_half.global.v16f32", "v16f32 (i64, p1)"), + ("air.vloada_half.global.v3f32", "v3f32 (i64, p1)"), + ("air.vstore_half.global.rtz.f32", "void (f32, i64, p1)"), + ("air.vstore_half.local.rte.v4f32", "void (v4f32, i64, p3)"), + ( + "air.vstore_half.global.rtn.v16f32", + "void (v16f32, i64, p1)", + ), + ("air.vstorea_half.global.rtp.v3f32", "void (v3f32, i64, p1)"), // Simdgroup matrices. ( "air.simdgroup_matrix_8x8_load.v64f32.p3f32", diff --git a/crates/metal2vulkan-air/src/intrinsics/math.rs b/crates/metal2vulkan-air/src/intrinsics/math.rs index e05d7c1e6..53998d2df 100644 --- a/crates/metal2vulkan-air/src/intrinsics/math.rs +++ b/crates/metal2vulkan-air/src/intrinsics/math.rs @@ -1,4 +1,5 @@ -//! The math family: `air.[fast_][.].`. +//! The math family: `air.[fast_][.].`, and OpenCL C's +//! `air.{native,half}_.`. //! //! One declarative table ([`TABLE`]) lists every function stem with its domain and operand //! shape. A float function takes an optional `fast_` prefix and no sign token; a sign-sensitive @@ -6,6 +7,14 @@ //! same stem may name a float and an integer function (`min`, `max`, `clamp`): the sign token //! decides, and the type token must agree with the domain. //! +//! Apple's OpenCL compiler spells OpenCL C's `native_` and `half_` of a +//! `float` scalar or vector `air.native_.` and `air.half_.`, for the stems +//! [`OPENCL_STEMS`] lists (it spells `native_divide`, `native_recip`, `half_divide` and +//! `half_recip` as plain arithmetic). OpenCL C leaves their precision to the implementation, and +//! Metal's differ by device: `native_powr(100, 0.5)` answers `0x1.400002p+3` on an M3 Max (macOS +//! 27.0.1) and `0x1.4p+3` on a Radeon Pro 5300M (macOS 26.7.1). Each reads as the function at +//! [`Precision::Fast`], the device's fast form. +//! //! Two functions reach AIR as calls to Metal runtime routines instead, declarations Apple's //! compiler emits and its backend defines at pipeline creation: `frexp` as //! `___metal_frexp__pthread(T, thread I*)` (AIR 2.9 spells the same operation @@ -21,15 +30,24 @@ use super::ty::{Elem, NumTy, Sign}; use crate::error::IntrinsicError; use crate::ir::AddrSpace; -/// Whether a float function was spelled with the `fast_` prefix. +/// Whether a float function was spelled with the `fast_` prefix (or OpenCL C's `native_` or +/// `half_`). #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Precision { - /// Spelled without `fast_`; always so for integer functions and the runtime routines. + /// Spelled without a prefix; always so for integer functions and the runtime routines. Precise, - /// Spelled `air.fast_`: Metal's fast-math form. + /// Spelled `air.fast_`: Metal's fast-math form; or `air.native_` or + /// `air.half_`: OpenCL C's functions of the implementation's precision, read as that form + /// (module doc). Fast, } +/// The stems Apple's OpenCL compiler spells with the `native_` and `half_` prefixes, on `float` +/// types only: OpenCL C's `native_` and `half_` but `divide` and `recip`. +pub(super) const OPENCL_STEMS: &[&str] = &[ + "cos", "exp", "exp10", "exp2", "log", "log10", "log2", "powr", "rsqrt", "sin", "sqrt", "tan", +]; + /// A math function. Integer functions whose result depends on signedness carry the [`Sign`] the /// name spells; `Clz`/`Ctz` carry their `is_zero_undef` immediate. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -330,9 +348,21 @@ pub(super) const TABLE: &[(&str, Domain, Shape)] = { }; impl Math { - /// Parse the part of a name after `air.`: `[fast_]stem.[s|u.]type`. `None` is not a math - /// name (another family's, or an unknown one). + /// Parse the part of a name after `air.`: `[fast_]stem.[s|u.]type`, or + /// `{native,half}_stem.type` of a stem [`OPENCL_STEMS`] lists and a `float` type. `None` is not + /// a math name (another family's, or an unknown one). pub(super) fn parse(rest: &str) -> Option { + let opencl = ["native_", "half_"] + .iter() + .find_map(|p| rest.strip_prefix(p)); + if let Some(r) = opencl { + let (stem, ty) = r.split_once('.')?; + let float = NumTy::parse(ty).is_some_and(|t| t.elem == Elem::F32); + if !(OPENCL_STEMS.contains(&stem) && float) { + return None; + } + return Math::parse(&format!("fast_{r}")); + } let (fast, rest) = match rest.strip_prefix("fast_") { Some(r) => (true, r), None => (false, rest), diff --git a/crates/metal2vulkan-air/src/intrinsics/mod.rs b/crates/metal2vulkan-air/src/intrinsics/mod.rs index 40d8ed3b4..c2bcd3f10 100644 --- a/crates/metal2vulkan-air/src/intrinsics/mod.rs +++ b/crates/metal2vulkan-air/src/intrinsics/mod.rs @@ -27,7 +27,8 @@ //! atomics and coherent accesses, derivatives, textures and samplers, barriers and fences, //! simdgroup and quad operations, simdgroup matrices, function constants, fragment operations, //! pull-model interpolation, imageblocks, async copies, function tables, acceleration-structure -//! queries, ray intersection (`air.intersect`), tensor descriptors, indirect commands, and the +//! queries, ray intersection (`air.intersect`), tensor descriptors, indirect commands, OpenCL C's +//! vector data loads and stores, and the //! closed `llvm.*` set with the AGX family. Every other `air.*` name (names whose declarations have not been observed) stays //! unknown. [`UNDECODED`] lists the known families among them, and the intrinsic census of the //! `bitcode-reader` audit reports every unknown name with row counts. [`UNDECODED_FEATURES`] names @@ -49,6 +50,7 @@ mod stage; mod sync; mod texture; mod ty; +mod vector_data; #[cfg(test)] mod families_tests; @@ -84,6 +86,7 @@ pub use texture::{Access, Form}; pub use texture::{Component, LodMode, Query, SamplerOp, TexOp, TexRole, Texture}; pub use ty::NumTy; pub use ty::{Elem, Sign}; +pub use vector_data::{HalfRounding, VectorData, VectorDataOp}; use crate::error::Feature; use crate::error::IntrinsicError; @@ -150,6 +153,9 @@ pub enum AirIntrinsic { IndirectCommand(IndirectCommand), /// An object or mesh function's operation. Mesh(Mesh), + /// OpenCL C's vector data loads and stores: `air.vload[a][_half]..` and + /// `air.vstore[a][_half].[.].`. + VectorData(VectorData), } impl AirIntrinsic { @@ -206,6 +212,7 @@ impl AirIntrinsic { .or_else(|| Tensor::parse(rest).map(A::Tensor)) .or_else(|| IndirectCommand::parse(rest).map(A::IndirectCommand)) .or_else(|| Mesh::parse(rest).map(A::Mesh)) + .or_else(|| VectorData::parse(rest).map(A::VectorData)) .or_else(|| Math::parse(rest).map(A::Math)) } @@ -255,6 +262,7 @@ impl AirIntrinsic { AirIntrinsic::Tensor(t) => t.signature(), AirIntrinsic::IndirectCommand(c) => c.signature(), AirIntrinsic::Mesh(m) => m.signature(), + AirIntrinsic::VectorData(v) => v.signature(), } } diff --git a/crates/metal2vulkan-air/src/intrinsics/tests.rs b/crates/metal2vulkan-air/src/intrinsics/tests.rs index 8595c22cc..6a034ed67 100644 --- a/crates/metal2vulkan-air/src/intrinsics/tests.rs +++ b/crates/metal2vulkan-air/src/intrinsics/tests.rs @@ -1141,3 +1141,181 @@ fn dropped_family_names_only_the_markers_decode_drops() { assert_eq!(dropped_family("llvm.assumed"), None); assert_eq!(dropped_family("air.lifetime.start"), None); } + +#[test] +fn opencl_native_and_half_functions_read_as_the_fast_form() { + let mut decoded = 0; + for prefix in ["native_", "half_"] { + for &stem in super::math::OPENCL_STEMS { + for lanes in [1, 2, 3, 4, 8, 16] { + let ty = token(NumTy { + elem: Elem::F32, + lanes, + }); + let name = format!("air.{prefix}{stem}.{ty}"); + let fast = air(&format!("air.fast_{stem}.{ty}")); + assert_eq!(air(&name), fast, "{name}"); + let AirIntrinsic::Math(m) = fast else { + panic!("{name}"); + }; + assert_eq!(m.precision, Precision::Fast, "{name}"); + decoded += 1; + } + } + } + assert_eq!(decoded, 144); + for name in [ + "air.native_divide.f32", // spelled as arithmetic + "air.half_recip.v4f32", // spelled as arithmetic + "air.native_fabs.f32", // no OpenCL C native_fabs + "air.native_cos.f16", // float types only + "air.half_powr.v2f16", // float types only + "air.native_fast_cos.f32", // one prefix + "air.native_cos.s.f32", // no sign token + "air.native_cos.f32.extra", // trailing token + ] { + assert_eq!(classify_self(name), DeclClass::Unknown, "{name}"); + } +} + +#[test] +fn opencl_vector_data_functions_decode_with_their_strides() { + use AddrSpace::{Constant as C, Device as G, Thread as P, Threadgroup as L}; + let v = |name: &str| match air(name) { + AirIntrinsic::VectorData(v) => v, + other => panic!("{name}: {other:?}"), + }; + let n = |elem, lanes| NumTy { elem, lanes }; + for (name, op, space, ty, stride) in [ + ( + "air.vload.global.v3i32", + VectorDataOp::Load, + G, + n(Elem::I32, 3), + 3, + ), + ( + "air.vload.constant.v16i8", + VectorDataOp::Load, + C, + n(Elem::I8, 16), + 16, + ), + ( + "air.vload.local.v2i64", + VectorDataOp::Load, + L, + n(Elem::I64, 2), + 2, + ), + ( + "air.vload.private.v8i16", + VectorDataOp::Load, + P, + n(Elem::I16, 8), + 8, + ), + ( + "air.vstore.global.v4f32", + VectorDataOp::Store, + G, + n(Elem::F32, 4), + 4, + ), + ( + "air.vload_half.constant.f32", + VectorDataOp::LoadHalf { aligned: false }, + C, + n(Elem::F32, 1), + 1, + ), + ( + "air.vload_half.global.v3f32", + VectorDataOp::LoadHalf { aligned: false }, + G, + n(Elem::F32, 3), + 3, + ), + ( + "air.vloada_half.global.v3f32", + VectorDataOp::LoadHalf { aligned: true }, + G, + n(Elem::F32, 3), + 4, + ), + ( + "air.vloada_half.local.v8f32", + VectorDataOp::LoadHalf { aligned: true }, + L, + n(Elem::F32, 8), + 8, + ), + ( + "air.vstore_half.global.rtz.f32", + VectorDataOp::StoreHalf { + aligned: false, + rounding: HalfRounding::Rtz, + }, + G, + n(Elem::F32, 1), + 1, + ), + ( + "air.vstore_half.private.rtp.v3f32", + VectorDataOp::StoreHalf { + aligned: false, + rounding: HalfRounding::Rtp, + }, + P, + n(Elem::F32, 3), + 3, + ), + ( + "air.vstorea_half.global.rtn.v3f32", + VectorDataOp::StoreHalf { + aligned: true, + rounding: HalfRounding::Rtn, + }, + G, + n(Elem::F32, 3), + 4, + ), + ( + "air.vstorea_half.local.rte.v16f32", + VectorDataOp::StoreHalf { + aligned: true, + rounding: HalfRounding::Rte, + }, + L, + n(Elem::F32, 16), + 16, + ), + ] { + let d = v(name); + assert_eq!( + (d.op, d.space, d.ty, d.stride()), + (op, space, ty, stride), + "{name}" + ); + let half = matches!( + op, + VectorDataOp::LoadHalf { .. } | VectorDataOp::StoreHalf { .. } + ); + assert_eq!(d.data(), if half { Elem::F16 } else { ty.elem }, "{name}"); + } + for name in [ + "air.vload.global.i32", // one lane is no vload + "air.vload.global.v5i32", // no such width + "air.vload.global.v4f16", // no half vload observed + "air.vstore.constant.v4i32", // no store to constant memory + "air.vload.device.v4i32", // OpenCL's space names + "air.vloada_half.global.f32", // vloada_half has vector forms only + "air.vload_half.global.v4i32", // half forms are of floats + "air.vstore_half.global.v4f32", // a rounding is spelled + "air.vstore_half.global.rtx.f32", // no such rounding + "air.vstore.global.v4i32.extra", // trailing token + "air.vload.global.rte.v4i32", // no rounding on a load + ] { + assert_eq!(classify_self(name), DeclClass::Unknown, "{name}"); + } +} diff --git a/crates/metal2vulkan-air/src/intrinsics/vector_data.rs b/crates/metal2vulkan-air/src/intrinsics/vector_data.rs new file mode 100644 index 000000000..5f25bbfa4 --- /dev/null +++ b/crates/metal2vulkan-air/src/intrinsics/vector_data.rs @@ -0,0 +1,167 @@ +//! OpenCL C's vector data functions, as Apple's OpenCL compiler spells them: +//! `air.vload..` and `air.vstore..` (`vload`, `vstore`), and over `half` +//! data `air.vload_half..`, `air.vloada_half..`, +//! `air.vstore_half...` and `air.vstorea_half...` +//! (`vload_half[]`, `vloada_half`, `vstore_half[][_]`, +//! `vstorea_half[_]`; the compiler spells a store without a rounding `rte`). +//! +//! A load is `T (i64 offset, ptr p)` and a store `void (T v, i64 offset, ptr p)`, `p` a pointer to +//! the data's elements in ``: `global` (device), `constant` (loads only), `local` +//! (threadgroup) or `private` (thread). `T` is `v` for `vload` and `vstore`, `E` one of `i8`, +//! `i16`, `i32`, `i64` and `f32` (OpenCL's signed and unsigned types alike) and `n` one of 2, 3, 4, +//! 8 and 16; it is `f32` or `vf32` for the `half` forms (`vf32` for `vloada_half` and +//! `vstorea_half`), whose data is `half`. Canonicalization makes each call its element accesses +//! (`canon::vector_data`). + +use super::sig::{Operand, Signature}; +use super::ty::{Elem, NumTy}; +use crate::ir::AddrSpace; + +/// The rounding a store to `half` data names. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum HalfRounding { + /// `rte`: to nearest, ties to even. + Rte, + /// `rtz`: toward zero. + Rtz, + /// `rtp`: toward positive infinity. + Rtp, + /// `rtn`: toward negative infinity. + Rtn, +} + +impl HalfRounding { + fn parse(token: &str) -> Option { + Some(match token { + "rte" => HalfRounding::Rte, + "rtz" => HalfRounding::Rtz, + "rtp" => HalfRounding::Rtp, + "rtn" => HalfRounding::Rtn, + _ => return None, + }) + } +} + +/// What a vector data function does. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum VectorDataOp { + /// `air.vload`: `T`'s elements from `p + offset * n`. + Load, + /// `air.vstore`: `v`'s elements to `p + offset * n`. + Store, + /// `air.vload_half` and (`aligned`) `air.vloada_half`: `T`'s lanes, each a `half` widened to + /// `float`, from `p + offset * n` (a `vloada_half3`'s from `p + offset * 4`). + LoadHalf { + /// `vloada_half`. + aligned: bool, + }, + /// `air.vstore_half` and (`aligned`) `air.vstorea_half`: `v`'s lanes, each narrowed to `half`, + /// to `p + offset * n` (a `vstorea_half3`'s to `p + offset * 4`). + StoreHalf { + /// `vstorea_half`. + aligned: bool, + /// The rounding the name spells. + rounding: HalfRounding, + }, +} + +/// A decoded vector data function. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct VectorData { + /// The operation. + pub op: VectorDataOp, + /// The data's address space, the name's ``. + pub space: AddrSpace, + /// The value type the name spells: the load's result, the store's value. + pub ty: NumTy, +} + +impl VectorData { + /// Parse the part of a name after `air.`. `None` is no vector data function. + pub(super) fn parse(rest: &str) -> Option { + let mut t = rest.split('.'); + let (head, space) = (t.next()?, t.next()?); + let load = head.starts_with("vload"); + let op = match head { + "vload" => VectorDataOp::Load, + "vstore" => VectorDataOp::Store, + "vload_half" | "vloada_half" => VectorDataOp::LoadHalf { + aligned: head == "vloada_half", + }, + "vstore_half" | "vstorea_half" => VectorDataOp::StoreHalf { + aligned: head == "vstorea_half", + rounding: HalfRounding::parse(t.next()?)?, + }, + _ => return None, + }; + let space = match space { + "global" => AddrSpace::Device, + "constant" if load => AddrSpace::Constant, + "local" => AddrSpace::Threadgroup, + "private" => AddrSpace::Thread, + _ => return None, + }; + let ty = NumTy::parse(t.next()?)?; + if t.next().is_some() || !matches!(ty.lanes, 1 | 2 | 3 | 4 | 8 | 16) { + return None; + } + let ok = match op { + VectorDataOp::Load | VectorDataOp::Store => { + ty.lanes > 1 + && matches!( + ty.elem, + Elem::I8 | Elem::I16 | Elem::I32 | Elem::I64 | Elem::F32 + ) + } + VectorDataOp::LoadHalf { aligned } | VectorDataOp::StoreHalf { aligned, .. } => { + ty.elem == Elem::F32 && !(aligned && ty.lanes == 1) + } + }; + ok.then_some(VectorData { op, space, ty }) + } + + /// `T (i64, ptr)` or `void (T, i64, ptr)`. + pub fn signature(&self) -> Signature { + let (t, offset, p) = ( + Operand::Num(self.ty), + Operand::Num(NumTy::scalar(Elem::I64)), + Operand::Ptr(self.space), + ); + match self.op { + VectorDataOp::Load | VectorDataOp::LoadHalf { .. } => Signature::new(t, &[offset, p]), + VectorDataOp::Store | VectorDataOp::StoreHalf { .. } => { + Signature::new(Operand::Void, &[t, offset, p]) + } + } + } + + /// The element the data holds: `half` for the `half` forms, else `T`'s. + pub fn data(&self) -> Elem { + match self.op { + VectorDataOp::Load | VectorDataOp::Store => self.ty.elem, + VectorDataOp::LoadHalf { .. } | VectorDataOp::StoreHalf { .. } => Elem::F16, + } + } + + /// The elements one step of `offset` moves `p`: `n`, but 4 for a `vloada_half3` or a + /// `vstorea_half3`. + pub fn stride(&self) -> u32 { + match self.op { + VectorDataOp::LoadHalf { aligned: true } + | VectorDataOp::StoreHalf { aligned: true, .. } + if self.ty.lanes == 3 => + { + 4 + } + _ => self.ty.lanes, + } + } + + /// Whether the function stores. + pub fn stores(&self) -> bool { + matches!( + self.op, + VectorDataOp::Store | VectorDataOp::StoreHalf { .. } + ) + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index de3964a6e..0eddabdbf 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -347,6 +347,8 @@ mod noted_apart; mod notice_command_buffers; mod numbered_samplers; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod opencl_data; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod opencl_images; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod opencl_kernels; diff --git a/crates/metal2vulkan-runtime/src/tests/opencl_data.rs b/crates/metal2vulkan-runtime/src/tests/opencl_data.rs new file mode 100644 index 000000000..0b05b64b1 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/opencl_data.rs @@ -0,0 +1,406 @@ +//! OpenCL C's vector data functions and `native_powr` in compute pipelines of OpenCL mode +//! (`ComputePipelineDescriptor::open_cl_mode_enabled`), each kernel in the shape Apple's OpenCL +//! compiler writes (`__entry_` calling the kernel; `vl3_odd` calls the intrinsics through +//! the internal wrappers the compiler writes, the others call them directly), run with the hidden +//! buffers bound as Metal's OpenCL dispatcher binds them, and compared with what an M3 Max (macOS +//! 27.0.1), a Radeon Pro 5300M and a UHD Graphics 630 (macOS 26.7.1) compute for kernels of the +//! same shapes over the same data: +//! +//! - **vl3_odd**: `vstore3(vload3(i, g + 1), i, o)` over 10 threads, `g[j] = 100 + j`: `o[j]` is +//! `101 + j`, three `uint`s a thread from one past the buffer's start (no 16-byte alignment). +//! - **vlodd**: `vstore3(vload3(i, g + 1), i, o + 1)` of `uchar`s and `vstore2(vload2(i, s + 1), i, +//! t + 1)` of `short`s over 4 threads, `g[j] = 100 + j`, `s[j] = 1000 + j`: bytes 1 to 12 of `o` +//! are 101 to 112 and shorts 1 to 8 of `t` are 1001 to 1008, the rest untouched. +//! - **vha3**: `vload_half3(i, g)` and `vloada_half3(i, g)` of halves `g[j] = 0x5000 + j` over 4 +//! threads read halves `3i` to `3i + 2` and `4i` to `4i + 2`; `vstore_half3(_, i, h)` writes +//! halves 0 to 11 and `vstorea_half3_rte(_, i, h + 32)` three of each four from half 32. +//! - **vsh_round**: `vstore_half` and its `_rte`, `_rtz`, `_rtp` and `_rtn` forms of 32 floats: +//! the Radeon Pro 5300M and the UHD Graphics 630 store every form as `vstore_half_rte`, word for +//! word, and the M3 Max rounds as each names; the crate stores every form as the device converts +//! (the device's own rounding to nearest even, checked on the values whose `half` is normal). +//! - **npowr**: `native_powr` of `float4`s: each device answers within a few ulps of the others +//! (`powr(100, 0.5)` is `0x1.400002p+3` on the M3 Max, `0x1.4p+3` on the Radeon Pro 5300M); the +//! crate's answers are within `2^-12` of the M3 Max's, relatively (the device's own `powr`). +//! +//! 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}; +use super::opencl_mode::{ + floats, floats_buffer, kernel_list, line, run, state, whole, words, words_buffer, +}; +use crate::{Buffer, Device, ResourceOptions}; + +/// The node of argument `n`, a buffer at `index` of `size`-byte elements of `ty`, `access` one of +/// `read`, `read_write`. +fn data(n: u32, index: u32, access: &str, (ty, size): (&str, u32), name: &str) -> String { + format!( + "!{{i32 {n}, !\"air.buffer\", !\"air.location_index\", i32 {index}, i32 1, !\"air.{access}\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 {size}, !\"air.arg_type_align_size\", i32 {size}, !\"air.arg_type_name\", !\"{ty}\", !\"air.arg_name\", !\"{name}\"}}" + ) +} + +/// `__kernel void vl3_odd(__global const uint *g, __global uint *o)`. +fn vl3_odd() -> String { + let body = "define void @__entry_vl3_odd(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {\n\ +entry:\n\ + tail call fastcc void @vl3_odd(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\ + ret void\n}\n\ +define internal fastcc void @vl3_odd(ptr addrspace(1) %g, ptr addrspace(1) %o) #1 {\n\ +entry:\n\ + %i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %g1 = getelementptr inbounds i32, ptr addrspace(1) %g, i64 1\n\ + %v = tail call fastcc <3 x i32> @_Z6vload3mPU8CLglobalKj(i64 %i, ptr addrspace(1) %g1)\n\ + tail call fastcc void @_Z7vstore3Dv3_jmPU8CLglobalj(<3 x i32> %v, i64 %i, ptr addrspace(1) %o)\n\ + ret void\n}\n\ +define internal fastcc void @_Z7vstore3Dv3_jmPU8CLglobalj(<3 x i32> %0, i64 %1, ptr addrspace(1) %2) #2 {\n\ + tail call void @air.vstore.global.v3i32(<3 x i32> %0, i64 %1, ptr addrspace(1) %2) #6\n\ + ret void\n}\n\ +define internal fastcc <3 x i32> @_Z6vload3mPU8CLglobalKj(i64 %0, ptr addrspace(1) %1) #2 {\n\ + %3 = tail call <3 x i32> @air.vload.global.v3i32(i64 %0, ptr addrspace(1) %1) #7\n\ + ret <3 x i32> %3\n}\n\ +declare void @air.vstore.global.v3i32(<3 x i32>, i64, ptr addrspace(1)) #6\n\ +declare <3 x i32> @air.vload.global.v3i32(i64, ptr addrspace(1)) #7\n\ +attributes #6 = { nounwind willreturn memory(argmem: write) }\n\ +attributes #7 = { nounwind willreturn memory(argmem: read) }\n"; + let args = [ + data(0, 0, "read", ("uint", 4), "g"), + data(1, 1, "read_write", ("uint", 4), "o"), + ]; + format!("{body}{}", kernel_list("__entry_vl3_odd", &args)) +} + +/// `__kernel void vlodd(__global const uchar *g, __global const short *s, __global uchar *o, +/// __global short *t)`. +fn vlodd() -> String { + let body = "define void @__entry_vlodd(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3) #0 {\n\ +entry:\n\ + tail call fastcc void @vlodd(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3)\n\ + ret void\n}\n\ +define internal fastcc void @vlodd(ptr addrspace(1) %g, ptr addrspace(1) %s, ptr addrspace(1) %o, ptr addrspace(1) %t) #1 {\n\ +entry:\n\ + %i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %g1 = getelementptr inbounds i8, ptr addrspace(1) %g, i64 1\n\ + %o1 = getelementptr inbounds i8, ptr addrspace(1) %o, i64 1\n\ + %b = tail call <3 x i8> @air.vload.global.v3i8(i64 %i, ptr addrspace(1) %g1) #7\n\ + tail call void @air.vstore.global.v3i8(<3 x i8> %b, i64 %i, ptr addrspace(1) %o1) #6\n\ + %s1 = getelementptr inbounds i16, ptr addrspace(1) %s, i64 1\n\ + %t1 = getelementptr inbounds i16, ptr addrspace(1) %t, i64 1\n\ + %h = tail call <2 x i16> @air.vload.global.v2i16(i64 %i, ptr addrspace(1) %s1) #7\n\ + tail call void @air.vstore.global.v2i16(<2 x i16> %h, i64 %i, ptr addrspace(1) %t1) #6\n\ + ret void\n}\n\ +declare <3 x i8> @air.vload.global.v3i8(i64, ptr addrspace(1)) #7\n\ +declare void @air.vstore.global.v3i8(<3 x i8>, i64, ptr addrspace(1)) #6\n\ +declare <2 x i16> @air.vload.global.v2i16(i64, ptr addrspace(1)) #7\n\ +declare void @air.vstore.global.v2i16(<2 x i16>, i64, ptr addrspace(1)) #6\n\ +attributes #6 = { nounwind willreturn memory(argmem: write) }\n\ +attributes #7 = { nounwind willreturn memory(argmem: read) }\n"; + let args = [ + data(0, 0, "read", ("uchar", 1), "g"), + data(1, 1, "read", ("short", 2), "s"), + data(2, 2, "read_write", ("uchar", 1), "o"), + data(3, 3, "read_write", ("short", 2), "t"), + ]; + format!("{body}{}", kernel_list("__entry_vlodd", &args)) +} + +/// `__kernel void vha3(__global const half *g, __global float *o, __global half *h)`: `o[6i..]` +/// take `vload_half3(i, g)` and `vloada_half3(i, g)`, stored to `h` by `vstore_half3` and to +/// `h + 32` by `vstorea_half3_rte`. +fn vha3() -> String { + let mut body = String::from( + "define void @__entry_vha3(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2) #0 {\n\ +entry:\n\ + tail call fastcc void @vha3(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2)\n\ + ret void\n}\n\ +define internal fastcc void @vha3(ptr addrspace(1) %g, ptr addrspace(1) %o, ptr addrspace(1) %h) #1 {\n\ +entry:\n\ + %i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %a = tail call <3 x float> @air.vload_half.global.v3f32(i64 %i, ptr addrspace(1) %g) #7\n\ + %b = tail call <3 x float> @air.vloada_half.global.v3f32(i64 %i, ptr addrspace(1) %g) #7\n\ + %i6 = mul i64 %i, 6\n", + ); + for (k, (v, lane)) in [("a", 0), ("a", 1), ("a", 2), ("b", 0), ("b", 1), ("b", 2)] + .into_iter() + .enumerate() + { + body.push_str(&format!( + " %x{k} = extractelement <3 x float> %{v}, i32 {lane}\n\ + %j{k} = add i64 %i6, {k}\n\ + %p{k} = getelementptr inbounds float, ptr addrspace(1) %o, i64 %j{k}\n\ + store float %x{k}, ptr addrspace(1) %p{k}, align 4\n" + )); + } + body.push_str( + " tail call void @air.vstore_half.global.rte.v3f32(<3 x float> %a, i64 %i, ptr addrspace(1) %h) #6\n\ + %h32 = getelementptr inbounds half, ptr addrspace(1) %h, i64 32\n\ + tail call void @air.vstorea_half.global.rte.v3f32(<3 x float> %b, i64 %i, ptr addrspace(1) %h32) #6\n\ + ret void\n}\n\ +declare <3 x float> @air.vload_half.global.v3f32(i64, ptr addrspace(1)) #7\n\ +declare <3 x float> @air.vloada_half.global.v3f32(i64, ptr addrspace(1)) #7\n\ +declare void @air.vstore_half.global.rte.v3f32(<3 x float>, i64, ptr addrspace(1)) #6\n\ +declare void @air.vstorea_half.global.rte.v3f32(<3 x float>, i64, ptr addrspace(1)) #6\n\ +attributes #6 = { nounwind willreturn memory(argmem: write) }\n\ +attributes #7 = { nounwind willreturn memory(argmem: read) }\n", + ); + let args = [ + data(0, 0, "read", ("half", 2), "g"), + data(1, 1, "read_write", ("float", 4), "o"), + data(2, 2, "read_write", ("half", 2), "h"), + ]; + format!("{body}{}", kernel_list("__entry_vha3", &args)) +} + +/// `__kernel void vsh_round(__global const float *f, __global half *h)`: `f[i]` stored at half +/// `i` by `vstore_half`, and at `32 + i`, `64 + i`, `96 + i` and `128 + i` by its `_rte`, +/// `_rtz`, `_rtp` and `_rtn` forms. +fn vsh_round() -> String { + let mut body = String::from( + "define void @__entry_vsh_round(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {\n\ +entry:\n\ + tail call fastcc void @vsh_round(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\ + ret void\n}\n\ +define internal fastcc void @vsh_round(ptr addrspace(1) %f, ptr addrspace(1) %h) #1 {\n\ +entry:\n\ + %i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %pf = getelementptr inbounds float, ptr addrspace(1) %f, i64 %i\n\ + %x = load float, ptr addrspace(1) %pf, align 4\n", + ); + let mut decls = String::new(); + for (k, rounding) in ["rte", "rte", "rtz", "rtp", "rtn"].into_iter().enumerate() { + let name = format!("@air.vstore_half.global.{rounding}.f32"); + body.push_str(&format!( + " %h{k} = getelementptr inbounds half, ptr addrspace(1) %h, i64 {}\n\ + tail call void {name}(float %x, i64 %i, ptr addrspace(1) %h{k}) #6\n", + 32 * k + )); + let decl = format!("declare void {name}(float, i64, ptr addrspace(1)) #6\n"); + if !decls.contains(&decl) { + decls.push_str(&decl); + } + } + body.push_str(" ret void\n}\n"); + body.push_str(&decls); + body.push_str("attributes #6 = { nounwind willreturn memory(argmem: write) }\n"); + let args = [ + data(0, 0, "read", ("float", 4), "f"), + data(1, 1, "read_write", ("half", 2), "h"), + ]; + format!("{body}{}", kernel_list("__entry_vsh_round", &args)) +} + +/// `__kernel void npowr(__global const float4 *a, __global const float4 *b, __global float4 *o)`: +/// `o[i] = native_powr(a[i], b[i])`. +fn npowr() -> String { + let body = "define void @__entry_npowr(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2) #0 {\n\ +entry:\n\ + tail call fastcc void @npowr(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2)\n\ + ret void\n}\n\ +define internal fastcc void @npowr(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %o) #1 {\n\ +entry:\n\ + %i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %pa = getelementptr inbounds <4 x float>, ptr addrspace(1) %a, i64 %i\n\ + %va = load <4 x float>, ptr addrspace(1) %pa, align 16\n\ + %pb = getelementptr inbounds <4 x float>, ptr addrspace(1) %b, i64 %i\n\ + %vb = load <4 x float>, ptr addrspace(1) %pb, align 16\n\ + %r = tail call fastcc <4 x float> @_Z11native_powrDv4_fS_(<4 x float> %va, <4 x float> %vb)\n\ + %po = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i\n\ + store <4 x float> %r, ptr addrspace(1) %po, align 16\n\ + ret void\n}\n\ +define internal fastcc <4 x float> @_Z11native_powrDv4_fS_(<4 x float> %0, <4 x float> %1) #2 {\n\ + %3 = tail call <4 x float> @air.native_powr.v4f32(<4 x float> %0, <4 x float> %1) #3\n\ + ret <4 x float> %3\n}\n\ +declare <4 x float> @air.native_powr.v4f32(<4 x float>, <4 x float>) #3\n"; + let args = [ + data(0, 0, "read", ("float4", 16), "a"), + data(1, 1, "read", ("float4", 16), "b"), + data(2, 2, "read_write", ("float4", 16), "o"), + ]; + format!("{body}{}", kernel_list("__entry_npowr", &args)) +} + +/// A shared buffer of `bytes`. +fn bytes_buffer(device: &Device, bytes: &[u8]) -> Buffer { + device + .new_buffer_with_bytes(bytes, ResourceOptions::shared()) + .unwrap() +} + +/// A shared buffer of the 16-bit words `halves`. +fn halves_buffer(device: &Device, halves: &[u16]) -> Buffer { + let bytes: Vec = halves.iter().flat_map(|h| h.to_le_bytes()).collect(); + bytes_buffer(device, &bytes) +} + +/// The bytes of `buffer`, which no command uses now. +fn bytes(buffer: &Buffer) -> Vec { + words(buffer) + .into_iter() + .flat_map(u32::to_le_bytes) + .collect() +} + +/// The 16-bit words of `buffer`, which no command uses now. +fn halves(buffer: &Buffer) -> Vec { + bytes(buffer) + .as_chunks::<2>() + .0 + .iter() + .map(|h| u16::from_le_bytes(*h)) + .collect() +} + +/// No dispatch offset, one dimension. +const ONE: ([u32; 3], u32) = ([0; 3], 1); + +#[test] +fn opencl_mode_vload3_reads_three_elements_past_an_unaligned_pointer() { + let scratch = Scratch::new("opencl-data-vload3"); + let device = device(&scratch.0); + let s = state(&device, &vl3_odd(), "__entry_vl3_odd"); + let g = words_buffer(&device, &(0..64).map(|j| 100 + j).collect::>()); + let o = words_buffer(&device, &[0xeeee_eeee; 30]); + run(&device, &s, line(10, 1), ONE, &[whole(&g), whole(&o)], None); + assert_eq!(words(&o), (101..131).collect::>()); +} + +#[test] +fn opencl_mode_vector_data_moves_bytes_and_shorts_at_odd_elements() { + let scratch = Scratch::new("opencl-data-narrow"); + let device = device(&scratch.0); + let s = state(&device, &vlodd(), "__entry_vlodd"); + let g = bytes_buffer(&device, &(100..164).collect::>()); + let sh = halves_buffer(&device, &(1000..1064).collect::>()); + let o = bytes_buffer(&device, &[0xee; 16]); + let t = halves_buffer(&device, &[0xeeee; 16]); + let args = [whole(&g), whole(&sh), whole(&o), whole(&t)]; + run(&device, &s, line(4, 1), ONE, &args, None); + let mut want = vec![0xee; 16]; + want[1..13].copy_from_slice(&(101..113).collect::>()); + assert_eq!(bytes(&o), want); + let mut want = vec![0xeeee; 16]; + want[1..9].copy_from_slice(&(1001..1009).collect::>()); + assert_eq!(halves(&t), want); +} + +#[test] +fn opencl_mode_half_vector_data_steps_three_or_four_halves() { + let scratch = Scratch::new("opencl-data-half3"); + let device = device(&scratch.0); + let s = state(&device, &vha3(), "__entry_vha3"); + let g = halves_buffer(&device, &(0..64).map(|j| 0x5000 + j).collect::>()); + let o = floats_buffer(&device, &[0.0; 24]); + let h = halves_buffer(&device, &[0xeeee; 64]); + run( + &device, + &s, + line(4, 1), + ONE, + &[whole(&g), whole(&o), whole(&h)], + None, + ); + // Each half `0x5000 + j` is `32 + j / 32`. + let read: Vec = floats(&o).iter().map(|x| (x - 32.0) * 32.0).collect(); + #[rustfmt::skip] + let want: [f32; 24] = [ + 0.0, 1.0, 2.0, 0.0, 1.0, 2.0, + 3.0, 4.0, 5.0, 4.0, 5.0, 6.0, + 6.0, 7.0, 8.0, 8.0, 9.0, 10.0, + 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, + ]; + assert_eq!(read, want); + let mut want = vec![0xeeee; 64]; + for (j, w) in (0..).zip(want.iter_mut().take(12)) { + *w = 0x5000 + j; + } + for i in 0..4u16 { + for lane in 0..3 { + want[usize::from(32 + 4 * i + lane)] = 0x5000 + 4 * i + lane; + } + } + assert_eq!(halves(&h), want); +} + +/// The 32 floats of `vsh_round`, with the half `vstore_half_rte` stores for each on the three +/// Macs where that half is a normal number or an infinity (`None` for the rest: a NaN, a zero, a +/// subnormal, whose encoding the device's conversion decides). +#[rustfmt::skip] +const ROUNDED: [(f32, Option); 32] = [ + // 1 + 2^-11 (a tie), 1 + 3 * 2^-12, and its negation. + (1.0 + 1.0 / 2048.0, Some(0x3c00)), (1.0 + 3.0 / 4096.0, Some(0x3c01)), + (-(1.0 + 3.0 / 4096.0), Some(0xbc01)), + // Past the largest half: 65520 is the tie with the next power of two. + (65520.0, Some(0x7c00)), (70000.0, Some(0x7c00)), (-70000.0, Some(0xfc00)), + (1e-8, None), (-1e-8, None), (3e-5, None), (-3e-5, None), (f32::NAN, None), + (f32::INFINITY, Some(0x7c00)), (f32::NEG_INFINITY, Some(0xfc00)), (-0.0, None), + (0.1, Some(0x2e66)), (1.0 / 3.0, Some(0x3555)), (2049.0, Some(0x6800)), (2051.0, Some(0x6802)), + (-2049.0, Some(0xe800)), (65504.0, Some(0x7bff)), (65519.0, Some(0x7bff)), + // 2^-24, 1.5 * 2^-25, 2^-25, -1.5 * 2^-25, 6.1e-5: zeros and subnormals. + (1.0 / 16_777_216.0, None), (1.5 / 33_554_432.0, None), (1.0 / 33_554_432.0, None), + (-1.5 / 33_554_432.0, None), (6.1e-5, None), + // 2^-14 - 2^-25 (the tie between the largest subnormal and the least normal) and + // 2^-14 - 2^-26. + (1.0 / 16_384.0 - 1.0 / 33_554_432.0, Some(0x0400)), + (1.0 / 16_384.0 - 1.0 / 67_108_864.0, Some(0x0400)), + (1e10, Some(0x7c00)), (-1e10, Some(0xfc00)), (0.5, Some(0x3800)), + (std::f32::consts::PI, Some(0x4248)), +]; + +#[test] +fn opencl_mode_vstore_half_stores_every_rounding_as_the_device_converts() { + let scratch = Scratch::new("opencl-data-vstore-half"); + let device = device(&scratch.0); + let s = state(&device, &vsh_round(), "__entry_vsh_round"); + let f = floats_buffer(&device, &ROUNDED.map(|(x, _)| x)); + let h = halves_buffer(&device, &[0xeeee; 160]); + run(&device, &s, line(32, 1), ONE, &[whole(&f), whole(&h)], None); + let h = halves(&h); + let (plain, forms) = h.split_at(32); + // Every rounding the names spell stores what `vstore_half` stores, as the x86 Macs do. + for (k, form) in forms.chunks(32).enumerate() { + assert_eq!(form, plain, "form {k} of rte, rtz, rtp, rtn"); + } + // That is the device's conversion: to nearest, ties to even, where the half is normal. + for (i, (&(x, rte), &got)) in ROUNDED.iter().zip(plain).enumerate() { + if let Some(rte) = rte { + assert_eq!(got, rte, "{i}: {x:e}"); + } + } +} + +#[test] +fn opencl_mode_native_powr_answers_the_devices_powr() { + let scratch = Scratch::new("opencl-data-native-powr"); + let device = device(&scratch.0); + let s = state(&device, &npowr(), "__entry_npowr"); + #[rustfmt::skip] + let (a, b, m3) = ( + [2.0, 0.5, 10.0, 3.0, 1.5, 100.0, 0.25, 7.0, 1e-3, 1e3, 4.0, 9.0], + [3.0, 2.0, -1.0, 0.5, 7.25, 0.5, -2.0, 1.5, 2.0, -1.0, 0.5, 0.5], + [ + 8.0, 0.25, f32::from_bits(0x3dcc_cccd), f32::from_bits(0x3fdd_b3d7), + f32::from_bits(0x4197_4504), f32::from_bits(0x4120_0001), 16.0, + f32::from_bits(0x4194_297e), f32::from_bits(0x3586_37be), f32::from_bits(0x3a83_126f), + 2.0, 3.0, + ], + ); + let (ab, bb) = (floats_buffer(&device, &a), floats_buffer(&device, &b)); + let o = floats_buffer(&device, &[0.0; 12]); + run( + &device, + &s, + line(3, 1), + ONE, + &[whole(&ab), whole(&bb), whole(&o)], + None, + ); + for (i, (got, want)) in floats(&o).into_iter().zip(m3).enumerate() { + let error = ((got - want) / want).abs(); + assert!( + error <= 2f32.powi(-12), + "powr({}, {}): {got:e}, the M3 Max {want:e}", + a[i], + b[i] + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs b/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs index c2a480600..c8d27e34c 100644 --- a/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs +++ b/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs @@ -454,7 +454,7 @@ pub(super) fn floats(buffer: &Buffer) -> Vec { /// One of a kernel's own arguments, as bound. #[derive(Clone, Copy)] -enum Arg<'a> { +pub(super) enum Arg<'a> { /// A buffer from a byte offset (`setBuffer:offset:atIndex:`). Buffer(&'a Buffer, u64), /// Bytes (`setBytes:length:atIndex:`). @@ -462,14 +462,14 @@ enum Arg<'a> { } /// `buffer` from its start. -fn whole(buffer: &Buffer) -> Arg<'_> { +pub(super) fn whole(buffer: &Buffer) -> Arg<'_> { Arg::Buffer(buffer, 0) } /// `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, `args` at 3 and up, and `local` bytes of threadgroup memory at index 0 where `Some`. -fn run( +pub(super) fn run( device: &Device, state: &ComputePipelineState, (grid, group): (Size, Size), @@ -506,7 +506,7 @@ fn run( } /// One dimension's grid. -fn line(threads: u64, group: u64) -> (Size, Size) { +pub(super) fn line(threads: u64, group: u64) -> (Size, Size) { (Size::new(threads, 1, 1), Size::new(group, 1, 1)) } diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 5ff7939ba..87b8293dc 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -878,6 +878,10 @@ fn route_air(cx: &SelectCx<'_>, op: &AirIntrinsic, decl: FuncId) -> Route { // An encoder operation writes its command's record through device addresses. A::IndirectCommand(_) => Route::Family(LowerFamily::Access), A::Mesh(_) => Route::Family(LowerFamily::Mesh), + // Canonicalization makes every vector data call its element accesses. + A::VectorData(_) => Route::Refuse(invariant( + "a vector data function survived canonicalization", + )), // Canonicalization made every read of a global built-in at a constant lane a read of a // built-in parameter, but a fragment's read of one Metal refuses there, which is // refused as its own feature; a read at another lane is not lowered. diff --git a/crates/metal2vulkan/src/pipeline/compile/partition.rs b/crates/metal2vulkan/src/pipeline/compile/partition.rs index e94535606..c8da63b0f 100644 --- a/crates/metal2vulkan/src/pipeline/compile/partition.rs +++ b/crates/metal2vulkan/src/pipeline/compile/partition.rs @@ -169,6 +169,7 @@ fn observes(callee: &Callee) -> bool { | AirIntrinsic::Convert(_) | AirIntrinsic::Pack(_) | AirIntrinsic::Coherent(_) + | AirIntrinsic::VectorData(_) | AirIntrinsic::Texture(_) | AirIntrinsic::Sampler(_) | AirIntrinsic::FunctionConstant(_) diff --git a/crates/metal2vulkan/src/reflection/live.rs b/crates/metal2vulkan/src/reflection/live.rs index 4c4950c60..dc67925cc 100644 --- a/crates/metal2vulkan/src/reflection/live.rs +++ b/crates/metal2vulkan/src/reflection/live.rs @@ -646,6 +646,7 @@ impl<'a> Engine<'a> { !matches!(a, AsyncCopy::NullEvent | AsyncCopy::IsNullEvent) } AirIntrinsic::Mesh(op) => self.mesh_write_kept(*op, call, roots), + AirIntrinsic::VectorData(v) => v.stores(), AirIntrinsic::Atomic(_) | AirIntrinsic::Sync(_) | AirIntrinsic::SimdMatrix(_) diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 2e9237ab2..df515720b 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1176,6 +1176,7 @@ enum metal2vulkan-air::intrinsics::FunctionTable #[derive(Clone, Copy, Debug, Pa enum metal2vulkan-air::intrinsics::GlobalVar #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum GlobalVar enum metal2vulkan-air::intrinsics::GroupOp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum GroupOp enum metal2vulkan-air::intrinsics::GroupScope #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum GroupScope +enum metal2vulkan-air::intrinsics::HalfRounding #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum HalfRounding enum metal2vulkan-air::intrinsics::HandleKind #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum HandleKind enum metal2vulkan-air::intrinsics::ImageDim #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ImageDim enum metal2vulkan-air::intrinsics::Imageblock #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Imageblock @@ -1208,6 +1209,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::VectorDataOp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum VectorDataOp 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 @@ -1905,6 +1907,9 @@ field metal2vulkan-air::intrinsics::Texture.op pub op: TexOp field metal2vulkan-air::intrinsics::Texture.states_access pub states_access: bool field metal2vulkan-air::intrinsics::Texture.status pub status: bool field metal2vulkan-air::intrinsics::Texture.texel pub texel: Option +field metal2vulkan-air::intrinsics::VectorData.op pub op: VectorDataOp +field metal2vulkan-air::intrinsics::VectorData.space pub space: AddrSpace +field metal2vulkan-air::intrinsics::VectorData.ty pub ty: NumTy field metal2vulkan-air::ir::Block.end pub end: InstId field metal2vulkan-air::ir::Block.name pub name: Option field metal2vulkan-air::ir::Block.start pub start: InstId @@ -7787,6 +7792,10 @@ 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::VectorData::data pub fn data(&self) -> Elem +method metal2vulkan-air::intrinsics::VectorData::signature pub fn signature(&self) -> Signature +method metal2vulkan-air::intrinsics::VectorData::stores pub fn stores(&self) -> bool +method metal2vulkan-air::intrinsics::VectorData::stride pub fn stride(&self) -> u32 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 @@ -9826,6 +9835,7 @@ struct metal2vulkan-air::intrinsics::Pack #[derive(Clone, Copy, Debug, PartialEq struct metal2vulkan-air::intrinsics::Signature #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct Signature struct metal2vulkan-air::intrinsics::SimdgroupSize #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SimdgroupSize struct metal2vulkan-air::intrinsics::Texture #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Texture +struct metal2vulkan-air::intrinsics::VectorData #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct VectorData struct metal2vulkan-air::ir::Align #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Align(u8) struct metal2vulkan-air::ir::Arena #[derive(Clone, PartialEq, Eq, Hash)] pub struct Arena struct metal2vulkan-air::ir::Block #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct Block @@ -10986,6 +10996,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::VectorData VectorData(VectorData) 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 @@ -11100,6 +11111,10 @@ variant metal2vulkan-air::intrinsics::GroupOp::Sum Sum variant metal2vulkan-air::intrinsics::GroupOp::Xor Xor variant metal2vulkan-air::intrinsics::GroupScope::Quad Quad variant metal2vulkan-air::intrinsics::GroupScope::Simdgroup Simdgroup +variant metal2vulkan-air::intrinsics::HalfRounding::Rte Rte +variant metal2vulkan-air::intrinsics::HalfRounding::Rtn Rtn +variant metal2vulkan-air::intrinsics::HalfRounding::Rtp Rtp +variant metal2vulkan-air::intrinsics::HalfRounding::Rtz Rtz variant metal2vulkan-air::intrinsics::HandleKind::AccelerationStructure AccelerationStructure variant metal2vulkan-air::intrinsics::HandleKind::Command Command variant metal2vulkan-air::intrinsics::HandleKind::ComputePipelineState ComputePipelineState @@ -11338,6 +11353,8 @@ variant metal2vulkan-air::intrinsics::PackFormat::UnormRgb9e5 UnormRgb9e5 variant metal2vulkan-air::intrinsics::Precision::Fast Fast variant metal2vulkan-air::intrinsics::Precision::Precise Precise variant metal2vulkan-air::intrinsics::Query::ArraySize ArraySize +variant metal2vulkan-air::intrinsics::Query::ChannelDataType ChannelDataType +variant metal2vulkan-air::intrinsics::Query::ChannelOrder ChannelOrder variant metal2vulkan-air::intrinsics::Query::Depth Depth variant metal2vulkan-air::intrinsics::Query::Height Height variant metal2vulkan-air::intrinsics::Query::NumMipLevels NumMipLevels @@ -11426,6 +11443,10 @@ 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::VectorDataOp::Load Load +variant metal2vulkan-air::intrinsics::VectorDataOp::LoadHalf LoadHalf { aligned: bool } +variant metal2vulkan-air::intrinsics::VectorDataOp::Store Store +variant metal2vulkan-air::intrinsics::VectorDataOp::StoreHalf StoreHalf { aligned: bool, rounding: HalfRounding } variant metal2vulkan-air::intrinsics::WorkItem::GlobalOffset GlobalOffset variant metal2vulkan-air::intrinsics::WorkItem::WorkDim WorkDim variant metal2vulkan-air::ir::AddrSpace::Constant Constant = 2 diff --git a/docs/API.md b/docs/API.md index 93dfa455c..7e62d8d71 100644 --- a/docs/API.md +++ b/docs/API.md @@ -750,6 +750,36 @@ layout stride of `None` is `MTLBufferLayoutStrideDynamic`: the stride comes from 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 + `get_image_channel_data_type(image)` (`air.get_channel_order_texture_` and + `air.get_channel_data_type_texture_`, `Query::ChannelOrder` and + `Query::ChannelDataType`) read the third hidden buffer as it holds them: word `2t + 1` for the + order and word `2t` for the data type of the image at texture index `t`, as an M3 Max (macOS + 27.0.1) and a Radeon Pro 5300M (macOS 26.7.1) answer. Metal refuses the queries of a buffer or + a depth image, and the crate decodes none (`UnknownIntrinsic`); without the mode it refuses + each query (`Unsupported` with `Lowering(Texture)`). Apple's OpenCL binds a 2D texture of + height 1 for an `image1d_t`, which the AIR declares `texture1d`, and a 2D array texture of + height 1 for an `image1d_array_t` (`texture1d_array`). In the mode the kernel's slot is that + texture's type (`TextureType::Type2D`, `Type2DArray`), and each read, sample and write of the + image, `get_image_width` and `get_image_array_size` is the 2D texture's at row 0 (a sampled + coordinate at the row's centre), as both Macs answer. + - OpenCL C's `native_` and `half_` of `float` types + (`air.native_.` and `air.half_.`, for `cos`, `exp`, `exp10`, `exp2`, + `log`, `log10`, `log2`, `powr`, `rsqrt`, `sin`, `sqrt` and `tan`, scalar and of every vector + width) are the function's fast form, as `fast::` is (`Precision::Fast`). OpenCL C + leaves their precision to the implementation, and Metal's devices differ: + `native_powr(100, 0.5)` is `0x1.400002p+3` on the M3 Max and `0x1.4p+3` on the Radeon Pro + 5300M. + - OpenCL C's vector data functions (`vload`, `vstore`, `vload_half[]`, + `vloada_half`, `vstore_half[][_]` and `vstorea_half[_]`, which + the compiler spells `air.vload[a][_half]..` and + `air.vstore[a][_half].[.].`, `VectorData`) read and write `n` elements + at `p + offset * n` (`offset * 4` for `vloada_half3` and `vstorea_half3`), each at its own + element's alignment, in every address space and of every element type the compiler spells. + `vload3` of a `uint` pointer one element past a buffer's start reads the three words that + follow, as the M3 Max, the Radeon Pro 5300M and a UHD Graphics 630 (macOS 26.7.1) do. The + `half` forms widen each `half` read to `float` and narrow each lane stored to `half`; a + store's rounding is an accepted difference (section 10, Conversions). ## 4. A render pipeline @@ -4970,6 +5000,15 @@ each item named states the rule in full. wraps (the M3 Max creates none), and a float to an integer by `.rtp` or `.rtn` truncates on the 5300M (the others create none). The M3 Max's compiler service exits on the forms it does not compile, where the runtime compiles them all. +- **`vstore_half` and `vstorea_half` with a rounding (`_rtz`, `_rtp`, `_rtn`) store each lane as + the device converts a `float` to `half`, to nearest even.** Measured over 32 values among them + ties, overflows past the largest `half`, subnormals and zeros, with the `vstore_half4` forms alike + (probe jobs m3-max-15563 on the M3 Max, macOS 27.0.1; m3-max-15564 on a Radeon Pro 5300M and + m3-max-15584 on a UHD Graphics 630, macOS 26.7.1): + + | Form | M3 Max | Radeon Pro 5300M | UHD Graphics 630 | Runtime | + |---|---|---|---|---| + | `vstore_half_rtz`, `_rtp`, `_rtn` (`70000.0` by `_rtz`) | as named (`0x7bff`) | nearest even (`0x7c00`) | nearest even (`0x7c00`) | nearest even (`0x7c00`) | **Inline assembly** diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 65580126c..32333550c 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 (each `byval` argument's copy made at its call first), 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, 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, 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 | +| `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 (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, 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, 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, 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 | | `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 |