From 0b1053f0ccb0d6b59a8d5e9512705e5f135fa7e1 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 22 Nov 2026 21:11:24 -0800 Subject: [PATCH] Translator: a threadgroup load or store at a constant offset outside the arena is a zero load or no store An unchecked threadgroup arena access whose offset is a plain constant outside the arena built an OpAccessChain into the arena's word array with a constant index past its length, which the SPIR-V builder rejects (OperandRule::Range), so the function failed with an internal error instead of translating or refusing. Such an access lies outside every threadgroup object, which Metal leaves undefined, so it is now decided at translation time as a contained arena's constant access is: a zero load, or no store. The decision reads the offset and the arena's size as plain constants and interns nothing, so every access inside the arena, and every module that built before, is unchanged; an arena whose size is a specialization constant is never decided this way (its word array has no constant length to break). The shape: Apple's compiler, knowing t == 0 in a branch, writes tg[t - 1u] of a static threadgroup array at arena offset 0 as element 0xFFFFFFFF, a wrapped arena offset of 0xFFFFFFFC. It is the whole of the translation census's internal errors at da020e5d7b (18 functions in 4 libraries on all five profiles, kindcount's m3-max-69549): each a load of an i32 word from a static [N x i32] or [N x float] threadgroup global through an inbounds GEP [0, 4294967295], in a branch, on the arena's u32 words. SEMANTICS_VERSION 2277: those functions' outcome moves from an internal error to a module. Verified: probe m3-max-69624 (base da020e5d7b plus a report at the builder's range rule) found that one site and shape for all 18 rows; probe m3-max-69654 reproduced the same internal error from owned MSL. The new test drives a load and a store at element 4294967295 of a 64-word threadgroup array through from_queries on four profiles, in an arena of u32 words and one of float words, and checks L3 and the interpreter's answers (the load reads 0, no word takes the store). --- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/lower/access/local.rs | 32 +++++++- .../src/tests/engine_threadgroup_floats.rs | 81 ++++++++++++++++++- docs/API.md | 4 +- 4 files changed, 115 insertions(+), 4 deletions(-) diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 21ab5c70f..f4d29c40d 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2276; +pub const SEMANTICS_VERSION: u32 = 2277; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/access/local.rs b/crates/metal2vulkan/src/lower/access/local.rs index 13405a806..fbf44a4f0 100644 --- a/crates/metal2vulkan/src/lower/access/local.rs +++ b/crates/metal2vulkan/src/lower/access/local.rs @@ -44,7 +44,10 @@ //! **Bounds** of an arena access are checked unless the arena is threadgroup memory on a profile //! whose `ThreadgroupMemory` is `Native` ([`contained`]): there no threadgroup access is contained, an arena's, its atomics', memory //! intrinsics', pointer cells' and imageblock's alike, nor a typed threadgroup object's index, and -//! one past the memory is undefined, as in Metal (no robustness feature covers arenas). Contained, +//! one past the memory is undefined, as in Metal (no robustness feature covers arenas). An +//! unchecked load or store at a constant offset outside the arena, which lies outside every object +//! in it and may lie past its words, where no access chain may index with a constant, is a zero +//! load or no store, as a contained one is. Contained, //! with `inb` the normative check against the arena's exact byte //! size, a load reads at `select(inb, off, 0)` and yields `select(inb, v, 0)`, and a store sits in //! a builder-closed `if_(inb)`. A dereference of a null private pointer (undefined in Metal) reads @@ -2033,6 +2036,15 @@ pub(super) fn emit_access_at( mem: ArenaMem(decl, ops), kept, }; + // An unchecked access at a constant offset outside the arena lies outside every object in it, + // where Metal leaves the access undefined, and no access chain may index the arena's words + // with a constant past them: it is a zero load or no store, as a contained one is. + if !a.contained && outside_arena(fb, off, &decl, u64::from(leaf.bytes))? { + return match stored { + None => leaf::zero(fb, &leaf).map(Some), + Some(_) => Ok(None), + }; + } if decl.floats { return float_words(cx, fb, (a, decl, ops), off, stored); } @@ -2076,6 +2088,24 @@ pub(super) fn emit_access_at( } } +/// Whether a `bytes`-byte access at `off` lies outside `decl`'s arena by the normative check +/// (`contain::in_bounds`), decided at translation time: `off` and the arena's size are plain +/// constants. `false` when either is not one. +fn outside_arena( + fb: &mut FunctionBuilder<'_>, + off: SValue, + decl: &ArenaDecl, + bytes: u64, +) -> BResult { + let Some(off) = fb.const_scalar(off)? else { + return Ok(false); + }; + let Some(ConstBits(size)) = fb.module().consts().scalar_bits(decl.size) else { + return Ok(false); + }; + Ok(size < bytes || off > size - bytes) +} + /// Load or store (`stored`) `a`'s leaf, whole `float` words, at byte offset `off` of an arena of /// `float` words (`ArenaDecl::floats`, the module docs): lane `j` of `lanes` at word /// `off / 4 + j`, one typed access each, uncontained. diff --git a/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs b/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs index 4aaaedef0..16f9d77b1 100644 --- a/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs +++ b/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs @@ -10,8 +10,11 @@ //! - The array is Metal's allocation: a region filling `maxComputeSharedMemorySize` is planned, one //! byte more is refused, and a static arena's array is its own words. An arena filling the limit //! answers every word. +//! - A load or store at a constant offset outside the arena is a zero load or no store, in either +//! form of the arena. //! -//! An access past threadgroup memory is undefined, in Metal as here; no test reads one. +//! An access past threadgroup memory at a run-time offset is undefined, in Metal as here; no test +//! reads one. //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. @@ -577,3 +580,79 @@ fn an_arena_filling_the_limit_answers_every_word_in_range() { } } } + +/// Thread `t` of 64 stores `t + 100` at word `t` of the static `[64 x float]` global as a `TY`, +/// stores a `TY` at the global's element 4294967295, a constant offset (`0xFFFFFFFC`, wrapped) +/// outside the arena, loads it, and loads word `t` back: `out[t]` is the outside load and +/// `out[64 + t]` word `t`. `TO`, `FROM_Y` and `FROM_Z` convert to and from `TY`. +const OUTSIDE: &str = r#" %w = and i32 %t, 63 + %v = add i32 %w, 100 + %x = TO + %pa = getelementptr inbounds TY, ptr addrspace(3) BASE, i32 %w + store TY %x, ptr addrspace(3) %pa, align 4 + %past = getelementptr inbounds [64 x float], ptr addrspace(3) BASE, i64 0, i64 4294967295 + store TY %x, ptr addrspace(3) %past, align 4 + %y = load TY, ptr addrspace(3) %past, align 4 + %z = load TY, ptr addrspace(3) %pa, align 4 + %yo = FROM_Y + %zo = FROM_Z + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %t + store i32 %yo, ptr addrspace(1) %o, align 4 + %t64 = add i32 %t, 64 + %o2 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %t64 + store i32 %zo, ptr addrspace(1) %o2, align 4 + ret void +"#; + +/// A threadgroup load and store at a constant offset outside the arena ([`OUTSIDE`]) are a zero +/// load and no store, through `from_queries`, in an arena of `u32` words (`int` accesses) and in +/// one of `float` words: the module builds and passes L3, the outside load reads 0, and no word +/// of the arena takes the outside store. +#[test] +fn a_constant_threadgroup_offset_outside_the_arena_loads_zero_and_stores_nothing() { + let forms = [ + ( + "i32", + ["add i32 %v, 0", "add i32 %y, 0", "add i32 %z, 0"], + TgWords::Composed, + "", + ), + ( + "float", + [ + "uitofp i32 %v to float", + "fptoui float %y to i32", + "fptoui float %z to i32", + ], + TgWords::Floats, + ".floats", + ), + ]; + let want: Vec = std::iter::repeat_n(0, 64).chain(100..164).collect(); + for (ty, [to, from_y, from_z], words, census_suffix) in forms { + let body = OUTSIDE + .replace("TY", ty) + .replace("FROM_Y", from_y) + .replace("FROM_Z", from_z) + .replace("TO", to); + let Some(bc) = assemble("tg_static", &static_of(64, &body)) else { + return; + }; + for stem in PROFILES { + let prof = queried(stem); + let what = format!("{ty} accesses on {stem}"); + let a = compile(&bc, "tg_static", &prof).unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, &prof).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let (plan, m) = typed_module(&bc, "tg_static", &prof).expect("module"); + let tg = plan.families.access.local.tg.as_ref().expect("an arena"); + assert_eq!(tg.words, words, "{what}"); + let census = plan.census(); + for name in ["access.threadgroup.load", "access.threadgroup.store"] { + let name = format!("{name}{census_suffix}"); + assert!(census.contains_key(&name), "{what}: {name} in {census:?}"); + } + let got = run_both(&m, &resources_of(&plan, &[], want.len())); + assert_eq!(got, want, "{what}"); + } + } +} diff --git a/docs/API.md b/docs/API.md index d1d9a3bd4..01e79c0c4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -650,7 +650,9 @@ through buffer arguments it reads at any index. - **Threadgroup memory.** No threadgroup memory access is bounded: a load or store, atomic, memory intrinsic, pointer cell or imageblock access of a threadgroup arena, and a typed threadgroup object's index, run as the program states them, and - one past the memory is undefined, as in Metal. A kernel whose every threadgroup access is a + one past the memory is undefined, as in Metal. A load or store of the arena at a constant offset + outside it, undefined in Metal too, is a zero load or no store: no access chain may index the + arena's words with a constant past them. A kernel whose every threadgroup access is a whole, aligned `float` (a scalar or a vector of two to four), with no atomic, memory intrinsic, imageblock or pointer kept in it, and whose SIMD groups are not emulated, holds its threadgroup memory as a `Workgroup` array of `float`: each access is one typed load or store a lane, with no