1use std::slice;
4
5use rustc_ast::InlineAsmOptions;
6use rustc_attr_ir::lang_items::LangItem;
7use rustc_data_structures::packed::Pu128;
8use rustc_macros::{StableHash, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
9use rustc_span::bug;
10use smallvec::{SmallVec, smallvec};
11use thin_vec::ThinVec;
12
13use super::*;
14
15impl SwitchTargets {
16 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 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 #[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 #[inline]
47 pub fn otherwise(&self) -> BasicBlock {
48 *self.targets.last().unwrap()
49 }
50
51 #[inline]
58 pub fn iter(&self) -> SwitchTargetsIter<'_> {
59 SwitchTargetsIter { inner: iter::zip(&self.values, &self.targets) }
60 }
61
62 #[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 #[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 #[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 #[inline]
94 pub fn add_target(&mut self, value: u128, bb: BasicBlock) {
95 let value = Pu128(value);
96 if self.values.contains(&value) {
97 ::rustc_span::macros::bug_impl(None,
format_args!("target value {0:?} already present", value),
Location::caller());bug!("target value {:?} already present", value);
98 }
99 self.values.push(value);
100 self.targets.insert(self.targets.len() - 1, bb);
101 }
102
103 #[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 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 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 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 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, _, _) => ::rustc_span::macros::bug_impl(None,
format_args!("{0:?} cannot overflow", op), Location::caller())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 ::rustc_span::macros::bug_impl(None, format_args!("Unexpected AssertKind"),
Location::caller())bug!("Unexpected AssertKind")
228 }
229 }
230 }
231
232 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, _, _) => ::rustc_span::macros::bug_impl(None,
format_args!("{0:?} cannot overflow", op), Location::caller())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
335impl<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 ::rustc_span::macros::bug_impl(None,
format_args!("gen blocks can be resumed after they return and will keep returning `None`"),
Location::caller())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) -> Self {
Terminator {
source_info: ::core::clone::Clone::clone(&self.source_info),
kind: ::core::clone::Clone::clone(&self.kind),
}
}
}Clone, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for Terminator<'tcx> {
fn encode(&self, __encoder: &mut __E) {
let Terminator {
source_info: ref __binding_0, kind: 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 Terminator<'tcx> {
fn decode(__decoder: &mut __D) -> Self {
Terminator {
source_info: ::rustc_serialize::Decodable::decode(__decoder),
kind: ::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 } => {
{ __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 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 }
=> {
Terminator {
source_info: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
kind: ::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 {
Terminator { source_info: __binding_0, kind: __binding_1 }
=> {
Terminator {
source_info: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
kind: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__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 } => {
{
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)]
418pub struct Terminator<'tcx> {
419 pub source_info: SourceInfo,
420 pub kind: TerminatorKind<'tcx>,
421}
422
423impl<'tcx> Terminator<'tcx> {
424 #[inline]
425 pub fn successors(&self) -> Successors<'_> {
426 self.kind.successors()
427 }
428
429 #[inline]
431 pub fn identical_successor(&self) -> Option<BasicBlock> {
432 let mut successors = self.successors();
433 let first_succ = successors.next()?;
434 if successors.all(|succ| first_succ == succ) { Some(first_succ) } else { None }
435 }
436
437 #[inline]
438 pub fn successors_mut<'a>(&'a mut self, f: impl FnMut(&'a mut BasicBlock)) {
439 self.kind.successors_mut(f)
440 }
441
442 #[inline]
443 pub fn unwind(&self) -> Option<&UnwindAction> {
444 self.kind.unwind()
445 }
446
447 #[inline]
448 pub fn unwind_mut(&mut self) -> Option<&mut UnwindAction> {
449 self.kind.unwind_mut()
450 }
451}
452
453impl<'tcx> TerminatorKind<'tcx> {
454 pub const fn name(&self) -> &'static str {
457 match self {
458 TerminatorKind::Goto { .. } => "Goto",
459 TerminatorKind::SwitchInt { .. } => "SwitchInt",
460 TerminatorKind::UnwindResume => "UnwindResume",
461 TerminatorKind::UnwindTerminate(_) => "UnwindTerminate",
462 TerminatorKind::Return => "Return",
463 TerminatorKind::Unreachable => "Unreachable",
464 TerminatorKind::Drop { .. } => "Drop",
465 TerminatorKind::Call { .. } => "Call",
466 TerminatorKind::TailCall { .. } => "TailCall",
467 TerminatorKind::Assert { .. } => "Assert",
468 TerminatorKind::Yield { .. } => "Yield",
469 TerminatorKind::CoroutineDrop => "CoroutineDrop",
470 TerminatorKind::FalseEdge { .. } => "FalseEdge",
471 TerminatorKind::FalseUnwind { .. } => "FalseUnwind",
472 TerminatorKind::InlineAsm { .. } => "InlineAsm",
473 }
474 }
475
476 #[inline]
477 pub fn if_(cond: Operand<'tcx>, t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
478 TerminatorKind::SwitchInt { discr: cond, targets: SwitchTargets::static_if(0, f, t) }
479 }
480
481 #[inline]
482 pub fn goto(target: BasicBlock) -> TerminatorKind<'tcx> {
483 TerminatorKind::Goto { target, loop_hint_attrs: ThinVec::new() }
484 }
485}
486
487pub use helper::*;
488
489mod helper {
490 use super::*;
491 pub type Successors<'a> = impl DoubleEndedIterator<Item = BasicBlock> + 'a;
492
493 #[inline]
495 #[define_opaque(Successors)]
496 fn mk_successors(
497 slice: &[BasicBlock],
498 option1: Option<BasicBlock>,
499 option2: Option<BasicBlock>,
500 ) -> Successors<'_> {
501 slice.iter().copied().chain(option1.into_iter().chain(option2))
502 }
503
504 impl SwitchTargets {
505 #[inline]
508 pub fn successors_for_value(&self, value: u128) -> Successors<'_> {
509 let target = self.target_for_value(value);
510 mk_successors(&[], Some(target), None)
511 }
512 }
513
514 impl<'tcx> TerminatorKind<'tcx> {
515 #[inline]
516 pub fn successors(&self) -> Successors<'_> {
517 use self::TerminatorKind::*;
518 match *self {
519 Drop { target: ref t, unwind: UnwindAction::Cleanup(u), drop: Some(d), .. } => {
521 mk_successors(slice::from_ref(t), Some(u), Some(d))
522 }
523 Call { target: Some(ref t), unwind: UnwindAction::Cleanup(u), .. }
525 | Yield { resume: ref t, drop: Some(u), .. }
526 | Drop { target: ref t, unwind: UnwindAction::Cleanup(u), drop: None, .. }
527 | Drop { target: ref t, unwind: _, drop: Some(u), .. }
528 | Assert { target: ref t, unwind: UnwindAction::Cleanup(u), .. }
529 | FalseUnwind { real_target: ref t, unwind: UnwindAction::Cleanup(u) } => {
530 mk_successors(slice::from_ref(t), Some(u), None)
531 }
532 Goto { target: ref t, .. }
534 | Call { target: None, unwind: UnwindAction::Cleanup(ref t), .. }
535 | Call { target: Some(ref t), unwind: _, .. }
536 | Yield { resume: ref t, drop: None, .. }
537 | Drop { target: ref t, unwind: _, .. }
538 | Assert { target: ref t, unwind: _, .. }
539 | FalseUnwind { real_target: ref t, unwind: _ } => {
540 mk_successors(slice::from_ref(t), None, None)
541 }
542 UnwindResume
544 | UnwindTerminate(_)
545 | CoroutineDrop
546 | Return
547 | Unreachable
548 | TailCall { .. }
549 | Call { target: None, unwind: _, .. } => mk_successors(&[], None, None),
550 InlineAsm { ref targets, unwind: UnwindAction::Cleanup(u), .. } => {
552 mk_successors(targets, Some(u), None)
553 }
554 InlineAsm { ref targets, unwind: _, .. } => mk_successors(targets, None, None),
555 SwitchInt { ref targets, .. } => mk_successors(&targets.targets, None, None),
556 FalseEdge { ref real_target, imaginary_target } => {
558 mk_successors(slice::from_ref(real_target), Some(imaginary_target), None)
559 }
560 }
561 }
562
563 #[inline]
564 pub fn successors_mut<'a>(&'a mut self, mut f: impl FnMut(&'a mut BasicBlock)) {
565 use self::TerminatorKind::*;
566 match self {
567 Drop { target, unwind, drop, .. } => {
568 f(target);
569 if let UnwindAction::Cleanup(u) = unwind {
570 f(u)
571 }
572 if let Some(d) = drop {
573 f(d)
574 }
575 }
576 Call { target, unwind, .. } => {
577 if let Some(target) = target {
578 f(target);
579 }
580 if let UnwindAction::Cleanup(u) = unwind {
581 f(u)
582 }
583 }
584 Yield { resume, drop, .. } => {
585 f(resume);
586 if let Some(d) = drop {
587 f(d)
588 }
589 }
590 Assert { target, unwind, .. } | FalseUnwind { real_target: target, unwind } => {
591 f(target);
592 if let UnwindAction::Cleanup(u) = unwind {
593 f(u)
594 }
595 }
596 Goto { target, .. } => {
597 f(target);
598 }
599 UnwindResume
600 | UnwindTerminate(_)
601 | CoroutineDrop
602 | Return
603 | Unreachable
604 | TailCall { .. } => {}
605 InlineAsm { targets, unwind, .. } => {
606 for target in targets {
607 f(target);
608 }
609 if let UnwindAction::Cleanup(u) = unwind {
610 f(u)
611 }
612 }
613 SwitchInt { targets, .. } => {
614 for target in &mut targets.targets {
615 f(target);
616 }
617 }
618 FalseEdge { real_target, imaginary_target } => {
619 f(real_target);
620 f(imaginary_target);
621 }
622 }
623 }
624 }
625}
626
627impl<'tcx> TerminatorKind<'tcx> {
628 #[inline]
629 pub fn unwind(&self) -> Option<&UnwindAction> {
630 match *self {
631 TerminatorKind::Goto { .. }
632 | TerminatorKind::UnwindResume
633 | TerminatorKind::UnwindTerminate(_)
634 | TerminatorKind::Return
635 | TerminatorKind::TailCall { .. }
636 | TerminatorKind::Unreachable
637 | TerminatorKind::CoroutineDrop
638 | TerminatorKind::Yield { .. }
639 | TerminatorKind::SwitchInt { .. }
640 | TerminatorKind::FalseEdge { .. } => None,
641 TerminatorKind::Call { ref unwind, .. }
642 | TerminatorKind::Assert { ref unwind, .. }
643 | TerminatorKind::Drop { ref unwind, .. }
644 | TerminatorKind::FalseUnwind { ref unwind, .. }
645 | TerminatorKind::InlineAsm { ref unwind, .. } => Some(unwind),
646 }
647 }
648
649 #[inline]
650 pub fn unwind_mut(&mut self) -> Option<&mut UnwindAction> {
651 match *self {
652 TerminatorKind::Goto { .. }
653 | TerminatorKind::UnwindResume
654 | TerminatorKind::UnwindTerminate(_)
655 | TerminatorKind::Return
656 | TerminatorKind::TailCall { .. }
657 | TerminatorKind::Unreachable
658 | TerminatorKind::CoroutineDrop
659 | TerminatorKind::Yield { .. }
660 | TerminatorKind::SwitchInt { .. }
661 | TerminatorKind::FalseEdge { .. } => None,
662 TerminatorKind::Call { ref mut unwind, .. }
663 | TerminatorKind::Assert { ref mut unwind, .. }
664 | TerminatorKind::Drop { ref mut unwind, .. }
665 | TerminatorKind::FalseUnwind { ref mut unwind, .. }
666 | TerminatorKind::InlineAsm { ref mut unwind, .. } => Some(unwind),
667 }
668 }
669
670 #[inline]
671 pub fn as_switch(&self) -> Option<(&Operand<'tcx>, &SwitchTargets)> {
672 match self {
673 TerminatorKind::SwitchInt { discr, targets } => Some((discr, targets)),
674 _ => None,
675 }
676 }
677
678 #[inline]
679 pub fn as_goto(&self) -> Option<BasicBlock> {
680 match self {
681 TerminatorKind::Goto { target, loop_hint_attrs: _ } => Some(*target),
682 _ => None,
683 }
684 }
685}
686
687#[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 {
Self::None => ::core::fmt::Formatter::write_str(f, "None"),
Self::Single(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Single",
&__self_0),
Self::Double(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Double",
__self_0, &__self_1),
Self::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),
Self::SwitchInt { targets: __self_0, discr: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SwitchInt", "targets", __self_0, "discr", &__self_1),
}
}
}Debug)]
688pub enum TerminatorEdges<'mir, 'tcx> {
689 None,
691 Single(BasicBlock),
694 Double(BasicBlock, BasicBlock),
697 AssignOnReturn {
699 return_: SmallVec<[BasicBlock; 1]>,
700 cleanup: Option<BasicBlock>,
702 place: CallReturnPlaces<'mir, 'tcx>,
703 },
704 SwitchInt { targets: &'mir SwitchTargets, discr: &'mir Operand<'tcx> },
706}
707
708#[derive(#[automatically_derived]
impl<'a, 'tcx> ::core::marker::Copy for CallReturnPlaces<'a, 'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'a, 'tcx> ::core::clone::TrivialClone for
CallReturnPlaces<'a, 'tcx> {
}
#[automatically_derived]
impl<'a, 'tcx> ::core::clone::Clone for CallReturnPlaces<'a, 'tcx> {
#[inline]
fn clone(&self) -> Self {
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 {
Self::Call(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Call",
&__self_0),
Self::Yield(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Yield",
&__self_0),
Self::InlineAsm(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InlineAsm", &__self_0),
}
}
}Debug)]
711pub enum CallReturnPlaces<'a, 'tcx> {
712 Call(Place<'tcx>),
713 Yield(Place<'tcx>),
714 InlineAsm(&'a [InlineAsmOperand<'tcx>]),
715}
716
717impl<'tcx> CallReturnPlaces<'_, 'tcx> {
718 pub fn for_each(&self, mut f: impl FnMut(Place<'tcx>)) {
719 match *self {
720 Self::Call(place) | Self::Yield(place) => f(place),
721 Self::InlineAsm(operands) => {
722 for op in operands {
723 match *op {
724 InlineAsmOperand::Out { place: Some(place), .. }
725 | InlineAsmOperand::InOut { out_place: Some(place), .. } => f(place),
726 _ => {}
727 }
728 }
729 }
730 }
731 }
732}
733
734impl<'tcx> Terminator<'tcx> {
735 pub fn edges(&self) -> TerminatorEdges<'_, 'tcx> {
736 self.kind.edges()
737 }
738}
739
740impl<'tcx> TerminatorKind<'tcx> {
741 pub fn edges(&self) -> TerminatorEdges<'_, 'tcx> {
742 use TerminatorKind::*;
743 match *self {
744 Return
745 | TailCall { .. }
746 | UnwindResume
747 | UnwindTerminate(_)
748 | CoroutineDrop
749 | Unreachable => TerminatorEdges::None,
750
751 Goto { target, loop_hint_attrs: _ } => TerminatorEdges::Single(target),
752
753 Assert { target, unwind, expected: _, msg: _, cond: _ }
756 | Drop { target, unwind, place: _, replace: _, drop: _ }
757 | FalseUnwind { real_target: target, unwind } => match unwind {
758 UnwindAction::Cleanup(unwind) => TerminatorEdges::Double(target, unwind),
759 UnwindAction::Continue | UnwindAction::Terminate(_) | UnwindAction::Unreachable => {
760 TerminatorEdges::Single(target)
761 }
762 },
763
764 FalseEdge { real_target, imaginary_target } => {
765 TerminatorEdges::Double(real_target, imaginary_target)
766 }
767
768 Yield { resume: target, drop, resume_arg, value: _ } => {
769 TerminatorEdges::AssignOnReturn {
770 return_: [target].into_iter().chain(drop.into_iter()).collect(),
771 cleanup: None,
772 place: CallReturnPlaces::Yield(resume_arg),
773 }
774 }
775
776 Call { unwind, destination, target, func: _, args: _, fn_span: _, call_source: _ } => {
777 TerminatorEdges::AssignOnReturn {
778 return_: target.into_iter().collect(),
779 cleanup: unwind.cleanup_block(),
780 place: CallReturnPlaces::Call(destination),
781 }
782 }
783
784 InlineAsm {
785 asm_macro: _,
786 template: _,
787 ref operands,
788 options: _,
789 line_spans: _,
790 ref targets,
791 unwind,
792 } => TerminatorEdges::AssignOnReturn {
793 return_: targets.iter().copied().collect(),
794 cleanup: unwind.cleanup_block(),
795 place: CallReturnPlaces::InlineAsm(operands),
796 },
797
798 SwitchInt { ref targets, ref discr } => TerminatorEdges::SwitchInt { targets, discr },
799 }
800 }
801}
802
803impl CallSource {
804 pub fn from_hir_call(self) -> bool {
805 #[allow(non_exhaustive_omitted_patterns)] match self {
CallSource::Normal => true,
_ => false,
}matches!(self, CallSource::Normal)
806 }
807}
808
809impl InlineAsmMacro {
810 pub const fn diverges(self, options: InlineAsmOptions) -> bool {
811 match self {
812 InlineAsmMacro::Asm => options.contains(InlineAsmOptions::NORETURN),
813 InlineAsmMacro::NakedAsm => true,
814 }
815 }
816}