1 //! Lazily compute the inverse of each `SwitchInt`'s switch targets. Modeled after
2 //! `Predecessors`/`PredecessorCache`.
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_data_structures::sync::OnceCell;
7 use rustc_index::vec::IndexVec;
8 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
9 use smallvec::SmallVec;
11 use crate::mir::{BasicBlock, BasicBlockData, Terminator, TerminatorKind};
13 pub type SwitchSources = FxHashMap<(BasicBlock, BasicBlock), SmallVec<[Option<u128>; 1]>>;
15 #[derive(Clone, Debug)]
16 pub(super) struct SwitchSourceCache {
17 cache: OnceCell<SwitchSources>,
20 impl SwitchSourceCache {
22 pub(super) fn new() -> Self {
23 SwitchSourceCache { cache: OnceCell::new() }
26 /// Invalidates the switch source cache.
28 pub(super) fn invalidate(&mut self) {
29 self.cache = OnceCell::new();
32 /// Returns the switch sources for this MIR.
34 pub(super) fn compute(
36 basic_blocks: &IndexVec<BasicBlock, BasicBlockData<'_>>,
38 self.cache.get_or_init(|| {
39 let mut switch_sources: SwitchSources = FxHashMap::default();
40 for (bb, data) in basic_blocks.iter_enumerated() {
41 if let Some(Terminator {
42 kind: TerminatorKind::SwitchInt { targets, .. }, ..
45 for (value, target) in targets.iter() {
46 switch_sources.entry((target, bb)).or_default().push(Some(value));
48 switch_sources.entry((targets.otherwise(), bb)).or_default().push(None);
57 impl<S: Encoder> Encodable<S> for SwitchSourceCache {
59 fn encode(&self, _s: &mut S) {}
62 impl<D: Decoder> Decodable<D> for SwitchSourceCache {
64 fn decode(_: &mut D) -> Self {
69 impl<CTX> HashStable<CTX> for SwitchSourceCache {
71 fn hash_stable(&self, _: &mut CTX, _: &mut StableHasher) {
76 TrivialTypeTraversalAndLiftImpls! {