1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use syntax::ast::{self, MetaItem};
13 use rustc_data_structures::bitvec::{bitwise, BitwiseOperator};
14 use rustc_data_structures::indexed_set::{HybridIdxSet, IdxSet};
15 use rustc_data_structures::indexed_vec::Idx;
16 use rustc_data_structures::work_queue::WorkQueue;
18 use rustc::ty::{self, TyCtxt};
19 use rustc::mir::{self, Mir, BasicBlock, BasicBlockData, Location, Statement, Terminator};
20 use rustc::mir::traversal;
21 use rustc::session::Session;
23 use std::borrow::Borrow;
26 use std::path::PathBuf;
29 pub use self::impls::{MaybeStorageLive};
30 pub use self::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
31 pub use self::impls::DefinitelyInitializedPlaces;
32 pub use self::impls::EverInitializedPlaces;
33 pub use self::impls::borrows::Borrows;
34 pub use self::impls::HaveBeenBorrowedLocals;
35 pub use self::at_location::{FlowAtLocation, FlowsAtLocation};
36 pub(crate) use self::drop_flag_effects::*;
38 use self::move_paths::MoveData;
41 pub mod drop_flag_effects;
46 pub(crate) use self::move_paths::indexes;
48 pub(crate) struct DataflowBuilder<'a, 'tcx: 'a, BD> where BD: BitDenotation
51 flow_state: DataflowAnalysis<'a, 'tcx, BD>,
52 print_preflow_to: Option<String>,
53 print_postflow_to: Option<String>,
56 /// `DebugFormatted` encapsulates the "{:?}" rendering of some
57 /// arbitrary value. This way: you pay cost of allocating an extra
58 /// string (as well as that of rendering up-front); in exchange, you
59 /// don't have to hand over ownership of your value or deal with
61 pub(crate) struct DebugFormatted(String);
64 pub fn new(input: &dyn fmt::Debug) -> DebugFormatted {
65 DebugFormatted(format!("{:?}", input))
69 impl fmt::Debug for DebugFormatted {
70 fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
71 write!(w, "{}", self.0)
75 pub(crate) trait Dataflow<BD: BitDenotation> {
76 /// Sets up and runs the dataflow problem, using `p` to render results if
77 /// implementation so chooses.
78 fn dataflow<P>(&mut self, p: P) where P: Fn(&BD, BD::Idx) -> DebugFormatted {
79 let _ = p; // default implementation does not instrument process.
84 /// Sets up the entry, gen, and kill sets for this instance of a dataflow problem.
85 fn build_sets(&mut self);
87 /// Finds a fixed-point solution to this instance of a dataflow problem.
88 fn propagate(&mut self);
91 impl<'a, 'tcx: 'a, BD> Dataflow<BD> for DataflowBuilder<'a, 'tcx, BD> where BD: BitDenotation
93 fn dataflow<P>(&mut self, p: P) where P: Fn(&BD, BD::Idx) -> DebugFormatted {
94 self.flow_state.build_sets();
95 self.pre_dataflow_instrumentation(|c,i| p(c,i)).unwrap();
96 self.flow_state.propagate();
97 self.post_dataflow_instrumentation(|c,i| p(c,i)).unwrap();
100 fn build_sets(&mut self) { self.flow_state.build_sets(); }
101 fn propagate(&mut self) { self.flow_state.propagate(); }
104 pub(crate) fn has_rustc_mir_with(attrs: &[ast::Attribute], name: &str) -> Option<MetaItem> {
106 if attr.check_name("rustc_mir") {
107 let items = attr.meta_item_list();
108 for item in items.iter().flat_map(|l| l.iter()) {
109 match item.meta_item() {
110 Some(mi) if mi.check_name(name) => return Some(mi.clone()),
119 pub struct MoveDataParamEnv<'gcx, 'tcx> {
120 pub(crate) move_data: MoveData<'tcx>,
121 pub(crate) param_env: ty::ParamEnv<'gcx>,
124 pub(crate) fn do_dataflow<'a, 'gcx, 'tcx, BD, P>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
126 node_id: ast::NodeId,
127 attributes: &[ast::Attribute],
128 dead_unwinds: &IdxSet<BasicBlock>,
131 -> DataflowResults<BD>
132 where BD: BitDenotation + InitialFlow,
133 P: Fn(&BD, BD::Idx) -> DebugFormatted
135 let flow_state = DataflowAnalysis::new(mir, dead_unwinds, bd);
136 flow_state.run(tcx, node_id, attributes, p)
139 impl<'a, 'gcx: 'tcx, 'tcx: 'a, BD> DataflowAnalysis<'a, 'tcx, BD> where BD: BitDenotation
141 pub(crate) fn run<P>(self,
142 tcx: TyCtxt<'a, 'gcx, 'tcx>,
143 node_id: ast::NodeId,
144 attributes: &[ast::Attribute],
145 p: P) -> DataflowResults<BD>
146 where P: Fn(&BD, BD::Idx) -> DebugFormatted
148 let name_found = |sess: &Session, attrs: &[ast::Attribute], name| -> Option<String> {
149 if let Some(item) = has_rustc_mir_with(attrs, name) {
150 if let Some(s) = item.value_str() {
151 return Some(s.to_string())
155 &format!("{} attribute requires a path", item.ident));
162 let print_preflow_to =
163 name_found(tcx.sess, attributes, "borrowck_graphviz_preflow");
164 let print_postflow_to =
165 name_found(tcx.sess, attributes, "borrowck_graphviz_postflow");
167 let mut mbcx = DataflowBuilder {
169 print_preflow_to, print_postflow_to, flow_state: self,
173 mbcx.flow_state.results()
177 struct PropagationContext<'b, 'a: 'b, 'tcx: 'a, O> where O: 'b + BitDenotation
179 builder: &'b mut DataflowAnalysis<'a, 'tcx, O>,
182 impl<'a, 'tcx: 'a, BD> DataflowAnalysis<'a, 'tcx, BD> where BD: BitDenotation
184 fn propagate(&mut self) {
185 let mut temp = IdxSet::new_empty(self.flow_state.sets.bits_per_block);
186 let mut propcx = PropagationContext {
189 propcx.walk_cfg(&mut temp);
192 fn build_sets(&mut self) {
193 // First we need to build the entry-, gen- and kill-sets.
196 let sets = &mut self.flow_state.sets.for_block(mir::START_BLOCK.index());
197 self.flow_state.operator.start_block_effect(&mut sets.on_entry);
200 for (bb, data) in self.mir.basic_blocks().iter_enumerated() {
201 let &mir::BasicBlockData { ref statements, ref terminator, is_cleanup: _ } = data;
203 let mut interim_state;
204 let sets = &mut self.flow_state.sets.for_block(bb.index());
205 let track_intrablock = BD::accumulates_intrablock_state();
206 if track_intrablock {
207 debug!("swapping in mutable on_entry, initially {:?}", sets.on_entry);
208 interim_state = sets.on_entry.to_owned();
209 sets.on_entry = &mut interim_state;
211 for j_stmt in 0..statements.len() {
212 let location = Location { block: bb, statement_index: j_stmt };
213 self.flow_state.operator.before_statement_effect(sets, location);
214 self.flow_state.operator.statement_effect(sets, location);
215 if track_intrablock {
216 sets.apply_local_effect();
220 if terminator.is_some() {
221 let location = Location { block: bb, statement_index: statements.len() };
222 self.flow_state.operator.before_terminator_effect(sets, location);
223 self.flow_state.operator.terminator_effect(sets, location);
224 if track_intrablock {
225 sets.apply_local_effect();
232 impl<'b, 'a: 'b, 'tcx: 'a, BD> PropagationContext<'b, 'a, 'tcx, BD> where BD: BitDenotation
234 fn walk_cfg(&mut self, in_out: &mut IdxSet<BD::Idx>) {
235 let mut dirty_queue: WorkQueue<mir::BasicBlock> =
236 WorkQueue::with_all(self.builder.mir.basic_blocks().len());
237 let mir = self.builder.mir;
238 while let Some(bb) = dirty_queue.pop() {
239 let bb_data = &mir[bb];
241 let sets = self.builder.flow_state.sets.for_block(bb.index());
242 debug_assert!(in_out.words().len() == sets.on_entry.words().len());
243 in_out.overwrite(sets.on_entry);
244 in_out.union(sets.gen_set);
245 in_out.subtract(sets.kill_set);
247 self.builder.propagate_bits_into_graph_successors_of(
248 in_out, (bb, bb_data), &mut dirty_queue);
253 fn dataflow_path(context: &str, path: &str) -> PathBuf {
254 let mut path = PathBuf::from(path);
255 let new_file_name = {
256 let orig_file_name = path.file_name().unwrap().to_str().unwrap();
257 format!("{}_{}", context, orig_file_name)
259 path.set_file_name(new_file_name);
263 impl<'a, 'tcx: 'a, BD> DataflowBuilder<'a, 'tcx, BD> where BD: BitDenotation
265 fn pre_dataflow_instrumentation<P>(&self, p: P) -> io::Result<()>
266 where P: Fn(&BD, BD::Idx) -> DebugFormatted
268 if let Some(ref path_str) = self.print_preflow_to {
269 let path = dataflow_path(BD::name(), path_str);
270 graphviz::print_borrowck_graph_to(self, &path, p)
276 fn post_dataflow_instrumentation<P>(&self, p: P) -> io::Result<()>
277 where P: Fn(&BD, BD::Idx) -> DebugFormatted
279 if let Some(ref path_str) = self.print_postflow_to {
280 let path = dataflow_path(BD::name(), path_str);
281 graphviz::print_borrowck_graph_to(self, &path, p)
288 /// DataflowResultsConsumer abstracts over walking the MIR with some
289 /// already constructed dataflow results.
291 /// It abstracts over the FlowState and also completely hides the
292 /// underlying flow analysis results, because it needs to handle cases
293 /// where we are combining the results of *multiple* flow analyses
294 /// (e.g. borrows + inits + uninits).
295 pub(crate) trait DataflowResultsConsumer<'a, 'tcx: 'a> {
296 type FlowState: FlowsAtLocation;
298 // Observation Hooks: override (at least one of) these to get analysis feedback.
299 fn visit_block_entry(&mut self,
301 _flow_state: &Self::FlowState) {}
303 fn visit_statement_entry(&mut self,
305 _stmt: &Statement<'tcx>,
306 _flow_state: &Self::FlowState) {}
308 fn visit_terminator_entry(&mut self,
310 _term: &Terminator<'tcx>,
311 _flow_state: &Self::FlowState) {}
313 // Main entry point: this drives the processing of results.
315 fn analyze_results(&mut self, flow_uninit: &mut Self::FlowState) {
316 let flow = flow_uninit;
317 for (bb, _) in traversal::reverse_postorder(self.mir()) {
318 flow.reset_to_entry_of(bb);
319 self.process_basic_block(bb, flow);
323 fn process_basic_block(&mut self, bb: BasicBlock, flow_state: &mut Self::FlowState) {
324 let BasicBlockData { ref statements, ref terminator, is_cleanup: _ } =
326 let mut location = Location { block: bb, statement_index: 0 };
327 for stmt in statements.iter() {
328 flow_state.reconstruct_statement_effect(location);
329 self.visit_statement_entry(location, stmt, flow_state);
330 flow_state.apply_local_effect(location);
331 location.statement_index += 1;
334 if let Some(ref term) = *terminator {
335 flow_state.reconstruct_terminator_effect(location);
336 self.visit_terminator_entry(location, term, flow_state);
338 // We don't need to apply the effect of the terminator,
339 // since we are only visiting dataflow state on control
340 // flow entry to the various nodes. (But we still need to
341 // reconstruct the effect, because the visit method might
346 // Delegated Hooks: Provide access to the MIR and process the flow state.
348 fn mir(&self) -> &'a Mir<'tcx>;
351 pub fn state_for_location<'tcx, T: BitDenotation>(loc: Location,
353 result: &DataflowResults<T>,
356 let mut on_entry = result.sets().on_entry_set_for(loc.block.index()).to_owned();
357 let mut kill_set = on_entry.to_hybrid();
358 let mut gen_set = kill_set.clone();
361 let mut sets = BlockSets {
362 on_entry: &mut on_entry,
363 kill_set: &mut kill_set,
364 gen_set: &mut gen_set,
367 for stmt in 0..loc.statement_index {
368 let mut stmt_loc = loc;
369 stmt_loc.statement_index = stmt;
370 analysis.before_statement_effect(&mut sets, stmt_loc);
371 analysis.statement_effect(&mut sets, stmt_loc);
374 // Apply the pre-statement effect of the statement we're evaluating.
375 if loc.statement_index == mir[loc.block].statements.len() {
376 analysis.before_terminator_effect(&mut sets, loc);
378 analysis.before_statement_effect(&mut sets, loc);
385 pub struct DataflowAnalysis<'a, 'tcx: 'a, O> where O: BitDenotation
387 flow_state: DataflowState<O>,
388 dead_unwinds: &'a IdxSet<mir::BasicBlock>,
392 impl<'a, 'tcx: 'a, O> DataflowAnalysis<'a, 'tcx, O> where O: BitDenotation
394 pub fn results(self) -> DataflowResults<O> {
395 DataflowResults(self.flow_state)
398 pub fn mir(&self) -> &'a Mir<'tcx> { self.mir }
401 pub struct DataflowResults<O>(pub(crate) DataflowState<O>) where O: BitDenotation;
403 impl<O: BitDenotation> DataflowResults<O> {
404 pub fn sets(&self) -> &AllSets<O::Idx> {
408 pub fn operator(&self) -> &O {
413 /// State of a dataflow analysis; couples a collection of bit sets
414 /// with operator used to initialize and merge bits during analysis.
415 pub struct DataflowState<O: BitDenotation>
417 /// All the sets for the analysis. (Factored into its
418 /// own structure so that we can borrow it mutably
419 /// on its own separate from other fields.)
420 pub sets: AllSets<O::Idx>,
422 /// operator used to initialize, combine, and interpret bits.
423 pub(crate) operator: O,
426 impl<O: BitDenotation> DataflowState<O> {
427 pub(crate) fn interpret_set<'c, P>(&self,
429 set: &IdxSet<O::Idx>,
431 -> Vec<DebugFormatted>
432 where P: Fn(&O, O::Idx) -> DebugFormatted
434 set.iter().map(|i| render_idx(o, i)).collect()
437 pub(crate) fn interpret_hybrid_set<'c, P>(&self,
439 set: &HybridIdxSet<O::Idx>,
441 -> Vec<DebugFormatted>
442 where P: Fn(&O, O::Idx) -> DebugFormatted
444 set.iter().map(|i| render_idx(o, i)).collect()
449 pub struct AllSets<E: Idx> {
450 /// Analysis bitwidth for each block.
451 bits_per_block: usize,
453 /// For each block, bits valid on entry to the block.
454 on_entry_sets: Vec<IdxSet<E>>,
456 /// For each block, bits generated by executing the statements +
457 /// terminator in the block -- with one caveat. In particular, for
458 /// *call terminators*, the effect of storing the destination is
459 /// not included, since that only takes effect on the **success**
460 /// edge (and not the unwind edge).
461 gen_sets: Vec<HybridIdxSet<E>>,
463 /// For each block, bits killed by executing the statements +
464 /// terminator in the block -- with one caveat. In particular, for
465 /// *call terminators*, the effect of storing the destination is
466 /// not included, since that only takes effect on the **success**
467 /// edge (and not the unwind edge).
468 kill_sets: Vec<HybridIdxSet<E>>,
471 /// Triple of sets associated with a given block.
473 /// Generally, one sets up `on_entry`, `gen_set`, and `kill_set` for
474 /// each block individually, and then runs the dataflow analysis which
475 /// iteratively modifies the various `on_entry` sets (but leaves the
476 /// other two sets unchanged, since they represent the effect of the
477 /// block, which should be invariant over the course of the analysis).
479 /// It is best to ensure that the intersection of `gen_set` and
480 /// `kill_set` is empty; otherwise the results of the dataflow will
481 /// have a hidden dependency on what order the bits are generated and
482 /// killed during the iteration. (This is such a good idea that the
483 /// `fn gen` and `fn kill` methods that set their state enforce this
486 pub struct BlockSets<'a, E: Idx> {
487 /// Dataflow state immediately before control flow enters the given block.
488 pub(crate) on_entry: &'a mut IdxSet<E>,
490 /// Bits that are set to 1 by the time we exit the given block. Hybrid
491 /// because it usually contains only 0 or 1 elements.
492 pub(crate) gen_set: &'a mut HybridIdxSet<E>,
494 /// Bits that are set to 0 by the time we exit the given block. Hybrid
495 /// because it usually contains only 0 or 1 elements.
496 pub(crate) kill_set: &'a mut HybridIdxSet<E>,
499 impl<'a, E:Idx> BlockSets<'a, E> {
500 fn gen(&mut self, e: &E) {
502 self.kill_set.remove(e);
504 fn gen_all<I>(&mut self, i: I)
505 where I: IntoIterator,
509 self.gen(j.borrow());
513 fn kill(&mut self, e: &E) {
514 self.gen_set.remove(e);
515 self.kill_set.add(e);
518 fn kill_all<I>(&mut self, i: I)
519 where I: IntoIterator,
523 self.kill(j.borrow());
527 fn apply_local_effect(&mut self) {
528 self.on_entry.union(self.gen_set);
529 self.on_entry.subtract(self.kill_set);
533 impl<E:Idx> AllSets<E> {
534 pub fn bits_per_block(&self) -> usize { self.bits_per_block }
535 pub fn for_block(&mut self, block_idx: usize) -> BlockSets<E> {
537 on_entry: &mut self.on_entry_sets[block_idx],
538 gen_set: &mut self.gen_sets[block_idx],
539 kill_set: &mut self.kill_sets[block_idx],
543 pub fn on_entry_set_for(&self, block_idx: usize) -> &IdxSet<E> {
544 &self.on_entry_sets[block_idx]
546 pub fn gen_set_for(&self, block_idx: usize) -> &HybridIdxSet<E> {
547 &self.gen_sets[block_idx]
549 pub fn kill_set_for(&self, block_idx: usize) -> &HybridIdxSet<E> {
550 &self.kill_sets[block_idx]
554 /// Parameterization for the precise form of data flow that is used.
555 /// `InitialFlow` handles initializing the bitvectors before any
556 /// code is inspected by the analysis. Analyses that need more nuanced
557 /// initialization (e.g. they need to consult the results of some other
558 /// dataflow analysis to set up the initial bitvectors) should not
560 pub trait InitialFlow {
561 /// Specifies the initial value for each bit in the `on_entry` set
562 fn bottom_value() -> bool;
565 pub trait BitDenotation: BitwiseOperator {
566 /// Specifies what index type is used to access the bitvector.
569 /// Some analyses want to accumulate knowledge within a block when
570 /// analyzing its statements for building the gen/kill sets. Override
571 /// this method to return true in such cases.
573 /// When this returns true, the statement-effect (re)construction
574 /// will clone the `on_entry` state and pass along a reference via
575 /// `sets.on_entry` to that local clone into `statement_effect` and
576 /// `terminator_effect`).
578 /// When it's false, no local clone is constructed; instead a
579 /// reference directly into `on_entry` is passed along via
580 /// `sets.on_entry` instead, which represents the flow state at
581 /// the block's start, not necessarily the state immediately prior
582 /// to the statement/terminator under analysis.
584 /// In either case, the passed reference is mutable; but this is a
585 /// wart from using the `BlockSets` type in the API; the intention
586 /// is that the `statement_effect` and `terminator_effect` methods
587 /// mutate only the gen/kill sets.
589 /// FIXME: We should consider enforcing the intention described in
590 /// the previous paragraph by passing the three sets in separate
591 /// parameters to encode their distinct mutabilities.
592 fn accumulates_intrablock_state() -> bool { false }
594 /// A name describing the dataflow analysis that this
595 /// BitDenotation is supporting. The name should be something
596 /// suitable for plugging in as part of a filename e.g. avoid
597 /// space-characters or other things that tend to look bad on a
598 /// file system, like slashes or periods. It is also better for
599 /// the name to be reasonably short, again because it will be
600 /// plugged into a filename.
601 fn name() -> &'static str;
603 /// Size of each bitvector allocated for each block in the analysis.
604 fn bits_per_block(&self) -> usize;
606 /// Mutates the entry set according to the effects that
607 /// have been established *prior* to entering the start
608 /// block. This can't access the gen/kill sets, because
609 /// these won't be accounted for correctly.
611 /// (For example, establishing the call arguments.)
612 fn start_block_effect(&self, entry_set: &mut IdxSet<Self::Idx>);
614 /// Similar to `statement_effect`, except it applies
615 /// *just before* the statement rather than *just after* it.
617 /// This matters for "dataflow at location" APIs, because the
618 /// before-statement effect is visible while visiting the
619 /// statement, while the after-statement effect only becomes
620 /// visible at the next statement.
622 /// Both the before-statement and after-statement effects are
623 /// applied, in that order, before moving for the next
625 fn before_statement_effect(&self,
626 _sets: &mut BlockSets<Self::Idx>,
627 _location: Location) {}
629 /// Mutates the block-sets (the flow sets for the given
630 /// basic block) according to the effects of evaluating statement.
632 /// This is used, in particular, for building up the
633 /// "transfer-function" representing the overall-effect of the
634 /// block, represented via GEN and KILL sets.
636 /// The statement is identified as `bb_data[idx_stmt]`, where
637 /// `bb_data` is the sequence of statements identified by `bb` in
639 fn statement_effect(&self,
640 sets: &mut BlockSets<Self::Idx>,
643 /// Similar to `terminator_effect`, except it applies
644 /// *just before* the terminator rather than *just after* it.
646 /// This matters for "dataflow at location" APIs, because the
647 /// before-terminator effect is visible while visiting the
648 /// terminator, while the after-terminator effect only becomes
649 /// visible at the terminator's successors.
651 /// Both the before-terminator and after-terminator effects are
652 /// applied, in that order, before moving for the next
654 fn before_terminator_effect(&self,
655 _sets: &mut BlockSets<Self::Idx>,
656 _location: Location) {}
658 /// Mutates the block-sets (the flow sets for the given
659 /// basic block) according to the effects of evaluating
662 /// This is used, in particular, for building up the
663 /// "transfer-function" representing the overall-effect of the
664 /// block, represented via GEN and KILL sets.
666 /// The effects applied here cannot depend on which branch the
668 fn terminator_effect(&self,
669 sets: &mut BlockSets<Self::Idx>,
672 /// Mutates the block-sets according to the (flow-dependent)
673 /// effect of a successful return from a Call terminator.
675 /// If basic-block BB_x ends with a call-instruction that, upon
676 /// successful return, flows to BB_y, then this method will be
677 /// called on the exit flow-state of BB_x in order to set up the
678 /// entry flow-state of BB_y.
680 /// This is used, in particular, as a special case during the
681 /// "propagate" loop where all of the basic blocks are repeatedly
682 /// visited. Since the effects of a Call terminator are
683 /// flow-dependent, the current MIR cannot encode them via just
684 /// GEN and KILL sets attached to the block, and so instead we add
685 /// this extra machinery to represent the flow-dependent effect.
687 /// FIXME: Right now this is a bit of a wart in the API. It might
688 /// be better to represent this as an additional gen- and
689 /// kill-sets associated with each edge coming out of the basic
691 fn propagate_call_return(&self,
692 in_out: &mut IdxSet<Self::Idx>,
693 call_bb: mir::BasicBlock,
694 dest_bb: mir::BasicBlock,
695 dest_place: &mir::Place);
698 impl<'a, 'tcx, D> DataflowAnalysis<'a, 'tcx, D> where D: BitDenotation
700 pub fn new(mir: &'a Mir<'tcx>,
701 dead_unwinds: &'a IdxSet<mir::BasicBlock>,
702 denotation: D) -> Self where D: InitialFlow {
703 let bits_per_block = denotation.bits_per_block();
704 let num_blocks = mir.basic_blocks().len();
706 let on_entry_sets = if D::bottom_value() {
707 vec![IdxSet::new_filled(bits_per_block); num_blocks]
709 vec![IdxSet::new_empty(bits_per_block); num_blocks]
711 let gen_sets = vec![HybridIdxSet::new_empty(bits_per_block); num_blocks];
712 let kill_sets = gen_sets.clone();
717 flow_state: DataflowState {
724 operator: denotation,
729 pub fn new_from_sets(mir: &'a Mir<'tcx>,
730 dead_unwinds: &'a IdxSet<mir::BasicBlock>,
731 sets: AllSets<D::Idx>,
732 denotation: D) -> Self {
736 flow_state: DataflowState {
738 operator: denotation,
744 impl<'a, 'tcx: 'a, D> DataflowAnalysis<'a, 'tcx, D> where D: BitDenotation
746 /// Propagates the bits of `in_out` into all the successors of `bb`,
747 /// using bitwise operator denoted by `self.operator`.
749 /// For most blocks, this is entirely uniform. However, for blocks
750 /// that end with a call terminator, the effect of the call on the
751 /// dataflow state may depend on whether the call returned
752 /// successfully or unwound.
754 /// To reflect this, the `propagate_call_return` method of the
755 /// `BitDenotation` mutates `in_out` when propagating `in_out` via
756 /// a call terminator; such mutation is performed *last*, to
757 /// ensure its side-effects do not leak elsewhere (e.g. into
759 fn propagate_bits_into_graph_successors_of(
761 in_out: &mut IdxSet<D::Idx>,
762 (bb, bb_data): (mir::BasicBlock, &mir::BasicBlockData),
763 dirty_list: &mut WorkQueue<mir::BasicBlock>)
765 match bb_data.terminator().kind {
766 mir::TerminatorKind::Return |
767 mir::TerminatorKind::Resume |
768 mir::TerminatorKind::Abort |
769 mir::TerminatorKind::GeneratorDrop |
770 mir::TerminatorKind::Unreachable => {}
771 mir::TerminatorKind::Goto { target } |
772 mir::TerminatorKind::Assert { target, cleanup: None, .. } |
773 mir::TerminatorKind::Yield { resume: target, drop: None, .. } |
774 mir::TerminatorKind::Drop { target, location: _, unwind: None } |
775 mir::TerminatorKind::DropAndReplace {
776 target, value: _, location: _, unwind: None
778 self.propagate_bits_into_entry_set_for(in_out, target, dirty_list);
780 mir::TerminatorKind::Yield { resume: target, drop: Some(drop), .. } => {
781 self.propagate_bits_into_entry_set_for(in_out, target, dirty_list);
782 self.propagate_bits_into_entry_set_for(in_out, drop, dirty_list);
784 mir::TerminatorKind::Assert { target, cleanup: Some(unwind), .. } |
785 mir::TerminatorKind::Drop { target, location: _, unwind: Some(unwind) } |
786 mir::TerminatorKind::DropAndReplace {
787 target, value: _, location: _, unwind: Some(unwind)
789 self.propagate_bits_into_entry_set_for(in_out, target, dirty_list);
790 if !self.dead_unwinds.contains(&bb) {
791 self.propagate_bits_into_entry_set_for(in_out, unwind, dirty_list);
794 mir::TerminatorKind::SwitchInt { ref targets, .. } => {
795 for target in targets {
796 self.propagate_bits_into_entry_set_for(in_out, *target, dirty_list);
799 mir::TerminatorKind::Call { cleanup, ref destination, func: _, args: _ } => {
800 if let Some(unwind) = cleanup {
801 if !self.dead_unwinds.contains(&bb) {
802 self.propagate_bits_into_entry_set_for(in_out, unwind, dirty_list);
805 if let Some((ref dest_place, dest_bb)) = *destination {
806 // N.B.: This must be done *last*, after all other
807 // propagation, as documented in comment above.
808 self.flow_state.operator.propagate_call_return(
809 in_out, bb, dest_bb, dest_place);
810 self.propagate_bits_into_entry_set_for(in_out, dest_bb, dirty_list);
813 mir::TerminatorKind::FalseEdges { real_target, ref imaginary_targets } => {
814 self.propagate_bits_into_entry_set_for(in_out, real_target, dirty_list);
815 for target in imaginary_targets {
816 self.propagate_bits_into_entry_set_for(in_out, *target, dirty_list);
819 mir::TerminatorKind::FalseUnwind { real_target, unwind } => {
820 self.propagate_bits_into_entry_set_for(in_out, real_target, dirty_list);
821 if let Some(unwind) = unwind {
822 if !self.dead_unwinds.contains(&bb) {
823 self.propagate_bits_into_entry_set_for(in_out, unwind, dirty_list);
830 fn propagate_bits_into_entry_set_for(&mut self,
831 in_out: &IdxSet<D::Idx>,
833 dirty_queue: &mut WorkQueue<mir::BasicBlock>) {
834 let entry_set = self.flow_state.sets.for_block(bb.index()).on_entry;
835 let set_changed = bitwise(entry_set.words_mut(),
837 &self.flow_state.operator);
839 dirty_queue.insert(bb);