diff --git a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs index cdb1466f4..6e2d3b815 100644 --- a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs +++ b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs @@ -1205,6 +1205,77 @@ fn read_forms_are_chosen_by_the_declaration() { assert_eq!(roles(l), [R::Texture, R::Coord, R::Lod, R::Access]); } +/// A 2D or 3D texture atomic's two forms: Xcode's AIR passes an offset after the coordinate (and +/// layer), the AIR macOS 26.6's Metal on x86-64 hands its device omits it. The declaration picks +/// the form; a 1D, 1D array or buffer atomic has one form, without an offset. +#[test] +fn atomic_forms_are_chosen_by_the_declaration() { + use TexRole as R; + let roles = |t: Texture| t.layout().positions().map(|(r, _)| r).collect::>(); + let texture = |name: &str, decl: &str| match declared_air(name, decl) { + AirIntrinsic::Texture(t) => t, + other => panic!("{name}: {other:?}"), + }; + let fetch = "air.atomic_fetch_add_explicit_texture_2d.u.v4i32"; + let current = texture(fetch, "v4i32 (p1, v2i32, v2i32, v4i32, i32, i32)"); + let legacy = texture(fetch, "v4i32 (p1, v2i32, v4i32, i32, i32)"); + assert_eq!((current.form, legacy.form), (Form::Current, Form::Legacy)); + assert_eq!( + roles(legacy), + [R::Texture, R::Coord, R::Value, R::Order, R::Access] + ); + let legacy_cases = [ + ( + "air.atomic_fetch_xor_explicit_texture_2d.s.v4i32", + "v4i32 (p1, v2i32, v4i32, i32, i32)", + ), + ( + "air.atomic_fetch_min_explicit_texture_2d_array.u.v4i32", + "v4i32 (p1, v2i32, i32, v4i32, i32, i32)", + ), + ( + "air.atomic_exchange_explicit_texture_3d.s.v4i32", + "v4i32 (p1, v3i32, v4i32, i32, i32)", + ), + ( + "air.atomic_load_explicit_texture_2d.u.v4i32", + "v4i32 (p1, v2i32, i32, i32)", + ), + ( + "air.atomic_store_explicit_texture_2d_array.s.v4i32", + "void (p1, v4i32, v2i32, i32, i32, i32)", + ), + ( + "air.atomic_compare_exchange_weak_explicit_texture_2d.u.v4i32", + "i1 (p1, v2i32, p0, v4i32, i32, i32, i32)", + ), + ( + "air.atomic_max_explicit_texture_2d.u.v4i64", + "void (p1, v2i32, v4i64, i32, i32)", + ), + ( + "air.atomic_fetch_max_explicit_texture_2d.i16.u.v4i32", + "v4i32 (p1, v2i16, v4i32, i32, i32)", + ), + ]; + for (name, decl) in legacy_cases { + let t = texture(name, decl); + assert_eq!(t.form, Form::Legacy, "{name}"); + assert!(!roles(t).contains(&R::Offset), "{name}"); + } + // One form where the shape has no offset: a 1D atomic declared with one more position is not + // a form of it. + let one_d = "air.atomic_fetch_add_explicit_texture_1d.u.v4i32"; + assert_eq!( + texture(one_d, "v4i32 (p1, i32, v4i32, i32, i32)").form, + Form::Current + ); + assert!(matches!( + declared(one_d, "v4i32 (p1, i32, i32, v4i32, i32, i32)"), + DeclClass::Mismatch + )); +} + #[test] fn texture_layouts_name_every_position() { use TexRole as R; diff --git a/crates/metal2vulkan-air/src/intrinsics/texture.rs b/crates/metal2vulkan-air/src/intrinsics/texture.rs index 8691d37f6..1a3bceae0 100644 --- a/crates/metal2vulkan-air/src/intrinsics/texture.rs +++ b/crates/metal2vulkan-air/src/intrinsics/texture.rs @@ -31,6 +31,9 @@ //! `void (tex, T value, coord, [layer], [offset], i32 order, i32 access)`; and //! `compare_exchange_weak` `i1 (tex, coord, [layer], [offset], ptr expected, T desired, //! i32 order, i32 failure order, i32 access)`, whose `expected` is a thread pointer to a `T`. +//! The **legacy** form of a 2D or 3D one (a `ulong` one's too) omits the offset position: the +//! AIR macOS 26.6's Metal on x86-64 hands its device for a library whose own declarations +//! pass the offset. //! - queries, null checks, fences, LOD queries, and the imageblock slice write as documented on //! [`TexOp`]. //! @@ -193,12 +196,14 @@ pub struct Texel { pub sign: Option, } -/// The two operand forms of a texture read. +/// The two operand forms of a texture read or a 2D or 3D texture atomic. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Form { - /// The current form (with a sampler and, where the shape has one, an offset position). + /// The current form (a read's with a sampler and, where the shape has one, an offset + /// position; an atomic's with its offset position). Current, - /// The older form without the sampler and offset positions. + /// The older form: a read's without the sampler and offset positions, an atomic's without + /// the offset position. Legacy, } @@ -213,7 +218,8 @@ pub struct Texture { pub texel: Option, /// `.i16`: 16-bit integer coordinates, offsets, layers, faces, levels, and sample indices. pub coord16: bool, - /// The operand form: a read's current or legacy form; `Current` for every other operation. + /// The operand form: a read's or a 2D or 3D atomic's current or legacy form; `Current` for + /// every other operation. pub form: Form, /// The access qualifier, for operations that carry one. pub access: Option, @@ -612,8 +618,8 @@ fn num(elem: Elem, lanes: u32) -> Operand { } impl Texture { - /// Parse the part of a name after `air.`. Returns the current-form template; a read also - /// has a [`Form::Legacy`] alternative ([`Texture::alternative`]). + /// Parse the part of a name after `air.`. Returns the current-form template; a read and a 2D + /// or 3D atomic also have a [`Form::Legacy`] alternative ([`Texture::alternative`]). pub(super) fn parse(rest: &str) -> Option { let (head, tail) = match rest.split_once('.') { Some((h, t)) => (h, Some(t)), @@ -689,10 +695,15 @@ impl Texture { (t.valid() && ulong_stem == ulong_atomic).then_some(t) } - /// The other operand form a declaration of the same name may have (a read's legacy form). + /// The other operand form a declaration of the same name may have (a read's, or a 2D or 3D + /// atomic's, legacy form). pub(super) fn alternative(self) -> Option { - let current_read = self.op == TexOp::Read && self.form == Form::Current; - current_read.then_some(Texture { + let legacy = match self.op { + TexOp::Read => true, + TexOp::Atomic(_) => matches!(self.image.dim, ImageDim::D2 | ImageDim::D3), + _ => false, + }; + (legacy && self.form == Form::Current).then_some(Texture { form: Form::Legacy, ..self }) @@ -879,7 +890,8 @@ impl Texture { l.push(R::Access, access); } TexOp::Atomic(op) => { - let has_offset = matches!(shape.dim, ImageDim::D2 | ImageDim::D3); + let has_offset = + matches!(shape.dim, ImageDim::D2 | ImageDim::D3) && self.form == Form::Current; l.push(R::Texture, tex); // A store passes its value first (MSL `atomic_store(value, coord)`). l.push_if(op == AtomicOp::Store, R::Value, texel); diff --git a/crates/metal2vulkan/src/tests/engine_texture_atomic_unk.rs b/crates/metal2vulkan/src/tests/engine_texture_atomic_unk.rs index 00c74a251..eab9c663d 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_atomic_unk.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_atomic_unk.rs @@ -13,7 +13,10 @@ //! texel against the image's size on every profile (Metal's out-of-bounds exchange fails and //! leaves `expected`), and writes lane 0 back; //! - a result is Metal's `(old, 0, 0, 1)` and a compare-exchange writes lane 0 of `expected` -//! only (measured), so results and `expected` read past lane 0 lower. +//! only (measured), so results and `expected` read past lane 0 lower; +//! - a 2D, 2D array or 3D atomic in the legacy form, without the offset position (the AIR +//! macOS 26.6's Metal on x86-64 hands its device), compiles as the same atomic with a zero +//! offset. //! //! Previously every kernel but the 2D `fetch_max` was refused `UnknownIntrinsic`, so these tests //! fail without it. A profile without a format's atomic feature refuses with the typed device gap, @@ -390,3 +393,160 @@ fn every_lane_of_results_and_expected_lowers() { } assert!(compiled >= 18, "{compiled}"); } + +/// The arguments of an argument or parameter list, split at the commas outside `()` and `<>`. +fn split_args(list: &str) -> Vec<&str> { + let (mut out, mut depth, mut start) = (Vec::new(), 0i32, 0); + for (i, c) in list.char_indices() { + match c { + '(' | '<' => depth += 1, + ')' | '>' => depth -= 1, + ',' if depth == 0 => { + out.push(list[start..i].trim()); + start = i + 1; + } + _ => {} + } + } + out.push(list[start..].trim()); + out +} + +/// `line` in the legacy atomic form when it declares or calls a 2D, 2D array or 3D texture +/// atomic: the offset position dropped, with whether the line is the declaration. The dropped +/// argument is checked to be the zero offset vector. +fn legacy_atomic_line(line: &str) -> Option<(String, bool)> { + let at = line.find("@air.atomic_")?; + let name_len = line[at..].find('(')?; + let name = &line[at + "@air.atomic_".len()..at + name_len]; + let (op, rest) = name.split_once("_explicit_texture_")?; + let shape = rest.split('.').next()?; + if !matches!(shape, "2d" | "2d_array" | "3d") { + return None; + } + // The offset follows the texture, a store's value, the coordinate and the layer. + let offset = 2 + usize::from(op == "store") + usize::from(shape == "2d_array"); + let open = at + name_len; + let mut depth = 0; + let close = line[open..].char_indices().find_map(|(i, c)| { + depth += match c { + '(' => 1, + ')' => -1, + _ => 0, + }; + (depth == 0).then_some(open + i) + })?; + let mut args = split_args(&line[open + 1..close]); + let dropped = args.remove(offset); + let declaration = line.starts_with("declare "); + assert!( + dropped.starts_with("<2 x i") || dropped.starts_with("<3 x i"), + "{name}: position {offset} is {dropped:?}, not an offset" + ); + assert!( + declaration || dropped.ends_with("zeroinitializer"), + "{name}: the offset {dropped:?} is not zero" + ); + let rewritten = format!( + "{}({}){}", + &line[..open], + args.join(", "), + &line[close + 1..] + ); + Some((rewritten, declaration)) +} + +/// `text` with every 2D, 2D array and 3D texture atomic in the legacy form +/// ([`legacy_atomic_line`]), and the number of declarations and calls rewritten. +fn legacy_atomics(text: &str) -> (String, usize, usize) { + let (mut decls, mut calls) = (0, 0); + let mut out = String::with_capacity(text.len()); + for line in text.lines() { + match legacy_atomic_line(line) { + Some((rewritten, declaration)) => { + if declaration { + decls += 1; + } else { + calls += 1; + } + out.push_str(&rewritten); + } + None => out.push_str(line), + } + out.push('\n'); + } + (out, decls, calls) +} + +/// A 2D, 2D array or 3D texture atomic in the legacy form, without the offset position (the AIR +/// macOS 26.6's Metal on x86-64 hands its device), compiles as the same atomic with a zero +/// offset: the owned atomic fixtures (every operation, `uint` and `int`, 16-bit coordinates, +/// compare-exchange, store, `ulong` `min` and `max`) with every offset dropped compile on the same +/// profiles, with the same strategies and the same image atomics. Without the legacy form such a +/// declaration matches no layout of its name and is refused `UnknownIntrinsic`. +#[test] +fn legacy_texture_atomics_without_the_offset_compile_alike() { + use metal2vulkan_devtools::llvm_assemble_text; + let mut compiled = 0; + for (stem, entry) in [ + ("unk_atomic_ops", "unk_atomic_ops"), + ("unk_atomic_lanes", "unk_atomic_lanes"), + ("unk_ulong_atomics", "unk_ulong_atomics"), + ("trh_texture_atomic", "trh_texture_atomic"), + ] { + let Some(current) = fixture(stem) else { + return; + }; + let text = std::fs::read_to_string(engine_dir().join(format!("{stem}.ll"))).expect("read"); + let (legacy_text, decls, calls) = legacy_atomics(&text); + assert!( + decls > 0 && calls >= decls, + "{stem}: {decls} declarations, {calls} calls" + ); + let legacy = match llvm_assemble_text(&legacy_text) { + Ok(b) => b, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected legacy {stem}: {why}"), + }; + for (profile, p) in profiles() { + let what = format!("{profile}: legacy {stem}"); + let a = artifact(¤t, entry, &profile, &p); + let b = artifact(&legacy, entry, &profile, &p); + let (Some(a), Some(b)) = (a.as_ref(), b.as_ref()) else { + assert_eq!(a.is_some(), b.is_some(), "{what}"); + continue; + }; + compiled += 1; + let uses = |x: &FunctionArtifact| { + x.strategies + .entries + .iter() + .map(|(k, u)| (k.clone(), u.uses)) + .collect::>() + }; + assert_eq!(uses(a), uses(b), "{what}: strategies"); + for op in [ + OP_IMAGE_TEXEL_POINTER, + OP_ATOMIC_LOAD, + OP_ATOMIC_EXCHANGE, + OP_ATOMIC_COMPARE_EXCHANGE, + OP_ATOMIC_I_ADD, + OP_ATOMIC_I_SUB, + OP_ATOMIC_S_MIN, + OP_ATOMIC_U_MIN, + OP_ATOMIC_S_MAX, + OP_ATOMIC_U_MAX, + OP_ATOMIC_AND, + OP_ATOMIC_OR, + OP_ATOMIC_XOR, + ] { + assert_eq!(count(a, op), count(b, op), "{what}: opcode {op}"); + } + assert_eq!(image_formats(a), image_formats(b), "{what}"); + } + } + assert!(compiled >= 12, "{compiled}"); +}