From 3e7a7c1e34fac18137a12a23eba1a5e09485ce3c Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 18:36:29 -0800 Subject: [PATCH] Translator: the builder's growth is charged inside a block, and its doublings before they are reserved The SPIR-V builder cannot hold the meter, so the walk charged the builder's growth after each AIR block's code. That left two gaps. - One block could grow the builder by any amount before its charge. On the heaviest kernel of a guest library (Iris Xe profile), the module-wide value table (one 16-byte entry per result) doubled from 16 to 32 MiB inside one block. - The entry hooks' code and the walk's variables (6.0 MiB there) were charged only once the walk returned. Together, the attempt held 21.8 MiB more than the ledger counted at one point (probe job m3-max-65302, GPU-free, release). Now: - structurize::emit::Poll holds the walk's meter and growth. The emitter counts each instruction of a block's code on it: CodeEmitter::block and block_live take it, and lower::Emitter counts in block, segment and synchronization. - The walk charges once its variables are allocated, after each block, and every 16 counted instructions. Each charge counts the builder's footprint plus what the next 4,096 results, blocks and open-block instructions reserve (FunctionBuilder::footprint_ahead): the doubling of the value table, of the block table, and of the open block's instruction storage, wherever 4,096 more would pass the capacity. A doubling is on the ledger before it is reserved. - What is charged ahead and not reserved stays charged (the ledger keeps the high-water mark) until the builder grows into it. - The walk's growth starts from what the caller charged: lower::emit charges the hooks' code before the walk. Nothing emitted changes. The modules, the refusal classes and the work units are the same; only when the ledger counts the builder moves. Verified: - New test ledger_resident::a_long_block_s_code_is_charged_while_it_grows: one block of 8,000 bfloat operations, under ledger caps of one to seven eighths of its 22.6 MB peak. Each refusal holds at most the cap and a ninth. - Red on development (job m3-max-65388): under the 5.65 MB cap, the refusal came with 16.76 MB held, the block's whole code. - Green here (job m3-max-65425): 3.88 MB held under the same cap. - Compile job m3-max-65425: fmt; clippy plain, --cfg m2v_gpu and --cfg m2v_cpu_icd; workspace Rustdoc -D warnings; the metal2vulkan and metal2vulkan-air suites, golden hashes and the render descriptor key among them. - Both guest libraries, every kernel lowered plain and with partial threadgroups on its library's profile: 252 rows in job m3-max-65424 against m3-max-65302. - All 252 translate. Every module hash and every work count is equal. - The heaviest row's ledger peak stays 440.2 of 450 MiB. Other peaks rise by at most 1.7 MiB, on the smallest rows: the charge ahead that nothing reserved. Live growth is unchanged. - The builder's bytes past its charge, at any push, fall from at most 16.0 MiB to 0. - The most held past the ledger falls from 21.8 to 13.1 MiB. The rest is outside the walk: the module's finalization after it. - The heaviest row makes 67,562 charges where it made 48,031. States-only play before landing (job m3-max-65452, lavapipe, this change on bebd518dfb with the player's states-only probe): all 9 standard streams exit 0, 0 render and 0 compute states refused, 0 not attempted. --- crates/metal2vulkan/src/lower/emit.rs | 29 +++- .../src/spirv/builder/function.rs | 26 ++++ .../spirv/interp/tests/structured_trace.rs | 12 +- crates/metal2vulkan/src/structurize/emit.rs | 128 +++++++++++++----- .../src/structurize/emit/predicate.rs | 12 +- .../src/structurize/emit/tests.rs | 9 +- .../metal2vulkan/src/tests/ledger_resident.rs | 82 ++++++++--- 7 files changed, 231 insertions(+), 67 deletions(-) diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 266fafeb5..07c467152 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -59,7 +59,7 @@ use crate::spirv::ir::{ BinOp, ConstBits, Constant, ConvOp, ExecMode, ExecModel, MemAccess, PushMember, Type, TypedModule, ValueOrigin, }; -use crate::structurize::emit::{CodeEmitter, StructVars}; +use crate::structurize::emit::{CodeEmitter, Poll, StructVars}; use crate::structurize::promote::promote_single_store; fn invariant(detail: impl Into) -> Error { @@ -1110,6 +1110,7 @@ impl<'a> Emitter<'a> { first: bool, last: bool, vars: &StructVars, + poll: &mut Poll<'_>, ) -> BResult<()> { let phis = first && self @@ -1132,6 +1133,7 @@ impl<'a> Emitter<'a> { for (id, v) in seg { em.ensure_operands(fb, id)?; em.inst(fb, id, v, vars)?; + poll.count(fb)?; } if last { em.copies(b, fb, vars, true)?; @@ -1292,7 +1294,12 @@ impl CodeEmitter for Emitter<'_> { Ok(()) } - fn block(&mut self, b: crate::air::ir::BlockId, fb: &mut FunctionBuilder<'_>) -> BResult<()> { + fn block( + &mut self, + b: crate::air::ir::BlockId, + fb: &mut FunctionBuilder<'_>, + poll: &mut Poll<'_>, + ) -> BResult<()> { let vars = self.vars()?; if self.cx.entry_block.is_none() { self.cx.entry_block = fb.entry_block(); @@ -1327,6 +1334,7 @@ impl CodeEmitter for Emitter<'_> { return Err(self.cx.fail(format!("{id:?} is out of range"))); }; self.inst(fb, id, v, &vars)?; + poll.count(fb)?; } self.copies(b, fb, &vars, false) } @@ -1379,9 +1387,10 @@ impl CodeEmitter for Emitter<'_> { b: crate::air::ir::BlockId, live: Option, fb: &mut FunctionBuilder<'_>, + poll: &mut Poll<'_>, ) -> BResult<()> { let Some(live) = live else { - return self.block(b, fb); + return self.block(b, fb, poll); }; let vars = self.vars()?; if self.cx.entry_block.is_none() { @@ -1418,12 +1427,13 @@ impl CodeEmitter for Emitter<'_> { seg.push((id, v)); continue; } - self.segment(b, fb, live, &seg, first, false, &vars)?; + self.segment(b, fb, live, &seg, first, false, &vars, poll)?; seg.clear(); first = false; self.sync_inst(fb, id, v, live, uniform, &vars)?; + poll.count(fb)?; } - self.segment(b, fb, live, &seg, first, true, &vars) + self.segment(b, fb, live, &seg, first, true, &vars, poll) } fn vote(&mut self, live: SValue, fb: &mut FunctionBuilder<'_>) -> BResult { @@ -1537,8 +1547,9 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result Result<(TypedModule, Vec, BTreeSet, usize), Error> { let decl = declare(&mut mb, plan)?; - // The builder is charged as it grows: the declarations here, the walk's growth by - // `structurize::emit` after each block, and what the walk left once it returns. + // The builder is charged as it grows: the declarations here, the entry hooks' code + // before the walk, the walk's growth by `structurize::emit` as it emits, and what the + // walk left once it returns. let mut held = Growth::default(); held.charge_to(mb.footprint(), m)?; let mut em = Emitter::new(e, body, plan, &decl); @@ -1571,6 +1582,10 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result fb.finish().map_err(Error::from), diff --git a/crates/metal2vulkan/src/spirv/builder/function.rs b/crates/metal2vulkan/src/spirv/builder/function.rs index 455c33a57..03f55a9a0 100644 --- a/crates/metal2vulkan/src/spirv/builder/function.rs +++ b/crates/metal2vulkan/src/spirv/builder/function.rs @@ -57,6 +57,32 @@ impl<'m> FunctionBuilder<'m> { self.cursor } + /// The module's [`ModuleBuilder::footprint`], and the capacity its containers that grow with + /// the code reserve while `ahead` more entries go in each: the value table, one entry per + /// result of the module; the block table, one draft per block; and the open block's + /// instruction storage. Each doubles when full, so the emitters charge this at their poll + /// points to put a doubling on the ledger before it is reserved, whenever fewer than `ahead` + /// results, blocks or instructions come before the next poll. + pub fn footprint_ahead(&self, ahead: usize) -> usize { + /// The bytes `v` reserves while `ahead` more elements are pushed one at a time. + fn reserved(v: &Vec, ahead: usize) -> usize { + let needed = v.len().saturating_add(ahead); + let mut cap = v.capacity(); + while cap < needed { + cap = cap.saturating_mul(2).max(4); + } + (cap - v.capacity()).saturating_mul(std::mem::size_of::()) + } + let open = self + .cursor + .and_then(|b| self.m.blocks.get(b.index())) + .map_or(0, |bd| reserved(&bd.insts, ahead)); + self.m.footprint() + + reserved(&self.m.values, ahead) + + reserved(&self.m.blocks, ahead) + + open + } + /// The function's entry block, which dominates every block of the function. pub fn entry_block(&self) -> Option { self.m diff --git a/crates/metal2vulkan/src/spirv/interp/tests/structured_trace.rs b/crates/metal2vulkan/src/spirv/interp/tests/structured_trace.rs index 460c897c0..7f151f33c 100644 --- a/crates/metal2vulkan/src/spirv/interp/tests/structured_trace.rs +++ b/crates/metal2vulkan/src/spirv/interp/tests/structured_trace.rs @@ -36,7 +36,7 @@ use crate::error::{Error, Feature}; use crate::spirv::ids::{DemoteTy, FuncId, ScalarTy, VarId}; use crate::spirv::ir::AtomicOp; use crate::spirv::testing::{check_valid, committed_profiles}; -use crate::structurize::emit::{emit, CodeEmitter, StructVars}; +use crate::structurize::emit::{emit, CodeEmitter, Poll, StructVars}; use crate::structurize::promote::promote_single_store; use crate::structurize::testkit::generate::{self, Rng}; use crate::structurize::testkit::hash::{key, Hash, EXEC_MUL, MIX}; @@ -461,7 +461,12 @@ impl CodeEmitter for TraceEmitter<'_> { Ok(()) } - fn block(&mut self, b: AirBlock, fb: &mut FunctionBuilder<'_>) -> BResult<()> { + fn block( + &mut self, + b: AirBlock, + fb: &mut FunctionBuilder<'_>, + _poll: &mut Poll<'_>, + ) -> BResult<()> { let g = self.glob; if self.predicated { let ballot = self.live_ballot(b, None, fb)?; @@ -510,9 +515,10 @@ impl CodeEmitter for TraceEmitter<'_> { b: AirBlock, live: Option, fb: &mut FunctionBuilder<'_>, + poll: &mut Poll<'_>, ) -> BResult<()> { let Some(l) = live else { - return self.block(b, fb); + return self.block(b, fb, poll); }; let ballot = self.live_ballot(b, Some(l), fb)?; fb.if_( diff --git a/crates/metal2vulkan/src/structurize/emit.rs b/crates/metal2vulkan/src/structurize/emit.rs index 03477723f..b0b01ab15 100644 --- a/crates/metal2vulkan/src/structurize/emit.rs +++ b/crates/metal2vulkan/src/structurize/emit.rs @@ -57,7 +57,14 @@ pub trait CodeEmitter { /// loads of the demoted values it uses and phi variables it reads (once, at its top), the /// stores of the demoted values it defines, and the parallel copy into the incoming variables /// of its successors' phis. It may open builder-closed constructs and must leave a block open. - fn block(&mut self, b: BlockId, fb: &mut FunctionBuilder<'_>) -> BResult<()>; + /// It counts each instruction of `b` it emits on `poll` ([`Poll::count`]), so a long block's + /// code is charged while it grows. + fn block( + &mut self, + b: BlockId, + fb: &mut FunctionBuilder<'_>, + poll: &mut Poll<'_>, + ) -> BResult<()>; /// The `bool` value of branch condition `v`, in the open block. fn cond(&mut self, v: ValueId, fb: &mut FunctionBuilder<'_>) -> BResult; /// A 32-bit integer for switch selector `v`, in the open block: for every case literal `l` of @@ -109,8 +116,9 @@ pub trait CodeEmitter { b: BlockId, _live: Option, fb: &mut FunctionBuilder<'_>, + poll: &mut Poll<'_>, ) -> BResult<()> { - self.block(b, fb) + self.block(b, fb, poll) } /// Whether `live` holds for some invocation of the workgroup: a workgroup-uniform `bool`, @@ -237,9 +245,11 @@ fn check_tree(s: &Structured, meter: &mut Meter) -> Result<(), Error> { } /// P8: emit `s` into `fb`, whose entry block is open and empty, through `c`. On success no block -/// is open; the caller finishes the function. The builder's growth is charged to `meter` after -/// each block's code, so an oversized module is refused while it grows, and returned when the -/// walk ends: the caller owns the builder and charges what it holds. A refusal from the pre-pass +/// is open; the caller finishes the function. The builder's growth past what the caller has +/// charged (its footprint when `emit` is called) is charged to `meter` once the variables are +/// allocated, after each block's code and inside it ([`Poll`]), so an oversized module is refused +/// while it grows, and returned when the walk ends: the caller owns the builder and charges what +/// it holds. A refusal from the pre-pass /// (`Limit:: ConstructNesting`, `Unsupported`) leaves `fb` untouched; a builder error aborts the /// function (the builder is not rolled back). pub fn emit( @@ -249,6 +259,7 @@ pub fn emit( meter: &mut Meter, ) -> Result { check_tree(s, meter)?; + let start = fb.module().footprint(); let vars = allocate(s, fb, c)?; // A walk that is not predicated runs each invocation's trips of a loop as the source does, so // no trip reads a value an earlier one left in a demoted value's or a phi's variable where @@ -261,33 +272,27 @@ pub fn emit( } c.bind(&vars)?; let u32_ty = u32_type(fb.module())?; - // The builder's growth during this walk is charged after each block's code and returned when - // the walk ends: the builder is the caller's, who charges what it holds. - let start = fb.module().footprint(); - let growth = Growth::from_charged(start); + // The builder's growth during this walk, its variables first, is charged as it grows and + // returned when the walk ends: the builder is the caller's, who charges what it holds. let mut cx = Cx { tree: &s.tree, c, vars: &vars, u32_ty, - meter, - growth, - fault: None, + poll: Poll { + meter, + growth: Growth::from_charged(start), + since: 0, + fault: None, + }, }; - if let Some(p) = vars.pending { - let zero = cx.konst(fb, 0)?; - let ptr = fb.var_ptr(p)?; - fb.store(ptr, zero, MemAccess::default())?; - } - let walked = if cx.c.predicated() { - predicate::walk_root(&mut cx, fb) - } else { - list(&mut cx, fb, s.tree.root(), None) - .and_then(|()| cx.poll(fb)) - .map_err(Error::from) - }; - cx.meter.release(cx.growth.charged() - start); - if let Some(fault) = cx.fault { + let walked = cx + .poll + .charge(fb) + .map_err(Error::from) + .and_then(|()| walk(&mut cx, fb, s)); + cx.poll.meter.release(cx.poll.growth.charged() - start); + if let Some(fault) = cx.poll.fault { return Err(fault); } walked?; @@ -297,6 +302,26 @@ pub fn emit( Ok(vars) } +/// The walk of `s`'s tree, from the store of `pending`'s initial value. +fn walk( + cx: &mut Cx<'_, E>, + fb: &mut FunctionBuilder<'_>, + s: &Structured, +) -> Result<(), Error> { + if let Some(p) = cx.vars.pending { + let zero = cx.konst(fb, 0)?; + let ptr = fb.var_ptr(p)?; + fb.store(ptr, zero, MemAccess::default())?; + } + if cx.c.predicated() { + predicate::walk_root(cx, fb) + } else { + list(cx, fb, s.tree.root(), None) + .and_then(|()| cx.poll.charge(fb)) + .map_err(Error::from) + } +} + fn u32_type(m: &mut ModuleBuilder) -> BResult { m.ty(Type::Int { width: 32, @@ -357,24 +382,61 @@ struct Cx<'e, E> { c: &'e mut E, vars: &'e StructVars, u32_ty: TypeId, - meter: &'e mut Meter, + poll: Poll<'e>, +} + +/// The instructions of blocks' code [`Poll::count`] lets pass between two charges. +pub const POLL_INSTRUCTIONS: u32 = 16; + +/// The results, blocks and open-block instructions a poll charges ahead of the builder +/// ([`FunctionBuilder::footprint_ahead`]): 256 of each for each instruction [`Poll::count`] lets +/// pass. The value and block tables hold one entry per result and per block of the module, so +/// their doublings are the largest growth the builder makes at once (the value table from 16 to +/// 32 MiB past a million results); charged ahead, each is on the ledger before it is reserved. +/// Code that makes more between two polls doubles a table there, and the next poll charges it. +pub const AHEAD: usize = 256 * POLL_INSTRUCTIONS as usize; + +/// The builder's growth during a walk, charged to the attempt's meter at the walk's poll points +/// (once its variables are allocated, after each block's code, and every [`POLL_INSTRUCTIONS`] +/// instructions the emitter writes inside blocks, [`CodeEmitter::block`]) with what the next +/// [`AHEAD`] results, blocks and instructions reserve. The ledger keeps the high-water mark +/// ([`Growth`]): what was charged ahead and not reserved stays charged until the builder grows +/// into it. +pub struct Poll<'m> { + meter: &'m mut Meter, /// The builder bytes charged so far. growth: Growth, + /// The instructions counted since the last charge. + since: u32, /// A meter refusal met inside the walk, which returns a builder error; `emit` reports this /// instead. fault: Option, } -impl Cx<'_, E> { - /// Charge the builder's growth since the last poll to the meter. - fn poll(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult<()> { - let footprint = fb.module().footprint(); +impl Poll<'_> { + /// Count one instruction of a block's code the emitter wrote, and charge at every + /// [`POLL_INSTRUCTIONS`]th. + pub fn count(&mut self, fb: &FunctionBuilder<'_>) -> BResult<()> { + self.since += 1; + if self.since < POLL_INSTRUCTIONS { + return Ok(()); + } + self.charge(fb) + } + + /// Charge the builder's growth since the last poll, and what the next [`AHEAD`] results, + /// blocks and instructions reserve, to the meter. + fn charge(&mut self, fb: &FunctionBuilder<'_>) -> BResult<()> { + self.since = 0; + let footprint = fb.footprint_ahead(AHEAD); self.growth.charge_to(footprint, self.meter).map_err(|e| { self.fault.get_or_insert(e.into()); BuildError::Control(ControlRule::NoCurrentBlock) }) } +} +impl Cx<'_, E> { fn stmt(&self, id: StmtId) -> BResult<&Stmt> { self.tree .stmt(id) @@ -498,8 +560,8 @@ fn simple( ) -> BResult<()> { match st { Stmt::Code(b) => { - cx.c.block(*b, fb)?; - cx.poll(fb)?; + cx.c.block(*b, fb, &mut cx.poll)?; + cx.poll.charge(fb)?; } Stmt::SetSel { sel, value } => { let ptr = cx.sel_ptr(fb, *sel)?; diff --git a/crates/metal2vulkan/src/structurize/emit/predicate.rs b/crates/metal2vulkan/src/structurize/emit/predicate.rs index 9f61724f8..632c5430b 100644 --- a/crates/metal2vulkan/src/structurize/emit/predicate.rs +++ b/crates/metal2vulkan/src/structurize/emit/predicate.rs @@ -107,7 +107,7 @@ impl Facts { /// The facts of the tree of `cx` ([`facts_of`]). fn facts(cx: &mut Cx<'_, E>) -> Result { let c = &*cx.c; - facts_of(cx.tree, |b| c.syncs(b), cx.meter) + facts_of(cx.tree, |b| c.syncs(b), cx.poll.meter) } /// The facts of `tree` (children precede parents in the arena) whose blocks synchronize where @@ -284,9 +284,9 @@ pub(super) fn walk_root( // Every invocation that returned in a divergent position ends here. cx.c.on_return(None, fb)?; } - cx.poll(fb) + cx.poll.charge(fb) })(); - cx.meter.release(facts.bytes()); + cx.poll.meter.release(facts.bytes()); r.map_err(Error::from) } @@ -527,12 +527,12 @@ fn code( return Err(BuildError::Control(ControlRule::NoCurrentBlock)); } if st.live { - cx.c.block(b, fb)?; + cx.c.block(b, fb, &mut cx.poll)?; } else { let l = w.load(fb, w.live)?; - cx.c.block_live(b, Some(l), fb)?; + cx.c.block_live(b, Some(l), fb, &mut cx.poll)?; } - cx.poll(fb)?; + cx.poll.charge(fb)?; Ok(st) } diff --git a/crates/metal2vulkan/src/structurize/emit/tests.rs b/crates/metal2vulkan/src/structurize/emit/tests.rs index 85e611630..be68f0bb3 100644 --- a/crates/metal2vulkan/src/structurize/emit/tests.rs +++ b/crates/metal2vulkan/src/structurize/emit/tests.rs @@ -22,7 +22,7 @@ mod convergence; use std::collections::BTreeMap; -use super::{emit, CodeEmitter, StructVars}; +use super::{emit, CodeEmitter, Poll, StructVars}; use crate::air::ir::{BlockId, ValueId}; use crate::budget::{Budget, Meter, CONSTRUCT_NESTING}; use crate::device::profile::DeviceProfile; @@ -122,7 +122,12 @@ impl CodeEmitter for TestEmitter<'_> { Ok(()) } - fn block(&mut self, b: BlockId, fb: &mut FunctionBuilder<'_>) -> BResult<()> { + fn block( + &mut self, + b: BlockId, + fb: &mut FunctionBuilder<'_>, + _poll: &mut Poll<'_>, + ) -> BResult<()> { let vars = self.vars.as_ref().expect("bound"); let loads: Vec = self.preds[b.raw() as usize] .iter() diff --git a/crates/metal2vulkan/src/tests/ledger_resident.rs b/crates/metal2vulkan/src/tests/ledger_resident.rs index 663a7d0f2..2c5c8fbed 100644 --- a/crates/metal2vulkan/src/tests/ledger_resident.rs +++ b/crates/metal2vulkan/src/tests/ledger_resident.rs @@ -16,6 +16,12 @@ //! allocator counts the bytes the translation asked for on its own thread //! (`constant_blob_footprint::held_during`), the same number on any host. //! +//! A kernel of one long block holds the same under the same caps. The SPIR-V builder cannot hold +//! the meter while the emitter grows it, so its growth is charged at the walk's poll points +//! (`structurize::emit::Poll`); charged only after each block, a long block's whole code was built +//! past the cap before the refusal, and the doublings of its instruction storage and of the +//! module's value table were reserved before they were charged. +//! //! `llvm-as` assembles the kernel; without it the test skips visibly. use crate::budget::{Budget, Meter, LEDGER_BYTES, SPIRV_WORDS, WORK_UNITS}; @@ -43,9 +49,7 @@ const CHAIN: usize = 16; /// application to the one before's result, with the constants 1, 2, ..., and stores the last /// result to word 0. fn module() -> String { - let mut s = String::from( - "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n", - ); + let mut s = String::from(HEADER); s.push_str( "define internal fastcc float @body(float %x, float %c, ptr addrspace(1) %out) {\nb0:\n", ); @@ -79,11 +83,41 @@ fn module() -> String { s.push_str(&format!( " store float %c{CHAIN}, ptr addrspace(1) %0, align 4\n ret void\n}}\n\n" )); - s.push_str("!llvm.module.flags = !{!0}\n!air.kernel = !{!20}\n!air.version = !{!17}\n!air.language_version = !{!18}\n\n"); - s.push_str("!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n!10 = !{}\n!11 = !{!12}\n!12 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"float\", !\"air.arg_name\", !\"out\"}\n!17 = !{i32 2, i32 8, i32 0}\n!18 = !{!\"Metal\", i32 4, i32 0, i32 0}\n!20 = !{ptr @chain, !10, !11}\n"); + s.push_str(&footer("chain")); s } +/// The `bfloat` operations of [`long_block`]. +const LONG: usize = 8_000; + +/// `@long(out)`: one block that narrows word 0 to `bfloat` as `x`, applies `* x` or `+ x` to it +/// as [`halves`] picks, [`LONG`] times, and stores the result, widened, to word 0. Each `bfloat` +/// operation lowers to a bounded integer rounding of up to 18 instructions, so the block's code is +/// most of what the translation holds. +fn long_block() -> String { + let mut s = String::from(HEADER); + s.push_str( + "define void @long(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0) {\nentry:\n %a = load float, ptr addrspace(1) %0, align 4\n %v0 = fptrunc float %a to bfloat\n", + ); + for i in 1..=LONG { + let op = if halves(i) { "fmul" } else { "fadd" }; + s.push_str(&format!(" %v{i} = {op} bfloat %v{}, %v0\n", i - 1)); + } + s.push_str(&format!( + " %r = fpext bfloat %v{LONG} to float\n store float %r, ptr addrspace(1) %0, align 4\n ret void\n}}\n\n" + )); + s.push_str(&footer("long")); + s +} + +/// The module's target lines. +const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; + +/// The metadata of kernel `@name(device float *out [[buffer(0)]])`. +fn footer(name: &str) -> String { + format!("!llvm.module.flags = !{{!0}}\n!air.kernel = !{{!20}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\n!0 = !{{i32 7, !\"air.max_device_buffers\", i32 31}}\n!10 = !{{}}\n!11 = !{{!12}}\n!12 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"float\", !\"air.arg_name\", !\"out\"}}\n!17 = !{{i32 2, i32 8, i32 0}}\n!18 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n!20 = !{{ptr @{name}, !10, !11}}\n") +} + /// Whether operation `i` of the body halves the value (else it adds `0.25`): a bit of a /// multiplicative hash of `i`, so no stretch of the body repeats another (only the applications /// repeat). @@ -91,11 +125,11 @@ fn halves(i: usize) -> bool { ((i as u64).wrapping_mul(2_654_435_761) >> 16) & 1 == 1 } -/// The module assembled by `llvm-as`, or `None` (the test skips visibly) without it. -fn assembled() -> Option> { +/// `text` assembled by `llvm-as`, or `None` (the test skips visibly) without it. +fn assembled(text: &str) -> Option> { let scratch = Scratch::new("m2v-ledger-resident"); - let ll = scratch.path().join("chain.ll"); - std::fs::write(&ll, module()).expect("write"); + let ll = scratch.path().join("kernel.ll"); + std::fs::write(&ll, text).expect("write"); match llvm_assemble(&ll) { Ok(b) => Some(b), Err(AssembleError::Missing(t)) => { @@ -106,14 +140,14 @@ fn assembled() -> Option> { } } -/// `@chain` compiled for `p` under a ledger cap of `cap` bytes: the result, the ledger peak, and -/// the most bytes the compile held at once. -fn compiled(bc: &[u8], p: &DeviceProfile, cap: u64) -> (Result<(), Error>, u64, u64) { +/// Kernel `entry` compiled for `p` under a ledger cap of `cap` bytes: the result, the ledger +/// peak, and the most bytes the compile held at once. +fn compiled(bc: &[u8], entry: &str, p: &DeviceProfile, cap: u64) -> (Result<(), Error>, u64, u64) { let mut m = Meter::with_caps(&Budget::default(), WORK_UNITS, cap); let (r, held) = held_during(|| { compile_bitcode( bc, - EntryRef::Name("chain"), + EntryRef::Name(entry), &FunctionConstantValues::defaults(), p, &LowerInputs::new(), @@ -132,14 +166,30 @@ fn within(ledger: u64) -> u64 { #[test] fn what_a_translation_holds_stays_within_its_ledger() { - let Some(bc) = assembled() else { + let Some(bc) = assembled(&module()) else { return; }; let p = profile("runtime-floor", DevicePolicy::RESIDENT_TABLES).expect("profile"); // The shape: the applications are rolled into a loop (the body holds none). let (_, _, kept) = compile_kept(&bc, "chain", &p).expect("chain"); assert_eq!(kept.loops().len(), 1, "the applications roll into one loop"); - let (r, peak, held) = compiled(&bc, &p, LEDGER_BYTES); + holds_within_its_ledger(&bc, "chain", &p); +} + +#[test] +fn a_long_block_s_code_is_charged_while_it_grows() { + let Some(bc) = assembled(&long_block()) else { + return; + }; + let p = profile("runtime-floor", DevicePolicy::RESIDENT_TABLES).expect("profile"); + holds_within_its_ledger(&bc, "long", &p); +} + +/// `entry` translates within the standard ledger, holding at most its ledger peak and a ninth at +/// once; under caps of one to seven eighths of that peak it is refused `LedgerBytes`, holding at +/// most the cap and a ninth by then. +fn holds_within_its_ledger(bc: &[u8], entry: &str, p: &DeviceProfile) { + let (r, peak, held) = compiled(bc, entry, p, LEDGER_BYTES); r.expect("translates"); eprintln!("uncapped: ledger peak {peak} bytes, {held} bytes held at once"); assert!( @@ -148,7 +198,7 @@ fn what_a_translation_holds_stays_within_its_ledger() { ); for eighths in 1..8 { let cap = peak * eighths / 8; - let (r, _, held) = compiled(&bc, &p, cap); + let (r, _, held) = compiled(bc, entry, p, cap); eprintln!("cap {cap} bytes ({eighths}/8): {held} bytes held at once"); assert_eq!( r,