Translator: the outline pass goes; a repeated region is written in line again (SEMANTICS 2263)

What: spirv::outline (a repeated region of 500 or more instructions written once, as a kept
routine declared DontInline) is deleted with its tests, its call in the stage bound and in
pipeline::testing, its notes in weights.rs, ir::Function::kept, ModuleBuilder::kept_routine and the
serializer, docs/API.md and docs/ARCHITECTURE.md. roll's items and its spine take back their own
visibility and signature (the loop-body sequences only the outline search read). The
bounded-growth test's chain is all one group again: no pass now folds a repeated graph.
cache::SEMANTICS_VERSION 2262 to 2263. The sampling and texel routines stay kept routines,
DontInline as before.

Why: a regression on NVIDIA. Job m3-max-64837 (RTX 2080, 620.70.06, um790, exclusive) made k7
(610e4b3d of the Iris capture's library, weight 320,401) cold through the runtime's helper, arms
A db5fefc2ce (before the pass), B 71014cd7bc's product (the pass in), C 36ed0d15b2, alternated
A B C A B C. The helper's CPU time and peak resident set (VmHWM):
- A: 37.74 s, 1,749 MiB; 37.90 s, 1,750 MiB.
- B: 85.82 s, 2,040 MiB; 87.44 s, 2,041 MiB (10 kept routines; largest function 195,769
  instructions against A's 336,129).
- C: 87.35 s, 2,049 MiB.
B is 2.3 times A's CPU and 16.6% more memory. The pass's only gain on file was synthetic (one
function called from 50 places, m3-max-64453). RADV and ANV cannot gain from it: Mesa 26.2.6
inlines every function before either backend sees the shader, RADV in radv_shader_spirv_to_nir
(src/amd/vulkan/radv_shader.c:574, nir_inline_functions) and ANV through the common runtime
(src/intel/vulkan/anv_device.c:792 sets the shader ops; src/vulkan/runtime/vk_pipeline.c:211 calls
vk_spirv_to_nir, whose src/vulkan/runtime/vk_nir.c:176 runs nir_inline_functions).

Verified: the compile job of this commit and a states-only play of nine streams against
development follow; the golden table and the render key are re-blessed at the pin.
This commit is contained in:
Anees Iqbal committed 2026-11-21 13:15:45 -08:00
1 parent 16d3037930
commit b20dc87d22
14 files changed
+50 -2336

No files matched your search

+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 = 2262;
pub const SEMANTICS_VERSION: u32 = 2263;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -8,8 +8,7 @@
//!
//! Every module's entry is weighed (`spirv::roll::entry_weight`: the entry's instructions with each
//! call counted as its callee's body, as the driver inlines every call) after the repeated regions
//! are rolled and written as kept routines (`spirv::outline`), and the weight is the module's
//! ([`ModuleStats::entry_weight`]). A kernel past the
//! are rolled, and the weight is the module's ([`ModuleStats::entry_weight`]). A kernel past the
//! bound that took the `Emulated` simdgroup tier only in place of the `Direct` tier's pin to the
//! device's widest mode (`lower::simd::widest_pin`) is planned again keeping the pin
//! (`lower::simd::WidestPin::Kept`), its emulated module dropped and what its plan and emission
@@ -86,11 +85,6 @@ pub(super) fn emit(
m.weighted(crate::pipeline::compile::weights::HOIST, |m| {
crate::spirv::hoist::hoist_uniform_loads(&mut emitted.module, p.robustness(), m)
})?;
// A driver that keeps a routine compiles it once: repeated regions are written once, as
// kept routines.
m.weighted(crate::pipeline::compile::weights::ROLL, |m| {
crate::spirv::outline::outline_entry(&mut emitted.module, m)
})?;
let weight = crate::spirv::roll::entry_weight(&emitted.module, m)?;
if weight <= bounds.compiled || widest == WidestPin::Kept || !plan.families.simd.widest_pin
{
@@ -39,9 +39,7 @@ pub(crate) const SELECT: u32 = 6;
pub(crate) const STRUCTURIZE: u32 = 5;
/// Emission ([`emit_module`](crate::lower::emit::emit_module)), the structurizer inside it aside.
pub(crate) const EMIT: u32 = 9;
/// Rolling repeated regions ([`roll_entry`](crate::spirv::roll::roll_entry)), and writing them as
/// kept routines ([`outline_entry`](crate::spirv::outline::outline_entry)): the same spine, keys
/// and exact comparisons, so rolling's weight (the routines' work is not measured apart).
/// Rolling repeated regions ([`roll_entry`](crate::spirv::roll::roll_entry)).
pub(crate) const ROLL: u32 = 1;
/// Hoisting uniform loads ([`hoist_uniform_loads`](crate::spirv::hoist::hoist_uniform_loads)).
pub(crate) const HOIST: u32 = 2;
@@ -414,7 +414,6 @@ fn typed_module_of(
crate::lower::emit::emit_module(&spec, &plan, m)?;
crate::spirv::roll::roll_entry(&mut module, m)?;
crate::spirv::hoist::hoist_uniform_loads(&mut module, p.robustness(), m)?;
crate::spirv::outline::outline_entry(&mut module, m)?;
crate::spirv::verify::verify(&module, p, m)?;
Ok((plan, module))
}
@@ -993,8 +993,7 @@ impl ModuleBuilder {
/// every site that needs it, declared `DontInline` (`OpFunction`'s function control) on every
/// serialization (`crate::spirv::serialize::serialize`), the standard SPIR-V statement that its
/// calls stay calls. A linear filter emulation's sum (a texel routine) and one combined
/// binding's sample emulation (a sampling routine) are kept routines, as is a region a function
/// holds more than once, which `spirv::outline` writes in this form. A driver that honours the
/// binding's sample emulation (a sampling routine) are kept routines. A driver that honours the
/// control (NVIDIA's) compiles it once where it would otherwise compile it again inside every
/// sample that calls it, which made a fragment of a few hundred emulated samples take tens of
/// seconds to create on an RTX 3090; one that inlines every function (Mesa's) ignores it. Its
+3 -3
View File
@@ -1206,9 +1206,9 @@ pub struct Function {
/// `Function`-storage variables, declared at the top of the entry block.
pub vars: Vec<VarId>,
/// Whether the function is a kept routine (`ModuleBuilder::kept_routine`): a linear filter
/// emulation's sum, one combined binding's sample emulation, or a region the function held
/// more than once (`spirv::outline`), which `serialize` declares `DontInline`, so a driver that
/// honours the control compiles it once and calls it from each site.
/// emulation's sum or one combined binding's sample emulation, which `serialize` declares
/// `DontInline`, so a driver that honours the control compiles it once and calls it from each
/// site.
pub kept: bool,
}
-1
View File
@@ -14,7 +14,6 @@ pub mod ids;
#[cfg(test)]
pub mod interp;
pub mod ir;
pub mod outline;
pub mod requirements;
pub mod roll;
pub mod serialize;
File diff suppressed because it is too large. Load diff
@@ -1,539 +0,0 @@
//! A set of regions written as a kept routine computes what the regions computed, a region that
//! differs stays in line, and a variable whose value carries from one run of its region to the next
//! is passed to the routine, not made its own. One search takes every repeat of a region, however
//! many.
use super::*;
use crate::budget::Budget;
use crate::device::profile::DeviceProfile;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::spirv::builder::constructs::{ArmEnd, LoopSpec};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::GlobalId;
use crate::spirv::interp::{run, Buffer, Config, Resources};
use crate::spirv::ir::{natural_layout, BinOp, ExecMode, ExecModel, LayoutRule, MemAccess};
use crate::spirv::testing::{assert_valid, committed_profiles};
fn meter() -> Meter {
Meter::new(&Budget::default())
}
fn u32_ty(b: &mut ModuleBuilder) -> TypeId {
b.ty(Type::Int {
width: 32,
signed: false,
})
.expect("u32")
}
fn c32(f: &mut FunctionBuilder<'_>, v: u32) -> Value {
let c = f.u32_const(v).expect("constant");
f.module().const_value(c).expect("value")
}
fn slot(kind: ResourceKind, index: u32) -> ResourceSlot {
ResourceSlot {
stage: Stage::Kernel,
kind,
index,
}
}
/// A `Block { u32 data[]; }` storage buffer at buffer slot `index`.
fn buffer(b: &mut ModuleBuilder, index: u32) -> GlobalId {
let u32_ = u32_ty(b);
let rta = b
.ty(Type::RuntimeArray {
elem: u32_,
stride: Some(4),
})
.expect("runtime array");
let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta]).expect("layout");
let block = b
.ty(Type::Struct {
members: [rta].into(),
layout: Some(layout),
})
.expect("block");
b.resource(
slot(ResourceKind::Buffer, index),
StorageClass::StorageBuffer,
block,
)
.expect("resource")
}
fn elem(f: &mut FunctionBuilder<'_>, buf: GlobalId, i: Value) -> BResult<Value> {
let zero = c32(f, 0);
let base = f.module().global_value(buf)?;
f.access_chain(base, &[zero, i])
}
fn load_at(f: &mut FunctionBuilder<'_>, buf: GlobalId, i: u32) -> BResult<Value> {
let i = c32(f, i);
let p = elem(f, buf, i)?;
f.load(p, MemAccess::default())
}
fn store_at(f: &mut FunctionBuilder<'_>, buf: GlobalId, i: Value, v: Value) -> BResult<()> {
let p = elem(f, buf, i)?;
f.store(p, v, MemAccess::default())
}
fn words(bytes: &[u8]) -> Vec<u32> {
bytes
.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
.collect()
}
fn resources(input: &[u32], out_words: usize) -> Resources {
Resources {
buffers: vec![
Buffer {
slot: Some(slot(ResourceKind::Buffer, 0)),
address: None,
bytes: input.iter().flat_map(|w| w.to_le_bytes()).collect(),
},
Buffer {
slot: Some(slot(ResourceKind::Buffer, 1)),
address: None,
bytes: vec![0; out_words * 4],
},
],
push: Vec::new(),
spec: Default::default(),
}
}
fn moltenvk() -> DeviceProfile {
committed_profiles()
.expect("profiles")
.into_iter()
.find(|(s, _)| s == "moltenvk-m3")
.expect("moltenvk-m3")
.1
}
/// The eight operations of a region's chain, its fourth `fourth`.
fn chain(fourth: BinOp) -> [(BinOp, u32); 8] {
[
(BinOp::IMul, 3),
(BinOp::BitwiseXor, 5),
(BinOp::IAdd, 7),
(fourth, 11),
(BinOp::BitwiseXor, 13),
(BinOp::IAdd, 17),
(BinOp::IMul, 19),
(BinOp::BitwiseXor, 23),
]
}
/// [`chain`] computed on `x`.
fn apply_chain(x: u32, fourth: BinOp) -> u32 {
chain(fourth).iter().fold(x, |p, (op, k)| match op {
BinOp::IMul => p.wrapping_mul(*k),
BinOp::BitwiseXor => p ^ k,
BinOp::IAdd => p.wrapping_add(*k),
BinOp::ISub => p.wrapping_sub(*k),
_ => panic!("no such chain operation"),
})
}
/// Region `j`: `x = seed + 10 (j + 1) + dep` through a variable, [`chain`] on `x` (`p`), `y = x >
/// 25 ? 2 x : x + 1` through a selection's phi, a loop counting a variable initialized to 0 up to
/// 3, and `out[base + 2 + j] = y + count + p`. Returns `y`.
fn region(
f: &mut FunctionBuilder<'_>,
out: GlobalId,
(seed, base, dep): (Value, Value, Value),
j: u32,
fourth: BinOp,
) -> BResult<Value> {
let u32_ = u32_ty(f.module());
let v = f.local_var(u32_, None)?;
let vp = f.var_ptr(v)?;
let add = c32(f, 10 * (j + 1));
let x0 = f.binary(BinOp::IAdd, seed, add)?;
let x0 = f.binary(BinOp::IAdd, x0, dep)?;
f.store(vp, x0, MemAccess::default())?;
let x = f.load(vp, MemAccess::default())?;
let mut p = x;
for (op, k) in chain(fourth) {
let k = c32(f, k);
p = f.binary(op, p, k)?;
}
let c25 = c32(f, 25);
let big = f.binary(BinOp::UGreaterThan, x, c25)?;
let y = f.if_(
&mut (),
big,
Box::new(move |f, _| {
let two = c32(f, 2);
Ok(ArmEnd::FallThrough(vec![f.binary(BinOp::IMul, x, two)?]))
}),
Some(Box::new(move |f, _| {
let one = c32(f, 1);
Ok(ArmEnd::FallThrough(vec![f.binary(BinOp::IAdd, x, one)?]))
})),
)?;
let y = *y.0.first().expect("phi");
let zero = f.u32_const(0)?;
let cnt = f.local_var(u32_, Some(zero))?;
let cp = f.var_ptr(cnt)?;
f.loop_(
&mut (),
LoopSpec::default(),
Box::new(move |f, _, lc| {
let c = f.load(cp, MemAccess::default())?;
let three = c32(f, 3);
let done = f.binary(BinOp::UGreaterThanEqual, c, three)?;
f.if_(
&mut (),
done,
Box::new(|f, _| {
lc.break_(f)?;
Ok(ArmEnd::Exits)
}),
None,
)?;
let one = c32(f, 1);
let c1 = f.binary(BinOp::IAdd, c, one)?;
f.store(cp, c1, MemAccess::default())
}),
)?;
let n = f.load(cp, MemAccess::default())?;
let r = f.binary(BinOp::IAdd, y, n)?;
let r = f.binary(BinOp::IAdd, r, p)?;
let at = c32(f, 2 + j);
let idx = f.binary(BinOp::IAdd, base, at)?;
store_at(f, out, idx, r)?;
Ok(y)
}
/// One [`region`] after another, region `j`'s chain's fourth operation `fourths[j]`, reading `in =
/// [seed, base, seed2]` and writing `out`; then `out[0] = y + 100` of the last region. With
/// `cross`, each region but the first adds the previous region's `y` where the first adds `seed2`.
fn kernel(fourths: &[BinOp], cross: bool) -> TypedModule {
let mut b = ModuleBuilder::new();
let input = buffer(&mut b, 0);
let out = buffer(&mut b, 1);
let void = b.ty(Type::Void).expect("void");
let mut f = b.function(void).expect("function");
let body = |f: &mut FunctionBuilder<'_>| -> BResult<()> {
let seed = load_at(f, input, 0)?;
let base = load_at(f, input, 1)?;
let seed2 = load_at(f, input, 2)?;
let mut y = seed2;
for (j, fourth) in fourths.iter().enumerate() {
let dep = if cross && j > 0 { y } else { seed2 };
y = region(f, out, (seed, base, dep), j as u32, *fourth)?;
}
let c100 = c32(f, 100);
let z = f.binary(BinOp::IAdd, y, c100)?;
let zero = c32(f, 0);
store_at(f, out, zero, z)?;
f.ret(None)
};
body(&mut f).expect("body");
let main = f.finish().expect("finish");
b.entry(
ExecModel::GLCompute,
main,
vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }],
)
.expect("entry");
b.finalize().expect("finalize")
}
/// The words [`kernel`] writes, `base` 0.
fn expected(fourths: &[BinOp], cross: bool, seed: u32, seed2: u32) -> Vec<u32> {
let mut out = vec![0u32; 2 + fourths.len()];
let mut y = seed2;
for (j, fourth) in fourths.iter().enumerate() {
let dep = if cross && j > 0 { y } else { seed2 };
let x = seed.wrapping_add(10 * (j as u32 + 1)).wrapping_add(dep);
let p = apply_chain(x, *fourth);
y = if x > 25 {
x.wrapping_mul(2)
} else {
x.wrapping_add(1)
};
out[2 + j] = y.wrapping_add(3).wrapping_add(p);
}
out[0] = y.wrapping_add(100);
out
}
/// Each kept routine of `m`, with the calls of it in the entry.
fn routines(m: &TypedModule) -> Vec<(FuncId, usize)> {
let entry = &m.functions()[m.entry().func.index()];
let mut out = Vec::new();
for (i, f) in m.functions().iter().enumerate() {
if !f.kept {
continue;
}
let id = FuncId::new(i as u32);
let calls = entry
.blocks
.iter()
.flat_map(|b| &m.blocks()[b.index()].insts)
.filter(|n| matches!(n.inst, Inst::Call { func, .. } if func == id))
.count();
out.push((id, calls));
}
out
}
/// The `OpFunction`s (opcode 54) of a module's words whose control is `DontInline`.
fn dont_inline(words: &[u32]) -> usize {
let mut out = 0;
let mut at = 5;
while at < words.len() {
let (count, op) = ((words[at] >> 16) as usize, words[at] & 0xFFFF);
if op == 54 && words[at + 3] & 0x2 != 0 {
out += 1;
}
at += count.max(1);
}
out
}
/// Run `before` and `after` over `input` and check both write `want`.
fn same_words(before: &TypedModule, after: &TypedModule, input: &[u32], want: &[u32]) {
let n = want.len();
let a = run(before, &Config::default(), resources(input, n)).expect("run in line");
let b = run(after, &Config::default(), resources(input, n)).expect("run as calls");
assert_eq!(words(&a.buffers[1]), want, "in line, input {input:?}");
assert_eq!(words(&b.buffers[1]), want, "as calls, input {input:?}");
}
/// Three regions that are the same code but their constants, each with its own variables (one
/// with an initializer), a selection merging a value by phi and a counting loop, become calls of
/// one kept routine, which takes their selection and loop; the last region's `y`, read after it,
/// is the routine's result. The module is valid, declares the routine `DontInline`, and writes
/// what the regions wrote, for inputs on both sides of the selection. Each region is under the
/// size measured to run no slower as a routine, so the pass as compiles run it leaves them.
#[test]
fn three_equal_regions_become_calls_of_one_kept_routine_that_computes_the_same() {
let fourths = [BinOp::IMul; 3];
let orig = kernel(&fourths, false);
let mut kept = orig.clone();
assert_eq!(outline_entry(&mut kept, &mut meter()).expect("outline"), 0);
let mut m = orig.clone();
assert_eq!(outline(&mut m, 1, &mut meter()).expect("outline"), 1);
assert_eq!(routines(&m), [(FuncId::new(1), 3)]);
let routine = &m.functions()[1];
assert_eq!(routine.vars.len(), 2, "the region's two variables");
assert_eq!(orig.loops().len(), 3);
assert_eq!(m.loops().len(), 1, "the routine's loop");
let spirv = assert_valid(m.clone(), &moltenvk());
assert_eq!(dont_inline(&spirv), 1);
for (seed, seed2) in [(1u32, 2u32), (20, 0), (0, 0), (7, 30)] {
let want = expected(&fourths, false, seed, seed2);
same_words(&orig, &m, &[seed, 0, seed2], &want);
}
// Nothing is left to write as a routine.
assert_eq!(outline(&mut m, 1, &mut meter()).expect("outline again"), 0);
}
/// A chain: each region but the first reads the previous region's `y` where the first reads
/// `seed2`. Every region's `y` is the routine's result, and each call after the first is passed
/// the call before's.
#[test]
fn a_chain_of_regions_passes_each_call_the_result_of_the_one_before() {
let fourths = [BinOp::IMul; 3];
let orig = kernel(&fourths, true);
let mut m = orig.clone();
assert_eq!(outline(&mut m, 1, &mut meter()).expect("outline"), 1);
assert_eq!(routines(&m), [(FuncId::new(1), 3)]);
assert_valid(m.clone(), &moltenvk());
for (seed, seed2) in [(3u32, 4u32), (20, 0), (0, 0), (1, 30)] {
let want = expected(&fourths, true, seed, seed2);
same_words(&orig, &m, &[seed, 0, seed2], &want);
}
}
/// Of three regions, the middle one's chain subtracts where the others' multiply: the first and
/// last become calls (their keys agree one item past the first region's end, where the next
/// region's first addition reads a value from before it and the kernel's last reads the last
/// region's `y`, so the set is compared again without that item), and the middle one stays in
/// line. Two regions that differ so become nothing.
#[test]
fn a_region_that_differs_stays_in_line_beside_the_calls_of_the_equal_ones() {
let fourths = [BinOp::IMul, BinOp::ISub, BinOp::IMul];
let orig = kernel(&fourths, false);
let mut m = orig.clone();
assert_eq!(outline(&mut m, 1, &mut meter()).expect("outline"), 1);
assert_eq!(routines(&m), [(FuncId::new(1), 2)]);
assert_eq!(
m.loops().len(),
2,
"the routine's loop and the middle region's"
);
assert_valid(m.clone(), &moltenvk());
for (seed, seed2) in [(1u32, 2u32), (20, 0), (7, 30)] {
let want = expected(&fourths, false, seed, seed2);
same_words(&orig, &m, &[seed, 0, seed2], &want);
}
let mut two = kernel(&[BinOp::IMul, BinOp::ISub], false);
assert_eq!(outline(&mut two, 1, &mut meter()).expect("outline"), 0);
}
/// Eighty equal regions, more repeats than a window's extents are tried against: the first search
/// takes all eighty as one set, where a search that took only the repeats it tried would leave the
/// rest for another search and another routine of the same code (a function of many repeats
/// searched once per few dozen of them). Written so, the module is valid and writes what the
/// regions wrote. (The eighty calls are then equal items themselves, so with regions this small
/// a later search may write runs of them as a routine too.)
#[test]
fn one_search_takes_every_repeat_of_a_region_past_the_repeats_it_extends_against() {
let fourths = [BinOp::IMul; 80];
let orig = kernel(&fourths, false);
let mut cache = KeyCache::default();
let mut settled = vec![false; orig.functions().len()];
let mut ledger = 0usize;
let plan = find(
&orig,
1,
(&mut cache, settled.as_mut_slice()),
&mut meter(),
&mut ledger,
)
.expect("find")
.expect("a set");
assert_eq!(plan.occ.len(), 80);
let mut m = orig.clone();
assert!(outline(&mut m, 1, &mut meter()).expect("outline") >= 1);
assert_valid(m.clone(), &moltenvk());
for (seed, seed2) in [(1u32, 2u32), (20, 0)] {
let want = expected(&fourths, false, seed, seed2);
same_words(&orig, &m, &[seed, 0, seed2], &want);
}
}
/// Region `j` of the looped kernel: `a = acc`, `t = a * 5` through a variable it stores first,
/// [`chain`] on `t` (`p`), `acc = a + p`, and `out[2 + j] = acc`.
fn looped_region(f: &mut FunctionBuilder<'_>, out: GlobalId, acc: VarId, j: u32) -> BResult<()> {
let u32_ = u32_ty(f.module());
let ap = f.var_ptr(acc)?;
let a = f.load(ap, MemAccess::default())?;
let tmp = f.local_var(u32_, None)?;
let tp = f.var_ptr(tmp)?;
let five = c32(f, 5);
let t0 = f.binary(BinOp::IMul, a, five)?;
f.store(tp, t0, MemAccess::default())?;
let t = f.load(tp, MemAccess::default())?;
let mut p = t;
for (op, k) in chain(BinOp::IMul) {
let k = c32(f, k);
p = f.binary(op, p, k)?;
}
let s = f.binary(BinOp::IAdd, a, p)?;
f.store(ap, s, MemAccess::default())?;
let at = c32(f, 2 + j);
store_at(f, out, at, s)
}
/// A loop of four trips running `k` [`looped_region`]s one after another, region `j` on its own
/// accumulator, a variable initialized to `j`.
fn looped_kernel(k: u32) -> TypedModule {
let mut b = ModuleBuilder::new();
let input = buffer(&mut b, 0);
let out = buffer(&mut b, 1);
let void = b.ty(Type::Void).expect("void");
let mut f = b.function(void).expect("function");
let body = |f: &mut FunctionBuilder<'_>| -> BResult<()> {
let u32_ = u32_ty(f.module());
let first = load_at(f, input, 0)?;
let mut accs = Vec::new();
for j in 0..k {
let c = f.u32_const(j)?;
accs.push(f.local_var(u32_, Some(c))?);
}
let zero = f.u32_const(0)?;
let it = f.local_var(u32_, Some(zero))?;
let ip = f.var_ptr(it)?;
f.loop_(
&mut (),
LoopSpec::default(),
Box::new(move |f, _, lc| {
let c = f.load(ip, MemAccess::default())?;
let four = c32(f, 4);
let done = f.binary(BinOp::UGreaterThanEqual, c, four)?;
f.if_(
&mut (),
done,
Box::new(|f, _| {
lc.break_(f)?;
Ok(ArmEnd::Exits)
}),
None,
)?;
for (j, acc) in accs.iter().enumerate() {
looped_region(f, out, *acc, j as u32)?;
}
let one = c32(f, 1);
let c1 = f.binary(BinOp::IAdd, c, one)?;
f.store(ip, c1, MemAccess::default())
}),
)?;
let zero = c32(f, 0);
store_at(f, out, zero, first)?;
f.ret(None)
};
body(&mut f).expect("body");
let main = f.finish().expect("finish");
b.entry(
ExecModel::GLCompute,
main,
vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }],
)
.expect("entry");
b.finalize().expect("finalize")
}
/// The words [`looped_kernel`] writes for `in[0] = first`.
fn looped_expected(k: u32, first: u32) -> Vec<u32> {
let mut out = vec![0u32; 2 + k as usize];
let mut accs: Vec<u32> = (0..k).collect();
for _ in 0..4 {
for (j, acc) in accs.iter_mut().enumerate() {
let a = *acc;
*acc = a.wrapping_add(apply_chain(a.wrapping_mul(5), BinOp::IMul));
out[2 + j] = *acc;
}
}
out[0] = first;
out
}
/// Two regions in a loop, each on its own accumulator: the accumulator, read before it is written,
/// carries its value from one trip to the next, so the routine is passed it as a pointer; the
/// variable each region stores before it reads it becomes the routine's own. Both regions are
/// one block each, and the module writes what they wrote.
#[test]
fn a_variable_read_before_it_is_written_in_a_loop_is_passed_to_the_routine() {
let orig = looped_kernel(2);
let mut m = orig.clone();
assert_eq!(outline(&mut m, 1, &mut meter()).expect("outline"), 1);
assert_eq!(routines(&m), [(FuncId::new(1), 2)]);
let routine = &m.functions()[1];
assert_eq!(routine.vars.len(), 1, "the variable stored first");
let pointers = routine
.params
.iter()
.filter(|p| {
let t = m.value(**p).expect("parameter").ty;
matches!(m.types().get(t).expect("type"), Type::Pointer { .. })
})
.count();
assert_eq!(pointers, 1, "the accumulator");
assert_valid(m.clone(), &moltenvk());
for first in [0u32, 9] {
same_words(&orig, &m, &[first], &looped_expected(2, first));
}
}
+34 -70
View File
@@ -115,7 +115,7 @@ const MAX_PAIRS: usize = 8;
/// The exact comparisons per search.
const MAX_VERIFIES: usize = 32;
/// [`Item::inst`] of a construct (or the spine's end).
pub(in crate::spirv) const TAIL: u32 = u32::MAX;
const TAIL: u32 = u32::MAX;
/// The most functions searched per run: the heaviest the entry reaches.
const MAX_FUNCS: usize = 8;
/// The deepest arm searched: a sequence inside this many selections and switches.
@@ -124,8 +124,8 @@ const MAX_DEPTH: u32 = 8;
/// The pass's maps and sets of ids, hashed by [`Fnv`]'s word mix rather than SipHash: their keys
/// are the module's own dense ids, and no output depends on their order (each one the pass walks
/// is sorted first, or only read by key).
pub(in crate::spirv) type HashMap<K, V> = std::collections::HashMap<K, V, BuildHasherDefault<Fnv>>;
pub(in crate::spirv) type HashSet<K> = std::collections::HashSet<K, BuildHasherDefault<Fnv>>;
type HashMap<K, V> = std::collections::HashMap<K, V, BuildHasherDefault<Fnv>>;
type HashSet<K> = std::collections::HashSet<K, BuildHasherDefault<Fnv>>;
fn invariant(detail: impl Into<String>) -> Error {
Error::Internal(InternalError::new(InternalKind::Invariant, detail))
@@ -188,21 +188,16 @@ const UNKEYED: u64 = u64::MAX;
/// first region's read turns into a copy of the trip's lane, and a copy's key is never read
/// (every reader skips copies). Everything else the roll writes takes a new result.
#[derive(Default)]
pub(in crate::spirv) struct KeyCache {
struct KeyCache {
/// By value: its instruction's key, or [`UNKEYED`].
keys: Vec<u64>,
/// The bytes charged for `keys`.
pub(in crate::spirv) charged: usize,
charged: usize,
}
impl KeyCache {
/// The key of `node`, kept or taken now.
pub(in crate::spirv) fn key(
&mut self,
m: &TypedModule,
node: &InstNode,
meter: &mut Meter,
) -> Result<u64, Error> {
fn key(&mut self, m: &TypedModule, node: &InstNode, meter: &mut Meter) -> Result<u64, Error> {
let Some(r) = node.result else {
return inst_key(m, node);
};
@@ -238,7 +233,7 @@ pub fn entry_weight(m: &TypedModule, meter: &mut Meter) -> Result<u64, Error> {
}
/// [`entry_weight`] of every function.
pub(in crate::spirv) fn weights(m: &TypedModule, meter: &mut Meter) -> Result<Vec<u64>, Error> {
fn weights(m: &TypedModule, meter: &mut Meter) -> Result<Vec<u64>, Error> {
let n = m.functions.len();
let mut w = vec![0u64; n];
// 0: not reached, 1: callees pending, 2: weighed.
@@ -323,7 +318,7 @@ fn inst_weight(node: &InstNode, w: &[u64]) -> u64 {
/// of is mixed in whole (a multiply and a shift, each a bijection of the state), where a byte-wise
/// FNV-1a took a multiply per byte. Keys are only compared for equality, never ordered, so the
/// hash function decides nothing but which keys collide.
pub(in crate::spirv) struct Fnv(u64);
struct Fnv(u64);
impl Default for Fnv {
fn default() -> Fnv {
@@ -405,22 +400,22 @@ impl Hasher for Fnv {
/// An item of the spine: instruction `inst` of spine block `spine`, or ([`TAIL`]) the construct
/// that block heads, its merge's phis included, or the spine's end.
#[derive(Clone, Copy, Debug)]
pub(in crate::spirv) struct Item {
pub(in crate::spirv) spine: u32,
pub(in crate::spirv) inst: u32,
pub(in crate::spirv) key: u64,
pub(in crate::spirv) weight: u64,
struct Item {
spine: u32,
inst: u32,
key: u64,
weight: u64,
}
/// The entry's top-level code (see the module docs).
pub(in crate::spirv) struct Spine {
struct Spine {
/// The layout position of each module block in the entry (`u32::MAX`: another function's).
pub(in crate::spirv) pos: Vec<u32>,
pos: Vec<u32>,
/// The entry's blocks in layout order.
pub(in crate::spirv) layout: Vec<BlockId>,
layout: Vec<BlockId>,
/// The spine's blocks, in order.
pub(in crate::spirv) blocks: Vec<BlockId>,
pub(in crate::spirv) items: Vec<Item>,
blocks: Vec<BlockId>,
items: Vec<Item>,
/// By layout position, each instruction's [`inst_key`] (0 for a copy, which no key reads),
/// taken once: an item's key, a construct's (which combines its instructions'), and the
/// alignment of two regions read it.
@@ -428,7 +423,7 @@ pub(in crate::spirv) struct Spine {
}
impl Spine {
pub(in crate::spirv) fn pos(&self, b: BlockId) -> Option<usize> {
fn pos(&self, b: BlockId) -> Option<usize> {
self.pos
.get(b.index())
.copied()
@@ -444,21 +439,17 @@ impl Spine {
}
}
pub(in crate::spirv) fn block(m: &TypedModule, b: BlockId) -> Result<&Block, Error> {
fn block(m: &TypedModule, b: BlockId) -> Result<&Block, Error> {
m.blocks.get(b.index()).ok_or_else(|| invariant("block"))
}
pub(in crate::spirv) fn block_mut(m: &mut TypedModule, b: BlockId) -> Result<&mut Block, Error> {
fn block_mut(m: &mut TypedModule, b: BlockId) -> Result<&mut Block, Error> {
m.blocks
.get_mut(b.index())
.ok_or_else(|| invariant("block"))
}
pub(in crate::spirv) fn charge<T>(
meter: &mut Meter,
ledger: &mut usize,
n: usize,
) -> Result<(), Error> {
fn charge<T>(meter: &mut Meter, ledger: &mut usize, n: usize) -> Result<(), Error> {
let bytes = n.saturating_mul(std::mem::size_of::<T>());
meter.charge(bytes)?;
*ledger = ledger.saturating_add(bytes);
@@ -548,12 +539,11 @@ fn fixed(m: &TypedModule, sp: &Spine, lo: usize, inv: &HashSet<Value>, v: Value)
}
/// The entry's spine: its top-level sequence, then the arms of its selections and switches,
/// each a sequence of its own, to [`MAX_DEPTH`] constructs deep, and with `loops` the body of
/// each loop too (from its header's branch to its continue block). Each sequence ends in an item
/// each a sequence of its own, to [`MAX_DEPTH`] constructs deep. Each sequence ends in an item
/// whose key no other item has, so no run crosses from one into another.
pub(in crate::spirv) fn spine(
fn spine(
m: &TypedModule,
(func, w, loops): (FuncId, &[u64], bool),
(func, w): (FuncId, &[u64]),
cache: &mut KeyCache,
meter: &mut Meter,
ledger: &mut usize,
@@ -707,24 +697,6 @@ pub(in crate::spirv) fn spine(
key: h.finish(),
weight,
});
// A loop's body is a sequence of its own, where asked: from its header's branch to
// its continue block.
if loops && depth < MAX_DEPTH {
if let (None, Terminator::Branch(h)) = (&b.merge, &b.term) {
let hb = block(m, *h)?;
if let (Some(Merge::Loop { cont, .. }), Terminator::Branch(first)) =
(hb.merge, &hb.term)
{
let hi = sp.pos(cont).unwrap_or(0);
if let Some(fp) = sp.pos(*first).filter(|p| *p > lp + 1 && *p < hi) {
if let Some(x) = begun.get_mut(fp).filter(|x| !**x) {
*x = true;
seqs.push((*first, hi, depth + 1));
}
}
}
}
}
// The arms of a selection or switch are sequences of their own.
if depth < MAX_DEPTH && matches!(b.merge, Some(Merge::Selection { .. })) {
let mut arms = Vec::new();
@@ -835,7 +807,7 @@ fn find_in(
ledger: &mut usize,
verifies: &mut usize,
) -> Result<Option<Plan>, Error> {
let sp = spine(m, (func, w, false), cache, meter, ledger)?;
let sp = spine(m, (func, w), cache, meter, ledger)?;
let n = sp.items.len();
// What each value of the function is through its copies.
charge::<u32>(meter, ledger, m.values.len())?;
@@ -1171,7 +1143,7 @@ fn region_insts(b: &Block, range: Range<usize>) -> Vec<(usize, &InstNode)> {
/// Whether a value may differ by trip in operand `operand` of `inst`: an operand any value of
/// its type may stand in.
pub(in crate::spirv) fn varying_ok(inst: &Inst, operand: usize) -> bool {
fn varying_ok(inst: &Inst, operand: usize) -> bool {
match inst {
Inst::Store { .. } => operand == 1,
Inst::Unary { .. }
@@ -1197,7 +1169,7 @@ pub(in crate::spirv) fn varying_ok(inst: &Inst, operand: usize) -> bool {
/// Whether a region may hold `inst`: an instruction the stage executes at most once (interlock,
/// mesh output counts) may not be repeated by a loop.
pub(in crate::spirv) fn rollable(inst: &Inst) -> bool {
fn rollable(inst: &Inst) -> bool {
!matches!(
inst,
Inst::BeginInterlock | Inst::EndInterlock | Inst::SetMeshOutputs { .. }
@@ -1218,7 +1190,7 @@ fn image_use(inst: &Inst) -> bool {
/// The operand of `inst` (in [`Inst::for_each_value`] order) that must be a constant but may
/// differ by trip through an `OpSwitch` on the trip index ([`split_by_trip`]): an image
/// instruction's `ConstOffset`.
pub(in crate::spirv) fn switched_operand(inst: &Inst) -> Option<usize> {
fn switched_operand(inst: &Inst) -> Option<usize> {
let (lead, ops) = match inst {
Inst::ImageSample { dref, ops, .. } => (2 + usize::from(dref.is_some()), ops),
Inst::ImageFetch { ops, .. } | Inst::ImageGather { ops, .. } => (2, ops),
@@ -2201,7 +2173,7 @@ fn verify(
}
/// Intern type `t`, declaring it when new.
pub(in crate::spirv) fn ty(m: &mut TypedModule, t: Type) -> Result<TypeId, Error> {
fn ty(m: &mut TypedModule, t: Type) -> Result<TypeId, Error> {
let (id, fresh) = m.types.intern(t, &m.consts)?;
if fresh {
m.decls.push(Decl::Type(id));
@@ -2209,11 +2181,7 @@ pub(in crate::spirv) fn ty(m: &mut TypedModule, t: Type) -> Result<TypeId, Error
Ok(id)
}
pub(in crate::spirv) fn new_value(
m: &mut TypedModule,
ty: TypeId,
origin: ValueOrigin,
) -> Result<Value, Error> {
fn new_value(m: &mut TypedModule, ty: TypeId, origin: ValueOrigin) -> Result<Value, Error> {
let v = Value::new(u32::try_from(m.values.len()).map_err(|_| invariant("value ids"))?);
m.values.push(ValueDef { ty, origin });
Ok(v)
@@ -2266,7 +2234,7 @@ fn local(m: &mut TypedModule, entry: FuncId, pointee: TypeId) -> Result<Value, E
Ok(value)
}
pub(in crate::spirv) fn new_block(m: &mut TypedModule, func: FuncId) -> Result<BlockId, Error> {
fn new_block(m: &mut TypedModule, func: FuncId) -> Result<BlockId, Error> {
let id = BlockId::new(u32::try_from(m.blocks.len()).map_err(|_| invariant("block ids"))?);
m.blocks.push(Block {
func,
@@ -2294,7 +2262,7 @@ fn push_void(m: &mut TypedModule, b: BlockId, inst: Inst) -> Result<(), Error> {
}
/// Mark `results` (of instructions and phis that left their block) removed.
pub(in crate::spirv) fn removed(m: &mut TypedModule, results: impl Iterator<Item = Value>) {
fn removed(m: &mut TypedModule, results: impl Iterator<Item = Value>) {
for r in results {
if let Some(d) = m.values.get_mut(r.index()) {
d.origin = ValueOrigin::Removed;
@@ -2304,11 +2272,7 @@ pub(in crate::spirv) fn removed(m: &mut TypedModule, results: impl Iterator<Item
/// Move the merge and terminator of `from` to `to` (a new block that takes over `from`'s
/// edges): the successors' phis, a loop's preheader, and a switch-at-use header follow.
pub(in crate::spirv) fn move_tail(
m: &mut TypedModule,
from: BlockId,
to: BlockId,
) -> Result<(), Error> {
fn move_tail(m: &mut TypedModule, from: BlockId, to: BlockId) -> Result<(), Error> {
let (merge, term) = {
let b = block(m, from)?;
(b.merge, b.term.clone())
@@ -14,8 +14,7 @@
//! `?:` arm or a `&&`/`||` operand. A value SPIRV-Cross would forward into its one reader without
//! the dependencies of its operands is written the same way (`forwards_without_dependencies`), so
//! it is evaluated where the module does, before any later write overwrites what it reads. A kept
//! routine (a texel routine's sum, a sampling routine's emulation, or a repeated region
//! `spirv::outline` wrote once) is declared `DontInline`.
//! routine (a texel routine's sum or a sampling routine's emulation) is declared `DontInline`.
//!
//! Every number link assigns (descriptor set and binding, `Location`/`Component`, `SpecId`) is a
//! literal operand of an `OpDecorate`. The serializer writes 0 there and records a relocation
@@ -111,8 +111,7 @@ fn cost_of<T>(work: impl FnOnce() -> T) -> (T, Cost) {
/// Irreducible on purpose: it is the shape that reaches the structurizer's irreducible-region
/// handling, where a per-block table of blocks would be quadratic, and it keeps every block alive
/// through the planner. Each group loads a distinct buffer word, so the conditions cannot be folded
/// away, and each group's two operations are drawn from four by a hash of its index, so no run of
/// groups long enough to be written once as a routine repeats: the graph survives intact.
/// away and the graph survives intact.
fn irreducible_chain(groups: usize) -> String {
let mut out = String::from(
r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
@@ -123,15 +122,8 @@ entry:
br label %g0
"#,
);
const OPS: [&str; 4] = ["add", "sub", "xor", "or"];
for group in 0..groups {
let word = group % 1024;
// splitmix64's finalizer of the group's index: two operations from its low four bits.
let mut z = (group as u64).wrapping_add(0x9E37_79B9_7F4A_7C15);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let (op_a, op_b) = (OPS[(z & 3) as usize], OPS[((z >> 2) & 3) as usize]);
out.push_str(&format!(
"g{group}:
%p{group} = getelementptr inbounds i32, ptr addrspace(1) %out, i64 {word}
@@ -139,11 +131,11 @@ entry:
%c{group} = icmp sgt i32 %v{group}, 0
br i1 %c{group}, label %a{group}, label %b{group}
a{group}:
%av{group} = {op_a} i32 %v{group}, 1
%av{group} = add i32 %v{group}, 1
%ac{group} = icmp sgt i32 %av{group}, 3
br i1 %ac{group}, label %b{group}, label %g{next}
b{group}:
%bv{group} = {op_b} i32 %v{group}, 2
%bv{group} = add i32 %v{group}, 2
%bc{group} = icmp sgt i32 %bv{group}, 5
br i1 %bc{group}, label %a{group}, label %g{next}
",
+2 -6
View File
@@ -523,14 +523,10 @@ assert!(stats.reachable_blocks <= stats.blocks);
blocks are the program's, while a module that calls a many-block function from many sites holds
a program far larger than its own blocks; the two read alike in `blocks` alone. Lowering emits
such functions itself: the handle-table search (unrolled branch-free steps) and the root-table
search (a loop), each emitted once and called at every access. A region of 500 or more
instructions that a function holds more than once (a function the program calls from several
places, inlined at each) is written once too, as a routine declared `DontInline` and called
from each place: NVIDIA's driver compiles it once, and RADV and ANV (Mesa 26.2.6) compile the
same code with or without the control.
search (a loop), each emitted once and called at every access.
- `entry_weight` is what a driver compiles once it has inlined every call: the entry's
instructions with each call counted as its callee's body, after repeated regions are rolled
into loops (a region written as a routine counts at each of its calls). A stage past `pipeline::COMPILED_STAGE_WEIGHT` (99,109, the heaviest measured to
into loops. A stage past `pipeline::COMPILED_STAGE_WEIGHT` (99,109, the heaviest measured to
compile within host-sized memory on the slowest compiler measured) is one whose creation may
take the host's memory: the translator makes it all the same, and `metal2vulkan-runtime`
compiles such a kernel only in a helper process the consumer caps (its README, "Kernels past
+3 -4
View File
@@ -23,11 +23,10 @@ metallib | AIR bitcode
── 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,
half values held at 16 bits under the 16-bit float hoist, outline, half_hold}
half values held at 16 bits under the 16-bit float hoist, half_hold}
controls, repeated regions of large entries rolled
into loops, loop-invariant loads of uniform views
moved before their loops, repeated regions of 500
instructions or more written once as kept routines
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, held to spirv::serialize
the word cap
@@ -76,7 +75,7 @@ rest is `crates/metal2vulkan/src/`.
| `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), `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 writing of repeated regions as kept routines (`outline`), 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 |
| `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/`) |
| `spirv_binary/` | A reader of SPIR-V's binary form over the grammar's instruction table, used only by tests |
| `device/` | `DeviceDescription` (from a Khronos profile, or from `ash`), `DevicePolicy`, and the derived `DeviceProfile` every decision reads |