Skip to main content

rustc_middle/mir/
basic_blocks.rs

1use std::sync::{Arc, OnceLock};
2
3use rustc_data_structures::graph;
4use rustc_data_structures::graph::dominators::{Dominators, dominators};
5use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
6use rustc_index::{IndexSlice, IndexVec};
7use rustc_macros::{StableHash, 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};
13
14#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for BasicBlocks<'tcx>
    {
    #[inline]
    fn clone(&self) -> Self {
        BasicBlocks {
            basic_blocks: ::core::clone::Clone::clone(&self.basic_blocks),
            cache: ::core::clone::Clone::clone(&self.cache),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for BasicBlocks<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let BasicBlocks {
                        basic_blocks: ref __binding_0, cache: ref __binding_1 } =
                    *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for BasicBlocks<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                BasicBlocks {
                    basic_blocks: ::rustc_serialize::Decodable::decode(__decoder),
                    cache: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for BasicBlocks<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "BasicBlocks basic_blocks cache", &self.basic_blocks,
            &&self.cache)
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            BasicBlocks<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    BasicBlocks {
                        basic_blocks: ref __binding_0, cache: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for BasicBlocks<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        BasicBlocks { basic_blocks: __binding_0, cache: __binding_1
                            } => {
                            BasicBlocks {
                                basic_blocks: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                cache: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    BasicBlocks { basic_blocks: __binding_0, cache: __binding_1
                        } => {
                        BasicBlocks {
                            basic_blocks: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            cache: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for BasicBlocks<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    BasicBlocks {
                        basic_blocks: ref __binding_0, cache: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
15pub struct BasicBlocks<'tcx> {
16    basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
17    /// Use an `Arc` so we can share the cache when we clone the MIR body, as borrowck does.
18    cache: Arc<CfgCache>,
19}
20
21// Typically 95%+ of basic blocks have 4 or fewer predecessors.
22pub type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>;
23
24#[derive(#[automatically_derived]impl ::core::clone::Clone for CfgCache {
    #[inline]
    fn clone(&self) -> Self {
        CfgCache {
            predecessors: ::core::clone::Clone::clone(&self.predecessors),
            reverse_postorder: ::core::clone::Clone::clone(&self.reverse_postorder),
            dominators: ::core::clone::Clone::clone(&self.dominators),
        }
    }
}Clone, #[automatically_derived]impl ::core::default::Default for CfgCache {
    #[inline]
    fn default() -> Self {
        CfgCache {
            predecessors: ::core::default::Default::default(),
            reverse_postorder: ::core::default::Default::default(),
            dominators: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]impl ::core::fmt::Debug for CfgCache {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "CfgCache predecessors reverse_postorder dominators",
            &self.predecessors, &self.reverse_postorder, &&self.dominators)
    }
}Debug)]
25pub struct CfgCache {
26    predecessors: OnceLock<Predecessors>,
27    reverse_postorder: OnceLock<Vec<BasicBlock>>,
28    dominators: OnceLock<Dominators<BasicBlock>>,
29}
30
31impl CfgCache {
32    #[inline]
33    pub fn dominators(self: &Arc<Self>, bbs: &BasicBlocks<'_>) -> &Dominators<BasicBlock> {
34        if true {
    if !Arc::ptr_eq(self, &bbs.cache) {
        ::core::panicking::panic("assertion failed: Arc::ptr_eq(self, &bbs.cache)")
    };
};debug_assert!(Arc::ptr_eq(self, &bbs.cache));
35        self.dominators.get_or_init(|| dominators(bbs))
36    }
37
38    #[inline]
39    pub fn reverse_postorder(self: &Arc<Self>, bbs: &BasicBlocks<'_>) -> &[BasicBlock] {
40        if true {
    if !Arc::ptr_eq(self, &bbs.cache) {
        ::core::panicking::panic("assertion failed: Arc::ptr_eq(self, &bbs.cache)")
    };
};debug_assert!(Arc::ptr_eq(self, &bbs.cache));
41        self.reverse_postorder.get_or_init(|| {
42            let mut rpo: Vec<_> = Postorder::new(&bbs.basic_blocks, START_BLOCK, None).collect();
43            rpo.reverse();
44            rpo
45        })
46    }
47
48    #[inline]
49    pub fn predecessors(self: &Arc<Self>, bbs: &BasicBlocks<'_>) -> &Predecessors {
50        if true {
    if !Arc::ptr_eq(self, &bbs.cache) {
        ::core::panicking::panic("assertion failed: Arc::ptr_eq(self, &bbs.cache)")
    };
};debug_assert!(Arc::ptr_eq(self, &bbs.cache));
51        self.predecessors.get_or_init(|| {
52            let mut preds = IndexVec::from_elem(SmallVec::new(), &bbs.basic_blocks);
53            for (bb, data) in bbs.basic_blocks.iter_enumerated() {
54                for succ in data.terminator().successors() {
55                    preds[succ].push(bb);
56                }
57            }
58            preds
59        })
60    }
61}
62
63impl<'tcx> BasicBlocks<'tcx> {
64    #[inline]
65    pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
66        BasicBlocks { basic_blocks, cache: Arc::new(CfgCache::default()) }
67    }
68
69    #[inline]
70    pub fn cfg_cache(&self) -> Arc<CfgCache> {
71        Arc::clone(&self.cache)
72    }
73
74    #[inline]
75    pub fn dominators(&self) -> &Dominators<BasicBlock> {
76        self.cache.dominators(self)
77    }
78
79    /// Returns predecessors for each basic block.
80    #[inline]
81    pub fn predecessors(&self) -> &Predecessors {
82        self.cache.predecessors(self)
83    }
84
85    /// Returns basic blocks in a reverse postorder.
86    ///
87    /// See [`traversal::reverse_postorder`]'s docs to learn what is postorder traversal.
88    ///
89    /// [`traversal::reverse_postorder`]: crate::mir::traversal::reverse_postorder
90    #[inline]
91    pub fn reverse_postorder(&self) -> &[BasicBlock] {
92        self.cache.reverse_postorder(self)
93    }
94
95    /// Returns mutable reference to basic blocks. Invalidates CFG cache.
96    #[inline]
97    pub fn as_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
98        self.invalidate_cfg_cache();
99        &mut self.basic_blocks
100    }
101
102    /// Get mutable access to basic blocks without invalidating the CFG cache.
103    ///
104    /// By calling this method instead of e.g. [`BasicBlocks::as_mut`] you promise not to change
105    /// the CFG. This means that
106    ///
107    ///  1) The number of basic blocks remains unchanged
108    ///  2) The set of successors of each terminator remains unchanged.
109    ///  3) For each `TerminatorKind::SwitchInt`, the `targets` remains the same and the terminator
110    ///     kind is not changed.
111    ///
112    /// If any of these conditions cannot be upheld, you should call [`BasicBlocks::invalidate_cfg_cache`].
113    #[inline]
114    pub fn as_mut_preserves_cfg(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
115        &mut self.basic_blocks
116    }
117
118    /// Invalidates cached information about the CFG.
119    ///
120    /// You will only ever need this if you have also called [`BasicBlocks::as_mut_preserves_cfg`].
121    /// All other methods that allow you to mutate the basic blocks also call this method
122    /// themselves, thereby avoiding any risk of accidentally cache invalidation.
123    pub fn invalidate_cfg_cache(&mut self) {
124        if let Some(cache) = Arc::get_mut(&mut self.cache) {
125            // If we only have a single reference to this cache, clear it.
126            *cache = CfgCache::default();
127        } else {
128            // If we have several references to this cache, overwrite the pointer itself so other
129            // users can continue to use their (valid) cache.
130            self.cache = Arc::new(CfgCache::default());
131        }
132    }
133}
134
135impl<'tcx> std::ops::Deref for BasicBlocks<'tcx> {
136    type Target = IndexSlice<BasicBlock, BasicBlockData<'tcx>>;
137
138    #[inline]
139    fn deref(&self) -> &IndexSlice<BasicBlock, BasicBlockData<'tcx>> {
140        &self.basic_blocks
141    }
142}
143
144impl<'tcx> graph::DirectedGraph for BasicBlocks<'tcx> {
145    type Node = BasicBlock;
146
147    #[inline]
148    fn num_nodes(&self) -> usize {
149        self.basic_blocks.len()
150    }
151}
152
153impl<'tcx> graph::StartNode for BasicBlocks<'tcx> {
154    #[inline]
155    fn start_node(&self) -> Self::Node {
156        START_BLOCK
157    }
158}
159
160impl<'tcx> graph::Successors for BasicBlocks<'tcx> {
161    #[inline]
162    fn successors(&self, node: Self::Node) -> impl Iterator<Item = Self::Node> {
163        self.basic_blocks[node].terminator().successors()
164    }
165}
166
167impl<'tcx> graph::Predecessors for BasicBlocks<'tcx> {
168    #[inline]
169    fn predecessors(&self, node: Self::Node) -> impl Iterator<Item = Self::Node> {
170        self.predecessors()[node].iter().copied()
171    }
172}
173
174// Done here instead of in `structural_impls.rs` because `Cache` is private, as is `basic_blocks`.
175impl<'tcx> crate::ty::TypeFoldable<crate::ty::TyCtxt<'tcx>> for CfgCache {
    fn try_fold_with<F: crate::ty::FallibleTypeFolder<crate::ty::TyCtxt<'tcx>>>(self,
        _: &mut F) -> ::std::result::Result<Self, F::Error> {
        Ok(self)
    }
    #[inline]
    fn fold_with<F: crate::ty::TypeFolder<crate::ty::TyCtxt<'tcx>>>(self,
        _: &mut F) -> Self {
        self
    }
}
impl<'tcx> crate::ty::TypeVisitable<crate::ty::TyCtxt<'tcx>> for CfgCache {
    #[inline]
    fn visit_with<F: crate::ty::TypeVisitor<crate::ty::TyCtxt<'tcx>>>(&self,
        _: &mut F) -> F::Result {
        <F::Result as ::rustc_middle::ty::VisitorResult>::output()
    }
}TrivialTypeTraversalImpls! { CfgCache }
176
177impl<S: Encoder> Encodable<S> for CfgCache {
178    #[inline]
179    fn encode(&self, _s: &mut S) {}
180}
181
182impl<D: Decoder> Decodable<D> for CfgCache {
183    #[inline]
184    fn decode(_: &mut D) -> Self {
185        Default::default()
186    }
187}
188
189impl StableHash for CfgCache {
190    #[inline]
191    fn stable_hash<Hcx: StableHashCtxt>(&self, _: &mut Hcx, _: &mut StableHasher) {}
192}