Translator: a fragment's derivatives state the reconvergence mode only in a loop a back edge re-enters from inside a selection
A fragment entry whose only tangled instructions that depend on reconvergence take derivatives (dfdx, dfdy, fwidth, implicit-LOD samples, LOD queries) no longer states MaximallyReconvergesKHR (or SubgroupUniformControlFlowKHR), records Reconvergence::Guaranteed and carries no DeviceReconvergence, on every device, except where its emitted 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 (a continue from inside a selection, or two latches). There it takes the mode the profile gives a tangled entry, and the note where the profile has no maximal reconvergence. Entries with group operations or barriers keep today's behaviour. Why: MSL 6.11.1.1 leaves derivatives undefined within nonuniform control flow, and an implicit level or LOD query is the derivative of its coordinate, so such an instruction is Metal's only where the quad reaches it together. Without a mode SPIR-V reconverges invocations at the merge of a construct they entered together and all leave by it (2.2.5, Uniform Control Flow); only the continue target of a loop entered from several blocks needs SPV_KHR_maximal_reconvergence to rejoin the quad for the next iteration. AMDVLK 2025.Q2.1 miscompiles a large fragment function under the mode (an 8x8-cell grid on the 780M, blockiness 9.15 against RADV's 2.87; the same play with the mode stripped reads 2.92, job m3-max-71921), and the note logged on every device without the feature for a case Metal leaves undefined. How: SelectCx::derivatives marks the derivative and implicit-LOD tangled values; simd::finish defers a fragment entry with only those to SimdPlan::quad_loops; lower::simd::quad_loop::settle decides on the emitted module, before verification, and declares the mode with TypedModule::declare_modes where it applies. The PrecisionNote and Reconvergence docs, the docs/API.md catalogue entry and its Precision sentence, and the simd module doc say the same. SEMANTICS_VERSION 2298. Verified: - Metal-defined reconvergence cases with the mode stripped equal them with it, and Metal, on the 780M under AMDVLK 2025.Q2.1 and RADV (m3-max-72068), the RTX 5080 (m3-max-72069), the RTX 3090 (m3-max-72071), the Iris Xe (m3-max-72070) and lavapipe (m3-max-72077): 0 of 4096 pixels differ from Metal either way. Each entry under this change reads one of the two. - The lettering play on the 780M under AMDVLK to frame 4016 (m3-max-72116, this change against its baseff2b13cb96): blockiness 2.92 against the base's 9.15 and RADV's 2.87. In the same job under AMDVLK, the runtime's device suite (717 tests, one process each) reads 714 passed and the same 3 failed for base and change, 0 verdicts differing; `conformance replay --gpu` gives identical verdicts and lines. - Lowering diff, card-free (m3-max-72134), on every committed profile over five recordings, base against change: only fragment-stage modules differ (22514 of 43708 render states, from 906 fragment entry points); 0 vertex modules and 0 of 16160 compute modules differ; on nvidia-pascal-linux and runtime-floor no module differs and only the reconvergence and the note move. The golden table's 1079 changed cells are 83 fragment entries (!air.fragment) on the 13 profiles with maximal reconvergence (m3-max-72117); its bless is due at the next pin. - Reach (m3-max-72028, m3-max-72101, m3-max-72194): on the 780M RADV profile, standing for the 13 maximal profiles, 229 fragment entry points of the lettering recording, 906 of five other recordings and 3108 of fifteen more lose the mode; none still states it. - Timing, base / change / base, each play from empty caches, GPU busy against the base mean: the 780M under RADV, 4017 frames (m3-max-72164), +0.07% whole play, +0.06% from frame 250, at most +0.96% in any 250-frame window after it; the RTX 3090, 751 frames (m3-max-72163), +0.82%, +1.08%, at most +1.71%, clocks alike per arm; the Iris Xe, 751 frames (m3-max-72202), -0.07%, -0.04%, at most -0.01%. The RTX 5080's run (m3-max-72128) read noise: its base arms' GPU busy stood 3.0-8.5% apart in four of five windows. - Release translation of the largest row, the 357,837-word lettering fragment module, through the command line with spirv-val: 0.28 s and 43.6 MiB, as the base's 0.29 s and 43.5 MiB (m3-max-72178). The slowest single pipeline of a recording compiles in at most 0.5 s on a loaded host, and its process peaks at 436 MiB (m3-max-72169, m3-max-72177); five recordings' batch, 75 runs a side interleaved, takes 0.44% longer than the base's (m3-max-72134). - Tests (engine_quad_loops): derivatives in selections, after merges, after a loop and in a one-latch loop state no mode and no note on every committed profile; a two-latch loop around a sample or dfdx takes the profile's mode and, without maximal reconvergence, the note; a fragment quad operation keeps the mode. With the routing switched off, derivatives_outside_a_re_entered_loop_state_no_mode_and_no_note fails and the other two pass (m3-max-72117). Gate at this commit (m3-max-72200): fmt, clippy in every configuration, Rustdoc, the suites, the doctests and lavapipe's quad_control pass, but for the golden table's bless; `conformance replay --cpu` on lavapipe, reconvergence cases included, reads the same as on62ab49b966line for line, and holds the ledger.
This commit is contained in:
1 parent
62ab49b966
commit
7360a148bb
12 files changed
+457
-30
No files matched your search
Vendored
+1
-1
@@ -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 = 2297;
|
||||
pub const SEMANTICS_VERSION: u32 = 2298;
|
||||
|
||||
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
|
||||
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
|
||||
|
||||
@@ -38,9 +38,8 @@
|
||||
//! discarded thread only while its quad keeps a live thread, and drops a quad whose every thread is
|
||||
//! discarded from the simdgroup. Demote, which the profile lacks there, maps Metal's helper to
|
||||
//! Vulkan's, as for every other helper lane, and is the form every profile with it takes;
|
||||
//! `MaximallyReconvergesKHR`, which an entry with a tangled instruction
|
||||
//! declares where the profile has it (`lower::simd`), keeps such a helper a lane of later subgroup
|
||||
//! operations. Demote needs no guard: Vulkan helper invocations have no memory side effects and
|
||||
//! `MaximallyReconvergesKHR`, which an entry with a subgroup operation declares where the profile
|
||||
//! has it (`lower::simd`), keeps such a helper a lane of later subgroup operations. Demote needs no guard: Vulkan helper invocations have no memory side effects and
|
||||
//! their outputs are discarded.
|
||||
//!
|
||||
//! **A quad of helpers alone**. Metal drops a quad whose every thread is discarded from the
|
||||
|
||||
@@ -2395,6 +2395,7 @@ fn select_one(
|
||||
let value = id(cx, Value::Inst(at))?;
|
||||
if tangled {
|
||||
cx.tangled.insert(value);
|
||||
cx.derivatives.insert(value);
|
||||
}
|
||||
let clamp_reference = clamps_reference(cx, comparison, sampler)?;
|
||||
let sampling = Sampling {
|
||||
|
||||
@@ -519,6 +519,10 @@ pub struct SelectCx<'a> {
|
||||
/// Tangled instructions (subgroup/quad ops, derivatives, implicit-LOD samples, barriers),
|
||||
/// which the families that select them add.
|
||||
pub tangled: BTreeSet<ValueId>,
|
||||
/// The tangled instructions that read other lanes only to take derivatives: `dfdx`, `dfdy`
|
||||
/// and `fwidth`, implicit-LOD samples and LOD queries (`lower::simd`'s module,
|
||||
/// **Reconvergence**).
|
||||
pub derivatives: BTreeSet<ValueId>,
|
||||
/// Each family's own plan.
|
||||
pub families: FamilyPlans,
|
||||
/// The offset shapes the access family has read while selecting this function's typed
|
||||
@@ -1245,6 +1249,7 @@ pub fn select(
|
||||
descriptors: DescriptorCounts::default(),
|
||||
simd: SimdClass::None,
|
||||
tangled: BTreeSet::new(),
|
||||
derivatives: BTreeSet::new(),
|
||||
families: FamilyPlans::default(),
|
||||
shapes: access::local::Shapes::default(),
|
||||
root_sets,
|
||||
|
||||
@@ -182,7 +182,14 @@
|
||||
//! 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`).
|
||||
//! 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`.
|
||||
|
||||
pub mod agx;
|
||||
pub mod divergent;
|
||||
@@ -190,6 +197,7 @@ mod group;
|
||||
pub mod lockstep;
|
||||
pub mod matrix;
|
||||
pub mod pressure;
|
||||
pub mod quad_loop;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
pub mod uniform;
|
||||
@@ -212,7 +220,7 @@ use crate::lower::arith::legal::{form_on, wide_form_on, Form, Held, LoweredConst
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::select::{FamilyPlans, Plan, SelectCx};
|
||||
use crate::lower::strategy::{FamilyStrategy, Strategy};
|
||||
use crate::pipeline::artifact::{PrecisionNote, Reconvergence};
|
||||
use crate::pipeline::artifact::PrecisionNote;
|
||||
use crate::pipeline::sym::Stage;
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::error::BResult;
|
||||
@@ -320,6 +328,12 @@ 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)>,
|
||||
/// 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,
|
||||
@@ -451,16 +465,6 @@ pub fn widest_pin(cx: &SelectCx<'_>, m: &mut Meter) -> Result<bool, Error> {
|
||||
Ok(pressure::peak_words(cx.entry, cx.body, m)? > WIDEST_PIN_WORDS)
|
||||
}
|
||||
|
||||
/// The artifact's reconvergence: `ImplementationDefined` when the entry holds a tangled instruction
|
||||
/// and the profile has no maximal reconvergence.
|
||||
pub fn reconvergence(plan: &Plan) -> Reconvergence {
|
||||
if plan.families.simd.implementation_defined {
|
||||
Reconvergence::ImplementationDefined
|
||||
} else {
|
||||
Reconvergence::Guaranteed
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` raised by operation classes `ops`: a cross-lane class with them added. The matrix class
|
||||
/// already implies cross-lane use.
|
||||
pub fn raise(c: SimdClass, ops: OpBits) -> SimdClass {
|
||||
@@ -541,12 +545,23 @@ 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`).
|
||||
let barriers = &cx.families.barrier;
|
||||
if cx
|
||||
.tangled
|
||||
.iter()
|
||||
.any(|&v| crate::lower::sync::barrier::reconverges(barriers, v))
|
||||
{
|
||||
let fragment = cx.stage == Stage::Fragment;
|
||||
let (mut others, mut derivatives) = (false, false);
|
||||
for &v in &cx.tangled {
|
||||
if !crate::lower::sync::barrier::reconverges(barriers, v) {
|
||||
continue;
|
||||
}
|
||||
if fragment && cx.derivatives.contains(&v) {
|
||||
derivatives = true;
|
||||
} else {
|
||||
others = true;
|
||||
}
|
||||
}
|
||||
if others || derivatives {
|
||||
let model = &cx.profile.fields().subgroup;
|
||||
let (mode, defined) = if model.maximal_reconvergence {
|
||||
(ReconvergenceMode::Maximal, false)
|
||||
@@ -555,8 +570,12 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
} else {
|
||||
(ReconvergenceMode::None, true)
|
||||
};
|
||||
cx.families.simd.mode = mode;
|
||||
cx.families.simd.implementation_defined = defined;
|
||||
if others {
|
||||
cx.families.simd.mode = mode;
|
||||
cx.families.simd.implementation_defined = defined;
|
||||
} else {
|
||||
cx.families.simd.quad_loops = Some((mode, defined));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use super::{ReconvergenceMode, SimdPlan};
|
||||
use crate::pipeline::artifact::Reconvergence;
|
||||
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`]).
|
||||
pub fn settle(simd: &SimdPlan, module: &mut TypedModule) -> BResult<Reconvergence> {
|
||||
let implementation_defined = match simd.quad_loops {
|
||||
Some((mode, implementation_defined)) if reentered(module) => {
|
||||
let mode = match mode {
|
||||
ReconvergenceMode::None => None,
|
||||
ReconvergenceMode::Maximal => Some(ExecMode::MaximallyReconverges),
|
||||
ReconvergenceMode::UniformControlFlow => Some(ExecMode::SubgroupUniformControlFlow),
|
||||
};
|
||||
if let Some(mode) = mode {
|
||||
module.declare_modes(&[mode])?;
|
||||
}
|
||||
implementation_defined
|
||||
}
|
||||
_ => simd.implementation_defined,
|
||||
};
|
||||
Ok(if implementation_defined {
|
||||
Reconvergence::ImplementationDefined
|
||||
} else {
|
||||
Reconvergence::Guaranteed
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `inst` reads other lanes only to take a derivative: a derivative, an implicit-LOD
|
||||
/// sample or an LOD query.
|
||||
fn takes_derivatives(inst: &Inst) -> bool {
|
||||
match inst {
|
||||
Inst::ImageSample { form, .. } => form.implicit,
|
||||
Inst::Derivative { .. } | Inst::ImageQueryLod { .. } => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `t` branches to `to`.
|
||||
fn branches_to(t: &Terminator, to: BlockId) -> bool {
|
||||
match t {
|
||||
Terminator::Branch(x) => *x == to,
|
||||
Terminator::CondBranch { t, f, .. } => *t == to || *f == to,
|
||||
Terminator::Switch { default, cases, .. } => {
|
||||
*default == to || cases.iter().any(|(_, b)| *b == to)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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).
|
||||
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),
|
||||
})
|
||||
};
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for (fi, f) in functions.iter().enumerate() {
|
||||
if holds.get(fi).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
if f.blocks.iter().filter_map(block).any(|b| site(b, &holds)) {
|
||||
if let Some(x) = holds.get_mut(fi) {
|
||||
*x = true;
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
functions.iter().any(|f| {
|
||||
// Each block's site, and the sites before each layout position.
|
||||
let mut before = Vec::with_capacity(f.blocks.len() + 1);
|
||||
before.push(0usize);
|
||||
for b in &f.blocks {
|
||||
let here = block(b).is_some_and(|b| site(b, &holds));
|
||||
before.push(before.last().copied().unwrap_or(0) + usize::from(here));
|
||||
}
|
||||
f.blocks.iter().enumerate().any(|(start, h)| {
|
||||
let Some(Merge::Loop { merge, cont }) = block(h).and_then(|b| b.merge) else {
|
||||
return false;
|
||||
};
|
||||
let Some(end) = f.blocks.iter().position(|b| *b == merge) else {
|
||||
return false;
|
||||
};
|
||||
let construct = f.blocks.get(start..end).unwrap_or(&[]);
|
||||
let sites =
|
||||
before.get(end).copied().unwrap_or(0) - before.get(start).copied().unwrap_or(0);
|
||||
sites > 0
|
||||
&& construct
|
||||
.iter()
|
||||
.filter_map(block)
|
||||
.filter(|b| branches_to(&b.term, cont))
|
||||
.nth(1)
|
||||
.is_some()
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -582,6 +582,7 @@ fn select_derivative(
|
||||
(DerivativeOp::Fwidth, false) => DerivOp::Fwidth,
|
||||
};
|
||||
cx.tangled.insert(id);
|
||||
cx.derivatives.insert(id);
|
||||
Ok(BarrierStrategy::Derivative(Deriv { op, value }))
|
||||
}
|
||||
|
||||
|
||||
@@ -477,7 +477,9 @@ pub struct ComputePipelineMetalInfo {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Reconvergence {
|
||||
/// Maximal reconvergence (or no tangled operation depends on it).
|
||||
/// 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).
|
||||
Guaranteed,
|
||||
/// Reconvergence after divergence is implementation-defined on this profile.
|
||||
ImplementationDefined,
|
||||
@@ -1875,8 +1877,11 @@ 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.
|
||||
/// Static per stage: recorded for any tangled instruction in the entry, as the stage's
|
||||
/// `reconvergence` is.
|
||||
/// 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.
|
||||
///
|
||||
/// Validation derives no tolerance from it: a difference stays a mismatch, which the note
|
||||
/// explains.
|
||||
|
||||
@@ -3137,6 +3137,9 @@ fn lower_bounded<K>(
|
||||
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)?;
|
||||
// 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.
|
||||
@@ -3245,7 +3248,6 @@ fn lower_bounded<K>(
|
||||
}
|
||||
// Implementation-defined where a tangled instruction runs without maximal reconvergence
|
||||
// (`lower::simd` chooses the entry's reconvergence mode), which the stage's note records.
|
||||
let reconvergence = crate::lower::simd::reconvergence(&plan);
|
||||
if reconvergence == Reconvergence::ImplementationDefined
|
||||
&& !precision.contains(&PrecisionNote::DeviceReconvergence)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! 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
|
||||
//! 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
|
||||
//! function with a quad operation keeps its mode.
|
||||
//!
|
||||
//! `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, compile_kept, engine_dir, 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";
|
||||
|
||||
/// A constexpr sampler: magnify nearest, minify linear, repeat.
|
||||
const SAMPLER_WORDS: u64 = 34901797601020050;
|
||||
|
||||
fn assemble(name: &str, body: &str) -> Option<Vec<u8>> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"m2v-quad-loops-{}-{}-{name}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
std::fs::create_dir_all(&dir).expect("scratch");
|
||||
let ll = dir.join("f.ll");
|
||||
std::fs::write(&ll, format!("{HEADER}{body}")).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}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture(stem: &str) -> Option<Vec<u8>> {
|
||||
match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) {
|
||||
Ok(b) => Some(b),
|
||||
Err(AssembleError::Missing(why)) => {
|
||||
eprintln!("SKIPPED: {why}");
|
||||
None
|
||||
}
|
||||
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {stem}: {why}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A fragment function `f` that, four trips, takes a value of its position and its trip number
|
||||
/// that reads the quad (an implicit-LOD sample of texture slot 0, or `dfdx` where `derivative`)
|
||||
/// and adds or subtracts it by its pixel column's parity. With `two_latches` each parity's block
|
||||
/// branches back to the loop's header itself, so the loop is re-entered by back edges from
|
||||
/// inside a selection; without, both join one latch first.
|
||||
fn looped(two_latches: bool, derivative: bool) -> String {
|
||||
let take = if derivative {
|
||||
"%pv = fmul <4 x float> %pos, %s4\n %v = tail call fast <4 x float> @air.dfdx.v4f32(<4 x float> %pv)"
|
||||
} else {
|
||||
"%r = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n %v = extractvalue { <4 x float>, i8 } %r, 0"
|
||||
};
|
||||
let (incoming, arms, exit) = if two_latches {
|
||||
(
|
||||
"[ %i1, %a ], [ %i1, %b ]",
|
||||
"a:\n %acc1 = fadd <4 x float> %acc, %v\n br i1 %more, label %head, label %exit\n\n\
|
||||
b:\n %acc2 = fsub <4 x float> %acc, %v\n br i1 %more, label %head, label %exit\n",
|
||||
"exit:\n %res = phi <4 x float> [ %acc1, %a ], [ %acc2, %b ]\n ret <4 x float> %res\n",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
"[ %i1, %latch ]",
|
||||
"a:\n %acc1 = fadd <4 x float> %acc, %v\n br label %latch\n\n\
|
||||
b:\n %acc2 = fsub <4 x float> %acc, %v\n br label %latch\n\n\
|
||||
latch:\n %acc3 = phi <4 x float> [ %acc1, %a ], [ %acc2, %b ]\n br i1 %more, label %head, label %exit\n",
|
||||
"exit:\n ret <4 x float> %acc3\n",
|
||||
)
|
||||
};
|
||||
let accs = if two_latches {
|
||||
"[ %acc1, %a ], [ %acc2, %b ]"
|
||||
} else {
|
||||
"[ %acc3, %latch ]"
|
||||
};
|
||||
format!(
|
||||
r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {SAMPLER_WORDS}, i64 0], align 8
|
||||
|
||||
define <4 x float> @f(<4 x float> %pos, ptr addrspace(1) %t) {{
|
||||
entry:
|
||||
%xy = shufflevector <4 x float> %pos, <4 x float> poison, <2 x i32> <i32 0, i32 1>
|
||||
%x = extractelement <4 x float> %pos, i64 0
|
||||
%xi = fptoui float %x to i32
|
||||
%odd = and i32 %xi, 1
|
||||
%c = icmp eq i32 %odd, 0
|
||||
br label %head
|
||||
|
||||
head:
|
||||
%i = phi i32 [ 0, %entry ], {incoming}
|
||||
%acc = phi <4 x float> [ zeroinitializer, %entry ], {accs}
|
||||
%fi = uitofp i32 %i to float
|
||||
%s1 = insertelement <2 x float> poison, float %fi, i64 0
|
||||
%s2 = shufflevector <2 x float> %s1, <2 x float> poison, <2 x i32> zeroinitializer
|
||||
%s3 = insertelement <4 x float> poison, float %fi, i64 0
|
||||
%s4 = shufflevector <4 x float> %s3, <4 x float> poison, <4 x i32> zeroinitializer
|
||||
%uv0 = fmul <2 x float> %xy, <float 6.250000e-02, float 6.250000e-02>
|
||||
%uv = fadd <2 x float> %uv0, %s2
|
||||
{take}
|
||||
%i1 = add i32 %i, 1
|
||||
%more = icmp ult i32 %i1, 4
|
||||
br i1 %c, label %a, label %b
|
||||
|
||||
{arms}
|
||||
{exit}}}
|
||||
|
||||
declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)
|
||||
declare <4 x float> @air.dfdx.v4f32(<4 x float>)
|
||||
|
||||
!air.fragment = !{{!0}}
|
||||
!air.sampler_states = !{{!6}}
|
||||
!0 = !{{ptr @f, !1, !3}}
|
||||
!1 = !{{!2}}
|
||||
!2 = !{{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}}
|
||||
!3 = !{{!4, !5}}
|
||||
!4 = !{{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}}
|
||||
!5 = !{{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"t"}}
|
||||
!6 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
/// The mode `entry` of `bc` states on `p`, its reconvergence, whether it records
|
||||
/// `DeviceReconvergence`, and whether its module holds a quad-scoped instruction in a re-entered
|
||||
/// loop; its words linked and validated (`spirv-val`).
|
||||
fn reading(
|
||||
bc: &[u8],
|
||||
entry: &str,
|
||||
stem: &str,
|
||||
p: &DeviceProfile,
|
||||
) -> (&'static str, Reconvergence, bool, bool) {
|
||||
let (a, _, m) = compile_kept(bc, entry, p).unwrap_or_else(|e| panic!("{stem} {entry}: {e}"));
|
||||
let (_, words) = link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem} {entry}: 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",
|
||||
};
|
||||
let noted = a.precision.contains(&PrecisionNote::DeviceReconvergence);
|
||||
(
|
||||
mode,
|
||||
a.reconvergence,
|
||||
noted,
|
||||
crate::lower::simd::quad_loop::reentered(&m),
|
||||
)
|
||||
}
|
||||
|
||||
/// A fragment function's derivatives in selections, after a selection's merge, after a loop and
|
||||
/// inside a loop one latch closes state no mode and record `Guaranteed` with no
|
||||
/// `DeviceReconvergence`, on every committed profile, as no loop re-enters them.
|
||||
#[test]
|
||||
fn derivatives_outside_a_re_entered_loop_state_no_mode_and_no_note() {
|
||||
let Some(tangle) = fixture("rch_helper_tangle") else {
|
||||
return;
|
||||
};
|
||||
let Some(one_latch) = assemble("one_latch", &looped(false, false)) else {
|
||||
return;
|
||||
};
|
||||
let Some(one_latch_dfdx) = assemble("one_latch_dfdx", &looped(false, true)) else {
|
||||
return;
|
||||
};
|
||||
let cases: [(&[u8], &str); 9] = [
|
||||
(&tangle, "rch_tangle_sample_after"),
|
||||
(&tangle, "rch_tangle_dfdx_after"),
|
||||
(&tangle, "rch_tangle_lod_after"),
|
||||
(&tangle, "rch_tangle_sample_before"),
|
||||
(&tangle, "rch_tangle_unread"),
|
||||
(&tangle, "rch_tangle_merge_after"),
|
||||
(&tangle, "rch_tangle_loop_after"),
|
||||
(&one_latch, "f"),
|
||||
(&one_latch_dfdx, "f"),
|
||||
];
|
||||
for (stem, p) in committed_profiles().expect("profiles") {
|
||||
for (bc, entry) in cases {
|
||||
let (mode, reconvergence, noted, reentered) = reading(bc, entry, &stem, &p);
|
||||
assert_eq!(
|
||||
(mode, reconvergence, noted, reentered),
|
||||
("none", Reconvergence::Guaranteed, false, false),
|
||||
"{stem} {entry}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fragment function whose implicit-LOD sample or `dfdx` lies in a loop that two latches,
|
||||
/// each inside an arm of a selection on the pixel's column, 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_derivative_in_a_re_entered_loop_keeps_the_mode_and_the_note() {
|
||||
let Some(sample) = assemble("two_latches", &looped(true, false)) else {
|
||||
return;
|
||||
};
|
||||
let Some(dfdx) = assemble("two_latches_dfdx", &looped(true, true)) else {
|
||||
return;
|
||||
};
|
||||
for (stem, p) in committed_profiles().expect("profiles") {
|
||||
let sg = p.fields().subgroup;
|
||||
let expected = if sg.maximal_reconvergence {
|
||||
("maximal", Reconvergence::Guaranteed, false, true)
|
||||
} else if sg.uniform_control_flow {
|
||||
("ucf", Reconvergence::ImplementationDefined, true, true)
|
||||
} else {
|
||||
("none", Reconvergence::ImplementationDefined, true, true)
|
||||
};
|
||||
for bc in [&sample, &dfdx] {
|
||||
assert_eq!(reading(bc, "f", &stem, &p), expected, "{stem}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fragment function with a quad operation keeps the mode wherever it compiles: its quad sum
|
||||
/// reconverges, whatever its samples do.
|
||||
#[test]
|
||||
fn a_fragment_quad_operation_keeps_the_mode() {
|
||||
let Some(tangle) = fixture("rch_helper_tangle") else {
|
||||
return;
|
||||
};
|
||||
let mut compiled = 0;
|
||||
for (stem, p) in committed_profiles().expect("profiles") {
|
||||
if !p.fields().subgroup.maximal_reconvergence {
|
||||
continue;
|
||||
}
|
||||
for entry in ["rch_tangle_quad_after", "rch_tangle_quad_before"] {
|
||||
if compile(&tangle, entry, &p).is_err() {
|
||||
continue;
|
||||
}
|
||||
compiled += 1;
|
||||
let (mode, reconvergence, noted, _) = reading(&tangle, entry, &stem, &p);
|
||||
assert_eq!(
|
||||
(mode, reconvergence, noted),
|
||||
("maximal", Reconvergence::Guaranteed, false),
|
||||
"{stem} {entry}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(compiled > 0, "no profile compiled a quad operation");
|
||||
}
|
||||
@@ -129,6 +129,7 @@ mod engine_private_memory;
|
||||
mod engine_private_render_state;
|
||||
mod engine_profile_f;
|
||||
mod engine_pull_model;
|
||||
mod engine_quad_loops;
|
||||
mod engine_quad_ops;
|
||||
mod engine_qualified_signature;
|
||||
mod engine_rate_map;
|
||||
|
||||
+11
-3
@@ -1461,8 +1461,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). A note
|
||||
that holds only under some bound values is in `specialized_notes`;
|
||||
(`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
|
||||
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.
|
||||
Section 9 lists every note.
|
||||
@@ -1566,7 +1568,13 @@ 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. Static per stage: recorded for any tangled instruction in the entry.
|
||||
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.
|
||||
- `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
|
||||
|
||||
Reference in new issue
Block a user