Outline: a search counts each extent's occurrences over the whole function

What: find_in compares an extent against every repeat of its seed window in the function (ranges
of keys by prefix hashes), not only the first 64 repeats it extends against, so one search makes
one routine for every occurrence of a region. The context keeps, by layout position, whether a
loop holds it, and the set of loops' continue blocks; apply drops the gone regions' first blocks
from the switches-at-use list once. The bounded-growth test's chain draws each group's two
operations from four by a hash of the group's index.

Why: the compile job of 08455481c5 (m3-max-64636) failed
engine_bounded_growth::compile_cost_grows_linearly_with_the_block_count: doubling its chain of
equal groups multiplied total compile allocation by 3.43 (49,119,827 to 168,331,419 bytes), 26,005
to 83,028 words. A set held at most 65 occurrences and its saving was counted over them, so a
function of N repeats was searched about N/64 times, each search linear in the function: the
quadratic term. Two scans per occurrence over every loop of the module (in_loop, the continue
check) and a retain over switches-at-use per region were the same shape. The test's chain is all
one group repeated, which the pass rightly writes as one routine, so its module stops growing with
the chain ("the generated graph was folded away"); its groups now differ, so the graph it
measures survives whole.

Verified: not yet run; the new test
a_region_repeated_past_the_repeats_tried_is_one_routine_called_at_every_repeat (80 equal regions
are one routine with 80 calls; the search as it was makes two) and the bounded-growth test run in
the next compile job.
This commit is contained in:
Anees Iqbal committed 2026-11-21 12:18:24 -08:00
1 parent 7e92b1d0fa
commit f0a204d6a0
3 files changed
+110 -28

No files matched your search

+79 -24
View File
@@ -43,10 +43,12 @@
//!
//! What differs between regions in any other way keeps them in line. Candidate sets come from the
//! spine's keys: windows of [`WINDOW`] items whose keys hash alike seed a pair of regions, extended
//! both ways while the keys agree, and the set is the occurrences of a window that share the
//! extent with the largest saving; a set whose comparison fails at an operand or a result is
//! compared again without the item that holds it. Work is linear in the function per search,
//! bounded in functions, occurrences, extension steps and comparisons, and metered on the
//! both ways while the keys agree against the window's first [`MAX_OCCURRENCES`] repeats, and
//! the set is every occurrence of the window in the function that shares the extent with the
//! largest saving (ranges of keys compared by prefix hashes), so a region repeated a thousand
//! times is one routine from one search; a set whose comparison fails at an operand or a result
//! is compared again without the item that holds it. Work is linear in the function per search,
//! bounded in functions, extents, extension steps and comparisons, and metered on the
//! per-attempt [`Meter`].
#[cfg(test)]
@@ -76,7 +78,7 @@ pub const MIN_REGION: u64 = 500;
pub const MAX_ROUTINES: u32 = 64;
/// The items a seed window holds.
const WINDOW: usize = 16;
/// The most occurrences of a seed compared with its first.
/// The repeats of a seed window whose extents beside its first are tried.
const MAX_OCCURRENCES: usize = 64;
/// The exact comparisons per search.
const MAX_VERIFIES: usize = 32;
@@ -257,6 +259,25 @@ fn find_in(
// first item listed under it in order.
const B: u64 = 0x0000_0100_0000_01B3;
let pow = (1..WINDOW).fold(1u64, |p, _| p.wrapping_mul(B));
// The same polynomial over every prefix of the keys, and the powers of `B`: the hash of any
// range of items in constant time.
charge::<u64>(meter, ledger, 2 * (n + 1))?;
let mut ph = Vec::with_capacity(n + 1);
let mut pp = Vec::with_capacity(n + 1);
let (mut hp, mut bp) = (0u64, 1u64);
ph.push(hp);
pp.push(bp);
for it in &sp.items {
hp = hp.wrapping_mul(B).wrapping_add(it.key);
bp = bp.wrapping_mul(B);
ph.push(hp);
pp.push(bp);
}
let range = |a: usize, len: usize| {
let end = ph.get(a + len).copied().unwrap_or(0);
let start = ph.get(a).copied().unwrap_or(0);
end.wrapping_sub(start.wrapping_mul(pp.get(len).copied().unwrap_or(0)))
};
let mut h = 0u64;
for i in 0..WINDOW {
h = h.wrapping_mul(B).wrapping_add(key(i).unwrap_or(0));
@@ -292,9 +313,9 @@ fn find_in(
if covered.get(p0).copied().unwrap_or(true) {
continue;
}
// Each later occurrence's extent beside the first's: its first item, and how far the keys
// agree to the left of the window and from its start.
let mut ext: Vec<(usize, usize, usize)> = Vec::new();
// Each of the first later occurrences' extent beside the first's: how far the keys agree
// to the left of the window and from its start.
let mut ext: Vec<(usize, usize)> = Vec::new();
for &pj in g.iter().skip(1).take(MAX_OCCURRENCES) {
let pj = pj as usize;
if pj < p0 + WINDOW || !(0..WINDOW).all(|d| same(p0 + d, pj + d)) {
@@ -310,21 +331,29 @@ fn find_in(
r += 1;
steps -= 1;
}
ext.push((pj, l, r));
ext.push((l, r));
}
meter.tick(u32::try_from(ext.len().saturating_mul(ext.len())).unwrap_or(u32::MAX))?;
meter.tick(u32::try_from(ext.len()).unwrap_or(u32::MAX))?;
let mut best: Option<Cand> = None;
for &(_, l, r) in &ext {
for &(l, r) in &ext {
let len = l + r;
let weight = span(p0 - l, len);
if weight < min_region {
continue;
}
// The occurrences that hold the extent, none overlapping the one before.
// Every occurrence of the window in the function that holds the extent, none
// overlapping the one before.
meter.tick(u32::try_from(g.len()).unwrap_or(u32::MAX))?;
let h0 = range(p0 - l, len);
let mut starts = vec![p0 - l];
for &(pk, lk, rk) in &ext {
let s = pk - l;
if lk >= l && rk >= r && starts.last().is_some_and(|q| s >= q + len) {
for &pk in g.iter().skip(1) {
let Some(s) = (pk as usize).checked_sub(l) else {
continue;
};
if starts.last().is_some_and(|q| s >= q + len)
&& s + len <= n
&& range(s, len) == h0
{
starts.push(s);
}
}
@@ -472,8 +501,11 @@ struct Cx<'s> {
/// By layout position: the positions of the blocks that branch to it or name it as their
/// merge or continue target.
preds: Vec<Vec<u32>>,
/// The function's loops: the layout positions of the header and the merge.
loops: Vec<(usize, usize)>,
/// By layout position: whether a loop of the function holds it (after the loop's header
/// and before its merge).
in_loop: Vec<bool>,
/// Every loop's continue block.
conts: HashSet<BlockId>,
/// By header: its loop's index in the module's table.
header_of: HashMap<BlockId, usize>,
at_use: HashSet<BlockId>,
@@ -532,19 +564,39 @@ fn context<'s>(
}
}
}
let mut loops = Vec::new();
charge::<(i32, bool)>(meter, ledger, nl + 1)?;
charge::<BlockId>(meter, ledger, m.loops.len())?;
let mut depth = vec![0i32; nl + 1];
let mut conts = HashSet::default();
let mut header_of = HashMap::default();
for (i, l) in m.loops.iter().enumerate() {
conts.insert(l.cont);
let (Some(h), Some(mg)) = (sp.pos(l.header), sp.pos(l.merge)) else {
continue;
};
loops.push((h, mg));
if h + 1 < mg {
if let Some(d) = depth.get_mut(h + 1) {
*d += 1;
}
if let Some(d) = depth.get_mut(mg) {
*d -= 1;
}
}
header_of.insert(l.header, i);
if let Some(var) = l.exit_sel.and_then(|v| m.vars.get(v.index())) {
bump(&mut uses, var.value);
}
}
charge::<(usize, usize, BlockId)>(meter, ledger, loops.len())?;
let mut open = 0i32;
let in_loop = depth
.iter()
.take(nl)
.map(|d| {
open += d;
open > 0
})
.collect();
charge::<(BlockId, usize)>(meter, ledger, header_of.len())?;
charge::<BlockId>(meter, ledger, m.switches_at_use.len())?;
let at_use = m.switches_at_use.iter().copied().collect();
Ok(Cx {
@@ -552,7 +604,8 @@ fn context<'s>(
sp,
uses,
preds,
loops,
in_loop,
conts,
header_of,
at_use,
})
@@ -1053,7 +1106,7 @@ fn verify(
}
}
}
if nb > 1 && m.loops.iter().any(|l| l.cont == bd.last) {
if nb > 1 && cx.conts.contains(&bd.last) {
return Ok(Err(None));
}
}
@@ -1122,7 +1175,7 @@ fn verify(
// runs: the blocks of its own sequence.
let in_loop: Vec<bool> = occ
.iter()
.map(|bd| cx.loops.iter().any(|&(h, mg)| h < bd.ps && bd.ps < mg))
.map(|bd| cx.in_loop.get(bd.ps).copied().unwrap_or(false))
.collect();
let mut always: Vec<Vec<bool>> = Vec::with_capacity(occ.len());
for (bd, &s) in occ.iter().zip(&c.starts) {
@@ -1531,6 +1584,7 @@ fn apply(m: &mut TypedModule, plan: &Plan) -> Result<(), Error> {
let mut rename: HashMap<Value, Value> = HashMap::default();
let mut gone: HashSet<BlockId> = HashSet::default();
let mut body: Vec<BlockId> = Vec::new();
let mut cut: HashSet<BlockId> = HashSet::default();
for t in order {
let o = plan.occ.get(t).ok_or_else(|| invariant("region"))?;
let (call, outs) = call_nodes(m, o, f, ret, &results)?;
@@ -1564,7 +1618,7 @@ fn apply(m: &mut TypedModule, plan: &Plan) -> Result<(), Error> {
body.extend(o.blocks.iter().skip(1).copied());
} else {
removed(m, taken.iter().filter_map(|n| n.result));
m.switches_at_use.retain(|h| *h != o.first);
cut.insert(o.first);
gone.extend(o.blocks.iter().skip(1).copied());
}
let rest = block_mut(m, o.last)?.insts.split_off(o.idx);
@@ -1582,6 +1636,7 @@ fn apply(m: &mut TypedModule, plan: &Plan) -> Result<(), Error> {
bs.insts.extend(call);
bs.insts.extend(rest);
}
m.switches_at_use.retain(|h| !cut.contains(h));
let moved: HashSet<BlockId> = body.iter().copied().collect();
m.functions
.get_mut(f.index())
+20 -1
View File
@@ -1,6 +1,7 @@
//! 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.
//! is passed to the routine, not made its own. A region repeated more often than a search tries
//! extents against is still one routine.
use super::*;
use crate::budget::Budget;
@@ -382,6 +383,24 @@ fn a_region_that_differs_stays_in_line_beside_the_calls_of_the_equal_ones() {
assert_eq!(outline(&mut two, 1, &mut meter()).expect("outline"), 0);
}
/// Eighty equal regions, more repeats than a window's extents are tried against, are one routine
/// called eighty times, made by one search: a search that took only the repeats it tried would
/// leave the rest for another search and another routine of the same code, and a function of
/// many repeats would be searched once per few dozen of them.
#[test]
fn a_region_repeated_past_the_repeats_tried_is_one_routine_called_at_every_repeat() {
let fourths = [BinOp::IMul; 80];
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), 80)]);
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<()> {
@@ -111,7 +111,8 @@ 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 the graph survives intact.
/// 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.
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"
@@ -122,8 +123,15 @@ 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}
@@ -131,11 +139,11 @@ entry:
%c{group} = icmp sgt i32 %v{group}, 0
br i1 %c{group}, label %a{group}, label %b{group}
a{group}:
%av{group} = add i32 %v{group}, 1
%av{group} = {op_a} 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} = add i32 %v{group}, 2
%bv{group} = {op_b} i32 %v{group}, 2
%bc{group} = icmp sgt i32 %bv{group}, 5
br i1 %bc{group}, label %a{group}, label %g{next}
",