From 3fbbadbc6ef14a14a5951c7677aad19e333a29fb Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 3 Dec 2026 10:51:23 -0800 Subject: [PATCH] Translator: a seq_cst fence adds to the device's fence word, so seq_cst fences are totally ordered Vulkan has no sequentially consistent order ("SequentiallyConsistent memory semantics is not supported and must not be used", vkspec 1.4.366, Memory Semantics), and an acquire-release fence lets two threads that each store and then load the other's word both read the old values, which Metal's seq_cst fence forbids: it "establishes a single total modification order of all tagged atomic operations" (MSL 6.16.1). Such a fence was refused, Unsupported{IdentityDomains} SeqCstFence; five kernels of the first-setup walk's library aa5e72671a992cea meet it, each with four air.atomic.fence(mem_device, seq_cst, device) (probe m3-max-84688). The planner's ruled form, one for every device: a seq_cst air.atomic.fence at any scope beyond the thread, an LLVM fence seq_cst, and a program's seq_cst barrier whose memory scope is the device keep the acquire-release barrier they had at their own scope, then add 1 with OpAtomicIAdd at Device scope, with the barrier's semantics, to the device's fence word. Adds to one word are totally ordered and each reads the one before it, so the earlier fence's add (a release) synchronizes with the later's (an acquire). Threadgroup and simdgroup fences take the device word too (planner, option A): a stronger order than Metal names, with no workgroup memory and no change to the threadgroup memory limit. The word: pipeline::SEQ_CST_FENCE_WORD (256) bytes past PushField::ZeroAddress, in the runtime's zero chunk: one per device (Core holds one Ring; the chunk is kept for the device's life and never given back), made with every buffer usage, read only in its first 16 bytes (a checked load's unit at ZeroAddress, psb::ZERO_RANGE_READ, and an indirect command buffer reset's index token of 0 bytes), its value never read. A function with such a fence reads ZeroAddress whether or not it checks an access (access::place_zero_address keeps it). No new push field. - lower::sync::barrier: total_order (selection: notes device scope, places ZeroAddress) and add_to_fence_word (emission); Fence and Barrier carry `total`; require_seq_cst and SEQ_CST_FORM deleted. lower::sync::memory_model: the LLVM fence's `total`. - error: IdentityCause::SeqCstFence deleted (the consumer names it nowhere: git grep -n 'SeqCstFence\|SEQ_CST\|seq_cst_fence' at reims-vgpu f054ad57c1 finds only C __ATOMIC_SEQ_CST). - Guards: psb.rs asserts ZERO_RANGE_READ <= SEQ_CST_FENCE_WORD at compile time; ring.rs asserts the word fits its chunk; the_fence_word_lies_past_the_zero_range_s_reads checks both readers. - Tests: the red test's threadgroup and simdgroup rows take the device add (option A); the identity, dispatch and MSL 4.1 tests compile a4_device_fence, device_fence_store and a27_memory_order where they asserted the refusal. - Validation: ToolingRequirement::SeqCstFence and executor_contract::seq_cst_fence retired, as the runtime runs the fence; a_seq_cst_fence_runs_through_the_runtime replaces the refusal test. - Docs: the runtime README moves the fence from the identity refusals to a known gap with the add's cost (RTX 3090 m3-max-84667, RX 7900 XTX m3-max-84666, Iris Xe m3-max-84668; device fences, standing for threadgroup and simdgroup ones too); docs/API.md and ring.rs say where the word lies. api_signatures.tsv blessed; REFUSALS.md regenerated, unchanged. - SEMANTICS_VERSION 2360 (2359 went to checked naming, which landed first), RUNTIME_VERSION 2565 (a runtime word added; renumbered 2566 below). Verified, potluck jobs on this branch rebased onto development 436dd1045e, each at a commit of the branch (whose later commits declare the MSL 4.1 barrier in the test, count 40 requirements, take RUNTIME 2566, satisfy clippy's assertions_on_constants and add the api_surface row): - m3-max-84728: the red test at the red commit, with the barrier declared, fails on the IdentityDomains SeqCstFence refusal (RED EXIT=100); validation 1344 passed, 2 skipped; conformance 1053 passed, 0 skipped; doctests EXIT=0. - m3-max-84778, at the tree of the branch's last commit: clippy plain EXIT=0; metal2vulkan, air, runtime, devtools and harness 3494 run, 3491 passed, 24 skipped, 3 failed: golden_hashes and the fixture inventory's parts 1 and 4, whose 45 moved cells are a27_memory_order, a4_device_fence and device_fence_store on each of 15 profiles, Unsupported{IdentityDomains} -> ok (re-blessed on development). The seq_cst test validates every module with spirv-val on every profile. - clippy -D warnings with the const assertions: plain m3-max-84758, --cfg m2v_gpu m3-max-84759, --cfg m2v_cpu_icd m3-max-84761, each EXIT=0; rustdoc and api-docs at the last commit's tree, m3-max-84817, EXIT=0. - Cells against the M3 Max's committed Metal observations: a4_device_fence (8ebbfe8893f9) and a27_memory_order (914fc7fd4040) Match on lavapipe (m3-max-84766) and on the Radeon 780M under its venue amd-780m-radv (m3-max-84772); a_seq_cst_fence_runs_through_the_runtime and a_fence_of_another_order_is_made_through_the_runtime pass on both. --- crates/metal2vulkan-runtime/README.md | 23 +- crates/metal2vulkan-runtime/src/ring.rs | 11 +- crates/metal2vulkan-validation/build.rs | 1 - .../src/candidate/tests/engine_compute.rs | 41 ++-- .../src/executor_contract.rs | 7 - .../src/executor_contract/seq_cst_fence.rs | 199 ------------------ .../src/requirement.rs | 42 +--- crates/metal2vulkan-validation/src/triage.rs | 18 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/error/mod.rs | 4 - crates/metal2vulkan/src/error/tests.rs | 6 +- crates/metal2vulkan/src/lower/access/mod.rs | 6 +- crates/metal2vulkan/src/lower/access/psb.rs | 6 + crates/metal2vulkan/src/lower/sync/barrier.rs | 98 ++++++--- .../src/lower/sync/memory_model.rs | 37 +++- crates/metal2vulkan/src/pipeline/mod.rs | 1 + crates/metal2vulkan/src/pipeline/sym.rs | 17 +- .../metal2vulkan/src/tests/engine_air_2_9.rs | 28 ++- .../metal2vulkan/src/tests/engine_dispatch.rs | 20 +- .../metal2vulkan/src/tests/engine_identity.rs | 40 ++-- .../metal2vulkan/src/tests/engine_seq_cst.rs | 56 +++-- crates/metal2vulkan/tests/api_signatures.tsv | 3 +- docs/API.md | 7 +- 23 files changed, 281 insertions(+), 392 deletions(-) delete mode 100644 crates/metal2vulkan-validation/src/executor_contract/seq_cst_fence.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index fe2e1be3c..a80206bed 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -4544,16 +4544,27 @@ cache is answered compile-required on both. yet; - Metal 4.1's `read(sampler, coord)` of an argument buffer's texture, through a constexpr sampler or a sampler argument: the golden table holds the refusal (`engine/kernel_read_through`'s - `rt_heap_zero`, `rt_heap_ow` and `rt_heap_arg`); - - a sequentially consistent fence (`atomic_thread_fence` of `memory_order_seq_cst` beyond the - thread, or a `seq_cst` barrier whose memory scope is the device), which Vulkan has no order - for (its memory model reads `SequentiallyConsistent` as acquire-release) ("a sequentially - consistent fence"): the translator test - `a_seq_cst_fence_is_refused_naming_its_form_under_the_identity_domains` asserts the text. + `rt_heap_zero`, `rt_heap_ow` and `rt_heap_arg`). The states-only plays of the 26 kept replay streams on lavapipe, each making every pipeline state its stream makes, refuse none of their render or compute states, a refusal under the identity domains among them. +- A sequentially consistent fence (`atomic_thread_fence` of `memory_order_seq_cst` beyond the + thread, at any scope, an LLVM `fence seq_cst`, or a `seq_cst` barrier whose memory scope is the + device) costs one contended atomic: Vulkan has no sequentially consistent order, so each such + fence keeps its acquire-release barrier and then adds 1 to one `u32` that every such fence of + 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 + 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 + 3090 0.0158 against 0.0331 ms at N = 0 (2.09 times) and 0.0188 against 0.0344 ms at 64 (1.83 + 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. - A 64-bit texture atomic (`atomic_min` or `atomic_max` on a `ulong` texture), which Metal's feature set tables give the Apple8 family and later ("GPU devices in the Apple8 family support 64-bit atomic minimum and maximum using ulong, on both buffers and textures, only on macOS"), diff --git a/crates/metal2vulkan-runtime/src/ring.rs b/crates/metal2vulkan-runtime/src/ring.rs index 2549b8ff6..33ef69821 100644 --- a/crates/metal2vulkan-runtime/src/ring.rs +++ b/crates/metal2vulkan-runtime/src/ring.rs @@ -41,7 +41,11 @@ //! //! Another, taken the same way, is the zero range ([`Ring::zero`]): zeros that no command and no //! buffer argument reaches, which a checked load of a buffer argument outside its buffer reads -//! (the translator's `PushField::ZeroAddress`), so it reads zero. +//! (the translator's `PushField::ZeroAddress`), so it reads zero. The same chunk holds the device's +//! fence word, `metal2vulkan::pipeline::SEQ_CST_FENCE_WORD` bytes in: one per device, since the +//! device has one ring and the chunk is never given back, which every sequentially consistent fence +//! adds 1 to, so those fences are totally ordered. No load reads past the chunk's first 16 bytes, +//! and nothing reads the word; its value may be any. //! //! A third is the whole execution range ([`Ring::whole`]): Metal's //! `MTLIndirectCommandBufferExecutionRange` of every command, location 0 and length `u32::MAX`, @@ -61,6 +65,8 @@ use std::sync::{Condvar, Mutex, OnceLock, PoisonError}; /// A chunk's length: the most one write takes. pub(crate) const CHUNK: u64 = 64 * 1024; +// The zero range's chunk holds the device's fence word. +const _: () = assert!(metal2vulkan::pipeline::SEQ_CST_FENCE_WORD + 4 <= CHUNK); /// A ring block's length. pub(crate) const BLOCK: u64 = 32 * CHUNK; /// The chunks of a block: a take that leaves fewer free asks the block-maker thread for the @@ -261,7 +267,8 @@ impl Ring { } /// The zero range's address (the module docs): a chunk of zeros taken as the nil buffer's - /// is, which nothing is bound to, so nothing writes it. A multiple of 16. + /// is, which nothing is bound to; only the fence word past its first 16 bytes is written, by + /// shaders' atomic adds. A multiple of 16. pub(crate) fn zero(&self, core: &Core) -> Result { self.kept(core, &self.zero, &[]) } diff --git a/crates/metal2vulkan-validation/build.rs b/crates/metal2vulkan-validation/build.rs index 3cf6c8341..032f2b149 100644 --- a/crates/metal2vulkan-validation/build.rs +++ b/crates/metal2vulkan-validation/build.rs @@ -88,7 +88,6 @@ fn main() { "src/executor_contract/rate_map/layout.rs", "src/executor_contract/rate_map/value.rs", "src/executor_contract/sample_rate.rs", - "src/executor_contract/seq_cst_fence.rs", "src/requirement.rs", "src/check/cfg_fact.rs", "src/observation_contract.rs", diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs index 75c8b852c..177ad5381 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs @@ -526,39 +526,44 @@ fn a_kernel_runs_through_the_runtime_with_its_linked_visible_functions() { assert_eq!(floats, expected); } -/// A sequentially consistent fence is refused through the runtime, typed, as -/// `ToolingRequirement::SeqCstFence` says of the case (`executor_contract::seq_cst_fence`): the -/// owned fixture `a4_device_fence` stores, fences at the device's scope in `seq_cst` order, and -/// stores again. The day the runtime runs it, this fails, and the requirement goes. +/// A sequentially consistent fence through the runtime: the owned fixture `a4_device_fence` +/// stores, fences at the device's scope in `seq_cst` order (its barrier, then its add to the +/// device's fence word past the zero range), and stores again; the runtime makes and runs it, and +/// its words are the stores'. #[cfg(target_os = "linux")] #[test] -fn a_seq_cst_fence_is_refused_through_the_runtime_as_its_requirement_says() { +fn a_seq_cst_fence_runs_through_the_runtime() { let bitcode = llvm_assemble(&engine_dir().join("a4_device_fence.ll")).unwrap(); let threads = Dispatch::Threads { threads: [8, 1, 1], threads_per_group: [8, 1, 1], }; - let mut fence = case("a4_device_fence", vec![0; 64], threads); + let input = (0..8u32).map(|t| t * 3 + 1).collect::>(); + let mut fence = case( + "a4_device_fence", + input.iter().flat_map(|word| word.to_le_bytes()).collect(), + threads, + ); fence.buffers.insert(1, vec![0; 64]); fence.output = ComputeOutput::Buffer { binding: 1, offset: 0, length: 64, }; - let error = run_on_runtime(&fence, &bitcode, &[]).unwrap_err(); - assert!(matches!(error, ExecutorError::NotSupported(_)), "{error}"); - assert!( - error - .to_string() - .contains("a sequentially consistent fence"), - "{error}" - ); + let output = run_on_runtime(&fence, &bitcode, &[]).unwrap().output; + let expected = input + .iter() + .map(|word| word + 1) + .chain(input.iter().map(|word| word * 2)) + .flat_map(u32::to_le_bytes) + .collect::>(); + assert_eq!(output, expected); } -/// The other way of [`a_seq_cst_fence_is_refused_through_the_runtime_as_its_requirement_says`]: -/// the owned fixture `rlm_runtime_limits`'s `rlm_fence_acq_rel` holds the same two stores around a -/// device-scope fence of `acq_rel` order, which carries no `ToolingRequirement::SeqCstFence`, and -/// the runtime makes and runs it: its words are the stores'. +/// The other order of [`a_seq_cst_fence_runs_through_the_runtime`]: the owned fixture +/// `rlm_runtime_limits`'s `rlm_fence_acq_rel` holds the same two stores around a device-scope +/// fence of `acq_rel` order, its barrier alone, and the runtime makes and runs it: its words are +/// the stores'. #[cfg(target_os = "linux")] #[test] fn a_fence_of_another_order_is_made_through_the_runtime() { diff --git a/crates/metal2vulkan-validation/src/executor_contract.rs b/crates/metal2vulkan-validation/src/executor_contract.rs index 9b0108047..6dabd7769 100644 --- a/crates/metal2vulkan-validation/src/executor_contract.rs +++ b/crates/metal2vulkan-validation/src/executor_contract.rs @@ -8,7 +8,6 @@ pub mod out_of_bounds; pub mod rate_map; pub mod render_target_array; pub mod sample_rate; -pub mod seq_cst_fence; pub mod sparse; pub mod stage_inputs; pub mod tessellation; @@ -694,9 +693,6 @@ pub fn unsupported_reflection_requirements( /// /// The Metal oracle: a compute kernel that samples with a `min_lod_clamp`, whose pipeline Apple's /// compiler cannot build ([`min_lod_clamp::kernel_min_lod_clamp_requirement`]). -/// -/// The engine's candidate again: a sequentially consistent fence, which the runtime refuses -/// ([`seq_cst_fence::seq_cst_fence_requirement`]). pub fn unsupported_source_requirements( source_ll: &str, reflection: &ShaderInterface, @@ -710,9 +706,6 @@ pub fn unsupported_source_requirements( requirements.extend(min_lod_clamp::kernel_min_lod_clamp_requirement( source_ll, reflection, )); - requirements.extend(seq_cst_fence::seq_cst_fence_requirement( - source_ll, reflection, - )); let calls = air_call_counts(source_ll); requirements.extend(unsupported_air_requirements(&calls)); requirements.extend(indirect_command_requirement( diff --git a/crates/metal2vulkan-validation/src/executor_contract/seq_cst_fence.rs b/crates/metal2vulkan-validation/src/executor_contract/seq_cst_fence.rs deleted file mode 100644 index 2f586e078..000000000 --- a/crates/metal2vulkan-validation/src/executor_contract/seq_cst_fence.rs +++ /dev/null @@ -1,199 +0,0 @@ -//! A sequentially consistent fence. -//! -//! The translator orders a `seq_cst` fence, and a program's `seq_cst` barrier whose memory scope is -//! the device, with every other such fence of the command buffer through an acquire-release -//! increment of one word of its execution status buffer (`lower::sync::barrier`). The runtime's -//! identity domains reach no such word: its pipeline is refused as `Unsupported{IdentityDomains}`, -//! naming the fence ("a sequentially consistent fence"), so the engine's candidate does not run the -//! case ([`ToolingRequirement::SeqCstFence`]). The Metal oracle runs it. -//! -//! The scan reads the entry's function and the functions it reaches by direct calls, which its -//! pipeline compiles, as the `min_lod_clamp` scan does. A call counts in the forms the translator -//! takes the word for: `air.atomic.fence` of order `seq_cst` (5) at a scope other than the thread -//! (a threadgroup scope only in a stage with a threadgroup), and a barrier in the MSL 4.1 form (its -//! three operands carry an order) of order `seq_cst` whose memory scope is the device or the -//! legacy all-devices scope; each names a memory (`mem_device`, `mem_threadgroup`, `mem_texture` -//! or `mem_threadgroup_imageblock`), without which it orders nothing and emits no fence. A -//! barrier of the AIR 2.8 form orders memory at its own execution scope, never the device's, and -//! is no claim. A call whose operands are not constant integers is no claim. - -use super::min_lod_clamp::{direct_callee, function_bodies}; -use crate::air::reflect::{ShaderInterface, ShaderStage}; -use crate::requirement::ToolingRequirement; -use metal2vulkan_air::intrinsics::{AirIntrinsic, Sync}; -use std::collections::BTreeSet; - -/// The `seq_cst` memory order's immediate. -const SEQ_CST: u64 = 5; -/// The memories a fence orders that the translator emits a fence for (`mem_device`, -/// `mem_threadgroup`, `mem_texture`, `mem_threadgroup_imageblock`). -const ORDERED_MEMORIES: u64 = 0xf; -/// The `thread_scope` immediates: thread, threadgroup, device, all devices. -const THREAD: u64 = 0; -const THREADGROUP: u64 = 1; -const DEVICE: u64 = 2; -const ALL_DEVICES: u64 = 3; - -/// [`ToolingRequirement::SeqCstFence`] when a call the pipeline of `reflection`'s entry compiles -/// is a sequentially consistent fence ([`takes_the_status_word`]). -pub fn seq_cst_fence_requirement( - source_ll: &str, - reflection: &ShaderInterface, -) -> Option { - let threadgroup = matches!( - reflection.stage, - ShaderStage::Kernel | ShaderStage::Object | ShaderStage::Mesh - ); - reflection - .entry_point - .as_deref() - .is_some_and(|entry| fences(source_ll, entry, threadgroup)) - .then_some(ToolingRequirement::SeqCstFence) -} - -/// Whether a call in the function `entry` of `source_ll`, or in a function it reaches by direct -/// calls, takes the execution status word ([`takes_the_status_word`]); `threadgroup` says whether -/// the stage has a threadgroup. A module that does not define `entry` has none. -pub fn fences(source_ll: &str, entry: &str, threadgroup: bool) -> bool { - if !source_ll.contains("@air.atomic.fence") - && !source_ll.contains("@air.wg.barrier") - && !source_ll.contains("@air.simdgroup.barrier") - { - return false; - } - let bodies = function_bodies(source_ll); - let Some((&entry, _)) = bodies.get_key_value(entry) else { - return false; - }; - let mut reached = BTreeSet::from([entry]); - let mut pending = vec![entry]; - while let Some(function) = pending.pop() { - for callee in bodies[function] - .iter() - .filter_map(|text| direct_callee(text)) - { - if let Some((&callee, _)) = bodies.get_key_value(callee) { - if reached.insert(callee) { - pending.push(callee); - } - } - } - } - reached - .iter() - .flat_map(|function| &bodies[function]) - .any(|text| takes_the_status_word(text, threadgroup)) -} - -/// Whether the instruction `text` is a barrier or fence call in a form the translator orders -/// through the execution status word (the module documentation's). -pub fn takes_the_status_word(text: &str, threadgroup: bool) -> bool { - let Some(at) = text.find("call ") else { - return false; - }; - let call = &text[at..]; - let Some(name_start) = call.find("@air.").map(|at| at + 1) else { - return false; - }; - let Some(name_length) = call[name_start..].find('(') else { - return false; - }; - let Some(AirIntrinsic::Sync(sync)) = - AirIntrinsic::parse(&call[name_start..name_start + name_length]) - else { - return false; - }; - let arguments = &call[name_start + name_length + 1..]; - let Some(arguments) = arguments.rfind(')').map(|end| &arguments[..end]) else { - return false; - }; - let immediates: Option> = super::split_top_level(arguments) - .into_iter() - .map(|operand| operand.trim().strip_prefix("i32 ")?.trim().parse().ok()) - .collect(); - let Some(&[flags, order, scope]) = immediates.as_deref() else { - return false; - }; - if order != SEQ_CST || flags & ORDERED_MEMORIES == 0 { - return false; - } - match sync { - Sync::Fence { .. } => scope != THREAD && (scope != THREADGROUP || threadgroup), - Sync::Barrier { .. } => matches!(scope, DEVICE | ALL_DEVICES), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn module(body: &str) -> String { - format!( - "declare void @air.atomic.fence(i32, i32, i32)\n\ - declare void @air.wg.barrier(i32, i32)\n\ - define void @k() {{\nentry:\n{body}\n ret void\n}}\n" - ) - } - - /// The forms the translator orders through the status word are claimed, at each scope the - /// fence orders beyond its thread, and in a function the entry calls. - #[test] - fn a_seq_cst_fence_beyond_its_thread_is_claimed() { - for scope in [1, 2, 3, 4] { - let text = module(&format!( - " call void @air.atomic.fence(i32 1, i32 5, i32 {scope})" - )); - assert!(fences(&text, "k", true), "scope {scope}"); - } - let barrier = module(" call void @air.wg.barrier(i32 2, i32 5, i32 2)"); - assert!(fences(&barrier, "k", true)); - let callee = "declare void @air.atomic.fence(i32, i32, i32)\n\ - define internal void @f() {\nentry:\n call void @air.atomic.fence(i32 4, i32 5, i32 2)\n ret void\n}\n\ - define void @k() {\nentry:\n call void @f()\n ret void\n}\n"; - assert!(fences(callee, "k", true)); - } - - /// No claim for a fence the translator emits without the word: another order, the thread's - /// scope, no memory, a threadgroup scope in a stage without one, a barrier of the AIR 2.8 form - /// or of a threadgroup memory scope, a call outside the entry's reach, or a run-time operand. - #[test] - fn a_fence_the_translator_orders_without_the_word_is_no_claim() { - let unclaimed = [ - " call void @air.atomic.fence(i32 1, i32 4, i32 2)", - " call void @air.atomic.fence(i32 1, i32 0, i32 2)", - " call void @air.atomic.fence(i32 1, i32 5, i32 0)", - " call void @air.atomic.fence(i32 0, i32 5, i32 2)", - " call void @air.atomic.fence(i32 16, i32 5, i32 2)", - " call void @air.wg.barrier(i32 1, i32 1)", - " call void @air.wg.barrier(i32 1, i32 5, i32 1)", - " call void @air.wg.barrier(i32 1, i32 4, i32 2)", - " call void @air.atomic.fence(i32 1, i32 %order, i32 2)", - ]; - for body in unclaimed { - assert!(!fences(&module(body), "k", true), "{body}"); - } - let threadgroup = module(" call void @air.atomic.fence(i32 2, i32 5, i32 1)"); - assert!(fences(&threadgroup, "k", true)); - assert!(!fences(&threadgroup, "k", false)); - let unreached = "declare void @air.atomic.fence(i32, i32, i32)\n\ - define internal void @f() {\nentry:\n call void @air.atomic.fence(i32 1, i32 5, i32 2)\n ret void\n}\n\ - define void @k() {\nentry:\n ret void\n}\n"; - assert!(!fences(unreached, "k", true)); - assert!(!fences(&module(""), "missing", true)); - } - - /// The two public fixtures whose runs the runtime refuses for the word carry it: a - /// device-scope `seq_cst` fence between two stores, and MSL 4.1's barrier of `seq_cst` order - /// at the device's memory scope. - #[test] - fn the_public_fixtures_the_runtime_refuses_for_the_word_are_claimed() { - let engine = metal2vulkan_devtools::engine_dir(); - for (name, entry) in [ - ("a4_device_fence.ll", "a4_device_fence"), - ("a27_memory_order.ll", "a27_memory_order"), - ] { - let text = std::fs::read_to_string(engine.join(name)).unwrap(); - assert!(fences(&text, entry, true), "{name}"); - } - } -} diff --git a/crates/metal2vulkan-validation/src/requirement.rs b/crates/metal2vulkan-validation/src/requirement.rs index eaab3644f..436579df8 100644 --- a/crates/metal2vulkan-validation/src/requirement.rs +++ b/crates/metal2vulkan-validation/src/requirement.rs @@ -148,18 +148,6 @@ pub enum ToolingRequirement { /// the authored compile census still compiles an object or mesh case's pipeline /// (`engine::prepare_compile`). MeshRenderPipeline, - /// A sequentially consistent fence its entry's pipeline compiles - /// (`executor_contract::seq_cst_fence`): an `atomic_thread_fence` of `memory_order_seq_cst` - /// that orders a memory beyond its thread, or a `seq_cst` barrier of the MSL 4.1 form whose - /// memory scope is the device. The translator orders such a fence with the command buffer's - /// other ones through an atomic on its execution status word, which the runtime's identity - /// domains do not reach: the runtime refuses the pipeline (`Unsupported{IdentityDomains}`, - /// naming the fence, "a sequentially consistent fence"), so the limit is the runtime's - /// ([`Limit::Runtime`]) and the engine's candidate does not run the case. The device tests - /// `candidate::tests::engine_compute::a_seq_cst_fence_is_refused_through_the_runtime_as_its_requirement_says` - /// and `..::a_fence_of_another_order_is_made_through_the_runtime` hold it both ways. The Metal - /// oracle runs it, so a case of it stays Metal-qualified ([`Self::qualifies_on_metal`]). - SeqCstFence, /// A visible function table bound to a vertex or fragment function (`executor_contract`'s /// `engine_source_requirements` and `case_requirements`): function pointers called from a /// render pipeline, which Metal lets a program ask for through @@ -309,7 +297,6 @@ impl ToolingRequirement { Self::MeshCompanion, Self::DepthOutsideUnitRange, Self::MeshRenderPipeline, - Self::SeqCstFence, Self::RenderFunctionTable, Self::IndexBufferPastEnd, Self::UlongTextureAtomic, @@ -356,7 +343,6 @@ impl ToolingRequirement { Self::MeshCompanion => "mesh_companion", Self::DepthOutsideUnitRange => "depth_outside_unit_range", Self::MeshRenderPipeline => "mesh_render_pipeline", - Self::SeqCstFence => "seq_cst_fence", Self::RenderFunctionTable => "render_function_table", Self::IndexBufferPastEnd => "index_buffer_past_end", Self::UlongTextureAtomic => "ulong_texture_atomic", @@ -392,10 +378,10 @@ impl ToolingRequirement { /// implementation's private layout where the engine's module decodes this crate's, and a /// depth outside `[0, 1]` a case gives a depth image, which the runtime puts nowhere /// ([`ToolingRequirement::DepthOutsideUnitRange`]), and a mesh render pipeline it does not - /// draw ([`ToolingRequirement::MeshRenderPipeline`]), and a sequentially consistent fence, a - /// render function's function table, an indexed draw past its index buffer, a 64-bit texture - /// atomic and separate depth and stencil attachments, which the runtime refuses - /// ([`ToolingRequirement::SeqCstFence`], [`ToolingRequirement::RenderFunctionTable`], + /// draw ([`ToolingRequirement::MeshRenderPipeline`]), and a render function's function + /// table, an indexed draw past its index buffer, a 64-bit texture atomic and separate depth + /// and stencil attachments, which the runtime refuses + /// ([`ToolingRequirement::RenderFunctionTable`], /// [`ToolingRequirement::IndexBufferPastEnd`], [`ToolingRequirement::UlongTextureAtomic`], /// [`ToolingRequirement::SeparateDepthStencil`]). /// @@ -425,7 +411,6 @@ impl ToolingRequirement { | Self::RasterizationRateMapPlacement | Self::DepthOutsideUnitRange | Self::MeshRenderPipeline - | Self::SeqCstFence | Self::RenderFunctionTable | Self::IndexBufferPastEnd | Self::UlongTextureAtomic @@ -457,7 +442,7 @@ impl ToolingRequirement { /// Whose limit this requirement records. Every requirement is this crate's tooling's except /// [`ToolingRequirement::KernelMinLodClamp`], which Apple's compiler cannot build a pipeline - /// for, and [`ToolingRequirement::SeqCstFence`], [`ToolingRequirement::DepthOutsideUnitRange`], + /// for, and [`ToolingRequirement::DepthOutsideUnitRange`], /// [`ToolingRequirement::MeshRenderPipeline`], [`ToolingRequirement::RenderFunctionTable`], /// [`ToolingRequirement::IndexBufferPastEnd`], [`ToolingRequirement::UlongTextureAtomic`], /// [`ToolingRequirement::SeparateDepthStencil`], [`ToolingRequirement::KernelImageblock`], @@ -472,8 +457,7 @@ impl ToolingRequirement { pub const fn limit(self) -> Limit { match self { Self::KernelMinLodClamp => Limit::Metal, - Self::SeqCstFence - | Self::DepthOutsideUnitRange + Self::DepthOutsideUnitRange | Self::MeshRenderPipeline | Self::RenderFunctionTable | Self::IndexBufferPastEnd @@ -635,19 +619,6 @@ mod tests { assert!(requirement.qualifies_on_metal(), "{requirement}"); } - /// A sequentially consistent fence: the Metal oracle runs it, so its cases stay - /// Metal-qualified; the runtime refuses it, so the engine's candidate runs none, the runtime's - /// limit, which closes its rows. - #[test] - fn a_seq_cst_fence_stops_only_the_candidate() { - let requirement = ToolingRequirement::SeqCstFence; - assert_eq!(requirement.stops(), [Executor::EngineCandidate]); - assert_eq!(requirement.limit(), Limit::Runtime, "{requirement}"); - assert!(!requirement.blocks_closure(), "{requirement}"); - assert!(requirement.qualifies_on_metal(), "{requirement}"); - assert_eq!("seq_cst_fence".parse(), Ok(requirement)); - } - /// A render function's function table: the Metal oracle draws it, so its cases stay /// Metal-qualified; the runtime's render pipeline state reads none, so the engine's candidate /// runs none, the runtime's limit, which closes its rows. @@ -811,7 +782,6 @@ mod tests { [ ToolingRequirement::DepthOutsideUnitRange, ToolingRequirement::MeshRenderPipeline, - ToolingRequirement::SeqCstFence, ToolingRequirement::RenderFunctionTable, ToolingRequirement::IndexBufferPastEnd, ToolingRequirement::UlongTextureAtomic, diff --git a/crates/metal2vulkan-validation/src/triage.rs b/crates/metal2vulkan-validation/src/triage.rs index 39d257fc6..0d62939e7 100644 --- a/crates/metal2vulkan-validation/src/triage.rs +++ b/crates/metal2vulkan-validation/src/triage.rs @@ -1456,9 +1456,9 @@ entry: ToolingRequirement::KernelMinLodClamp, ToolingRequirement::RenderDeviceBufferArray, ]); - let runtime_refused = with(&[ToolingRequirement::SeqCstFence]); + let runtime_refused = with(&[ToolingRequirement::UlongTextureAtomic]); let runtime_refused_and_gap = with(&[ - ToolingRequirement::SeqCstFence, + ToolingRequirement::UlongTextureAtomic, ToolingRequirement::RenderDeviceBufferArray, ]); write_cached( @@ -1500,9 +1500,10 @@ entry: /// The owned fixture `rlm_runtime_limits` holds each shape of a requirement the runtime refuses /// beside the same shape without it, as its device tests run them - /// (`candidate::tests::engine_compute`): the `acq_rel` fence carries no `seq_cst_fence`, which - /// `a4_device_fence`'s `seq_cst` fence carries; and the read of a texture buffer an argument - /// buffer holds carries what the same read of a 2D member carries, as the runtime makes both. + /// (`candidate::tests::engine_compute`): the read of a texture buffer an argument buffer holds + /// carries what the same read of a 2D member carries, as the runtime makes both; and the + /// `acq_rel` fence carries what `a4_device_fence`'s `seq_cst` fence carries, as the runtime + /// makes both. #[test] fn the_runtime_limit_fixture_holds_each_shape_beside_its_pair() { let engine = metal2vulkan_devtools::engine_dir(); @@ -1520,11 +1521,10 @@ entry: requirements(limits, "rlm_member_texture_buffer"), requirements(limits, "rlm_member_texture") ); - assert!( - !requirements(limits, "rlm_fence_acq_rel").contains(&ToolingRequirement::SeqCstFence) + assert_eq!( + requirements(limits, "rlm_fence_acq_rel"), + requirements("a4_device_fence.ll", "a4_device_fence") ); - assert!(requirements("a4_device_fence.ll", "a4_device_fence") - .contains(&ToolingRequirement::SeqCstFence)); } #[test] diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index f7da77627..5433d9fe5 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 = 2359; +pub const SEMANTICS_VERSION: u32 = 2360; /// 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/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index b595a028f..4d0577cb1 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -1102,10 +1102,6 @@ pub enum IdentityCause { /// minimum level or emulated filter the function specializes, a bicubic filter of a 1D /// texture, or an anisotropic sampler slot whose filter the function emulates. SamplerState, - /// A sequentially consistent fence, which Vulkan has no order for: its memory model reads - /// `SequentiallyConsistent` as acquire-release, whose fence allows the store buffering Metal's - /// fence forbids. - SeqCstFence, /// A storage texture access the device takes only with a declared format, whose bound format /// no input names under the identity domains. StorageTextureFormat, diff --git a/crates/metal2vulkan/src/error/tests.rs b/crates/metal2vulkan/src/error/tests.rs index 6fbe3722e..4c83b5840 100644 --- a/crates/metal2vulkan/src/error/tests.rs +++ b/crates/metal2vulkan/src/error/tests.rs @@ -288,11 +288,11 @@ fn an_identity_refusal_names_its_cause() { u.to_string(), "IdentityDomains: StorageTextureFormat; needs NotImplemented" ); - let named = Unsupported::identity(IdentityCause::SeqCstFence) - .naming(DiagName::new("a sequentially consistent fence")); + let named = Unsupported::identity(IdentityCause::TextureState) + .naming(DiagName::new("a texture's swizzle")); assert_eq!( named.to_string(), - "IdentityDomains (a sequentially consistent fence): SeqCstFence; needs NotImplemented" + "IdentityDomains (a texture's swizzle): TextureState; needs NotImplemented" ); } diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 05251b394..80efe9fad 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -1072,7 +1072,9 @@ pub(crate) fn note_variable(cx: &mut SelectCx<'_>, slot: SlotRef, fixed: bool, r /// clamps its offset instead, and an atomic outside its buffer runs nothing. A read whose own /// offset the memory plan proves one value counts too: emission checks it where its emitted /// offset is not a constant (a select or a phi of pointers), which is not known before it, so -/// where every such read's emitted offset is a constant the field is placed and not read. +/// where every such read's emitted offset is a constant the field is placed and not read. A +/// `seq_cst` fence's add reaches the device's fence word past it too +/// (`sync::barrier::total_order`), so a function with one keeps the field. fn place_zero_address( cx: &mut SelectCx<'_>, lowering: &[Option], @@ -1085,7 +1087,7 @@ fn place_zero_address( .any(|(plan, l)| matches!(l, Some(SlotLowering::Psb { .. })) && checked_read(&plan.slot)); let pulled = (own.iter()).any(|(s, l)| matches!(l, SlotLowering::Psb { .. }) && checked_read(s)); - match shared || pulled { + match shared || pulled || cx.families.barrier.fence_word { true => cx.push.insert(PushField::ZeroAddress), false => cx.push.remove(&PushField::ZeroAddress), }; diff --git a/crates/metal2vulkan/src/lower/access/psb.rs b/crates/metal2vulkan/src/lower/access/psb.rs index 367ea5746..d9de5faaf 100644 --- a/crates/metal2vulkan/src/lower/access/psb.rs +++ b/crates/metal2vulkan/src/lower/access/psb.rs @@ -79,6 +79,12 @@ pub(super) fn add_slot_offset( fb.convert(ConvOp::Bitcast, words, address) } +/// The most bytes a load reads at the zero range (`PushField::ZeroAddress`) where its check fails: +/// one unit, of 1, 2, 4, 8 or 16 bytes, at the range's first byte ([`PsbMem::outside`]). The +/// device's fence word lies past them (`pipeline::SEQ_CST_FENCE_WORD`). +pub(crate) const ZERO_RANGE_READ: u64 = 16; +const _: () = assert!(ZERO_RANGE_READ <= crate::pipeline::SEQ_CST_FENCE_WORD); + /// A `u64` constant. pub fn k64(fb: &mut FunctionBuilder<'_>, v: u64) -> BResult { let ty = u64_ty(fb)?; diff --git a/crates/metal2vulkan/src/lower/sync/barrier.rs b/crates/metal2vulkan/src/lower/sync/barrier.rs index 5f5f1f210..9126429d0 100644 --- a/crates/metal2vulkan/src/lower/sync/barrier.rs +++ b/crates/metal2vulkan/src/lower/sync/barrier.rs @@ -30,10 +30,22 @@ //! `Subgroup`, threadgroup → `Workgroup`, device and the legacy all-devices scope → `Device`, //! the widest scope of one logical device) with the order (`seq_cst` is `AcquireRelease`, as in //! Vulkan). A fence that orders nothing another invocation can observe (a relaxed order, no -//! memory flag, or thread scope) emits nothing. A `seq_cst` fence, and a program's `seq_cst` -//! barrier whose memory scope is the device, is refused ([`require_seq_cst`]): Vulkan reads -//! `SequentiallyConsistent` as `AcquireRelease`, and Metal's fence forbids the store buffering -//! that order allows. +//! memory flag, or thread scope) emits nothing. +//! - **Sequentially consistent fences** ([`total_order`]). Vulkan has no sequentially consistent +//! order ("SequentiallyConsistent memory semantics is not supported and must not be used", the +//! Vulkan specification's memory model), and an acquire-release fence lets two threads that each +//! store and then load the other's word both read the old values (store buffering), which Metal's +//! `seq_cst` fence forbids: it "establishes a single total modification order of all tagged +//! atomic operations" (the Metal Shading Language specification, 6.16.1). So a `seq_cst` fence +//! at any scope, and a program's `seq_cst` barrier whose memory scope is the device, keeps its +//! acquire-release barrier at its own scope and then adds 1 to the device's fence word +//! ([`SEQ_CST_FENCE_WORD`] bytes past `PushField::ZeroAddress`) with an `OpAtomicIAdd` at +//! `Device` scope with the barrier's semantics. Adds to one word are totally ordered and each +//! reads the one before it, so of two such fences the earlier's add, a release, synchronizes +//! with the later's, an acquire: the later thread's loads see the earlier's stores. One word for +//! every scope orders more pairs than a simdgroup or threadgroup fence names, as Metal permits, +//! and needs no workgroup memory; every such fence pays the word's contention (the runtime's +//! known gaps). Its value is never read. //! - **Memory model**. Under the Vulkan memory model a barrier or fence that names memory also //! makes it available and visible (`MakeAvailable | MakeVisible`); under `GLSL450` it does not //! (those bits need the Vulkan model). The semantics are computed at emission from the plan's @@ -56,16 +68,16 @@ use crate::air::intrinsics::{ use crate::air::ir::{Callee, Inst, InstId, InstKind, Value, ValueId}; use crate::device::requirements::VkFeature; use crate::device::subgroup::{OpBits, SimdClass, Tier}; -use crate::error::{Capability, DiagName, Error, Feature, IdentityCause, LowerFamily, Unsupported}; +use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported}; use crate::lower::emit::EmitCx; use crate::lower::select::{FamilyPlans, Plan, SelectCx}; use crate::lower::strategy::{FamilyStrategy, Strategy}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::Stage; +use crate::pipeline::sym::{PushField, Stage, SEQ_CST_FENCE_WORD}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; -use crate::spirv::ir::{DerivOp, ExecMode, MemoryOrder, Scope, Semantics}; +use crate::spirv::ir::{AtomicOp, BinOp, DerivOp, ExecMode, MemoryOrder, Scope, Semantics}; use std::borrow::Cow; fn not_lowered() -> Error { @@ -128,6 +140,9 @@ pub struct Barrier { /// (`dispatch::KernelDecl::rows_may_split`), a condition of specialization constants alone, /// so it is uniform and a driver folds it. pub rows: bool, + /// A program's `seq_cst` barrier whose memory scope is the device: it adds 1 to the device's + /// fence word after the barrier ([`total_order`]). + pub total: bool, } /// Who placed a barrier. @@ -149,6 +164,9 @@ pub struct Fence { pub scope: Scope, pub flags: MemFlags, pub order: MemoryOrder, + /// A `seq_cst` fence: it adds 1 to the device's fence word after the barrier + /// ([`total_order`]). + pub total: bool, } /// A derivative of `value`. @@ -196,8 +214,10 @@ impl FamilyStrategy for BarrierStrategy { match self { // The instruction and its scope and semantics constants; a guarded one's local-size // test and selection. - BarrierStrategy::Barrier(b) => 16 + ROWS_GUARD_WORDS * u32::from(b.rows), - BarrierStrategy::Fence(_) => 12, + BarrierStrategy::Barrier(b) => { + 16 + ROWS_GUARD_WORDS * u32::from(b.rows) + TOTAL_ORDER_WORDS * u32::from(b.total) + } + BarrierStrategy::Fence(f) => 12 + TOTAL_ORDER_WORDS * u32::from(f.total), BarrierStrategy::NoFence => 0, BarrierStrategy::Derivative(_) => 4, } @@ -229,6 +249,9 @@ pub struct BarrierPlan { /// only pairs that meet where a simdgroup spans two rows of its threadgroup /// (`air::Lockstep::rows`): on a flattened tier the kernel records `RuntimeFact::RowLockstep`. pub rows_only: bool, + /// A `seq_cst` fence adds to the device's fence word ([`total_order`]): the function reads + /// `PushField::ZeroAddress`. + pub fence_word: bool, } /// Whether tangled instruction `v` depends on how subgroups reconverge: every one but a threadgroup @@ -416,7 +439,7 @@ fn select_barrier( && memory == Scope::Device && order != MemoryOrder::Relaxed; if seq_cst { - require_seq_cst(cx)?; + total_order(cx); } cx.tangled.insert(id); if scope == Scope::Workgroup { @@ -432,6 +455,7 @@ fn select_barrier( order, origin, rows: false, + total: seq_cst, })) } @@ -461,12 +485,13 @@ fn select_fence( crate::lower::sync::memory_model::note_device_scope(cx); } if seq_cst { - require_seq_cst(cx)?; + total_order(cx); } Ok(BarrierStrategy::Fence(Fence { scope, flags, order, + total: seq_cst, })) } @@ -474,19 +499,36 @@ fn select_fence( /// (`dispatch::KernelDecl::rows_may_split`), its constants, and the selection around the barrier. pub const ROWS_GUARD_WORDS: u32 = 40; -/// The form a sequentially consistent fence is refused as under the identity domains -/// ([`require_seq_cst`]). -pub(crate) const SEQ_CST_FORM: &str = "a sequentially consistent fence"; +/// The words an add to the device's fence word takes ([`add_to_fence_word`]): the zero range's +/// address, the offset and the sum, the word's place, and the add with its constants. +pub(crate) const TOTAL_ORDER_WORDS: u32 = 40; -/// A sequentially consistent fence: Vulkan has no sequentially consistent order (its memory model -/// reads `SequentiallyConsistent` as `AcquireRelease`), and an acquire-release fence lets two -/// threads that each store and then load the other's word both read the old values (store -/// buffering), which Metal's `seq_cst` fence forbids. The fence is refused as `IdentityDomains`, -/// not implemented, naming [`SEQ_CST_FORM`]. -pub fn require_seq_cst(_: &mut SelectCx<'_>) -> Result<(), Error> { - Err(Unsupported::identity(IdentityCause::SeqCstFence) - .naming(DiagName::new(SEQ_CST_FORM)) - .into()) +/// A sequentially consistent fence's total order (the module docs): its add goes to the device's +/// fence word, which the function reaches past `PushField::ZeroAddress` at `Device` scope. +pub fn total_order(cx: &mut SelectCx<'_>) { + // Under the Vulkan memory model a `Device`-scope atomic needs `vulkanMemoryModelDeviceScope`. + crate::lower::sync::memory_model::note_device_scope(cx); + cx.push.insert(PushField::ZeroAddress); + cx.families.barrier.fence_word = true; +} + +/// Add 1 to the device's fence word, [`SEQ_CST_FENCE_WORD`] bytes past `PushField::ZeroAddress`, +/// at `Device` scope with semantics `sem`, its fence's (the module docs' total order). The old +/// value is not read. +pub fn add_to_fence_word( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + sem: Semantics, +) -> BResult<()> { + let zero = cx.push_field(fb, PushField::ZeroAddress)?; + let offset = crate::lower::access::psb::k64(fb, SEQ_CST_FENCE_WORD)?; + let address = fb.binary(BinOp::IAdd, zero, offset)?; + let u32_ = fb.uint_ty(32)?; + let word = fb.device_place(address, u32_)?; + let one = fb.u32_const(1)?; + let one = fb.module().const_value(one)?; + fb.atomic(AtomicOp::IAdd, word, Scope::Device, sem, one)?; + Ok(()) } fn select_derivative( @@ -602,11 +644,19 @@ pub fn emit( } None => fb.control_barrier(scope, memory, sem)?, } + if b.total { + add_to_fence_word(cx, fb, sem)?; + } Ok(()) } BarrierStrategy::Fence(f) => { let scope = simdgroup_scope(cx.plan, f.scope); - fb.memory_barrier(scope, semantics(f.flags, f.order, model)) + let sem = semantics(f.flags, f.order, model); + fb.memory_barrier(scope, sem)?; + if f.total { + add_to_fence_word(cx, fb, sem)?; + } + Ok(()) } BarrierStrategy::NoFence => Ok(()), BarrierStrategy::Derivative(d) => { diff --git a/crates/metal2vulkan/src/lower/sync/memory_model.rs b/crates/metal2vulkan/src/lower/sync/memory_model.rs index d6b457b4e..51fe5d0b5 100644 --- a/crates/metal2vulkan/src/lower/sync/memory_model.rs +++ b/crates/metal2vulkan/src/lower/sync/memory_model.rs @@ -66,7 +66,8 @@ //! `Device` scope (the widest scope of one logical device, as for Metal's legacy all-devices //! fence) over every memory a stage can reach (`UniformMemory`, `ImageMemory`, and //! `WorkgroupMemory` in a kernel), with the ordering mapped as `air.atomic.fence`'s (`seq_cst` -//! is `AcquireRelease`, and a `seq_cst` fence is refused, `barrier::require_seq_cst`). +//! is `AcquireRelease`, and a `seq_cst` fence also adds to the device's fence word, +//! `barrier::total_order`). //! `unordered` and `monotonic` are //! not fence orderings in LLVM and never decode here; a relaxed ordering would emit nothing. @@ -90,8 +91,14 @@ use std::borrow::Cow; #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] pub enum MemoryModelStrategy { - /// A system-scope LLVM `fence`: `OpMemoryBarrier(Device, order | memories)`. - Fence { flags: MemFlags, order: MemoryOrder }, + /// A system-scope LLVM `fence`: `OpMemoryBarrier(Device, order | memories)`, and for a + /// `seq_cst` one (`total`) the add to the device's fence word after it + /// (`barrier::total_order`). + Fence { + flags: MemFlags, + order: MemoryOrder, + total: bool, + }, /// A single-thread fence: nothing is emitted. NoFence, } @@ -106,8 +113,10 @@ impl FamilyStrategy for MemoryModelStrategy { fn words(&self) -> u32 { match self { - // The instruction and its scope and semantics constants. - MemoryModelStrategy::Fence { .. } => 12, + // The instruction and its scope and semantics constants, and a `seq_cst` fence's add. + MemoryModelStrategy::Fence { total, .. } => { + 12 + barrier::TOTAL_ORDER_WORDS * u32::from(*total) + } MemoryModelStrategy::NoFence => 0, } } @@ -298,8 +307,9 @@ pub fn select( SyncScope::SingleThread => Ok(MemoryModelStrategy::NoFence), SyncScope::System => { note_device_scope(cx); - if a.ordering == Ordering::SeqCst { - barrier::require_seq_cst(cx)?; + let total = a.ordering == Ordering::SeqCst; + if total { + barrier::total_order(cx); } Ok(MemoryModelStrategy::Fence { flags: MemFlags { @@ -310,6 +320,7 @@ pub fn select( object_data: false, }, order, + total, }) } } @@ -323,9 +334,17 @@ pub fn emit( s: &MemoryModelStrategy, ) -> BResult<()> { match s { - MemoryModelStrategy::Fence { flags, order } => { + MemoryModelStrategy::Fence { + flags, + order, + total, + } => { let sem: Semantics = barrier::semantics(*flags, *order, barrier::memory_model(cx.plan)); - fb.memory_barrier(Scope::Device, sem) + fb.memory_barrier(Scope::Device, sem)?; + if *total { + barrier::add_to_fence_word(cx, fb, sem)?; + } + Ok(()) } MemoryModelStrategy::NoFence => Ok(()), } diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index dc9860054..936684291 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -166,6 +166,7 @@ pub use sym::{ AccelerationStructureLevel, AirUserKey, Axis, CombinedSampler, HandleClass, ImageAccess, ImageDim, ImageHandleClass, PushField, ResourceKind, ResourceSlot, SampledType, SamplerRef, SlotClass, SlotRef, SpecKey, Stage, StorageFormatClass, Symbol, SyntheticBinding, VaryingKey, + SEQ_CST_FENCE_WORD, }; pub use vertex::{PulledAttribute, VertexAttribute, VertexBinding, VertexInputState, VertexStride}; diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 2b92f56d6..7d20bd827 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -755,8 +755,11 @@ pub enum PushField { /// Under the identity domains, the device address (`u64`) of 16 bytes of zeros, at a multiple /// of 16, that nothing writes: a load of a buffer slot checked against its `SlotBounds` /// reads each of its units there where the check fails, so it reads zero (`docs/API.md`, - /// section 5). Being a multiple of 16 it is never `u64::MAX`, the value a floor stage whose - /// tail it is tests for (`lower::push::tail_never_pushed`). + /// section 5). [`SEQ_CST_FENCE_WORD`] bytes past it lies the device's fence word, one `u32` + /// per device that a `seq_cst` fence adds 1 to (`lower::sync::barrier`'s total order) and + /// nothing reads: the memory there is the consumer's, one block for the device's life, and its + /// first value may be any. Being a multiple of 16 it is never `u64::MAX`, the value a floor + /// stage whose tail it is tests for (`lower::push::tail_never_pushed`). ZeroAddress, /// Under the identity domains, a buffer slot's buffer (`uvec2`): the bytes of the buffer before /// the slot's bind offset (the bind offset), then the buffer's length; for a `set*Bytes` copy 0 @@ -777,6 +780,16 @@ pub enum PushField { TailWord, } +/// The offset past `PushField::ZeroAddress` of the device's fence word: one `u32`, at a multiple of +/// 4, that every sequentially consistent fence the device runs adds 1 to at `Device` scope, so +/// those fences are totally ordered (Metal's `memory_order_seq_cst` on `atomic_thread_fence`, which +/// Vulkan's memory model has no order for). The consumer's memory at the zero range's address +/// holds at least this many bytes and 4 more, one block for the device's life, of which no reader +/// of the zero range reads past its first 16 bytes and nothing reads the word; its value may start +/// as any and nothing depends on it. 256 bytes past the zeros, it lies on another cache line than +/// they do. +pub const SEQ_CST_FENCE_WORD: u64 = 256; + /// A relocatable literal: which decoration operand the serializer reserved, and for what. #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] diff --git a/crates/metal2vulkan/src/tests/engine_air_2_9.rs b/crates/metal2vulkan/src/tests/engine_air_2_9.rs index cc666a699..aaa9b9e8c 100644 --- a/crates/metal2vulkan/src/tests/engine_air_2_9.rs +++ b/crates/metal2vulkan/src/tests/engine_air_2_9.rs @@ -449,16 +449,24 @@ fn msl_4_1_orders_reach_spirv() { let every = 0x40 | 0x100 | 0x800; let render = 0x40 | 0x800; // `a27_memory_order` holds a `seq_cst` barrier at `thread_scope_device`, a sequentially - // consistent fence, which the identity domains refuse: a known gap of the runtime's. - match compile(&bc, "a27_memory_order", &p) { - Err(crate::error::Error::Unsupported(u)) => assert_eq!( - u.cause, - Some(crate::error::Cause::Identity( - crate::error::IdentityCause::SeqCstFence - )) - ), - other => panic!("a27_memory_order: {:?}", other.map(|_| ())), - } + // consistent fence: after its barrier it adds 1 to the device's fence word at `Device` scope + // with the barrier's semantics (`lower::sync::barrier`'s total order). + let a = + compile(&bc, "a27_memory_order", &p).unwrap_or_else(|e| panic!("a27_memory_order: {e}")); + let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("a27_memory_order: {e}")); + let text = spirv_dis(&words); + let vulkan = text.contains("OpMemoryModel Logical Vulkan"); + let device_barrier = ( + "OpControlBarrier".to_owned(), + vec![2, 1, under(vulkan, 0x8 | 0x40)], + ); + let fence_add = ( + "OpAtomicIAdd".to_owned(), + vec![1, under(vulkan, 0x8 | 0x40)], + ); + let ops = sync_operands(&text); + assert!(ops.contains(&device_barrier), "{text}"); + assert!(ops.contains(&fence_add), "{text}"); let cases: [(&str, Vec); 2] = [ ( "a27_wide_and_float", diff --git a/crates/metal2vulkan/src/tests/engine_dispatch.rs b/crates/metal2vulkan/src/tests/engine_dispatch.rs index d77596927..cf2a32119 100644 --- a/crates/metal2vulkan/src/tests/engine_dispatch.rs +++ b/crates/metal2vulkan/src/tests/engine_dispatch.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use crate::device::requirements::VkFeature; use crate::device::subgroup::{self, OpBits, SimdClass, SubgroupRequirement, Tier}; -use crate::error::{Capability, Cause, Error, Feature, IdentityCause, Needs}; +use crate::error::{Capability, Error, Feature, Needs}; use crate::lower::dispatch::{region_bytes, LocalSizeForm}; use crate::lower::select::Plan; use crate::pipeline::facts::RuntimeFact; @@ -127,24 +127,16 @@ fn run_word0(plan: &Plan, m: &TypedModule, d: &Dispatch) -> u32 { /// Every kernel compiles on every M1 profile where its simd tier exists, links, relocates, and /// passes L3; the artifact carries the dispatch facts and the specialization symbols of its -/// local-size form. `device_fence_store`'s device-scope `seq_cst` fence is the identity domains' -/// typed refusal naming it (a known gap of the runtime). +/// local-size form. `device_fence_store`'s device-scope `seq_cst` fence lowers too, adding to the +/// device's fence word (`lower::sync::barrier`'s total order). #[test] fn dispatch_kernels_compile_link_and_validate() { let Some(bc) = fixture() else { return }; for stem in PROFILES { let p = profile(stem).expect(stem); - match compile(&bc, "device_fence_store", &p) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::IdentityDomains, "{stem}"); - assert_eq!( - u.cause, - Some(Cause::Identity(IdentityCause::SeqCstFence)), - "{stem}" - ); - } - other => panic!("{stem} device_fence_store: {:?}", other.map(|a| a.key)), - } + let a = compile(&bc, "device_fence_store", &p) + .unwrap_or_else(|e| panic!("{stem} device_fence_store: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} device_fence_store: {e}")); for entry in MARKERS.iter().chain(&["threadgroup_barrier_store"]) { let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index b3bc1800b..bfa834358 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -4368,35 +4368,29 @@ fn a_constant_blob_past_the_modules_bound_is_refused_naming_its_size() { } } -/// A kernel whose device-scope `seq_cst` fence orders its two stores (`a4_device_fence`) is -/// refused, naming the fence ([`SEQ_CST_FORM`](crate::lower::sync::barrier::SEQ_CST_FORM)). +/// A kernel whose device-scope `seq_cst` fence orders its two stores (`a4_device_fence`) lowers +/// under the identity domains: the fence adds to the device's fence word past the zero range +/// (`lower::sync::barrier`'s total order), so the function reads `PushField::ZeroAddress`, and +/// the module passes the validator. #[test] -fn a_seq_cst_fence_is_refused_naming_its_form_under_the_identity_domains() { +fn a_seq_cst_fence_adds_to_the_device_s_fence_word_under_the_identity_domains() { let Some(bc) = assemble("a4_device_fence") else { return; }; for stem in PROFILES { let p = profile(stem).unwrap_or_else(|e| panic!("{e}")); - match compile(&bc, "a4_device_fence", &p) { - Err(Error::Unsupported(u)) => { - assert_eq!( - (u.feature, u.needs), - (Feature::IdentityDomains, Needs::NotImplemented), - "{stem}" - ); - assert_eq!( - u.cause, - Some(Cause::Identity(IdentityCause::SeqCstFence)), - "{stem}" - ); - assert_eq!( - u.symbol.map(|f| f.to_string()).as_deref(), - Some(crate::lower::sync::barrier::SEQ_CST_FORM), - "{stem}" - ); - } - other => panic!("{stem}: {:?}", other.map(|_| ())), - } + let (a, plan, _) = + compile_kept(&bc, "a4_device_fence", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + assert!( + plan.push + .fields + .iter() + .any(|f| f.field == PushField::ZeroAddress), + "{stem}: no zero range" + ); + let text = spirv_dis(&a.module.words); + assert_eq!(text.matches("OpAtomicIAdd").count(), 1, "{stem}\n{text}"); } } diff --git a/crates/metal2vulkan/src/tests/engine_seq_cst.rs b/crates/metal2vulkan/src/tests/engine_seq_cst.rs index a26463237..cbc438e9f 100644 --- a/crates/metal2vulkan/src/tests/engine_seq_cst.rs +++ b/crates/metal2vulkan/src/tests/engine_seq_cst.rs @@ -1,19 +1,20 @@ //! Sequentially consistent fences: a `seq_cst` `air.atomic.fence` (at simdgroup, threadgroup or //! device scope), a `seq_cst` barrier of the MSL 4.1 form whose memory scope is the device, and an -//! LLVM `fence seq_cst` keep the acquire-release barrier their order maps to and add one -//! acquire-release atomic add of 1, with the barrier's semantics, on one word every fence of its -//! scope shares (`lower::sync::barrier`'s total order): the threadgroup's word for a simdgroup or -//! threadgroup fence in a kernel, at `Workgroup` scope, and the device's fence word past -//! `PushField::ZeroAddress` (`pipeline::SEQ_CST_FENCE_WORD`) for a device one, at `Device` scope. An -//! `acq_rel`, `acquire` or `release` fence is the barrier alone. +//! LLVM `fence seq_cst` keep the acquire-release barrier their order maps to, at their own scope, +//! and add one acquire-release atomic add of 1, with the barrier's semantics, on the device's +//! fence word past `PushField::ZeroAddress` ([`SEQ_CST_FENCE_WORD`]), at `Device` scope, which +//! every such fence shares (`lower::sync::barrier`'s total order). An `acq_rel`, `acquire` or +//! `release` fence is the barrier alone. //! //! The kernel is the store-buffering litmus of our probe //! (`metal2vulkan_devtools::litmus::store_buffering`). use std::collections::{BTreeMap, BTreeSet}; +use crate::lower::access::psb::ZERO_RANGE_READ; use crate::pipeline::sym::PushField; use crate::pipeline::testing::{compile_kept, link_and_validate}; +use crate::pipeline::SEQ_CST_FENCE_WORD; use crate::spirv::testing::committed_profiles; use metal2vulkan_devtools::litmus::store_buffering; use metal2vulkan_devtools::{llvm_assemble_text, AssembleError}; @@ -27,11 +28,8 @@ const OP_CONTROL_BARRIER: u32 = 224; const OP_MEMORY_BARRIER: u32 = 225; const OP_ATOMIC_IADD: u32 = 234; -/// SPIR-V's `Device` and `Workgroup` scopes, and the `Workgroup` and `PhysicalStorageBuffer` -/// storage classes. +/// SPIR-V's `Device` scope and `PhysicalStorageBuffer` storage class. const DEVICE: u32 = 1; -const WORKGROUP: u32 = 2; -const CLASS_WORKGROUP: u32 = 4; const CLASS_PSB: u32 = 5349; /// Bitcode of `text` through `llvm-as`, or `None` (printing why) where it is missing. @@ -114,12 +112,12 @@ fn adds_and_barriers(words: &[u32]) -> (Vec, Vec) { } /// On every committed profile, each `seq_cst` fence of the store-buffering kernel keeps its -/// barrier and adds 1 at its scope to its scope's word, with the barrier's semantics: a device -/// fence (an `air.atomic.fence` at device scope, an LLVM `fence seq_cst`, and a `seq_cst` barrier -/// whose memory scope is the device) at `Device` scope through a `PhysicalStorageBuffer` pointer, -/// the function reading `PushField::ZeroAddress`; a threadgroup or simdgroup fence at `Workgroup` -/// scope on a `Workgroup` word. An `acq_rel`, `acquire` or `release` fence is its barrier alone, -/// with no add and no zero range. Every module passes the validator. +/// barrier and adds 1 to the device's fence word at `Device` scope through a +/// `PhysicalStorageBuffer` pointer, with the barrier's semantics, the function reading +/// `PushField::ZeroAddress`: an `air.atomic.fence` at device, threadgroup and simdgroup scope, an +/// LLVM `fence seq_cst`, and a `seq_cst` barrier whose memory scope is the device. An `acq_rel`, +/// `acquire` or `release` fence is its barrier alone, with no add and no zero range. Every module +/// passes the validator. #[test] fn a_seq_cst_fence_adds_to_its_scope_s_word_and_no_other_fence_does() { // (fence, the adds' scope and pointer class, or none) @@ -135,11 +133,11 @@ fn a_seq_cst_fence_adds_to_its_scope_s_word_and_no_other_fence_does() { ), ( " tail call void @air.atomic.fence(i32 1, i32 5, i32 1)", - Some((WORKGROUP, CLASS_WORKGROUP)), + Some((DEVICE, CLASS_PSB)), ), ( " tail call void @air.atomic.fence(i32 1, i32 5, i32 4)", - Some((WORKGROUP, CLASS_WORKGROUP)), + Some((DEVICE, CLASS_PSB)), ), ( " tail call void @air.atomic.fence(i32 1, i32 4, i32 2)", @@ -181,9 +179,8 @@ fn a_seq_cst_fence_adds_to_its_scope_s_word_and_no_other_fence_does() { }; assert_eq!(add, &expected, "{what}"); } - assert_eq!( + assert!( fields.contains(&PushField::ZeroAddress), - *scope == DEVICE, "{what}: {fields:?}" ); } @@ -195,3 +192,22 @@ fn a_seq_cst_fence_adds_to_its_scope_s_word_and_no_other_fence_does() { } } } + +/// The device's fence word lies past every byte a reader of the zero range reads: a checked +/// load's unit, at most [`ZERO_RANGE_READ`] bytes at the range's first byte, and an indirect +/// command buffer's reset command, whose index token binds the range with no bytes. +#[test] +fn the_fence_word_lies_past_the_zero_range_s_reads() { + assert!(ZERO_RANGE_READ <= SEQ_CST_FENCE_WORD); + assert_eq!(SEQ_CST_FENCE_WORD % 4, 0); + let layout = crate::pipeline::IndirectDrawLayout::new(2, 2).expect("a layout"); + let zero = 0x1000_u64; + let command = layout.reset_command(0, zero); + let at = layout.index() as usize; + assert_eq!( + command[at..at + 8], + zero.to_le_bytes(), + "the index token's address" + ); + assert_eq!(command[at + 8..at + 12], [0; 4], "the index token's bytes"); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 5cced5b1c..36f343818 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -408,6 +408,7 @@ const metal2vulkan::pipeline::COMPILED_STAGE_WEIGHT pub const COMPILED_STAGE_WEI const metal2vulkan::pipeline::DEEP_THREADGROUP pub const DEEP_THREADGROUP: u32 const metal2vulkan::pipeline::GRID_TILE_THREADS pub const GRID_TILE_THREADS: u32 const metal2vulkan::pipeline::NONUNIFORM pub const NONUNIFORM: u32 +const metal2vulkan::pipeline::SEQ_CST_FENCE_WORD pub const SEQ_CST_FENCE_WORD: u64 const-value metal2vulkan-air::bitstream::BLOCKINFO_BLOCK_ID 0 const-value metal2vulkan-air::bitstream::TOP_LEVEL_ABBREV_WIDTH 2 const-value metal2vulkan-air::budget::BITSTREAM_NESTING 64 @@ -470,6 +471,7 @@ const-value metal2vulkan::pipeline::COMPILED_STAGE_WEIGHT 39_014 const-value metal2vulkan::pipeline::DEEP_THREADGROUP 64 const-value metal2vulkan::pipeline::GRID_TILE_THREADS 256 const-value metal2vulkan::pipeline::NONUNIFORM 1 +const-value metal2vulkan::pipeline::SEQ_CST_FENCE_WORD 256 enum metal2vulkan-air::abi::AbiHandle #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum AbiHandle enum metal2vulkan-air::abi::AbiInt #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AbiInt enum metal2vulkan-air::abi::AccelerationStructureKind #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum AccelerationStructureKind @@ -9709,7 +9711,6 @@ variant metal2vulkan::error::IdentityCause::EncoderValue EncoderValue variant metal2vulkan::error::IdentityCause::HeapResource HeapResource variant metal2vulkan::error::IdentityCause::ObjectOrMeshStage ObjectOrMeshStage variant metal2vulkan::error::IdentityCause::SamplerState SamplerState -variant metal2vulkan::error::IdentityCause::SeqCstFence SeqCstFence variant metal2vulkan::error::IdentityCause::StorageTextureFormat StorageTextureFormat variant metal2vulkan::error::IdentityCause::TextureState TextureState variant metal2vulkan::error::ImageblockCause::CellPointer CellPointer diff --git a/docs/API.md b/docs/API.md index cd6ededa6..dc80e4cd3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1237,7 +1237,12 @@ for dependency in &pipeline.dependencies { shorter than one access push a length that every such access past it fails. An access at a constant offset, and an access through a pointer loaded from memory or made from an integer, is not checked. A runtime writes `SlotBounds` from the bound buffer; `ZeroAddress` is the runtime's - own memory. What the check costs, measured on the runtime against the same build with the check + own memory, one block for the device's life that holds at least `pipeline::SEQ_CST_FENCE_WORD` + bytes and 4 more: past the zeros, at that offset, lies the device's fence word, which every + sequentially consistent fence adds 1 to at `Device` scope, so those fences are totally ordered + (Vulkan's memory model has no sequentially consistent order); no load reads it, and it may start + at any value. A function with such a fence reads `ZeroAddress` for it whether or not it checks + an access. What the check costs, measured on the runtime against the same build with the check removed (release, no validation layer): in the compute harness's GPU time, `wide_bindings` 34.7% slower on a Radeon 780M, 38.5% on an RTX 3090 and 68% on an Iris Xe; `bind_2000` 17.9%, 32.1% and 11.3%; `constant_managed` and `constant_private` 8.0% and 8.3% on the 780M, 22.2% and 25.8% on the