rustc_middle/mir/
basic_blocks.rs

1use rustc_data_structures::fx::FxHashMap;
2use rustc_data_structures::graph;
3use rustc_data_structures::graph::dominators::{Dominators, dominators};
4use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
5use rustc_data_structures::sync::OnceLock;
6use rustc_index::{IndexSlice, IndexVec};
7use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
8use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
9use smallvec::SmallVec;
10
11use crate::mir::traversal::Postorder;
12use crate::mir::{BasicBlock, BasicBlockData, START_BLOCK, Terminator, TerminatorKind};
13
14#[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
15pub struct BasicBlocks<'tcx> {
16    basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
17    cache: Cache,
18}
19
20// Typically 95%+ of basic blocks have 4 or fewer predecessors.
21type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>;
22
23type SwitchSources = FxHashMap<(BasicBlock, BasicBlock), SmallVec<[Option<u128>; 1]>>;
24
25#[derive(Clone, Default, Debug)]
26struct Cache {
27    predecessors: OnceLock<Predecessors>,
28    switch_sources: OnceLock<SwitchSources>,
29    reverse_postorder: OnceLock<Vec<BasicBlock>>,
30    dominators: OnceLock<Dominators<BasicBlock>>,
31}
32
33impl<'tcx> BasicBlocks<'tcx> {
34    #[inline]
35    pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
36        BasicBlocks { basic_blocks, cache: Cache::default() }
37    }
38
39    pub fn dominators(&self) -> &Dominators<BasicBlock> {
40        self.cache.dominators.get_or_init(|| dominators(self))
41    }
42
43    /// Returns predecessors for each basic block.
44    #[inline]
45    pub fn predecessors(&self) -> &Predecessors {
46        self.cache.predecessors.get_or_init(|| {
47            let mut preds = IndexVec::from_elem(SmallVec::new(), &self.basic_blocks);
48            for (bb, data) in self.basic_blocks.iter_enumerated() {
49                if let Some(term) = &data.terminator {
50                    for succ in term.successors() {
51                        preds[succ].push(bb);
52                    }
53                }
54            }
55            preds
56        })
57    }
58
59    /// Returns basic blocks in a reverse postorder.
60    ///
61    /// See [`traversal::reverse_postorder`]'s docs to learn what is preorder traversal.
62    ///
63    /// [`traversal::reverse_postorder`]: crate::mir::traversal::reverse_postorder
64    #[inline]
65    pub fn reverse_postorder(&self) -> &[BasicBlock] {
66        self.cache.reverse_postorder.get_or_init(|| {
67            let mut rpo: Vec<_> = Postorder::new(&self.basic_blocks, START_BLOCK, ()).collect();
68            rpo.reverse();
69            rpo
70        })
71    }
72
73    /// `switch_sources()[&(target, switch)]` returns a list of switch
74    /// values that lead to a `target` block from a `switch` block.
75    #[inline]
76    pub fn switch_sources(&self) -> &SwitchSources {
77        self.cache.switch_sources.get_or_init(|| {
78            let mut switch_sources: SwitchSources = FxHashMap::default();
79            for (bb, data) in self.basic_blocks.iter_enumerated() {
80                if let Some(Terminator {
81                    kind: TerminatorKind::SwitchInt { targets, .. }, ..
82                }) = &data.terminator
83                {
84                    for (value, target) in targets.iter() {
85                        switch_sources.entry((target, bb)).or_default().push(Some(value));
86                    }
87                    switch_sources.entry((targets.otherwise(), bb)).or_default().push(None);
88                }
89            }
90            switch_sources
91        })
92    }
93
94    /// Returns mutable reference to basic blocks. Invalidates CFG cache.
95    #[inline]
96    pub fn as_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
97        self.invalidate_cfg_cache();
98        &mut self.basic_blocks
99    }
100
101    /// Get mutable access to basic blocks without invalidating the CFG cache.
102    ///
103    /// By calling this method instead of e.g. [`BasicBlocks::as_mut`] you promise not to change
104    /// the CFG. This means that
105    ///
106    ///  1) The number of basic blocks remains unchanged
107    ///  2) The set of successors of each terminator remains unchanged.
108    ///  3) For each `TerminatorKind::SwitchInt`, the `targets` remains the same and the terminator
109    ///     kind is not changed.
110    ///
111    /// If any of these conditions cannot be upheld, you should call [`BasicBlocks::invalidate_cfg_cache`].
112    #[inline]
113    pub fn as_mut_preserves_cfg(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
114        &mut self.basic_blocks
115    }
116
117    /// Invalidates cached information about the CFG.
118    ///
119    /// You will only ever need this if you have also called [`BasicBlocks::as_mut_preserves_cfg`].
120    /// All other methods that allow you to mutate the basic blocks also call this method
121    /// themselves, thereby avoiding any risk of accidentally cache invalidation.
122    pub fn invalidate_cfg_cache(&mut self) {
123        self.cache = Cache::default();
124    }
125}
126
127impl<'tcx> std::ops::Deref for BasicBlocks<'tcx> {
128    type Target = IndexSlice<BasicBlock, BasicBlockData<'tcx>>;
129
130    #[inline]
131    fn deref(&self) -> &IndexSlice<BasicBlock, BasicBlockData<'tcx>> {
132        &self.basic_blocks
133    }
134}
135
136impl<'tcx> graph::DirectedGraph for BasicBlocks<'tcx> {
137    type Node = BasicBlock;
138
139    #[inline]
140    fn num_nodes(&self) -> usize {
141        self.basic_blocks.len()
142    }
143}
144
145impl<'tcx> graph::StartNode for BasicBlocks<'tcx> {
146    #[inline]
147    fn start_node(&self) -> Self::Node {
148        START_BLOCK
149    }
150}
151
152impl<'tcx> graph::Successors for BasicBlocks<'tcx> {
153    #[inline]
154    fn successors(&self, node: Self::Node) -> impl Iterator<Item = Self::Node> {
155        self.basic_blocks[node].terminator().successors()
156    }
157}
158
159impl<'tcx> graph::Predecessors for BasicBlocks<'tcx> {
160    #[inline]
161    fn predecessors(&self, node: Self::Node) -> impl Iterator<Item = Self::Node> {
162        self.predecessors()[node].iter().copied()
163    }
164}
165
166// Done here instead of in `structural_impls.rs` because `Cache` is private, as is `basic_blocks`.
167TrivialTypeTraversalImpls! { Cache }
168
169impl<S: Encoder> Encodable<S> for Cache {
170    #[inline]
171    fn encode(&self, _s: &mut S) {}
172}
173
174impl<D: Decoder> Decodable<D> for Cache {
175    #[inline]
176    fn decode(_: &mut D) -> Self {
177        Default::default()
178    }
179}
180
181impl<CTX> HashStable<CTX> for Cache {
182    #[inline]
183    fn hash_stable(&self, _: &mut CTX, _: &mut StableHasher) {}
184}