rustc_mir_build/builder/scope.rs
1/*!
2Managing the scope stack. The scopes are tied to lexical scopes, so as
3we descend the THIR, we push a scope on the stack, build its
4contents, and then pop it off. Every scope is named by a
5`region::Scope`.
6
7### SEME Regions
8
9When pushing a new [Scope], we record the current point in the graph (a
10basic block); this marks the entry to the scope. We then generate more
11stuff in the control-flow graph. Whenever the scope is exited, either
12via a `break` or `return` or just by fallthrough, that marks an exit
13from the scope. Each lexical scope thus corresponds to a single-entry,
14multiple-exit (SEME) region in the control-flow graph.
15
16For now, we record the `region::Scope` to each SEME region for later reference
17(see caveat in next paragraph). This is because destruction scopes are tied to
18them. This may change in the future so that MIR lowering determines its own
19destruction scopes.
20
21### Not so SEME Regions
22
23In the course of building matches, it sometimes happens that certain code
24(namely guards) gets executed multiple times. This means that the scope lexical
25scope may in fact correspond to multiple, disjoint SEME regions. So in fact our
26mapping is from one scope to a vector of SEME regions. Since the SEME regions
27are disjoint, the mapping is still one-to-one for the set of SEME regions that
28we're currently in.
29
30Also in matches, the scopes assigned to arms are not always even SEME regions!
31Each arm has a single region with one entry for each pattern. We manually
32manipulate the scheduled drops in this scope to avoid dropping things multiple
33times.
34
35### Drops
36
37The primary purpose for scopes is to insert drops: while building
38the contents, we also accumulate places that need to be dropped upon
39exit from each scope. This is done by calling `schedule_drop`. Once a
40drop is scheduled, whenever we branch out we will insert drops of all
41those places onto the outgoing edge. Note that we don't know the full
42set of scheduled drops up front, and so whenever we exit from the
43scope we only drop the values scheduled thus far. For example, consider
44the scope S corresponding to this loop:
45
46```
47# let cond = true;
48loop {
49 let x = ..;
50 if cond { break; }
51 let y = ..;
52}
53```
54
55When processing the `let x`, we will add one drop to the scope for
56`x`. The break will then insert a drop for `x`. When we process `let
57y`, we will add another drop (in fact, to a subscope, but let's ignore
58that for now); any later drops would also drop `y`.
59
60### Early exit
61
62There are numerous "normal" ways to early exit a scope: `break`,
63`continue`, `return` (panics are handled separately). Whenever an
64early exit occurs, the method `break_scope` is called. It is given the
65current point in execution where the early exit occurs, as well as the
66scope you want to branch to (note that all early exits from to some
67other enclosing scope). `break_scope` will record the set of drops currently
68scheduled in a [DropTree]. Later, before `in_breakable_scope` exits, the drops
69will be added to the CFG.
70
71Panics are handled in a similar fashion, except that the drops are added to the
72MIR once the rest of the function has finished being lowered. If a terminator
73can panic, call `diverge_from(block)` with the block containing the terminator
74`block`.
75
76### Breakable scopes
77
78In addition to the normal scope stack, we track a loop scope stack
79that contains only loops and breakable blocks. It tracks where a `break`,
80`continue` or `return` should go to.
81
82*/
83
84use std::mem;
85
86use rustc_data_structures::fx::FxHashMap;
87use rustc_hir::HirId;
88use rustc_index::{IndexSlice, IndexVec};
89use rustc_middle::middle::region;
90use rustc_middle::mir::*;
91use rustc_middle::thir::{ExprId, LintLevel};
92use rustc_middle::ty::{self, TyCtxt};
93use rustc_middle::{bug, span_bug};
94use rustc_session::lint::Level;
95use rustc_span::source_map::Spanned;
96use rustc_span::{DUMMY_SP, Span};
97use tracing::{debug, instrument};
98
99use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG};
100
101#[derive(Debug)]
102pub(crate) struct Scopes<'tcx> {
103 scopes: Vec<Scope>,
104
105 /// The current set of breakable scopes. See module comment for more details.
106 breakable_scopes: Vec<BreakableScope<'tcx>>,
107
108 /// The scope of the innermost if-then currently being lowered.
109 if_then_scope: Option<IfThenScope>,
110
111 /// Drops that need to be done on unwind paths. See the comment on
112 /// [DropTree] for more details.
113 unwind_drops: DropTree,
114
115 /// Drops that need to be done on paths to the `CoroutineDrop` terminator.
116 coroutine_drops: DropTree,
117}
118
119#[derive(Debug)]
120struct Scope {
121 /// The source scope this scope was created in.
122 source_scope: SourceScope,
123
124 /// the region span of this scope within source code.
125 region_scope: region::Scope,
126
127 /// set of places to drop when exiting this scope. This starts
128 /// out empty but grows as variables are declared during the
129 /// building process. This is a stack, so we always drop from the
130 /// end of the vector (top of the stack) first.
131 drops: Vec<DropData>,
132
133 moved_locals: Vec<Local>,
134
135 /// The drop index that will drop everything in and below this scope on an
136 /// unwind path.
137 cached_unwind_block: Option<DropIdx>,
138
139 /// The drop index that will drop everything in and below this scope on a
140 /// coroutine drop path.
141 cached_coroutine_drop_block: Option<DropIdx>,
142}
143
144#[derive(Clone, Copy, Debug)]
145struct DropData {
146 /// The `Span` where drop obligation was incurred (typically where place was
147 /// declared)
148 source_info: SourceInfo,
149
150 /// local to drop
151 local: Local,
152
153 /// Whether this is a value Drop or a StorageDead.
154 kind: DropKind,
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
158pub(crate) enum DropKind {
159 Value,
160 Storage,
161 ForLint,
162}
163
164#[derive(Debug)]
165struct BreakableScope<'tcx> {
166 /// Region scope of the loop
167 region_scope: region::Scope,
168 /// The destination of the loop/block expression itself (i.e., where to put
169 /// the result of a `break` or `return` expression)
170 break_destination: Place<'tcx>,
171 /// Drops that happen on the `break`/`return` path.
172 break_drops: DropTree,
173 /// Drops that happen on the `continue` path.
174 continue_drops: Option<DropTree>,
175}
176
177#[derive(Debug)]
178struct IfThenScope {
179 /// The if-then scope or arm scope
180 region_scope: region::Scope,
181 /// Drops that happen on the `else` path.
182 else_drops: DropTree,
183}
184
185/// The target of an expression that breaks out of a scope
186#[derive(Clone, Copy, Debug)]
187pub(crate) enum BreakableTarget {
188 Continue(region::Scope),
189 Break(region::Scope),
190 Return,
191}
192
193rustc_index::newtype_index! {
194 #[orderable]
195 struct DropIdx {}
196}
197
198const ROOT_NODE: DropIdx = DropIdx::ZERO;
199
200/// A tree of drops that we have deferred lowering. It's used for:
201///
202/// * Drops on unwind paths
203/// * Drops on coroutine drop paths (when a suspended coroutine is dropped)
204/// * Drops on return and loop exit paths
205/// * Drops on the else path in an `if let` chain
206///
207/// Once no more nodes could be added to the tree, we lower it to MIR in one go
208/// in `build_mir`.
209#[derive(Debug)]
210struct DropTree {
211 /// Nodes in the drop tree, containing drop data and a link to the next node.
212 drops: IndexVec<DropIdx, DropNode>,
213 /// Map for finding the index of an existing node, given its contents.
214 existing_drops_map: FxHashMap<DropNodeKey, DropIdx>,
215 /// Edges into the `DropTree` that need to be added once it's lowered.
216 entry_points: Vec<(DropIdx, BasicBlock)>,
217}
218
219/// A single node in the drop tree.
220#[derive(Debug)]
221struct DropNode {
222 /// Info about the drop to be performed at this node in the drop tree.
223 data: DropData,
224 /// Index of the "next" drop to perform (in drop order, not declaration order).
225 next: DropIdx,
226}
227
228/// Subset of [`DropNode`] used for reverse lookup in a hash table.
229#[derive(Debug, PartialEq, Eq, Hash)]
230struct DropNodeKey {
231 next: DropIdx,
232 local: Local,
233 kind: DropKind,
234}
235
236impl Scope {
237 /// Whether there's anything to do for the cleanup path, that is,
238 /// when unwinding through this scope. This includes destructors,
239 /// but not StorageDead statements, which don't get emitted at all
240 /// for unwinding, for several reasons:
241 /// * clang doesn't emit llvm.lifetime.end for C++ unwinding
242 /// * LLVM's memory dependency analysis can't handle it atm
243 /// * polluting the cleanup MIR with StorageDead creates
244 /// landing pads even though there's no actual destructors
245 /// * freeing up stack space has no effect during unwinding
246 /// Note that for coroutines we do emit StorageDeads, for the
247 /// use of optimizations in the MIR coroutine transform.
248 fn needs_cleanup(&self) -> bool {
249 self.drops.iter().any(|drop| match drop.kind {
250 DropKind::Value | DropKind::ForLint => true,
251 DropKind::Storage => false,
252 })
253 }
254
255 fn invalidate_cache(&mut self) {
256 self.cached_unwind_block = None;
257 self.cached_coroutine_drop_block = None;
258 }
259}
260
261/// A trait that determined how [DropTree] creates its blocks and
262/// links to any entry nodes.
263trait DropTreeBuilder<'tcx> {
264 /// Create a new block for the tree. This should call either
265 /// `cfg.start_new_block()` or `cfg.start_new_cleanup_block()`.
266 fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock;
267
268 /// Links a block outside the drop tree, `from`, to the block `to` inside
269 /// the drop tree.
270 fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock);
271}
272
273impl DropTree {
274 fn new() -> Self {
275 // The root node of the tree doesn't represent a drop, but instead
276 // represents the block in the tree that should be jumped to once all
277 // of the required drops have been performed.
278 let fake_source_info = SourceInfo::outermost(DUMMY_SP);
279 let fake_data =
280 DropData { source_info: fake_source_info, local: Local::MAX, kind: DropKind::Storage };
281 let drops = IndexVec::from_raw(vec![DropNode { data: fake_data, next: DropIdx::MAX }]);
282 Self { drops, entry_points: Vec::new(), existing_drops_map: FxHashMap::default() }
283 }
284
285 /// Adds a node to the drop tree, consisting of drop data and the index of
286 /// the "next" drop (in drop order), which could be the sentinel [`ROOT_NODE`].
287 ///
288 /// If there is already an equivalent node in the tree, nothing is added, and
289 /// that node's index is returned. Otherwise, the new node's index is returned.
290 fn add_drop(&mut self, data: DropData, next: DropIdx) -> DropIdx {
291 let drops = &mut self.drops;
292 *self
293 .existing_drops_map
294 .entry(DropNodeKey { next, local: data.local, kind: data.kind })
295 // Create a new node, and also add its index to the map.
296 .or_insert_with(|| drops.push(DropNode { data, next }))
297 }
298
299 /// Registers `from` as an entry point to this drop tree, at `to`.
300 ///
301 /// During [`Self::build_mir`], `from` will be linked to the corresponding
302 /// block within the drop tree.
303 fn add_entry_point(&mut self, from: BasicBlock, to: DropIdx) {
304 debug_assert!(to < self.drops.next_index());
305 self.entry_points.push((to, from));
306 }
307
308 /// Builds the MIR for a given drop tree.
309 fn build_mir<'tcx, T: DropTreeBuilder<'tcx>>(
310 &mut self,
311 cfg: &mut CFG<'tcx>,
312 root_node: Option<BasicBlock>,
313 ) -> IndexVec<DropIdx, Option<BasicBlock>> {
314 debug!("DropTree::build_mir(drops = {:#?})", self);
315
316 let mut blocks = self.assign_blocks::<T>(cfg, root_node);
317 self.link_blocks(cfg, &mut blocks);
318
319 blocks
320 }
321
322 /// Assign blocks for all of the drops in the drop tree that need them.
323 fn assign_blocks<'tcx, T: DropTreeBuilder<'tcx>>(
324 &mut self,
325 cfg: &mut CFG<'tcx>,
326 root_node: Option<BasicBlock>,
327 ) -> IndexVec<DropIdx, Option<BasicBlock>> {
328 // StorageDead statements can share blocks with each other and also with
329 // a Drop terminator. We iterate through the drops to find which drops
330 // need their own block.
331 #[derive(Clone, Copy)]
332 enum Block {
333 // This drop is unreachable
334 None,
335 // This drop is only reachable through the `StorageDead` with the
336 // specified index.
337 Shares(DropIdx),
338 // This drop has more than one way of being reached, or it is
339 // branched to from outside the tree, or its predecessor is a
340 // `Value` drop.
341 Own,
342 }
343
344 let mut blocks = IndexVec::from_elem(None, &self.drops);
345 blocks[ROOT_NODE] = root_node;
346
347 let mut needs_block = IndexVec::from_elem(Block::None, &self.drops);
348 if root_node.is_some() {
349 // In some cases (such as drops for `continue`) the root node
350 // already has a block. In this case, make sure that we don't
351 // override it.
352 needs_block[ROOT_NODE] = Block::Own;
353 }
354
355 // Sort so that we only need to check the last value.
356 let entry_points = &mut self.entry_points;
357 entry_points.sort();
358
359 for (drop_idx, drop_node) in self.drops.iter_enumerated().rev() {
360 if entry_points.last().is_some_and(|entry_point| entry_point.0 == drop_idx) {
361 let block = *blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg));
362 needs_block[drop_idx] = Block::Own;
363 while entry_points.last().is_some_and(|entry_point| entry_point.0 == drop_idx) {
364 let entry_block = entry_points.pop().unwrap().1;
365 T::link_entry_point(cfg, entry_block, block);
366 }
367 }
368 match needs_block[drop_idx] {
369 Block::None => continue,
370 Block::Own => {
371 blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg));
372 }
373 Block::Shares(pred) => {
374 blocks[drop_idx] = blocks[pred];
375 }
376 }
377 if let DropKind::Value = drop_node.data.kind {
378 needs_block[drop_node.next] = Block::Own;
379 } else if drop_idx != ROOT_NODE {
380 match &mut needs_block[drop_node.next] {
381 pred @ Block::None => *pred = Block::Shares(drop_idx),
382 pred @ Block::Shares(_) => *pred = Block::Own,
383 Block::Own => (),
384 }
385 }
386 }
387
388 debug!("assign_blocks: blocks = {:#?}", blocks);
389 assert!(entry_points.is_empty());
390
391 blocks
392 }
393
394 fn link_blocks<'tcx>(
395 &self,
396 cfg: &mut CFG<'tcx>,
397 blocks: &IndexSlice<DropIdx, Option<BasicBlock>>,
398 ) {
399 for (drop_idx, drop_node) in self.drops.iter_enumerated().rev() {
400 let Some(block) = blocks[drop_idx] else { continue };
401 match drop_node.data.kind {
402 DropKind::Value => {
403 let terminator = TerminatorKind::Drop {
404 target: blocks[drop_node.next].unwrap(),
405 // The caller will handle this if needed.
406 unwind: UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
407 place: drop_node.data.local.into(),
408 replace: false,
409 drop: None,
410 async_fut: None,
411 };
412 cfg.terminate(block, drop_node.data.source_info, terminator);
413 }
414 DropKind::ForLint => {
415 let stmt = Statement {
416 source_info: drop_node.data.source_info,
417 kind: StatementKind::BackwardIncompatibleDropHint {
418 place: Box::new(drop_node.data.local.into()),
419 reason: BackwardIncompatibleDropReason::Edition2024,
420 },
421 };
422 cfg.push(block, stmt);
423 let target = blocks[drop_node.next].unwrap();
424 if target != block {
425 // Diagnostics don't use this `Span` but debuginfo
426 // might. Since we don't want breakpoints to be placed
427 // here, especially when this is on an unwind path, we
428 // use `DUMMY_SP`.
429 let source_info =
430 SourceInfo { span: DUMMY_SP, ..drop_node.data.source_info };
431 let terminator = TerminatorKind::Goto { target };
432 cfg.terminate(block, source_info, terminator);
433 }
434 }
435 // Root nodes don't correspond to a drop.
436 DropKind::Storage if drop_idx == ROOT_NODE => {}
437 DropKind::Storage => {
438 let stmt = Statement {
439 source_info: drop_node.data.source_info,
440 kind: StatementKind::StorageDead(drop_node.data.local),
441 };
442 cfg.push(block, stmt);
443 let target = blocks[drop_node.next].unwrap();
444 if target != block {
445 // Diagnostics don't use this `Span` but debuginfo
446 // might. Since we don't want breakpoints to be placed
447 // here, especially when this is on an unwind path, we
448 // use `DUMMY_SP`.
449 let source_info =
450 SourceInfo { span: DUMMY_SP, ..drop_node.data.source_info };
451 let terminator = TerminatorKind::Goto { target };
452 cfg.terminate(block, source_info, terminator);
453 }
454 }
455 }
456 }
457 }
458}
459
460impl<'tcx> Scopes<'tcx> {
461 pub(crate) fn new() -> Self {
462 Self {
463 scopes: Vec::new(),
464 breakable_scopes: Vec::new(),
465 if_then_scope: None,
466 unwind_drops: DropTree::new(),
467 coroutine_drops: DropTree::new(),
468 }
469 }
470
471 fn push_scope(&mut self, region_scope: (region::Scope, SourceInfo), vis_scope: SourceScope) {
472 debug!("push_scope({:?})", region_scope);
473 self.scopes.push(Scope {
474 source_scope: vis_scope,
475 region_scope: region_scope.0,
476 drops: vec![],
477 moved_locals: vec![],
478 cached_unwind_block: None,
479 cached_coroutine_drop_block: None,
480 });
481 }
482
483 fn pop_scope(&mut self, region_scope: (region::Scope, SourceInfo)) -> Scope {
484 let scope = self.scopes.pop().unwrap();
485 assert_eq!(scope.region_scope, region_scope.0);
486 scope
487 }
488
489 fn scope_index(&self, region_scope: region::Scope, span: Span) -> usize {
490 self.scopes
491 .iter()
492 .rposition(|scope| scope.region_scope == region_scope)
493 .unwrap_or_else(|| span_bug!(span, "region_scope {:?} does not enclose", region_scope))
494 }
495
496 /// Returns the topmost active scope, which is known to be alive until
497 /// the next scope expression.
498 fn topmost(&self) -> region::Scope {
499 self.scopes.last().expect("topmost_scope: no scopes present").region_scope
500 }
501}
502
503impl<'a, 'tcx> Builder<'a, 'tcx> {
504 // Adding and removing scopes
505 // ==========================
506
507 /// Start a breakable scope, which tracks where `continue`, `break` and
508 /// `return` should branch to.
509 pub(crate) fn in_breakable_scope<F>(
510 &mut self,
511 loop_block: Option<BasicBlock>,
512 break_destination: Place<'tcx>,
513 span: Span,
514 f: F,
515 ) -> BlockAnd<()>
516 where
517 F: FnOnce(&mut Builder<'a, 'tcx>) -> Option<BlockAnd<()>>,
518 {
519 let region_scope = self.scopes.topmost();
520 let scope = BreakableScope {
521 region_scope,
522 break_destination,
523 break_drops: DropTree::new(),
524 continue_drops: loop_block.map(|_| DropTree::new()),
525 };
526 self.scopes.breakable_scopes.push(scope);
527 let normal_exit_block = f(self);
528 let breakable_scope = self.scopes.breakable_scopes.pop().unwrap();
529 assert!(breakable_scope.region_scope == region_scope);
530 let break_block =
531 self.build_exit_tree(breakable_scope.break_drops, region_scope, span, None);
532 if let Some(drops) = breakable_scope.continue_drops {
533 self.build_exit_tree(drops, region_scope, span, loop_block);
534 }
535 match (normal_exit_block, break_block) {
536 (Some(block), None) | (None, Some(block)) => block,
537 (None, None) => self.cfg.start_new_block().unit(),
538 (Some(normal_block), Some(exit_block)) => {
539 let target = self.cfg.start_new_block();
540 let source_info = self.source_info(span);
541 self.cfg.terminate(
542 normal_block.into_block(),
543 source_info,
544 TerminatorKind::Goto { target },
545 );
546 self.cfg.terminate(
547 exit_block.into_block(),
548 source_info,
549 TerminatorKind::Goto { target },
550 );
551 target.unit()
552 }
553 }
554 }
555
556 /// Start an if-then scope which tracks drop for `if` expressions and `if`
557 /// guards.
558 ///
559 /// For an if-let chain:
560 ///
561 /// if let Some(x) = a && let Some(y) = b && let Some(z) = c { ... }
562 ///
563 /// There are three possible ways the condition can be false and we may have
564 /// to drop `x`, `x` and `y`, or neither depending on which binding fails.
565 /// To handle this correctly we use a `DropTree` in a similar way to a
566 /// `loop` expression and 'break' out on all of the 'else' paths.
567 ///
568 /// Notes:
569 /// - We don't need to keep a stack of scopes in the `Builder` because the
570 /// 'else' paths will only leave the innermost scope.
571 /// - This is also used for match guards.
572 pub(crate) fn in_if_then_scope<F>(
573 &mut self,
574 region_scope: region::Scope,
575 span: Span,
576 f: F,
577 ) -> (BasicBlock, BasicBlock)
578 where
579 F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<()>,
580 {
581 let scope = IfThenScope { region_scope, else_drops: DropTree::new() };
582 let previous_scope = mem::replace(&mut self.scopes.if_then_scope, Some(scope));
583
584 let then_block = f(self).into_block();
585
586 let if_then_scope = mem::replace(&mut self.scopes.if_then_scope, previous_scope).unwrap();
587 assert!(if_then_scope.region_scope == region_scope);
588
589 let else_block =
590 self.build_exit_tree(if_then_scope.else_drops, region_scope, span, None).map_or_else(
591 || self.cfg.start_new_block(),
592 |else_block_and| else_block_and.into_block(),
593 );
594
595 (then_block, else_block)
596 }
597
598 /// Convenience wrapper that pushes a scope and then executes `f`
599 /// to build its contents, popping the scope afterwards.
600 #[instrument(skip(self, f), level = "debug")]
601 pub(crate) fn in_scope<F, R>(
602 &mut self,
603 region_scope: (region::Scope, SourceInfo),
604 lint_level: LintLevel,
605 f: F,
606 ) -> BlockAnd<R>
607 where
608 F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<R>,
609 {
610 let source_scope = self.source_scope;
611 if let LintLevel::Explicit(current_hir_id) = lint_level {
612 let parent_id =
613 self.source_scopes[source_scope].local_data.as_ref().unwrap_crate_local().lint_root;
614 self.maybe_new_source_scope(region_scope.1.span, current_hir_id, parent_id);
615 }
616 self.push_scope(region_scope);
617 let mut block;
618 let rv = unpack!(block = f(self));
619 block = self.pop_scope(region_scope, block).into_block();
620 self.source_scope = source_scope;
621 debug!(?block);
622 block.and(rv)
623 }
624
625 /// Push a scope onto the stack. You can then build code in this
626 /// scope and call `pop_scope` afterwards. Note that these two
627 /// calls must be paired; using `in_scope` as a convenience
628 /// wrapper maybe preferable.
629 pub(crate) fn push_scope(&mut self, region_scope: (region::Scope, SourceInfo)) {
630 self.scopes.push_scope(region_scope, self.source_scope);
631 }
632
633 /// Pops a scope, which should have region scope `region_scope`,
634 /// adding any drops onto the end of `block` that are needed.
635 /// This must match 1-to-1 with `push_scope`.
636 pub(crate) fn pop_scope(
637 &mut self,
638 region_scope: (region::Scope, SourceInfo),
639 mut block: BasicBlock,
640 ) -> BlockAnd<()> {
641 debug!("pop_scope({:?}, {:?})", region_scope, block);
642
643 block = self.leave_top_scope(block);
644
645 self.scopes.pop_scope(region_scope);
646
647 block.unit()
648 }
649
650 /// Sets up the drops for breaking from `block` to `target`.
651 pub(crate) fn break_scope(
652 &mut self,
653 mut block: BasicBlock,
654 value: Option<ExprId>,
655 target: BreakableTarget,
656 source_info: SourceInfo,
657 ) -> BlockAnd<()> {
658 let span = source_info.span;
659
660 let get_scope_index = |scope: region::Scope| {
661 // find the loop-scope by its `region::Scope`.
662 self.scopes
663 .breakable_scopes
664 .iter()
665 .rposition(|breakable_scope| breakable_scope.region_scope == scope)
666 .unwrap_or_else(|| span_bug!(span, "no enclosing breakable scope found"))
667 };
668 let (break_index, destination) = match target {
669 BreakableTarget::Return => {
670 let scope = &self.scopes.breakable_scopes[0];
671 if scope.break_destination != Place::return_place() {
672 span_bug!(span, "`return` in item with no return scope");
673 }
674 (0, Some(scope.break_destination))
675 }
676 BreakableTarget::Break(scope) => {
677 let break_index = get_scope_index(scope);
678 let scope = &self.scopes.breakable_scopes[break_index];
679 (break_index, Some(scope.break_destination))
680 }
681 BreakableTarget::Continue(scope) => {
682 let break_index = get_scope_index(scope);
683 (break_index, None)
684 }
685 };
686
687 match (destination, value) {
688 (Some(destination), Some(value)) => {
689 debug!("stmt_expr Break val block_context.push(SubExpr)");
690 self.block_context.push(BlockFrame::SubExpr);
691 block = self.expr_into_dest(destination, block, value).into_block();
692 self.block_context.pop();
693 }
694 (Some(destination), None) => {
695 self.cfg.push_assign_unit(block, source_info, destination, self.tcx)
696 }
697 (None, Some(_)) => {
698 panic!("`return`, `become` and `break` with value and must have a destination")
699 }
700 (None, None) => {
701 if self.tcx.sess.instrument_coverage() {
702 // Normally we wouldn't build any MIR in this case, but that makes it
703 // harder for coverage instrumentation to extract a relevant span for
704 // `continue` expressions. So here we inject a dummy statement with the
705 // desired span.
706 self.cfg.push_coverage_span_marker(block, source_info);
707 }
708 }
709 }
710
711 let region_scope = self.scopes.breakable_scopes[break_index].region_scope;
712 let scope_index = self.scopes.scope_index(region_scope, span);
713 let drops = if destination.is_some() {
714 &mut self.scopes.breakable_scopes[break_index].break_drops
715 } else {
716 let Some(drops) = self.scopes.breakable_scopes[break_index].continue_drops.as_mut()
717 else {
718 self.tcx.dcx().span_delayed_bug(
719 source_info.span,
720 "unlabelled `continue` within labelled block",
721 );
722 self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
723
724 return self.cfg.start_new_block().unit();
725 };
726 drops
727 };
728
729 let drop_idx = self.scopes.scopes[scope_index + 1..]
730 .iter()
731 .flat_map(|scope| &scope.drops)
732 .fold(ROOT_NODE, |drop_idx, &drop| drops.add_drop(drop, drop_idx));
733
734 drops.add_entry_point(block, drop_idx);
735
736 // `build_drop_trees` doesn't have access to our source_info, so we
737 // create a dummy terminator now. `TerminatorKind::UnwindResume` is used
738 // because MIR type checking will panic if it hasn't been overwritten.
739 // (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
740 self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
741
742 self.cfg.start_new_block().unit()
743 }
744
745 /// Sets up the drops for breaking from `block` due to an `if` condition
746 /// that turned out to be false.
747 ///
748 /// Must be called in the context of [`Builder::in_if_then_scope`], so that
749 /// there is an if-then scope to tell us what the target scope is.
750 pub(crate) fn break_for_else(&mut self, block: BasicBlock, source_info: SourceInfo) {
751 let if_then_scope = self
752 .scopes
753 .if_then_scope
754 .as_ref()
755 .unwrap_or_else(|| span_bug!(source_info.span, "no if-then scope found"));
756
757 let target = if_then_scope.region_scope;
758 let scope_index = self.scopes.scope_index(target, source_info.span);
759
760 // Upgrade `if_then_scope` to `&mut`.
761 let if_then_scope = self.scopes.if_then_scope.as_mut().expect("upgrading & to &mut");
762
763 let mut drop_idx = ROOT_NODE;
764 let drops = &mut if_then_scope.else_drops;
765 for scope in &self.scopes.scopes[scope_index + 1..] {
766 for drop in &scope.drops {
767 drop_idx = drops.add_drop(*drop, drop_idx);
768 }
769 }
770 drops.add_entry_point(block, drop_idx);
771
772 // `build_drop_trees` doesn't have access to our source_info, so we
773 // create a dummy terminator now. `TerminatorKind::UnwindResume` is used
774 // because MIR type checking will panic if it hasn't been overwritten.
775 // (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
776 self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
777 }
778
779 /// Sets up the drops for explicit tail calls.
780 ///
781 /// Unlike other kinds of early exits, tail calls do not go through the drop tree.
782 /// Instead, all scheduled drops are immediately added to the CFG.
783 pub(crate) fn break_for_tail_call(
784 &mut self,
785 mut block: BasicBlock,
786 args: &[Spanned<Operand<'tcx>>],
787 source_info: SourceInfo,
788 ) -> BlockAnd<()> {
789 let arg_drops: Vec<_> = args
790 .iter()
791 .rev()
792 .filter_map(|arg| match &arg.node {
793 Operand::Copy(_) => bug!("copy op in tail call args"),
794 Operand::Move(place) => {
795 let local =
796 place.as_local().unwrap_or_else(|| bug!("projection in tail call args"));
797
798 if !self.local_decls[local].ty.needs_drop(self.tcx, self.typing_env()) {
799 return None;
800 }
801
802 Some(DropData { source_info, local, kind: DropKind::Value })
803 }
804 Operand::Constant(_) => None,
805 })
806 .collect();
807
808 let mut unwind_to = self.diverge_cleanup_target(
809 self.scopes.scopes.iter().rev().nth(1).unwrap().region_scope,
810 DUMMY_SP,
811 );
812 let typing_env = self.typing_env();
813 let unwind_drops = &mut self.scopes.unwind_drops;
814
815 // the innermost scope contains only the destructors for the tail call arguments
816 // we only want to drop these in case of a panic, so we skip it
817 for scope in self.scopes.scopes[1..].iter().rev().skip(1) {
818 // FIXME(explicit_tail_calls) code duplication with `build_scope_drops`
819 for drop_data in scope.drops.iter().rev() {
820 let source_info = drop_data.source_info;
821 let local = drop_data.local;
822
823 if !self.local_decls[local].ty.needs_drop(self.tcx, typing_env) {
824 continue;
825 }
826
827 match drop_data.kind {
828 DropKind::Value => {
829 // `unwind_to` should drop the value that we're about to
830 // schedule. If dropping this value panics, then we continue
831 // with the *next* value on the unwind path.
832 debug_assert_eq!(unwind_drops.drops[unwind_to].data.local, drop_data.local);
833 debug_assert_eq!(unwind_drops.drops[unwind_to].data.kind, drop_data.kind);
834 unwind_to = unwind_drops.drops[unwind_to].next;
835
836 let mut unwind_entry_point = unwind_to;
837
838 // the tail call arguments must be dropped if any of these drops panic
839 for drop in arg_drops.iter().copied() {
840 unwind_entry_point = unwind_drops.add_drop(drop, unwind_entry_point);
841 }
842
843 unwind_drops.add_entry_point(block, unwind_entry_point);
844
845 let next = self.cfg.start_new_block();
846 self.cfg.terminate(
847 block,
848 source_info,
849 TerminatorKind::Drop {
850 place: local.into(),
851 target: next,
852 unwind: UnwindAction::Continue,
853 replace: false,
854 drop: None,
855 async_fut: None,
856 },
857 );
858 block = next;
859 }
860 DropKind::ForLint => {
861 self.cfg.push(
862 block,
863 Statement {
864 source_info,
865 kind: StatementKind::BackwardIncompatibleDropHint {
866 place: Box::new(local.into()),
867 reason: BackwardIncompatibleDropReason::Edition2024,
868 },
869 },
870 );
871 }
872 DropKind::Storage => {
873 // Only temps and vars need their storage dead.
874 assert!(local.index() > self.arg_count);
875 self.cfg.push(
876 block,
877 Statement { source_info, kind: StatementKind::StorageDead(local) },
878 );
879 }
880 }
881 }
882 }
883
884 block.unit()
885 }
886
887 fn is_async_drop_impl(
888 tcx: TyCtxt<'tcx>,
889 local_decls: &IndexVec<Local, LocalDecl<'tcx>>,
890 typing_env: ty::TypingEnv<'tcx>,
891 local: Local,
892 ) -> bool {
893 let ty = local_decls[local].ty;
894 if ty.is_async_drop(tcx, typing_env) || ty.is_coroutine() {
895 return true;
896 }
897 ty.needs_async_drop(tcx, typing_env)
898 }
899 fn is_async_drop(&self, local: Local) -> bool {
900 Self::is_async_drop_impl(self.tcx, &self.local_decls, self.typing_env(), local)
901 }
902
903 fn leave_top_scope(&mut self, block: BasicBlock) -> BasicBlock {
904 // If we are emitting a `drop` statement, we need to have the cached
905 // diverge cleanup pads ready in case that drop panics.
906 let needs_cleanup = self.scopes.scopes.last().is_some_and(|scope| scope.needs_cleanup());
907 let is_coroutine = self.coroutine.is_some();
908 let unwind_to = if needs_cleanup { self.diverge_cleanup() } else { DropIdx::MAX };
909
910 let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes");
911 let has_async_drops = is_coroutine
912 && scope.drops.iter().any(|v| v.kind == DropKind::Value && self.is_async_drop(v.local));
913 let dropline_to = if has_async_drops { Some(self.diverge_dropline()) } else { None };
914 let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes");
915 let typing_env = self.typing_env();
916 build_scope_drops(
917 &mut self.cfg,
918 &mut self.scopes.unwind_drops,
919 &mut self.scopes.coroutine_drops,
920 scope,
921 block,
922 unwind_to,
923 dropline_to,
924 is_coroutine && needs_cleanup,
925 self.arg_count,
926 |v: Local| Self::is_async_drop_impl(self.tcx, &self.local_decls, typing_env, v),
927 )
928 .into_block()
929 }
930
931 /// Possibly creates a new source scope if `current_root` and `parent_root`
932 /// are different, or if -Zmaximal-hir-to-mir-coverage is enabled.
933 pub(crate) fn maybe_new_source_scope(
934 &mut self,
935 span: Span,
936 current_id: HirId,
937 parent_id: HirId,
938 ) {
939 let (current_root, parent_root) =
940 if self.tcx.sess.opts.unstable_opts.maximal_hir_to_mir_coverage {
941 // Some consumers of rustc need to map MIR locations back to HIR nodes. Currently
942 // the only part of rustc that tracks MIR -> HIR is the
943 // `SourceScopeLocalData::lint_root` field that tracks lint levels for MIR
944 // locations. Normally the number of source scopes is limited to the set of nodes
945 // with lint annotations. The -Zmaximal-hir-to-mir-coverage flag changes this
946 // behavior to maximize the number of source scopes, increasing the granularity of
947 // the MIR->HIR mapping.
948 (current_id, parent_id)
949 } else {
950 // Use `maybe_lint_level_root_bounded` to avoid adding Hir dependencies on our
951 // parents. We estimate the true lint roots here to avoid creating a lot of source
952 // scopes.
953 (
954 self.maybe_lint_level_root_bounded(current_id),
955 if parent_id == self.hir_id {
956 parent_id // this is very common
957 } else {
958 self.maybe_lint_level_root_bounded(parent_id)
959 },
960 )
961 };
962
963 if current_root != parent_root {
964 let lint_level = LintLevel::Explicit(current_root);
965 self.source_scope = self.new_source_scope(span, lint_level);
966 }
967 }
968
969 /// Walks upwards from `orig_id` to find a node which might change lint levels with attributes.
970 /// It stops at `self.hir_id` and just returns it if reached.
971 fn maybe_lint_level_root_bounded(&mut self, orig_id: HirId) -> HirId {
972 // This assertion lets us just store `ItemLocalId` in the cache, rather
973 // than the full `HirId`.
974 assert_eq!(orig_id.owner, self.hir_id.owner);
975
976 let mut id = orig_id;
977 loop {
978 if id == self.hir_id {
979 // This is a moderately common case, mostly hit for previously unseen nodes.
980 break;
981 }
982
983 if self.tcx.hir_attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) {
984 // This is a rare case. It's for a node path that doesn't reach the root due to an
985 // intervening lint level attribute. This result doesn't get cached.
986 return id;
987 }
988
989 let next = self.tcx.parent_hir_id(id);
990 if next == id {
991 bug!("lint traversal reached the root of the crate");
992 }
993 id = next;
994
995 // This lookup is just an optimization; it can be removed without affecting
996 // functionality. It might seem strange to see this at the end of this loop, but the
997 // `orig_id` passed in to this function is almost always previously unseen, for which a
998 // lookup will be a miss. So we only do lookups for nodes up the parent chain, where
999 // cache lookups have a very high hit rate.
1000 if self.lint_level_roots_cache.contains(id.local_id) {
1001 break;
1002 }
1003 }
1004
1005 // `orig_id` traced to `self_id`; record this fact. If `orig_id` is a leaf node it will
1006 // rarely (never?) subsequently be searched for, but it's hard to know if that is the case.
1007 // The performance wins from the cache all come from caching non-leaf nodes.
1008 self.lint_level_roots_cache.insert(orig_id.local_id);
1009 self.hir_id
1010 }
1011
1012 /// Creates a new source scope, nested in the current one.
1013 pub(crate) fn new_source_scope(&mut self, span: Span, lint_level: LintLevel) -> SourceScope {
1014 let parent = self.source_scope;
1015 debug!(
1016 "new_source_scope({:?}, {:?}) - parent({:?})={:?}",
1017 span,
1018 lint_level,
1019 parent,
1020 self.source_scopes.get(parent)
1021 );
1022 let scope_local_data = SourceScopeLocalData {
1023 lint_root: if let LintLevel::Explicit(lint_root) = lint_level {
1024 lint_root
1025 } else {
1026 self.source_scopes[parent].local_data.as_ref().unwrap_crate_local().lint_root
1027 },
1028 };
1029 self.source_scopes.push(SourceScopeData {
1030 span,
1031 parent_scope: Some(parent),
1032 inlined: None,
1033 inlined_parent_scope: None,
1034 local_data: ClearCrossCrate::Set(scope_local_data),
1035 })
1036 }
1037
1038 /// Given a span and the current source scope, make a SourceInfo.
1039 pub(crate) fn source_info(&self, span: Span) -> SourceInfo {
1040 SourceInfo { span, scope: self.source_scope }
1041 }
1042
1043 // Finding scopes
1044 // ==============
1045
1046 /// Returns the scope that we should use as the lifetime of an
1047 /// operand. Basically, an operand must live until it is consumed.
1048 /// This is similar to, but not quite the same as, the temporary
1049 /// scope (which can be larger or smaller).
1050 ///
1051 /// Consider:
1052 /// ```ignore (illustrative)
1053 /// let x = foo(bar(X, Y));
1054 /// ```
1055 /// We wish to pop the storage for X and Y after `bar()` is
1056 /// called, not after the whole `let` is completed.
1057 ///
1058 /// As another example, if the second argument diverges:
1059 /// ```ignore (illustrative)
1060 /// foo(Box::new(2), panic!())
1061 /// ```
1062 /// We would allocate the box but then free it on the unwinding
1063 /// path; we would also emit a free on the 'success' path from
1064 /// panic, but that will turn out to be removed as dead-code.
1065 pub(crate) fn local_scope(&self) -> region::Scope {
1066 self.scopes.topmost()
1067 }
1068
1069 // Scheduling drops
1070 // ================
1071
1072 pub(crate) fn schedule_drop_storage_and_value(
1073 &mut self,
1074 span: Span,
1075 region_scope: region::Scope,
1076 local: Local,
1077 ) {
1078 self.schedule_drop(span, region_scope, local, DropKind::Storage);
1079 self.schedule_drop(span, region_scope, local, DropKind::Value);
1080 }
1081
1082 /// Indicates that `place` should be dropped on exit from `region_scope`.
1083 ///
1084 /// When called with `DropKind::Storage`, `place` shouldn't be the return
1085 /// place, or a function parameter.
1086 pub(crate) fn schedule_drop(
1087 &mut self,
1088 span: Span,
1089 region_scope: region::Scope,
1090 local: Local,
1091 drop_kind: DropKind,
1092 ) {
1093 let needs_drop = match drop_kind {
1094 DropKind::Value | DropKind::ForLint => {
1095 if !self.local_decls[local].ty.needs_drop(self.tcx, self.typing_env()) {
1096 return;
1097 }
1098 true
1099 }
1100 DropKind::Storage => {
1101 if local.index() <= self.arg_count {
1102 span_bug!(
1103 span,
1104 "`schedule_drop` called with body argument {:?} \
1105 but its storage does not require a drop",
1106 local,
1107 )
1108 }
1109 false
1110 }
1111 };
1112
1113 // When building drops, we try to cache chains of drops to reduce the
1114 // number of `DropTree::add_drop` calls. This, however, means that
1115 // whenever we add a drop into a scope which already had some entries
1116 // in the drop tree built (and thus, cached) for it, we must invalidate
1117 // all caches which might branch into the scope which had a drop just
1118 // added to it. This is necessary, because otherwise some other code
1119 // might use the cache to branch into already built chain of drops,
1120 // essentially ignoring the newly added drop.
1121 //
1122 // For example consider there’s two scopes with a drop in each. These
1123 // are built and thus the caches are filled:
1124 //
1125 // +--------------------------------------------------------+
1126 // | +---------------------------------+ |
1127 // | | +--------+ +-------------+ | +---------------+ |
1128 // | | | return | <-+ | drop(outer) | <-+ | drop(middle) | |
1129 // | | +--------+ +-------------+ | +---------------+ |
1130 // | +------------|outer_scope cache|--+ |
1131 // +------------------------------|middle_scope cache|------+
1132 //
1133 // Now, a new, innermost scope is added along with a new drop into
1134 // both innermost and outermost scopes:
1135 //
1136 // +------------------------------------------------------------+
1137 // | +----------------------------------+ |
1138 // | | +--------+ +-------------+ | +---------------+ | +-------------+
1139 // | | | return | <+ | drop(new) | <-+ | drop(middle) | <--+| drop(inner) |
1140 // | | +--------+ | | drop(outer) | | +---------------+ | +-------------+
1141 // | | +-+ +-------------+ | |
1142 // | +---|invalid outer_scope cache|----+ |
1143 // +----=----------------|invalid middle_scope cache|-----------+
1144 //
1145 // If, when adding `drop(new)` we do not invalidate the cached blocks for both
1146 // outer_scope and middle_scope, then, when building drops for the inner (rightmost)
1147 // scope, the old, cached blocks, without `drop(new)` will get used, producing the
1148 // wrong results.
1149 //
1150 // Note that this code iterates scopes from the innermost to the outermost,
1151 // invalidating caches of each scope visited. This way bare minimum of the
1152 // caches gets invalidated. i.e., if a new drop is added into the middle scope, the
1153 // cache of outer scope stays intact.
1154 //
1155 // Since we only cache drops for the unwind path and the coroutine drop
1156 // path, we only need to invalidate the cache for drops that happen on
1157 // the unwind or coroutine drop paths. This means that for
1158 // non-coroutines we don't need to invalidate caches for `DropKind::Storage`.
1159 let invalidate_caches = needs_drop || self.coroutine.is_some();
1160 for scope in self.scopes.scopes.iter_mut().rev() {
1161 if invalidate_caches {
1162 scope.invalidate_cache();
1163 }
1164
1165 if scope.region_scope == region_scope {
1166 let region_scope_span = region_scope.span(self.tcx, self.region_scope_tree);
1167 // Attribute scope exit drops to scope's closing brace.
1168 let scope_end = self.tcx.sess.source_map().end_point(region_scope_span);
1169
1170 scope.drops.push(DropData {
1171 source_info: SourceInfo { span: scope_end, scope: scope.source_scope },
1172 local,
1173 kind: drop_kind,
1174 });
1175
1176 return;
1177 }
1178 }
1179
1180 span_bug!(span, "region scope {:?} not in scope to drop {:?}", region_scope, local);
1181 }
1182
1183 /// Schedule emission of a backwards incompatible drop lint hint.
1184 /// Applicable only to temporary values for now.
1185 #[instrument(level = "debug", skip(self))]
1186 pub(crate) fn schedule_backwards_incompatible_drop(
1187 &mut self,
1188 span: Span,
1189 region_scope: region::Scope,
1190 local: Local,
1191 ) {
1192 // Note that we are *not* gating BIDs here on whether they have significant destructor.
1193 // We need to know all of them so that we can capture potential borrow-checking errors.
1194 for scope in self.scopes.scopes.iter_mut().rev() {
1195 // Since we are inserting linting MIR statement, we have to invalidate the caches
1196 scope.invalidate_cache();
1197 if scope.region_scope == region_scope {
1198 let region_scope_span = region_scope.span(self.tcx, self.region_scope_tree);
1199 let scope_end = self.tcx.sess.source_map().end_point(region_scope_span);
1200
1201 scope.drops.push(DropData {
1202 source_info: SourceInfo { span: scope_end, scope: scope.source_scope },
1203 local,
1204 kind: DropKind::ForLint,
1205 });
1206
1207 return;
1208 }
1209 }
1210 span_bug!(
1211 span,
1212 "region scope {:?} not in scope to drop {:?} for linting",
1213 region_scope,
1214 local
1215 );
1216 }
1217
1218 /// Indicates that the "local operand" stored in `local` is
1219 /// *moved* at some point during execution (see `local_scope` for
1220 /// more information about what a "local operand" is -- in short,
1221 /// it's an intermediate operand created as part of preparing some
1222 /// MIR instruction). We use this information to suppress
1223 /// redundant drops on the non-unwind paths. This results in less
1224 /// MIR, but also avoids spurious borrow check errors
1225 /// (c.f. #64391).
1226 ///
1227 /// Example: when compiling the call to `foo` here:
1228 ///
1229 /// ```ignore (illustrative)
1230 /// foo(bar(), ...)
1231 /// ```
1232 ///
1233 /// we would evaluate `bar()` to an operand `_X`. We would also
1234 /// schedule `_X` to be dropped when the expression scope for
1235 /// `foo(bar())` is exited. This is relevant, for example, if the
1236 /// later arguments should unwind (it would ensure that `_X` gets
1237 /// dropped). However, if no unwind occurs, then `_X` will be
1238 /// unconditionally consumed by the `call`:
1239 ///
1240 /// ```ignore (illustrative)
1241 /// bb {
1242 /// ...
1243 /// _R = CALL(foo, _X, ...)
1244 /// }
1245 /// ```
1246 ///
1247 /// However, `_X` is still registered to be dropped, and so if we
1248 /// do nothing else, we would generate a `DROP(_X)` that occurs
1249 /// after the call. This will later be optimized out by the
1250 /// drop-elaboration code, but in the meantime it can lead to
1251 /// spurious borrow-check errors -- the problem, ironically, is
1252 /// not the `DROP(_X)` itself, but the (spurious) unwind pathways
1253 /// that it creates. See #64391 for an example.
1254 pub(crate) fn record_operands_moved(&mut self, operands: &[Spanned<Operand<'tcx>>]) {
1255 let local_scope = self.local_scope();
1256 let scope = self.scopes.scopes.last_mut().unwrap();
1257
1258 assert_eq!(scope.region_scope, local_scope, "local scope is not the topmost scope!",);
1259
1260 // look for moves of a local variable, like `MOVE(_X)`
1261 let locals_moved = operands.iter().flat_map(|operand| match operand.node {
1262 Operand::Copy(_) | Operand::Constant(_) => None,
1263 Operand::Move(place) => place.as_local(),
1264 });
1265
1266 for local in locals_moved {
1267 // check if we have a Drop for this operand and -- if so
1268 // -- add it to the list of moved operands. Note that this
1269 // local might not have been an operand created for this
1270 // call, it could come from other places too.
1271 if scope.drops.iter().any(|drop| drop.local == local && drop.kind == DropKind::Value) {
1272 scope.moved_locals.push(local);
1273 }
1274 }
1275 }
1276
1277 // Other
1278 // =====
1279
1280 /// Returns the [DropIdx] for the innermost drop if the function unwound at
1281 /// this point. The `DropIdx` will be created if it doesn't already exist.
1282 fn diverge_cleanup(&mut self) -> DropIdx {
1283 // It is okay to use dummy span because the getting scope index on the topmost scope
1284 // must always succeed.
1285 self.diverge_cleanup_target(self.scopes.topmost(), DUMMY_SP)
1286 }
1287
1288 /// This is similar to [diverge_cleanup](Self::diverge_cleanup) except its target is set to
1289 /// some ancestor scope instead of the current scope.
1290 /// It is possible to unwind to some ancestor scope if some drop panics as
1291 /// the program breaks out of a if-then scope.
1292 fn diverge_cleanup_target(&mut self, target_scope: region::Scope, span: Span) -> DropIdx {
1293 let target = self.scopes.scope_index(target_scope, span);
1294 let (uncached_scope, mut cached_drop) = self.scopes.scopes[..=target]
1295 .iter()
1296 .enumerate()
1297 .rev()
1298 .find_map(|(scope_idx, scope)| {
1299 scope.cached_unwind_block.map(|cached_block| (scope_idx + 1, cached_block))
1300 })
1301 .unwrap_or((0, ROOT_NODE));
1302
1303 if uncached_scope > target {
1304 return cached_drop;
1305 }
1306
1307 let is_coroutine = self.coroutine.is_some();
1308 for scope in &mut self.scopes.scopes[uncached_scope..=target] {
1309 for drop in &scope.drops {
1310 if is_coroutine || drop.kind == DropKind::Value {
1311 cached_drop = self.scopes.unwind_drops.add_drop(*drop, cached_drop);
1312 }
1313 }
1314 scope.cached_unwind_block = Some(cached_drop);
1315 }
1316
1317 cached_drop
1318 }
1319
1320 /// Prepares to create a path that performs all required cleanup for a
1321 /// terminator that can unwind at the given basic block.
1322 ///
1323 /// This path terminates in Resume. The path isn't created until after all
1324 /// of the non-unwind paths in this item have been lowered.
1325 pub(crate) fn diverge_from(&mut self, start: BasicBlock) {
1326 debug_assert!(
1327 matches!(
1328 self.cfg.block_data(start).terminator().kind,
1329 TerminatorKind::Assert { .. }
1330 | TerminatorKind::Call { .. }
1331 | TerminatorKind::Drop { .. }
1332 | TerminatorKind::FalseUnwind { .. }
1333 | TerminatorKind::InlineAsm { .. }
1334 ),
1335 "diverge_from called on block with terminator that cannot unwind."
1336 );
1337
1338 let next_drop = self.diverge_cleanup();
1339 self.scopes.unwind_drops.add_entry_point(start, next_drop);
1340 }
1341
1342 /// Returns the [DropIdx] for the innermost drop for dropline (coroutine drop path).
1343 /// The `DropIdx` will be created if it doesn't already exist.
1344 fn diverge_dropline(&mut self) -> DropIdx {
1345 // It is okay to use dummy span because the getting scope index on the topmost scope
1346 // must always succeed.
1347 self.diverge_dropline_target(self.scopes.topmost(), DUMMY_SP)
1348 }
1349
1350 /// Similar to diverge_cleanup_target, but for dropline (coroutine drop path)
1351 fn diverge_dropline_target(&mut self, target_scope: region::Scope, span: Span) -> DropIdx {
1352 debug_assert!(
1353 self.coroutine.is_some(),
1354 "diverge_dropline_target is valid only for coroutine"
1355 );
1356 let target = self.scopes.scope_index(target_scope, span);
1357 let (uncached_scope, mut cached_drop) = self.scopes.scopes[..=target]
1358 .iter()
1359 .enumerate()
1360 .rev()
1361 .find_map(|(scope_idx, scope)| {
1362 scope.cached_coroutine_drop_block.map(|cached_block| (scope_idx + 1, cached_block))
1363 })
1364 .unwrap_or((0, ROOT_NODE));
1365
1366 if uncached_scope > target {
1367 return cached_drop;
1368 }
1369
1370 for scope in &mut self.scopes.scopes[uncached_scope..=target] {
1371 for drop in &scope.drops {
1372 cached_drop = self.scopes.coroutine_drops.add_drop(*drop, cached_drop);
1373 }
1374 scope.cached_coroutine_drop_block = Some(cached_drop);
1375 }
1376
1377 cached_drop
1378 }
1379
1380 /// Sets up a path that performs all required cleanup for dropping a
1381 /// coroutine, starting from the given block that ends in
1382 /// [TerminatorKind::Yield].
1383 ///
1384 /// This path terminates in CoroutineDrop.
1385 pub(crate) fn coroutine_drop_cleanup(&mut self, yield_block: BasicBlock) {
1386 debug_assert!(
1387 matches!(
1388 self.cfg.block_data(yield_block).terminator().kind,
1389 TerminatorKind::Yield { .. }
1390 ),
1391 "coroutine_drop_cleanup called on block with non-yield terminator."
1392 );
1393 let cached_drop = self.diverge_dropline();
1394 self.scopes.coroutine_drops.add_entry_point(yield_block, cached_drop);
1395 }
1396
1397 /// Utility function for *non*-scope code to build their own drops
1398 /// Force a drop at this point in the MIR by creating a new block.
1399 pub(crate) fn build_drop_and_replace(
1400 &mut self,
1401 block: BasicBlock,
1402 span: Span,
1403 place: Place<'tcx>,
1404 value: Rvalue<'tcx>,
1405 ) -> BlockAnd<()> {
1406 let source_info = self.source_info(span);
1407
1408 // create the new block for the assignment
1409 let assign = self.cfg.start_new_block();
1410 self.cfg.push_assign(assign, source_info, place, value.clone());
1411
1412 // create the new block for the assignment in the case of unwinding
1413 let assign_unwind = self.cfg.start_new_cleanup_block();
1414 self.cfg.push_assign(assign_unwind, source_info, place, value.clone());
1415
1416 self.cfg.terminate(
1417 block,
1418 source_info,
1419 TerminatorKind::Drop {
1420 place,
1421 target: assign,
1422 unwind: UnwindAction::Cleanup(assign_unwind),
1423 replace: true,
1424 drop: None,
1425 async_fut: None,
1426 },
1427 );
1428 self.diverge_from(block);
1429
1430 assign.unit()
1431 }
1432
1433 /// Creates an `Assert` terminator and return the success block.
1434 /// If the boolean condition operand is not the expected value,
1435 /// a runtime panic will be caused with the given message.
1436 pub(crate) fn assert(
1437 &mut self,
1438 block: BasicBlock,
1439 cond: Operand<'tcx>,
1440 expected: bool,
1441 msg: AssertMessage<'tcx>,
1442 span: Span,
1443 ) -> BasicBlock {
1444 let source_info = self.source_info(span);
1445 let success_block = self.cfg.start_new_block();
1446
1447 self.cfg.terminate(
1448 block,
1449 source_info,
1450 TerminatorKind::Assert {
1451 cond,
1452 expected,
1453 msg: Box::new(msg),
1454 target: success_block,
1455 unwind: UnwindAction::Continue,
1456 },
1457 );
1458 self.diverge_from(block);
1459
1460 success_block
1461 }
1462
1463 /// Unschedules any drops in the top scope.
1464 ///
1465 /// This is only needed for `match` arm scopes, because they have one
1466 /// entrance per pattern, but only one exit.
1467 pub(crate) fn clear_top_scope(&mut self, region_scope: region::Scope) {
1468 let top_scope = self.scopes.scopes.last_mut().unwrap();
1469
1470 assert_eq!(top_scope.region_scope, region_scope);
1471
1472 top_scope.drops.clear();
1473 top_scope.invalidate_cache();
1474 }
1475}
1476
1477/// Builds drops for `pop_scope` and `leave_top_scope`.
1478///
1479/// # Parameters
1480///
1481/// * `unwind_drops`, the drop tree data structure storing what needs to be cleaned up if unwind occurs
1482/// * `scope`, describes the drops that will occur on exiting the scope in regular execution
1483/// * `block`, the block to branch to once drops are complete (assuming no unwind occurs)
1484/// * `unwind_to`, describes the drops that would occur at this point in the code if a
1485/// panic occurred (a subset of the drops in `scope`, since we sometimes elide StorageDead and other
1486/// instructions on unwinding)
1487/// * `dropline_to`, describes the drops that would occur at this point in the code if a
1488/// coroutine drop occured.
1489/// * `storage_dead_on_unwind`, if true, then we should emit `StorageDead` even when unwinding
1490/// * `arg_count`, number of MIR local variables corresponding to fn arguments (used to assert that we don't drop those)
1491fn build_scope_drops<'tcx, F>(
1492 cfg: &mut CFG<'tcx>,
1493 unwind_drops: &mut DropTree,
1494 coroutine_drops: &mut DropTree,
1495 scope: &Scope,
1496 block: BasicBlock,
1497 unwind_to: DropIdx,
1498 dropline_to: Option<DropIdx>,
1499 storage_dead_on_unwind: bool,
1500 arg_count: usize,
1501 is_async_drop: F,
1502) -> BlockAnd<()>
1503where
1504 F: Fn(Local) -> bool,
1505{
1506 debug!("build_scope_drops({:?} -> {:?}), dropline_to={:?}", block, scope, dropline_to);
1507
1508 // Build up the drops in evaluation order. The end result will
1509 // look like:
1510 //
1511 // [SDs, drops[n]] --..> [SDs, drop[1]] -> [SDs, drop[0]] -> [[SDs]]
1512 // | | |
1513 // : | |
1514 // V V
1515 // [drop[n]] -...-> [drop[1]] ------> [drop[0]] ------> [last_unwind_to]
1516 //
1517 // The horizontal arrows represent the execution path when the drops return
1518 // successfully. The downwards arrows represent the execution path when the
1519 // drops panic (panicking while unwinding will abort, so there's no need for
1520 // another set of arrows).
1521 //
1522 // For coroutines, we unwind from a drop on a local to its StorageDead
1523 // statement. For other functions we don't worry about StorageDead. The
1524 // drops for the unwind path should have already been generated by
1525 // `diverge_cleanup_gen`.
1526
1527 // `unwind_to` indicates what needs to be dropped should unwinding occur.
1528 // This is a subset of what needs to be dropped when exiting the scope.
1529 // As we unwind the scope, we will also move `unwind_to` backwards to match,
1530 // so that we can use it should a destructor panic.
1531 let mut unwind_to = unwind_to;
1532
1533 // The block that we should jump to after drops complete. We start by building the final drop (`drops[n]`
1534 // in the diagram above) and then build the drops (e.g., `drop[1]`, `drop[0]`) that come before it.
1535 // block begins as the successor of `drops[n]` and then becomes `drops[n]` so that `drops[n-1]`
1536 // will branch to `drops[n]`.
1537 let mut block = block;
1538
1539 // `dropline_to` indicates what needs to be dropped should coroutine drop occur.
1540 let mut dropline_to = dropline_to;
1541
1542 for drop_data in scope.drops.iter().rev() {
1543 let source_info = drop_data.source_info;
1544 let local = drop_data.local;
1545
1546 match drop_data.kind {
1547 DropKind::Value => {
1548 // `unwind_to` should drop the value that we're about to
1549 // schedule. If dropping this value panics, then we continue
1550 // with the *next* value on the unwind path.
1551 //
1552 // We adjust this BEFORE we create the drop (e.g., `drops[n]`)
1553 // because `drops[n]` should unwind to `drops[n-1]`.
1554 debug_assert_eq!(unwind_drops.drops[unwind_to].data.local, drop_data.local);
1555 debug_assert_eq!(unwind_drops.drops[unwind_to].data.kind, drop_data.kind);
1556 unwind_to = unwind_drops.drops[unwind_to].next;
1557
1558 if let Some(idx) = dropline_to {
1559 debug_assert_eq!(coroutine_drops.drops[idx].data.local, drop_data.local);
1560 debug_assert_eq!(coroutine_drops.drops[idx].data.kind, drop_data.kind);
1561 dropline_to = Some(coroutine_drops.drops[idx].next);
1562 }
1563
1564 // If the operand has been moved, and we are not on an unwind
1565 // path, then don't generate the drop. (We only take this into
1566 // account for non-unwind paths so as not to disturb the
1567 // caching mechanism.)
1568 if scope.moved_locals.contains(&local) {
1569 continue;
1570 }
1571
1572 unwind_drops.add_entry_point(block, unwind_to);
1573 if let Some(to) = dropline_to
1574 && is_async_drop(local)
1575 {
1576 coroutine_drops.add_entry_point(block, to);
1577 }
1578
1579 let next = cfg.start_new_block();
1580 cfg.terminate(
1581 block,
1582 source_info,
1583 TerminatorKind::Drop {
1584 place: local.into(),
1585 target: next,
1586 unwind: UnwindAction::Continue,
1587 replace: false,
1588 drop: None,
1589 async_fut: None,
1590 },
1591 );
1592 block = next;
1593 }
1594 DropKind::ForLint => {
1595 // As in the `DropKind::Storage` case below:
1596 // normally lint-related drops are not emitted for unwind,
1597 // so we can just leave `unwind_to` unmodified, but in some
1598 // cases we emit things ALSO on the unwind path, so we need to adjust
1599 // `unwind_to` in that case.
1600 if storage_dead_on_unwind {
1601 debug_assert_eq!(unwind_drops.drops[unwind_to].data.local, drop_data.local);
1602 debug_assert_eq!(unwind_drops.drops[unwind_to].data.kind, drop_data.kind);
1603 unwind_to = unwind_drops.drops[unwind_to].next;
1604 }
1605
1606 // If the operand has been moved, and we are not on an unwind
1607 // path, then don't generate the drop. (We only take this into
1608 // account for non-unwind paths so as not to disturb the
1609 // caching mechanism.)
1610 if scope.moved_locals.contains(&local) {
1611 continue;
1612 }
1613
1614 cfg.push(
1615 block,
1616 Statement {
1617 source_info,
1618 kind: StatementKind::BackwardIncompatibleDropHint {
1619 place: Box::new(local.into()),
1620 reason: BackwardIncompatibleDropReason::Edition2024,
1621 },
1622 },
1623 );
1624 }
1625 DropKind::Storage => {
1626 // Ordinarily, storage-dead nodes are not emitted on unwind, so we don't
1627 // need to adjust `unwind_to` on this path. However, in some specific cases
1628 // we *do* emit storage-dead nodes on the unwind path, and in that case now that
1629 // the storage-dead has completed, we need to adjust the `unwind_to` pointer
1630 // so that any future drops we emit will not register storage-dead.
1631 if storage_dead_on_unwind {
1632 debug_assert_eq!(unwind_drops.drops[unwind_to].data.local, drop_data.local);
1633 debug_assert_eq!(unwind_drops.drops[unwind_to].data.kind, drop_data.kind);
1634 unwind_to = unwind_drops.drops[unwind_to].next;
1635 }
1636 if let Some(idx) = dropline_to {
1637 debug_assert_eq!(coroutine_drops.drops[idx].data.local, drop_data.local);
1638 debug_assert_eq!(coroutine_drops.drops[idx].data.kind, drop_data.kind);
1639 dropline_to = Some(coroutine_drops.drops[idx].next);
1640 }
1641 // Only temps and vars need their storage dead.
1642 assert!(local.index() > arg_count);
1643 cfg.push(block, Statement { source_info, kind: StatementKind::StorageDead(local) });
1644 }
1645 }
1646 }
1647 block.unit()
1648}
1649
1650impl<'a, 'tcx: 'a> Builder<'a, 'tcx> {
1651 /// Build a drop tree for a breakable scope.
1652 ///
1653 /// If `continue_block` is `Some`, then the tree is for `continue` inside a
1654 /// loop. Otherwise this is for `break` or `return`.
1655 fn build_exit_tree(
1656 &mut self,
1657 mut drops: DropTree,
1658 else_scope: region::Scope,
1659 span: Span,
1660 continue_block: Option<BasicBlock>,
1661 ) -> Option<BlockAnd<()>> {
1662 let blocks = drops.build_mir::<ExitScopes>(&mut self.cfg, continue_block);
1663 let is_coroutine = self.coroutine.is_some();
1664
1665 // Link the exit drop tree to unwind drop tree.
1666 if drops.drops.iter().any(|drop_node| drop_node.data.kind == DropKind::Value) {
1667 let unwind_target = self.diverge_cleanup_target(else_scope, span);
1668 let mut unwind_indices = IndexVec::from_elem_n(unwind_target, 1);
1669 for (drop_idx, drop_node) in drops.drops.iter_enumerated().skip(1) {
1670 match drop_node.data.kind {
1671 DropKind::Storage | DropKind::ForLint => {
1672 if is_coroutine {
1673 let unwind_drop = self
1674 .scopes
1675 .unwind_drops
1676 .add_drop(drop_node.data, unwind_indices[drop_node.next]);
1677 unwind_indices.push(unwind_drop);
1678 } else {
1679 unwind_indices.push(unwind_indices[drop_node.next]);
1680 }
1681 }
1682 DropKind::Value => {
1683 let unwind_drop = self
1684 .scopes
1685 .unwind_drops
1686 .add_drop(drop_node.data, unwind_indices[drop_node.next]);
1687 self.scopes.unwind_drops.add_entry_point(
1688 blocks[drop_idx].unwrap(),
1689 unwind_indices[drop_node.next],
1690 );
1691 unwind_indices.push(unwind_drop);
1692 }
1693 }
1694 }
1695 }
1696 // Link the exit drop tree to dropline drop tree (coroutine drop path) for async drops
1697 if is_coroutine
1698 && drops.drops.iter().any(|DropNode { data, next: _ }| {
1699 data.kind == DropKind::Value && self.is_async_drop(data.local)
1700 })
1701 {
1702 let dropline_target = self.diverge_dropline_target(else_scope, span);
1703 let mut dropline_indices = IndexVec::from_elem_n(dropline_target, 1);
1704 for (drop_idx, drop_data) in drops.drops.iter_enumerated().skip(1) {
1705 match drop_data.data.kind {
1706 DropKind::Storage | DropKind::ForLint => {
1707 let coroutine_drop = self
1708 .scopes
1709 .coroutine_drops
1710 .add_drop(drop_data.data, dropline_indices[drop_data.next]);
1711 dropline_indices.push(coroutine_drop);
1712 }
1713 DropKind::Value => {
1714 let coroutine_drop = self
1715 .scopes
1716 .coroutine_drops
1717 .add_drop(drop_data.data, dropline_indices[drop_data.next]);
1718 if self.is_async_drop(drop_data.data.local) {
1719 self.scopes.coroutine_drops.add_entry_point(
1720 blocks[drop_idx].unwrap(),
1721 dropline_indices[drop_data.next],
1722 );
1723 }
1724 dropline_indices.push(coroutine_drop);
1725 }
1726 }
1727 }
1728 }
1729 blocks[ROOT_NODE].map(BasicBlock::unit)
1730 }
1731
1732 /// Build the unwind and coroutine drop trees.
1733 pub(crate) fn build_drop_trees(&mut self) {
1734 if self.coroutine.is_some() {
1735 self.build_coroutine_drop_trees();
1736 } else {
1737 Self::build_unwind_tree(
1738 &mut self.cfg,
1739 &mut self.scopes.unwind_drops,
1740 self.fn_span,
1741 &mut None,
1742 );
1743 }
1744 }
1745
1746 fn build_coroutine_drop_trees(&mut self) {
1747 // Build the drop tree for dropping the coroutine while it's suspended.
1748 let drops = &mut self.scopes.coroutine_drops;
1749 let cfg = &mut self.cfg;
1750 let fn_span = self.fn_span;
1751 let blocks = drops.build_mir::<CoroutineDrop>(cfg, None);
1752 if let Some(root_block) = blocks[ROOT_NODE] {
1753 cfg.terminate(
1754 root_block,
1755 SourceInfo::outermost(fn_span),
1756 TerminatorKind::CoroutineDrop,
1757 );
1758 }
1759
1760 // Build the drop tree for unwinding in the normal control flow paths.
1761 let resume_block = &mut None;
1762 let unwind_drops = &mut self.scopes.unwind_drops;
1763 Self::build_unwind_tree(cfg, unwind_drops, fn_span, resume_block);
1764
1765 // Build the drop tree for unwinding when dropping a suspended
1766 // coroutine.
1767 //
1768 // This is a different tree to the standard unwind paths here to
1769 // prevent drop elaboration from creating drop flags that would have
1770 // to be captured by the coroutine. I'm not sure how important this
1771 // optimization is, but it is here.
1772 for (drop_idx, drop_node) in drops.drops.iter_enumerated() {
1773 if let DropKind::Value = drop_node.data.kind
1774 && let Some(bb) = blocks[drop_idx]
1775 {
1776 debug_assert!(drop_node.next < drops.drops.next_index());
1777 drops.entry_points.push((drop_node.next, bb));
1778 }
1779 }
1780 Self::build_unwind_tree(cfg, drops, fn_span, resume_block);
1781 }
1782
1783 fn build_unwind_tree(
1784 cfg: &mut CFG<'tcx>,
1785 drops: &mut DropTree,
1786 fn_span: Span,
1787 resume_block: &mut Option<BasicBlock>,
1788 ) {
1789 let blocks = drops.build_mir::<Unwind>(cfg, *resume_block);
1790 if let (None, Some(resume)) = (*resume_block, blocks[ROOT_NODE]) {
1791 cfg.terminate(resume, SourceInfo::outermost(fn_span), TerminatorKind::UnwindResume);
1792
1793 *resume_block = blocks[ROOT_NODE];
1794 }
1795 }
1796}
1797
1798// DropTreeBuilder implementations.
1799
1800struct ExitScopes;
1801
1802impl<'tcx> DropTreeBuilder<'tcx> for ExitScopes {
1803 fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
1804 cfg.start_new_block()
1805 }
1806 fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
1807 // There should be an existing terminator with real source info and a
1808 // dummy TerminatorKind. Replace it with a proper goto.
1809 // (The dummy is added by `break_scope` and `break_for_else`.)
1810 let term = cfg.block_data_mut(from).terminator_mut();
1811 if let TerminatorKind::UnwindResume = term.kind {
1812 term.kind = TerminatorKind::Goto { target: to };
1813 } else {
1814 span_bug!(term.source_info.span, "unexpected dummy terminator kind: {:?}", term.kind);
1815 }
1816 }
1817}
1818
1819struct CoroutineDrop;
1820
1821impl<'tcx> DropTreeBuilder<'tcx> for CoroutineDrop {
1822 fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
1823 cfg.start_new_block()
1824 }
1825 fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
1826 let term = cfg.block_data_mut(from).terminator_mut();
1827 if let TerminatorKind::Yield { ref mut drop, .. } = term.kind {
1828 *drop = Some(to);
1829 } else if let TerminatorKind::Drop { ref mut drop, .. } = term.kind {
1830 *drop = Some(to);
1831 } else {
1832 span_bug!(
1833 term.source_info.span,
1834 "cannot enter coroutine drop tree from {:?}",
1835 term.kind
1836 )
1837 }
1838 }
1839}
1840
1841struct Unwind;
1842
1843impl<'tcx> DropTreeBuilder<'tcx> for Unwind {
1844 fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
1845 cfg.start_new_cleanup_block()
1846 }
1847 fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
1848 let term = &mut cfg.block_data_mut(from).terminator_mut();
1849 match &mut term.kind {
1850 TerminatorKind::Drop { unwind, .. } => {
1851 if let UnwindAction::Cleanup(unwind) = *unwind {
1852 let source_info = term.source_info;
1853 cfg.terminate(unwind, source_info, TerminatorKind::Goto { target: to });
1854 } else {
1855 *unwind = UnwindAction::Cleanup(to);
1856 }
1857 }
1858 TerminatorKind::FalseUnwind { unwind, .. }
1859 | TerminatorKind::Call { unwind, .. }
1860 | TerminatorKind::Assert { unwind, .. }
1861 | TerminatorKind::InlineAsm { unwind, .. } => {
1862 *unwind = UnwindAction::Cleanup(to);
1863 }
1864 TerminatorKind::Goto { .. }
1865 | TerminatorKind::SwitchInt { .. }
1866 | TerminatorKind::UnwindResume
1867 | TerminatorKind::UnwindTerminate(_)
1868 | TerminatorKind::Return
1869 | TerminatorKind::TailCall { .. }
1870 | TerminatorKind::Unreachable
1871 | TerminatorKind::Yield { .. }
1872 | TerminatorKind::CoroutineDrop
1873 | TerminatorKind::FalseEdge { .. } => {
1874 span_bug!(term.source_info.span, "cannot unwind from {:?}", term.kind)
1875 }
1876 }
1877 }
1878}