Translator tests: a function inlined three times rolls under the identity domains

engine_roll ran only under the resident-table domains, where an access never makes the slot's
direct base. Under the identity domains, the runtime's, each application of a function reaches its
buffer at the slot's own device address. The new kernel `@head_thrice` applies `@head` three
times: it adds its constant, then loads word 0, before the body's first branch, so the first
application makes the slot's address after an instruction of its own. The test asserts on lavapipe
and MoltenVK that the entry weighs about one application (`@head_once`), that it holds one more
loop, that the slot is reached at its address (an `OpIAddCarry`), that it passes L3, and that it
computes the three applications' values on the CPU interpreter. Each profile prints its weights.

Red at development (m3-max-78287, msi): three applications weighed 26,737 against one's 13,355 on
lavapipe (2.00 bodies), and 13,539 against 13,488 at e2e76d8879^ (1.00). With the load as the
application's first instruction both forms rolled (m3-max-78272): the run then starts after the
first application's two extracts, so that shape does not show it.
This commit is contained in:
Anees Iqbal committed 2026-12-02 06:20:53 -08:00
1 parent 472cfba642
commit edabd70447
1 file changed
+143 -4
+143 -4
View File
@@ -7,12 +7,22 @@
//! (`spirv::roll::entry_weight`) are one body's, as for a kernel that applies the function once,
//! where two bodies are above the size that rolls.
//!
//! Under the identity domains, the runtime's, a function whose every application reads its buffer
//! before the body's first branch rolls too: each application reaches the slot at its own device
//! address, and the regions are the same code only where each makes that address or each reads it
//! from before the run.
//!
//! The body is a chain of `float` multiplies and adds, which the interpreter computes exactly.
//! `llvm-as` assembles the module; without it the test skips visibly.
use std::collections::BTreeMap;
use super::engine_word_phases::{bounds_word, identity_profiles, slot_word, ZERO_UNMAPPED};
use crate::device::DevicePolicy;
use crate::lower::dispatch::region_bytes;
use crate::lower::select::Plan;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::pipeline::interface::PushLoc;
use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage};
use crate::pipeline::testing::{
compile_kept, link_and_validate, llvm_assemble, meter, profile, AssembleError, Scratch,
};
@@ -43,7 +53,9 @@ const CHAIN: usize = 6;
/// `@chain` applies the body [`CHAIN`] times, each application to the one before's result, with
/// the constants 1, 2, ..., and stores the last result to word 0; `@lanes` loads a `float4` from
/// words 0 to 3, adds `0.5` to each lane, and applies the body to each lane in turn, with the
/// constant 1, storing the results to words 4 to 7.
/// constant 1, storing the results to words 4 to 7. `@head(x, c, out)` adds `c` to `x`, loads word 0
/// and adds it, then applies the body with `c`; `@head_once` stores `head(X, 1)` to word 1, and
/// `@head_thrice` stores `head(X, 1)`, `head(X, 2)` and `head(X, 3)` to words 1 to 3.
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",
@@ -106,8 +118,26 @@ fn module() -> String {
));
}
s.push_str(" ret void\n}\n\n");
s.push_str("!llvm.module.flags = !{!0}\n!air.kernel = !{!20, !21, !22, !23}\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 @twice, !10, !11}\n!21 = !{ptr @once, !10, !11}\n!22 = !{ptr @chain, !10, !11}\n!23 = !{ptr @lanes, !10, !11}\n");
s.push_str("define internal fastcc float @head(float %x, float %c, ptr addrspace(1) %out) {\nentry:\n %y0 = fadd float %x, %c\n %h = load float, ptr addrspace(1) %out, align 4\n %y = fadd float %y0, %h\n %r = call fastcc float @body(float %y, float %c, ptr addrspace(1) %out)\n ret float %r\n}\n\n");
for (name, n) in [("head_once", 1), ("head_thrice", 3)] {
s.push_str(&format!(
"define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0) {{\nentry:\n %x = fadd float 0x{:016X}, -0.0\n",
f64::from(X).to_bits()
));
for j in 1..=n {
s.push_str(&format!(
" %a{j} = call fastcc float @head(float %x, float {j}.0, ptr addrspace(1) %0)\n"
));
}
for j in 1..=n {
s.push_str(&format!(
" %p{j} = getelementptr inbounds float, ptr addrspace(1) %0, i64 {j}\n store float %a{j}, ptr addrspace(1) %p{j}, align 4\n"
));
}
s.push_str(" ret void\n}\n\n");
}
s.push_str("!llvm.module.flags = !{!0}\n!air.kernel = !{!20, !21, !22, !23, !24, !25}\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 @twice, !10, !11}\n!21 = !{ptr @once, !10, !11}\n!22 = !{ptr @chain, !10, !11}\n!23 = !{ptr @lanes, !10, !11}\n!24 = !{ptr @head_once, !10, !11}\n!25 = !{ptr @head_thrice, !10, !11}\n");
s
}
@@ -273,3 +303,112 @@ fn a_chain_of_applications_and_one_by_lane_are_compiled_once_on_every_profile()
}
}
}
/// Where [`run_identity`] places the buffer: above 4 GiB, so a dropped high word shows.
const IDENTITY_BUFFER: u64 = 0x1_0000_0000;
/// Run `m` (planned as `plan` under the identity domains) over one buffer of `words` at
/// [`IDENTITY_BUFFER`], bound at its start, pushing what the identity domains push for it.
fn run_identity(m: &TypedModule, plan: &Plan, words: &[u32], stem: &str) -> Vec<u32> {
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)];
for f in &plan.push.fields {
let PushLoc::Push { offset } = f.loc else {
panic!("{stem}: {f:?} spilled");
};
let o = offset as usize;
match f.field {
PushField::SlotGuestBase(_) => {
push[o..o + 8].copy_from_slice(&slot_word(IDENTITY_BUFFER).to_le_bytes())
}
PushField::SlotBounds(_) => {
push[o..o + 8].copy_from_slice(&bounds_word(bytes.len(), 0))
}
PushField::ZeroAddress => push[o..o + 8].copy_from_slice(&ZERO_UNMAPPED.to_le_bytes()),
PushField::DispatchRegion => push[o..o + 32]
.copy_from_slice(&region_bytes([0; 3], [1, 1, 1], [1, 1, 1]).expect("packs")),
_ => panic!("{stem}: unexpected push field {f:?}"),
}
}
let res = Resources {
buffers: vec![Buffer {
slot: None,
address: Some(IDENTITY_BUFFER),
bytes,
}],
push,
spec: BTreeMap::from(crate::pipeline::threadgroup_constants([1, 1, 1])),
};
let out = run(m, &Config::default(), res).unwrap_or_else(|e| panic!("{stem}: {e}"));
let b = out.buffers.first().expect("buffer");
b.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
.collect()
}
/// Under the identity domains (`DevicePolicy::default`, the runtime's), a function that reads its
/// buffer after its first operation and before the body's first branch (`@head`), so the first
/// application's straight-line code makes the slot's address after work of its own, and is
/// applied three times (`@head_thrice`) is
/// compiled once, as one loop of three trips, on lavapipe and MoltenVK with their buffers reached
/// at their device addresses: the entry weighs about one application (`@head_once`), and it
/// computes what the three written out compute. Each line it prints names the weights, the loops
/// and the module's `OpIAddCarry` count, which shows the slot reached at its address.
#[test]
fn a_function_that_reads_its_buffer_first_is_compiled_once_under_the_identity_domains() {
let Some(bitcode) = assembled() else {
return;
};
let h = 0.5f32;
let want: Vec<u32> = std::iter::once(h)
.chain([1.0f32, 2.0, 3.0].map(|c| apply(X + c + h, c)))
.map(f32::to_bits)
.collect();
let mut ran = 0;
for (stem, p) in identity_profiles() {
if !matches!(stem.as_str(), "lavapipe" | "moltenvk-m3") {
continue;
}
ran += 1;
let (_, _, once) = compile_kept(&bitcode, "head_once", &p).expect("once");
let (art, plan, kept) = compile_kept(&bitcode, "head_thrice", &p).expect("thrice");
let (w1, w3) = (
entry_weight(&once, &mut meter()).expect("weight"),
entry_weight(&kept, &mut meter()).expect("weight"),
);
let carries = super::engine_handles::count(&art, crate::spv::Op::IAddCarry as u16);
eprintln!(
"roll-identity {stem}: one application weighs {w1}, three weigh {w3} ({:.2} bodies); loops {} against {}; OpIAddCarry {carries}",
w3 as f64 / w1 as f64,
kept.loops().len(),
once.loops().len()
);
assert!(
carries > 0,
"{stem}: the slot is reached at its device address"
);
assert!(
w1 * 2 > ROLL_ABOVE,
"{stem}: two applications are above the size that rolls: 2 x {w1}"
);
assert!(
w3 < w1 + 512,
"{stem}: the body is compiled once: {w3} instructions where one application is {w1}"
);
assert_eq!(
kept.loops().len(),
once.loops().len() + 1,
"{stem}: one loop of three trips"
);
link_and_validate(&art, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}"));
let input = [h.to_bits(), 0, 0, 0];
assert_eq!(
run_identity(&kept, &plan, &input, &stem),
want,
"{stem}: the three applications written out"
);
}
assert_eq!(ran, 2, "lavapipe and MoltenVK derive the identity domains");
}