1 //! Inlining pass for MIR functions
3 use rustc_attr as attr;
4 use rustc_index::bit_set::BitSet;
5 use rustc_index::vec::{Idx, IndexVec};
6 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
7 use rustc_middle::mir::visit::*;
8 use rustc_middle::mir::*;
9 use rustc_middle::ty::subst::Subst;
10 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
11 use rustc_target::spec::abi::Abi;
13 use super::simplify::{remove_dead_blocks, CfgSimplifier};
14 use crate::transform::MirPass;
15 use std::collections::VecDeque;
18 const DEFAULT_THRESHOLD: usize = 50;
19 const HINT_THRESHOLD: usize = 100;
21 const INSTR_COST: usize = 5;
22 const CALL_PENALTY: usize = 25;
23 const LANDINGPAD_PENALTY: usize = 50;
24 const RESUME_PENALTY: usize = 45;
26 const UNKNOWN_SIZE_COST: usize = 10;
30 #[derive(Copy, Clone, Debug)]
31 struct CallSite<'tcx> {
32 callee: Instance<'tcx>,
34 source_info: SourceInfo,
37 impl<'tcx> MirPass<'tcx> for Inline {
38 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
39 if tcx.sess.opts.debugging_opts.mir_opt_level >= 2 {
40 if tcx.sess.opts.debugging_opts.instrument_coverage {
41 // The current implementation of source code coverage injects code region counters
42 // into the MIR, and assumes a 1-to-1 correspondence between MIR and source-code-
44 debug!("function inlining is disabled when compiling with `instrument_coverage`");
48 param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
49 codegen_fn_attrs: tcx.codegen_fn_attrs(body.source.def_id()),
57 struct Inliner<'tcx> {
59 param_env: ParamEnv<'tcx>,
60 codegen_fn_attrs: &'tcx CodegenFnAttrs,
64 fn run_pass(&self, caller_body: &mut Body<'tcx>) {
65 // Keep a queue of callsites to try inlining on. We take
66 // advantage of the fact that queries detect cycles here to
67 // allow us to try and fetch the fully optimized MIR of a
68 // call; if it succeeds, we can inline it and we know that
69 // they do not call us. Otherwise, we just don't try to
72 // We use a queue so that we inline "broadly" before we inline
73 // in depth. It is unclear if this is the best heuristic,
74 // really, but that's true of all the heuristics in this
77 let mut callsites = VecDeque::new();
79 let def_id = caller_body.source.def_id();
81 // Only do inlining into fn bodies.
82 let self_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
83 if self.tcx.hir().body_owner_kind(self_hir_id).is_fn_or_closure()
84 && caller_body.source.promoted.is_none()
86 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated() {
87 if let Some(callsite) = self.get_valid_function_call(bb, bb_data, caller_body) {
88 callsites.push_back(callsite);
96 let mut changed = false;
100 while let Some(callsite) = callsites.pop_front() {
101 debug!("checking whether to inline callsite {:?}", callsite);
103 if let InstanceDef::Item(_) = callsite.callee.def {
104 if !self.tcx.is_mir_available(callsite.callee.def_id()) {
106 "checking whether to inline callsite {:?} - MIR unavailable",
113 let callee_body = if let Some(callee_def_id) = callsite.callee.def_id().as_local() {
114 let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
115 // Avoid a cycle here by only using `instance_mir` only if we have
116 // a lower `HirId` than the callee. This ensures that the callee will
117 // not inline us. This trick only works without incremental compilation.
118 // So don't do it if that is enabled. Also avoid inlining into generators,
119 // since their `optimized_mir` is used for layout computation, which can
120 // create a cycle, even when no attempt is made to inline the function
121 // in the other direction.
122 if !self.tcx.dep_graph.is_fully_enabled()
123 && self_hir_id < callee_hir_id
124 && caller_body.generator_kind.is_none()
126 self.tcx.instance_mir(callsite.callee.def)
131 // This cannot result in a cycle since the callee MIR is from another crate
132 // and is already optimized.
133 self.tcx.instance_mir(callsite.callee.def)
136 let callee_body: &Body<'tcx> = &*callee_body;
138 let callee_body = if self.consider_optimizing(callsite, callee_body) {
139 self.tcx.subst_and_normalize_erasing_regions(
140 &callsite.callee.substs,
148 // Copy only unevaluated constants from the callee_body into the caller_body.
149 // Although we are only pushing `ConstKind::Unevaluated` consts to
150 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
151 // because we are calling `subst_and_normalize_erasing_regions`.
152 caller_body.required_consts.extend(
153 callee_body.required_consts.iter().copied().filter(|&constant| {
154 matches!(constant.literal.val, ConstKind::Unevaluated(_, _, _))
158 let start = caller_body.basic_blocks().len();
159 debug!("attempting to inline callsite {:?} - body={:?}", callsite, callee_body);
160 if !self.inline_call(callsite, caller_body, callee_body) {
161 debug!("attempting to inline callsite {:?} - failure", callsite);
164 debug!("attempting to inline callsite {:?} - success", callsite);
166 // Add callsites from inlined function
167 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated().skip(start) {
168 if let Some(new_callsite) =
169 self.get_valid_function_call(bb, bb_data, caller_body)
171 // Don't inline the same function multiple times.
172 if callsite.callee != new_callsite.callee {
173 callsites.push_back(new_callsite);
187 // Simplify if we inlined anything.
189 debug!("running simplify cfg on {:?}", caller_body.source);
190 CfgSimplifier::new(caller_body).simplify();
191 remove_dead_blocks(caller_body);
195 fn get_valid_function_call(
198 bb_data: &BasicBlockData<'tcx>,
199 caller_body: &Body<'tcx>,
200 ) -> Option<CallSite<'tcx>> {
201 // Don't inline calls that are in cleanup blocks.
202 if bb_data.is_cleanup {
206 // Only consider direct calls to functions
207 let terminator = bb_data.terminator();
208 if let TerminatorKind::Call { func: ref op, .. } = terminator.kind {
209 if let ty::FnDef(callee_def_id, substs) = *op.ty(caller_body, self.tcx).kind() {
210 // To resolve an instance its substs have to be fully normalized, so
212 let normalized_substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
214 Instance::resolve(self.tcx, self.param_env, callee_def_id, normalized_substs)
218 if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def {
222 return Some(CallSite { callee, bb, source_info: terminator.source_info });
229 fn consider_optimizing(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
230 debug!("consider_optimizing({:?})", callsite);
231 self.should_inline(callsite, callee_body)
232 && self.tcx.consider_optimizing(|| {
233 format!("Inline {:?} into {:?}", callee_body.span, callsite)
237 fn should_inline(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
238 debug!("should_inline({:?})", callsite);
241 // Cannot inline generators which haven't been transformed yet
242 if callee_body.yield_ty.is_some() {
243 debug!(" yield ty present - not inlining");
247 let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee.def_id());
249 let self_features = &self.codegen_fn_attrs.target_features;
250 let callee_features = &codegen_fn_attrs.target_features;
251 if callee_features.iter().any(|feature| !self_features.contains(feature)) {
252 debug!("`callee has extra target features - not inlining");
256 let self_no_sanitize =
257 self.codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
258 let callee_no_sanitize =
259 codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
260 if self_no_sanitize != callee_no_sanitize {
261 debug!("`callee has incompatible no_sanitize attribute - not inlining");
265 let hinted = match codegen_fn_attrs.inline {
266 // Just treat inline(always) as a hint for now,
267 // there are cases that prevent inlining that we
268 // need to check for first.
269 attr::InlineAttr::Always => true,
270 attr::InlineAttr::Never => {
271 debug!("`#[inline(never)]` present - not inlining");
274 attr::InlineAttr::Hint => true,
275 attr::InlineAttr::None => false,
278 // Only inline local functions if they would be eligible for cross-crate
279 // inlining. This is to ensure that the final crate doesn't have MIR that
280 // reference unexported symbols
281 if callsite.callee.def_id().is_local() {
282 if callsite.callee.substs.non_erasable_generics().count() == 0 && !hinted {
283 debug!(" callee is an exported function - not inlining");
288 let mut threshold = if hinted { HINT_THRESHOLD } else { DEFAULT_THRESHOLD };
290 // Significantly lower the threshold for inlining cold functions
291 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
295 // Give a bonus functions with a small number of blocks,
296 // We normally have two or three blocks for even
297 // very small functions.
298 if callee_body.basic_blocks().len() <= 3 {
299 threshold += threshold / 4;
301 debug!(" final inline threshold = {}", threshold);
303 // FIXME: Give a bonus to functions with only a single caller
304 let mut first_block = true;
307 // Traverse the MIR manually so we can account for the effects of
308 // inlining on the CFG.
309 let mut work_list = vec![START_BLOCK];
310 let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
311 while let Some(bb) = work_list.pop() {
312 if !visited.insert(bb.index()) {
315 let blk = &callee_body.basic_blocks()[bb];
317 for stmt in &blk.statements {
318 // Don't count StorageLive/StorageDead in the inlining cost.
320 StatementKind::StorageLive(_)
321 | StatementKind::StorageDead(_)
322 | StatementKind::Nop => {}
323 _ => cost += INSTR_COST,
326 let term = blk.terminator();
327 let mut is_drop = false;
329 TerminatorKind::Drop { ref place, target, unwind }
330 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
332 work_list.push(target);
333 // If the place doesn't actually need dropping, treat it like
335 let ty = place.ty(callee_body, tcx).subst(tcx, callsite.callee.substs).ty;
336 if ty.needs_drop(tcx, self.param_env) {
337 cost += CALL_PENALTY;
338 if let Some(unwind) = unwind {
339 cost += LANDINGPAD_PENALTY;
340 work_list.push(unwind);
347 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
350 // If the function always diverges, don't inline
351 // unless the cost is zero
355 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
356 if let ty::FnDef(def_id, _) = *f.literal.ty.kind() {
357 // Don't give intrinsics the extra penalty for calls
358 let f = tcx.fn_sig(def_id);
359 if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
362 cost += CALL_PENALTY;
365 cost += CALL_PENALTY;
367 if cleanup.is_some() {
368 cost += LANDINGPAD_PENALTY;
371 TerminatorKind::Assert { cleanup, .. } => {
372 cost += CALL_PENALTY;
374 if cleanup.is_some() {
375 cost += LANDINGPAD_PENALTY;
378 TerminatorKind::Resume => cost += RESUME_PENALTY,
379 _ => cost += INSTR_COST,
383 for &succ in term.successors() {
384 work_list.push(succ);
391 // Count up the cost of local variables and temps, if we know the size
392 // use that, otherwise we use a moderately-large dummy cost.
394 let ptr_size = tcx.data_layout.pointer_size.bytes();
396 for v in callee_body.vars_and_temps_iter() {
397 let v = &callee_body.local_decls[v];
398 let ty = v.ty.subst(tcx, callsite.callee.substs);
399 // Cost of the var is the size in machine-words, if we know
401 if let Some(size) = type_size_of(tcx, self.param_env, ty) {
402 cost += (size / ptr_size) as usize;
404 cost += UNKNOWN_SIZE_COST;
408 if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
409 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
412 if cost <= threshold {
413 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
416 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
424 callsite: CallSite<'tcx>,
425 caller_body: &mut Body<'tcx>,
426 mut callee_body: Body<'tcx>,
428 let terminator = caller_body[callsite.bb].terminator.take().unwrap();
429 match terminator.kind {
430 // FIXME: Handle inlining of diverging calls
431 TerminatorKind::Call { args, destination: Some(destination), cleanup, .. } => {
432 debug!("inlined {:?} into {:?}", callsite.callee, caller_body.source);
434 let mut local_map = IndexVec::with_capacity(callee_body.local_decls.len());
435 let mut scope_map = IndexVec::with_capacity(callee_body.source_scopes.len());
437 for mut scope in callee_body.source_scopes.iter().cloned() {
438 // Map the callee scopes into the caller.
439 // FIXME(eddyb) this may ICE if the scopes are out of order.
440 scope.parent_scope = scope.parent_scope.map(|s| scope_map[s]);
441 scope.inlined_parent_scope = scope.inlined_parent_scope.map(|s| scope_map[s]);
443 if scope.parent_scope.is_none() {
444 let callsite_scope = &caller_body.source_scopes[callsite.source_info.scope];
446 // Attach the outermost callee scope as a child of the callsite
447 // scope, via the `parent_scope` and `inlined_parent_scope` chains.
448 scope.parent_scope = Some(callsite.source_info.scope);
449 assert_eq!(scope.inlined_parent_scope, None);
450 scope.inlined_parent_scope = if callsite_scope.inlined.is_some() {
451 Some(callsite.source_info.scope)
453 callsite_scope.inlined_parent_scope
456 // Mark the outermost callee scope as an inlined one.
457 assert_eq!(scope.inlined, None);
458 scope.inlined = Some((callsite.callee, callsite.source_info.span));
459 } else if scope.inlined_parent_scope.is_none() {
460 // Make it easy to find the scope with `inlined` set above.
461 scope.inlined_parent_scope = Some(scope_map[OUTERMOST_SOURCE_SCOPE]);
464 let idx = caller_body.source_scopes.push(scope);
468 for loc in callee_body.vars_and_temps_iter() {
469 let mut local = callee_body.local_decls[loc].clone();
471 local.source_info.scope = scope_map[local.source_info.scope];
472 local.source_info.span = callsite.source_info.span;
474 let idx = caller_body.local_decls.push(local);
478 // If the call is something like `a[*i] = f(i)`, where
479 // `i : &mut usize`, then just duplicating the `a[*i]`
480 // Place could result in two different locations if `f`
481 // writes to `i`. To prevent this we need to create a temporary
482 // borrow of the place and pass the destination as `*temp` instead.
483 fn dest_needs_borrow(place: Place<'_>) -> bool {
484 for elem in place.projection.iter() {
486 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
494 let dest = if dest_needs_borrow(destination.0) {
495 debug!("creating temp for return destination");
496 let dest = Rvalue::Ref(
497 self.tcx.lifetimes.re_erased,
498 BorrowKind::Mut { allow_two_phase_borrow: false },
502 let ty = dest.ty(caller_body, self.tcx);
504 let temp = LocalDecl::new(ty, callsite.source_info.span);
506 let tmp = caller_body.local_decls.push(temp);
507 let tmp = Place::from(tmp);
509 let stmt = Statement {
510 source_info: callsite.source_info,
511 kind: StatementKind::Assign(box (tmp, dest)),
513 caller_body[callsite.bb].statements.push(stmt);
514 self.tcx.mk_place_deref(tmp)
519 let return_block = destination.1;
521 // Copy the arguments if needed.
522 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, return_block);
524 let bb_len = caller_body.basic_blocks().len();
525 let mut integrator = Integrator {
532 cleanup_block: cleanup,
533 in_cleanup_block: false,
537 for mut var_debug_info in callee_body.var_debug_info.drain(..) {
538 integrator.visit_var_debug_info(&mut var_debug_info);
539 caller_body.var_debug_info.push(var_debug_info);
542 for (bb, mut block) in callee_body.basic_blocks_mut().drain_enumerated(..) {
543 integrator.visit_basic_block_data(bb, &mut block);
544 caller_body.basic_blocks_mut().push(block);
547 let terminator = Terminator {
548 source_info: callsite.source_info,
549 kind: TerminatorKind::Goto { target: BasicBlock::new(bb_len) },
552 caller_body[callsite.bb].terminator = Some(terminator);
557 caller_body[callsite.bb].terminator =
558 Some(Terminator { source_info: terminator.source_info, kind });
566 args: Vec<Operand<'tcx>>,
567 callsite: &CallSite<'tcx>,
568 caller_body: &mut Body<'tcx>,
569 return_block: BasicBlock,
573 // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
574 // The caller provides the arguments wrapped up in a tuple:
576 // tuple_tmp = (a, b, c)
577 // Fn::call(closure_ref, tuple_tmp)
579 // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
580 // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
581 // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
584 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
586 // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
587 // if we "spill" that into *another* temporary, so that we can map the argument
588 // variable in the callee MIR directly to an argument variable on our side.
589 // So we introduce temporaries like:
591 // tmp0 = tuple_tmp.0
592 // tmp1 = tuple_tmp.1
593 // tmp2 = tuple_tmp.2
595 // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
596 // FIXME(eddyb) make this check for `"rust-call"` ABI combined with
597 // `callee_body.spread_arg == None`, instead of special-casing closures.
598 if tcx.is_closure(callsite.callee.def_id()) {
599 let mut args = args.into_iter();
600 let self_ = self.create_temp_if_necessary(
601 args.next().unwrap(),
606 let tuple = self.create_temp_if_necessary(
607 args.next().unwrap(),
612 assert!(args.next().is_none());
614 let tuple = Place::from(tuple);
615 let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.kind() {
618 bug!("Closure arguments are not passed as a tuple");
621 // The `closure_ref` in our example above.
622 let closure_ref_arg = iter::once(self_);
624 // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
625 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
626 // This is e.g., `tuple_tmp.0` in our example above.
628 Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty.expect_ty()));
630 // Spill to a local to make e.g., `tmp0`.
631 self.create_temp_if_necessary(tuple_field, callsite, caller_body, return_block)
634 closure_ref_arg.chain(tuple_tmp_args).collect()
637 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body, return_block))
642 /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
643 /// temporary `T` and an instruction `T = arg`, and returns `T`.
644 fn create_temp_if_necessary(
647 callsite: &CallSite<'tcx>,
648 caller_body: &mut Body<'tcx>,
649 return_block: BasicBlock,
651 // FIXME: Analysis of the usage of the arguments to avoid
652 // unnecessary temporaries.
654 if let Operand::Move(place) = &arg {
655 if let Some(local) = place.as_local() {
656 if caller_body.local_kind(local) == LocalKind::Temp {
657 // Reuse the operand if it's a temporary already
663 debug!("creating temp for argument {:?}", arg);
664 // Otherwise, create a temporary for the arg
665 let arg = Rvalue::Use(arg);
667 let ty = arg.ty(caller_body, self.tcx);
669 let arg_tmp = LocalDecl::new(ty, callsite.source_info.span);
670 let arg_tmp = caller_body.local_decls.push(arg_tmp);
672 caller_body[callsite.bb].statements.push(Statement {
673 source_info: callsite.source_info,
674 kind: StatementKind::StorageLive(arg_tmp),
676 caller_body[callsite.bb].statements.push(Statement {
677 source_info: callsite.source_info,
678 kind: StatementKind::Assign(box (Place::from(arg_tmp), arg)),
680 caller_body[return_block].statements.insert(
683 source_info: callsite.source_info,
684 kind: StatementKind::StorageDead(arg_tmp),
692 fn type_size_of<'tcx>(
694 param_env: ty::ParamEnv<'tcx>,
697 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
703 * Integrates blocks from the callee function into the calling function.
704 * Updates block indices, references to locals and other control flow
707 struct Integrator<'a, 'tcx> {
710 local_map: IndexVec<Local, Local>,
711 scope_map: IndexVec<SourceScope, SourceScope>,
712 destination: Place<'tcx>,
713 return_block: BasicBlock,
714 cleanup_block: Option<BasicBlock>,
715 in_cleanup_block: bool,
719 impl<'a, 'tcx> Integrator<'a, 'tcx> {
720 fn update_target(&self, tgt: BasicBlock) -> BasicBlock {
721 let new = BasicBlock::new(tgt.index() + self.block_idx);
722 debug!("updating target `{:?}`, new: `{:?}`", tgt, new);
726 fn make_integrate_local(&self, local: Local) -> Local {
727 if local == RETURN_PLACE {
728 return self.destination.local;
731 let idx = local.index() - 1;
732 if idx < self.args.len() {
733 return self.args[idx];
736 self.local_map[Local::new(idx - self.args.len())]
740 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
741 fn tcx(&self) -> TyCtxt<'tcx> {
745 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
746 *local = self.make_integrate_local(*local);
749 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
750 // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
751 let dest_proj_len = self.destination.projection.len();
752 if place.local == RETURN_PLACE && dest_proj_len > 0 {
753 let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
754 projs.extend(self.destination.projection);
755 projs.extend(place.projection);
757 place.projection = self.tcx.intern_place_elems(&*projs);
759 // Handles integrating any locals that occur in the base
761 self.super_place(place, context, location)
764 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
765 self.in_cleanup_block = data.is_cleanup;
766 self.super_basic_block_data(block, data);
767 self.in_cleanup_block = false;
770 fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
771 self.super_retag(kind, place, loc);
773 // We have to patch all inlined retags to be aware that they are no longer
774 // happening on function entry.
775 if *kind == RetagKind::FnEntry {
776 *kind = RetagKind::Default;
780 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
781 // Don't try to modify the implicit `_0` access on return (`return` terminators are
782 // replaced down below anyways).
783 if !matches!(terminator.kind, TerminatorKind::Return) {
784 self.super_terminator(terminator, loc);
787 match terminator.kind {
788 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
789 TerminatorKind::Goto { ref mut target } => {
790 *target = self.update_target(*target);
792 TerminatorKind::SwitchInt { ref mut targets, .. } => {
793 for tgt in targets.all_targets_mut() {
794 *tgt = self.update_target(*tgt);
797 TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
798 | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
799 *target = self.update_target(*target);
800 if let Some(tgt) = *unwind {
801 *unwind = Some(self.update_target(tgt));
802 } else if !self.in_cleanup_block {
803 // Unless this drop is in a cleanup block, add an unwind edge to
804 // the original call's cleanup block
805 *unwind = self.cleanup_block;
808 TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
809 if let Some((_, ref mut tgt)) = *destination {
810 *tgt = self.update_target(*tgt);
812 if let Some(tgt) = *cleanup {
813 *cleanup = Some(self.update_target(tgt));
814 } else if !self.in_cleanup_block {
815 // Unless this call is in a cleanup block, add an unwind edge to
816 // the original call's cleanup block
817 *cleanup = self.cleanup_block;
820 TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
821 *target = self.update_target(*target);
822 if let Some(tgt) = *cleanup {
823 *cleanup = Some(self.update_target(tgt));
824 } else if !self.in_cleanup_block {
825 // Unless this assert is in a cleanup block, add an unwind edge to
826 // the original call's cleanup block
827 *cleanup = self.cleanup_block;
830 TerminatorKind::Return => {
831 terminator.kind = TerminatorKind::Goto { target: self.return_block };
833 TerminatorKind::Resume => {
834 if let Some(tgt) = self.cleanup_block {
835 terminator.kind = TerminatorKind::Goto { target: tgt }
838 TerminatorKind::Abort => {}
839 TerminatorKind::Unreachable => {}
840 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
841 *real_target = self.update_target(*real_target);
842 *imaginary_target = self.update_target(*imaginary_target);
844 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
845 // see the ordering of passes in the optimized_mir query.
847 bug!("False unwinds should have been removed before inlining")
849 TerminatorKind::InlineAsm { ref mut destination, .. } => {
850 if let Some(ref mut tgt) = *destination {
851 *tgt = self.update_target(*tgt);
857 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
858 *scope = self.scope_map[*scope];