diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index cfc13d525..97304a2ee 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 = 2298; +pub const SEMANTICS_VERSION: u32 = 2300; /// 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/select.rs b/crates/metal2vulkan/src/lower/select.rs index 4f91886c6..5180d9a07 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1654,7 +1654,7 @@ fn finish( // the simd class selects the tier; the emulated tier reads a kernel's same analysis below. let uniformity = simd::partly_live(&mut cx, &sel.strategy, m)?; simd::whole_quads(&mut cx, &sel.strategy, m)?; - simd::finish(&mut cx)?; + simd::finish(&mut cx, uniformity.as_ref(), m)?; tessellation::finish(&mut cx)?; sync::barrier::finish(&mut cx)?; sync::memory_model::finish(&mut cx)?; diff --git a/crates/metal2vulkan/src/lower/simd/mod.rs b/crates/metal2vulkan/src/lower/simd/mod.rs index 263142b1f..37c975e6c 100644 --- a/crates/metal2vulkan/src/lower/simd/mod.rs +++ b/crates/metal2vulkan/src/lower/simd/mod.rs @@ -182,14 +182,21 @@ //! threadgroup barrier the lockstep pass inserted stands where the whole threadgroup runs together //! and depends on no reconvergence (`sync::barrier::BarrierPlan::uniform_placed`): an entry whose //! only tangled instructions are such barriers declares no mode and records `Guaranteed`, as does -//! an emulated kernel whose others are emulated sites (`workgroup::check`). A fragment's -//! derivatives, implicit-LOD samples and LOD queries (`SelectCx::derivatives`) are Metal's only -//! where the quad reaches them together (MSL 6.11.1.1), which SPIR-V's own reconvergence gives -//! but in a loop a back edge re-enters from inside a selection: a fragment entry whose other -//! tangled instructions depend on no reconvergence takes the mode, and records -//! `ImplementationDefined` where the profile has no maximal reconvergence, only where its module -//! holds one of them in such a loop (`quad_loop`); elsewhere it declares no mode and records -//! `Guaranteed`. +//! an emulated kernel whose others are emulated sites (`workgroup::check`). Three kinds stand +//! where their invocations reach them together, which SPIR-V's own reconvergence gives but in a +//! loop a back edge re-enters from inside a selection: a fragment's derivatives, implicit-LOD +//! samples and LOD queries (`SelectCx::derivatives`), which are Metal's only where the quad +//! reaches them together (MSL 6.11.1.1); a program's threadgroup barrier +//! (`sync::barrier::BarrierPlan::threadgroup`), which every thread of the threadgroup executes; +//! and a kernel's tangled instruction in a block every invocation of the workgroup executes +//! together (`uniform::Uniformity` under the kernel's unit axes; a kernel compiled for partial +//! threadgroups has none). An entry whose every group operation stands in a block the pass proves +//! uniform for the threadgroup, with no re-entered loop around it, states no mode and records +//! `Guaranteed`, its threadgroup barriers and a fragment's derivatives counting alike. Where one +//! of them stands in such a loop the entry takes the mode, and records `ImplementationDefined` +//! where the profile has no maximal reconvergence (`reentry`). The pass proves no loop uniform +//! whose exit differs between invocations, even where a threadgroup barrier on every path through +//! it makes every invocation run it as often: a group operation in such a loop keeps the mode. pub mod agx; pub mod divergent; @@ -197,7 +204,7 @@ mod group; pub mod lockstep; pub mod matrix; pub mod pressure; -pub mod quad_loop; +pub mod reentry; #[cfg(test)] mod tests; pub mod uniform; @@ -328,12 +335,14 @@ pub struct SimdPlan { pub mode: ReconvergenceMode, /// A tangled instruction runs without maximal reconvergence on this profile. pub implementation_defined: bool, - /// A fragment entry whose only tangled instructions that depend on reconvergence take - /// derivatives (`SelectCx::derivatives`): the mode and `implementation_defined` the profile - /// gives a tangled entry, which the entry takes only where its module holds such an - /// instruction in a loop a back edge re-enters from inside a selection - /// ([`quad_loop::settle`]). Elsewhere it states no mode and its reconvergence is guaranteed. - pub quad_loops: Option<(ReconvergenceMode, bool)>, + /// An entry whose only tangled instructions that depend on reconvergence stand where their + /// invocations reach them together (a fragment's derivatives, a threadgroup barrier, a + /// kernel's instruction in a workgroup-uniform block; the module docs, "Reconvergence"): the + /// mode and `implementation_defined` the profile gives a tangled entry, which the entry takes + /// only where its module holds a tangled instruction in a loop a back edge re-enters from + /// inside a selection ([`reentry::settle`]). Elsewhere it states no mode and its + /// reconvergence is guaranteed. + pub reentry: Option<(ReconvergenceMode, bool)>, /// In the `Emulated` tier, the words each lane publishes to the scratch in the widest /// exchange of the function; 0 when no operation exchanges values. pub exchange_words: u32, @@ -488,7 +497,15 @@ pub fn raise(c: SimdClass, ops: OpBits) -> SimdClass { /// is raised with the `Cluster32` classes instead. `tier` chooses between `Direct` and /// `Cluster32` by subgroup size alone, so the final class selects the tier whose classes it /// holds, or the refusal `select` then reports. -pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { +/// +/// `uniform` is a kernel's workgroup uniformity where `partly_live` computed it; a kernel compiled +/// without partial threadgroups whose tangled instructions it does not prove together computes it +/// here. +pub fn finish( + cx: &mut SelectCx<'_>, + uniform: Option<&uniform::Uniformity>, + m: &mut Meter, +) -> Result<(), Error> { // A fragment function's simdgroups are the pixels the device's rasterizer packs into a // subgroup, so an operation over the simdgroup's members combines a simdgroup Metal allows, not // the reference's. So does a quad operation beside a helper query in a function that discards, @@ -545,23 +562,27 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { .into()); } } - // A fragment's derivatives, implicit levels and LOD queries depend on reconvergence only in a - // loop a back edge re-enters from inside a selection, which the emitted module shows - // (`quad_loop::settle`). + // A tangled instruction its invocations reach together wherever SPIR-V reconverges them + // depends on reconvergence only in a loop a back edge re-enters from inside a selection, + // which the emitted module shows (`reentry::settle`). + let together = together(cx, uniform, m)?; let barriers = &cx.families.barrier; let fragment = cx.stage == Stage::Fragment; - let (mut others, mut derivatives) = (false, false); + let (mut others, mut reached) = (false, false); for &v in &cx.tangled { if !crate::lower::sync::barrier::reconverges(barriers, v) { continue; } - if fragment && cx.derivatives.contains(&v) { - derivatives = true; + if (fragment && cx.derivatives.contains(&v)) + || barriers.threadgroup.contains(&v) + || together.contains(&v) + { + reached = true; } else { others = true; } } - if others || derivatives { + if others || reached { let model = &cx.profile.fields().subgroup; let (mode, defined) = if model.maximal_reconvergence { (ReconvergenceMode::Maximal, false) @@ -574,7 +595,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.families.simd.mode = mode; cx.families.simd.implementation_defined = defined; } else { - cx.families.simd.quad_loops = Some((mode, defined)); + cx.families.simd.reentry = Some((mode, defined)); } } Ok(()) @@ -730,6 +751,46 @@ fn reads_live_lanes(s: &Strategy) -> bool { } } +/// The tangled instructions of a kernel compiled without partial threadgroups that stand in a block +/// every invocation of its workgroup executes together, the same number of times (`uniform`, +/// under the kernel's unit axes: `divergent::workgroup_uniformity`): from `uniform` where +/// `partly_live` computed it, else computed here where some tangled instruction is neither a +/// threadgroup barrier nor one the lockstep pass placed. Empty for every other function. +fn together( + cx: &SelectCx<'_>, + uniform: Option<&uniform::Uniformity>, + m: &mut Meter, +) -> Result, Error> { + let mut together = BTreeSet::new(); + let barriers = &cx.families.barrier; + let wanted = cx.tangled.iter().any(|&v| { + crate::lower::sync::barrier::reconverges(barriers, v) && !barriers.threadgroup.contains(&v) + }); + if cx.stage != Stage::Kernel || cx.inputs.partial_threadgroups || !wanted { + return Ok(together); + } + let computed = match uniform { + Some(_) => None, + None => Some(divergent::workgroup_uniformity(cx, m)?), + }; + if let Some(u) = uniform.or(computed.as_ref()) { + for (b, block) in cx.body.blocks.iter() { + if !u.is_uniform(b) { + continue; + } + for id in block.inst_ids() { + if let Some(v) = cx.values.inst(id).filter(|v| cx.tangled.contains(v)) { + together.insert(v); + } + } + } + } + if let Some(u) = &computed { + m.release(u.ledger_bytes()); + } + Ok(together) +} + /// Record the operations of the body that read another lane where some lane of the group may /// not take part (`SimdPlan::partly_live`), before the tier is chosen: on a subgroup tier such an /// operation ballots its live lanes and reads a lane that does not take part through the calling diff --git a/crates/metal2vulkan/src/lower/simd/quad_loop.rs b/crates/metal2vulkan/src/lower/simd/reentry.rs similarity index 52% rename from crates/metal2vulkan/src/lower/simd/quad_loop.rs rename to crates/metal2vulkan/src/lower/simd/reentry.rs index abdd08767..d34873499 100644 --- a/crates/metal2vulkan/src/lower/simd/quad_loop.rs +++ b/crates/metal2vulkan/src/lower/simd/reentry.rs @@ -1,21 +1,33 @@ -//! The reconvergence of a fragment entry whose only tangled instructions that depend on -//! reconvergence take derivatives (`SimdPlan::quad_loops`): `dfdx`, `dfdy` and `fwidth`, -//! implicit-LOD samples and LOD queries. +//! The reconvergence of an entry whose only tangled instructions that depend on reconvergence +//! stand where their invocations reach them together wherever SPIR-V reconverges them +//! (`SimdPlan::reentry`): //! -//! Metal leaves derivatives undefined within nonuniform control flow (MSL 6.11.1.1), and an -//! implicit level or an LOD query is the derivative of its coordinate (MSL 6.12), so such an -//! instruction is Metal's only where the invocations reach it together. Without a reconvergence -//! mode SPIR-V reconverges invocations at the merge of a construct they entered together and all -//! leave by that merge (SPIR-V 2.2.5, "Uniform Control Flow"), which covers every place they -//! rejoin but one: a loop's continue target. Invocations that reach the continue target from -//! different blocks (a continue from inside a selection, or two latches) are not known to run the -//! next iteration together, where Metal's run it as uniform control flow; -//! `MaximallyReconvergesKHR` reconverges them there (`SPV_KHR_maximal_reconvergence`, -//! "Reconvergence"). So the entry takes the mode the profile gives a tangled entry, and its -//! `implementation_defined` (`PrecisionNote::DeviceReconvergence` where the profile has no maximal -//! reconvergence), only where its module holds such an instruction, itself or through a call, in -//! the construct of a loop whose continue target two or more blocks of the construct branch to -//! ([`reentered`]); elsewhere it states no mode and its reconvergence is guaranteed. +//! - a fragment's derivatives (`dfdx`, `dfdy` and `fwidth`), implicit-LOD samples and LOD +//! queries: Metal leaves derivatives undefined within nonuniform control flow (MSL 6.11.1.1), +//! and an implicit level or an LOD query is the derivative of its coordinate (MSL 6.12), so such +//! an instruction is Metal's only where the quad reaches it together; +//! - a threadgroup barrier, which Metal requires every thread of the threadgroup to execute, the +//! same number of times (MSL 6.10.1); +//! - a kernel's instruction in a block every invocation of the workgroup executes together, the +//! same number of times (`uniform::Uniformity`, under the kernel's unit axes): every enclosing +//! selection's condition and every enclosing loop's exit is the same for every invocation, and +//! no invocation skips the block by a `break`, `continue` or `return`. +//! +//! Without a reconvergence mode SPIR-V reconverges invocations at the merge of a construct they +//! entered together and all leave by that merge (SPIR-V 2.2.5, "Uniform Control Flow"), and an +//! `OpControlBarrier` of `Workgroup` execution scope is defined only where every invocation +//! executes the same dynamic instance of it (`OpControlBarrier`; invocations resume the same +//! dynamic instances only under those reconvergence conditions, 2.2.5, "Dynamic Instance"). +//! That covers every place such invocations rejoin but one: a loop's continue target. +//! Invocations that reach the continue target from different blocks (a continue from inside a +//! selection, or two latches) are not known to run the next iteration together, where Metal's run +//! it as uniform control flow; `MaximallyReconvergesKHR` reconverges them there +//! (`SPV_KHR_maximal_reconvergence`, "Reconvergence"). So the entry takes the mode the profile +//! gives a tangled entry, and its `implementation_defined` (`PrecisionNote::DeviceReconvergence` +//! where the profile has no maximal reconvergence), only where its module holds a tangled +//! instruction, itself or through a call, in the construct of a loop whose continue target two or +//! more blocks of the construct branch to ([`reentered`]); elsewhere it states no mode and its +//! reconvergence is guaranteed. use super::{ReconvergenceMode, SimdPlan}; use crate::pipeline::artifact::Reconvergence; @@ -23,10 +35,10 @@ use crate::spirv::error::BResult; use crate::spirv::ids::BlockId; use crate::spirv::ir::{Block, ExecMode, Inst, Merge, Terminator, TypedModule}; -/// The entry's reconvergence once `module` is emitted, declaring the deferred mode of a fragment -/// entry whose derivatives lie in a re-entered loop ([`reentered`]). +/// The entry's reconvergence once `module` is emitted, declaring the deferred mode of an entry +/// whose tangled instructions lie in a re-entered loop ([`reentered`]). pub fn settle(simd: &SimdPlan, module: &mut TypedModule) -> BResult { - let implementation_defined = match simd.quad_loops { + let implementation_defined = match simd.reentry { Some((mode, implementation_defined)) if reentered(module) => { let mode = match mode { ReconvergenceMode::None => None, @@ -47,12 +59,15 @@ pub fn settle(simd: &SimdPlan, module: &mut TypedModule) -> BResult bool { +/// Whether `inst` is tangled: a derivative, an implicit-LOD sample, an LOD query, a control +/// barrier or a group operation. +fn tangled(inst: &Inst) -> bool { match inst { Inst::ImageSample { form, .. } => form.implicit, - Inst::Derivative { .. } | Inst::ImageQueryLod { .. } => true, + Inst::Derivative { .. } + | Inst::ImageQueryLod { .. } + | Inst::ControlBarrier { .. } + | Inst::Group { .. } => true, _ => false, } } @@ -69,20 +84,20 @@ fn branches_to(t: &Terminator, to: BlockId) -> bool { } } -/// Whether `module` holds a derivative, an implicit-LOD sample or an LOD query, itself or through -/// a call, in the construct of a loop whose continue target two or more blocks of the construct -/// branch to. A construct is the layout interval from its header to its merge, as the module's +/// Whether `module` holds a tangled instruction ([`tangled`]), itself or through a call, in the +/// construct of a loop whose continue target two or more blocks of the construct branch to. A construct is the layout interval from its header to its merge, as the module's /// verification holds it (`spirv::verify`). pub fn reentered(module: &TypedModule) -> bool { let blocks = module.blocks(); let functions = module.functions(); let block = |b: &BlockId| blocks.get(b.index()); - // The functions that take derivatives, themselves or through a call (a monotone fixpoint). + // The functions that hold a tangled instruction, themselves or through a call (a monotone + // fixpoint). let mut holds = vec![false; functions.len()]; let site = |b: &Block, holds: &[bool]| { b.insts.iter().any(|n| match &n.inst { Inst::Call { func, .. } => holds.get(func.index()).copied().unwrap_or(false), - inst => takes_derivatives(inst), + inst => tangled(inst), }) }; let mut changed = true; diff --git a/crates/metal2vulkan/src/lower/simd/workgroup.rs b/crates/metal2vulkan/src/lower/simd/workgroup.rs index ca8eb7a9c..df16387fd 100644 --- a/crates/metal2vulkan/src/lower/simd/workgroup.rs +++ b/crates/metal2vulkan/src/lower/simd/workgroup.rs @@ -71,7 +71,8 @@ //! **Reconvergence**. The emulated operations exchange through workgroup memory between workgroup //! barriers in workgroup-uniform control flow (predicated where the source diverges), so no result //! depends on how subgroups reconverge: an entry whose only tangled instructions are emulated ones -//! declares no reconvergence mode and records `Reconvergence::Guaranteed`. +//! declares no reconvergence mode, not even in a re-entered loop (`super::reentry`), and records +//! `Reconvergence::Guaranteed`. use crate::air::intrinsics::{GroupOp, MemFlags}; use crate::air::ir::ValueId; @@ -308,6 +309,7 @@ pub fn check( if !other_tangled { cx.families.simd.mode = ReconvergenceMode::None; cx.families.simd.implementation_defined = false; + cx.families.simd.reentry = None; } cx.families.simd.exchange_words = words; cx.families.simd.guarded_barriers = crate::lower::access::identity(cx.profile); diff --git a/crates/metal2vulkan/src/lower/sync/barrier.rs b/crates/metal2vulkan/src/lower/sync/barrier.rs index 85e920166..f94580c27 100644 --- a/crates/metal2vulkan/src/lower/sync/barrier.rs +++ b/crates/metal2vulkan/src/lower/sync/barrier.rs @@ -224,9 +224,15 @@ pub struct BarrierPlan { /// placement proved the whole threadgroup reaches together /// (`uniform::Uniformity::under_barriers`), so, though tangled, none depends on how subgroups /// reconverge, as the emulated tier's exchanges between workgroup barriers in workgroup-uniform - /// control flow do not. A program's barrier is not among them: it keeps the profile's - /// reconvergence. + /// control flow do not. A program's barrier is not among them: it is in [`threadgroup`]. + /// + /// [`threadgroup`]: Self::threadgroup pub uniform_placed: std::collections::BTreeSet, + /// Every threadgroup barrier, the program's and the lockstep pass's. Metal requires every + /// thread of the threadgroup to execute each, the same number of times, so its invocations + /// reach it together wherever SPIR-V reconverges them: everywhere but a loop a back edge + /// re-enters from inside a selection (`lower::simd::reentry`). + pub threadgroup: std::collections::BTreeSet, /// `lower::simd::lockstep` inserted a simdgroup barrier: the simd class takes it at /// [`lockstep_class`], once the program's own operations have set theirs. pub lockstep_simdgroup: bool, @@ -424,8 +430,11 @@ fn select_barrier( require_seq_cst(cx)?; } cx.tangled.insert(id); - if origin != Origin::Program && scope == Scope::Workgroup { - cx.families.barrier.uniform_placed.insert(id); + if scope == Scope::Workgroup { + cx.families.barrier.threadgroup.insert(id); + if origin != Origin::Program { + cx.families.barrier.uniform_placed.insert(id); + } } Ok(BarrierStrategy::Barrier(Barrier { scope, diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 89b125de1..ab8ae7614 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -478,8 +478,9 @@ pub struct ComputePipelineMetalInfo { #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Reconvergence { /// Maximal reconvergence (or no tangled operation depends on it: among a fragment function's - /// derivatives, implicit-LOD samples and LOD queries, only one in a loop a back edge re-enters - /// from inside a selection does). + /// derivatives, implicit-LOD samples and LOD queries, a threadgroup barrier, and a kernel's + /// operation in a block every thread of the threadgroup runs together, only one in a loop a + /// back edge re-enters from inside a selection does). Guaranteed, /// Reconvergence after divergence is implementation-defined on this profile. ImplementationDefined, @@ -1877,11 +1878,16 @@ pub enum PrecisionNote { /// which lanes run it together, where Metal's lanes reconverge maximally, so such an operation /// may see other lanes active than Metal's. Under subgroup-uniform control flow /// (`shaderSubgroupUniformControlFlow`) the lanes reconverge where control flow is uniform. - /// A fragment function's derivatives, implicit-LOD samples and LOD queries, which Metal - /// leaves undefined within nonuniform control flow, count only inside a loop that a back - /// edge re-enters from inside a selection (a `continue` there, or two latches), where SPIR-V - /// reconverges the quad for the next iteration only under maximal reconvergence. Static per - /// stage: recorded for any such instruction in the entry, as the stage's `reconvergence` is. + /// Three kinds count only inside a loop that a back edge re-enters from inside a selection (a + /// `continue` there, or two latches), where SPIR-V reconverges the lanes for the next + /// iteration only under maximal reconvergence: a fragment function's derivatives, implicit-LOD + /// samples and LOD queries, which Metal leaves undefined within nonuniform control flow; a + /// threadgroup barrier, which Metal requires every thread of the threadgroup to reach; and a + /// kernel's operation in a block every thread of the threadgroup runs together (every + /// enclosing condition and loop exit the same for every thread, none skipping the block by a + /// `break`, `continue` or `return`; a kernel compiled for partial threadgroups has none). + /// Static per stage: recorded for any such instruction in the entry, as the stage's + /// `reconvergence` is. /// /// Validation derives no tolerance from it: a difference stays a mismatch, which the note /// explains. diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index b31d76a5f..c508e755a 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3137,9 +3137,10 @@ fn lower_bounded( let modes = crate::lower::arith::narrow::controlled_modes(p).unwrap_or_default(); module.declare_modes(&modes)?; } - // A fragment entry whose derivatives alone are tangled takes its reconvergence mode only where - // the module holds one of them in a loop a back edge re-enters from inside a selection. - let reconvergence = crate::lower::simd::quad_loop::settle(&plan.families.simd, &mut module)?; + // An entry whose tangled instructions all stand where their invocations reach them together + // takes its reconvergence mode only where the module holds one in a loop a back edge re-enters + // from inside a selection. + let reconvergence = crate::lower::simd::reentry::settle(&plan.families.simd, &mut module)?; // Native half rounding and widening: a module that rounds through the device's quantize or // conversion, or widens a `half` by the device where that is not controlled to be Metal's, // records each kind, and requires no fact. diff --git a/crates/metal2vulkan/src/tests/engine_quad_loops.rs b/crates/metal2vulkan/src/tests/engine_quad_loops.rs index 8f36ba650..f4c940967 100644 --- a/crates/metal2vulkan/src/tests/engine_quad_loops.rs +++ b/crates/metal2vulkan/src/tests/engine_quad_loops.rs @@ -1,5 +1,5 @@ //! A fragment function whose only tangled instructions take derivatives (`dfdx`, implicit-LOD -//! samples, LOD queries) and its reconvergence (`lower::simd::quad_loop`): it states no mode and +//! samples, LOD queries) and its reconvergence (`lower::simd::reentry`): it states no mode and //! records `Guaranteed` with no `DeviceReconvergence` on every committed profile, but where one of //! them lies in a loop a back edge re-enters from inside a selection, where it takes the mode the //! profile gives a tangled entry and, without maximal reconvergence, the note. A fragment @@ -158,7 +158,7 @@ fn reading( mode, a.reconvergence, noted, - crate::lower::simd::quad_loop::reentered(&m), + crate::lower::simd::reentry::reentered(&m), ) } diff --git a/crates/metal2vulkan/src/tests/engine_reconvergence_together.rs b/crates/metal2vulkan/src/tests/engine_reconvergence_together.rs new file mode 100644 index 000000000..79e2072c6 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_reconvergence_together.rs @@ -0,0 +1,255 @@ +//! A kernel's tangled instructions that its threads reach together wherever SPIR-V reconverges +//! them, and its reconvergence (`lower::simd::reentry`): a threadgroup barrier, which Metal +//! requires every thread of the threadgroup to reach, and a group operation in a block the +//! workgroup uniformity proves every thread runs together. An entry whose tangled instructions +//! are all such states no mode and records `Guaranteed` with no `DeviceReconvergence` on every +//! committed profile, but where one of them lies in a loop a back edge re-enters from inside a +//! selection, where it takes the mode the profile gives a tangled entry. A group operation after +//! a selection inside a per-thread branch, or in a loop whose exit differs between threads, +//! keeps the mode. +//! +//! The kernels are our own: `k(device uint *out [[buffer(0)]], uint t +//! [[thread_index_in_threadgroup]])`, each writing one value to `out[t]`. +//! +//! `llvm-as` assembles the fixtures; without it the tests skip visibly. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::device::profile::DeviceProfile; +use crate::pipeline::artifact::{PrecisionNote, Reconvergence}; +use crate::pipeline::testing::{compile_kept, link_and_validate, llvm_assemble, AssembleError}; +use crate::spirv::testing::{committed_profiles, spirv_dis}; + +const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; + +/// Kernel `k` with `body`: the blocks from `entry` on, `%0` the buffer `out` and `%1` the +/// thread's index in its threadgroup; the body ends by storing to `out[t]` and returning. +fn kernel(name: &str, body: &str) -> Option> { + static NEXT: AtomicU64 = AtomicU64::new(0); + let text = format!( + "{HEADER}define void @k(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, i32 noundef %1) {{\nentry:\n{body}}}\n\n\ + declare void @air.wg.barrier(i32, i32)\ndeclare i32 @air.simd_shuffle.u.i32(i32, i16)\n\n\ + !air.kernel = !{{!9}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\ + !9 = !{{ptr @k, !10, !11}}\n!10 = !{{}}\n!11 = !{{!12, !13}}\n\ + !12 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"out\"}}\n\ + !13 = !{{i32 1, !\"air.thread_index_in_threadgroup\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"t\"}}\n\ + !17 = !{{i32 2, i32 8, i32 0}}\n!18 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n" + ); + let dir = std::env::temp_dir().join(format!( + "m2v-reconvergence-together-{}-{}-{name}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).expect("scratch"); + let ll = dir.join("k.ll"); + std::fs::write(&ll, text).expect("write"); + let r = llvm_assemble(&ll); + let _ = std::fs::remove_dir_all(&dir); + match r { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}\n{body}"), + } +} + +/// The store of `%r` to `out[t]` and the return, as the last block's tail. +const STORE: &str = " %e = zext i32 %1 to i64\n %p = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %e\n store i32 %r, ptr addrspace(1) %p, align 4\n ret void\n"; + +/// A threadgroup barrier and nothing else tangled. +fn barrier_alone() -> String { + format!(" call void @air.wg.barrier(i32 2, i32 1)\n %r = add i32 %1, 1\n{STORE}") +} + +/// A threadgroup barrier at the head of a loop of four trips whose two latches, one in each arm +/// of a selection on the thread's parity, branch back to the head: every thread reaches the +/// barrier each trip, and the loop is re-entered by back edges from inside a selection. +fn barrier_in_two_latches() -> String { + format!( + " %odd = and i32 %1, 1\n %c = icmp eq i32 %odd, 0\n br label %head\n\n\ + head:\n %i = phi i32 [ 0, %entry ], [ %i1, %a ], [ %i1, %b ]\n call void @air.wg.barrier(i32 2, i32 1)\n\ + %i1 = add i32 %i, 1\n %more = icmp ult i32 %i1, 4\n br i1 %c, label %a, label %b\n\n\ + a:\n br i1 %more, label %head, label %exit\n\n\ + b:\n br i1 %more, label %head, label %exit\n\n\ + exit:\n %r = add i32 %i1, %1\n{STORE}" + ) +} + +/// A shuffle in a loop of four trips, each reading lane `i` of the running value. +fn shuffle_counted() -> String { + format!( + " br label %head\n\n\ + head:\n %i = phi i32 [ 0, %entry ], [ %i1, %head ]\n %acc = phi i32 [ %1, %entry ], [ %s, %head ]\n\ + %l = trunc i32 %i to i16\n %s = tail call i32 @air.simd_shuffle.u.i32(i32 %acc, i16 %l)\n\ + %i1 = add i32 %i, 1\n %more = icmp ult i32 %i1, 4\n br i1 %more, label %head, label %exit\n\n\ + exit:\n %r = add i32 %s, 0\n{STORE}" + ) +} + +/// A shuffle after the merge of a selection on the thread's parity, inside a branch only threads +/// below 8 take. +fn shuffle_after_merge_in_branch() -> String { + format!( + " %c = icmp ult i32 %1, 8\n br i1 %c, label %in, label %done\n\n\ + in:\n %odd = and i32 %1, 1\n %d = icmp eq i32 %odd, 0\n br i1 %d, label %a, label %b\n\n\ + a:\n br label %m\n\nb:\n br label %m\n\n\ + m:\n %v = phi i32 [ 1, %a ], [ 2, %b ]\n %s = tail call i32 @air.simd_shuffle.u.i32(i32 %v, i16 0)\n br label %done\n\n\ + done:\n %r = phi i32 [ %s, %m ], [ 7, %entry ]\n{STORE}" + ) +} + +/// A shuffle in a loop whose exit compares the trip with the thread's index. +fn shuffle_per_thread_exit() -> String { + format!( + " br label %head\n\n\ + head:\n %i = phi i32 [ 0, %entry ], [ %i1, %head ]\n %acc = phi i32 [ %1, %entry ], [ %s, %head ]\n\ + %s = tail call i32 @air.simd_shuffle.u.i32(i32 %acc, i16 0)\n\ + %i1 = add i32 %i, 1\n %more = icmp ult i32 %i1, %1\n br i1 %more, label %head, label %exit\n\n\ + exit:\n %r = add i32 %s, 0\n{STORE}" + ) +} + +/// What the kernel states on `p`: its mode, its reconvergence, whether it records +/// `DeviceReconvergence`, whether its module holds a tangled instruction in a re-entered loop, +/// and whether it holds a subgroup shuffle (a subgroup tier, not the emulated one); its words +/// linked and validated (`spirv-val`). `None` where the profile refuses the kernel. +fn reading( + bc: &[u8], + stem: &str, + p: &DeviceProfile, +) -> Option<(&'static str, Reconvergence, bool, bool, bool)> { + let (a, _, m) = compile_kept(bc, "k", p).ok()?; + let (_, words) = link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + let text = spirv_dis(&words); + let mode = match ( + text.contains("MaximallyReconvergesKHR"), + text.contains("SubgroupUniformControlFlowKHR"), + ) { + (true, false) => "maximal", + (false, true) => "ucf", + (false, false) => "none", + (true, true) => "both", + }; + Some(( + mode, + a.reconvergence, + a.precision.contains(&PrecisionNote::DeviceReconvergence), + crate::lower::simd::reentry::reentered(&m), + text.contains("OpGroupNonUniformShuffle "), + )) +} + +/// The mode, reconvergence and note a tangled entry takes on `p`. +fn tangled_on(p: &DeviceProfile) -> (&'static str, Reconvergence, bool) { + let sg = p.fields().subgroup; + if sg.maximal_reconvergence { + ("maximal", Reconvergence::Guaranteed, false) + } else if sg.uniform_control_flow { + ("ucf", Reconvergence::ImplementationDefined, true) + } else { + ("none", Reconvergence::ImplementationDefined, true) + } +} + +/// A kernel whose only tangled instruction is a threadgroup barrier states no mode and records +/// `Guaranteed` with no `DeviceReconvergence` on every committed profile. +#[test] +fn a_threadgroup_barrier_alone_states_no_mode() { + let Some(bc) = kernel("barrier_alone", &barrier_alone()) else { + return; + }; + let mut maximal = 0; + for (stem, p) in committed_profiles().expect("profiles") { + let r = reading(&bc, &stem, &p).unwrap_or_else(|| panic!("{stem}: refused")); + assert_eq!( + (r.0, r.1, r.2, r.3), + ("none", Reconvergence::Guaranteed, false, false), + "{stem}" + ); + maximal += usize::from(p.fields().subgroup.maximal_reconvergence); + } + assert!( + maximal > 0, + "no committed profile has maximal reconvergence" + ); +} + +/// A threadgroup barrier in a loop two latches inside a selection re-enter takes the profile's +/// mode: `MaximallyReconvergesKHR` and `Guaranteed` with maximal reconvergence; else +/// `SubgroupUniformControlFlowKHR` where offered, or no mode, with `ImplementationDefined` and +/// `DeviceReconvergence`. +#[test] +fn a_threadgroup_barrier_in_a_re_entered_loop_keeps_the_mode() { + let Some(bc) = kernel("barrier_two_latches", &barrier_in_two_latches()) else { + return; + }; + for (stem, p) in committed_profiles().expect("profiles") { + let r = reading(&bc, &stem, &p).unwrap_or_else(|| panic!("{stem}: refused")); + let (mode, reconvergence, noted) = tangled_on(&p); + assert_eq!( + (r.0, r.1, r.2, r.3), + (mode, reconvergence, noted, true), + "{stem}" + ); + } +} + +/// A shuffle in a loop of a constant trip count stands where every thread of the threadgroup +/// runs together: the kernel states no mode and records `Guaranteed` on every profile that +/// compiles it, a subgroup shuffle on some. +#[test] +fn a_shuffle_in_a_counted_loop_states_no_mode() { + let Some(bc) = kernel("shuffle_counted", &shuffle_counted()) else { + return; + }; + let mut shuffled = 0; + for (stem, p) in committed_profiles().expect("profiles") { + let Some(r) = reading(&bc, &stem, &p) else { + continue; + }; + assert_eq!( + (r.0, r.1, r.2, r.3), + ("none", Reconvergence::Guaranteed, false, false), + "{stem}" + ); + shuffled += usize::from(r.4 && p.fields().subgroup.maximal_reconvergence); + } + assert!( + shuffled > 0, + "no maximal profile compiled a subgroup shuffle" + ); +} + +/// A shuffle after a merge inside a branch some threads skip, and a shuffle in a loop whose +/// exit differs between threads, keep the profile's mode wherever they compile to a subgroup +/// shuffle. +#[test] +fn a_shuffle_outside_uniform_control_flow_keeps_the_mode() { + let Some(merged) = kernel("shuffle_after_merge", &shuffle_after_merge_in_branch()) else { + return; + }; + let Some(exits) = kernel("shuffle_per_thread_exit", &shuffle_per_thread_exit()) else { + return; + }; + let mut shuffled = 0; + for (stem, p) in committed_profiles().expect("profiles") { + for (case, bc) in [("after a merge", &merged), ("per-thread exit", &exits)] { + let Some(r) = reading(bc, &stem, &p) else { + continue; + }; + if !r.4 { + continue; + } + shuffled += 1; + let (mode, reconvergence, noted) = tangled_on(&p); + assert_eq!( + (r.0, r.1, r.2), + (mode, reconvergence, noted), + "{stem} {case}" + ); + } + } + assert!(shuffled > 0, "no profile compiled a subgroup shuffle"); +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 0f0460de3..e68ef5793 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -135,6 +135,7 @@ mod engine_qualified_signature; mod engine_rate_map; mod engine_ray_tracing; mod engine_read_through_constant; +mod engine_reconvergence_together; mod engine_recursion; mod engine_refused_families; mod engine_region_viewports; diff --git a/docs/API.md b/docs/API.md index 35fb5fe6d..f2e26d099 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1462,8 +1462,10 @@ runtime's `Error::basis` answers a translation error so. `precision_notes` (a `PrecisionNote`, each documenting its bound), and `reconvergence` says whether subgroup reconvergence after divergence matches Metal's (`Reconvergence::ImplementationDefined` where the profile lacks maximal reconvergence and the -stage holds a group operation or barrier that depends on it, or a fragment function's derivative, -implicit-LOD sample or LOD query in a loop that a back edge re-enters from inside a selection). A +stage holds a group operation or barrier that depends on it; a fragment function's derivative, +implicit-LOD sample or LOD query, a threadgroup barrier, and a kernel's group operation in a block +the translator proves uniform for the threadgroup depend on it only in a loop that a back edge +re-enters from inside a selection). A note that holds only under some bound values is in `specialized_notes`; `stage.precision_notes_bound(&specialization, &|key| bound(key))` gives the notes a pipeline created under `specialization` reaches where a draw or dispatch binds the values `bound` gives. @@ -1568,13 +1570,26 @@ bound. divergent control flow the device decides which lanes run it together, where Metal's lanes reconverge maximally, so such an operation may see other lanes active than Metal's. Under subgroup-uniform control flow (`shaderSubgroupUniformControlFlow`) the lanes reconverge where - control flow is uniform. A fragment function's derivatives, implicit-LOD samples and LOD - queries count only inside a loop that a back edge re-enters from inside a selection (a - `continue` there, or two latches): Metal leaves derivatives undefined within nonuniform control - flow, SPIR-V reconverges the quad wherever it rejoins at a merge, and only maximal - reconvergence rejoins it at such a loop's next iteration. Elsewhere such an entry states no - reconvergence mode on any device and records no note. Static per stage: recorded for any such - instruction in the entry. + control flow is uniform. Three kinds count only inside a loop that a back edge re-enters from + inside a selection (a `continue` there, or two latches), where only maximal reconvergence + rejoins the lanes for the next iteration; SPIR-V reconverges them wherever they rejoin at a + merge: + - a fragment function's derivatives, implicit-LOD samples and LOD queries, which Metal leaves + undefined within nonuniform control flow; + - a threadgroup barrier, which Metal requires every thread of the threadgroup to reach; + - a kernel's group operation in a block the translator proves uniform for the threadgroup: + every enclosing condition and every enclosing loop's exit is the same for every thread + (literals, constants, `constant` buffer fields and per-threadgroup values, and what is + computed from them), and no thread skips the block by a `break`, `continue` or `return`. + A loop whose exit differs between threads is not proven uniform, even where a barrier on + every path makes every thread run it as often. A kernel compiled for partial threadgroups + has no such block. + + An entry whose every group operation stands in a block the pass proves uniform for the + threadgroup, with no re-entered loop around it, states no mode and records + `Reconvergence::Guaranteed`; so does an entry whose other tangled instructions are of the first + two kinds, none in such a loop. Such an entry states no reconvergence mode on any device and + records no note. Static per stage: recorded for any such instruction in the entry. - `metal2vulkan-degrade-simdgroup-access-order` (precision). `SimdgroupAccessOrder`: A kernel holds two accesses of threadgroup or device memory, at least one a write, that different threads of one SIMD-group may make to the same bytes between two barriers, and no barrier or atomic