Translator: the emitted words are the only words check; the size estimate goes

Selection summed a word cost per strategy and per interface part into a `SizeEstimate` and refused
the function `LimitExceeded(SpirvWords)` before emission when the sum passed the cap. The sum was a
forecast, not a bound, and it overshot: a guest kernel (function hash 4cc9c0bb, Iris profile, on
the command-line path) estimated 30,197,397 words against the 16,777,216 cap and emits 8,589,684
(job 62553), so it was
refused for a size it does not have. The cap already held exactly on the serialized module; that
check is now the only one (`pipeline::compile::lower_bounded`). That kernel is now refused by what
it holds, `LedgerBytes` at 450 MiB; a function the estimate overshot that fits the ledger can now
translate (none in this library does).

Removed with the estimate, as nothing else read them:
- `lower::estimate` (`SizeEstimate` and its frame costs), `Plan::estimate`, the check in
  `stage_bound::emit` (which no longer takes the cap) and the selection's block count;
- the word sums that fed only the estimate: the stage interface's (`StageIoPlan::words`, its
  parameter, object, store and rounding costs, and the fragment family's input attachments,
  discards, interlock, sample loop, snapshots, imageblock, storage form, shader stencil, logic
  operation, blends and word merges), the tessellation and mesh interfaces', the dispatch forms',
  a module blob's, the tile staging's, and the emulated tier's and the predicated walk's extra
  words, with `Predication::reloads`;
- the predicated walk's second structurization before emission, which only measured its
  constructs for the estimate (`structurize::emit::construct_words`).
The per-strategy costs and shared-routine costs the `StrategyCensus` reports stay.

Public: `EntryPlan::estimated_words` goes. The consumer's checkout (reims-vgpu at 44d738908a) has 0
hits for `estimated_words` and for `EntryPlan`. `tests/api_signatures.tsv` loses that one row;
`tests/api_surface.rs`'s pinned names do not move (`EntryPlan` stays).

Tests: the checks that the estimate bounds the emitted words go from the tests that also check
something else; the tests that checked only that go (every stage, simd, leaf, tail, coordinate,
bicubic, snapshot, pulled-fetch and shared-switch entry's estimate, the large predicated body under
a multiple of its words, and the skeleton's estimate bound). The word cap's test keeps both sides
on the emitted words: a module compiles at a cap of its own words and is refused one word below.

SEMANTICS 2253: a function the estimate refused can now translate, and the refusal of one that
does not fit names the ledger. docs/REFUSALS.md regenerated: `SpirvWords` has the one site.

Verified:
- The gate on this change over f3f661dd14 (job 62796): fmt, the API signatures, clippy plain,
  --cfg m2v_gpu and --cfg m2v_cpu_icd, workspace Rustdoc and doctests green; nextest of
  metal2vulkan and metal2vulkan-runtime 3464 of 3468, the four reds development's own suites show
  at f3f661dd14 (m3-max-62774): the old render descriptor key, which hashes SEMANTICS_VERSION,
  and the new icb_indexed_extras fixture's golden cells, AIR printout and inventory part, all
  blessed on development.
- Every kernel of the guest library (63, by hash), on the command-line path: intel-irisxe-anv's
  runtime-policy device file, the release command line before (fe1e8780a2) and with this change
  over it, alternately per kernel on one node (job 62742). 62 keep their outcome and their
  output's hash; the one difference is 4cc9c0bb, refused SpirvWords before and LedgerBytes after.
  It is the slowest row and the largest peak on both sides: 2.55 s and 309 MiB before, 2.86 s and
  470 MiB after (it now runs into emission before the ledger refuses it). Total wall 12.0 s
  before, 12.3 s after.
This commit is contained in:
Anees Iqbal committed 2026-11-21 02:53:10 -08:00
1 parent c5d4070850
commit 2a054f7785
74 files changed
+100 -2168

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
//! The killable worker boundary of validation sweeps.
//!
//! The engine is in-process only: it enforces its budgets deterministically (work units, the
//! byte ledger, the pre-emission size estimate, a transient wall deadline). The validation worker
//! byte ledger, the emitted-words cap, a transient wall deadline). The validation worker
//! is the backstop around it: one attempt per child process, supervised as a process group under
//! the 20-second and 500-MiB ceilings ([`process`]), with a counting global allocator ([`alloc`])
//! that both enforces the byte budget inside the child and measures the peak attributable bytes
+1 -1
View File
@@ -61,7 +61,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 = 2252;
pub const SEMANTICS_VERSION: u32 = 2253;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -347,26 +347,6 @@ impl TilePlan {
pub fn pass_cells(&self) -> Option<PassCells> {
self.pass_cells.filter(|c| c.staged)
}
/// An upper estimate of the words the staging adds: two loops, two barriers, the call, and
/// per staged slot its image, a read, a guarded leaf store, and a leaf load and write; per
/// word of the pass's imageblock storage, a read, a word store, a word load and a write.
pub fn words_estimate(&self) -> u64 {
let pass = match self.pass_cells() {
Some(_) => 96 + 64 * u64::from(self.cell_bytes / 4),
None => 0,
};
let per: u64 = pass
+ self
.staged()
.map(|s| 96 + 4 * u64::from(s.leaf.cost()))
.sum::<u64>();
if per == 0 {
0
} else {
256 + per
}
}
}
/// The alignment a constant byte offset guarantees (at most 16).
@@ -28,29 +28,6 @@ use crate::spirv::error::{BResult, BuildError, OperandRule};
use crate::spirv::ids::Value;
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, UnOp};
/// An upper estimate of the SPIR-V words of one channel's rounding by `rule`.
pub fn channel_words(rule: ChannelWrite) -> u64 {
match rule {
ChannelWrite::FloatTowardZero { .. } => 32 * 6,
// The rounding's bias and the denormal's shift clamped beside the toward-zero rule's.
ChannelWrite::FloatNearestEven { .. } => 36 * 6,
// Written as computed, or no rule [`round`] takes.
_ => 0,
}
}
/// An upper estimate of the SPIR-V words of rounding an output by `rules`, its extracts and
/// construct included.
pub fn words(rules: &[Option<ChannelWrite>; 4]) -> u64 {
let written = rules.iter().flatten().count() as u64;
rules
.iter()
.flatten()
.map(|&r| channel_words(r))
.sum::<u64>()
+ written.saturating_add(1).saturating_mul(6)
}
fn malformed() -> BuildError {
BuildError::Operand {
op: crate::spv::Op::ExtInst,
@@ -148,21 +148,6 @@ impl NativeBlend {
pub fn reads_second(&self) -> bool {
self.factors().into_iter().any(second_factor)
}
/// An upper estimate of the SPIR-V words of [`native`]: the clamps of the source, the second
/// source and the blend color, and per class two factors, two products and the operation.
pub fn words(&self) -> u32 {
const CLAMP: u32 = 8 * 6;
const CLASS: u32 = 12 * 6;
let mut words = CLAMP + 3 * 6;
if self.reads_second() {
words += CLAMP;
}
if self.reads_constant() {
words += CLAMP + 2 * 6;
}
words + CLASS * (u32::from(self.color) + u32::from(self.alpha))
}
}
/// The values a native blend's factors read, `vec4`s of `f32`.
@@ -1368,51 +1353,6 @@ impl Blend {
.flatten()
.any(|a| nodes(a).into_iter().any(second))
}
/// An upper estimate of the SPIR-V words of the blend: the source's clamp and the lanes'
/// combination, the blend color's clamp, and each class's node reads, roundings to `half`,
/// and exact sums.
pub fn words(&self) -> u32 {
const BASE: u32 = 60 * 6;
const NODE: u32 = 6 * 6;
const ROUND: u32 = 48 * 6;
const SUM: u32 = 36 * 6;
let mut words = BASE;
// The second source's clamp, as the source's.
if self.reads_second() {
words = words.saturating_add(BASE / 2);
}
const CONSTANT: u32 = 18 * 6;
if self.reads_constant() {
words = words.saturating_add(CONSTANT);
}
for a in [&self.color, &self.alpha].into_iter().flatten() {
let (rounds, sums) = match a {
Arith::MinMax { .. } | Arith::Zero => (1, 0),
Arith::Term { .. } | Arith::Common { .. } => (1, 0),
Arith::Fused { .. } | Arith::Lerp { .. } => (1, 1),
Arith::Contracted { .. } => (2, 1),
Arith::Rounded { .. } => (3, 1),
};
let inner = match a {
Arith::Lerp { inner, .. } | Arith::Common { inner, .. } => {
inner.len().saturating_sub(1) as u32
}
_ => 0,
};
let ns = nodes(a);
// A one-minus or saturated node rounds once.
let node_rounds = ns
.iter()
.filter(|n| matches!(n, Node::OneMinus(_) | Node::Saturate))
.count() as u32;
words = words
.saturating_add(NODE.saturating_mul(ns.len() as u32))
.saturating_add(ROUND.saturating_mul(rounds + inner + node_rounds))
.saturating_add(SUM.saturating_mul(sums + inner));
}
words
}
}
/// Whether `a` is a difference of a blend constant's product and its one minus's (`BlendColor` with
-13
View File
@@ -541,19 +541,6 @@ pub struct DispatchPlan {
pub private_arena: bool,
}
/// The words a flat grid adds: its thread's index, position, and early return, derived once for the
/// return and once more for a `thread_position_in_grid` parameter.
pub const FLAT_GRID_WORDS: u64 = 400;
/// The words a folded variant adds: its threadgroup's index, position, and early return, derived
/// once for the return and once more for each grid position parameter.
pub const FOLDED_GROUPS_WORDS: u64 = 500;
/// The words a kernel's partial threadgroups add per derivation of their threads (the region's
/// flag, the threadgroup's position and threads, and the test or the position over them): once
/// for the test before the body, and once more for each builtin parameter.
pub const PARTIAL_THREADGROUPS_WORDS: u64 = 300;
/// The dispatch family's module-scope objects: the kernel's, when the plan has one.
#[derive(Clone, Debug, Default)]
pub struct Declared {
-89
View File
@@ -1,89 +0,0 @@
//! `SizeEstimate` and the `SpirvWords` checks.
//!
//! `select` sums a word cost per strategy (each family states its variants' costs,
//! `FamilyStrategy::words`) plus the fixed costs of the module frame, the declarations, and the
//! structured control flow, and refuses the function with `LimitExceeded(SpirvWords)` before
//! anything is emitted when the sum exceeds the cap (`budget::SPIRV_WORDS`, provisional until
//! phase 6 re-sets it from the old translator's output).
//!
//! The sum is a forecast, not a bound: each family states its costs from its own lowering, and
//! a function can emit more than their sum (one corpus row emits 744 words on `moltenvk-m3`
//! against an estimate of 581, 512 of them in its body, where its texture and arithmetic
//! strategies estimate 361). The early check saves emitting a function whose forecast is
//! already too large; the cap itself holds on the serialized words ([`check_emitted`]), so no
//! artifact above it is kept whatever the estimate said.
use crate::error::{Error, Limit};
/// Header, capabilities, memory model, entry point, the function frame, and the base types.
pub const MODULE_WORDS: u64 = 128;
/// One descriptor (a buffer view, an image, a sampler, the status binding): its types, variable,
/// and decorations.
pub const SLOT_WORDS: u64 = 40;
/// One push member: its type share, offset decoration, and access.
pub const PUSH_FIELD_WORDS: u64 = 12;
/// One AIR block after structurization: labels, merges, branches, and its share of the
/// structurizer's selector traffic (`Limit::OutputBlocks` bounds the block count).
pub const BLOCK_WORDS: u64 = 24;
/// One demoted value or phi variable: its declaration, stores, and loads.
pub const VARIABLE_WORDS: u64 = 16;
/// The planned output size of one function, in SPIR-V words.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SizeEstimate {
pub words: u64,
}
impl SizeEstimate {
/// Add `words`, saturating.
pub fn add(&mut self, words: u64) {
self.words = self.words.saturating_add(words);
}
/// Refuse an estimate above `cap` (`LimitExceeded(SpirvWords)`).
pub fn check(&self, cap: u64) -> Result<(), Error> {
if self.words > cap {
Err(Error::LimitExceeded(Limit::SpirvWords))
} else {
Ok(())
}
}
}
/// Refuse a serialized module of `words` words above `cap` (`LimitExceeded(SpirvWords)`): the exact
/// form of [`SizeEstimate::check`], which the estimate cannot guarantee.
pub fn check_emitted(words: usize, cap: u64) -> Result<(), Error> {
if u64::try_from(words).map_or(true, |w| w > cap) {
Err(Error::LimitExceeded(Limit::SpirvWords))
} else {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_estimate_above_the_cap_is_refused() {
let mut e = SizeEstimate::default();
e.add(MODULE_WORDS);
assert_eq!(e.check(MODULE_WORDS), Ok(()));
e.add(1);
assert_eq!(
e.check(MODULE_WORDS),
Err(Error::LimitExceeded(Limit::SpirvWords))
);
e.add(u64::MAX);
assert_eq!(e.words, u64::MAX, "saturates");
}
#[test]
fn emitted_words_above_the_cap_are_refused() {
assert_eq!(check_emitted(128, 128), Ok(()));
assert_eq!(
check_emitted(129, 128),
Err(Error::LimitExceeded(Limit::SpirvWords))
);
}
}
@@ -120,12 +120,6 @@ pub struct ColorInput {
pub alpha_red: bool,
}
/// An upper estimate of the words one input attachment declares (type, variable, decorations).
const OBJECT_WORDS: u64 = 32;
/// An upper estimate of the words one read adds (load, the sample's load, image read, lane
/// extraction, mask or rounding).
const READ_WORDS: u64 = 32;
/// The form of a color value of AIR type `ty`, read or written: a scalar or 2 to 4 lanes of
/// 32-bit held integers or floats. A 64-bit one is not Metal's (`refuse_int64_interface`);
/// `bool`, other widths, and aggregates are not lowered.
@@ -398,49 +392,6 @@ pub(crate) fn texture_decl(class: ImageHandleClass) -> ImageDecl {
}
}
/// How many uses the body makes of the planned color inputs.
pub(super) fn uses(cx: &SelectCx<'_>, colors: &[ColorInput]) -> u64 {
let mut uses = 0u64;
for inst in cx.body.insts.values() {
inst.kind.for_each_value(|v| {
if let Value::Arg(a) = v {
if colors.iter().any(|c| c.param == a.raw()) {
uses += 1;
}
}
});
}
uses
}
/// The words the planned input attachments add: one object per attachment and one read per use
/// (the storage form's are `fetch::words`).
pub(super) fn words(cx: &SelectCx<'_>, colors: &[ColorInput]) -> u64 {
let uses = uses(cx, colors);
// An extended-range attachment's read decodes its raw texel.
let extended: Vec<ColorInput> = colors
.iter()
.filter(|c| c.extended.is_some())
.copied()
.collect();
let decodes = self::uses(cx, &extended);
// An alpha-in-red attachment's read moves its red to alpha: a shuffle and its zero.
let red: Vec<ColorInput> = colors.iter().filter(|c| c.alpha_red).copied().collect();
let moves = self::uses(cx, &red);
let mut attachments: Vec<u32> = colors.iter().map(|c| c.color).collect();
attachments.sort_unstable();
attachments.dedup();
OBJECT_WORDS
.saturating_mul(attachments.len() as u64)
.saturating_add(READ_WORDS.saturating_mul(uses))
.saturating_add(u64::from(extended_range::DECODE_WORDS + 120).saturating_mul(decodes))
.saturating_add(ALPHA_IN_RED_WORDS.saturating_mul(moves))
}
/// An upper estimate of the words [`alpha_in_red`] adds: the shuffle, and the zero vector's
/// constant and type.
pub(super) const ALPHA_IN_RED_WORDS: u64 = 16;
/// Declare one input attachment per color index the plan reads, multisampled for a per-sample
/// function (`multisampled`), or its storage image in the interlocked storage form (`fetch`), which
/// holds the samples as its view states; the storage image of every other attachment in that form
@@ -92,11 +92,6 @@ pub struct CoveragePlan {
pub samples_before_loop: Option<u32>,
}
/// An upper estimate of the words the looping entry adds around the body function: its function
/// type, the entry function, the loop's blocks and merges, the mask's load, the bit's extraction,
/// the call, the `rest` variable's loads and stores, and the union of the kept samples.
pub(super) const LOOP_WORDS: u64 = 144;
fn invariant(msg: &'static str) -> Error {
Error::Internal(InternalError::new(InternalKind::Invariant, msg))
}
+1 -155
View File
@@ -295,7 +295,7 @@
use std::collections::{BTreeMap, BTreeSet};
use crate::air::abi::{AbiInt, OutputRole, ParamRole};
use crate::air::intrinsics::{AirIntrinsic, Fragment, PackDir, PackFormat};
use crate::air::intrinsics::{AirIntrinsic, Fragment, PackFormat};
use crate::air::ir::{Callee, InstKind, Type as AirType, TypeId as AirTypeId, Value};
use crate::device::requirements::{FormatUsage, VkFeature};
use crate::device::DeviceProfile;
@@ -2191,150 +2191,6 @@ pub(super) fn finish(cx: &SelectCx<'_>) -> Result<(), Error> {
Ok(())
}
/// An upper estimate of the words the storage form adds: one object per attachment, the pixel's
/// coordinate (and sample) and a read per use, and at each of `rets` returns the coordinate, the
/// guard (with the returned mask's bit), and a write per written attachment (a read first where
/// it merges kept channels, and a decode, blend, and encode where it blends an extended-range
/// texel; an exchange of red and blue per read and write of an attachment viewed in its
/// RGBA-order twin).
pub(super) fn words(cx: &SelectCx<'_>, uses: u64, rets: u64) -> u64 {
const OBJECT: u64 = 40;
const READ: u64 = 56;
const WRITE: u64 = 56;
let fetch = &cx.families.fragment.fetch;
if fetch.is_empty() {
return 0;
}
let written = fetch.values().filter(|sc| sc.writes).count() as u64;
let merged = fetch.values().filter(|sc| sc.view.merges()).count() as u64;
// A merge of the draw's kept channels tests four bits and selects.
const KEPT_AT_DRAW: u64 = 40;
let at_draw = fetch.values().filter(|sc| sc.view.kept_at_draw).count() as u64;
// An extended-range attachment's blended write reads, decodes, blends, and encodes its
// texel, its blend's words by its arithmetic, the larger of a `half4` and a `float4` output's;
// an unblended one rounds and encodes the output.
let blend: u64 = fetch
.values()
.filter_map(|sc| {
[FloatFmt::Half, FloatFmt::F32]
.into_iter()
.filter_map(|o| match blend_of(&sc.view, Some(o)) {
Ok(Some(b)) => Some(u64::from(b.words())),
_ => None,
})
.max()
})
.map(|b| {
READ.saturating_add(b).saturating_add(u64::from(
extended_range::DECODE_WORDS + extended_range::ENCODE_WORDS,
))
})
.fold(0u64, u64::saturating_add);
// A 16-bit float attachment's blended write (and a generic one, in `float`, its source and
// blend color clamped) reads its texel and blends in `half`, or in `float` with exact
// multiply-adds (twice the words) and Metal's conversion of the result; an
// 8-bit unorm one's clamps the output and decodes the codes (the storage image's store
// converts the result); a
// packed 16-bit one's clamps the output and rounds it to `half`, and decodes the word.
let sixteen: u64 = fetch
.values()
.filter(|sc| sc.view.extended.is_none())
.filter_map(|sc| {
let eq = sc.view.blend?;
let kept = self::written(sc.view.kept);
let pf = sc.view.pixel_format;
let half = extended_range::blend::BlendArith::Half;
let b = match sc.view.generic_blend {
true => generic(&eq, pf, kept).ok()?,
false => direct_blend(&eq, pf, kept, (blend_math(cx), half)).ok()?,
};
let unorm8 = match unorm8_format(pf) {
true => 48 * 6,
false => 0,
};
let packed = match sc.view.word {
Some(_) => 48 * 6 + stage_io::word_color::DECODE_WORDS,
None => 0,
};
Some(
READ.saturating_add(2 * u64::from(b.words()))
.saturating_add(32 * 6)
.saturating_add(unorm8)
.saturating_add(packed),
)
})
.fold(0u64, u64::saturating_add);
let unblended = fetch
.values()
.filter(|sc| sc.writes && sc.view.extended.is_some() && sc.view.blend.is_none())
.count() as u64;
// An extended-range attachment's read decodes its texel, an sRGB one's reorders its bytes and
// decodes them (`arith::pack::unpack`).
// An RGBA-order view's read and write exchange red and blue: one shuffle each.
const EXCHANGE: u64 = 10;
let exchanged = fetch
.values()
.filter(|sc| sc.view.rgba_view.is_some())
.count() as u64;
// An alpha-in-red image's read moves its red to alpha, and its write alpha to red.
let moved = fetch.values().filter(|sc| sc.view.alpha_in_red).count() as u64;
let read = match (
fetch.values().any(|sc| sc.view.extended.is_some()),
fetch.values().any(|sc| sc.view.uint_view.is_some()),
) {
(true, _) => READ.saturating_add(u64::from(extended_range::DECODE_WORDS) + 120),
(false, true) => READ.saturating_add(u64::from(srgb_words(PackDir::Unpack)) + 120),
(false, false) => READ,
}
// A packed 16-bit word attachment's read decodes the word's four fields. Added, not chosen:
// a function may read such an attachment beside one of another kind, and every use takes the
// larger shape.
.saturating_add(match fetch.values().any(|sc| sc.view.word.is_some()) {
true => stage_io::word_color::DECODE_WORDS,
false => 0,
})
.saturating_add(EXCHANGE.saturating_mul(exchanged))
.saturating_add(super::color::ALPHA_IN_RED_WORDS.saturating_mul(moved));
// An sRGB attachment's write encodes four channels (`arith::pack::pack`), reorders its bytes,
// and merges kept ones from the texel it reads first.
let srgb_writes = fetch
.values()
.filter(|sc| sc.writes && sc.view.uint_view.is_some())
.count() as u64;
let srgb_write = READ.saturating_add(u64::from(srgb_words(PackDir::Pack)) + 120);
// A word attachment's write encodes Metal's word and merges the kept fields: its kept mask
// from the draw's four bits (a test and a select per field).
let word_write: u64 = fetch
.values()
.filter(|sc| sc.writes)
.filter_map(|sc| sc.view.word)
.map(|w| stage_io::word_color::encode_words(w) + 4 * 24 + 40)
.fold(0u64, u64::saturating_add);
// A logic-operated write reads its texel and operates on each channel's codes.
let logic = fetch
.values()
.filter(|sc| sc.view.logic_op.is_some())
.count() as u64;
let logic_write = READ.saturating_add(super::logic::WRITE_WORDS);
let write = WRITE
.saturating_mul(written)
.saturating_add(READ.saturating_mul(merged))
.saturating_add(KEPT_AT_DRAW.saturating_mul(at_draw))
.saturating_add(blend)
.saturating_add(sixteen)
.saturating_add(stage_io::extended_color::WORDS.saturating_mul(unblended))
.saturating_add(srgb_write.saturating_mul(srgb_writes))
.saturating_add(word_write)
.saturating_add(logic_write.saturating_mul(logic))
.saturating_add((2 * EXCHANGE).saturating_mul(exchanged))
.saturating_add((EXCHANGE + super::color::ALPHA_IN_RED_WORDS).saturating_mul(moved))
.saturating_add(40);
OBJECT
.saturating_mul(fetch.len() as u64)
.saturating_add(read.saturating_mul(uses))
.saturating_add(rets.saturating_mul(write))
}
/// Declare storage-form attachment `color`'s storage image: a 2D storage image of its declared
/// format and its numeric type, multisampled or arrayed as it holds the samples
/// ([`StorageSamples`]).
@@ -3154,16 +3010,6 @@ fn blended(
extended_range::encode_keeping(fb, range, v, (texel, kept))
}
/// An upper estimate of the SPIR-V words of an sRGB texel's conversion in direction `dir`
/// ([`srgb_decode`], [`srgb_texel`]'s encode).
fn srgb_words(dir: PackDir) -> u32 {
let f4 = Form {
held: Held::Float(FloatFmt::F32),
lanes: 4,
};
pack::words(PackFormat::Unorm4x8Srgb, dir, f4)
}
/// The bytes of a texel of the sRGB format `format` held in one `u32` (`word`, the texel's bytes
/// in memory order), in red, green, blue, alpha order, as `arith::pack`'s `pack` and `unpack` hold
/// `unorm4x8_srgb`'s: `B8G8R8A8_SRGB`'s blue and red bytes swapped, `R8G8B8A8_SRGB`'s as they
@@ -151,29 +151,6 @@ pub struct ImageblockPlan {
pub early_tests: bool,
}
/// An upper estimate of the words one view's members add (each leaf read or written, and a
/// sub-word write's read).
fn view_words(v: Option<&(u32, View)>) -> u64 {
v.map_or(0, |(_, v)| {
v.members.iter().map(|m| u64::from(m.leaf.cost()) * 2).sum()
})
}
impl ImageblockPlan {
/// An upper estimate of the words the imageblock adds to a function of `rets` returns: the
/// input view once, in the first block, and, when the function writes an output view, at
/// each return the pixel's load and conversion, the image load, the discard guard, and the
/// output view (a function without one emits nothing at its returns).
pub fn words_estimate(&self, rets: u64) -> u64 {
let at_return = if self.output.is_some() {
64 + view_words(self.output.as_ref())
} else {
0
};
(64 + view_words(self.input.as_ref())).saturating_add(rets.saturating_mul(at_return))
}
}
/// The alignment a constant byte offset guarantees (at most 16).
fn offset_align(offset: u32) -> u64 {
1u64 << offset.trailing_zeros().min(4)
@@ -870,9 +847,6 @@ mod tests {
use super::*;
use crate::air::abi::{MemberKind, UserKey};
use crate::air::error::DiagName;
use crate::lower::arith::{Form, Held};
use crate::memory::leaf::Path;
use crate::spirv::ids::ScalarTy;
fn member(offset: u32, key: &str, layout: Option<u32>) -> Member {
Member {
@@ -937,54 +911,4 @@ mod tests {
}];
assert!(fingerprint(&cycle, StructRef(0), 16).is_none());
}
fn view(members: u32) -> View {
let leaf = Leaf {
form: Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes: 1,
},
bytes: 4,
path: Path::Aligned,
};
View {
members: (0..members)
.map(|i| ViewMember {
field: i,
leaf,
offset: i * 4,
})
.collect(),
ty: DemoteTy::Scalar(ScalarTy::Int { bits: 32 }),
}
}
/// The estimate counts the input view once and the output view at every return; a function
/// without an output view emits nothing at its returns.
#[test]
fn the_estimate_scales_the_output_view_with_the_returns() {
let input = ImageblockPlan {
input: Some((0, view(2))),
..ImageblockPlan::default()
};
assert_eq!(input.words_estimate(1), input.words_estimate(7));
let output = ImageblockPlan {
output: Some((0, view(2))),
..ImageblockPlan::default()
};
let (one, three) = (output.words_estimate(1), output.words_estimate(3));
let per_return = one - output.words_estimate(0);
assert!(per_return > 64, "{per_return}");
assert_eq!(three, output.words_estimate(0) + 3 * per_return);
let wider = ImageblockPlan {
output: Some((0, view(4))),
..ImageblockPlan::default()
};
assert!(
wider.words_estimate(3) - wider.words_estimate(0) > three - output.words_estimate(0)
);
}
}
@@ -121,10 +121,6 @@ impl RotatedInputBlend {
}
}
/// An upper estimate of the words one blended write adds beside its blend's arithmetic: the
/// input attachment's read, its decode, the encode, and a merge of kept channels.
const WRITE_WORDS: u64 = 120;
/// Whether the device orders framebuffer fetch through rasterization-order input attachments,
/// where this module computes an extended-range blend (on one that orders it through the pixel
/// interlock, the storage form does, `fetch::interlock_orders`).
@@ -504,33 +500,3 @@ pub(crate) fn rotated_texel(
};
extended_range::blend::blend_unorm8(fb, &b, arith, (part, texel), constant)
}
/// The words the planned blends add at `rets` returns: one input attachment each beside the
/// reads `color` counts, and at each return the read, decode, blend and encode.
pub(super) fn words(cx: &SelectCx<'_>, rets: u64) -> u64 {
let fp = &cx.families.fragment;
let extended = fp.input_blends.values().filter(|ib| ib.reads()).map(|ib| {
let blend = ib.blend.as_ref().map_or(0, |b| b.words());
let each = WRITE_WORDS
.saturating_add(u64::from(blend))
.saturating_add(u64::from(
extended_range::DECODE_WORDS + extended_range::ENCODE_WORDS,
));
each.saturating_mul(rets.max(1))
});
let math = fetch::blend_math(cx);
let rotated = fp
.rotated_blends
.values()
.filter(|rb| rb.reads())
.map(|rb| {
let half = extended_range::blend::BlendArith::Half;
let pf = PixelFormat::ARGB8Unorm;
let blend = extended_range::Blend::unorm8(&rb.equation, pf, rb.written, (math, half))
.map_or(0, |b| b.words());
WRITE_WORDS
.saturating_add(u64::from(blend))
.saturating_mul(rets.max(1))
});
extended.chain(rotated).fold(0u64, u64::saturating_add)
}
@@ -95,13 +95,6 @@ pub struct LogicChannels {
pub bits: [Option<u32>; 4],
}
/// An upper estimate of the words one channel's operation adds: the two codes, the operation, the
/// mask and the value written.
const CHANNEL_WORDS: u64 = 64;
/// An upper estimate of the words the operation of one write adds.
pub(crate) const WRITE_WORDS: u64 = 4 * CHANNEL_WORDS + 24;
/// The channels of a color attachment of `pf` whose logic operation the function computes (see
/// the module docs): every channel an 8-, 10- or 16-bit unorm one (a 10-bit format's alpha 2-bit),
/// an 8- or 16-bit snorm one, or an 8-, 16- or 32-bit integer one; `None` for another format.
@@ -538,12 +531,5 @@ pub(crate) fn input_operated(
operated(fb, li.op, li.channels, (form, part), texel)
}
/// The words the planned operations add at `rets` returns: one input attachment each, and at
/// each return the read and the operation.
pub(super) fn words(cx: &SelectCx<'_>, rets: u64) -> u64 {
let planned = cx.families.fragment.logic_inputs.len() as u64;
planned.saturating_mul(32u64.saturating_add(WRITE_WORDS.saturating_mul(rets.max(1))))
}
#[cfg(test)]
mod tests;
+1 -64
View File
@@ -287,19 +287,6 @@ impl FragmentPlan {
}
}
/// An upper estimate of the words `if discarded { kill }` adds at one return.
const RETURN_KILL_WORDS: u64 = 16;
/// An upper estimate of the words one whole-quad exit adds: two loads, an `or`, three quad swaps
/// and their direction constants, three `and`s, and `if all { kill }`.
const QUAD_EXIT_WORDS: u64 = 48;
/// An upper estimate of the words the interlocked entry adds around the body function: its
/// function type, the entry function, `Begin`, the call, `End`, the kill, and the return.
const WRAPPER_WORDS: u64 = 48;
/// An upper estimate of the words the guard of one side effect adds ([`not_discarded`]): the load of
/// `discarded` and its negation, the selection's merge, branch, three labels and two branches,
/// and for a result its phi and zero.
const GUARD_WORDS: u64 = 40;
/// Whether the function runs a quad or simdgroup operation whose answer depends on which of
/// its group's lanes are active (`GroupOp::reads_active_lanes`).
fn counts_active_lanes(cx: &SelectCx<'_>) -> bool {
@@ -315,19 +302,8 @@ fn counts_active_lanes(cx: &SelectCx<'_>) -> bool {
})
}
/// How many returns the function's body has.
fn returns(cx: &SelectCx<'_>) -> u64 {
cx.body
.insts
.values()
.filter(|i| matches!(i.kind, InstKind::Ret(_)))
.count() as u64
}
/// Complete the fragment family's plan once every instruction and parameter is selected: the
/// interlock of a function in a raster order group, the form of each discard site, and the words
/// the input attachments, the predicated returns, and the interlocked entry add to the stage
/// interface's size estimate.
/// interlock of a function in a raster order group and the form of each discard site.
pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> {
// A device may shade a triangle it clips as several, and then a quad a seam crosses runs
// once per piece: a fragment function's operation over the active lanes sees each piece's
@@ -368,45 +344,6 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> {
simd.cluster_ops = simd.cluster_ops.union(OpBits::QUAD);
simd.groups = true;
}
// Inside an interlocked body the returns do not kill: `main` kills once, after `End`.
let predicated = interlock.is_none() && forms.values().any(|f| *f == DiscardForm::Predicate);
// The returns, counted only where something is emitted at each of them.
let rets = if predicated || cx.families.fragment.imageblock.is_some() || storage {
returns(cx)
} else {
0
};
let killing_rets = if predicated { rets } else { 0 };
let wrapper = if interlock.is_some() {
WRAPPER_WORDS
} else if looped {
coverage::LOOP_WORDS
} else {
0
};
// The imageblock output is written at every return.
let imageblock = cx
.families
.fragment
.imageblock
.as_ref()
.map_or(0, |p| p.words_estimate(rets));
let words = color::words(cx, &cx.families.fragment.colors)
.saturating_add(fetch::words(
cx,
color::uses(cx, &cx.families.fragment.colors),
rets,
))
.saturating_add(stencil::words(cx, rets))
.saturating_add(input_blend::words(cx, returns(cx)))
.saturating_add(word_input::words(cx, returns(cx)))
.saturating_add(logic::words(cx, returns(cx)))
.saturating_add(killing_rets.saturating_mul(RETURN_KILL_WORDS))
.saturating_add((quad_exits.len() as u64).saturating_mul(QUAD_EXIT_WORDS))
.saturating_add((guarded.len() as u64).saturating_mul(GUARD_WORDS))
.saturating_add(wrapper)
.saturating_add(imageblock);
stage_io::add_interface_words(cx, words);
// The requirement is the feature alone: a Vulkan 1.3 device has it in core, and below 1.3
// the description lists it only with its extension.
let terminate = cx.profile.fields().fragment.terminate_invocation;
@@ -128,14 +128,6 @@ use crate::spirv::ir::{
ImageUsage, MemAccess, StorageClass, TexelMemory, Type as SType, UnOp,
};
/// An upper estimate of the words the entry's block adds: the helper's copy, the phase's test,
/// the interlock, the two selections and the return.
const BLOCK_WORDS: u64 = 80;
/// An upper estimate of the words one slot adds: its snapshot's variable, type and decorations, the
/// pixel, the copy's fetch, encode and write, and at a read the selection, the read and its decode
/// (a signed normalized form's, the longest: the sign's extension, the product and the bound).
const SLOT_WORDS: u64 = 400;
/// The fragment texture slots function `cx` reads through a snapshot, from its lowering inputs:
/// the stage interface's `FragCoord`, the phase's push field and each snapshot's storage image are
/// planned for them. A function with another interlock or a loop over its covered samples has none
@@ -181,8 +173,6 @@ pub(super) fn finish(
}
let n = u32::try_from(slots.len()).unwrap_or(u32::MAX);
cx.descriptors.storage_images = cx.descriptors.storage_images.saturating_add(n);
let words = BLOCK_WORDS.saturating_add(SLOT_WORDS.saturating_mul(u64::from(n)));
stage_io::add_interface_words(cx, words);
Ok(slots)
}
@@ -222,25 +222,6 @@ pub(super) fn finish(cx: &SelectCx<'_>) -> Result<(), Error> {
Ok(())
}
/// An upper estimate of the words the form adds: the shadow and its type, and at each of `rets`
/// returns the guard, the state's fields, the comparison and operation selections, and the read
/// and write (with the multisampled form's loop over the samples, its variables, and the mask's
/// writes).
pub(super) fn words(cx: &SelectCx<'_>, rets: u64) -> u64 {
const OBJECT: u64 = 40;
const RETURN: u64 = 480;
const SAMPLES: u64 = 160;
let Some(plan) = cx.families.fragment.stencil else {
return 0;
};
let per_return = if plan.samples.is_some() {
RETURN + SAMPLES
} else {
RETURN
};
OBJECT.saturating_add(rets.saturating_mul(per_return))
}
/// Declare the shadow: a 2D `uint` storage image of the planned declaration, multisampled for the
/// multisampled form.
pub(super) fn declare(
@@ -36,10 +36,6 @@ use crate::spirv::ir::BinOp;
use super::fetch;
/// An upper estimate of the words one merge adds at a return: the input attachment's read, the
/// word's extraction, and the masks and merge.
const MERGE_WORDS: u64 = 48;
/// The bits of `word`'s fields of the channels `kept`.
fn kept_bits(word: WordAttachment, kept: ColorWriteMask) -> u32 {
[
@@ -134,10 +130,3 @@ pub(crate) fn merge(
let word = fb.binary(BinOp::BitwiseAnd, word, take)?;
fb.binary(BinOp::BitwiseOr, read, word)
}
/// The words the planned merges add at `rets` returns: one input attachment each, and at each
/// return the read and the merge.
pub(super) fn words(cx: &SelectCx<'_>, rets: u64) -> u64 {
let merges = cx.families.fragment.word_merges.len() as u64;
merges.saturating_mul(32u64.saturating_add(MERGE_WORDS.saturating_mul(rets.max(1))))
}
-12
View File
@@ -305,18 +305,6 @@ impl FamilyStrategy for MeshStrategy {
}
}
/// The words an entry wrapper adds to the size estimate: its loops, barriers and stores.
pub const WRAPPER_WORDS: u64 = 400;
/// The words the family adds beyond its operations.
pub fn estimate_words(plan: &MeshPlan) -> u64 {
if plan.object || plan.mesh.is_some() {
WRAPPER_WORDS + 16 * plan.outputs.len() as u64
} else {
0
}
}
/// The mesh output type of the entry's `air.mesh` parameter.
fn mesh_outputs<'e>(cx: &SelectCx<'e>) -> Option<&'e MeshOutputs> {
cx.entry.ep.params.iter().find_map(|b| match &b.role {
+2 -4
View File
@@ -4,12 +4,11 @@
//! `strategy.rs`, `emit.rs`, `push.rs`, or this file:
//!
//! - [`select`]: the total routing of every instruction, intrinsic family, and parameter, and the
//! per-function [`select::Plan`] (push placement, size estimate).
//! per-function [`select::Plan`] (push placement).
//! - [`strategy`]: [`strategy::Strategy`], one variant per family wrapping its own enum.
//! - [`emit`]: [`emit::Emitter`], the `CodeEmitter` that routes each strategy to its family's
//! emit function, and the module driver.
//! - [`push`]: the complete placement algorithm; [`estimate`]: `SizeEstimate`;
//! [`view`]: the structurizer's `CfgView`.
//! - [`push`]: the complete placement algorithm; [`view`]: the structurizer's `CfgView`.
//! - Families: [`arith`], [`access`], [`texture`], [`sampler`], [`simd`], [`sync`] (`memory_model`,
//! `barrier`), [`fragment`], [`stage_io`], [`dispatch`], [`raytracing`], [`mesh`]. A family
//! refuses what it does not lower as `Unsupported{Lowering(family), NotImplemented}`; the
@@ -28,7 +27,6 @@ pub mod access;
pub mod arith;
pub mod dispatch;
pub mod emit;
pub mod estimate;
pub mod fragment;
pub mod mesh;
pub mod push;
@@ -202,8 +202,7 @@ const INTERSECT_FIELD_WORDS: u32 = 12;
/// An upper estimate of reading a candidate's intersection function table entry: the bind
/// residual, the bound range, three contained word reads, and the acceptance. Measured:
/// `kernel_instance_as_intersect.ll` emits 188 words more than its null-table variant on
/// `lavapipe`, the table's descriptor included, which the estimate prices at
/// `estimate::SLOT_WORDS` (40) besides these words.
/// `lavapipe`, the table's descriptor included.
const INTERSECT_TABLE_WORDS: u32 = 170;
/// An upper estimate of a multi-level intersector's id writes besides their two stores: the two
/// committed gets, their merge with the miss, and the hit's branch.
@@ -155,9 +155,7 @@ impl Bicubic {
/// conversions; for a 2D texture the small level's test and linear sample ([`SMALL_WORDS`], its
/// four taps' conversions on a raw sample) and each mirrored axis's pinned footprint
/// ([`PINNED_WORDS`]), and Metal's offset rule on each axis a constant offset moves
/// (`position::OFFSET_RULE_WORDS`). The estimate bounds every public bicubic fixture
/// (`the_estimate_bounds_the_bicubic_fixtures`), every raw form
/// (`the_srgb_estimate_bounds_its_emission`), and the mirrored forms (`mirrored_axes`).
/// (`position::OFFSET_RULE_WORDS`).
pub(super) fn words(&self) -> u32 {
let (base, taps) = if self.linear_only() {
(448, 2)
+3 -102
View File
@@ -32,8 +32,8 @@
//! `finish`), the slots' forms, extra transport, and push-table support
//! (`access::finish_slots`, `access::accept_placement`), and the accumulators of [`SelectCx`]:
//! descriptor counts per kind ([`DescriptorCounts`]), the simd class, and tangled instructions.
//! The generic checks over those accumulators (per-stage descriptor limits, the subgroup tier,
//! the size estimate) stay here.
//! The generic checks over those accumulators (per-stage descriptor limits and the subgroup
//! tier) stay here.
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
@@ -55,7 +55,6 @@ use crate::error::{
Capability, DiagName, Error, Feature, InternalError, InternalKind, LowerFamily, Unsupported,
};
use crate::lower::dispatch::DispatchPlan;
use crate::lower::estimate::{self, SizeEstimate};
use crate::lower::push;
use crate::lower::strategy::{FamilyStrategy, Strategy};
use crate::lower::{
@@ -401,7 +400,6 @@ pub struct Plan {
/// The notes of `precision` an access keeps only on the arms its specialization selects,
/// with their conditions ([`resolve_notes`]).
pub specialized: Vec<SpecializedNote>,
pub estimate: SizeEstimate,
/// The private memory a thread keeps, in bytes, as selection holds it to the device's
/// Function storage (`MemoryPlan::private_bytes`).
pub private_bytes: u64,
@@ -1337,7 +1335,6 @@ struct BodySelection {
selectors: BTreeMap<ValueId, SelectorForm>,
cross: Vec<(ValueId, DemoteTy)>,
phis: Vec<(ValueId, DemoteTy)>,
blocks: u64,
}
/// A texture or sampler family's refusal of an `air.*` call that names nothing names the
@@ -1427,9 +1424,7 @@ fn select_body(
// The `half` chains' operations held at `float` precision, before any of them is selected.
cx.families.arith.held_at_float = arith::half_chain::plan(cx, m)?;
let mut blocks = 0u64;
for (b, block) in body.blocks.iter() {
blocks += 1;
for id in block.inst_ids() {
m.tick(1)?;
let inst = body
@@ -1624,7 +1619,6 @@ fn select_body(
selectors,
cross: cross.into_iter().collect(),
phis,
blocks,
})
}
@@ -1775,76 +1769,8 @@ fn finish(
cx.families.texture.absent_arm =
texture::absent_arm(cx.entry, cx.body, &sel.strategy, cx.values, m)?;
let mut estimate = SizeEstimate::default();
estimate.add(estimate::MODULE_WORDS);
estimate.add(estimate::SLOT_WORDS.saturating_mul(descriptors.descriptors()));
estimate.add(estimate::PUSH_FIELD_WORDS.saturating_mul(placement.fields.len() as u64));
estimate.add(estimate::BLOCK_WORDS.saturating_mul(sel.blocks));
estimate
.add(estimate::VARIABLE_WORDS.saturating_mul((sel.cross.len() + sel.phis.len()) as u64));
for s in sel.strategy.iter().flatten() {
estimate.add(u64::from(s.words()));
// The separate form's sampled images.
let separate = separate_samplings(&cx.families, s);
estimate.add(u64::from(separate) * u64::from(sampler::SEPARATE_WORDS));
if tier == Tier::Emulated {
estimate.add(u64::from(simd::workgroup::extra_words(s)));
}
}
for v in &cx.families.simd.partly_live {
if let Some(s) = sel.strategy.get(v.index()).and_then(Option::as_ref) {
estimate.add(u64::from(simd::partly_live_words(s, tier)));
}
}
if let Some(p) = &cx.families.simd.predication {
estimate.add(simd::divergent::extra_words(
cx.body,
cx.values,
&sel.strategy,
p,
));
}
let access = access::routine_words(&cx.families.access);
let heap = texture::routine_words(&cx.families.texture, &cx.families.access);
let sampler = sampler::routine_words(&cx.families.sampler);
for (_, words) in arith::routine_words(&cx.families.arith)
.chain(access)
.chain(heap)
.chain(sampler)
{
estimate.add(words);
}
estimate.add(stage_io::estimate_words(&cx.families.stage_io));
estimate.add(mesh::estimate_words(&cx.families.mesh));
if let Some(blob) = &cx.families.access.blob {
estimate.add(crate::memory::blob::declared_words(blob));
}
if dispatch.as_ref().is_some_and(|d| d.flat_grid) {
estimate.add(dispatch::FLAT_GRID_WORDS);
}
if dispatch.as_ref().is_some_and(|d| d.folded_groups) {
estimate.add(dispatch::FOLDED_GROUPS_WORDS);
}
// A kernel's partial threadgroups: the test before the body, and each builtin parameter's.
if let Some(d) = dispatch
.as_ref()
.filter(|d| d.partial_groups && stage == Stage::Kernel)
{
let derivations = 1 + d.params.len() as u64;
estimate.add(dispatch::PARTIAL_THREADGROUPS_WORDS.saturating_mul(derivations));
}
estimate.add(tessellation::estimate_words(&cx.families.tessellation));
estimate.add(
cx.families
.access
.tile
.as_ref()
.map_or(0, access::tile::TilePlan::words_estimate),
);
let (entry, body) = (cx.entry, cx.body);
let (precision, specialized) = resolve_notes(&cx.families, cx.precision, cx.specialized);
let mut plan = Plan {
let plan = Plan {
stage,
values: cx.values,
strategy: sel.strategy,
@@ -1862,14 +1788,8 @@ fn finish(
facts: cx.facts.into_iter().collect(),
precision,
specialized,
estimate,
private_bytes: cx.memory.private_bytes,
};
let walk = match &plan.families.simd.predication {
Some(p) => walk_construct_words(entry, body, &plan, p, m)?,
None => 0,
};
plan.estimate.add(walk);
if access::identity(p) {
identity_admits(&plan)?;
}
@@ -2104,25 +2024,6 @@ fn identity_refusal(plan: &Plan) -> Option<String> {
None
}
/// The words the predicated walk of `plan` adds for the constructs of its structured tree
/// (`structurize::emit::construct_words`): the tree emission builds from the same view, here
/// built, measured and released before emission.
fn walk_construct_words(
entry: &Entry,
body: &Body,
plan: &Plan,
p: &simd::divergent::Predication,
m: &mut Meter,
) -> Result<u64, Error> {
let view = crate::lower::view::EntryView::new(entry, body, plan);
let s = m.weighted(crate::pipeline::compile::weights::STRUCTURIZE, |m| {
crate::structurize::structurize(&view, m)
})?;
let words = crate::structurize::emit::construct_words(&s.tree, |b| p.syncs(b), m);
s.release(m);
words
}
/// The constant a [`NoteTest`] reads: a sampler slot's `SamplerState` word or its
/// `NearestPixelSampler` boolean, by the function's slot index, or the class of the format bound
/// at a texture slot, which no constant carries (`SpecKey::BoundTexelFormat`), or the whole word
@@ -119,9 +119,6 @@ pub struct Predication {
/// with `live` set only where the invocation is one of its threadgroup's threads
/// (`dispatch::emit_entry`), rather than everywhere.
pub partial_groups: bool,
/// The reads a guarded segment may reload from a variable rather than find bound (counted
/// with the demotions), which the walk's estimate charges ([`extra_words`]).
pub reloads: u64,
}
impl Predication {
@@ -191,7 +188,6 @@ pub fn plan(
set,
vote_word: false,
partial_groups: false,
reloads: 0,
};
let mut home: Vec<(u32, u32)> = vec![(u32::MAX, 0); n];
for (b, block) in body.blocks.iter() {
@@ -224,8 +220,7 @@ pub fn plan(
}
p.uniform_conds.sort_unstable();
p.uniform_conds.dedup();
let (extra, reloads) = demotions(cx, strategy, set, &home, m)?;
p.reloads = reloads;
let extra = demotions(cx, strategy, set, &home, m)?;
Ok((p, extra))
})();
m.release(bytes);
@@ -476,18 +471,13 @@ fn sync_in_loop(cx: &SelectCx<'_>, p: &Predication, m: &mut Meter) -> Result<boo
/// may be one that no invocation executes. A use is what `FamilyPlans::reads` and
/// `FamilyPlans::incoming_reads` say an instruction or a copy reads (the value a forwarding
/// `extractvalue` forwards; a member-wise phi's members), the hooks the walk reloads through.
///
/// Also the number of uses a guarded segment may reload (`lower::emit`'s `segment` and
/// `ensure_operands`, which forget what a segment bound once it ends): every use but one of a
/// value its own segment defined (in the same block, not a phi, with no synchronization between
/// them, and not the terminator's, which the walk reads after the block's guards).
fn demotions(
cx: &SelectCx<'_>,
strategy: &[Option<Strategy>],
set: SyncSet,
home: &[(u32, u32)],
m: &mut Meter,
) -> Result<(BTreeMap<ValueId, DemoteTy>, u64), Error> {
) -> Result<BTreeMap<ValueId, DemoteTy>, Error> {
let body = cx.body;
let values = cx.values;
let families = &cx.families;
@@ -499,7 +489,6 @@ fn demotions(
.is_some_and(|s| set.holds(s))
};
let mut out = BTreeMap::new();
let mut reloads = 0u64;
for (b, block) in body.blocks.iter() {
// The position of each synchronization of the block, in order.
let syncs: Vec<u32> = block
@@ -550,9 +539,6 @@ fn demotions(
body.insts.get(d).map(|i| &i.kind),
Some(InstKind::Phi { .. })
);
if home_block != b.raw() || phi || term || between(def, at) {
reloads = reloads.saturating_add(1);
}
if home_block != b.raw() || sync_at(d) || (phi && !term) {
continue;
}
@@ -581,79 +567,5 @@ fn demotions(
out.insert(id, ty);
}
}
Ok((out, reloads))
Ok(out)
}
/// The SPIR-V words the predicated walk of plan `p` adds to a kernel's estimate for the AIR
/// blocks it emits (each block is one `Code` statement of the structured tree, which never
/// duplicates a block): a bound of what `structurize::emit::predicate` and `lower::emit` emit
/// there beyond the plain walk, each charge the worst case of the code it names. The walk's
/// constructs, which only the structured tree shows, are charged from the tree
/// (`structurize::emit::predicate::construct_words`).
///
/// - `WALK_FRAME` once: `walk_root`'s `live` variable and its first store, and the `bool` and
/// `u32` types and constants the walk and its votes name.
/// - Per block, `GUARD` for the `live` load of `predicate::code` and, per guarded segment of
/// `lower::emit`'s `block_live` (one more than the block's synchronizations), `SEGMENT`: its
/// `if live` selection.
/// - Per synchronization, its predicated form (`SYNC` and `workgroup::predicated_extra_words`)
/// and `RESULT`: `sync_inst`'s guarded store of its demoted result.
/// - Per use a guarded segment may reload ([`Predication::reloads`]), `RELOAD`: one `OpLoad`.
pub fn extra_words(
body: &crate::air::ir::Body,
values: crate::air::ir::ValueIndex,
strategy: &[Option<Strategy>],
p: &Predication,
) -> u64 {
let mut words = WALK_FRAME.saturating_add(RELOAD.saturating_mul(p.reloads));
for (_, block) in body.blocks.iter() {
let mut syncs = 0u64;
for id in block.inst_ids() {
let s = values
.inst(id)
.and_then(|v| strategy.get(v.index()))
.and_then(Option::as_ref);
if let Some(s) = s.filter(|s| p.set.holds(s)) {
syncs += 1;
words = words
.saturating_add(SYNC + RESULT)
.saturating_add(u64::from(super::workgroup::predicated_extra_words(s)));
}
}
words = words
.saturating_add(GUARD)
.saturating_add(SEGMENT.saturating_mul(syncs + 1));
}
words
}
/// `OpLoad` (4 words): a reload of a demoted value or phi, or a load of a walk flag.
pub(crate) const LOAD: u64 = 4;
/// `OpStore` (3 words) of a walk flag or a demoted value.
pub(crate) const STORE: u64 = 3;
/// An `if c { … }` with no else arm (`FunctionBuilder::if_`): `OpSelectionMerge` (3),
/// `OpBranchConditional` (4), the arm's `OpLabel` (2) and its `OpBranch` to the merge (2), and the
/// merge's `OpLabel` (2).
pub(crate) const IF: u64 = 13;
/// [`extra_words`]: the walk's frame, at most 16 words of variable and store and 48 of types and
/// constants.
const WALK_FRAME: u64 = 64;
/// [`extra_words`]: the `live` load before a guarded block.
const GUARD: u64 = LOAD;
/// [`extra_words`]: one guarded segment.
const SEGMENT: u64 = IF;
/// [`extra_words`]: a synchronization's sanitized operands and the reads of the published active
/// flags, beside `workgroup::predicated_extra_words`.
const SYNC: u64 = 96;
/// [`extra_words`]: a synchronization's demoted result stored where `live` holds.
const RESULT: u64 = IF + STORE;
/// [`extra_words`]: one reload.
const RELOAD: u64 = LOAD;
-20
View File
@@ -698,26 +698,6 @@ pub(super) fn partly_live_at(cx: &EmitCx<'_>, at: InstId) -> bool {
.is_some_and(|v| cx.plan.families.simd.partly_live.contains(&v))
}
/// An upper bound on the words operation `s` adds on subgroup tier `tier` when it is one of the
/// [`SimdPlan::partly_live`]. A multiply-add: the ballot with its `uvec4` type and `true`, and per
/// step its two owners' bit extracts and source selects and three zero selects, with the zero
/// constant; on `PartialFragment` also the subgroup size's load, and per step each owner's bound
/// test, index select, and conjunction. A group operation: the ballot, its source's bit extract and
/// select, and a zero select for each of its two moved values (a fill's data and filling value),
/// with the zero constant; on `PartialFragment` the size's load, bound test, index select, and
/// conjunction.
pub fn partly_live_words(s: &Strategy, tier: Tier) -> u32 {
let partial = tier == Tier::PartialFragment;
let dim = match s {
Strategy::Simd(SimdStrategy::Matrix(matrix::MatrixStrategy::Mac(_))) => 8,
Strategy::Simd(SimdStrategy::Agx(agx::AgxStrategy::MatMad(m))) => u32::from(m.dim),
Strategy::Simd(SimdStrategy::Group(_)) => return 48 + if partial { 24 } else { 0 },
_ => return 0,
};
let bound = if partial { 16 + dim * 32 } else { 0 };
48 + dim * 48 + bound
}
/// Plan a used parameter this family owns (`select::param_family`), each a fragment function's
/// (every integer form of it is held in a `u32`):
///
+2 -112
View File
@@ -72,7 +72,7 @@
//! depends on how subgroups reconverge: an entry whose only tangled instructions are emulated ones
//! declares no reconvergence mode and records `Reconvergence::Guaranteed`.
use crate::air::intrinsics::{GroupOp, GroupScope, MemFlags};
use crate::air::intrinsics::{GroupOp, MemFlags};
use crate::air::ir::ValueId;
use crate::budget::Meter;
use crate::error::{Error, Feature, LowerFamily, Unsupported};
@@ -180,117 +180,6 @@ fn emulated_site(s: &Strategy) -> bool {
}
}
/// The SPIR-V words one scratch read of a value of `w` words emits: the source clamp, per word its
/// address, access chain, and load, and the value's reassembly.
fn read_words(w: u32) -> u32 {
48 + 40 * w
}
/// The SPIR-V words of one of [`tree_fold`]'s or [`tree_scan`]'s rounds on a value of `v` words:
/// the published words, the two barriers, the source lane, its read, the lane-order selects of a
/// float min or max, the combining step, and the select that keeps the partial where the partner
/// holds no contribution.
fn tree_round_words(v: u32, g: &GroupPlan) -> u32 {
48 * v + read_words(v) + 128 + narrow::round_words(g.form)
}
/// The SPIR-V words of [`Emu::gather_bits`] of `conds` words and the closing barrier: the clears,
/// three barriers, the lane's bit, and per word its select, atomic `Or`, and load.
fn gather_words(conds: u32) -> u32 {
96 + 96 * conds
}
/// The SPIR-V words the emulated tier adds to strategy `s`'s own estimate: the stores of the
/// published words and the two barriers, and per read of another lane's value the scratch read with
/// its combining step; a simdgroup reduction is five tree rounds, a prefix sum or product six (a
/// float's exclusive sum and an exclusive product shift first), and a vote or ballot one
/// `Emu::gather_bits`. The subgroup instructions the estimate counted are not emitted, so this
/// over-counts.
pub fn extra_words(s: &Strategy) -> u32 {
let Some(w) = exchange_words(s) else {
return 0;
};
let publish = 48 * w + 48;
let reads = match s {
Strategy::Simd(SimdStrategy::Group(g)) => {
use GroupOp as G;
let v = moved(g).map_or(0, form_words);
let step = read_words(v) + 64 + narrow::round_words(g.form);
let rounds = SIMD_WIDTH.trailing_zeros();
match (g.scope, g.op) {
(GroupScope::Quad, G::IsFirst | G::ActiveThreadsMask)
| (GroupScope::Simdgroup, G::IsFirst) => 64,
(GroupScope::Simdgroup, G::All | G::Any | G::Ballot | G::ActiveThreadsMask)
| (GroupScope::Quad, G::All | G::Any | G::Ballot) => gather_words(2),
(
GroupScope::Simdgroup,
G::PrefixInclusiveSum
| G::PrefixExclusiveSum
| G::PrefixInclusiveProduct
| G::PrefixExclusiveProduct,
) => (rounds + 1) * tree_round_words(v, g),
(
GroupScope::Simdgroup,
G::Sum | G::Product | G::Min | G::Max | G::And | G::Or | G::Xor,
) => rounds * tree_round_words(v, g),
(
GroupScope::Quad,
G::Sum
| G::Product
| G::Min
| G::Max
| G::And
| G::Or
| G::Xor
| G::PrefixInclusiveSum
| G::PrefixExclusiveSum
| G::PrefixInclusiveProduct
| G::PrefixExclusiveProduct,
) => 4 * step,
(_, G::ShuffleAndFillUp | G::ShuffleAndFillDown) => 2 * step,
_ => step,
}
}
_ => TILE_READS * (read_words(1) + CELL_SELECT_WORDS),
};
publish + reads
}
/// The SPIR-V words the emulated tier adds to strategy `s` in a divergent block of a predicated
/// kernel: besides [`extra_words`], the published active flag and the active-lane select of each
/// value, the active-lane word of `is_first` and `broadcast_first` and of the votes, and, for a
/// quad's other operations, which read its lanes one by one, the read of each lane's flag; for a
/// multiply-add, per cell read the source lane's flag.
pub fn predicated_extra_words(s: &Strategy) -> u32 {
let base = extra_words(s);
match s {
Strategy::Simd(SimdStrategy::Group(g)) => {
let votes = matches!(g.op, GroupOp::All | GroupOp::Any);
let flags = if g.scope == GroupScope::Quad && !votes {
SIMD_WIDTH * (read_words(1) + 64)
} else {
gather_words(1)
};
base.saturating_mul(2)
.saturating_add(flags)
.saturating_add(96)
}
Strategy::Simd(
SimdStrategy::Matrix(MatrixStrategy::Mac(_))
| SimdStrategy::Agx(AgxStrategy::MatMad(_)),
) => base.saturating_add(TILE_READS * read_words(1)),
_ => base,
}
}
/// The cell reads of a multiply-add ([`extra_words`]): per step `k` of the (at most) eight, the
/// `a` cell and two `b` cells, each with the select of a zero cell (`CELL_SELECT_WORDS`).
const TILE_READS: u32 = 8 * 3;
/// The SPIR-V words of the select of a zero cell where a multiply-add's source lane does not
/// take part, and its constant ([`Emu::read_cell`]).
const CELL_SELECT_WORDS: u32 = 16;
/// The scratch bytes one simdgroup of a function publishing `words` per lane takes
/// (`4 · words · 32`).
pub fn bytes_per_simdgroup(words: u32) -> u64 {
@@ -1733,6 +1622,7 @@ pub(super) fn quad_op(
#[cfg(test)]
mod tests {
use super::*;
use crate::air::intrinsics::GroupScope;
use crate::lower::arith::legal::{FloatFmt, Held};
/// A lane publishes one word per lane of each value it moves: the predicate of a vote or
@@ -135,11 +135,6 @@ fn nan_kept(f: Form) -> bool {
!matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half))
}
/// The words of the planned roundings, each emitted once per return.
pub(super) fn words(rounded: impl IntoIterator<Item = [Option<ChannelWrite>; 4]>) -> u64 {
rounded.into_iter().map(|r| color_write::words(&r)).sum()
}
/// Output `x` (form `f`) to color attachment `color`, each lane the plan rounds rounded to nearest
/// even (`color_writes::HALF_NEAREST`), the others as computed.
pub(crate) fn round(
@@ -53,10 +53,6 @@ use crate::spirv::error::BResult;
use crate::spirv::ids::Value;
use crate::spirv::ir::{ConstBits, Constant, Type};
/// An upper estimate of the SPIR-V words of one output's [`encode`]: the lanes completed to four,
/// the rounding to `half`, the texel's encode, and the raw components' extract.
pub(crate) const WORDS: u64 = 60 * 6 + extended_range::ENCODE_WORDS as u64;
/// Plan output `f` (dual-source `index`) of a fragment function to color attachment `color`: where
/// `LoweringInputs::extended_range_colors` lists the attachment and the output is `float` or
/// `half`, record the attachment on the interface (`StageIo::extended_range_colors`) and the
+1 -45
View File
@@ -405,10 +405,6 @@ pub struct StageIoPlan {
pub reads_grid_position: bool,
/// Whether a kernel reads the stage-in region (`RuntimeFact::StageInRegion`).
pub region: bool,
/// An upper estimate of the words the interface adds: declarations, one load per use of an
/// interface parameter, one fetch per pulled attribute, the output stores, and the roundings of
/// color outputs.
pub words: u64,
/// The lanes of each color attachment's output a fragment function rounds itself
/// (`color_write`), through an output variable or in the storage form: each by its rule, a
/// half-float channel's under `TextureWriteRoundingMode::NearestEven`.
@@ -480,18 +476,6 @@ pub enum MergedValue {
BaseInstance,
}
/// The words a merged draw's vertex function adds at entry: the two input builtins' variables,
/// decorations and interface entries and their loads, the header's loads, the corner's 64-bit
/// arithmetic, the search's loop (its variables, test, halving, load and selection), the
/// command's draw's loads, the division and remainder, the slot table's address, the index
/// entry's loads and the index read, and the command's output and its stores.
pub(super) const MERGED_WORDS: u64 = 900;
/// The words a merged draw's fragment function adds at entry: the command's input, its
/// decorations and interface entry and its load, and the header's loads and the slot table's
/// address arithmetic.
pub(super) const MERGED_FRAGMENT_WORDS: u64 = 150;
/// How a vertex function compiled under `LoweringInputs::primitive_id_varying` writes the
/// primitive ID a fragment function reads from its varying on a device without a fragment
/// `PrimitiveId`: at each return, `(VertexIndex - first) / n` (`vertex` is the input builtin's
@@ -520,11 +504,6 @@ pub enum FirstVertex {
Zero,
}
/// The words a vertex function's primitive ID adds: its output variable, decorations and
/// interface entry, the vertex index's and base vertex's inputs, their loads, the push loads and
/// an extract, the subtraction, the division and the store.
const PRIMITIVE_ID_WORDS: u64 = 56;
/// How a vertex function compiled in the primitive ID's de-indexed form
/// (`LoweringInputs::primitive_id_indices`) reads its vertex: its stream position
/// `p = VertexIndex` (`vertex` is the input builtin's object; the draw starts at vertex 0) names
@@ -547,12 +526,6 @@ pub struct CapturedIndex {
pub first: Option<FirstVertex>,
}
/// The words a vertex function's index read adds: its input builtin's variable, decorations and
/// interface entry, its load, the layout's extract, the 64-bit address arithmetic, the device
/// place (its block and pointer types, conversion and access chain), the load, a `u16`'s
/// alignment and shift, and the base vertex's extract and add (at most 224, a `u16` read's).
pub(super) const CAPTURED_INDEX_WORDS: u64 = 400;
/// The second output (`[[color(n), index(1)]]`) a fragment function writes for an attachment held
/// with its channels rotated (`LoweringInputs::rotated_factors`): beside its first output there,
/// the returned value's field `field` (0 for a returned value itself), whose channels or
@@ -867,24 +840,11 @@ pub(crate) fn uniform_varyings(
}
/// Complete the stage-IO plan once every instruction and parameter is selected: the per-stage
/// interface limits and the size estimate.
/// interface limits.
pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
plan::finish(cx)
}
/// The words the stage interface adds to the size estimate.
pub fn estimate_words(plan: &StageIoPlan) -> u64 {
plan.words
}
/// Count `words` of the fragment family's part of the stage interface (input attachments and
/// the discard predicate's kill at each return) in the interface's size estimate. Called from
/// `fragment::finish`, after [`finish`] computed this family's own words.
pub fn add_interface_words(cx: &mut SelectCx<'_>, words: u64) {
let sp = &mut cx.families.stage_io;
sp.words = sp.words.saturating_add(words);
}
/// Plan the fragment's `FragCoord` input for a family that reads the invocation's pixel (the
/// fragment imageblock): the index of its object, shared with a `[[position]]` input.
pub fn frag_coord(cx: &mut SelectCx<'_>) -> usize {
@@ -2010,10 +1970,6 @@ pub(crate) fn metal_point_size(fb: &mut FunctionBuilder<'_>, size: SValue) -> BR
fb.select(positive, held, one)
}
/// The words [`metal_point_size`] adds to a store: the two comparisons, the two selects and the
/// three constants.
pub(crate) const POINT_SIZE_WORDS: u64 = 7;
/// Store the primitive ID of the primitive the vertex provokes to its varying
/// ([`PrimitiveIdStore`]): `(VertexIndex - first) / n`, `n` from
/// `PushField::VerticesPerPrimitive`.
+1 -127
View File
@@ -1573,7 +1573,6 @@ fn primitive_id_output(cx: &mut SelectCx<'_>) -> Result<(), Error> {
first,
object,
});
sp.words = sp.words.saturating_add(super::PRIMITIVE_ID_WORDS);
Ok(())
}
@@ -2538,7 +2537,6 @@ pub(super) fn captured_index(
StageBuiltin::VertexIndex,
);
sp.captured_index = Some(super::CapturedIndex { vertex, ty, first });
sp.words = sp.words.saturating_add(super::CAPTURED_INDEX_WORDS);
Ok(())
}
@@ -2620,7 +2618,6 @@ fn merged(cx: &mut SelectCx<'_>) -> Result<(), Error> {
instance,
command,
});
sp.words = sp.words.saturating_add(super::MERGED_WORDS);
cx.push.insert(PushField::MergedDrawAddress);
cx.facts.insert(RuntimeFact::MergedDraws);
Ok(())
@@ -2668,7 +2665,6 @@ pub(crate) fn finish_merged(cx: &mut SelectCx<'_>) -> Result<(), Error> {
IoDir::Input,
)?;
sp.merged_fragment = Some(object);
sp.words = sp.words.saturating_add(super::MERGED_FRAGMENT_WORDS);
}
_ => {}
}
@@ -2942,28 +2938,13 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result<Lin
})
}
/// Words per interface object, per parameter use, and per stored output element.
const OBJECT_WORDS: u64 = 32;
const USE_WORDS: u64 = 24;
const STORE_WORDS: u64 = 16;
/// The words a use of a [`Source::PixelCenter`] parameter adds to a load: `[[position]]`'s floor,
/// add, shuffle, and their constants; a varying's `InterpolateAtOffset` and its offset.
const PIXEL_WORDS: u64 = 24;
/// The words a use of a [`Source::Uniform`] parameter adds to a load: Metal's reading of an
/// interpolated constant, nine integer instructions on the bits and their constants.
const UNIFORM_WORDS: u64 = 64;
/// The words a use of a [`Source::QuadPrimitive`] parameter adds to a load: the shift and its
/// constant.
const QUAD_PRIMITIVE_WORDS: u64 = 8;
/// The per-stage interface limits and the size estimate.
/// The per-stage interface limits.
pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
if cx.stage == Stage::Kernel {
// A kernel's stage inputs: the region it depends on, and their size.
if cx.families.stage_io.region {
cx.facts.insert(RuntimeFact::StageInRegion);
}
cx.families.stage_io.words = param_words(cx);
return Ok(());
}
// Buffer writes and atomics in a vertex or fragment function need the stage's store feature
@@ -3086,70 +3067,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
});
sp.interface.sample_mask = Some(masks);
}
// Size: every object, the parameters' words, and a store per output element; a count's
// compare and select (and its constant 0) are a store's words more, and so is an
// amplification's offset added; an amplified output is a store, an add and a count's, and a
// region's viewport a load and a store.
let params = param_words(cx);
let sp = &mut cx.families.stage_io;
let stores: u64 = sp
.outputs
.iter()
.map(|o| {
let elements = match o.link.place {
Place::Spread(n) => u64::from(n),
_ => 1,
};
elements
+ super::POINT_SIZE_WORDS * u64::from(super::point_size_object(&sp.objects, o.link.object))
+ u64::from(o.below.is_some())
+ u64::from(o.offset.is_some())
+ u64::from(o.rotated)
})
.sum::<u64>()
// A rotation's second output: its field, two shuffles and a store.
+ 4 * sp.rotated_seconds.len() as u64
+ 3 * sp.amplified.len() as u64
// The region's draw index loaded and stored.
+ 2 * u64::from(sp.region_viewport.is_some())
+ u64::from(sp.point_size_default.is_some())
// The private sample mask's AND and store.
+ 2 * u64::from(sp.private_mask.is_some())
// The alpha test: the alpha's extracts, its clamp and code, the reference, the
// comparison and the kill.
+ 40 * u64::from(sp.alpha_test.is_some())
+ sp.depth_clamp.map_or(0, |d| match (d.range, d.clamps) {
// The `[0, 1]` selects, the range's two clamps and the negative NaN's select.
(true, _) => 14,
(false, true) => 5,
(false, false) => 2,
});
// Each return stores every output.
let rets = cx
.body
.insts
.values()
.filter(|i| matches!(i.kind, crate::air::ir::InstKind::Ret(_)))
.count() as u64;
// Each return also rounds every color output that rounds, and encodes the extended-range
// colors' texels.
let rounding = super::color_write::words(sp.rounded.values().copied())
.saturating_add(super::extended_color::WORDS.saturating_mul(sp.extended.len() as u64))
.saturating_add(
(sp.words_written.values())
.map(|&w| super::word_color::encode_words(w))
.fold(0u64, u64::saturating_add),
);
sp.words = (sp.objects.len() as u64)
.saturating_mul(OBJECT_WORDS)
.saturating_add(params)
.saturating_add(
stores
.saturating_add(1)
.saturating_mul(rets)
.saturating_mul(STORE_WORDS),
)
.saturating_add(rounding.saturating_mul(rets));
Ok(())
}
@@ -3195,46 +3112,3 @@ fn clamps_fragment_depth(cx: &SelectCx<'_>) -> bool {
.extensions
.contains(&VkExtension::ExtDepthRangeUnrestricted)
}
/// The words of the used stage-IO parameters: a load per use of an interface parameter (or of a
/// kernel's stage-in region), with its pixel-center form for a [`Source::PixelCenter`] one, and one
/// fetch per pulled attribute at entry (`fetch::PulledRead::words`), whose uses read the held
/// value.
fn param_words(cx: &SelectCx<'_>) -> u64 {
let mut fetch_words = 0u64;
let mut loaded: Vec<(u32, u64)> = Vec::new();
for p in &cx.families.stage_io.params {
match &p.source {
Source::Io(_)
| Source::AmplificationCount(_)
| Source::Unamplified(_)
| Source::Absent(_)
| Source::Pushed { .. }
| Source::DrawBase { .. }
| Source::StageInRegion { .. }
| Source::CapturedVertex(_)
| Source::CapturedBaseVertex(_)
| Source::Merged { .. } => loaded.push((p.param, USE_WORDS)),
Source::QuadPrimitive(_) => loaded.push((p.param, USE_WORDS + QUAD_PRIMITIVE_WORDS)),
Source::PixelCenter(_) | Source::LoopSample(_) | Source::AtLoopSample(_) => {
loaded.push((p.param, USE_WORDS + PIXEL_WORDS))
}
Source::Uniform(_) => loaded.push((p.param, USE_WORDS + UNIFORM_WORDS)),
// A read through an interpolation function (the call's own arithmetic is its
// strategy's).
Source::Interpolant { .. } => loaded.push((p.param, USE_WORDS + PIXEL_WORDS)),
Source::Pulled(r) => fetch_words = fetch_words.saturating_add(u64::from(r.words())),
}
}
let mut use_words = 0u64;
for inst in cx.body.insts.values() {
inst.kind.for_each_value(|v| {
if let Value::Arg(a) = v {
if let Some(&(_, words)) = loaded.iter().find(|(p, _)| *p == a.raw()) {
use_words = use_words.saturating_add(words);
}
}
});
}
fetch_words.saturating_add(use_words)
}
@@ -25,7 +25,7 @@
//! or keeps some channels (`lower::fragment::fetch`), and a blend there reads the word read first
//! as Metal's blend reads it ([`decode`]).
use crate::air::intrinsics::{PackDir, PackFormat};
use crate::air::intrinsics::PackFormat;
use crate::error::{Error, Feature, Unsupported};
use crate::lower::arith::color_write::half_rounded;
use crate::lower::arith::ops::{fsplat, splat, ty};
@@ -40,26 +40,6 @@ use crate::spirv::error::BResult;
use crate::spirv::ids::Value;
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, UnOp};
/// An upper estimate of the SPIR-V words of one output's [`encode`]: per channel the rounding to
/// `half`, the clamp, the product's rounding, the conversion, shift and merge.
pub(crate) const WORDS: u64 = 4 * (40 * 6 + 12 * 6);
/// An upper estimate of the SPIR-V words of one output's [`encode`] into `word`: [`WORDS`], and
/// for an 8-bit sRGB word `arith::pack::pack`'s encode.
pub(crate) fn encode_words(word: WordAttachment) -> u64 {
match word {
WordAttachment::Packed16 { .. } => WORDS,
WordAttachment::Srgb8 { .. } => {
let f4 = Form {
held: Held::Float(FloatFmt::F32),
lanes: 4,
};
WORDS + u64::from(pack::words(PackFormat::Unorm4x8Srgb, PackDir::Pack, f4))
}
WordAttachment::Rgb9e5 => crate::lower::texture::RGB9E5_WORDS + 6 * 8,
}
}
/// Plan output `f` (dual-source `index`) of a fragment function to color attachment `color`:
/// where `LoweringInputs::word_colors` lists the attachment and the output is `float` or `half` of
/// dual-source index 0, record the attachment on the interface (`StageIo::word_colors`) and the
@@ -206,10 +186,6 @@ pub(crate) fn encode(
Ok(out)
}
/// An upper estimate of the SPIR-V words of one [`decode`]: per channel the shift, mask,
/// conversion, product and rounding to `half`, and the vector's construction.
pub(crate) const DECODE_WORDS: u64 = 4 * (12 * 6 + 40 * 6) + 12;
/// The four channels Metal's blend reads from word `x` (a `u32`) of packed 16-bit word attachment
/// `word` (`WordAttachment::Packed16`), as a
/// `vec4` of `f32`, red first: each channel's code over its maximum code rounded to `half`, nearest
+1 -1
View File
@@ -4,7 +4,7 @@
//! enum, defined in the family module. A family whose lowering has not landed has an empty
//! (uninhabited) enum: its `select` refuses, so no plan ever holds one, and every match over it
//! is total by construction. Each variant of a family enum has exactly one emit function (the
//! family's `emit`), a word cost for `SizeEstimate`, and a stable name for the `StrategyCensus`.
//! family's `emit`), and a stable name and a word cost for the `StrategyCensus`.
//!
//! Interface-level lowering (stage IO, dispatch builtins, push fields) is planned per entry, not
//! per instruction, so it has no variant here.
@@ -219,8 +219,6 @@ pub struct EvalPlan {
pub params: Vec<EvalParam>,
/// The members each control-point call's result has read, by call.
reads: BTreeMap<InstId, Reads>,
/// An upper estimate of the words the interface adds.
pub words: u64,
}
/// The tessellation part of the per-function plan (`select::FamilyPlans`).
@@ -456,7 +454,6 @@ pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
elements: false,
params: Vec::new(),
reads,
words: 0,
});
Ok(())
}
@@ -764,58 +761,14 @@ pub fn select(
})
}
/// Words per interface object and per use of a loaded input.
const OBJECT_WORDS: u64 = 32;
const USE_WORDS: u64 = 24;
/// Complete the plan: refuse what the evaluation stage does not model, and estimate the words
/// of its interface.
/// Complete the plan: refuse what the evaluation stage does not model.
pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
let Some(e) = cx.families.tessellation.eval.as_ref() else {
return Ok(());
};
if cx.simd != SimdClass::None {
if cx.families.tessellation.eval.is_some() && cx.simd != SimdClass::None {
return Err(not_implemented());
}
let objects = u64::from(e.coord)
+ u64::from(e.patch)
+ u64::from(e.instance)
+ u64::from(e.view)
+ u64::from(e.elements);
let mut words = objects.saturating_mul(OBJECT_WORDS);
let mut loaded = Vec::new();
for p in &e.params {
match p.source {
Source::Pulled(r) => words = words.saturating_add(u64::from(r.words())),
Source::Coord { .. }
| Source::PatchIndex { .. }
| Source::Instance { .. }
| Source::BaseInstance { .. }
| Source::ViewIndex { .. }
| Source::AmplificationCount { .. } => loaded.push(p.param),
Source::ControlPoints => {}
}
}
for inst in cx.body.insts.values() {
inst.kind.for_each_value(|v| {
if let Value::Arg(a) = v {
if loaded.contains(&a.raw()) {
words = words.saturating_add(USE_WORDS);
}
}
});
}
if let Some(e) = cx.families.tessellation.eval.as_mut() {
e.words = words;
}
Ok(())
}
/// The words the evaluation interface adds to the size estimate.
pub fn estimate_words(plan: &TessellationPlan) -> u64 {
plan.eval.as_ref().map_or(0, |e| e.words)
}
/// The module-scope objects of an evaluation entry.
#[derive(Clone, Debug, Default)]
pub struct Declared {
@@ -1193,15 +1193,14 @@ pub(crate) fn srgb_raw_tap(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult<S
crate::lower::arith::pack::srgb_decode_texel(fb, x, SRGB_TEXEL)
}
/// The words [`srgb_raw_tap`] emits, at most: the transfer's steps on the color lanes
/// (`the_srgb_estimate_bounds_its_emission`).
/// The words [`srgb_raw_tap`] emits, at most: the transfer's steps on the color lanes.
pub(crate) const SRGB_TAP_WORDS: u32 = crate::lower::arith::pack::SRGB_DECODE_TEXEL_WORDS;
/// The color lanes of an sRGB texel ([`srgb_texel`]): red, green, and blue.
pub(crate) const SRGB_TEXEL: [bool; 4] = [true, true, true, false];
/// The words [`srgb_texel`] emits, at most: the transfer's steps, a `half` result's rounding, and
/// the lane's extraction (`the_srgb_estimate_bounds_its_emission`).
/// the lane's extraction.
pub(crate) const SRGB_DECODE_WORDS: u32 =
crate::lower::arith::pack::SRGB_DECODE_TEXEL_WORDS + 64 + 4 * 4 + 8;
@@ -1614,9 +1613,6 @@ fn shared_exponent_word(
fb.composite_construct(v4, &[word, zero, zero, zero])
}
/// An upper estimate of the SPIR-V words of one [`rgb9e5_word`].
pub(crate) const RGB9E5_WORDS: u64 = 3 * 8 * 7 + 3 * 7 * 7 + 16 * 7;
/// The `RGB9E5Float` word, a `u32`, Metal stores for the red, green and blue `f32` lanes of `x` (a
/// vector of at least three; a kernel's write, a `float` output's store into a word attachment,
/// `metal::format::WordAttachment::Rgb9e5`): each clamped to `[0, 65408]` on its bits (a NaN, a
+1 -1
View File
@@ -171,7 +171,7 @@ pub(crate) use emit::{
constant_lanes, dispatch, heap_element, heap_flags, heap_raw_form, heap_raw_image,
live_or_zero, reinterpret, resident_access, rgb9e5_word, slot_image, sparse_spec, srgb_raw_tap,
srgb_texel, swizzled_float, swizzled_gather, swizzled_held, tile_map, tiled_word, with_word,
NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_DECODE_WORDS, SRGB_TAP_WORDS, SRGB_TEXEL,
NullLeaf, TileLevel, SRGB_DECODE_WORDS, SRGB_TAP_WORDS, SRGB_TEXEL,
};
pub use emit::{emit, held_texel, to_image};
pub(crate) use slot::depth_comparison;
-13
View File
@@ -61,19 +61,6 @@ pub fn module_bytes(len: u64) -> u64 {
len.div_ceil(16).saturating_mul(16)
}
/// The words declaring `blob` adds to a module, at most: none for a bound blob (its view is a
/// descriptor's); for the module's words, an `OpConstant` of 4 words a word, the composite of
/// them, and the array, its length and the variable.
pub fn declared_words(blob: &BlobUse) -> u64 {
match blob.home {
BlobHome::Bound => 0,
BlobHome::Module => {
let words = module_bytes(blob.bytes.len() as u64) / 4;
words.saturating_mul(5).saturating_add(16)
}
}
}
/// The binding symbol of `stage`'s constant blob.
pub fn symbol(stage: Stage) -> ResourceSlot {
ResourceSlot {
+8 -7
View File
@@ -1776,9 +1776,8 @@ fn with_request_shared<'k, T>(
g(&r)
}
/// Compile entry `entry` of one wrapped or raw bitcode module (`bitcode`), refusing an estimate
/// above `word_cap` SPIR-V words before emission and a module above it after serialization
/// (`budget::SPIRV_WORDS` in production).
/// Compile entry `entry` of one wrapped or raw bitcode module (`bitcode`), refusing a module
/// above `word_cap` SPIR-V words after serialization (`budget::SPIRV_WORDS` in production).
#[cfg(test)]
pub(crate) fn compile_bitcode(
bitcode: &[u8],
@@ -1905,7 +1904,7 @@ pub(crate) fn compile_stage_kept(
/// The [`Plan`] of entry `entry` of `bitcode`: everything [`compile_bitcode`] does before the
/// size check (decode, specialize, analyze, select), under `catch_unwind`. For tests and
/// measurement of the plan's own claims, such as `SizeEstimate` being an upper bound.
/// measurement of the plan's own claims.
#[cfg(test)]
pub(crate) fn plan_bitcode(
bitcode: &[u8],
@@ -3214,7 +3213,7 @@ fn lower_bounded<K>(
merged,
held,
},
) = stage_bound::emit(r, p, (word_cap, bounds), m)?;
) = stage_bound::emit(r, p, bounds, m)?;
let function_tables = spec.function_tables.clone();
let reaches_command_buffers = spec.may_encode_indirect_commands();
let command_writes = spec.command_writes();
@@ -3354,8 +3353,10 @@ fn lower_bounded<K>(
m.release(ids.saturating_add(held));
m.charge(module.footprint())?; // The retained words and relocations.
// The estimate refused early; the cap holds on what was emitted.
crate::lower::estimate::check_emitted(module.words.len(), word_cap)?;
// The cap holds on what was emitted.
if u64::try_from(module.words.len()).map_or(true, |w| w > word_cap) {
return Err(Error::LimitExceeded(crate::error::Limit::SpirvWords));
}
let interface = stage_interface(
&plan,
symbols,
@@ -97,9 +97,6 @@ pub struct EntryPlan {
pub stage: Stage,
/// Each lowering strategy the plan selected: its uses, and the words it is estimated to emit.
pub strategies: BTreeMap<String, StrategyUse>,
/// The size check's estimate of the module's words: a compile refuses above
/// `budget::SPIRV_WORDS` before it emits.
pub estimated_words: u64,
}
impl DeviceProfile {
@@ -184,7 +181,6 @@ impl DeviceProfile {
plan_one(&r, self, widest, &mut m).map(|planned| EntryPlan {
stage: planned.plan.stage,
strategies: census(&planned.plan).entries,
estimated_words: planned.plan.estimate.words,
})
});
(planned, CompileReport::of(&m))
@@ -55,14 +55,14 @@ impl StageBounds {
};
}
/// `r`'s function planned and emitted with its repeated regions rolled, under the plan's word
/// estimate `word_cap` and under `bounds` (the module docs): planned again keeping the widest
/// mode's pin where only that pin's emulation passed the bound, else refused, naming the module's
/// entry weight and the bound ([`past_bound`]).
/// `r`'s function planned and emitted with its repeated regions rolled, under `bounds` (the
/// module docs): planned again keeping the widest mode's pin where only that pin's emulation
/// passed the bound, else refused, naming the module's entry weight and the bound
/// ([`past_bound`]).
pub(super) fn emit(
r: &Request<'_>,
p: &DeviceProfile,
(word_cap, bounds): (u64, StageBounds),
bounds: StageBounds,
m: &mut Meter,
) -> Result<(Planned, Emitted), Error> {
let analyzed = analyze_one(r, p, m)?;
@@ -70,7 +70,6 @@ pub(super) fn emit(
loop {
let before = m.ledger();
let (plan, kernel) = analyzed.select(p, widest, m)?;
plan.estimate.check(word_cap)?;
let mut emitted = m.weighted(crate::pipeline::compile::weights::EMIT, |m| {
crate::lower::emit::emit_module(&analyzed.spec, &plan, m)
})?;
+1 -28
View File
@@ -299,30 +299,7 @@ pub fn compile_kept(
&mut meter(),
SPIRV_WORDS,
)
.map(|(compiled, plan, module)| {
let a = compiled.artifact();
assert_walk_estimate(entry, &plan, a.module.words.len());
(Arc::new(a.clone()), plan, module)
})
}
/// The plan's size estimate bounds the `emitted` words of a module of the emulated simdgroup tier
/// or of the predicated walk: checked on every such module the engine tests build through
/// [`compile_kept`] and [`typed_module_with`] (the estimate refuses before emission, so one under
/// the emitted words would let a module past the cap only `check_emitted` catches, and one far
/// over refuses a module that fits).
fn assert_walk_estimate(entry: &str, plan: &Plan, emitted: usize) {
assert!(
!walked(plan) || plan.estimate.words >= emitted as u64,
"{entry}: estimate {} < emitted {emitted}",
plan.estimate.words
);
}
/// The plan is of the emulated simdgroup tier or walks its body predicated.
fn walked(plan: &Plan) -> bool {
plan.simd.1 == crate::device::subgroup::Tier::Emulated
|| plan.families.simd.predication.is_some()
.map(|(compiled, plan, module)| (Arc::new(compiled.artifact().clone()), plan, module))
}
/// The plan and the finished typed module of entry `entry` of `bitcode` for `p`, with no function
@@ -438,10 +415,6 @@ fn typed_module_of(
crate::spirv::roll::roll_entry(&mut module, m)?;
crate::spirv::hoist::hoist_uniform_loads(&mut module, p.robustness(), m)?;
crate::spirv::verify::verify(&module, p, m)?;
if walked(&plan) {
let words = crate::spirv::serialize::serialize(module.clone())?.words;
assert_walk_estimate(entry, &plan, words.len());
}
Ok((plan, module))
}
@@ -662,7 +662,5 @@ fn frame_next(frames: &[&[StmtId]]) -> Option<StmtId> {
mod predicate;
pub(crate) use predicate::construct_words;
#[cfg(test)]
mod tests;
@@ -184,103 +184,6 @@ fn facts_of(
}
}
/// A bound of the SPIR-V words the predicated walk of `tree` (whose blocks synchronize where
/// `syncs` holds) emits for its statements beyond what the plain walk emits for them, each the
/// worst case of the code below that emits it. The walk's `Code` statements, one per AIR block,
/// are charged with the plan (`lower::simd::divergent::extra_words`). The walk visits what
/// [`walk`] visits: the statements of a sequence and of a one-arm dispatch, and the arms and body
/// of a statement that synchronizes or escapes; any other statement runs as the plain walk emits
/// it ([`plain`]), so only its guard counts.
///
/// - A statement run as it is ([`plain`]), not a block: its `live` load and `if live` selection.
/// - `SetSel`, `SetPending`, `ClearPending`: [`W::store_live`]'s `live` load, old value load and
/// select beside the plain store.
/// - `Break`, `Continue`: the flag's [`W::store_live`] and the store clearing `live`.
/// - `Return`, `Unreachable` in a divergent position: the store clearing `live`.
/// - `If`, `GuardPending`, `Switch`, a dispatch of several arms: the reload of an `If`'s condition
/// or a `Switch`'s selector (`lower::emit`'s `cond` and `selector`, after a guarded block),
/// [`matches()`]'s literal constants, comparisons and disjunctions, the negation, and
/// [`branches_opt`]'s `live` load, per arm the select of its condition and either its `if` (no
/// synchronization) or its `live` store and reload and their disjunction (with one), and the
/// final `live` store.
/// - `Loop`: [`predicated_loop`]'s two flag variables, their first stores and the `live` load, per
/// iteration the `cont` load, the `live` and `cont` stores, the workgroup vote
/// (`lower::simd::workgroup::vote`: a scratch access chain, the atomic clear, set and read, three
/// barriers, the select and the comparison), the negation and the `if` leaving the loop, and
/// after it the `brk` load and the `live` store.
pub(crate) fn construct_words(
tree: &StructTree,
syncs: impl Fn(BlockId) -> bool,
meter: &mut Meter,
) -> Result<u64, Error> {
use crate::lower::simd::divergent::{IF, LOAD, STORE};
const SELECT: u64 = 6;
const NOT: u64 = 4;
const OR: u64 = 5;
const EQUAL: u64 = 5;
const CONSTANT: u64 = 4;
const VARIABLE: u64 = 4;
const BRANCH: u64 = 2;
const STORE_LIVE: u64 = LOAD + LOAD + SELECT;
const ARM: u64 = SELECT
+ if IF > STORE + LOAD + OR {
IF
} else {
STORE + LOAD + OR
};
const LITERAL: u64 = CONSTANT + EQUAL + OR;
const VOTE: u64 = (4 + 2) + 5 + 3 * 4 + SELECT + 7 + 6 + EQUAL;
const LOOP: u64 = 2 * VARIABLE
+ LOAD
+ 2 * STORE
+ (LOAD + 2 * STORE + VOTE + NOT + IF + BRANCH)
+ LOAD
+ STORE;
let f = facts_of(tree, syncs, meter)?;
let r = (|| -> Result<u64, Error> {
let mut words = 0u64;
let mut stack = vec![tree.root()];
while let Some(id) = stack.pop() {
meter.tick(1)?;
let st = tree.stmt(id)?;
let walked = f.hot(id) || f.escapes(id);
let branches = |arms: u64| LOAD + arms * ARM + STORE;
let (own, descend) = match st {
Stmt::Seq(_) | Stmt::Code(_) => (0, true),
Stmt::Dispatch { arms, .. } if arms.len() == 1 => (0, true),
Stmt::SetSel { .. } | Stmt::SetPending(_) | Stmt::ClearPending(_) => {
(STORE_LIVE, false)
}
Stmt::Break | Stmt::Continue => (STORE_LIVE + STORE + STORE, false),
Stmt::Return(_) | Stmt::Unreachable => (STORE, false),
_ if !walked => (LOAD + IF, false),
// The walk refuses these (`ControlRule::NoCurrentBlock`).
Stmt::Block { .. } | Stmt::Jump(_) => (0, true),
Stmt::If { .. } => (LOAD + NOT + branches(2), true),
Stmt::GuardPending(_) => (NOT + branches(2), true),
Stmt::Switch { cases, .. } => {
let literals: u64 = cases.iter().map(|(l, _)| l.len() as u64).sum();
let n = cases.len() as u64;
let lits = LITERAL * literals + OR * n + NOT;
(LOAD + lits + branches(n + 1), true)
}
Stmt::Dispatch { arms, .. } => {
let n = arms.len() as u64;
((LITERAL + OR) * n + NOT + branches(n), true)
}
Stmt::Loop { .. } => (LOOP, true),
};
words = words.saturating_add(own);
if descend {
stack.extend(st.children());
}
}
Ok(words)
})();
meter.release(f.bytes());
r
}
/// The flags and exits of the innermost walked loop.
#[derive(Clone, Copy, Debug)]
struct Flags<'l> {
+2 -48
View File
@@ -1749,41 +1749,6 @@ fn a_looping_kernel_reserves_no_status_binding_in_the_fallback() {
}
}
/// The plan's size estimate bounds the emitted words of every leaf kernel, in both encodings and in
/// the device-address form.
#[test]
fn the_estimate_bounds_every_leaf_kernel() {
let mut psb = LowerInputs::new();
psb.psb_slots.insert(sref(0));
for robust in [true, false] {
let p = profile_with("moltenvk-m3", robust, true);
for inputs in [LowerInputs::new(), psb.clone()] {
for k in leaf_kernels() {
let what = format!(
"{} robust={robust} psb={}",
k.name,
inputs != LowerInputs::new()
);
let Some(bc) = assemble_text(k.name, &leaf_kernel(&k)) else {
return;
};
let entry = EntryRef::Name(k.name);
let consts = FunctionConstantValues::defaults();
let plan = plan_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let a =
compile_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter(), SPIRV_WORDS)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
}
}
}
}
/// The opcodes of a SPIR-V module's instructions, in order.
fn opcodes(words: &[u32]) -> Vec<u16> {
let mut out = Vec::new();
@@ -1923,33 +1888,22 @@ fn a_push_field_the_entry_block_loaded_is_not_reloaded() {
}
}
/// The word cap holds on the emitted words, not only on the estimate. A public fixture whose
/// estimate is below its emitted words (a storage texture write) compiles at a cap equal to its
/// emitted words and is refused with `SpirvWords` one word below, although its estimate passes both
/// caps.
/// The word cap holds on the emitted words: a public fixture (a storage texture write) compiles at
/// a cap equal to its emitted words and is refused with `SpirvWords` one word below.
#[test]
fn the_word_cap_holds_on_the_emitted_words() {
let Some(bc) = assemble_file("storage_texture_write") else {
return;
};
// The write's rounding routine, counted whole, lifts the estimate past the emitted words.
let p = profile_with("moltenvk-m3", true, true);
let entry = EntryRef::Name("storage_texture_write");
let consts = FunctionConstantValues::defaults();
let inputs = LowerInputs::new();
let estimate = plan_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter())
.expect("plan")
.estimate
.words;
let words = compile_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter(), SPIRV_WORDS)
.expect("compile")
.module
.words
.len() as u64;
assert!(
estimate < words - 1,
"the fixture no longer emits more than its estimate ({estimate} >= {words} - 1)"
);
compile_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter(), words)
.expect("compiles at a cap of its emitted words");
assert_eq!(
+1 -9
View File
@@ -731,8 +731,7 @@ fn matmads_record_their_precision() {
/// Every AGX kernel compiles, links, relocates, and passes L3 on every committed profile; a
/// multiply-add exactly where a cross-lane shuffle class has a compute tier (a subgroup tier, or
/// emulated simdgroups), and elsewhere it is refused as that tier is. The plan's size estimate
/// bounds the emitted words.
/// emulated simdgroups), and elsewhere it is refused as that tier is.
#[test]
fn agx_kernels_compile_or_refuse_with_the_tier() {
let mut kernels = vec![
@@ -769,13 +768,6 @@ fn agx_kernels_compile_or_refuse_with_the_tier() {
if *shuffles && tier == Ok(Tier::Emulated) {
emulated += 1;
}
let (plan, _) = typed_module(bc, name, &p).expect("plan");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{stem} {name}: estimate {} < emitted {words}",
plan.estimate.words
);
ok += 1;
}
Err(Error::Unsupported(u)) if *shuffles => {
@@ -21,13 +21,11 @@ use crate::device::requirements::VkFeature;
use crate::device::requirements::VkProperty;
use crate::device::{Device, DevicePolicy};
use crate::error::{Capability, Error, Feature, LowerFamily, Needs};
use crate::library::FunctionConstantValues;
use crate::lower::emit::emit_module;
use crate::lower::select::{select, LowerInputs};
use crate::lower::simd::WidestPin;
use crate::memory::static_root::analyze_memory;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::compile::{plan_bitcode, EntryRef};
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::pipeline::testing::{
compile, description, link_and_validate, llvm_assemble, meter, profile, AssembleError, Scratch,
@@ -1141,22 +1139,6 @@ fn arith_kernels_validate_and_compute_on_every_profile() {
match (compile(&bitcode, kk.name, &p), missing) {
(Ok(a), None) => {
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
// The plan's estimate bounds the emitted words.
let plan = plan_bitcode(
&bitcode,
EntryRef::Name(kk.name),
&FunctionConstantValues::defaults(),
&p,
&LowerInputs::new(),
&mut meter(),
)
.unwrap_or_else(|e| panic!("{what}: plan: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
if let Some(n) = kk.note {
// A maths function records the device's precision.
let n = match n {
@@ -34,7 +34,7 @@ use crate::lower::emit::emit_module;
use crate::lower::select::{select, LowerInputs, Plan};
use crate::lower::simd::WidestPin;
use crate::memory::static_root::analyze_memory;
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::compile::{compile_bitcode, EntryRef};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::PushLoc;
use crate::pipeline::sym::{
@@ -114,26 +114,10 @@ fn assemble(name: &str, body: &str) -> Option<Vec<u8>> {
}
}
/// Compile entry `entry` of `bc` for `prof`, pass L3, and check that the plan's size estimate
/// bounds the emitted words.
/// Compile entry `entry` of `bc` for `prof` and pass L3.
fn l3(bc: &[u8], entry: &str, prof: &DeviceProfile, what: &str) {
let a = compile(bc, entry, prof).unwrap_or_else(|e| panic!("{what}: compile: {e}"));
link_and_validate(&a, prof).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let plan = plan_bitcode(
bc,
EntryRef::Name(entry),
&FunctionConstantValues::defaults(),
prof,
&LowerInputs::new(),
&mut meter(),
)
.unwrap_or_else(|e| panic!("{what}: plan: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
}
fn buffer_slot(index: u32) -> ResourceSlot {
@@ -1379,48 +1379,6 @@ fn the_footprint_arithmetic_is_no_contraction() {
}
}
/// The plan's word estimate bounds the emitted module of every public bicubic fixture (its samples'
/// call sites, and the routines once) on every committed profile.
#[test]
fn the_estimate_bounds_the_bicubic_fixtures() {
use crate::budget::SPIRV_WORDS;
use crate::library::FunctionConstantValues;
use crate::lower::select::LowerInputs;
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::testing::meter;
let fixtures = [
"bcu_address",
"bcu_edges",
"bcu_formats",
"bcu_forms",
"bcu_fragment",
"bcx_rules",
"bcx_table",
];
for name in fixtures {
let Ok(bc) = llvm_assemble(&engine_dir().join(format!("{name}.ll"))) else {
eprintln!("SKIPPED: llvm-as");
return;
};
for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") {
let what = format!("{name} on {stem}");
let (entry, consts) = (EntryRef::Name(name), FunctionConstantValues::defaults());
let inputs = LowerInputs::new();
let plan = plan_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let a = compile_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter(), SPIRV_WORDS)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let words = a.module.words.len() as u64;
eprintln!("{what}: estimate {} emitted {words}", plan.estimate.words);
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
}
}
}
/// A 2D bicubic sample is one call of the plane's routine (its sixteen taps, four fractions, the
/// bilinear test and the format's bits: 22 parameters), whose sum is the device's arithmetic: no
/// other routine of the old fixed-point datapath (the small level's separate quad call, the weights'
+3 -22
View File
@@ -27,17 +27,14 @@ use crate::device::profile::DeviceProfile;
use crate::device::requirements::VkFeature;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::{Capability, Error, Feature, Unsupported};
use crate::library::FunctionConstantValues;
use crate::lower::select::{LowerInputs, Plan};
use crate::pipeline::compile::{plan_bitcode, EntryRef};
use crate::lower::select::Plan;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::PushLoc;
use crate::pipeline::sym::{
Axis, PushField, ResourceKind, ResourceSlot, SpecKey, Stage, SyntheticBinding,
};
use crate::pipeline::testing::{
compile, fixtures_dir, link_and_validate, llvm_assemble, meter, profile, typed_module,
AssembleError,
compile, fixtures_dir, link_and_validate, llvm_assemble, profile, typed_module, AssembleError,
};
use crate::spirv::interp::{run, Buffer, Config, InterpError, Order, Resources, TrapKind};
use crate::spirv::ir::{GlobalKind, TypedModule};
@@ -122,26 +119,10 @@ fn fixture(name: &str) -> Option<Vec<u8>> {
}
}
/// Compile entry `entry` of `bc` for `prof`, pass L3, and check that the plan's size estimate
/// bounds the emitted words.
/// Compile entry `entry` of `bc` for `prof` and pass L3.
fn l3(bc: &[u8], entry: &str, prof: &DeviceProfile, what: &str) {
let a = compile(bc, entry, prof).unwrap_or_else(|e| panic!("{what}: compile: {e}"));
link_and_validate(&a, prof).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let plan = plan_bitcode(
bc,
EntryRef::Name(entry),
&FunctionConstantValues::defaults(),
prof,
&LowerInputs::new(),
&mut meter(),
)
.unwrap_or_else(|e| panic!("{what}: plan: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
}
fn to_bytes(words: &[u32]) -> Vec<u8> {
@@ -31,7 +31,7 @@ use crate::library::{FunctionConstantValues, Library};
use crate::lower::select::{LowerInputs, Plan};
use crate::metal::{self, PixelFormat, TextureType};
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::compile::{compile_bitcode, EntryRef};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::{
Axis, ResourceKind, ResourceSlot, SampledType, SlotClass, SlotRef, SpecKey, Stage,
@@ -222,8 +222,7 @@ fn inputs(bound: Option<SampledType>) -> LowerInputs {
i
}
/// Compile the kernel `bc` under `inputs` on `p`, check that the plan's word estimate bounds the
/// emission, and validate the linked module.
/// Compile the kernel `bc` under `inputs` on `p` and validate the linked module.
fn validate(
bc: &[u8],
inputs: &LowerInputs,
@@ -232,16 +231,8 @@ fn validate(
) {
let consts = FunctionConstantValues::defaults();
let entry = EntryRef::Name("k");
let plan = plan_bitcode(bc, entry, &consts, p, inputs, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let a = compile_bitcode(bc, entry, &consts, p, inputs, &mut meter(), SPIRV_WORDS)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}"));
}
@@ -772,8 +763,8 @@ fn held_classes(a: &crate::library::FunctionArtifact) -> Vec<SampledType> {
/// A read and a query of a texture an argument buffer holds, through each declared type, read a
/// member of another numeric class in its own class: on every committed profile with a sampled
/// heap, the module declares the sampled class of every numeric type, stays inside the plan's word
/// estimate, passes L3 and states `RuntimeFact::HeapCrossClassNeutral` for the formats it does not
/// heap, the module declares the sampled class of every numeric type, passes L3 and states
/// `RuntimeFact::HeapCrossClassNeutral` for the formats it does not
/// take alone (not `every_member`). A sample through the argument buffer, and a `ushort` read
/// (whose query still crosses), have no answer for any such member: they state the fact for every
/// member of their class, which the planner reports and the runtime announces.
@@ -845,8 +836,8 @@ fn a_texture_an_argument_buffer_holds_is_read_in_its_own_class() {
/// A `half` read of a texture an argument buffer holds merges its class arms as the texel's `half`
/// bits (`emit::read_crossed`), widened once after the merge: on every committed profile with a
/// sampled heap, the module merges a vector of four `u32`s and merges no texel struct, stays inside
/// the plan's word estimate and passes L3. A member of another class then keeps its words' low 16
/// sampled heap, the module merges a vector of four `u32`s and merges no texel struct, and passes
/// L3. A member of another class then keeps its words' low 16
/// bits wherever the value is stored unchanged, where a merge of each arm's widened `half` selected
/// against a null handle's zero is a move Metal's compiler does not fold back to the bits (on the
/// Apple M3 Max a NaN's bits became `0x7E00`). A `float` read, which widens nothing, still merges
@@ -438,12 +438,6 @@ fn check(stem: &str, bc: &[u8], kernel: &str, predicated: bool) {
predicated,
"{stem} {kernel}: predicated"
);
assert!(
plan.estimate.words >= a.module.words.len() as u64,
"{stem} {kernel}: estimate {} < emitted {}",
plan.estimate.words,
a.module.words.len()
);
let report = workgroup_barriers(&m).expect("check");
assert!(report.barriers > 0, "{stem} {kernel}: no barrier");
assert_eq!(report.in_callees, 0, "{stem} {kernel}");
@@ -32,7 +32,7 @@ use crate::library::{FunctionConstantValues, Library};
use crate::lower::select::{LowerInputs, Plan};
use crate::metal::format::ExtendedRange;
use crate::metal::{self, PixelFormat, TextureType};
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::compile::{compile_bitcode, EntryRef};
use crate::pipeline::interface::PushLoc;
use crate::pipeline::lower_inputs::{StorageImageChoice, StorageImageClass};
use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef};
@@ -190,8 +190,7 @@ fn profiles() -> Vec<(&'static str, crate::device::profile::DeviceProfile)> {
.collect()
}
/// Compile the kernel `bc` under `inputs` on `p`, check that the plan's word estimate bounds the
/// emission, and validate the linked module.
/// Compile the kernel `bc` under `inputs` on `p` and validate the linked module.
fn validate(
bc: &[u8],
inputs: &LowerInputs,
@@ -211,16 +210,8 @@ fn validate_entry(
) -> std::sync::Arc<crate::library::FunctionArtifact> {
let consts = FunctionConstantValues::defaults();
let entry = EntryRef::Name(entry);
let plan = plan_bitcode(bc, entry, &consts, p, inputs, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let a = compile_bitcode(bc, entry, &consts, p, inputs, &mut meter(), SPIRV_WORDS)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}"));
a
}
@@ -10,7 +10,7 @@
//! level's linear filter and the format's clamp are Metal's; the sum is the device's `f32`
//! multiply and add of the decoded taps under the weights computed from the fraction, where Metal
//! sums fixed-point weights exactly onto the lane's grid, and a `half` result is the device's
//! narrowing. Each compile is validated, and its plan's estimate bounds it. What no case measured
//! narrowing. Each compile is validated. What no case measured
//! is refused, `NotImplemented(SamplerBicubicFilter)`: a padded or bfloat form's bicubic sample, a
//! swizzled texture's, and a gather through a bicubic sampler.
@@ -4,8 +4,8 @@
//! handle's class index names.
//!
//! - On every committed profile with a sampled heap, a `float` or `half` read declares the float
//! class and its unsigned integer twin, defines the decode routine once, stays inside the
//! plan's word estimate, and passes L3; a query alone declares the twin and no routine.
//! class and its unsigned integer twin, defines the decode routine once, and passes L3; a
//! query alone declares the twin and no routine.
//! - A read of an unsigned integer heap group declares no twin and no routine, its query its own
//! class's; it declares the float class, which holds a member of a float format that it reads in
//! that member's own class.
@@ -124,7 +124,7 @@ fn sampled_2d(ty: SampledType) -> impl Fn(&ImageHandleClass) -> bool {
}
/// Each use on every committed profile with a sampled heap (the others refuse the argument
/// buffer's texture): the classes it declares, the routine, the word estimate, and L3.
/// buffer's texture): the classes it declares, the routine, and L3.
#[test]
fn heap_reads_reach_a_raw_member_through_the_unsigned_twin() {
let consts = FunctionConstantValues::defaults();
@@ -153,14 +153,6 @@ fn heap_reads_reach_a_raw_member_through_the_unsigned_twin() {
})) => continue,
Err(e) => panic!("{what}: {e}"),
};
let plan = plan_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let classes = heap_classes(&a);
let float = classes
@@ -299,7 +291,7 @@ define void @k(ptr addrspace(1) %out, ptr addrspace(2) %m, {param}i32 %gid) {{
/// group's unsigned integer class (`sampler::heap_raw`), on every committed profile with a
/// sampled heap: a constexpr sampler's nearest or linear sample, `float` or `half`, and its
/// `float` gather declare the twin, define the decode routine, state no
/// `RuntimeFact::HeapRawSamples`, stay inside the plan's word estimate, and pass L3; a `half`
/// `RuntimeFact::HeapRawSamples`, and pass L3; a `half`
/// gather (its non-bfloat forms not measured) and a sample through a runtime sampler slot
/// declare the twin too and state the fact (with no slot, and naming slot 0); a sample through a
/// mip-filtered constexpr sampler declares no twin and states the fact with no slot.
@@ -341,14 +333,6 @@ fn heap_samples_reach_a_raw_member_through_the_unsigned_twin() {
})) => continue,
Err(e) => panic!("{what}: {e}"),
};
let plan = plan_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let classes = heap_classes(&a);
let uint = classes
@@ -215,7 +215,7 @@ pub(super) struct Texels<'a> {
/// The samples kernel `bc` takes on `p` of `tex` in `form` at `coords`, through a runtime
/// sampler of word `word` where it has one: each result's lanes as bits (`half` lanes where
/// `half`). The compile is validated, and the plan's estimate bounds it.
/// `half`). The compile is validated.
fn sample(
bc: &[u8],
p: &crate::device::profile::DeviceProfile,
@@ -5,8 +5,8 @@
//! - On every committed profile, a fragment function compiled for a pipeline with such an
//! attachment (`rt6_fill_rgba32float`, `rt6_fill_rgba16float`) records the attachment
//! (`StageIo::extended_range_colors`), keeps its interface variable's Metal type, declares the
//! output variable as the raw format's unsigned components, bounds its emission by the plan's
//! estimate, and links: the attachment takes the raw format, a write of every raw component
//! output variable as the raw format's unsigned components, and links: the attachment takes
//! the raw format, a write of every raw component
//! under a full mask and of none under an empty one, no blend, and both modules pass L3.
//! - A blended attachment the function does not write (no fragment function) links with no blend
//! and an empty mask, as Metal leaves an unwritten attachment; one it writes is refused
@@ -145,7 +145,6 @@ fn fragment_outputs_to_extended_range_targets_write_raw_texels() {
let Some(bc) = fixture() else {
return;
};
let consts = FunctionConstantValues::defaults();
for stem in VENUES {
let p = venue(stem);
let v = compile(&bc, "rt6_fill_vertex", &p).expect("vertex");
@@ -204,21 +203,6 @@ fn fragment_outputs_to_extended_range_targets_write_raw_texels() {
(IoNumeric::Float, 4),
"{what}"
);
let plan = plan_bitcode(
&bc,
EntryRef::Name(entry),
&consts,
&p,
&inputs,
&mut meter(),
)
.unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(
plan.estimate.words >= f.module.words.len() as u64,
"{what}: estimate {} < emitted {}",
plan.estimate.words,
f.module.words.len()
);
let g = l.graphics.as_ref().expect("graphics");
let a = g.color_attachments[0].expect("attachment");
use vk::ColorComponentFlags as C;
@@ -22,7 +22,7 @@
//! descriptor refusals are typed.
//! - A `Compiled` kernel's fetches must be the pipeline descriptor's; keys take the descriptor
//! canonically.
//! - Every committed profile validates the modules (L3), and the size estimate bounds them.
//! - Every committed profile validates the modules (L3).
//!
//! `llvm-as` assembles the fixture; without it the tests skip visibly.
@@ -1660,7 +1660,7 @@ fn compiled_kernels_and_keys_follow_the_descriptor() {
));
}
/// The descriptors the validation and estimate checks compile under: every step.
/// The descriptors the validation checks compile under: every step.
fn every_step() -> Vec<StageInputDescriptor> {
use StepFunction as S;
vec![
@@ -1683,8 +1683,7 @@ fn every_step() -> Vec<StageInputDescriptor> {
]
}
/// L3 on every committed profile: each step's module links and validates wherever it compiles,
/// and the plan's size estimate bounds its words.
/// L3 on every committed profile: each step's module links and validates wherever it compiles.
#[test]
fn every_committed_profile_validates_the_fetch() {
let Some(bc) = fixture() else { return };
@@ -1728,14 +1727,6 @@ fn every_committed_profile_validates_the_fetch() {
Err(e) => panic!("{stem} {entry} psb={psb} {d:?}: {e}"),
};
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {entry}: {e}"));
let plan = plan_bitcode(&bc, EntryRef::Name(entry), &consts, &p, &i, &mut meter())
.expect("plan");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{stem} {entry} {d:?}: estimate {} < emitted {words}",
plan.estimate.words
);
// The artifact lists every fetched attribute with its descriptor entries.
let listed = a
.interface
@@ -15,8 +15,8 @@
//! words: the partial threadgroup's `threads_per_threadgroup`, its threads' positions and indices
//! over its own size, its simdgroups' indices, and, behind a threadgroup barrier, a neighbour's
//! threadgroup word and its simdgroup's sum over the live lanes alone. The variant's module passes
//! `spirv-val`, holds no workgroup barrier in a block its own uniformity does not prove uniform,
//! and is within its estimate; where its simdgroups are emulated it is refused
//! `spirv-val` and holds no workgroup barrier in a block its own uniformity does not prove
//! uniform; where its simdgroups are emulated it is refused
//! (`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`), so the split stays. No GPU is used.
//!
//! `llvm-as` assembles the kernels; a missing tool skips visibly.
@@ -323,8 +323,7 @@ fn grid_of(d: &Dispatch) -> ([u32; 3], [u32; 3]) {
/// every dispatch of `grids` (the dispatch, the split's regions, the variant's): both give
/// Metal's words, on the region counts given, and every region of the variant's plan of a
/// threadgroup size takes one specialization, whatever its grid. The variant's module is valid,
/// walks no workgroup barrier in non-uniform control flow, is within its estimate and states its
/// fact. `false` where the variant is refused or its key would emulate simdgroups (the split
/// walks no workgroup barrier in non-uniform control flow and states its fact. `false` where the variant is refused or its key would emulate simdgroups (the split
/// stays).
fn check(
stem: &str,
@@ -356,14 +355,8 @@ fn check(
"{stem} {entry}: the variant's fact"
);
link_and_validate(&a, dev.profile()).unwrap_or_else(|e| panic!("{stem} {entry}: {e}"));
let (plan, tm) =
let (_, tm) =
typed_module_with(bc, entry, dev.profile(), &inputs).expect("typed module");
assert!(
plan.estimate.words >= a.module.words.len() as u64,
"{stem} {entry}: estimate {} < emitted {}",
plan.estimate.words,
a.module.words.len()
);
let report = workgroup_barriers(&tm).expect("barriers");
assert!(
report.nonuniform.is_empty(),
@@ -359,9 +359,8 @@ fn resources_bound(plan: &Plan, mem: &Memory, threads: u32, binds: &[Bind]) -> (
)
}
/// Compile entry `entry` of `bc` for `p` under `inputs`, pass L3, check that the plan's size
/// estimate bounds the emitted words, and return the plan and the typed module the interpreter
/// runs.
/// Compile entry `entry` of `bc` for `p` under `inputs`, pass L3, and return the plan and the
/// typed module the interpreter runs.
fn checked(
bc: &[u8],
entry: &str,
@@ -381,12 +380,6 @@ fn checked(
.unwrap_or_else(|e| panic!("{what}: {e}"));
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let (plan, m) = typed_module_with(bc, entry, p, inputs).expect("module");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
(plan, m)
}
@@ -280,8 +280,8 @@ fn resources(
}
}
/// Compile entry `entry` of `bc` for `p`, pass L3, check that the plan's size estimate bounds
/// the emitted words, and return the plan and the typed module the interpreter runs.
/// Compile entry `entry` of `bc` for `p`, pass L3, and return the plan and the typed module the
/// interpreter runs.
fn checked(bc: &[u8], entry: &str, p: &DeviceProfile, what: &str) -> (Plan, TypedModule) {
let inputs = LowerInputs::new();
let a = compile_bitcode(
@@ -296,12 +296,6 @@ fn checked(bc: &[u8], entry: &str, p: &DeviceProfile, what: &str) -> (Plan, Type
.unwrap_or_else(|e| panic!("{what}: {e}"));
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let (plan, m) = typed_module_with(bc, entry, p, &inputs).expect("module");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
(plan, m)
}
@@ -8,7 +8,7 @@
//! a cube reads it as a normalized sampler. A runtime sampler's gather reads only its word's
//! coordinates bit, and its sample also its `NearestPixelSampler` specialization. Every module
//! requires the device's sampler (`VkProperty::DeviceSampling`) and validates on every committed
//! profile, and the plan's word estimate bounds what it emits.
//! profile.
//!
//! `llvm-as` assembles the kernels; without it the tests skip visibly.
@@ -871,43 +871,3 @@ fn a_subnormal_coordinate_reaches_the_device_unflushed() {
}
}
}
/// The plan's word estimate bounds the emitted module of every kernel above on every committed
/// profile.
#[test]
fn the_coordinate_estimate_bounds_its_emission() {
use crate::budget::SPIRV_WORDS;
use crate::library::FunctionConstantValues;
use crate::lower::select::LowerInputs;
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::testing::meter;
let profiles = crate::spirv::testing::committed_profiles().expect("profiles");
let pixel = pixel_cases()
.into_iter()
.map(|(n, o, w, _)| (n, o, Some(w)));
for (name, op, words) in cases()
.into_iter()
.map(|(n, o, w, _)| (n, o, w))
.chain(pixel)
{
let Some(bc) = assemble(name, &kernel(op, words)) else {
return;
};
for (stem, p) in &profiles {
let what = format!("{name} on {stem}");
let (entry, consts) = (EntryRef::Name("k"), FunctionConstantValues::defaults());
let inputs = LowerInputs::new();
let plan = plan_bitcode(&bc, entry, &consts, p, &inputs, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let a = compile_bitcode(&bc, entry, &consts, p, &inputs, &mut meter(), SPIRV_WORDS)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let emitted = a.module.words.len() as u64;
eprintln!("{what}: estimate {} emitted {emitted}", plan.estimate.words);
assert!(
plan.estimate.words >= emitted,
"{what}: estimate {} < emitted {emitted}",
plan.estimate.words
);
}
}
}
@@ -9,7 +9,6 @@
//! kernel equals the lane of the one-texture kernel bound to its candidate (with that
//! candidate's size and format), and the null texture (the switch's null arm) reads zero.
//! Candidates differ in size and format, so the emulation's facts must be the named one's.
//! - **The estimate bounds the emission** on every committed profile.
//!
//! `llvm-as` assembles the kernels; without it the tests skip visibly.
@@ -447,51 +446,3 @@ fn the_shared_emulation_answers_each_candidates_own_lane() {
}
}
}
/// The plan's word estimate bounds the emitted module of each shared form over 2, 8 and 32
/// candidates on every committed profile that admits it.
#[test]
fn the_shared_estimate_bounds_its_emission() {
use crate::budget::SPIRV_WORDS;
use crate::library::FunctionConstantValues;
use crate::lower::select::LowerInputs;
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::testing::meter;
let profiles = crate::spirv::testing::committed_profiles().expect("profiles");
let nearest = Form {
name: "nearest repeat",
words: sampler(0, REPEAT, false),
};
let mut all = forms().to_vec();
all.push(nearest);
for form in all {
for n in [2u32, 8, 32] {
let name = format!("{} n={n}", form.name);
let Some(bc) = assemble(&name, &kernel(Some(n), form)) else {
return;
};
for (stem, p) in &profiles {
let what = format!("{name} on {stem}");
let (entry, consts) = (EntryRef::Name("k"), FunctionConstantValues::defaults());
let inputs = LowerInputs::new();
let plan = match plan_bitcode(&bc, entry, &consts, p, &inputs, &mut meter()) {
Ok(plan) => plan,
Err(e) => {
assert!(stem != "lavapipe", "{what}: {e}");
eprintln!("{what}: refused: {e}");
continue;
}
};
let a = compile_bitcode(&bc, entry, &consts, p, &inputs, &mut meter(), SPIRV_WORDS)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let emitted = a.module.words.len() as u64;
eprintln!("{what}: estimate {} emitted {emitted}", plan.estimate.words);
assert!(
plan.estimate.words >= emitted,
"{what}: estimate {} < emitted {emitted}",
plan.estimate.words
);
}
}
}
}
+1 -25
View File
@@ -602,26 +602,6 @@ fn a_device_that_cannot_pin_the_stage_refuses_a_pinned_kernel() {
assert_eq!(nvk.check(&a.requirements), Ok(()));
}
/// The plan's size estimate bounds the emitted words of every kernel in both tiers.
#[test]
fn the_estimate_bounds_every_simd_kernel() {
let Some(bc) = assemble("simd_ops") else {
return;
};
for p in [moltenvk(), wave64()] {
for kernel in KERNELS {
let (plan, _) = typed_module(&bc, kernel, &p).expect("plan");
let a = compile(&bc, kernel, &p).expect("compile");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{kernel}: estimate {} < emitted {words}",
plan.estimate.words
);
}
}
}
/// A kernel with a tangled instruction declares `MaximallyReconvergesKHR` where the profile has
/// maximal reconvergence (reconvergence guaranteed), and records `ImplementationDefined` where it
/// has neither mode, beside `PrecisionNote::DeviceReconvergence`.
@@ -1056,7 +1036,7 @@ fn mask_expected(kernel: &str, n: u32, t: u32) -> u32 {
/// `quad_ballot` and `simd_active_threads_mask` (Apple's `air.quad_ballot` and
/// `air.simd_active_threads_mask.i64`) give Metal's masks in the `Direct` tier at 32 lanes
/// (with and without `shaderInt64`) and the `Cluster32` tier at 64, uniform and divergent, in
/// both scheduling orders; the estimate bounds their words.
/// both scheduling orders.
#[test]
fn quad_ballots_and_simd_active_masks_run_in_every_subgroup_tier() {
let Some(bc) = assemble("simd_masks") else {
@@ -1089,10 +1069,6 @@ fn quad_ballots_and_simd_active_masks_run_in_every_subgroup_tier() {
assert_eq!(plan.simd.1, tier, "{kernel}");
let a = compile(&bc, kernel, &p).unwrap_or_else(|e| panic!("{kernel}: {e}"));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{kernel}: L3: {e}"));
assert!(
plan.estimate.words >= a.module.words.len() as u64,
"{kernel}: the estimate"
);
for &local in locals {
let n: u32 = local.iter().product();
let out = run_all(&plan, &m, local, lanes);
@@ -763,17 +763,10 @@ fn run_expected(stem: &str, kernel: &str, plan: &Plan, m: &TypedModule, locals:
}
/// L3: the kernel links, relocates, and passes `spirv-val` under the profile, and uses no
/// subgroup instruction or capability. The plan's size estimate bounds the emitted words.
/// subgroup instruction or capability.
fn validate(stem: &str, bc: &[u8], kernel: &str) {
let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile");
let a = compile(bc, kernel, &p).unwrap_or_else(|e| panic!("{stem} {kernel}: {e}"));
let (plan, _) = typed_module(bc, kernel, &p).expect("plan");
let emitted = a.module.words.len() as u64;
assert!(
plan.estimate.words >= emitted,
"{stem} {kernel}: estimate {} < emitted {emitted}",
plan.estimate.words
);
let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {kernel}: {e}"));
let text = spirv_dis(&words);
assert!(
@@ -1756,76 +1749,6 @@ fn one_row_key() -> VariantKey {
key
}
/// `simd_divergent`'s `guard_k` (a simdgroup sum in divergent control flow) followed by `stages`
/// diamonds of plain arithmetic, each a branch on a per-thread value and a phi: a large body whose
/// predicated walk synchronizes in one block.
fn large_body(stages: u32) -> Option<Vec<u8>> {
let text = std::fs::read_to_string(engine_dir().join("simd_divergent.ll")).expect("read");
let start = text.find("define void @guard_k(").expect("guard_k");
let merge = start + text[start..].find("\n16:").expect("guard_k's merge") + 1;
let end = merge + text[merge..].find("\n}\n").expect("guard_k's end") + 1;
let mut body = String::from("16:\n br label %s0\n");
let mut prev = String::from("%2");
for i in 0..stages {
let next = i + 1;
body += &format!(
"s{i}:\n %k{i} = and i32 {prev}, 7\n %c{i} = icmp ult i32 %k{i}, 3\n \
br i1 %c{i}, label %a{i}, label %b{i}\n\
a{i}:\n %y{i} = mul i32 {prev}, 3\n br label %m{i}\n\
b{i}:\n %z{i} = add i32 {prev}, {next}\n br label %m{i}\n\
m{i}:\n %w{i} = phi i32 [ %y{i}, %a{i} ], [ %z{i}, %b{i} ]\n br label %s{next}\n"
);
prev = format!("%w{i}");
}
body += &format!(
"s{stages}:\n %at = zext i32 %2 to i64\n \
%out = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %at\n \
store i32 {prev}, ptr addrspace(1) %out, align 4\n ret void\n"
);
let text = format!("{}{body}{}", &text[..merge], &text[end..]);
assemble_text(&format!("large-body-{stages}"), &text)
}
/// A large body under the emulated-simdgroups input ([`large_body`]): its estimate bounds the
/// words it emits and stays within a small multiple of them (the walk is charged per construct it
/// emits), so it compiles under a words cap of that multiple of its emitted size.
#[test]
fn a_large_predicated_body_compiles_under_a_cap_it_fits() {
let Some(bc) = large_body(256) else {
return;
};
let p = profile("lavapipe", DevicePolicy::RESIDENT_TABLES).expect("profile");
let inputs = emulated_inputs();
let (plan, _) = typed_module_with(&bc, "guard_k", &p, &inputs).expect("plan");
assert!(
plan.families.simd.predication.is_some(),
"walked predicated"
);
let a = crate::pipeline::testing::compile_with(&bc, "guard_k", &p, &inputs).expect("compile");
let emitted = a.module.words.len() as u64;
assert!(
plan.estimate.words >= emitted,
"estimate {} < emitted {emitted}",
plan.estimate.words
);
let cap = 8 * emitted;
let capped = crate::pipeline::compile::compile_bitcode(
&bc,
crate::pipeline::compile::EntryRef::Name("guard_k"),
&crate::library::FunctionConstantValues::defaults(),
&p,
&inputs,
&mut crate::pipeline::testing::meter(),
cap,
);
assert!(
capped.is_ok(),
"estimate {} under cap {cap} (emitted {emitted}): {:?}",
plan.estimate.words,
capped.err()
);
}
/// `kernel` of `bc` on `DIRECT`: its own tier is `Direct` with a multiple-of-32 constraint, and
/// under the emulated-simdgroups input the `Emulated` tier, which depends on the variant, passes
/// L3 without a subgroup instruction, and gives the reading (a partial simdgroup's active lanes are
@@ -1866,10 +1789,6 @@ fn run_variant(bc: &[u8], kernel: &str, words: Option<u32>) {
)
.unwrap_or_else(|e| panic!("{kernel}: {e}"));
let a = compiled.artifact();
assert!(
plan.estimate.words >= a.module.words.len() as u64,
"{kernel}"
);
assert_eq!(a.subgroup, SubgroupRequirement::NONE, "{kernel}");
let (_, words) = link_and_validate(a, p).unwrap_or_else(|e| panic!("{kernel}: {e}"));
let text = spirv_dis(&words);
@@ -939,8 +939,7 @@ fn products_record_their_precision() {
/// Every matrix kernel compiles, links, relocates, and passes L3 on every committed profile
/// exactly where its cross-lane class (a shuffle with a product, the lane alone for blocks) has
/// a compute tier, and elsewhere is refused as that tier is (`matrix_mixed`'s five buffers fit
/// the runtime floor's four storage buffers per stage through a uniform view). The plan's size estimate
/// bounds the emitted words.
/// the runtime floor's four storage buffers per stage through a uniform view).
#[test]
fn matrix_kernels_compile_or_refuse_with_the_tier() {
// Each kernel with its operations' class: a product shuffles, the blocks alone read the lane.
@@ -984,13 +983,6 @@ fn matrix_kernels_compile_or_refuse_with_the_tier() {
Ok(a) => {
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {name}: {e}"));
assert!(tier.is_ok(), "{stem} {name}");
let (plan, _) = typed_module(bc, name, &p).expect("plan");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{stem} {name}: estimate {} < emitted {words}",
plan.estimate.words
);
ok += 1;
}
// Threadgroup memory Metal zeroes, on a device that does not zero it.
@@ -19,7 +19,7 @@ use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::{Error, InternalKind, Limit};
use crate::library::{FunctionArtifact, FunctionConstantValues};
use crate::lower::select::LowerInputs;
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::compile::{compile_bitcode, EntryRef};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::{
AccessSet, BufferForm, DescriptorView, PushLoc, SlotInterface, StageDescriptor, StageSpec,
@@ -276,9 +276,9 @@ fn typed_and_opaque_bitcode_give_identical_spirv() {
}
}
/// An estimate above the word cap is refused before emission.
/// A module above the word cap is refused.
#[test]
fn an_over_estimate_is_refused_before_emission() {
fn a_module_above_the_word_cap_is_refused() {
let Some(bitcode) = store_const() else { return };
let p = profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).expect("profile");
let a = compile(&bitcode, "store_const", &p).expect("compile");
@@ -307,43 +307,6 @@ fn an_over_estimate_is_refused_before_emission() {
assert!(ok.module.words.len() as u64 == words);
}
/// The word cap relies on `SizeEstimate` being an upper bound of the emitted module: on every M1
/// profile the plan's estimate is at least the artifact's word count, and a cap equal to the
/// estimate admits the compile.
#[test]
fn the_estimate_bounds_the_emitted_words() {
let Some(bitcode) = store_const() else { return };
for stem in M1_PROFILES {
let what = stem;
let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile");
let plan = plan_bitcode(
&bitcode,
EntryRef::Name("store_const"),
&FunctionConstantValues::defaults(),
&p,
&LowerInputs::new(),
&mut meter(),
)
.unwrap_or_else(|e| panic!("{what}: plan: {e}"));
let a = compile_bitcode(
&bitcode,
EntryRef::Name("store_const"),
&FunctionConstantValues::defaults(),
&p,
&LowerInputs::new(),
&mut meter(),
plan.estimate.words,
)
.unwrap_or_else(|e| panic!("{what}: compile at the estimate: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
}
}
/// A loop kernel from the public fixtures (a counted loop between a buffer load and a buffer store)
/// compiles once the access family lowers static-root loads and stores: its loop is the module's
/// one loop, with no execution status, and the module passes L3.
@@ -282,52 +282,3 @@ fn the_copy_of_a_snapshot_slot_refuses_a_form_its_fetch_s_lanes_do_not_hold() {
}
}
}
/// The entry's size estimate bounds the words every snapshot copy emits (`lower::fragment`'s
/// `snapshot::SLOT_WORDS`): every form under the resident-table domains.
#[test]
fn the_snapshot_estimate_bounds_the_copy_it_emits() {
use crate::library::function::FunctionConstantValues;
use crate::pipeline::compile::{plan_bitcode, EntryRef};
use crate::pipeline::lower_inputs::LoweringInputs;
use crate::pipeline::testing::{compile_with, meter, profile};
let Some(bc) = fixture("tob_renders") else {
return;
};
let inputs = |form: SnapshotForm| {
let mut inputs = LoweringInputs::new();
inputs.snapshot_textures.insert(SLOT, form);
inputs
};
let mut checked = 0;
for stem in PROFILES {
{
let policy = DevicePolicy::RESIDENT_TABLES;
let p = profile(stem, policy).expect("profile");
for form in FORMS {
let inputs = inputs(form);
let Ok(plan) = plan_bitcode(
&bc,
EntryRef::Name("tob_read"),
&FunctionConstantValues::defaults(),
&p,
&inputs,
&mut meter(),
) else {
continue;
};
let Ok(a) = compile_with(&bc, "tob_read", &p, &inputs) else {
continue;
};
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{stem} {form:?}: estimate {} < emitted {words}",
plan.estimate.words
);
checked += 1;
}
}
}
assert!(checked > 0, "a profile that compiles a snapshot copy");
}
@@ -10,7 +10,7 @@
//! outright. (The interpreter models no `Pow`, so no decoded value is run here.)
//! - The binder joins a slot to the plan's variant exactly where the device holds the bound
//! format's twin, and its views then view the twin; elsewhere they view the sRGB format.
//! - The plan's word estimate bounds the emission of every form on every committed profile.
//! - Every form validates on every committed profile.
//!
//! `llvm-as` assembles the kernels; without it the tests skip visibly.
@@ -27,7 +27,7 @@ use crate::lower::select::LowerInputs;
use crate::metal::format::bound_texel_format;
use crate::metal::texel_format::srgb_twin_on;
use crate::metal::{self, PixelFormat, TextureType};
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::compile::{compile_bitcode, EntryRef};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::{SlotClass, SlotRef, SpecKey, Stage};
use crate::pipeline::testing::{
@@ -515,11 +515,10 @@ declare {{ {vec4}, i8 }} @air.sample_texture_{name}.{suffix}({args})
)
}
/// The plan's word estimate bounds the emitted module of every access, with the slot in the
/// variant (decoding the twin's codes) and without (the device's decode), on every committed
/// profile, and every form validates there.
/// Every access compiles and validates, with the slot in the variant (decoding the twin's codes)
/// and without (the device's decode), on every committed profile.
#[test]
fn the_srgb_estimate_bounds_its_emission() {
fn every_srgb_form_validates() {
let consts = FunctionConstantValues::defaults();
let forms = [
("read half", Access::Read, true),
@@ -586,17 +585,8 @@ fn the_srgb_estimate_bounds_its_emission() {
{
let what = format!("{name}{twin} on {stem}");
let entry = EntryRef::Name("k");
let plan = plan_bitcode(&bc, entry, &consts, &p, &under, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let a = compile_bitcode(&bc, entry, &consts, &p, &under, &mut meter(), SPIRV_WORDS)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let words = a.module.words.len() as u64;
eprintln!("{what}: estimate {} emitted {words}", plan.estimate.words);
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
}
}
@@ -16,7 +16,7 @@ use crate::device::DevicePolicy;
use crate::error::{Capability, Error, Feature, Needs};
use crate::library::{FunctionArtifact, FunctionConstantValues};
use crate::metal::{VertexFormat, VertexStepFunction};
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::compile::{compile_bitcode, EntryRef};
use crate::pipeline::descriptor::{
VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor,
};
@@ -428,39 +428,6 @@ fn the_vertex_fetch_projection_selects_fixed_function_or_pulled() {
assert_eq!(a.interface.slots.len(), 1, "one slot for buffer 1");
}
/// The plan's size estimate bounds the emitted words of every stage entry.
#[test]
fn the_estimate_bounds_every_stage_entry() {
let Some(bc) = fixture() else { return };
let p = prof("moltenvk-m3");
for entry in [
"stage_io_vertex",
"stage_io_vertex_position",
"stage_io_vertex_clip",
"stage_io_vertex_layer",
"stage_io_fragment",
"stage_io_fragment_point",
"stage_io_fragment_dual_source",
] {
let plan = plan_bitcode(
&bc,
EntryRef::Name(entry),
&FunctionConstantValues::defaults(),
&p,
&LoweringInputs::new(),
&mut meter(),
)
.expect("plan");
let a = compile(&bc, entry, &p).expect("compile");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{entry}: estimate {} < emitted {words}",
plan.estimate.words
);
}
}
/// The variables `words` decorate `BuiltIn PointSize` (`OpDecorate <id> BuiltIn(11) PointSize(1)`)
/// that an `OpStore` (opcode 62) writes through.
fn stored_point_sizes(words: &[u32]) -> Vec<u32> {
@@ -23,17 +23,14 @@ use crate::device::requirements::VkFeature as F;
use crate::device::{DevicePolicy, DeviceProfile};
use crate::error::{Capability, Error, Feature, Needs};
use crate::library::FunctionArtifact;
use crate::library::FunctionConstantValues;
use crate::metal::PixelFormat;
use crate::pipeline::compile::{plan_bitcode, EntryRef};
use crate::pipeline::descriptor::ColorAttachmentDescriptor;
use crate::pipeline::link::{link, LinkInputs, RenderLinkInputs};
use crate::pipeline::lower_inputs::LoweringInputs;
use crate::pipeline::relocate::relocate;
use crate::pipeline::stage_io::{Interpolation, IoNumeric, IoRole, IoType, StageBuiltin};
use crate::pipeline::testing::{
compile, compile_kept, compile_with, engine_dir, fragment_inputs, llvm_assemble, meter,
profile, profile_without, AssembleError,
compile, compile_kept, compile_with, engine_dir, fragment_inputs, llvm_assemble, profile,
profile_without, AssembleError,
};
use crate::spirv::ir::{BinOp, ConstKind, Constant, Contraction, Inst, TypedModule, ValueOrigin};
use crate::spirv::testing::check_words_valid;
@@ -438,37 +435,3 @@ fn the_graphics_state_states_whether_the_fragment_function_reads_barycentric_coo
assert_eq!(graphics.reads_barycentric_coord, want, "{entry}");
}
}
/// The plan's size estimate bounds the emitted words of every entry, the `bool` conversions and the
/// barycentric lane reads included.
#[test]
fn the_estimate_bounds_every_tail_entry() {
let Some(bc) = fixture() else { return };
// A profile that compiles every tail entry (on MoltenVK, both barycentric forms are refused).
let p = prof("amd-780m-radv");
for entry in [
"tail_vertex_bool",
"tail_fragment_bool",
"tail_fragment_primitive",
"tail_fragment_layer",
"tail_fragment_barycentric",
"tail_fragment_barycentric_scalar",
] {
let plan = plan_bitcode(
&bc,
EntryRef::Name(entry),
&FunctionConstantValues::defaults(),
&p,
&LoweringInputs::new(),
&mut meter(),
)
.expect("plan");
let a = compile(&bc, entry, &p).expect("compile");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{entry}: estimate {} < emitted {words}",
plan.estimate.words
);
}
}
@@ -26,7 +26,7 @@ use crate::error::{Error, Feature, LowerFamily, Needs};
use crate::library::{FunctionArtifact, FunctionConstantValues};
use crate::lower::select::Plan;
use crate::metal::{VertexFormat, VertexStepFunction};
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::compile::{compile_bitcode, EntryRef};
use crate::pipeline::descriptor::{
VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor,
};
@@ -146,22 +146,6 @@ fn shared_pulled(rate: u32) -> VertexFetchProjection {
proj
}
/// [`all_pulled`] with the position and uv in normalized formats (signed 10:10:10:2 and SNORM16),
/// whose correctly rounded quotients are the dearest per-lane decode.
fn normalized_pulled(rate: u32) -> VertexFetchProjection {
use VertexStepFunction as S;
let mut proj = all_pulled(rate);
proj.attributes.insert(
0,
pulled(VertexFormat::Int1010102Normalized, 0, 0, S::PerVertex, 1),
);
proj.attributes.insert(
1,
pulled(VertexFormat::Short2Normalized, 12, 0, S::PerVertex, 1),
);
proj
}
/// Buffers 0 (its own) and 1 (shared with `scale`) pulled, 2 and 3 as in [`all_pulled`].
fn both_pulled(rate: u32) -> VertexFetchProjection {
use VertexStepFunction as S;
@@ -518,46 +502,6 @@ fn integer_formats_feed_float_attributes() {
}
}
/// The plan's size estimate bounds the emitted words with every attribute pulled, through views, a
/// shared slot, and (where the profile has them) device addresses, and with normalized formats'
/// exact quotients.
#[test]
fn the_estimate_bounds_pulled_fetches() {
let Some(bc) = fixture() else { return };
for stem in PROFILES {
let p = prof(stem);
let mut variant = inputs(both_pulled(3));
variant.psb_slots = [0, 1, 2, 3].into_iter().map(slot).collect();
let mut cases = vec![
inputs(all_pulled(3)),
inputs(shared_pulled(3)),
inputs(normalized_pulled(3)),
];
if p.fields().buffer_access == BufferAccess::Addressed {
cases.push(variant);
}
for i in cases {
let plan = plan_bitcode(
&bc,
EntryRef::Name(ENTRY),
&FunctionConstantValues::defaults(),
&p,
&i,
&mut meter(),
)
.expect("plan");
let a = compile_inputs(&bc, &p, &i).expect("compile");
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{stem} {:?}: estimate {} < emitted {words}",
i.psb_slots,
plan.estimate.words
);
}
}
}
/// A source buffer whose Metal index is also the function's `scale` argument reads through the
/// argument's slot. The slot is bound once, as a `Whole` storage buffer (alone, `scale` is a
/// `Bounded` window, a uniform view where the profile's containment allows one), read-only and
@@ -841,8 +785,7 @@ const ATOMIC_DECL: &str =
/// runs once before the body, so the function's accesses never reach the attribute. The shared slot
/// is one `Whole`, read-write storage binding (not `NonWritable`), or a `Psb` slot in the
/// `BufferRangeLimit` variant, and passes L3, on every profile with
/// `vertexPipelineStoresAndAtomics` (the others refuse the store by name, as alone); the size
/// estimate bounds the emitted words.
/// `vertexPipelineStoresAndAtomics` (the others refuse the store by name, as alone).
#[test]
fn a_written_or_atomic_argument_shares_its_slot() {
let (Some(write), Some(atomic)) = (
@@ -871,21 +814,6 @@ fn a_written_or_atomic_argument_shares_its_slot() {
}
let a = r.unwrap_or_else(|e| panic!("{what}: {e}"));
validate(&a, &p);
let plan = plan_bitcode(
bc,
EntryRef::Name("probe"),
&FunctionConstantValues::defaults(),
&p,
&i,
&mut meter(),
)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let words = a.module.words.len() as u64;
assert!(
plan.estimate.words >= words,
"{what}: estimate {} < emitted {words}",
plan.estimate.words
);
let s = buffer_slot(&a, 1).expect("buf's slot");
assert!(s.access.write, "{what}: {s:?}");
if how == "alone" {
@@ -5,7 +5,7 @@
//! but renders neither, a fragment function compiled for a pipeline with an `A1BGR5Unorm` or
//! `ABGR4Unorm` attachment (`rt6_fill_rgba32float`, `rt6_fill_rgba16float`) records the
//! attachment (`StageIo::word_colors`), keeps its interface variable's Metal type, declares the
//! output variable as one `uint`, bounds its emission by the plan's estimate, and links: the
//! output variable as one `uint`, and links: the
//! attachment takes `R16_UINT`, a write of its one component under a full mask and of none under
//! an empty one, no blend, and both modules pass L3.
//! - Where the device renders the format (lavapipe), the attachment takes the format itself.
@@ -41,12 +41,11 @@ use std::path::Path;
use crate::budget::Budget;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::{Error, Feature, Needs, RuntimeInput};
use crate::library::{FunctionConstantValues, Library};
use crate::library::Library;
use crate::lower::select::LowerInputs;
use crate::metal::format::WordAttachment;
use crate::metal::{self, ColorWriteMask, PixelFormat};
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::compile::{plan_bitcode, EntryRef};
use crate::pipeline::descriptor::{
ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource,
};
@@ -54,8 +53,7 @@ use crate::pipeline::link::{link, LinkInputs, RenderLinkInputs};
use crate::pipeline::relocate::relocate;
use crate::pipeline::stage_io::{IoNumeric, IoRole};
use crate::pipeline::testing::{
compile, compile_with, engine_dir, fragment_inputs, llvm_assemble, meter, profile,
AssembleError,
compile, compile_with, engine_dir, fragment_inputs, llvm_assemble, profile, AssembleError,
};
use crate::spirv::testing::{check_words_valid, spirv_dis};
use crate::vk;
@@ -113,7 +111,6 @@ fn fragment_outputs_to_word_attachments_write_the_word() {
let Some(bc) = fixture() else {
return;
};
let consts = FunctionConstantValues::defaults();
let p = venue("nvidia-rtx5080-laptop");
let v = compile(&bc, "rt6_fill_vertex", &p).expect("vertex");
for pf in FORMATS.into_iter().chain(SRGB) {
@@ -176,21 +173,6 @@ fn fragment_outputs_to_word_attachments_write_the_word() {
(IoNumeric::Float, 4),
"{what}"
);
let plan = plan_bitcode(
&bc,
EntryRef::Name(entry),
&consts,
&p,
&inputs,
&mut meter(),
)
.unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(
plan.estimate.words >= f.module.words.len() as u64,
"{what}: estimate {} < emitted {}",
plan.estimate.words,
f.module.words.len()
);
let g = l.graphics.as_ref().expect("graphics");
let a = g.color_attachments[0].expect("attachment");
assert_eq!(a.format, word.word_format(), "{what}");
@@ -2922,7 +2922,6 @@ field metal2vulkan::pipeline::EntryDescriptor.bitcode pub bitcode: &'a [u8]
field metal2vulkan::pipeline::EntryDescriptor.constants pub constants: FunctionConstantValues
field metal2vulkan::pipeline::EntryDescriptor.entry pub entry: EntryRef<'a>
field metal2vulkan::pipeline::EntryDescriptor.linked pub linked: Vec<LinkedSource<'a>>
field metal2vulkan::pipeline::EntryPlan.estimated_words pub estimated_words: u64
field metal2vulkan::pipeline::EntryPlan.stage pub stage: Stage
field metal2vulkan::pipeline::EntryPlan.strategies pub strategies: BTreeMap<String, StrategyUse>
field metal2vulkan::pipeline::ExtendedRangeColor.blended pub blended: bool
Can't render this file because it is too large.
-4
View File
@@ -1452,10 +1452,6 @@ fn one_entry_of_a_bare_module_translates_through_the_public_api() {
let (plan, _) = profile.plan_entry(&entry, &none, &budget);
let plan = plan.expect("plan");
assert_eq!(plan.stage, Stage::Kernel, "{stem}");
assert!(
plan.estimated_words >= alone.words.len() as u64,
"{stem}: the estimate bounds the module"
);
let specialized = profile
.specialized_entry(&entry, &none, &budget)
.expect("entry");
+4 -4
View File
@@ -19,8 +19,7 @@ metallib | AIR bitcode
── analyze ─────► MemoryPlan: provenance, one representation memory
per value, slot windows
── select ──────► Plan: a strategy per instruction and interface lower::select, lower::strategy
element, push-constant placement, requirements,
the output-size estimate (checked here)
element, push-constant placement, requirements
── structurize ─► a structured tree over the AIR CFG structurize
── emit ────────► a typed SPIR-V module through the builder structurize::emit, lower::*, spirv::builder
── tidy ────────► single-store promotion, dead values removed, structurize::promote, spirv::{dead, roll,
@@ -29,7 +28,8 @@ metallib | AIR bitcode
into loops, loop-invariant loads of uniform views
moved before their loops
── verify ──────► the full verifier; requirements within the profile spirv::verify, spirv::requirements
── serialize ───► SPIR-V 1.5 words with typed relocations spirv::serialize
── serialize ───► SPIR-V 1.5 words with typed relocations, held to spirv::serialize
the word cap
= CompiledFunction, keyed by FunctionCompileKey (the caller may cache it)
── link ────────► bindings, Locations, spec ids, the pipeline pipeline::link
layout, pipeline-wide limits, the generated pipeline::link::band
@@ -73,7 +73,7 @@ rest is `crates/metal2vulkan/src/`.
| `graph` | The shared RPO, dominator tree, loop forest and SCC |
| `budget` | `Budget`, `CancelToken`, and the per-attempt `Meter`: deadline, cancellation, work units, the byte ledger and every structural cap |
| `memory/` | Pointer provenance, the `MemoryPlan`, leaf access emitters, arenas, root and handle lookups, word composition, atomics; `memory::views`, a descriptor slot's views: a storage block or a uniform block |
| `lower/` | `select` (routing every instruction, intrinsic and parameter into the `Plan`), `strategy`, `push` (push-constant placement), `estimate` (output size), `specialized` (bound-texture values read as push data), and one module per family: `arith` (each float operation in the AIR's order, decorated by its own fast-math flags, so the device's compiler groups and fuses only what they allow; `half_chain`, a fast-math `half` chain held at `float` precision between its roundings where the device has no 16-bit floats), `access`, `texture`, `sampler`, `simd`, `sync`, `fragment`, `stage_io`, `dispatch`, `tessellation`, `mesh`, `raytracing` |
| `lower/` | `select` (routing every instruction, intrinsic and parameter into the `Plan`), `strategy`, `push` (push-constant placement), `specialized` (bound-texture values read as push data), and one module per family: `arith` (each float operation in the AIR's order, decorated by its own fast-math flags, so the device's compiler groups and fuses only what they allow; `half_chain`, a fast-math `half` chain held at `float` precision between its roundings where the device has no 16-bit floats), `access`, `texture`, `sampler`, `simd`, `sync`, `fragment`, `stage_io`, `dispatch`, `tessellation`, `mesh`, `raytracing` |
| `structurize/` | The structurizer over the AIR CFG, the emit walk that drives the families, and single-store promotion |
| `spirv/` | The typed SPIR-V IR and interners, the module and function builders, dead-value removal, the roll pass, the move of loop-invariant loads of uniform views out of their loops (`hoist`), the 16-bit holding of `half` values under the 16-bit float controls (`half_hold`), the verifier, requirement derivation and the serializer. `spirv::interp` is a CPU interpreter used only by tests |
| `spv.rs` | The SPIR-V grammar's opcodes and enumerants the translator names, generated from Khronos's grammar (`scripts/regen-spirv-grammar/`) |
+2 -2
View File
@@ -211,7 +211,7 @@ Columns:
| `InlinedInstructions` | Instructions after inlining | every device (a deterministic cap) | `ours` | 3: `crates/metal2vulkan-air/src/canon/inline.rs (inline)`, `crates/metal2vulkan-air/src/canon/inline.rs (u32_of)` (+1) | `rare`: very large shaders after inlining |
| `OutputBlocks` | Structurizer output blocks, `4(n+e)+1024` | every device (a deterministic cap) | `ours` | 4: `crates/metal2vulkan/src/structurize/irreducible.rs (round)`, `crates/metal2vulkan/src/structurize/mod.rs (structure_loops)` (+2) | `rare`: very large control flow |
| `IrreducibleDepth` | Irreducible nesting depth | every device (a deterministic cap) | `ours` | 4: `crates/metal2vulkan-air/src/graph/loops.rs (compute_in)`, `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs (check_within_depth)` (+1) | `none`: deeply nested irreducible loops |
| `SpirvWords` | Emitted SPIR-V words | every device (a deterministic cap) | `ours` | 2: `crates/metal2vulkan/src/lower/estimate.rs (check)`, `crates/metal2vulkan/src/lower/estimate.rs (check_emitted)` | `rare`: very large output modules |
| `SpirvWords` | Emitted SPIR-V words | every device (a deterministic cap) | `ours` | 1: `crates/metal2vulkan/src/pipeline/compile.rs (lower_bounded)` | `rare`: very large output modules |
| `WorkUnits` | Deterministic work units of one attempt | every device (a deterministic cap) | `ours` | 1: `crates/metal2vulkan-air/src/budget/mod.rs (counted)` | `rare`: very large shaders |
| `LedgerBytes` | Ledger bytes of one attempt | every device (a deterministic cap) | `ours` | 9: `crates/metal2vulkan-air/src/bitstream/mod.rs (count)`, `crates/metal2vulkan-air/src/budget/mod.rs (charge)` (+5) | `rare`: very large shaders |
| `TypeCount` | Types in the bitcode type table | every device (a deterministic cap) | `ours` | 2: `crates/metal2vulkan-air/src/bitcode/types.rs (decode)`, `crates/metal2vulkan-air/src/ir/types.rs (intern)` | `none`: a type table past the cap |
@@ -528,7 +528,7 @@ Each refusal's sites, with the function that builds it.
- `limit::InlinedInstructions`: `crates/metal2vulkan-air/src/canon/inline.rs (inline)`; `crates/metal2vulkan-air/src/canon/inline.rs (u32_of)`; `crates/metal2vulkan-air/src/canon/inline.rs (usize_of)`
- `limit::OutputBlocks`: `crates/metal2vulkan/src/structurize/irreducible.rs (round)`; `crates/metal2vulkan/src/structurize/mod.rs (structure_loops)`; `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs (output_cap_is_checked_before_allocating)`; `crates/metal2vulkan/src/structurize/structurizer_properties/trees.rs (the_output_cap_is_checked_before_emission)`
- `limit::IrreducibleDepth`: `crates/metal2vulkan-air/src/graph/loops.rs (compute_in)`; `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs (check_within_depth)`; `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs (irreducible_nesting_beyond_the_cap_is_refused, 2 sites)`
- `limit::SpirvWords`: `crates/metal2vulkan/src/lower/estimate.rs (check)`; `crates/metal2vulkan/src/lower/estimate.rs (check_emitted)`
- `limit::SpirvWords`: `crates/metal2vulkan/src/pipeline/compile.rs (lower_bounded)`
- `limit::WorkUnits`: `crates/metal2vulkan-air/src/budget/mod.rs (counted)`
- `limit::LedgerBytes`: `crates/metal2vulkan-air/src/bitstream/mod.rs (count)`; `crates/metal2vulkan-air/src/budget/mod.rs (charge)`; `crates/metal2vulkan-air/src/budget/mod.rs (grow, 2 sites)`; `crates/metal2vulkan-air/src/budget/mod.rs (reserve)`; `crates/metal2vulkan-air/src/budget/mod.rs (reserve_exact, 2 sites)`; `crates/metal2vulkan-air/src/graph/mod.rs (grow)`; `crates/metal2vulkan/src/spirv/verify/mod.rs (with_capacity)`
- `limit::TypeCount`: `crates/metal2vulkan-air/src/bitcode/types.rs (decode)`; `crates/metal2vulkan-air/src/ir/types.rs (intern)`