1//! A framework that can express both [gen-kill] and generic dataflow problems.
2//!
3//! To use this framework, implement the [`Analysis`] trait. There used to be a `GenKillAnalysis`
4//! alternative trait for gen-kill analyses that would pre-compute the transfer function for each
5//! block. It was intended as an optimization, but it ended up not being any faster than
6//! `Analysis`.
7//!
8//! The `impls` module contains several examples of dataflow analyses.
9//!
10//! Then call `iterate_to_fixpoint` on your type that impls `Analysis` to get a `Results`. From
11//! there, you can use a `ResultsCursor` to inspect the fixpoint solution to your dataflow problem
12//! (good for inspecting a small number of locations), or implement the `ResultsVisitor` interface
13//! and use `visit_results` (good for inspecting many or all locations). The following example uses
14//! the `ResultsCursor` approach.
15//!
16//! ```ignore (cross-crate-imports)
17//! use rustc_const_eval::dataflow::Analysis; // Makes `iterate_to_fixpoint` available.
18//!
19//! fn do_my_analysis(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) {
20//! let analysis = MyAnalysis::new()
21//! .iterate_to_fixpoint(tcx, body, None)
22//! .into_results_cursor(body);
23//!
24//! // Print the dataflow state *after* each statement in the start block.
25//! for (_, statement_index) in body.block_data[START_BLOCK].statements.iter_enumerated() {
26//! cursor.seek_after(Location { block: START_BLOCK, statement_index });
27//! let state = cursor.get();
28//! println!("{:?}", state);
29//! }
30//! }
31//! ```
32//!
33//! [gen-kill]: https://en.wikipedia.org/wiki/Data-flow_analysis#Bit_vector_problems
3435use rustc_index::bit_set::{DenseBitSet, MixedBitSet};
36use rustc_index::{Idx, IndexVec};
37use rustc_middle::bug;
38use rustc_middle::mir::{
39self, BasicBlock, BasicBlockData, CallReturnPlaces, Location, TerminatorEdges,
40};
41use rustc_middle::ty::TyCtxt;
42use tracing::error;
4344use self::graphviz::write_graphviz_results;
45use super::fmt::DebugWithContext;
4647mod cursor;
48mod direction;
49pub mod fmt;
50pub mod graphviz;
51pub mod lattice;
52mod results;
53mod visitor;
5455pub use self::cursor::ResultsCursor;
56pub use self::direction::{Backward, Direction, Forward};
57pub use self::lattice::{JoinSemiLattice, MaybeReachable};
58pub use self::results::{EntryStates, Results};
59pub use self::visitor::{ResultsVisitor, visit_reachable_results, visit_results};
6061/// Analysis domains are all bitsets of various kinds. This trait holds
62/// operations needed by all of them.
63pub trait BitSetExt<T> {
64fn contains(&self, elem: T) -> bool;
65}
6667impl<T: Idx> BitSetExt<T> for DenseBitSet<T> {
68fn contains(&self, elem: T) -> bool {
69self.contains(elem)
70 }
71}
7273impl<T: Idx> BitSetExt<T> for MixedBitSet<T> {
74fn contains(&self, elem: T) -> bool {
75self.contains(elem)
76 }
77}
7879/// A dataflow problem with an arbitrarily complex transfer function.
80///
81/// This trait specifies the lattice on which this analysis operates (the domain), its
82/// initial value at the entry point of each basic block, and various operations.
83///
84/// # Convergence
85///
86/// When implementing this trait it's possible to choose a transfer function such that the analysis
87/// does not reach fixpoint. To guarantee convergence, your transfer functions must maintain the
88/// following invariant:
89///
90/// > If the dataflow state **before** some point in the program changes to be greater
91/// than the prior state **before** that point, the dataflow state **after** that point must
92/// also change to be greater than the prior state **after** that point.
93///
94/// This invariant guarantees that the dataflow state at a given point in the program increases
95/// monotonically until fixpoint is reached. Note that this monotonicity requirement only applies
96/// to the same point in the program at different points in time. The dataflow state at a given
97/// point in the program may or may not be greater than the state at any preceding point.
98pub trait Analysis<'tcx> {
99/// The type that holds the dataflow state at any given point in the program.
100type Domain: Clone + JoinSemiLattice;
101102/// The direction of this analysis. Either `Forward` or `Backward`.
103type Direction: Direction = Forward;
104105/// Auxiliary data used for analyzing `SwitchInt` terminators, if necessary.
106type SwitchIntData = !;
107108/// A descriptive name for this analysis. Used only for debugging.
109 ///
110 /// This name should be brief and contain no spaces, periods or other characters that are not
111 /// suitable as part of a filename.
112const NAME: &'static str;
113114/// Returns the initial value of the dataflow state upon entry to each basic block.
115fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain;
116117/// Mutates the initial value of the dataflow state upon entry to the `START_BLOCK`.
118 ///
119 /// For backward analyses, initial state (besides the bottom value) is not yet supported. Trying
120 /// to mutate the initial state will result in a panic.
121//
122 // FIXME: For backward dataflow analyses, the initial state should be applied to every basic
123 // block where control flow could exit the MIR body (e.g., those terminated with `return` or
124 // `resume`). It's not obvious how to handle `yield` points in coroutines, however.
125fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain);
126127/// Given an `EffectIndex`, calls the appropriate `apply_*` method in the
128 /// {early,primary} x {statement,terminator} space.
129 ///
130 /// Do not override this; instead override one or more of the `apply_*` methods.
131#[inline]
132fn apply_effect<'mir>(
133&self,
134 state: &mut Self::Domain,
135 block: BasicBlock,
136 block_data: &'mir BasicBlockData<'tcx>,
137 idx: EffectIndex,
138 ) {
139let statement_index = idx.statement_index;
140let terminator_index = block_data.statements.len();
141let loc = Location { block, statement_index };
142let is_terminator = statement_index == terminator_index;
143144if !is_terminator {
145let statement = &block_data.statements[statement_index];
146match idx.effect {
147 Effect::Early => self.apply_early_statement_effect(state, statement, loc),
148 Effect::Primary => self.apply_primary_statement_effect(state, statement, loc),
149 }
150 } else {
151let terminator = block_data.terminator();
152match idx.effect {
153 Effect::Early => self.apply_early_terminator_effect(state, terminator, loc),
154 Effect::Primary => {
155self.apply_primary_terminator_effect(state, terminator, loc);
156 }
157 }
158 }
159 }
160161/// Updates the current dataflow state with an "early" effect, i.e. one
162 /// that occurs immediately before the given statement.
163 ///
164 /// This method is useful if the consumer of the results of this analysis only needs to observe
165 /// *part* of the effect of a statement (e.g. for two-phase borrows). As a general rule,
166 /// analyses should not implement this without also implementing
167 /// `apply_primary_statement_effect`.
168fn apply_early_statement_effect(
169&self,
170 _state: &mut Self::Domain,
171 _statement: &mir::Statement<'tcx>,
172 _location: Location,
173 ) {
174 }
175176/// Updates the current dataflow state with the effect of evaluating a statement.
177fn apply_primary_statement_effect(
178&self,
179 state: &mut Self::Domain,
180 statement: &mir::Statement<'tcx>,
181 location: Location,
182 );
183184/// Updates the current dataflow state with an effect that occurs immediately *before* the
185 /// given terminator.
186 ///
187 /// This method is useful if the consumer of the results of this analysis needs only to observe
188 /// *part* of the effect of a terminator (e.g. for two-phase borrows). As a general rule,
189 /// analyses should not implement this without also implementing
190 /// `apply_primary_terminator_effect`.
191fn apply_early_terminator_effect(
192&self,
193 _state: &mut Self::Domain,
194 _terminator: &mir::Terminator<'tcx>,
195 _location: Location,
196 ) {
197 }
198199/// Updates the current dataflow state with the effect of evaluating a terminator.
200 ///
201 /// The effect of a successful return from a `Call` terminator should **not** be accounted for
202 /// in this function. That should go in `apply_call_return_effect`. For example, in the
203 /// `InitializedPlaces` analyses, the return place for a function call is not marked as
204 /// initialized here.
205fn apply_primary_terminator_effect<'mir>(
206&self,
207 _state: &mut Self::Domain,
208 terminator: &'mir mir::Terminator<'tcx>,
209 _location: Location,
210 ) -> TerminatorEdges<'mir, 'tcx> {
211terminator.edges()
212 }
213214/* Edge-specific effects */
215216/// Updates the current dataflow state with the effect of a successful return from a `Call`
217 /// terminator.
218 ///
219 /// This is separate from `apply_primary_terminator_effect` to properly track state across
220 /// unwind edges.
221fn apply_call_return_effect(
222&self,
223 _state: &mut Self::Domain,
224 _block: BasicBlock,
225 _return_places: CallReturnPlaces<'_, 'tcx>,
226 ) {
227 }
228229/// Used to update the current dataflow state with the effect of taking a particular branch in
230 /// a `SwitchInt` terminator.
231 ///
232 /// Unlike the other edge-specific effects, which are allowed to mutate `Self::Domain`
233 /// directly, overriders of this method must return a `Self::SwitchIntData` value (wrapped in
234 /// `Some`). The `apply_switch_int_edge_effect` method will then be called once for each
235 /// outgoing edge and will have access to the dataflow state that will be propagated along that
236 /// edge, and also the `Self::SwitchIntData` value.
237 ///
238 /// This interface is somewhat more complex than the other visitor-like "effect" methods.
239 /// However, it is both more ergonomic—callers don't need to recompute or cache information
240 /// about a given `SwitchInt` terminator for each one of its edges—and more efficient—the
241 /// engine doesn't need to clone the exit state for a block unless
242 /// `get_switch_int_data` is actually called.
243fn get_switch_int_data(
244&self,
245 _block: mir::BasicBlock,
246 _targets: &mir::SwitchTargets,
247 _discr: &mir::Operand<'tcx>,
248 ) -> Option<Self::SwitchIntData> {
249None250 }
251252/// See comments on `get_switch_int_data`.
253fn apply_switch_int_edge_effect(
254&self,
255 _state: &mut Self::Domain,
256 _data: &mut Self::SwitchIntData,
257 _target_idx: SwitchTargetIndex,
258 ) {
259::core::panicking::panic("internal error: entered unreachable code");unreachable!();
260 }
261262/* Extension methods */
263264/// Finds the fixpoint for this dataflow problem.
265 ///
266 /// You shouldn't need to override this. Its purpose is to enable method chaining like so:
267 ///
268 /// ```ignore (cross-crate-imports)
269 /// let results = MyAnalysis::new(tcx, body)
270 /// .iterate_to_fixpoint(tcx, body, None)
271 /// .into_results_cursor(body);
272 /// ```
273 /// You can optionally add a `pass_name` to the graphviz output for this particular run of a
274 /// dataflow analysis. Some analyses are run multiple times in the compilation pipeline.
275 /// Without a `pass_name` to differentiates them, only the results for the latest run will be
276 /// saved.
277fn iterate_to_fixpoint<'mir>(
278self,
279 tcx: TyCtxt<'tcx>,
280 body: &'mir mir::Body<'tcx>,
281 pass_name: Option<&'static str>,
282 ) -> Results<'tcx, Self>
283where
284Self: Sized,
285Self::Domain: DebugWithContext<Self>,
286 {
287let mut entry_states =
288IndexVec::from_fn_n(|_| self.bottom_value(body), body.basic_blocks.len());
289self.initialize_start_block(body, &mut entry_states[mir::START_BLOCK]);
290291if Self::Direction::IS_BACKWARD && entry_states[mir::START_BLOCK] != self.bottom_value(body)
292 {
293::rustc_middle::util::bug::bug_fmt(format_args!("`initialize_start_block` is not yet supported for backward dataflow analyses"));bug!("`initialize_start_block` is not yet supported for backward dataflow analyses");
294 }
295296// Forward analyses use a reverse postorder (`rpo`). Every reachable basic block has a
297 // *rank*: its position within `rpo`. Rank order is dataflow order: for every edge A -> B
298 // that is not a back edge, rank(A) < rank(B). This is independent of basic block numbering
299 // (which depends on the vagaries of CFG construction).
300 //
301 // The CFG traversal uses a "min-rank" algorithm. First, all reachable basic blocks are
302 // marked as dirty. The loop-head invariant is that `curr_rank` always points to the
303 // minimum-rank dirty block in `rpo`. Before processing that block we mark it as clean. If
304 // the processing dirties a block with a rank lower than or equal to `curr_rank` (via a
305 // back edge, which could be an edge-to-self) then `curr_rank` is set to that
306 // lower-or-equal rank. After the block is processed, if `curr_rank` doesn't point to a
307 // dirty block it is moved to the next dirty block, and we iterate again.
308 //
309 // This algorithm ensures each basic block is processed only after all its dirty
310 // predecessors (ignoring back edges). When a back edge dirties an earlier block we return
311 // to that earlier block immediately, which avoids processing later blocks with possibly
312 // soon-to-be-stale information. Loop-free code is processed in a single pass.
313 //
314 // Backward analyses: we want a postorder instead of a reverse postorder, but we also want
315 // to avoid the cost of adding a `postorder` field to `mir::basic_blocks::Cache`. We can
316 // fake a postorder traversal cheaply by using a reverse postorder and flipping the rank
317 // mapping. There is also one wrinkle involving unreachable blocks; see below.
318319impl ::std::fmt::Debug for BasicBlockRank {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("bbr{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
320#[orderable]
321 #[debug_format = "bbr{}"]
322struct BasicBlockRank {}
323 }324325let rpo: &[BasicBlock] = body.basic_blocks.reverse_postorder();
326let last = rpo.len() - 1;
327328let mut ranks: IndexVec<BasicBlock, Option<BasicBlockRank>> =
329IndexVec::from_elem_n(None, body.basic_blocks.len());
330for (i, &bb) in rpo.iter().enumerate() {
331let rank = if Self::Direction::IS_FORWARD { i } else { last - i };
332 ranks[bb] = Some(BasicBlockRank::new(rank));
333 }
334335let mut dirty: DenseBitSet<BasicBlockRank> = DenseBitSet::new_filled(rpo.len());
336let mut curr_rank = BasicBlockRank::ZERO;
337338// `state` is not actually used between iterations; this is just an optimization to avoid
339 // reallocating every iteration.
340let mut state = self.bottom_value(body);
341342loop {
343let i = curr_rank.as_usize();
344let bb = rpo[if Self::Direction::IS_FORWARD { i } else { last - i }];
345if true {
if !dirty.contains(curr_rank) {
::core::panicking::panic("assertion failed: dirty.contains(curr_rank)")
};
};debug_assert!(dirty.contains(curr_rank)); // check invariant
346dirty.remove(curr_rank); // invariant temporarily broken
347348state.clone_from(&entry_states[bb]);
349let prop = |target: BasicBlock, state: &Self::Domain| {
350// A backward analysis may encounter an unreachable block, because a predecessor
351 // of a reachable block may be unreachable. Ignore any such block. (In contrast, in
352 // a forward analysis any successor of a reachable block must be reachable.)
353let target_rank = ranks[target];
354if Self::Direction::IS_BACKWARD && target_rank.is_none() {
355return;
356 }
357let target_rank = target_rank.unwrap();
358359let set_changed = entry_states[target].join(state);
360if set_changed {
361dirty.insert(target_rank);
362curr_rank = curr_rank.min(target_rank);
363 }
364 };
365Self::Direction::apply_effects_in_block(&self, body, &mut state, bb, &body[bb], prop);
366367match dirty.first_set_at_or_after(curr_rank) {
368Some(rank) => curr_rank = rank, // broken invariant re-established
369None => break, // no more dirty blocks; finish
370}
371 }
372373let results = Results { analysis: self, entry_states };
374375if tcx.sess.opts.unstable_opts.dump_mir_dataflow {
376let res = write_graphviz_results(tcx, body, &results, pass_name);
377if let Err(e) = res {
378{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_dataflow/src/framework/mod.rs:378",
"rustc_mir_dataflow::framework", ::tracing::Level::ERROR,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_dataflow/src/framework/mod.rs"),
::tracing_core::__macro_support::Option::Some(378u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_dataflow::framework"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::ERROR <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::ERROR <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Failed to write graphviz dataflow results: {0}",
e) as &dyn ::tracing::field::Value))])
});
} else { ; }
};error!("Failed to write graphviz dataflow results: {}", e);
379 }
380 }
381382results383 }
384}
385386#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SwitchTargetIndex {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SwitchTargetIndex::Normal(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Normal",
&__self_0),
SwitchTargetIndex::Otherwise =>
::core::fmt::Formatter::write_str(f, "Otherwise"),
}
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for SwitchTargetIndex {
#[inline]
fn clone(&self) -> SwitchTargetIndex {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SwitchTargetIndex { }Copy)]
387pub enum SwitchTargetIndex {
388// Index of a normal switch target.
389Normal(usize),
390// The final "otherwise" fallback target.
391Otherwise,
392}
393394/// The legal operations for a transfer function in a gen/kill problem.
395pub trait GenKill<T> {
396/// Inserts `elem` into the state vector.
397fn gen_(&mut self, elem: T);
398399/// Removes `elem` from the state vector.
400fn kill(&mut self, elem: T);
401402/// Calls `gen` for each element in `elems`.
403fn gen_all(&mut self, elems: impl IntoIterator<Item = T>) {
404for elem in elems {
405self.gen_(elem);
406 }
407 }
408409/// Calls `kill` for each element in `elems`.
410fn kill_all(&mut self, elems: impl IntoIterator<Item = T>) {
411for elem in elems {
412self.kill(elem);
413 }
414 }
415}
416417impl<T: Idx> GenKill<T> for DenseBitSet<T> {
418fn gen_(&mut self, elem: T) {
419self.insert(elem);
420 }
421422fn kill(&mut self, elem: T) {
423self.remove(elem);
424 }
425}
426427impl<T: Idx> GenKill<T> for MixedBitSet<T> {
428fn gen_(&mut self, elem: T) {
429self.insert(elem);
430 }
431432fn kill(&mut self, elem: T) {
433self.remove(elem);
434 }
435}
436437impl<T, S: GenKill<T>> GenKill<T> for MaybeReachable<S> {
438fn gen_(&mut self, elem: T) {
439match self {
440// If the state is not reachable, adding an element does nothing.
441MaybeReachable::Unreachable => {}
442 MaybeReachable::Reachable(set) => set.gen_(elem),
443 }
444 }
445446fn kill(&mut self, elem: T) {
447match self {
448// If the state is not reachable, killing an element does nothing.
449MaybeReachable::Unreachable => {}
450 MaybeReachable::Reachable(set) => set.kill(elem),
451 }
452 }
453}
454455// NOTE: DO NOT CHANGE VARIANT ORDER. The derived `Ord` impls rely on the current order.
456#[derive(#[automatically_derived]
impl ::core::clone::Clone for Effect {
#[inline]
fn clone(&self) -> Effect { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Effect { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Effect {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Effect::Early => "Early",
Effect::Primary => "Primary",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Effect {
#[inline]
fn eq(&self, other: &Effect) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Effect {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Effect {
#[inline]
fn partial_cmp(&self, other: &Effect)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for Effect {
#[inline]
fn cmp(&self, other: &Effect) -> ::core::cmp::Ordering {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr)
}
}Ord)]
457enum Effect {
458/// The "early" effect (e.g., `apply_early_statement_effect`) for a statement/terminator.
459Early,
460461/// The "primary" effect (e.g., `apply_primary_statement_effect`) for a statement/terminator.
462Primary,
463}
464465impl Effect {
466const fn at_index(self, statement_index: usize) -> EffectIndex {
467EffectIndex { effect: self, statement_index }
468 }
469}
470471#[derive(#[automatically_derived]
impl ::core::clone::Clone for EffectIndex {
#[inline]
fn clone(&self) -> EffectIndex {
let _: ::core::clone::AssertParamIsClone<usize>;
let _: ::core::clone::AssertParamIsClone<Effect>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EffectIndex { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for EffectIndex {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "EffectIndex",
"statement_index", &self.statement_index, "effect", &&self.effect)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for EffectIndex {
#[inline]
fn eq(&self, other: &EffectIndex) -> bool {
self.statement_index == other.statement_index &&
self.effect == other.effect
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for EffectIndex {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<Effect>;
}
}Eq)]
472pub struct EffectIndex {
473 statement_index: usize,
474 effect: Effect,
475}
476477#[cfg(test)]
478mod tests;