Leave one dominator computation in the crate, not three

The owned-CFG check, the relooper's loop-header scan, and (as of the previous
commit) the nesting structurizer each ran Cooper-Harvey-Kennedy over reverse
postorder and numbered the result into Euler intervals. Three copies of one
algorithm is how the structurizer ended up with dominator *sets* in the first
place: nobody writing it had a shared implementation to reach for.

Moved the index-based core out of `owned_cfg` into `native::dominators`, which
is now its only home, and pointed the structurizer's shape layer at it through
a label-to-index map it can build in one pass. `owned_cfg` and `rewrites` are a
pure move; the shape layer loses the private copy added in fdece24.

The core carries the oracle test the duplicates never had:
`the_intervals_answer_exactly_what_the_dominator_sets_answer` runs the dense
fixpoint as a test-only reference and cross-checks every ordered block pair on
nine shapes -- straight line, diamond, loop with exit, nested loops, self loop,
irreducible pair, unreachable block, rejoining paths, single block.
`the_tables_hold_one_entry_per_block` pins the linear representation.

Verified: full test suite, clippy, rustdoc, and byte-identical output over a
640-source corpus sample (0 of 640 differ).
This commit is contained in:
Anees Iqbal committed 2026-08-31 17:37:54 +03:00
1 parent fdece243c0
commit db01510465
5 files changed
+320 -254

No files matched your search

+273
View File
@@ -0,0 +1,273 @@
//! The one dominator computation in this crate.
//!
//! Cooper-Harvey-Kennedy iterative immediate dominators over reverse postorder, numbered into
//! Euler intervals so a dominance query is two integer comparisons rather than a walk up the tree.
//!
//! It works on dense block indices, `0` being the entry, because every caller already has (or can
//! cheaply build) that shape: the owned-CFG check indexes blocks positionally, the relooper indexes
//! them positionally, and the nesting structurizer maps its labels through a table it builds anyway.
//! Keeping one implementation is the point. The obvious alternative -- a dominator *set* per block --
//! is quadratic in the block count, and generated shaders reach block counts where that alone costs
//! hundreds of megabytes; the structurizer shipped that form once and it cost more memory than the
//! whole rest of the translation.
/// The reverse adjacency of a dense successor table.
pub(in crate::native) fn build_predecessors(successors: &[Vec<usize>]) -> Vec<Vec<usize>> {
let mut predecessors = vec![Vec::new(); successors.len()];
for (source, targets) in successors.iter().enumerate() {
for target in targets {
predecessors[*target].push(source);
}
}
predecessors
}
/// Reachability, dominance intervals, and immediate dominators of a dense block graph.
///
/// Returns `(reachable, intervals, idom)`, each indexed by block. `reachable` is what a depth-first
/// walk from block `0` reaches; `intervals` and `idom` are `None` for everything it does not.
pub(in crate::native) fn dominance(
successors: &[Vec<usize>],
predecessors: &[Vec<usize>],
) -> (Vec<bool>, Vec<Option<(usize, usize)>>, Vec<Option<usize>>) {
let count = successors.len();
if count == 0 {
return (Vec::new(), Vec::new(), Vec::new());
}
let mut visited = vec![false; count];
let mut postorder = Vec::with_capacity(count);
let mut stack = vec![(0usize, 0usize)];
visited[0] = true;
while let Some((node, cursor)) = stack.last_mut() {
if *cursor < successors[*node].len() {
let child = successors[*node][*cursor];
*cursor += 1;
if !visited[child] {
visited[child] = true;
stack.push((child, 0));
}
} else {
postorder.push(*node);
stack.pop();
}
}
let mut rpo = postorder;
rpo.reverse();
let mut rpo_rank = vec![usize::MAX; count];
for (rank, block) in rpo.iter().enumerate() {
rpo_rank[*block] = rank;
}
let mut idom = vec![None; count];
idom[0] = Some(0);
loop {
let mut changed = false;
for &node in rpo.iter().skip(1) {
let mut defined = predecessors[node]
.iter()
.copied()
.filter(|predecessor| idom[*predecessor].is_some());
let Some(mut candidate) = defined.next() else {
continue;
};
for predecessor in defined {
candidate = intersect(candidate, predecessor, &idom, &rpo_rank);
}
if idom[node] != Some(candidate) {
idom[node] = Some(candidate);
changed = true;
}
}
if !changed {
break;
}
}
let mut children = vec![Vec::new(); count];
for (node, parent) in idom.iter().enumerate() {
if let Some(parent) = parent.filter(|parent| *parent != node) {
children[parent].push(node);
}
}
let mut intervals: Vec<Option<(usize, usize)>> = vec![None; count];
let mut clock = 0usize;
let mut stack = vec![(0usize, false)];
while let Some((node, exiting)) = stack.pop() {
if exiting {
let start = intervals[node].expect("reachable dominator entered").0;
intervals[node] = Some((start, clock));
clock += 1;
} else {
intervals[node] = Some((clock, clock));
clock += 1;
stack.push((node, true));
stack.extend(children[node].iter().rev().map(|child| (*child, false)));
}
}
(visited, intervals, idom)
}
/// The meet of two nodes in the partially built dominator tree (the CHK `intersect`).
///
/// Both fingers only ever move to a strictly earlier reverse-postorder position, so the walk
/// terminates.
fn intersect(
mut left: usize,
mut right: usize,
idom: &[Option<usize>],
rpo_rank: &[usize],
) -> usize {
while left != right {
while rpo_rank[left] > rpo_rank[right] {
left = idom[left].expect("defined dominator");
}
while rpo_rank[right] > rpo_rank[left] {
right = idom[right].expect("defined dominator");
}
}
left
}
/// Whether `dominator` dominates `node`, given the Euler intervals from [`dominance`].
///
/// Reflexive, and false for either block being unreachable -- an unreachable block dominates
/// nothing and is dominated by nothing.
pub(in crate::native) fn dominates_interval(
dominance: &[Option<(usize, usize)>],
dominator: usize,
node: usize,
) -> bool {
let (Some((dom_in, dom_out)), Some((node_in, node_out))) =
(dominance[dominator], dominance[node])
else {
return false;
};
dom_in <= node_in && node_out <= dom_out
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
/// The textbook dominator sets, by fixpoint. This is the definition [`dominance`] has to agree
/// with; it lives here rather than in the graph because it is quadratic in the block count and
/// no production path can afford it.
fn dense_dominators(successors: &[Vec<usize>]) -> Vec<Option<BTreeSet<usize>>> {
let predecessors = build_predecessors(successors);
let mut reachable = vec![false; successors.len()];
let mut stack = vec![0usize];
if successors.is_empty() {
return Vec::new();
}
reachable[0] = true;
while let Some(node) = stack.pop() {
for target in &successors[node] {
if !reachable[*target] {
reachable[*target] = true;
stack.push(*target);
}
}
}
let all = (0..successors.len())
.filter(|node| reachable[*node])
.collect::<BTreeSet<_>>();
let mut dominators = (0..successors.len())
.map(|node| reachable[node].then(|| all.clone()))
.collect::<Vec<_>>();
dominators[0] = Some(BTreeSet::from([0]));
let mut changed = true;
while changed {
changed = false;
for node in all.iter().copied().filter(|node| *node != 0) {
let mut incoming = predecessors[node]
.iter()
.filter(|predecessor| reachable[**predecessor])
.filter_map(|predecessor| dominators[*predecessor].as_ref());
let Some(first) = incoming.next() else {
continue;
};
let mut next = first.clone();
for other in incoming {
next.retain(|candidate| other.contains(candidate));
}
next.insert(node);
if dominators[node].as_ref() != Some(&next) {
dominators[node] = Some(next);
changed = true;
}
}
}
dominators
}
/// Every graph shape the translator hands this: straight line, diamond, loops, a self loop, an
/// irreducible pair, unreachable blocks, and a block with no successors at all.
fn shapes() -> Vec<(&'static str, Vec<Vec<usize>>)> {
vec![
("single block", vec![vec![]]),
("straight line", vec![vec![1], vec![2], vec![]]),
("diamond", vec![vec![1, 2], vec![3], vec![3], vec![]]),
(
"loop with an exit",
vec![vec![1], vec![2, 3], vec![1], vec![]],
),
(
"nested loops",
vec![vec![1], vec![2], vec![2, 3], vec![1, 4], vec![]],
),
("self loop", vec![vec![0, 1], vec![]]),
("irreducible pair", vec![vec![1, 2], vec![2], vec![1]]),
("unreachable block", vec![vec![1], vec![], vec![1]]),
(
"two paths rejoining under a loop",
vec![vec![1, 2], vec![3], vec![3], vec![4, 5], vec![3], vec![]],
),
]
}
#[test]
fn the_intervals_answer_exactly_what_the_dominator_sets_answer() {
for (what, successors) in shapes() {
let dense = dense_dominators(&successors);
let (reachable, intervals, _) =
dominance(&successors, &build_predecessors(&successors));
for node in 0..successors.len() {
assert_eq!(
intervals[node].is_some(),
reachable[node],
"{what}: block {node} is numbered iff it is reachable"
);
for dominator in 0..successors.len() {
let expected = dense[node]
.as_ref()
.is_some_and(|set| set.contains(&dominator));
assert_eq!(
dominates_interval(&intervals, dominator, node),
expected,
"{what}: disagreement on whether {dominator} dominates {node}"
);
}
}
}
}
/// The representation is one number per block, three ways -- not a set per block. A dominator
/// set per block is quadratic, and shaders reach block counts where that alone costs more than
/// the whole per-translation memory budget.
#[test]
fn the_tables_hold_one_entry_per_block() {
for (what, successors) in shapes() {
let (reachable, intervals, idom) =
dominance(&successors, &build_predecessors(&successors));
assert_eq!(reachable.len(), successors.len(), "{what}");
assert_eq!(intervals.len(), successors.len(), "{what}");
assert_eq!(idom.len(), successors.len(), "{what}");
}
}
#[test]
fn an_empty_graph_has_no_dominators() {
let (reachable, intervals, idom) = dominance(&[], &[]);
assert!(reachable.is_empty() && intervals.is_empty() && idom.is_empty());
}
}
+1
View File
@@ -12,6 +12,7 @@ mod cfg_testkit;
mod constfold;
// Read-only typed-SSA soundness / carrier-comparison / reject-census diagnostics (no emission path).
mod diagnostics;
mod dominators;
mod emitter;
// Emitter entry points for the primary and structurally selected alternate representations.
mod emit_tiers;
+1 -116
View File
@@ -5,6 +5,7 @@
//! later rewrite cannot serialize a module that relies on `spirv-val` to discover broken ownership
//! or typing.
use super::dominators::{build_predecessors, dominance, dominates_interval};
use crate::spirv_module::{is_block_terminator, Function, Instruction, Operand};
use spirv::{Op, Word};
use std::collections::{HashMap, HashSet};
@@ -813,15 +814,6 @@ impl OwnedCfg {
}
}
fn dominates_interval(dominance: &[Option<(usize, usize)>], dominator: usize, node: usize) -> bool {
let (Some((dom_in, dom_out)), Some((node_in, node_out))) =
(dominance[dominator], dominance[node])
else {
return false;
};
dom_in <= node_in && node_out <= dom_out
}
fn operand_label(
operand: Option<&Operand>,
labels: &HashMap<Word, usize>,
@@ -1069,96 +1061,6 @@ pub(super) fn owned_function_construction_error(
cfg.check_structure(function).err()
}
fn build_predecessors(successors: &[Vec<usize>]) -> Vec<Vec<usize>> {
let mut predecessors = vec![Vec::new(); successors.len()];
for (source, targets) in successors.iter().enumerate() {
for target in targets {
predecessors[*target].push(source);
}
}
predecessors
}
pub(super) fn dominance(
successors: &[Vec<usize>],
predecessors: &[Vec<usize>],
) -> (Vec<bool>, Vec<Option<(usize, usize)>>, Vec<Option<usize>>) {
let count = successors.len();
if count == 0 {
return (Vec::new(), Vec::new(), Vec::new());
}
let mut visited = vec![false; count];
let mut postorder = Vec::with_capacity(count);
let mut stack = vec![(0usize, 0usize)];
visited[0] = true;
while let Some((node, cursor)) = stack.last_mut() {
if *cursor < successors[*node].len() {
let child = successors[*node][*cursor];
*cursor += 1;
if !visited[child] {
visited[child] = true;
stack.push((child, 0));
}
} else {
postorder.push(*node);
stack.pop();
}
}
let mut rpo = postorder;
rpo.reverse();
let mut rpo_rank = vec![usize::MAX; count];
for (rank, block) in rpo.iter().enumerate() {
rpo_rank[*block] = rank;
}
let mut idom = vec![None; count];
idom[0] = Some(0);
loop {
let mut changed = false;
for &node in rpo.iter().skip(1) {
let mut defined = predecessors[node]
.iter()
.copied()
.filter(|predecessor| idom[*predecessor].is_some());
let Some(mut candidate) = defined.next() else {
continue;
};
for predecessor in defined {
candidate = intersect(candidate, predecessor, &idom, &rpo_rank);
}
if idom[node] != Some(candidate) {
idom[node] = Some(candidate);
changed = true;
}
}
if !changed {
break;
}
}
let mut children = vec![Vec::new(); count];
for (node, parent) in idom.iter().enumerate() {
if let Some(parent) = parent.filter(|parent| *parent != node) {
children[parent].push(node);
}
}
let mut intervals: Vec<Option<(usize, usize)>> = vec![None; count];
let mut clock = 0usize;
let mut stack = vec![(0usize, false)];
while let Some((node, exiting)) = stack.pop() {
if exiting {
let start = intervals[node].expect("reachable dominator entered").0;
intervals[node] = Some((start, clock));
clock += 1;
} else {
intervals[node] = Some((clock, clock));
clock += 1;
stack.push((node, true));
stack.extend(children[node].iter().rev().map(|child| (*child, false)));
}
}
(visited, intervals, idom)
}
fn post_dominance(
structural_successors: &[Vec<usize>],
branch_successors: &[Vec<usize>],
@@ -1284,23 +1186,6 @@ fn dominators_precede_blocks(reachable: &[bool], idom: &[Option<usize>]) -> bool
})
}
fn intersect(
mut left: usize,
mut right: usize,
idom: &[Option<usize>],
rpo_rank: &[usize],
) -> usize {
while left != right {
while rpo_rank[left] > rpo_rank[right] {
left = idom[left].expect("defined dominator");
}
while rpo_rank[right] > rpo_rank[left] {
right = idom[right].expect("defined dominator");
}
}
left
}
fn referenced_ids(instruction: &Instruction) -> impl Iterator<Item = Word> + '_ {
instruction
.result_type
+44 -137
View File
@@ -125,169 +125,76 @@ impl Graph {
true
}
/// The reachable subgraph in reverse postorder, entry first.
/// The dominator tree of the reachable subgraph.
///
/// Reverse postorder is what makes the dominator iteration below converge in a couple of passes
/// instead of one pass per graph depth: every node's predecessors along a forward edge are
/// already final when it is visited.
fn reverse_postorder(&self) -> Vec<Label> {
let mut order = Vec::new();
let mut seen = BTreeSet::new();
if !self.successors.contains_key(&self.entry) {
return order;
}
seen.insert(self.entry);
let mut stack = vec![(self.entry, 0usize)];
while let Some((node, index)) = stack.pop() {
let targets = self.succ(node);
if index < targets.len() {
stack.push((node, index + 1));
let target = targets[index];
if self.successors.contains_key(&target) && seen.insert(target) {
stack.push((target, 0));
}
} else {
order.push(node);
}
}
order.reverse();
order
}
/// The dominator tree of the reachable subgraph, by the Cooper-Harvey-Kennedy iteration.
/// Dense block indices are what [`crate::native::dominators`] speaks, and the label ordering
/// this graph already keeps makes the translation a single pass each way.
fn dominators(&self) -> Dominators {
let order = self.reverse_postorder();
if order.is_empty() {
return Dominators::default();
}
let position = order
.iter()
let index = self
.successors
.keys()
.copied()
.enumerate()
.map(|(index, label)| (*label, index))
.collect::<BTreeMap<_, _>>();
// Indexed by reverse-postorder position, so a dominator always sits at a lower index than
// the node it dominates -- which is what lets `intersect` walk two fingers to their meet.
let mut idom: Vec<Option<usize>> = vec![None; order.len()];
idom[0] = Some(0);
let mut changed = true;
while changed {
changed = false;
for index in 1..order.len() {
let mut candidate: Option<usize> = None;
for predecessor in self.pred(order[index]) {
let Some(&predecessor) = position.get(predecessor) else {
continue;
};
if idom[predecessor].is_none() {
continue;
}
candidate = Some(match candidate {
None => predecessor,
Some(current) => intersect(current, predecessor, &idom),
});
}
if candidate.is_some() && idom[index] != candidate {
idom[index] = candidate;
changed = true;
}
}
.map(|(index, label)| (label, index))
.collect::<BTreeMap<Label, usize>>();
let Some(&entry) = index.get(&self.entry) else {
return Dominators::default();
};
// `dominance` walks from block 0, so the entry has to be block 0. Swapping it with whatever
// sorted first is cheaper than renumbering, and the rest of the mapping is unaffected.
let swap = |slot: usize| match slot {
0 => entry,
slot if slot == entry => 0,
slot => slot,
};
let mut successors = vec![Vec::new(); index.len()];
for (label, targets) in &self.successors {
successors[swap(index[label])] = targets
.iter()
.filter_map(|target| index.get(target).map(|target| swap(*target)))
.collect();
}
Dominators::from_tree(&order, &idom)
}
}
/// The meet of two nodes in the partially built dominator tree: their deepest common dominator.
///
/// Both fingers only ever move to a strictly lower reverse-postorder position, so the walk
/// terminates. An index whose parent link is missing or does not decrease cannot occur once the
/// iteration is seeded from the entry; treating it as the entry keeps the walk finite and only ever
/// weakens the dominance the caller concludes, which is the safe direction.
fn intersect(mut left: usize, mut right: usize, idom: &[Option<usize>]) -> usize {
while left != right {
while left > right {
match idom[left] {
Some(parent) if parent < left => left = parent,
_ => return 0,
}
}
while right > left {
match idom[right] {
Some(parent) if parent < right => right = parent,
_ => return 0,
}
let predecessors = crate::native::dominators::build_predecessors(&successors);
let (_, intervals, _) = crate::native::dominators::dominance(&successors, &predecessors);
Dominators {
block: index
.into_iter()
.map(|(label, slot)| (label, swap(slot)))
.collect(),
intervals,
}
}
left
}
/// Which blocks dominate which, over a graph's reachable subgraph.
///
/// One pre-order interval per block, not a dominator *set* per block. The set form is quadratic in
/// the block count: a 6301-block function -- an ordinary size for a generated convolution kernel --
/// One Euler interval per block, not a dominator *set* per block. The set form is quadratic in the
/// block count: a 6301-block function -- an ordinary size for a generated convolution kernel --
/// materializes about 40 million set entries, roughly 400 MiB, to answer the single question
/// [`Graph::is_reducible`] asks of it. That alone exceeds the whole per-translation memory budget.
/// The interval form is linear, and answers the same question with two integer comparisons.
#[derive(Default)]
pub(super) struct Dominators {
/// `(enter, exit)` of each block in a pre-order walk of the dominator tree. `a` dominates `b`
/// exactly when `b`'s interval nests inside `a`'s.
interval: BTreeMap<Label, (u32, u32)>,
/// The dense block index each label was given.
block: BTreeMap<Label, usize>,
intervals: Vec<Option<(usize, usize)>>,
}
impl Dominators {
/// Number the dominator tree described by `idom` (parent links by reverse-postorder position).
fn from_tree(order: &[Label], idom: &[Option<usize>]) -> Self {
let mut children: Vec<Vec<usize>> = vec![Vec::new(); order.len()];
for (index, parent) in idom.iter().enumerate() {
match parent {
Some(parent) if *parent != index => children[*parent].push(index),
_ => {}
}
}
let mut interval = BTreeMap::new();
let mut clock = 0u32;
// `Descend` numbers a node on the way in, `Close` on the way back out; an explicit stack
// rather than recursion because the tree is as deep as the function is long.
enum Step {
Descend(usize),
Close(usize),
}
let mut stack = vec![Step::Descend(0)];
let mut enter = vec![0u32; order.len()];
while let Some(step) = stack.pop() {
match step {
Step::Descend(index) => {
enter[index] = clock;
clock += 1;
stack.push(Step::Close(index));
for child in children[index].iter().rev() {
stack.push(Step::Descend(*child));
}
}
Step::Close(index) => {
interval.insert(order[index], (enter[index], clock));
clock += 1;
}
}
}
Self { interval }
}
/// Whether `ancestor` dominates `node`. Reflexive, and false for any block the reachable
/// subgraph does not contain -- which is what the retreating-edge check wants: an edge whose
/// source is unreachable was never on the walk that asks.
pub(super) fn dominates(&self, ancestor: Label, node: Label) -> bool {
let (Some(ancestor), Some(node)) = (self.interval.get(&ancestor), self.interval.get(&node))
let (Some(&ancestor), Some(&node)) = (self.block.get(&ancestor), self.block.get(&node))
else {
return false;
};
ancestor.0 <= node.0 && node.1 <= ancestor.1
crate::native::dominators::dominates_interval(&self.intervals, ancestor, node)
}
/// How many numbers the tree holds, which is what the linear bound is about.
/// How many blocks the tree numbers, which is what the linear bound is about.
#[cfg(test)]
pub(super) fn len(&self) -> usize {
self.interval.len()
pub(super) fn reached(&self) -> usize {
self.intervals.iter().filter(|slot| slot.is_some()).count()
}
}
@@ -866,6 +773,6 @@ mod tests {
let blocks = graph.reachable().len();
assert_eq!(blocks, (diamonds * 4 + 1) as usize);
assert!(graph.is_reducible());
assert_eq!(graph.dominators().len(), blocks);
assert_eq!(graph.dominators().reached(), blocks);
}
}
+1 -1
View File
@@ -1129,7 +1129,7 @@ pub(crate) fn function_has_unowned_backedge(function: &crate::spirv_module::Func
predecessors[successor].push(block);
}
}
let (reachable, dominance, _) = super::owned_cfg::dominance(&successors, &predecessors);
let (reachable, dominance, _) = super::dominators::dominance(&successors, &predecessors);
let loop_headers = function
.blocks
.iter()