Skip to main content

rustc_middle/mir/
terminator.rs

1//! Functionality for terminators and helper types that appear in terminators.
2
3use std::slice;
4
5use rustc_ast::InlineAsmOptions;
6use rustc_data_structures::packed::Pu128;
7use rustc_hir::LangItem;
8use rustc_hir::attrs::AttributeKind;
9use rustc_macros::{StableHash, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
10use smallvec::{SmallVec, smallvec};
11use thin_vec::ThinVec;
12
13use super::*;
14
15impl SwitchTargets {
16    /// Creates switch targets from an iterator of values and target blocks.
17    ///
18    /// The iterator may be empty, in which case the `SwitchInt` instruction is equivalent to
19    /// `goto otherwise;`.
20    pub fn new(targets: impl Iterator<Item = (u128, BasicBlock)>, otherwise: BasicBlock) -> Self {
21        let (values, mut targets): (SmallVec<_>, SmallVec<_>) =
22            targets.map(|(v, t)| (Pu128(v), t)).unzip();
23        targets.push(otherwise);
24        Self { values, targets }
25    }
26
27    /// Builds a switch targets definition that jumps to `then` if the tested value equals `value`,
28    /// and to `else_` if not.
29    pub fn static_if(value: u128, then: BasicBlock, else_: BasicBlock) -> Self {
30        Self { values: {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(Pu128(value));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [Pu128(value)])))
    }
}smallvec![Pu128(value)], targets: {
    let count = 0usize + 1usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(then);
        vec.push(else_);
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [then, else_])))
    }
}smallvec![then, else_] }
31    }
32
33    /// Inverse of `SwitchTargets::static_if`.
34    #[inline]
35    pub fn as_static_if(&self) -> Option<(u128, BasicBlock, BasicBlock)> {
36        if let &[value] = &self.values[..]
37            && let &[then, else_] = &self.targets[..]
38        {
39            Some((value.get(), then, else_))
40        } else {
41            None
42        }
43    }
44
45    /// Returns the fallback target that is jumped to when none of the values match the operand.
46    #[inline]
47    pub fn otherwise(&self) -> BasicBlock {
48        *self.targets.last().unwrap()
49    }
50
51    /// Returns an iterator over the switch targets.
52    ///
53    /// The iterator will yield tuples containing the value and corresponding target to jump to, not
54    /// including the `otherwise` fallback target.
55    ///
56    /// Note that this may yield 0 elements. Only the `otherwise` branch is mandatory.
57    #[inline]
58    pub fn iter(&self) -> SwitchTargetsIter<'_> {
59        SwitchTargetsIter { inner: iter::zip(&self.values, &self.targets) }
60    }
61
62    /// Returns a slice with all possible jump targets (including the fallback target).
63    #[inline]
64    pub fn all_targets(&self) -> &[BasicBlock] {
65        &self.targets
66    }
67
68    #[inline]
69    pub fn all_targets_mut(&mut self) -> &mut [BasicBlock] {
70        &mut self.targets
71    }
72
73    /// Returns a slice with all considered values (not including the fallback).
74    #[inline]
75    pub fn all_values(&self) -> &[Pu128] {
76        &self.values
77    }
78
79    #[inline]
80    pub fn all_values_mut(&mut self) -> &mut [Pu128] {
81        &mut self.values
82    }
83
84    /// Finds the `BasicBlock` to which this `SwitchInt` will branch given the
85    /// specific value. This cannot fail, as it'll return the `otherwise`
86    /// branch if there's not a specific match for the value.
87    #[inline]
88    pub fn target_for_value(&self, value: u128) -> BasicBlock {
89        self.iter().find_map(|(v, t)| (v == value).then_some(t)).unwrap_or_else(|| self.otherwise())
90    }
91
92    /// Adds a new target to the switch. Panics if you add an already present value.
93    #[inline]
94    pub fn add_target(&mut self, value: u128, bb: BasicBlock) {
95        let value = Pu128(value);
96        if self.values.contains(&value) {
97            crate::util::bug::bug_fmt(format_args!("target value {0:?} already present",
        value));bug!("target value {:?} already present", value);
98        }
99        self.values.push(value);
100        self.targets.insert(self.targets.len() - 1, bb);
101    }
102
103    /// Returns true if all targets (including the fallback target) are distinct.
104    #[inline]
105    pub fn is_distinct(&self) -> bool {
106        self.targets.iter().collect::<FxHashSet<_>>().len() == self.targets.len()
107    }
108}
109
110pub struct SwitchTargetsIter<'a> {
111    inner: iter::Zip<slice::Iter<'a, Pu128>, slice::Iter<'a, BasicBlock>>,
112}
113
114impl<'a> Iterator for SwitchTargetsIter<'a> {
115    type Item = (u128, BasicBlock);
116
117    #[inline]
118    fn next(&mut self) -> Option<Self::Item> {
119        self.inner.next().map(|(val, bb)| (val.get(), *bb))
120    }
121
122    #[inline]
123    fn size_hint(&self) -> (usize, Option<usize>) {
124        self.inner.size_hint()
125    }
126}
127
128impl<'a> ExactSizeIterator for SwitchTargetsIter<'a> {}
129
130impl UnwindAction {
131    fn cleanup_block(self) -> Option<BasicBlock> {
132        match self {
133            UnwindAction::Cleanup(bb) => Some(bb),
134            UnwindAction::Continue | UnwindAction::Unreachable | UnwindAction::Terminate(_) => None,
135        }
136    }
137}
138
139impl UnwindTerminateReason {
140    pub fn as_str(self) -> &'static str {
141        // Keep this in sync with the messages in `core/src/panicking.rs`.
142        match self {
143            UnwindTerminateReason::Abi => "panic in a function that cannot unwind",
144            UnwindTerminateReason::InCleanup => "panic in a destructor during cleanup",
145        }
146    }
147
148    /// A short representation of this used for MIR printing.
149    pub fn as_short_str(self) -> &'static str {
150        match self {
151            UnwindTerminateReason::Abi => "abi",
152            UnwindTerminateReason::InCleanup => "cleanup",
153        }
154    }
155
156    pub fn lang_item(self) -> LangItem {
157        match self {
158            UnwindTerminateReason::Abi => LangItem::PanicCannotUnwind,
159            UnwindTerminateReason::InCleanup => LangItem::PanicInCleanup,
160        }
161    }
162}
163
164impl<O> AssertKind<O> {
165    /// Returns true if this an overflow checking assertion controlled by -C overflow-checks.
166    pub fn is_optional_overflow_check(&self) -> bool {
167        use AssertKind::*;
168        use BinOp::*;
169        #[allow(non_exhaustive_omitted_patterns)] match self {
    OverflowNeg(..) | Overflow(Add | Sub | Mul | Shl | Shr, ..) => true,
    _ => false,
}matches!(self, OverflowNeg(..) | Overflow(Add | Sub | Mul | Shl | Shr, ..))
170    }
171
172    /// Get the lang item that is invoked to print a static message when this assert fires.
173    ///
174    /// The caller is expected to handle `BoundsCheck` and `MisalignedPointerDereference` by
175    /// invoking the appropriate lang item (panic_bounds_check/panic_misaligned_pointer_dereference)
176    /// instead of printing a static message. Those have dynamic arguments that aren't present for
177    /// the rest of the messages here.
178    pub fn panic_function(&self) -> LangItem {
179        use AssertKind::*;
180        match self {
181            Overflow(BinOp::Add, _, _) => LangItem::PanicAddOverflow,
182            Overflow(BinOp::Sub, _, _) => LangItem::PanicSubOverflow,
183            Overflow(BinOp::Mul, _, _) => LangItem::PanicMulOverflow,
184            Overflow(BinOp::Div, _, _) => LangItem::PanicDivOverflow,
185            Overflow(BinOp::Rem, _, _) => LangItem::PanicRemOverflow,
186            OverflowNeg(_) => LangItem::PanicNegOverflow,
187            Overflow(BinOp::Shr, _, _) => LangItem::PanicShrOverflow,
188            Overflow(BinOp::Shl, _, _) => LangItem::PanicShlOverflow,
189            Overflow(op, _, _) => crate::util::bug::bug_fmt(format_args!("{0:?} cannot overflow", op))bug!("{:?} cannot overflow", op),
190            DivisionByZero(_) => LangItem::PanicDivZero,
191            RemainderByZero(_) => LangItem::PanicRemZero,
192            ResumedAfterReturn(CoroutineKind::Coroutine(_)) => LangItem::PanicCoroutineResumed,
193            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
194                LangItem::PanicAsyncFnResumed
195            }
196            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
197                LangItem::PanicAsyncGenFnResumed
198            }
199            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
200                LangItem::PanicGenFnNone
201            }
202            ResumedAfterPanic(CoroutineKind::Coroutine(_)) => LangItem::PanicCoroutineResumedPanic,
203            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
204                LangItem::PanicAsyncFnResumedPanic
205            }
206            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
207                LangItem::PanicAsyncGenFnResumedPanic
208            }
209            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
210                LangItem::PanicGenFnNonePanic
211            }
212            NullPointerDereference => LangItem::PanicNullPointerDereference,
213            NullReferenceConstructed => LangItem::PanicNullReferenceConstructed,
214            InvalidEnumConstruction(_) => LangItem::PanicInvalidEnumConstruction,
215            ResumedAfterDrop(CoroutineKind::Coroutine(_)) => LangItem::PanicCoroutineResumedDrop,
216            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
217                LangItem::PanicAsyncFnResumedDrop
218            }
219            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
220                LangItem::PanicAsyncGenFnResumedDrop
221            }
222            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
223                LangItem::PanicGenFnNoneDrop
224            }
225
226            BoundsCheck { .. } | MisalignedPointerDereference { .. } => {
227                crate::util::bug::bug_fmt(format_args!("Unexpected AssertKind"))bug!("Unexpected AssertKind")
228            }
229        }
230    }
231
232    /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
233    ///
234    /// Needs to be kept in sync with the run-time behavior (which is defined by
235    /// `AssertKind::panic_function` and the lang items mentioned in its docs).
236    /// Note that we deliberately show more details here than we do at runtime, such as the actual
237    /// numbers that overflowed -- it is much easier to do so here than at runtime.
238    pub fn fmt_assert_args<W: fmt::Write>(&self, f: &mut W) -> fmt::Result
239    where
240        O: Debug,
241    {
242        use AssertKind::*;
243        match self {
244            BoundsCheck { len, index } => f.write_fmt(format_args!("\"index out of bounds: the length is {{}} but the index is {{}}\", {0:?}, {1:?}",
        len, index))write!(
245                f,
246                "\"index out of bounds: the length is {{}} but the index is {{}}\", {len:?}, {index:?}"
247            ),
248
249            OverflowNeg(op) => {
250                f.write_fmt(format_args!("\"attempt to negate `{{}}`, which would overflow\", {0:?}",
        op))write!(f, "\"attempt to negate `{{}}`, which would overflow\", {op:?}")
251            }
252            DivisionByZero(op) => f.write_fmt(format_args!("\"attempt to divide `{{}}` by zero\", {0:?}", op))write!(f, "\"attempt to divide `{{}}` by zero\", {op:?}"),
253            RemainderByZero(op) => f.write_fmt(format_args!("\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {0:?}",
        op))write!(
254                f,
255                "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {op:?}"
256            ),
257            Overflow(BinOp::Add, l, r) => f.write_fmt(format_args!("\"attempt to compute `{{}} + {{}}`, which would overflow\", {0:?}, {1:?}",
        l, r))write!(
258                f,
259                "\"attempt to compute `{{}} + {{}}`, which would overflow\", {l:?}, {r:?}"
260            ),
261            Overflow(BinOp::Sub, l, r) => f.write_fmt(format_args!("\"attempt to compute `{{}} - {{}}`, which would overflow\", {0:?}, {1:?}",
        l, r))write!(
262                f,
263                "\"attempt to compute `{{}} - {{}}`, which would overflow\", {l:?}, {r:?}"
264            ),
265            Overflow(BinOp::Mul, l, r) => f.write_fmt(format_args!("\"attempt to compute `{{}} * {{}}`, which would overflow\", {0:?}, {1:?}",
        l, r))write!(
266                f,
267                "\"attempt to compute `{{}} * {{}}`, which would overflow\", {l:?}, {r:?}"
268            ),
269            Overflow(BinOp::Div, l, r) => f.write_fmt(format_args!("\"attempt to compute `{{}} / {{}}`, which would overflow\", {0:?}, {1:?}",
        l, r))write!(
270                f,
271                "\"attempt to compute `{{}} / {{}}`, which would overflow\", {l:?}, {r:?}"
272            ),
273            Overflow(BinOp::Rem, l, r) => f.write_fmt(format_args!("\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {0:?}, {1:?}",
        l, r))write!(
274                f,
275                "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {l:?}, {r:?}"
276            ),
277            Overflow(BinOp::Shr, _, r) => {
278                f.write_fmt(format_args!("\"attempt to shift right by `{{}}`, which would overflow\", {0:?}",
        r))write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {r:?}")
279            }
280            Overflow(BinOp::Shl, _, r) => {
281                f.write_fmt(format_args!("\"attempt to shift left by `{{}}`, which would overflow\", {0:?}",
        r))write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {r:?}")
282            }
283            Overflow(op, _, _) => crate::util::bug::bug_fmt(format_args!("{0:?} cannot overflow", op))bug!("{:?} cannot overflow", op),
284            MisalignedPointerDereference { required, found } => {
285                f.write_fmt(format_args!("\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {0:?}, {1:?}",
        required, found))write!(
286                    f,
287                    "\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {required:?}, {found:?}"
288                )
289            }
290            NullPointerDereference => f.write_fmt(format_args!("\"null pointer dereference occurred\""))write!(f, "\"null pointer dereference occurred\""),
291            NullReferenceConstructed => f.write_fmt(format_args!("\"null reference produced\""))write!(f, "\"null reference produced\""),
292            InvalidEnumConstruction(source) => {
293                f.write_fmt(format_args!("\"trying to construct an enum from an invalid value {{}}\", {0:?}",
        source))write!(f, "\"trying to construct an enum from an invalid value {{}}\", {source:?}")
294            }
295            ResumedAfterReturn(CoroutineKind::Coroutine(_)) => {
296                f.write_fmt(format_args!("\"coroutine resumed after completion\""))write!(f, "\"coroutine resumed after completion\"")
297            }
298            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
299                f.write_fmt(format_args!("\"`async fn` resumed after completion\""))write!(f, "\"`async fn` resumed after completion\"")
300            }
301            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
302                f.write_fmt(format_args!("\"`async gen fn` resumed after completion\""))write!(f, "\"`async gen fn` resumed after completion\"")
303            }
304            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
305                f.write_fmt(format_args!("\"`gen fn` should just keep returning `None` after completion\""))write!(f, "\"`gen fn` should just keep returning `None` after completion\"")
306            }
307            ResumedAfterPanic(CoroutineKind::Coroutine(_)) => {
308                f.write_fmt(format_args!("\"coroutine resumed after panicking\""))write!(f, "\"coroutine resumed after panicking\"")
309            }
310            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
311                f.write_fmt(format_args!("\"`async fn` resumed after panicking\""))write!(f, "\"`async fn` resumed after panicking\"")
312            }
313            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
314                f.write_fmt(format_args!("\"`async gen fn` resumed after panicking\""))write!(f, "\"`async gen fn` resumed after panicking\"")
315            }
316            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
317                f.write_fmt(format_args!("\"`gen fn` should just keep returning `None` after panicking\""))write!(f, "\"`gen fn` should just keep returning `None` after panicking\"")
318            }
319            ResumedAfterDrop(CoroutineKind::Coroutine(_)) => {
320                f.write_fmt(format_args!("\"coroutine resumed after async drop\""))write!(f, "\"coroutine resumed after async drop\"")
321            }
322            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
323                f.write_fmt(format_args!("\"`async fn` resumed after async drop\""))write!(f, "\"`async fn` resumed after async drop\"")
324            }
325            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
326                f.write_fmt(format_args!("\"`async gen fn` resumed after async drop\""))write!(f, "\"`async gen fn` resumed after async drop\"")
327            }
328            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
329                f.write_fmt(format_args!("\"`gen fn` resumed after drop\""))write!(f, "\"`gen fn` resumed after drop\"")
330            }
331        }
332    }
333}
334
335/// Format the diagnostic message for use in a lint (e.g. when the assertion fails during const-eval).
336///
337/// Needs to be kept in sync with the run-time behavior (which is defined by
338/// `AssertKind::panic_function` and the lang items mentioned in its docs).
339/// Note that we deliberately show more details here than we do at runtime, such as the actual
340/// numbers that overflowed -- it is much easier to do so here than at runtime.
341impl<O: fmt::Debug> fmt::Display for AssertKind<O> {
342    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
343        use AssertKind::*;
344
345        match self {
346            BoundsCheck { len, index } => {
347                f.write_fmt(format_args!("index out of bounds: the length is {0:?} but the index is {1:?}",
        len, index))write!(f, "index out of bounds: the length is {len:?} but the index is {index:?}")
348            }
349            Overflow(BinOp::Shl, _, val) => {
350                f.write_fmt(format_args!("attempt to shift left by `{0:#?}`, which would overflow",
        val))write!(f, "attempt to shift left by `{val:#?}`, which would overflow")
351            }
352            Overflow(BinOp::Shr, _, val) => {
353                f.write_fmt(format_args!("attempt to shift right by `{0:#?}`, which would overflow",
        val))write!(f, "attempt to shift right by `{val:#?}`, which would overflow")
354            }
355            Overflow(binop, left, right) => {
356                f.write_fmt(format_args!("attempt to compute `{1:#?} {0} {2:#?}`, which would overflow",
        binop.to_hir_binop().as_str(), left, right))write!(
357                    f,
358                    "attempt to compute `{left:#?} {op} {right:#?}`, which would overflow",
359                    op = binop.to_hir_binop().as_str()
360                )
361            }
362            OverflowNeg(val) => f.write_fmt(format_args!("attempt to negate `{0:#?}`, which would overflow",
        val))write!(f, "attempt to negate `{val:#?}`, which would overflow"),
363            DivisionByZero(val) => f.write_fmt(format_args!("attempt to divide `{0:#?}` by zero", val))write!(f, "attempt to divide `{val:#?}` by zero"),
364            RemainderByZero(val) => {
365                f.write_fmt(format_args!("attempt to calculate the remainder of `{0:#?}` with a divisor of zero",
        val))write!(f, "attempt to calculate the remainder of `{val:#?}` with a divisor of zero")
366            }
367            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
368                f.write_fmt(format_args!("`async fn` resumed after completion"))write!(f, "`async fn` resumed after completion")
369            }
370            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
371                ::core::panicking::panic("not implemented")unimplemented!()
372            }
373            ResumedAfterReturn(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
374                crate::util::bug::bug_fmt(format_args!("gen blocks can be resumed after they return and will keep returning `None`"))bug!("gen blocks can be resumed after they return and will keep returning `None`")
375            }
376            ResumedAfterReturn(CoroutineKind::Coroutine(_)) => {
377                f.write_fmt(format_args!("coroutine resumed after completion"))write!(f, "coroutine resumed after completion")
378            }
379            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
380                f.write_fmt(format_args!("`async fn` resumed after panicking"))write!(f, "`async fn` resumed after panicking")
381            }
382            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
383                ::core::panicking::panic("not implemented")unimplemented!()
384            }
385            ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
386                f.write_fmt(format_args!("`gen` fn or block cannot be further iterated on after it panicked"))write!(f, "`gen` fn or block cannot be further iterated on after it panicked")
387            }
388            ResumedAfterPanic(CoroutineKind::Coroutine(_)) => {
389                f.write_fmt(format_args!("coroutine resumed after panicking"))write!(f, "coroutine resumed after panicking")
390            }
391            NullPointerDereference => f.write_fmt(format_args!("null pointer dereference occurred"))write!(f, "null pointer dereference occurred"),
392            NullReferenceConstructed => f.write_fmt(format_args!("null reference produced"))write!(f, "null reference produced"),
393            InvalidEnumConstruction(source) => {
394                f.write_fmt(format_args!("trying to construct an enum from an invalid value `{0:#?}`",
        source))write!(f, "trying to construct an enum from an invalid value `{source:#?}`")
395            }
396            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) => {
397                f.write_fmt(format_args!("`async fn` resumed after async drop"))write!(f, "`async fn` resumed after async drop")
398            }
399            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)) => {
400                ::core::panicking::panic("not implemented")unimplemented!()
401            }
402            ResumedAfterDrop(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
403                f.write_fmt(format_args!("`gen` fn or block cannot be further iterated on after it async dropped"))write!(f, "`gen` fn or block cannot be further iterated on after it async dropped")
404            }
405            ResumedAfterDrop(CoroutineKind::Coroutine(_)) => {
406                f.write_fmt(format_args!("coroutine resumed after async drop"))write!(f, "coroutine resumed after async drop")
407            }
408
409            MisalignedPointerDereference { required, found } => f.write_fmt(format_args!("misaligned pointer dereference: address must be a multiple of {0:#?} but is {1:#?}",
        required, found))write!(
410                f,
411                "misaligned pointer dereference: address must be a multiple of {required:#?} but is {found:#?}"
412            ),
413        }
414    }
415}
416
417#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Terminator<'tcx> {
    #[inline]
    fn clone(&self) -> Terminator<'tcx> {
        Terminator {
            source_info: ::core::clone::Clone::clone(&self.source_info),
            kind: ::core::clone::Clone::clone(&self.kind),
            attributes: ::core::clone::Clone::clone(&self.attributes),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for Terminator<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    Terminator {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        attributes: ref __binding_2 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for Terminator<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                Terminator {
                    source_info: ::rustc_serialize::Decodable::decode(__decoder),
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                    attributes: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            Terminator<'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 {
                    Terminator {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        attributes: ref __binding_2 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Terminator<'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 {
                        Terminator {
                            source_info: __binding_0,
                            kind: __binding_1,
                            attributes: __binding_2 } => {
                            Terminator {
                                source_info: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                kind: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                attributes: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    Terminator {
                        source_info: __binding_0,
                        kind: __binding_1,
                        attributes: __binding_2 } => {
                        Terminator {
                            source_info: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            kind: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            attributes: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Terminator<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    Terminator {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        attributes: ref __binding_2 } => {
                        {
                            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);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __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)]
418pub struct Terminator<'tcx> {
419    pub source_info: SourceInfo,
420    pub kind: TerminatorKind<'tcx>,
421    pub attributes: ThinVec<AttributeKind>,
422}
423
424impl<'tcx> Terminator<'tcx> {
425    #[inline]
426    pub fn successors(&self) -> Successors<'_> {
427        self.kind.successors()
428    }
429
430    /// Return `Some` if all successors are identical.
431    #[inline]
432    pub fn identical_successor(&self) -> Option<BasicBlock> {
433        let mut successors = self.successors();
434        let first_succ = successors.next()?;
435        if successors.all(|succ| first_succ == succ) { Some(first_succ) } else { None }
436    }
437
438    #[inline]
439    pub fn successors_mut<'a>(&'a mut self, f: impl FnMut(&'a mut BasicBlock)) {
440        self.kind.successors_mut(f)
441    }
442
443    #[inline]
444    pub fn unwind(&self) -> Option<&UnwindAction> {
445        self.kind.unwind()
446    }
447
448    #[inline]
449    pub fn unwind_mut(&mut self) -> Option<&mut UnwindAction> {
450        self.kind.unwind_mut()
451    }
452}
453
454impl<'tcx> TerminatorKind<'tcx> {
455    /// Returns a simple string representation of a `TerminatorKind` variant, independent of any
456    /// values it might hold (e.g. `TerminatorKind::Call` always returns `"Call"`).
457    pub const fn name(&self) -> &'static str {
458        match self {
459            TerminatorKind::Goto { .. } => "Goto",
460            TerminatorKind::SwitchInt { .. } => "SwitchInt",
461            TerminatorKind::UnwindResume => "UnwindResume",
462            TerminatorKind::UnwindTerminate(_) => "UnwindTerminate",
463            TerminatorKind::Return => "Return",
464            TerminatorKind::Unreachable => "Unreachable",
465            TerminatorKind::Drop { .. } => "Drop",
466            TerminatorKind::Call { .. } => "Call",
467            TerminatorKind::TailCall { .. } => "TailCall",
468            TerminatorKind::Assert { .. } => "Assert",
469            TerminatorKind::Yield { .. } => "Yield",
470            TerminatorKind::CoroutineDrop => "CoroutineDrop",
471            TerminatorKind::FalseEdge { .. } => "FalseEdge",
472            TerminatorKind::FalseUnwind { .. } => "FalseUnwind",
473            TerminatorKind::InlineAsm { .. } => "InlineAsm",
474        }
475    }
476
477    #[inline]
478    pub fn if_(cond: Operand<'tcx>, t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
479        TerminatorKind::SwitchInt { discr: cond, targets: SwitchTargets::static_if(0, f, t) }
480    }
481}
482
483pub use helper::*;
484
485mod helper {
486    use super::*;
487    pub type Successors<'a> = impl DoubleEndedIterator<Item = BasicBlock> + 'a;
488
489    // Note: this method ensures all paths below produce an iterator with the same concrete type.
490    #[inline]
491    #[define_opaque(Successors)]
492    fn mk_successors(
493        slice: &[BasicBlock],
494        option1: Option<BasicBlock>,
495        option2: Option<BasicBlock>,
496    ) -> Successors<'_> {
497        slice.iter().copied().chain(option1.into_iter().chain(option2))
498    }
499
500    impl SwitchTargets {
501        /// Like [`SwitchTargets::target_for_value`], but returning the same type as
502        /// [`Terminator::successors`].
503        #[inline]
504        pub fn successors_for_value(&self, value: u128) -> Successors<'_> {
505            let target = self.target_for_value(value);
506            mk_successors(&[], Some(target), None)
507        }
508    }
509
510    impl<'tcx> TerminatorKind<'tcx> {
511        #[inline]
512        pub fn successors(&self) -> Successors<'_> {
513            use self::TerminatorKind::*;
514            match *self {
515                // 3-successors for async drop: target, unwind, dropline (parent coroutine drop)
516                Drop { target: ref t, unwind: UnwindAction::Cleanup(u), drop: Some(d), .. } => {
517                    mk_successors(slice::from_ref(t), Some(u), Some(d))
518                }
519                // 2-successors
520                Call { target: Some(ref t), unwind: UnwindAction::Cleanup(u), .. }
521                | Yield { resume: ref t, drop: Some(u), .. }
522                | Drop { target: ref t, unwind: UnwindAction::Cleanup(u), drop: None, .. }
523                | Drop { target: ref t, unwind: _, drop: Some(u), .. }
524                | Assert { target: ref t, unwind: UnwindAction::Cleanup(u), .. }
525                | FalseUnwind { real_target: ref t, unwind: UnwindAction::Cleanup(u) } => {
526                    mk_successors(slice::from_ref(t), Some(u), None)
527                }
528                // single successor
529                Goto { target: ref t }
530                | Call { target: None, unwind: UnwindAction::Cleanup(ref t), .. }
531                | Call { target: Some(ref t), unwind: _, .. }
532                | Yield { resume: ref t, drop: None, .. }
533                | Drop { target: ref t, unwind: _, .. }
534                | Assert { target: ref t, unwind: _, .. }
535                | FalseUnwind { real_target: ref t, unwind: _ } => {
536                    mk_successors(slice::from_ref(t), None, None)
537                }
538                // No successors
539                UnwindResume
540                | UnwindTerminate(_)
541                | CoroutineDrop
542                | Return
543                | Unreachable
544                | TailCall { .. }
545                | Call { target: None, unwind: _, .. } => mk_successors(&[], None, None),
546                // Multiple successors
547                InlineAsm { ref targets, unwind: UnwindAction::Cleanup(u), .. } => {
548                    mk_successors(targets, Some(u), None)
549                }
550                InlineAsm { ref targets, unwind: _, .. } => mk_successors(targets, None, None),
551                SwitchInt { ref targets, .. } => mk_successors(&targets.targets, None, None),
552                // FalseEdge
553                FalseEdge { ref real_target, imaginary_target } => {
554                    mk_successors(slice::from_ref(real_target), Some(imaginary_target), None)
555                }
556            }
557        }
558
559        #[inline]
560        pub fn successors_mut<'a>(&'a mut self, mut f: impl FnMut(&'a mut BasicBlock)) {
561            use self::TerminatorKind::*;
562            match self {
563                Drop { target, unwind, drop, .. } => {
564                    f(target);
565                    if let UnwindAction::Cleanup(u) = unwind {
566                        f(u)
567                    }
568                    if let Some(d) = drop {
569                        f(d)
570                    }
571                }
572                Call { target, unwind, .. } => {
573                    if let Some(target) = target {
574                        f(target);
575                    }
576                    if let UnwindAction::Cleanup(u) = unwind {
577                        f(u)
578                    }
579                }
580                Yield { resume, drop, .. } => {
581                    f(resume);
582                    if let Some(d) = drop {
583                        f(d)
584                    }
585                }
586                Assert { target, unwind, .. } | FalseUnwind { real_target: target, unwind } => {
587                    f(target);
588                    if let UnwindAction::Cleanup(u) = unwind {
589                        f(u)
590                    }
591                }
592                Goto { target } => {
593                    f(target);
594                }
595                UnwindResume
596                | UnwindTerminate(_)
597                | CoroutineDrop
598                | Return
599                | Unreachable
600                | TailCall { .. } => {}
601                InlineAsm { targets, unwind, .. } => {
602                    for target in targets {
603                        f(target);
604                    }
605                    if let UnwindAction::Cleanup(u) = unwind {
606                        f(u)
607                    }
608                }
609                SwitchInt { targets, .. } => {
610                    for target in &mut targets.targets {
611                        f(target);
612                    }
613                }
614                FalseEdge { real_target, imaginary_target } => {
615                    f(real_target);
616                    f(imaginary_target);
617                }
618            }
619        }
620    }
621}
622
623impl<'tcx> TerminatorKind<'tcx> {
624    #[inline]
625    pub fn unwind(&self) -> Option<&UnwindAction> {
626        match *self {
627            TerminatorKind::Goto { .. }
628            | TerminatorKind::UnwindResume
629            | TerminatorKind::UnwindTerminate(_)
630            | TerminatorKind::Return
631            | TerminatorKind::TailCall { .. }
632            | TerminatorKind::Unreachable
633            | TerminatorKind::CoroutineDrop
634            | TerminatorKind::Yield { .. }
635            | TerminatorKind::SwitchInt { .. }
636            | TerminatorKind::FalseEdge { .. } => None,
637            TerminatorKind::Call { ref unwind, .. }
638            | TerminatorKind::Assert { ref unwind, .. }
639            | TerminatorKind::Drop { ref unwind, .. }
640            | TerminatorKind::FalseUnwind { ref unwind, .. }
641            | TerminatorKind::InlineAsm { ref unwind, .. } => Some(unwind),
642        }
643    }
644
645    #[inline]
646    pub fn unwind_mut(&mut self) -> Option<&mut UnwindAction> {
647        match *self {
648            TerminatorKind::Goto { .. }
649            | TerminatorKind::UnwindResume
650            | TerminatorKind::UnwindTerminate(_)
651            | TerminatorKind::Return
652            | TerminatorKind::TailCall { .. }
653            | TerminatorKind::Unreachable
654            | TerminatorKind::CoroutineDrop
655            | TerminatorKind::Yield { .. }
656            | TerminatorKind::SwitchInt { .. }
657            | TerminatorKind::FalseEdge { .. } => None,
658            TerminatorKind::Call { ref mut unwind, .. }
659            | TerminatorKind::Assert { ref mut unwind, .. }
660            | TerminatorKind::Drop { ref mut unwind, .. }
661            | TerminatorKind::FalseUnwind { ref mut unwind, .. }
662            | TerminatorKind::InlineAsm { ref mut unwind, .. } => Some(unwind),
663        }
664    }
665
666    #[inline]
667    pub fn as_switch(&self) -> Option<(&Operand<'tcx>, &SwitchTargets)> {
668        match self {
669            TerminatorKind::SwitchInt { discr, targets } => Some((discr, targets)),
670            _ => None,
671        }
672    }
673
674    #[inline]
675    pub fn as_goto(&self) -> Option<BasicBlock> {
676        match self {
677            TerminatorKind::Goto { target } => Some(*target),
678            _ => None,
679        }
680    }
681}
682
683#[derive(#[automatically_derived]
impl<'mir, 'tcx> ::core::fmt::Debug for TerminatorEdges<'mir, 'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TerminatorEdges::None =>
                ::core::fmt::Formatter::write_str(f, "None"),
            TerminatorEdges::Single(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Single",
                    &__self_0),
            TerminatorEdges::Double(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Double",
                    __self_0, &__self_1),
            TerminatorEdges::AssignOnReturn {
                return_: __self_0, cleanup: __self_1, place: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "AssignOnReturn", "return_", __self_0, "cleanup", __self_1,
                    "place", &__self_2),
            TerminatorEdges::SwitchInt { targets: __self_0, discr: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "SwitchInt", "targets", __self_0, "discr", &__self_1),
        }
    }
}Debug)]
684pub enum TerminatorEdges<'mir, 'tcx> {
685    /// For terminators that have no successor, like `return`.
686    None,
687    /// For terminators that have a single successor, like `goto`, and `assert` without a cleanup
688    /// block.
689    Single(BasicBlock),
690    /// For terminators that have two successors, like `assert` with a cleanup block, and
691    /// `falseEdge`.
692    Double(BasicBlock, BasicBlock),
693    /// Special action for `Yield`, `Call` and `InlineAsm` terminators.
694    AssignOnReturn {
695        return_: SmallVec<[BasicBlock; 1]>,
696        /// The cleanup block, if it exists.
697        cleanup: Option<BasicBlock>,
698        place: CallReturnPlaces<'mir, 'tcx>,
699    },
700    /// Special edge for `SwitchInt`.
701    SwitchInt { targets: &'mir SwitchTargets, discr: &'mir Operand<'tcx> },
702}
703
704/// List of places that are written to after a successful (non-unwind) return
705/// from a `Call`, `Yield` or `InlineAsm`.
706#[derive(#[automatically_derived]
impl<'a, 'tcx> ::core::marker::Copy for CallReturnPlaces<'a, 'tcx> { }Copy, #[automatically_derived]
impl<'a, 'tcx> ::core::clone::Clone for CallReturnPlaces<'a, 'tcx> {
    #[inline]
    fn clone(&self) -> CallReturnPlaces<'a, 'tcx> {
        let _: ::core::clone::AssertParamIsClone<Place<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Place<'tcx>>;
        let _:
                ::core::clone::AssertParamIsClone<&'a [InlineAsmOperand<'tcx>]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a, 'tcx> ::core::fmt::Debug for CallReturnPlaces<'a, 'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            CallReturnPlaces::Call(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Call",
                    &__self_0),
            CallReturnPlaces::Yield(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Yield",
                    &__self_0),
            CallReturnPlaces::InlineAsm(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "InlineAsm", &__self_0),
        }
    }
}Debug)]
707pub enum CallReturnPlaces<'a, 'tcx> {
708    Call(Place<'tcx>),
709    Yield(Place<'tcx>),
710    InlineAsm(&'a [InlineAsmOperand<'tcx>]),
711}
712
713impl<'tcx> CallReturnPlaces<'_, 'tcx> {
714    pub fn for_each(&self, mut f: impl FnMut(Place<'tcx>)) {
715        match *self {
716            Self::Call(place) | Self::Yield(place) => f(place),
717            Self::InlineAsm(operands) => {
718                for op in operands {
719                    match *op {
720                        InlineAsmOperand::Out { place: Some(place), .. }
721                        | InlineAsmOperand::InOut { out_place: Some(place), .. } => f(place),
722                        _ => {}
723                    }
724                }
725            }
726        }
727    }
728}
729
730impl<'tcx> Terminator<'tcx> {
731    pub fn edges(&self) -> TerminatorEdges<'_, 'tcx> {
732        self.kind.edges()
733    }
734}
735
736impl<'tcx> TerminatorKind<'tcx> {
737    pub fn edges(&self) -> TerminatorEdges<'_, 'tcx> {
738        use TerminatorKind::*;
739        match *self {
740            Return
741            | TailCall { .. }
742            | UnwindResume
743            | UnwindTerminate(_)
744            | CoroutineDrop
745            | Unreachable => TerminatorEdges::None,
746
747            Goto { target } => TerminatorEdges::Single(target),
748
749            // FIXME: Maybe we need also TerminatorEdges::Trio for async drop
750            // (target + unwind + dropline)
751            Assert { target, unwind, expected: _, msg: _, cond: _ }
752            | Drop { target, unwind, place: _, replace: _, drop: _ }
753            | FalseUnwind { real_target: target, unwind } => match unwind {
754                UnwindAction::Cleanup(unwind) => TerminatorEdges::Double(target, unwind),
755                UnwindAction::Continue | UnwindAction::Terminate(_) | UnwindAction::Unreachable => {
756                    TerminatorEdges::Single(target)
757                }
758            },
759
760            FalseEdge { real_target, imaginary_target } => {
761                TerminatorEdges::Double(real_target, imaginary_target)
762            }
763
764            Yield { resume: target, drop, resume_arg, value: _ } => {
765                TerminatorEdges::AssignOnReturn {
766                    return_: [target].into_iter().chain(drop.into_iter()).collect(),
767                    cleanup: None,
768                    place: CallReturnPlaces::Yield(resume_arg),
769                }
770            }
771
772            Call { unwind, destination, target, func: _, args: _, fn_span: _, call_source: _ } => {
773                TerminatorEdges::AssignOnReturn {
774                    return_: target.into_iter().collect(),
775                    cleanup: unwind.cleanup_block(),
776                    place: CallReturnPlaces::Call(destination),
777                }
778            }
779
780            InlineAsm {
781                asm_macro: _,
782                template: _,
783                ref operands,
784                options: _,
785                line_spans: _,
786                ref targets,
787                unwind,
788            } => TerminatorEdges::AssignOnReturn {
789                return_: targets.iter().copied().collect(),
790                cleanup: unwind.cleanup_block(),
791                place: CallReturnPlaces::InlineAsm(operands),
792            },
793
794            SwitchInt { ref targets, ref discr } => TerminatorEdges::SwitchInt { targets, discr },
795        }
796    }
797}
798
799impl CallSource {
800    pub fn from_hir_call(self) -> bool {
801        #[allow(non_exhaustive_omitted_patterns)] match self {
    CallSource::Normal => true,
    _ => false,
}matches!(self, CallSource::Normal)
802    }
803}
804
805impl InlineAsmMacro {
806    pub const fn diverges(self, options: InlineAsmOptions) -> bool {
807        match self {
808            InlineAsmMacro::Asm => options.contains(InlineAsmOptions::NORETURN),
809            InlineAsmMacro::NakedAsm => true,
810        }
811    }
812}