Translator: a seq_cst atomic operation takes the sequentially consistent fence

A seq_cst atomic operation on memory another thread reaches (an AIR 2.9 air.atomic.* buffer
atomic of order 5, its success order for a compare-exchange; an LLVM atomic load, store,
atomicrmw or cmpxchg of seq_cst) now takes the fence the landed seq_cst fence lowers to: an
acquire-release memory barrier at the operation's scope over the memories its order applies to,
then lower::sync::barrier's add of 1 on the device's fence word at Device scope with the
barrier's semantics. A store, a read-modify-write and a compare-exchange take it after the
operation; a load takes it before. Thread memory's atomics take none (no other invocation
observes their order); texture atomics of any order but relaxed stay refused; relaxed, acquire,
release and acq_rel operations are unchanged.

The fence before a load, derived: the stores' fences alone order every pair of fenced stores and
forbid store buffering and the R and 2+2W shapes, but two readers may still see two independent
seq_cst stores in opposite orders (IRIW), since a reader's two acquire loads synchronize with
nothing between them. MSL's single total order forbids that outcome. With an add on the one
fence word before each load, the two readers' second adds are ordered on that word; the earlier
reader's first load acquired its store, which then happens before the later reader's add and so
its second load, which must see it. A fence after a load would order nothing more.

Each such operation now costs one contended add on the device word: the runtime README's fence
known-gap line says so (every non-explicit atomic of MSL 4.1 is one), read from the fence's
measured rows. msl_4_1_orders_reach_spirv expects the fence's add after a27_wide_and_float's
float add and after each of a27_fragment_atomics' three atomics. reach.tsv drops the SeqCstFence
row, whose refusal no longer exists. The identity harness maps the device's fence word
(with_fence_word: its 4 bytes past the zero range, the rest still unmapped), and
engine_atomics' run_orders binds every kernel with it: the interpreter trapped on the fence's
add in the two contention tests whose kernels hold LLVM seq_cst atomics. SEMANTICS_VERSION
2367 (renumbered at landing; 2363-2366 went to arm 9, the blob move, the 1D bicubic and
the shared slice): a module holding a seq_cst atomic operation changes.

Verified:
- red 389e7cf44e, job m3-max-85066: a_seq_cst_atomic_operation_takes_the_fence fails at "a
  fence's barrier" (no add follows the store); the fence tests and msl_4_1_orders_reach_spirv
  pass. Green there: 4 passed.
- the product suite at the fix without the harness's fence word (85066): 3495 passed, 3 failed,
  24 skipped. The failures were golden_hashes_match_the_table (re-blessed on development) and
  engine_atomics' llvm_ and narrow_atomics_are_exact_under_contention, whose interpreter trapped
  on the unmapped fence word. With it (85271): engine_atomics, engine_seq_cst and
  engine_air_2_9 28 passed.
- validation 1344 passed, 2 skipped; conformance 1053 passed, 0 skipped; doctests EXIT=0
  (85066).
- clippy plain 85270, m2v_gpu 85269 and m2v_cpu_icd 85268 EXIT=0 at this tree. Rustdoc and
  api-docs 85093 EXIT=0 at the fix without the harness change, which adds test code only.
This commit is contained in:
Anees Iqbal committed 2026-12-03 13:12:57 -08:00
1 parent 7463025bc2
commit 5dc5ea3315
7 files changed
+91 -15

No files matched your search

+8 -2
View File
@@ -4565,7 +4565,13 @@ cache is answered compile-required on both.
the device shares (`metal2vulkan::pipeline::SEQ_CST_FENCE_WORD` bytes past the zero range the
runtime pushes as `PushField::ZeroAddress`), at `Device` scope, which totally orders them. A
threadgroup or simdgroup fence takes the same device word, so it pays the same contention,
though Metal orders it only within its threadgroup or simdgroup. Measured on device fences (a
though Metal orders it only within its threadgroup or simdgroup. A `seq_cst` atomic operation on
device or threadgroup memory takes the same barrier and add, after a store, a read-modify-write
or a compare-exchange, and before a load (so that no two loads of one thread see two other
threads' stores in the order another thread's two loads invert). Every non-explicit atomic of
MSL 4.1 (`atomic_store`, `atomic_load`, `atomic_fetch_add` and the rest) is one, as is an
`_explicit` atomic of `memory_order_seq_cst` and an LLVM atomic of `seq_cst`: a function built
for MSL 4.1 pays one contended add for each such atomic it executes. Measured on device fences (a
synthetic kernel of 1,048,576 invocations, each doing N rounds of integer work, a relaxed
atomic store, the fence and a relaxed atomic load; median of 9 alternated rounds, the fence
alone against the fence and its add), the add costs a fixed time per fence executed: on an RTX
@@ -4573,7 +4579,7 @@ cache is answered compile-required on both.
times); on a Radeon RX 7900 XTX 0.0143 against 0.0205 ms at 0 (1.43 times) and 1.005 times at
64; on an Iris Xe 1.015 times at 0 and 1.032 at 64; within 1% on all three from N = 1024. A
kernel that does little but such fences runs slower by that much; the threadgroup and simdgroup
fences' cost is read from these device rows, not measured apart. The add is a memory write of
fences' cost, and the atomic operations', is read from these device rows, not measured apart. The add is a memory write of
the function's (`StageInterface::writes_memory`), so a function whose only write it is counts as
one that writes memory: a dispatch of such a kernel runs where a kernel without writes runs
nothing, such a fragment function in a pipeline of more than one sample carries
+1 -1
View File
@@ -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 = 2366;
pub const SEMANTICS_VERSION: u32 = 2367;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
+51 -4
View File
@@ -57,7 +57,8 @@
//! arena (an LLVM `syncscope("singlethread")` atomic takes the same scope, which is only stronger,
//! as is an MSL 4.1 device atomic of a narrower `thread_scope`). A relaxed order (LLVM `monotonic`
//! or `unordered`) has no semantics; another order names memories at the Vulkan order (`seq_cst` is
//! `AcquireRelease`; a load keeps only the acquire part and a store only the release part), with
//! `AcquireRelease` and its fence below; a load keeps only the acquire part and a store only the
//! release part), with
//! `MakeAvailable`/`MakeVisible` under the Vulkan memory model (`sync::barrier::semantics`). The
//! memories are the call's Metal `mem_flags` when the AIR 2.9 form carries them (`UniformMemory`
//! for `mem_device`, `WorkgroupMemory` for `mem_threadgroup` and `mem_threadgroup_imageblock` in a
@@ -66,7 +67,15 @@
//! the function has no tile; a vertex function has no threadgroup memory, and only an object or
//! mesh function has `mem_object_data`'s, its payload, so those name nothing elsewhere), and the
//! atomic's own memory (`UniformMemory` or `WorkgroupMemory`) for an AIR 2.8 or LLVM atomic. A
//! `Device`-scope atomic is reported to the memory-model family. Metal's `volatile` qualifier and
//! `Device`-scope atomic is reported to the memory-model family. A `seq_cst` operation on memory
//! another thread reaches (MSL 4.1's non-explicit atomics are `seq_cst` over every memory) also
//! takes the sequentially consistent fence (`sync::barrier`'s total order): an acquire-release
//! memory barrier at its scope over its memories, then the add on the device's fence word, after
//! a store, a read-modify-write or a compare-exchange, and before a load. Store-side fences
//! alone forbid store buffering but not two loads that see two independent stores in opposite
//! orders (independent reads of independent writes), which MSL's single total order of every
//! thread's observations forbids; the fence before a load puts one of the device word's adds
//! between such a thread's two loads. Metal's `volatile` qualifier and
//! LLVM's `volatile` add nothing: an atomic is never elided or merged. A relaxed load that an exit
//! of a loop holding it depends on (a spin's, [`spin`]) acquires its own memory: with robust buffer
//! access, Mesa's RADV and ANV never showed a relaxed one a store that arrived after its first
@@ -215,6 +224,10 @@ pub struct AtomicAccess {
/// A relaxed load an exit of a loop holding it depends on ([`spin`]): it acquires its own
/// memory.
pub spin: bool,
/// A `seq_cst` operation on memory another thread reaches, which takes the sequentially
/// consistent fence (the module docs' total order): after a store, a read-modify-write or a
/// compare-exchange, before a load.
pub total: bool,
}
impl AtomicAccess {
@@ -277,7 +290,13 @@ impl AtomicAccess {
// The leaf's load and store around the operation.
AtomicMem::Private(a) => a.leaf.cost().saturating_mul(2).saturating_add(op),
};
per.saturating_add(compare).saturating_add(16)
let total = match self.total {
true => barrier::TOTAL_ORDER_WORDS + 8,
false => 0,
};
per.saturating_add(compare)
.saturating_add(16)
.saturating_add(total)
}
/// Whether the atomic opens a builder loop (a thread atomic never does: its operation is
@@ -435,6 +454,8 @@ struct Request {
compare: Option<CompareOperand>,
order: MemoryOrder,
failure: MemoryOrder,
/// The operation's order is `seq_cst` (its success order, for a compare-exchange).
seq_cst: bool,
/// An AIR 2.9 atomic's `mem_flags`; `None` for an AIR 2.8 or LLVM atomic.
flags: Option<MemFlags>,
}
@@ -483,6 +504,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result<Option<Request>, Error> {
compare,
order: order(a.order),
failure: a.failure.map_or(MemoryOrder::Relaxed, order),
seq_cst: a.order == AirOrder::SeqCst,
flags: a.flags,
}
}
@@ -504,6 +526,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result<Option<Request>, Error> {
compare: None,
order: llvm_order(atomic.ordering),
failure: MemoryOrder::Relaxed,
seq_cst: atomic.ordering == Ordering::SeqCst,
flags: None,
}
}
@@ -529,6 +552,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result<Option<Request>, Error> {
compare: Some(CompareOperand::Value(*cmp)),
order: llvm_order(success.ordering),
failure: llvm_order(*failure),
seq_cst: success.ordering == Ordering::SeqCst,
flags: None,
}
}
@@ -546,6 +570,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result<Option<Request>, Error> {
compare: None,
order: llvm_order(a.ordering),
failure: MemoryOrder::Relaxed,
seq_cst: a.ordering == Ordering::SeqCst,
flags: None,
},
InstKind::Store {
@@ -563,6 +588,7 @@ fn request(cx: &SelectCx<'_>, inst: &Inst) -> Result<Option<Request>, Error> {
compare: None,
order: llvm_order(a.ordering),
failure: MemoryOrder::Relaxed,
seq_cst: a.ordering == Ordering::SeqCst,
flags: None,
},
_ => return Ok(None),
@@ -691,6 +717,9 @@ pub fn select(
};
let spin =
r.kind == AtomicKind::Load && r.order == MemoryOrder::Relaxed && spin::is_spin(cx, at);
if r.seq_cst {
barrier::total_order(cx);
}
Ok(Some(AtomicAccess {
mem,
kind: r.kind,
@@ -702,6 +731,7 @@ pub fn select(
order: r.order,
failure: r.failure,
spin,
total: r.seq_cst,
// Threadgroup memory is a kernel's, an object function's, a mesh function's, and a
// fragment function's tile (device memory in the pass's buffer, which emission orders as
// such); a vertex function has none. The payload `mem_object_data` names is an object or
@@ -766,8 +796,9 @@ fn private(cx: &mut SelectCx<'_>, inst: &Inst, r: Request) -> Result<AtomicAcces
order: r.order,
failure: r.failure,
flags: r.flags,
// Thread memory: no other invocation stores to it.
// Thread memory: no other invocation stores to it, nor observes its order.
spin: false,
total: false,
})
}
@@ -1236,6 +1267,19 @@ pub fn emit(
Some(f) => (f, a.order),
None => (own, a.order),
};
// A `seq_cst` operation's fence: an acquire-release barrier at its scope over the memories
// its order applies to, then the add on the device's fence word, before a load and after any
// other operation.
let fence = a
.total
.then(|| barrier::semantics(flags, MemoryOrder::AcquireRelease, model));
let total_fence = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, sem| -> BResult<()> {
fb.memory_barrier(scope, sem)?;
barrier::add_to_fence_word(cx, fb, sem)
};
if let Some(sem) = fence.filter(|_| a.kind == AtomicKind::Load) {
total_fence(cx, fb, sem)?;
}
let o = Op {
kind: a.kind,
scope,
@@ -1342,6 +1386,9 @@ pub fn emit(
}
}
};
if let Some(sem) = fence.filter(|_| a.kind != AtomicKind::Load) {
total_fence(cx, fb, sem)?;
}
let Some(old) = result else {
return Ok(());
};
@@ -429,9 +429,11 @@ fn under(vulkan: bool, semantics: u32) -> u32 {
type Op = (&'static str, Vec<u32>);
/// MSL 4.1's orders and memory flags reach SPIR-V: a non-explicit atomic is `AcquireRelease` (a
/// load's acquire, a store's release half) over every memory the stage has, and an explicit one its
/// order over the memories it names, on a device whose simdgroup is its subgroup. The kernel of
/// barrier scopes, `a27_memory_order`, holds a sequentially consistent fence and is refused.
/// load's acquire, a store's release half) over every memory the stage has, and takes the
/// sequentially consistent fence, whose add on the device's fence word has the same semantics; an
/// explicit one is its order over the memories it names, on a device whose simdgroup is its
/// subgroup. The kernel of barrier scopes, `a27_memory_order`, holds a sequentially consistent
/// fence.
#[test]
fn msl_4_1_orders_reach_spirv() {
let path = engine_dir().join("a27_memory_order.ll");
@@ -472,18 +474,24 @@ fn msl_4_1_orders_reach_spirv() {
"a27_wide_and_float",
vec![
("OpAtomicUMax", vec![1, 0]),
// The float add's compare-and-swap loop: its acquiring read, then the exchange.
// The float add's compare-and-swap loop: its acquiring read, then the exchange;
// then its fence's add, the add being `seq_cst`.
("OpAtomicLoad", vec![1, 0x2 | 0x40]),
("OpAtomicCompareExchange", vec![1, 0x8 | every, 0]),
("OpAtomicIAdd", vec![1, 0x8 | every]),
],
),
(
// A render stage has no threadgroup memory.
// A render stage has no threadgroup memory. Each of its three `seq_cst` atomics
// takes its fence's add.
"a27_fragment_atomics",
vec![
("OpAtomicIAdd", vec![1, 0x8 | render]),
("OpAtomicLoad", vec![1, 0x2 | render]),
("OpAtomicStore", vec![1, 0x4 | render]),
("OpAtomicIAdd", vec![1, 0x8 | render]),
("OpAtomicIAdd", vec![1, 0x8 | render]),
("OpAtomicIAdd", vec![1, 0x8 | render]),
],
),
];
@@ -150,9 +150,11 @@ fn resources(plan: &Plan, init: &[Vec<u32>], threads: u32) -> Resources {
}
}
/// Run in both scheduling orders; returns each order's buffers as words.
/// Run in both scheduling orders, the device's fence word mapped for the `seq_cst` operations;
/// returns each order's buffers as words.
fn run_orders(m: &TypedModule, res: &Resources) -> Result<Vec<Vec<Vec<u32>>>, InterpError> {
let res = &super::identity_harness::bind(m, res.clone(), &BTreeMap::new());
let bound = super::identity_harness::bind(m, res.clone(), &BTreeMap::new());
let res = &super::identity_harness::with_fence_word(bound);
let mut outs = Vec::new();
for order in [Order::Forward, Order::Reverse] {
let cfg = Config {
@@ -201,6 +201,20 @@ fn fill(
res
}
/// `res` with the device's sequentially consistent fence word mapped: 4 zero bytes at
/// [`SEQ_CST_FENCE_WORD`] past the unmapped zero range [`fills`] names, which each `seq_cst` fence
/// and atomic operation adds to, the rest of that range still unmapped.
///
/// [`SEQ_CST_FENCE_WORD`]: crate::pipeline::SEQ_CST_FENCE_WORD
pub(crate) fn with_fence_word(mut res: Resources) -> Resources {
res.buffers.push(Buffer {
slot: None,
address: Some(ZERO_UNMAPPED + crate::pipeline::SEQ_CST_FENCE_WORD),
bytes: vec![0; 4],
});
res
}
/// The device address of [`with_zero`]'s zero range.
pub(crate) const ZERO: u64 = 0x7_0000_0000;
-1
View File
@@ -139,5 +139,4 @@ feature ProgramScopeSharedSlot rare MSL 3.2 program-scope buffers aliasing anoth
feature ProgramScopeLinked rare MSL 3.2 program-scope bindings in a linked visible function or a dynamic library
feature ProgramScopeRead none a read of a program-scope buffer's global that Apple's compiler is not seen to write
feature GenericPointer system MSL 4.1 generic pointers held in memory or of two spaces (macOS 27 and later)
feature SeqCstFence rare a seq_cst fence in a vertex or fragment stage without its stores and atomics
feature WideLines none a line under the Apple-private setLineWidth: at a width other than 1 drawn as the band, whose pipeline form the translator does not build (a selected slice or viewport, barycentric weights, multiview, synthesized geometry, too many stage outputs)
Can't render this file because it contains an unexpected character in line 17 and column 65.