From d862cd11eeb8a0fc0df1be503ad5283b1c24a303 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 31 Aug 2026 20:02:54 +0300 Subject: [PATCH] Key the structurizer's cached analyses on a block revision, not on remembering to invalidate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `forest_loop_merges` caches a `LoopForest` and a selection-merge map across the loop headers it plans, because deriving them once per graph edit instead of once per header is the difference between a bounded translation and a quadratic one. It invalidated that cache by hand: eight separate `collision_cache = None` assignments, one per mutation site, plus a `mutated` flag threaded through the collision branch to drive two more. Every future edit that adds a mutation has to remember to add a ninth, and a missing one is invisible — the stale forest still answers every query, just about the graph as it was. `RewriteBlocks` owns the block list and a revision only it can advance; `AnalysisCache` remembers the revision an analysis came from and re-derives exactly when it no longer matches. The eight assignments and the `mutated` flag are gone, and there is nothing left to forget. `rewrite` advances the revision only when a rewrite commits, which is sound because a decline leaves the list untouched (02c3f9e). Debug builds check that instead of trusting it: a rewrite that declines with the list edited fails at that call rather than at whatever wrong answer the poisoned cache produces later. `edit` — for a rewrite that does not report whether it fired — advances unconditionally. The reuse this buys was previously argued rather than checked. The collision test re-derived the forest that the top of the same iteration had just derived; they are the same forest because the only edit between them is on a path that `continue`s, which is a claim about code shape that nothing enforced. Now they are the same forest because the revision is the same. Verified: 2880 corpus sources byte-identical against eac559d. Slowest source (`fc78a004`) 2.81s -> 2.56s, and 2.77s at eac559d, so the analysis this recovers more than pays for the staged copy 02c3f9e added. `bounded_work`'s kernel: 871 -> 867 source CFGs (it reaches the selection structurizer, not this cache; comment updated). `cargo fmt --all --check`, clippy `-D warnings`, `RUSTDOCFLAGS='-D warnings' cargo doc`, `cargo test -p metal2vulkan` debug and release, `cargo test -p metal2vulkan-validation`. --- src/native/cfg/structured_emit/loop_merges.rs | 213 +++++++++--------- src/native/cfg/structured_emit/rewrite.rs | 208 +++++++++++++++++ src/native/tests/bounded_work.rs | 2 +- 3 files changed, 319 insertions(+), 104 deletions(-) diff --git a/src/native/cfg/structured_emit/loop_merges.rs b/src/native/cfg/structured_emit/loop_merges.rs index 925debffb..4b1943cd6 100644 --- a/src/native/cfg/structured_emit/loop_merges.rs +++ b/src/native/cfg/structured_emit/loop_merges.rs @@ -1426,22 +1426,27 @@ pub(in crate::native) fn forest_loop_merges( .map(|loop_info| (loop_info.body.len(), loop_info.header.clone())) .collect::>(); loop_headers.sort(); - let mut out_blocks = blocks.to_vec(); + let mut out_blocks = RewriteBlocks::new(blocks.to_vec()); let mut merges = HashMap::new(); let mut split_counter = 0usize; - let mut collision_cache: Option<(LoopForest, HashMap)> = None; + // Both analyses are keyed on the block revision, so each is derived once per graph state: + // the forest for the header being planned is the same forest the collision check needs, and + // a header that changes nothing does not pay for either again. + let mut forest_cache = AnalysisCache::default(); + let mut selection_cache = AnalysisCache::default(); // Inner ownership must be materialized first. Recompute the current forest and this header's plan // after every nested transform so an enclosing loop sees synthesized inner dispatch/backedge // blocks as part of its body and owns their exits too; reordering a stale source plan is insufficient. for (_, header) in loop_headers { - let forest = analyze(&out_blocks); + let forest = forest_cache.get(&out_blocks, analyze); // A bare unreachable target terminates the invocation in-place; unlike a live continuation it // does not need to be selected as the loop's unique merge. Keep it in the CFG/construct, but // exclude it from merge-candidate cardinality after proving the exact terminal shape. let terminal_exits = out_blocks + .get() .iter() - .filter(|block| block_ends_in_unreachable(&out_blocks, &block.name)) + .filter(|block| block_ends_in_unreachable(out_blocks.get(), &block.name)) .map(|block| block.name.clone()) .collect::>(); let current_plans = forest.structured_plan_ignoring_exits(&terminal_exits); @@ -1456,10 +1461,9 @@ pub(in crate::native) fn forest_loop_merges( if plan.restructure.as_slice() == [Restructure::NoExit] && plan.continue_block.as_deref() == Some(plan.header.as_str()) { - if let Some((merge, continue_target)) = - synth_noexit_self_latch(&mut out_blocks, &plan.header, &mut split_counter) + if let Some((merge, continue_target)) = out_blocks + .rewrite(|blocks| synth_noexit_self_latch(blocks, &plan.header, &mut split_counter)) { - collision_cache = None; merges.insert( plan.header.clone(), LoopMergeInfo { @@ -1494,14 +1498,10 @@ pub(in crate::native) fn forest_loop_merges( // its in-loop exit edges to `merge_block` through a fresh pass-through (with phi surgery // when `merge_block` carries a phi), leaving the original block as the enclosing // selection's merge. This is the dominant `cond-phi-shared/loop-role` frontier shape. - if collision_cache.is_none() { - let det_forest = analyze(&out_blocks); - let det_selection_merges = selection_merges(&out_blocks, &det_forest); - collision_cache = Some((det_forest, det_selection_merges)); - } - let (det_forest, det_selection_merges) = collision_cache.as_ref().unwrap(); + let det_selection_merges = + selection_cache.get(&out_blocks, |blocks| selection_merges(blocks, forest)); let collides = merge_collides_with_outer_selection_from( - det_forest, + forest, det_selection_merges, &plan.header, &merge_block, @@ -1514,29 +1514,31 @@ pub(in crate::native) fn forest_loop_merges( plan.restructure, merge_block, collides, - block_has_phi(&out_blocks, &merge_block), + block_has_phi(out_blocks.get(), &merge_block), ); } - let mut mutated = false; let merge_block = if collides { - let split = if block_has_phi(&out_blocks, &merge_block) { - split_phi_overlap( - &mut out_blocks, - det_forest, - &plan.header, - &merge_block, - &mut split_counter, - ) + let split = if block_has_phi(out_blocks.get(), &merge_block) { + out_blocks.rewrite(|blocks| { + split_phi_overlap( + blocks, + forest, + &plan.header, + &merge_block, + &mut split_counter, + ) + }) } else { - split_no_phi_overlap( - &mut out_blocks, - det_forest, - &plan.header, - &merge_block, - &mut split_counter, - ) + out_blocks.rewrite(|blocks| { + split_no_phi_overlap( + blocks, + forest, + &plan.header, + &merge_block, + &mut split_counter, + ) + }) }; - mutated |= split.is_some(); split.unwrap_or(merge_block) } else { merge_block @@ -1544,18 +1546,16 @@ pub(in crate::native) fn forest_loop_merges( // do-while normalization: when the latch (continue) block itself ends in a conditional // that exits to the loop merge (the exit test is at the loop bottom), split off a separate // unconditional continue block so the latch becomes an ordinary {continue, merge} break. - let rotated_continue = synth_dowhile_continue( - &mut out_blocks, - &plan.header, - &continue_target, - &merge_block, - &mut split_counter, - ); - mutated |= rotated_continue.is_some(); + let rotated_continue = out_blocks.rewrite(|blocks| { + synth_dowhile_continue( + blocks, + &plan.header, + &continue_target, + &merge_block, + &mut split_counter, + ) + }); let continue_target = rotated_continue.unwrap_or(continue_target); - if mutated { - collision_cache = None; - } merges.insert( plan.header.clone(), LoopMergeInfo { @@ -1573,14 +1573,9 @@ pub(in crate::native) fn forest_loop_merges( .loop_for_header(&plan.header) .map(|l| l.exits.clone()) .unwrap_or_default(); - if let Some(new_merge) = synth_multi_exit_merge( - &mut out_blocks, - &forest, - &plan.header, - &exits, - &mut split_counter, - ) { - collision_cache = None; + if let Some(new_merge) = out_blocks.rewrite(|blocks| { + synth_multi_exit_merge(blocks, forest, &plan.header, &exits, &mut split_counter) + }) { // A dispatch exit arm reached ALSO from outside the loop (a shared exit) is not // `M`-dominated; clone its dominated forward region so both arms reconverge at an // `M`-dominated merge (M2 residual fix). Only in the reject-triggered clone attempt @@ -1588,21 +1583,24 @@ pub(in crate::native) fn forest_loop_merges( // already admits at the base attempt (turning its valid dispatch into a reject→repair). if multi_exit_clone { privatize_dispatch_shared_exits( - &mut out_blocks, + out_blocks.edit(), &new_merge, &mut split_counter, ); } // The funnelled loop may now be a do-while (its latch conditionally exits to the new // dispatch merge); rotate that latch into a separate continue block too. - let continue_target = synth_dowhile_continue( - &mut out_blocks, - &plan.header, - &continue_target, - &new_merge, - &mut split_counter, - ) - .unwrap_or(continue_target); + let continue_target = out_blocks + .rewrite(|blocks| { + synth_dowhile_continue( + blocks, + &plan.header, + &continue_target, + &new_merge, + &mut split_counter, + ) + }) + .unwrap_or(continue_target); merges.insert( plan.header.clone(), LoopMergeInfo { @@ -1623,23 +1621,22 @@ pub(in crate::native) fn forest_loop_merges( .loop_for_header(&plan.header) .map(|l| l.latches.clone()) .unwrap_or_default(); - if let Some(new_latch) = synth_multi_latch_continue( - &mut out_blocks, - &plan.header, - &latches, - &mut split_counter, - ) { - collision_cache = None; + if let Some(new_latch) = out_blocks.rewrite(|blocks| { + synth_multi_latch_continue(blocks, &plan.header, &latches, &mut split_counter) + }) { // The unified loop may now be a do-while (its single latch conditionally exits to the // merge); rotate that latch into a separate unconditional continue block too. - let continue_target = synth_dowhile_continue( - &mut out_blocks, - &plan.header, - &new_latch, - &merge_block, - &mut split_counter, - ) - .unwrap_or(new_latch); + let continue_target = out_blocks + .rewrite(|blocks| { + synth_dowhile_continue( + blocks, + &plan.header, + &new_latch, + &merge_block, + &mut split_counter, + ) + }) + .unwrap_or(new_latch); merges.insert( plan.header.clone(), LoopMergeInfo { @@ -1662,42 +1659,48 @@ pub(in crate::native) fn forest_loop_merges( } continue; } - let split = if block_has_phi(&out_blocks, &merge_block) { + let split = if block_has_phi(out_blocks.get(), &merge_block) { // Phi-carrying shared block: the redirected predecessors' incomings are merged into a phi // in the synthesized pass-through block, and the shared block's phi takes that merged // value via the pass-through edge (preserving the enclosing continue's own incomings). - split_phi_overlap( - &mut out_blocks, - &forest, - &plan.header, - &merge_block, - &mut split_counter, - ) + out_blocks.rewrite(|blocks| { + split_phi_overlap( + blocks, + forest, + &plan.header, + &merge_block, + &mut split_counter, + ) + }) } else { - split_no_phi_overlap( - &mut out_blocks, - &forest, - &plan.header, - &merge_block, - &mut split_counter, - ) + out_blocks.rewrite(|blocks| { + split_no_phi_overlap( + blocks, + forest, + &plan.header, + &merge_block, + &mut split_counter, + ) + }) }; if let Some(new_merge) = split { - collision_cache = None; // The split redirected this loop's in-body predecessors of the shared merge (including its // latch) to `new_merge`; if the latch is now a do-while bottom test (conditionally branches // back to the header or out to `new_merge`), rotate it into a clean unconditional continue // too — exactly as the empty/MultipleExits branches do. Without this the latch stays both // the loop continue AND a conditional, which spirv-val rejects ("block exits the continue, // but not via a structured exit"). - let continue_target = synth_dowhile_continue( - &mut out_blocks, - &plan.header, - &continue_target, - &new_merge, - &mut split_counter, - ) - .unwrap_or(continue_target); + let continue_target = out_blocks + .rewrite(|blocks| { + synth_dowhile_continue( + blocks, + &plan.header, + &continue_target, + &new_merge, + &mut split_counter, + ) + }) + .unwrap_or(continue_target); merges.insert( plan.header.clone(), LoopMergeInfo { @@ -1719,17 +1722,21 @@ pub(in crate::native) fn forest_loop_merges( .map(|(h, i)| (h.clone(), i.merge.clone(), i.continue_target.clone())) .collect(); header_infos.sort(); - let final_forest = analyze(&out_blocks); + let final_forest = analyze(out_blocks.get()); for (h, m, c) in header_infos { let Some(loop_info) = final_forest.loop_for_header(&h) else { continue; }; let loop_body = loop_info.body.iter().cloned().collect::>(); - split_loop_header_selection(&mut out_blocks, &h, &m, &c, &loop_body, &mut split_counter); - split_loop_header_switch(&mut out_blocks, &h, &m, &c, &loop_body, &mut split_counter); + out_blocks.rewrite(|blocks| { + split_loop_header_selection(blocks, &h, &m, &c, &loop_body, &mut split_counter) + }); + out_blocks.rewrite(|blocks| { + split_loop_header_switch(blocks, &h, &m, &c, &loop_body, &mut split_counter) + }); } - (out_blocks, merges) + (out_blocks.into_inner(), merges) } /// Structure a pure self-latching infinite loop. LLVM permits a header which carries its own phis, diff --git a/src/native/cfg/structured_emit/rewrite.rs b/src/native/cfg/structured_emit/rewrite.rs index d1e30a67e..01a499623 100644 --- a/src/native/cfg/structured_emit/rewrite.rs +++ b/src/native/cfg/structured_emit/rewrite.rs @@ -33,3 +33,211 @@ pub(in crate::native) fn atomic_rewrite( *blocks = staged; Some(outcome) } + +/// A block list that counts the rewrites which have actually landed on it, so an analysis derived +/// from it can say whether it still describes the graph. +/// +/// The structurizer's transform loops interleave whole-function analyses (a [`LoopForest`], a +/// selection-merge map) with rewrites that may or may not fire. Caching an analysis across those +/// rewrites is the difference between one analysis per loop header and one per graph edit, but the +/// invalidation was hand-written: `forest_loop_merges` carried eight separate `cache = None` +/// assignments, one per mutation site, each of which a later edit has to remember to add. A missing +/// one is invisible — the stale forest still answers every query, just about the previous graph. +/// +/// Here the revision is the cache key and only this type can advance it, so an analysis is reused +/// exactly when the block list has not changed since it was derived and never otherwise. +/// +/// [`LoopForest`]: super::LoopForest +pub(in crate::native) struct RewriteBlocks { + blocks: Vec, + revision: u64, +} + +impl RewriteBlocks { + pub(in crate::native) fn new(blocks: Vec) -> Self { + Self { + blocks, + revision: 0, + } + } + + pub(in crate::native) fn get(&self) -> &[BodyBlock] { + &self.blocks + } + + /// The number of rewrites that have landed. Only ever compared for equality. + pub(in crate::native) fn revision(&self) -> u64 { + self.revision + } + + /// Run a rewrite that may decline, advancing the revision only when it commits. + /// + /// A decline must leave the list untouched — that is the contract [`atomic_rewrite`] gives every + /// primitive here — so holding the revision across one keeps a cached analysis valid, which is + /// the whole point of distinguishing a decline from a no-op. Debug builds check it rather than + /// assume it, so a primitive that stops honoring the contract fails the test suite here instead + /// of silently feeding a stale forest to the next loop header. + pub(in crate::native) fn rewrite( + &mut self, + rewrite: impl FnOnce(&mut Vec) -> Option, + ) -> Option { + #[cfg(debug_assertions)] + let before = decline_witness(&self.blocks); + match rewrite(&mut self.blocks) { + Some(outcome) => { + self.revision += 1; + Some(outcome) + } + None => { + #[cfg(debug_assertions)] + assert!( + before == decline_witness(&self.blocks), + "a declined rewrite edited the block list; wrap it in atomic_rewrite" + ); + None + } + } + } + + /// Mutable access for a rewrite that does not report whether it fired. The revision advances + /// unconditionally, so a cached analysis is dropped whether or not the list actually changed. + pub(in crate::native) fn edit(&mut self) -> &mut Vec { + self.revision += 1; + &mut self.blocks + } + + pub(in crate::native) fn into_inner(self) -> Vec { + self.blocks + } +} + +/// What [`RewriteBlocks::rewrite`] compares to catch a decline that edited the list: a hash of the +/// block names and successor labels, in order. That is the substrate the corrupting cases here +/// damage — an edge redirected to a block that was never inserted, or a split block left behind — +/// and it is cheap enough to take on every declined rewrite in a debug build, which a full carrier +/// comparison is not. +#[cfg(debug_assertions)] +fn decline_witness(blocks: &[BodyBlock]) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + blocks.len().hash(&mut hasher); + for block in blocks { + block.name.hash(&mut hasher); + super::block_successors(block).hash(&mut hasher); + } + hasher.finish() +} + +/// A whole-function analysis remembered alongside the [`RewriteBlocks`] revision it was derived +/// from, so the derivation runs once per graph state instead of once per query. +pub(in crate::native) struct AnalysisCache { + entry: Option<(u64, T)>, +} + +impl Default for AnalysisCache { + fn default() -> Self { + Self { entry: None } + } +} + +impl AnalysisCache { + /// The analysis for `blocks` as it stands now, deriving it only if the cached one predates the + /// current revision. + pub(in crate::native) fn get<'cache>( + &'cache mut self, + blocks: &RewriteBlocks, + derive: impl FnOnce(&[BodyBlock]) -> T, + ) -> &'cache T { + let revision = blocks.revision(); + if !matches!(&self.entry, Some((cached, _)) if *cached == revision) { + self.entry = Some((revision, derive(blocks.get()))); + } + &self.entry.as_ref().expect("just derived").1 + } +} + +#[cfg(test)] +mod tests { + use super::super::test_support::bb; + use super::*; + + fn one_block() -> Vec { + vec![bb("%entry", &["ret void"])] + } + + /// The property the whole caching scheme rests on: a decline is not a graph state. A rewrite + /// that reports `None` leaves the revision alone, so an analysis derived before it is still + /// the analysis of the current graph; a rewrite that reports `Some` moves it. + #[test] + fn only_a_committed_rewrite_advances_the_revision() { + let mut blocks = RewriteBlocks::new(one_block()); + let start = blocks.revision(); + + assert_eq!(blocks.rewrite(|_| None::<()>), None); + assert_eq!(blocks.revision(), start, "a decline is not a change"); + + assert_eq!( + blocks.rewrite(|blocks| { + blocks.push(bb("%tail", &["ret void"])); + Some(()) + }), + Some(()) + ); + assert_ne!(blocks.revision(), start, "a commit is a change"); + assert_eq!(blocks.get().len(), 2); + } + + /// A rewrite that does not report whether it fired cannot be trusted to have done nothing, so + /// handing out `&mut` counts as a change either way. + #[test] + fn unreported_edit_access_advances_the_revision() { + let mut blocks = RewriteBlocks::new(one_block()); + let start = blocks.revision(); + let _ = blocks.edit(); + assert_ne!(blocks.revision(), start); + } + + /// The cache derives once per graph state and not once per query — the reuse that turns one + /// analysis per graph edit back into one per loop header — and never serves a result derived + /// from a graph that has since changed. + #[test] + fn an_analysis_is_derived_once_per_revision() { + let mut blocks = RewriteBlocks::new(one_block()); + let mut cache = AnalysisCache::default(); + let mut derivations = 0usize; + + for _ in 0..3 { + assert_eq!( + *cache.get(&blocks, |b| { + derivations += 1; + b.len() + }), + 1 + ); + } + assert_eq!(derivations, 1, "an unchanged graph is analyzed once"); + + blocks.edit().push(bb("%tail", &["ret void"])); + assert_eq!( + *cache.get(&blocks, |b| { + derivations += 1; + b.len() + }), + 2 + ); + assert_eq!(derivations, 2, "a changed graph is analyzed again"); + } + + /// A declined rewrite that edited the list anyway is what silently poisons every cache keyed on + /// the revision, so debug builds catch it at the rewrite rather than at some later wrong answer. + #[test] + #[should_panic(expected = "a declined rewrite edited the block list")] + #[cfg(debug_assertions)] + fn a_declined_rewrite_that_edited_the_list_is_caught() { + let mut blocks = RewriteBlocks::new(one_block()); + blocks.rewrite(|blocks| { + blocks.push(bb("%tail", &["ret void"])); + None::<()> + }); + } +} diff --git a/src/native/tests/bounded_work.rs b/src/native/tests/bounded_work.rs index d24774cd5..1c06d6452 100644 --- a/src/native/tests/bounded_work.rs +++ b/src/native/tests/bounded_work.rs @@ -86,7 +86,7 @@ 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 +/// Measured at 867. 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