Record the structurizer's selection splits too, and count the analyses so neither comes back
The selection structurizer re-derived dominance and rebuilt the source CFG after every private merge it spliced in, the same defect fixed one commit ago in the merge-ownership pass. Counted on the slowest source in the local corpus -- a 44-block kernel that took 4.2 seconds -- translation built 19,384 source CFGs, and 9,522 of them, 55% of the total block-visits, came from that one statement. It is now 2.7 seconds, and it is the slowest source in the corpus by wall clock. `unique_selection_merges_with_loop_exit_and_forced_inner` splices a pass-through in front of a shared natural merge, once per header that claims it, and the `!construct_tree_owned` arms then re-derived so the new block would participate in the next header's ownership question. Recording the split answers that exactly, for the reasons `Dominators::record_pass_through` sets out: a pass-through elides out of every path through it, so the blocks that were already there keep their dominators, and the new block's follow from its predecessors. The natural loops were already known to be unchanged -- an acyclic pass-through in front of an existing block adds no back edge -- which is why the old code called `analyze_reusing_natural_loops` rather than `analyze`. The last commit's `PassThroughDominance` is folded into `Dominators` itself. The structurizer's `cur_forest` has to stay a `LoopForest` (the synthesis functions take one), so the recording has to be reachable from there; putting it on the dominator relation gives it to both callers with no signature churn, and `LoopForest::record_pass_through` forwards. The contract that a pass-through is never itself a split target is now a `debug_assert!` that costs nothing until something records. `header_owned_merge_predecessors` replaces two identical copies of the rule for which predecessors a selection header owns. It has a third caller now -- recording a split means naming the edges it carried -- and three copies of that filter would be three things to keep in step. Two regression guards, because the two ways to be quadratic need different instruments: * `src/native/tests/bounded_work.rs` counts source CFG constructions for a kernel whose loop exit is claimed by six selections. 871 as it stands; 2209 with the re-derivation put back; the bound is 1400. The count is exact and machine-independent -- six sizes reproduce to the block over repeated runs -- where the wall time this defect actually costs is neither. The counter is `#[cfg(test)]`, thread-local, and absent from a release library. * `tests/bounded_growth.rs`'s total-allocation bound, added last commit, is what covers the merge-ownership pass; this kernel does not reach that pass, and its peak-memory bound sees neither. Both files now say which defect each number catches. Verified byte-identical over 2880 local corpus sources, and over the generated irreducible chain at 1502, 3002 and 6002 blocks. A fresh timing sweep over the same 2880: 0 over the 20-second ceiling, slowest 2.74s. Full gate green -- fmt, clippy `-D warnings`, rustdoc `-D warnings`, `cargo test --release -p metal2vulkan`, `cargo test -p metal2vulkan-validation`, and the debug build so the new `debug_assert!` and the counter both run. Not claimed fixed: 871 whole-function analyses for a seventeen-block kernel is still far more than that kernel is worth, and the retry ladder, not any one pass, is where the rest of them come from.
This commit is contained in:
1 parent
1eec182d2b
commit
c43bb11612
7 files changed
+295
-114
No files matched your search
+112
-87
@@ -16,6 +16,37 @@ use crate::spirv_module::Operand;
|
||||
use spirv::{Op, Word};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
// How many source CFGs this thread has built, for the redundant-work regression checks.
|
||||
//
|
||||
// Building a [`Cfg`] is the unit of whole-function analysis: the dominator tree, the natural-loop
|
||||
// forest, and every ownership decision derived from either start here. A translator that re-derives
|
||||
// one per construct instead of maintaining it is quadratic in the block count, which is how the
|
||||
// 20-second per-attempt ceiling in `AGENTS.md` gets broken -- and the count, unlike a wall time,
|
||||
// is the same number on every machine.
|
||||
//
|
||||
// Thread-local because the unit tests run concurrently in one binary while a single translation is
|
||||
// sequential. Test builds only; there is no counter in a release library.
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static CFG_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn cfg_builds_bump() {
|
||||
CFG_BUILDS.with(|count| count.set(count.get() + 1));
|
||||
}
|
||||
|
||||
/// Source CFGs built on this thread while `work` ran.
|
||||
///
|
||||
/// See the note on `CFG_BUILDS` above for why this number, rather than a wall time or a
|
||||
/// high-water mark, is what a redundant-work regression check should assert on.
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn cfg_builds_during<T>(work: impl FnOnce() -> T) -> (T, usize) {
|
||||
let before = CFG_BUILDS.with(std::cell::Cell::get);
|
||||
let value = work();
|
||||
(value, CFG_BUILDS.with(std::cell::Cell::get) - before)
|
||||
}
|
||||
|
||||
/// Successor/predecessor adjacency of a function's source CFG. Only edges whose
|
||||
/// target is a real block in the function are recorded — a branch to a
|
||||
/// non-existent label is dropped, matching the natural-loop analysis contract.
|
||||
@@ -42,6 +73,8 @@ impl Cfg {
|
||||
/// that is not itself a block are dropped from both `successors` and
|
||||
/// `predecessors` (a branch to a non-existent label carries no CFG meaning).
|
||||
pub(in crate::native) fn from_blocks(blocks: &[BodyBlock]) -> Option<Cfg> {
|
||||
#[cfg(test)]
|
||||
cfg_builds_bump();
|
||||
let entry = blocks.first()?.name.clone();
|
||||
// Only edges to real blocks count (a branch to a non-existent label is ignored here).
|
||||
let names: HashSet<String> = blocks.iter().map(|b| b.name.clone()).collect();
|
||||
@@ -98,7 +131,11 @@ impl Cfg {
|
||||
let (idom, intervals) = named_dominators(&self.order, |name| {
|
||||
self.successors.get(name).map(Vec::as_slice).unwrap_or(&[])
|
||||
});
|
||||
Dominators { idom, intervals }
|
||||
Dominators {
|
||||
idom,
|
||||
intervals,
|
||||
pass_throughs: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,87 +155,6 @@ pub(in crate::native) fn block_dominators(blocks: &[BodyBlock]) -> Dominators {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Dominance over a block list that edge splitting only ever extends with pass-through blocks.
|
||||
///
|
||||
/// The ownership passes repeatedly split an edge: some predecessors of a block `T` are redirected
|
||||
/// through a fresh block `S` whose only successor is `T`. Re-deriving the whole relation after each
|
||||
/// split is the obvious way to keep answering dominance questions, and it makes a pass that
|
||||
/// performs one split per construct quadratic in the block count — the shape that breaks the
|
||||
/// per-translation time ceiling on generated shaders.
|
||||
///
|
||||
/// It is also unnecessary, twice over:
|
||||
///
|
||||
/// * **The old blocks do not move.** Every entry-to-`X` path after the split is an entry-to-`X`
|
||||
/// path before it with `S` spliced in, and vice versa. The pre-existing blocks on it are the
|
||||
/// same ones, so dominance among pre-existing blocks is exactly unchanged.
|
||||
/// * **A pass-through's own dominators follow from its predecessors.** Every path to `S` is a path
|
||||
/// to one of its predecessors plus one edge, so a block other than `S` dominates `S` exactly when
|
||||
/// it dominates all of them. Resolving predecessors that are themselves pass-throughs leaves a
|
||||
/// set of original blocks, which the unchanged base relation answers for.
|
||||
///
|
||||
/// So the base relation is computed once and each split is *recorded* rather than re-derived. The
|
||||
/// recording is exact, not an approximation: [`Self::dominates`] agrees with a relation freshly
|
||||
/// computed over the mutated block list, which is what
|
||||
/// `a_recorded_pass_through_answers_what_a_fresh_analysis_answers` checks.
|
||||
///
|
||||
/// `dominator` must be a block of the original list. A pass-through is never a split target — split
|
||||
/// targets are chosen before any splitting starts — so no caller has reason to ask whether one
|
||||
/// dominates something, and this cannot answer it.
|
||||
pub(in crate::native) struct PassThroughDominance {
|
||||
/// Dominance of the block list as it stood before any split.
|
||||
base: Dominators,
|
||||
/// Each recorded pass-through, resolved to the original blocks that stand in for it.
|
||||
pass_throughs: HashMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl PassThroughDominance {
|
||||
/// The relation of `blocks`, with no splits recorded yet.
|
||||
pub(in crate::native) fn of_blocks(blocks: &[BodyBlock]) -> Self {
|
||||
PassThroughDominance {
|
||||
base: block_dominators(blocks),
|
||||
pass_throughs: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record that `name` was spliced in front of a block, carrying exactly `predecessors`.
|
||||
///
|
||||
/// `predecessors` is the complete set of edges redirected through it; a pass-through with no
|
||||
/// predecessors is unreachable, and is then dominated by nothing, as in
|
||||
/// [`crate::native::dominators`].
|
||||
pub(in crate::native) fn record_pass_through(&mut self, name: &str, predecessors: &[String]) {
|
||||
let mut originals = Vec::new();
|
||||
for predecessor in predecessors {
|
||||
match self.pass_throughs.get(predecessor) {
|
||||
Some(resolved) => originals.extend(resolved.iter().cloned()),
|
||||
None => originals.push(predecessor.clone()),
|
||||
}
|
||||
}
|
||||
originals.sort();
|
||||
originals.dedup();
|
||||
self.pass_throughs.insert(name.to_string(), originals);
|
||||
}
|
||||
|
||||
/// Whether `dominator`, a block of the original list, dominates `node`.
|
||||
pub(in crate::native) fn dominates(&self, dominator: &str, node: &str) -> bool {
|
||||
if dominator == node {
|
||||
return true;
|
||||
}
|
||||
debug_assert!(
|
||||
!self.pass_throughs.contains_key(dominator),
|
||||
"a pass-through is never a split target, so nothing asks what it dominates"
|
||||
);
|
||||
match self.pass_throughs.get(node) {
|
||||
Some(originals) => {
|
||||
!originals.is_empty()
|
||||
&& originals
|
||||
.iter()
|
||||
.all(|original| self.base.dominates(dominator, original))
|
||||
}
|
||||
None => self.base.dominates(dominator, node),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Immediate dominators and Euler intervals of a CFG whose blocks are named.
|
||||
///
|
||||
/// `order` is the dense numbering, entry first; `successors` names each block's targets. Both the
|
||||
@@ -238,7 +194,8 @@ pub(super) fn named_dominators<'a>(
|
||||
(named_idom, named_intervals)
|
||||
}
|
||||
|
||||
/// Immediate-dominator relation of a source CFG (entry maps to itself).
|
||||
/// Immediate-dominator relation of a source CFG (entry maps to itself), together with any
|
||||
/// pass-through blocks spliced into that CFG since it was derived.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(in crate::native) struct Dominators {
|
||||
/// Immediate dominator of each block (entry maps to itself).
|
||||
@@ -246,11 +203,39 @@ pub(in crate::native) struct Dominators {
|
||||
/// Euler intervals of the immediate-dominator tree. Dominance is interval containment, avoiding
|
||||
/// an O(tree depth) parent walk at every query in large generated CFGs.
|
||||
intervals: HashMap<String, (usize, usize)>,
|
||||
/// Each pass-through given to [`Self::record_pass_through`], resolved to the blocks of the CFG
|
||||
/// this relation was derived from. Empty unless a caller records one.
|
||||
pass_throughs: HashMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Dominators {
|
||||
/// `true` if `dominator` dominates `node` (walking the idom chain).
|
||||
/// `true` if `dominator` dominates `node`.
|
||||
///
|
||||
/// Once a pass-through has been recorded, `dominator` must be a block of the CFG this was
|
||||
/// derived from. A recorded pass-through is never the target of a later split -- split targets
|
||||
/// are chosen before any splitting starts -- so no caller has reason to ask what one dominates,
|
||||
/// and this cannot answer it.
|
||||
pub(in crate::native) fn dominates(&self, dominator: &str, node: &str) -> bool {
|
||||
if dominator == node {
|
||||
return true;
|
||||
}
|
||||
if !self.pass_throughs.is_empty() {
|
||||
debug_assert!(
|
||||
!self.pass_throughs.contains_key(dominator),
|
||||
"a pass-through is never a split target, so nothing asks what it dominates"
|
||||
);
|
||||
if let Some(originals) = self.pass_throughs.get(node) {
|
||||
return !originals.is_empty()
|
||||
&& originals
|
||||
.iter()
|
||||
.all(|original| self.dominates_derived(dominator, original));
|
||||
}
|
||||
}
|
||||
self.dominates_derived(dominator, node)
|
||||
}
|
||||
|
||||
/// Interval containment, for two blocks of the CFG this relation was derived from.
|
||||
fn dominates_derived(&self, dominator: &str, node: &str) -> bool {
|
||||
if dominator == node {
|
||||
return true;
|
||||
}
|
||||
@@ -262,6 +247,45 @@ impl Dominators {
|
||||
dom_in <= node_in && node_out <= dom_out
|
||||
}
|
||||
|
||||
/// Record that `name` was spliced in front of a block, carrying exactly `predecessors`.
|
||||
///
|
||||
/// The ownership passes repeatedly split an edge: some predecessors of a block `T` are
|
||||
/// redirected through a fresh block `S` whose only successor is `T`. Re-deriving the whole
|
||||
/// relation after each split is the obvious way to keep answering dominance questions, and it
|
||||
/// makes a pass that performs one split per construct quadratic in the block count -- the shape
|
||||
/// that breaks the per-translation time ceiling on generated shaders.
|
||||
///
|
||||
/// It is also unnecessary, twice over:
|
||||
///
|
||||
/// * **The blocks that were already there do not move.** Every entry-to-`X` path after the split
|
||||
/// is an entry-to-`X` path before it with `S` spliced in, and vice versa. The pre-existing
|
||||
/// blocks on it are the same ones, so dominance among them is exactly unchanged.
|
||||
/// * **A pass-through's own dominators follow from its predecessors.** Every path to `S` is a
|
||||
/// path to one of its predecessors plus one edge, so a block other than `S` dominates `S`
|
||||
/// exactly when it dominates all of them. Resolving predecessors that are themselves recorded
|
||||
/// pass-throughs leaves blocks of the derived CFG, which the unchanged relation answers for.
|
||||
///
|
||||
/// So a pass that only ever splices pass-throughs records each one instead of re-deriving. The
|
||||
/// recording is exact, not an approximation: [`Self::dominates`] then agrees with a relation
|
||||
/// freshly derived from the mutated block list, which is what
|
||||
/// `a_recorded_pass_through_answers_what_a_fresh_analysis_answers` checks.
|
||||
///
|
||||
/// `predecessors` is the complete set of edges redirected through it; a pass-through with no
|
||||
/// predecessors is unreachable, and is then dominated by nothing, as in
|
||||
/// [`crate::native::dominators`].
|
||||
pub(in crate::native) fn record_pass_through(&mut self, name: &str, predecessors: &[String]) {
|
||||
let mut derived = Vec::new();
|
||||
for predecessor in predecessors {
|
||||
match self.pass_throughs.get(predecessor) {
|
||||
Some(resolved) => derived.extend(resolved.iter().cloned()),
|
||||
None => derived.push(predecessor.clone()),
|
||||
}
|
||||
}
|
||||
derived.sort();
|
||||
derived.dedup();
|
||||
self.pass_throughs.insert(name.to_string(), derived);
|
||||
}
|
||||
|
||||
/// Immediate dominator of `node` (the entry, and any node mapping to itself, returns `None`).
|
||||
pub(in crate::native) fn idom(&self, node: &str) -> Option<&str> {
|
||||
self.idom
|
||||
@@ -575,7 +599,8 @@ mod tests {
|
||||
/// A recorded split must answer every dominance question the way a fresh analysis of the
|
||||
/// mutated block list answers it.
|
||||
///
|
||||
/// This is the property [`PassThroughDominance`] trades a re-analysis per split for. It holds
|
||||
/// This is the property [`Dominators::record_pass_through`] trades a re-analysis per split for.
|
||||
/// It holds
|
||||
/// because a pass-through elides out of every path through it, and it is worth checking rather
|
||||
/// than reasoning about: the failure mode is not a crash but an ownership pass quietly choosing
|
||||
/// a different set of predecessors to redirect, which surfaces much later as a structurally
|
||||
@@ -591,7 +616,7 @@ mod tests {
|
||||
blk("body", "br i1 %c2, label %h, label %m"),
|
||||
blk("m", "ret void"),
|
||||
];
|
||||
let mut dominance = PassThroughDominance::of_blocks(&blocks);
|
||||
let mut dominance = block_dominators(&blocks);
|
||||
|
||||
// Two splits in a row, the second carrying the first's pass-through: the recursive case.
|
||||
splice_pass_through(&mut blocks, "%s0", "%m", &["%h", "%body"]);
|
||||
@@ -618,7 +643,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_pass_through_with_no_predecessors_is_dominated_by_nothing() {
|
||||
let blocks = vec![blk("0", "br label %a"), blk("a", "ret void")];
|
||||
let mut dominance = PassThroughDominance::of_blocks(&blocks);
|
||||
let mut dominance = block_dominators(&blocks);
|
||||
dominance.record_pass_through("%s0", &[]);
|
||||
assert!(!dominance.dominates("%0", "%s0"));
|
||||
assert!(dominance.dominates("%s0", "%s0"));
|
||||
|
||||
@@ -49,6 +49,16 @@ impl LoopForest {
|
||||
self.doms.dominates(dominator, node)
|
||||
}
|
||||
|
||||
/// Record a pass-through spliced in front of one of this CFG's blocks.
|
||||
///
|
||||
/// Forwards to [`Dominators::record_pass_through`]; see there for why a recorded split is exact
|
||||
/// and what re-deriving instead costs. Only dominance is updated -- an acyclic pass-through in
|
||||
/// front of an existing block leaves every back edge, natural-loop body and nesting relation
|
||||
/// exactly as it was, so the loops this forest already holds stay correct.
|
||||
pub(in crate::native) fn record_pass_through(&mut self, name: &str, predecessors: &[String]) {
|
||||
self.doms.record_pass_through(name, predecessors);
|
||||
}
|
||||
|
||||
/// The natural loop headed by `header`, if any.
|
||||
pub(in crate::native) fn loop_for_header(&self, header: &str) -> Option<&NaturalLoop> {
|
||||
self.loops.iter().find(|l| l.header == header)
|
||||
|
||||
@@ -1166,7 +1166,7 @@ pub(in crate::native) fn privatize_reused_emitted_merge_targets(
|
||||
.collect::<Vec<_>>();
|
||||
// Every question this pass asks the graph is a dominance question, so it asks for dominance and
|
||||
// not for the natural-loop forest built around it.
|
||||
let mut dominance = PassThroughDominance::of_blocks(blocks);
|
||||
let mut dominance = block_dominators(blocks);
|
||||
let mut shared = claims
|
||||
.into_iter()
|
||||
.filter(|claim| {
|
||||
@@ -2217,6 +2217,14 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
} else {
|
||||
&cur_forest
|
||||
};
|
||||
// Which edges the split below will carry, read before it moves them. Only the
|
||||
// `!construct_tree_owned` arm records into `cur_forest`; the construct-tree arm
|
||||
// deliberately keeps deciding ownership from the immutable source forest.
|
||||
let carried = if construct_tree_owned {
|
||||
Vec::new()
|
||||
} else {
|
||||
header_owned_merge_predecessors(&out, synthesis_forest, &b.name, &exit_target)
|
||||
};
|
||||
let synth = if block_has_phi(&out, &exit_target) {
|
||||
synth_unique_selection_merge_phi(
|
||||
&mut out,
|
||||
@@ -2251,7 +2259,7 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
&mut counter,
|
||||
);
|
||||
} else {
|
||||
cur_forest = analyze_reusing_natural_loops(&out, &forest.loops);
|
||||
cur_forest.record_pass_through(&merge, &carried);
|
||||
if !loop_exit_selection {
|
||||
let current =
|
||||
out.iter().find(|block| block.name == b.name).unwrap_or(b);
|
||||
@@ -2348,6 +2356,12 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
} else {
|
||||
HashSet::new()
|
||||
};
|
||||
// As above: read before the split moves them, and only for the arms that record.
|
||||
let carried = if construct_tree_owned {
|
||||
Vec::new()
|
||||
} else {
|
||||
header_owned_merge_predecessors(&out, &cur_forest, &b.name, &natural)
|
||||
};
|
||||
let synth = if natural_has_phi {
|
||||
if construct_tree_owned && !explicit_no_phi_preds.is_empty() {
|
||||
synth_unique_selection_merge_phi_explicit(
|
||||
@@ -2402,11 +2416,12 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
stopped_for_growth = true;
|
||||
} else if !construct_tree_owned {
|
||||
// A unique-selection merge only splits forward edges with an acyclic
|
||||
// pass-through. Natural loops and their nesting are unchanged; recomputing
|
||||
// every loop body after each of hundreds of nested selection splits made
|
||||
// large generated CFGs revisit the whole graph quadratically. Refresh only
|
||||
// dominance for the newly inserted block and retain the proven loop forest.
|
||||
cur_forest = analyze_reusing_natural_loops(&out, &forest.loops);
|
||||
// pass-through. Natural loops and their nesting are unchanged, and so is
|
||||
// dominance among the blocks that were already there -- so record the one
|
||||
// block it added rather than re-deriving the relation. Re-deriving here made
|
||||
// large generated CFGs revisit the whole graph once per split: it was 55% of
|
||||
// every CFG rebuild the slowest corpus source performed.
|
||||
cur_forest.record_pass_through(&s, &carried);
|
||||
}
|
||||
if construct_tree_owned && !propagated_origins.is_empty() {
|
||||
for target in &headers {
|
||||
|
||||
@@ -30,10 +30,9 @@
|
||||
use super::blocks::{
|
||||
block_successors, conditional_branch_targets, index_branch_merges_by_header, synthetic_block,
|
||||
};
|
||||
use super::graph::PassThroughDominance;
|
||||
use super::graph::block_dominators;
|
||||
use super::loopforest::{
|
||||
analyze, analyze_reusing_natural_loops, break_aware_selection_merges, selection_merges,
|
||||
LoopForest, Restructure,
|
||||
analyze, break_aware_selection_merges, selection_merges, LoopForest, Restructure,
|
||||
};
|
||||
use super::structured_order::{structured_order, structured_order_terminal};
|
||||
// Re-bind the sibling module names so the responsibility bands can reach them via `super::`
|
||||
|
||||
@@ -578,14 +578,8 @@ pub(in crate::native) fn synth_unique_selection_merge(
|
||||
natural: &str,
|
||||
counter: &mut usize,
|
||||
) -> Option<String> {
|
||||
let preds: HashSet<String> = blocks
|
||||
.iter()
|
||||
.filter(|b| {
|
||||
b.role != BlockRole::ConstructTreeRoute
|
||||
&& block_successors(b).iter().any(|s| s == natural)
|
||||
&& forest.dominates(header, &b.name)
|
||||
})
|
||||
.map(|b| b.name.clone())
|
||||
let preds: HashSet<String> = header_owned_merge_predecessors(blocks, forest, header, natural)
|
||||
.into_iter()
|
||||
.collect();
|
||||
if preds.is_empty() {
|
||||
return None;
|
||||
@@ -627,18 +621,38 @@ pub(in crate::native) fn synth_unique_selection_merge_phi(
|
||||
natural: &str,
|
||||
counter: &mut usize,
|
||||
) -> Option<String> {
|
||||
let preds = blocks
|
||||
.iter()
|
||||
.filter(|b| {
|
||||
b.role != BlockRole::ConstructTreeRoute
|
||||
&& block_successors(b).iter().any(|s| s == natural)
|
||||
&& forest.dominates(header, &b.name)
|
||||
})
|
||||
.map(|b| b.name.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let preds = header_owned_merge_predecessors(blocks, forest, header, natural);
|
||||
synth_unique_selection_merge_phi_explicit(blocks, &preds, natural, &HashSet::new(), counter)
|
||||
}
|
||||
|
||||
/// The predecessors of `natural` that a selection headed by `header` owns, in block order.
|
||||
///
|
||||
/// One rule, in one place, because it is also the answer to "which edges did that split carry?" --
|
||||
/// a caller keeping an incremental dominance relation across splits
|
||||
/// ([`crate::native::cfg::graph::Dominators::record_pass_through`]) has to record exactly this set,
|
||||
/// and a second copy of the rule would be a second thing to keep in step.
|
||||
///
|
||||
/// Construct-tree gateways are excluded: a route block stands for control that entered the region
|
||||
/// from outside, so redirecting it would move edges the header does not own.
|
||||
pub(in crate::native) fn header_owned_merge_predecessors(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
header: &str,
|
||||
natural: &str,
|
||||
) -> Vec<String> {
|
||||
blocks
|
||||
.iter()
|
||||
.filter(|block| {
|
||||
block.role != BlockRole::ConstructTreeRoute
|
||||
&& block_successors(block)
|
||||
.iter()
|
||||
.any(|target| target == natural)
|
||||
&& forest.dominates(header, &block.name)
|
||||
})
|
||||
.map(|block| block.name.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Phi-aware unique-merge synthesis over an explicit set of owned predecessors.
|
||||
///
|
||||
/// A construct-tree gateway can sit between an owned predecessor and the shared natural merge. In
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
//! A translation must not re-derive the whole function once per construct.
|
||||
//!
|
||||
//! The two hard per-attempt budgets in `AGENTS.md` -- 20 seconds and 500 MiB -- are broken by
|
||||
//! quadratic terms, not by slow loop bodies, and the two quadratics an analysis can be need
|
||||
//! different instruments to see. A quadratic *representation* shows up in peak memory, which is what
|
||||
//! `tests/bounded_growth.rs` watches. A quadratic *repetition* does not: each table is linear and
|
||||
//! short-lived, so the footprint stays flat while the wall clock goes up. What it does move is the
|
||||
//! number of times the whole function gets analyzed, and that count is exact, deterministic, and the
|
||||
//! same on every machine -- so this measures it directly rather than through a proxy.
|
||||
//!
|
||||
//! Two of these have shipped. The merge-ownership pass re-derived the function's dominance after
|
||||
//! every split it made, and the selection structurizer re-derived dominance and the loop forest
|
||||
//! after each pass-through it inserted. Both now record the one block they added
|
||||
//! ([`crate::native::cfg::graph::Dominators::record_pass_through`]) instead. The kernel below
|
||||
//! reaches the structurizer's; the merge-ownership pass's is the one
|
||||
//! `tests/bounded_growth.rs` catches, in its total-allocation bound.
|
||||
|
||||
use crate::native::cfg::graph::cfg_builds_during;
|
||||
use crate::passes::Stage;
|
||||
|
||||
/// A kernel with `groups` selections inside one loop, each able to break out to the loop's exit.
|
||||
///
|
||||
/// The exit is therefore the natural merge that all `groups` selection headers claim at once, and
|
||||
/// the structurizer gives each of them a private merge by splicing a pass-through in front of it.
|
||||
/// That is the shape whose per-split re-derivation this file exists to keep out: the splits happen
|
||||
/// one after another on the same block, so the cost of re-deriving is multiplied by the number of
|
||||
/// selections. Each group loads a distinct buffer word so nothing folds away.
|
||||
fn loop_exit_selection_chain(groups: usize) -> String {
|
||||
let mut out = String::from(
|
||||
r#"target triple = "air64_v28-apple-macosx26.5.0"
|
||||
|
||||
%Words = type { [1024 x i32] }
|
||||
|
||||
define void @k(ptr addrspace(1) %out) {
|
||||
entry:
|
||||
br label %loop
|
||||
|
||||
loop:
|
||||
%i = phi i32 [ 0, %entry ], [ %inext, %latch ]
|
||||
br label %h0
|
||||
"#,
|
||||
);
|
||||
for group in 0..groups {
|
||||
let word = group % 1024;
|
||||
out.push_str(&format!(
|
||||
"h{group}:
|
||||
%p{group} = getelementptr inbounds %Words, ptr addrspace(1) %out, i64 0, i32 0, i64 {word}
|
||||
%v{group} = load i32, ptr addrspace(1) %p{group}
|
||||
%c{group} = icmp sgt i32 %v{group}, 0
|
||||
br i1 %c{group}, label %t{group}, label %h{next}
|
||||
t{group}:
|
||||
%tv{group} = add i32 %v{group}, 1
|
||||
%tc{group} = icmp sgt i32 %tv{group}, 3
|
||||
br i1 %tc{group}, label %exit, label %h{next}
|
||||
",
|
||||
next = group + 1
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
r#"h{groups}:
|
||||
br label %latch
|
||||
|
||||
latch:
|
||||
%inext = add i32 %i, 1
|
||||
%done = icmp slt i32 %inext, 16
|
||||
br i1 %done, label %loop, label %exit
|
||||
|
||||
exit:
|
||||
ret void
|
||||
}}
|
||||
|
||||
!air.kernel = !{{!0}}
|
||||
!0 = !{{ptr @k, !1, !2}}
|
||||
!1 = !{{}}
|
||||
!2 = !{{!3}}
|
||||
!3 = !{{i32 0, !"air.buffer", !"air.buffer_size", i32 4096, !"air.struct_type_info", !4, !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"Words", !"air.arg_name", !"out"}}
|
||||
!4 = !{{i32 0, i32 4096, i32 0, !"uint", !"v0"}}
|
||||
"#
|
||||
));
|
||||
out
|
||||
}
|
||||
|
||||
/// Selections in the measured kernel. Two blocks each, plus the entry, loop header, the block that
|
||||
/// falls out of the chain, the latch and the exit -- seventeen blocks at six.
|
||||
const GROUPS: usize = 6;
|
||||
|
||||
/// The most source CFGs this kernel may be worth.
|
||||
///
|
||||
/// Measured at 871. Restoring the structurizer's per-split re-derivation puts it at 2209; this sits
|
||||
/// between them with room on both sides. The count is deterministic -- the same six numbers come back on every
|
||||
/// run -- so a failure here is a real change in how much whole-function analysis a translation does,
|
||||
/// not noise. That is a decision worth making deliberately: raising this bound is fine when a new
|
||||
/// analysis genuinely earns its place, and is the wrong answer when a maintained result was replaced
|
||||
/// by a re-derived one.
|
||||
const MAX_CFG_BUILDS: usize = 1400;
|
||||
|
||||
#[test]
|
||||
fn a_shared_loop_exit_is_not_re_analyzed_once_per_split() {
|
||||
let scratch = std::env::temp_dir().join(format!(
|
||||
"m2v_bounded_work_{}_{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
std::fs::create_dir_all(&scratch).expect("scratch directory");
|
||||
let source = loop_exit_selection_chain(GROUPS);
|
||||
let (translated, builds) =
|
||||
cfg_builds_during(|| crate::translate_sanitized_native(&source, Stage::Kernel, &scratch));
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
|
||||
translated.expect("the generated kernel translates");
|
||||
assert!(
|
||||
builds <= MAX_CFG_BUILDS,
|
||||
"translating a {GROUPS}-selection kernel built {builds} source CFGs (bound {MAX_CFG_BUILDS}); \
|
||||
some pass is deriving the whole function again after a graph edit instead of maintaining \
|
||||
what it already had, which is how the 20-second per-attempt ceiling gets broken"
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use crate::spirv_module::{load_bytes, Module};
|
||||
use spirv::{Decoration, Op, StorageClass, Word};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
mod bounded_work;
|
||||
mod buffers;
|
||||
mod control_flow;
|
||||
mod interface;
|
||||
|
||||
Reference in new issue
Block a user