1 //! Inlining pass for MIR functions
3 use rustc_attr as attr;
4 use rustc_hir::def_id::DefId;
5 use rustc_index::bit_set::BitSet;
6 use rustc_index::vec::{Idx, IndexVec};
7 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
8 use rustc_middle::mir::visit::*;
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::subst::{Subst, SubstsRef};
11 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
12 use rustc_target::spec::abi::Abi;
14 use super::simplify::{remove_dead_blocks, CfgSimplifier};
15 use crate::transform::MirPass;
16 use std::collections::VecDeque;
19 const DEFAULT_THRESHOLD: usize = 50;
20 const HINT_THRESHOLD: usize = 100;
22 const INSTR_COST: usize = 5;
23 const CALL_PENALTY: usize = 25;
24 const LANDINGPAD_PENALTY: usize = 50;
25 const RESUME_PENALTY: usize = 45;
27 const UNKNOWN_SIZE_COST: usize = 10;
31 #[derive(Copy, Clone, Debug)]
32 struct CallSite<'tcx> {
34 substs: SubstsRef<'tcx>,
39 impl<'tcx> MirPass<'tcx> for Inline {
40 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
41 if tcx.sess.opts.debugging_opts.mir_opt_level >= 2 {
42 if tcx.sess.opts.debugging_opts.instrument_coverage {
43 // The current implementation of source code coverage injects code region counters
44 // into the MIR, and assumes a 1-to-1 correspondence between MIR and source-code-
46 debug!("function inlining is disabled when compiling with `instrument_coverage`");
48 Inliner { tcx, codegen_fn_attrs: tcx.codegen_fn_attrs(body.source.def_id()) }
55 struct Inliner<'tcx> {
57 codegen_fn_attrs: &'tcx CodegenFnAttrs,
61 fn run_pass(&self, caller_body: &mut Body<'tcx>) {
62 // Keep a queue of callsites to try inlining on. We take
63 // advantage of the fact that queries detect cycles here to
64 // allow us to try and fetch the fully optimized MIR of a
65 // call; if it succeeds, we can inline it and we know that
66 // they do not call us. Otherwise, we just don't try to
69 // We use a queue so that we inline "broadly" before we inline
70 // in depth. It is unclear if this is the best heuristic,
71 // really, but that's true of all the heuristics in this
74 let mut callsites = VecDeque::new();
76 let def_id = caller_body.source.def_id();
78 let param_env = self.tcx.param_env_reveal_all_normalized(def_id);
80 // Only do inlining into fn bodies.
81 let self_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
82 if self.tcx.hir().body_owner_kind(self_hir_id).is_fn_or_closure()
83 && caller_body.source.promoted.is_none()
85 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated() {
86 if let Some(callsite) =
87 self.get_valid_function_call(bb, bb_data, caller_body, param_env)
89 callsites.push_back(callsite);
97 let mut changed = false;
100 local_change = false;
101 while let Some(callsite) = callsites.pop_front() {
102 debug!("checking whether to inline callsite {:?}", callsite);
103 if !self.tcx.is_mir_available(callsite.callee) {
104 debug!("checking whether to inline callsite {:?} - MIR unavailable", callsite);
108 let callee_body = if let Some(callee_def_id) = callsite.callee.as_local() {
109 let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
110 // Avoid a cycle here by only using `optimized_mir` only if we have
111 // a lower `HirId` than the callee. This ensures that the callee will
112 // not inline us. This trick only works without incremental compilation.
113 // So don't do it if that is enabled. Also avoid inlining into generators,
114 // since their `optimized_mir` is used for layout computation, which can
115 // create a cycle, even when no attempt is made to inline the function
116 // in the other direction.
117 if !self.tcx.dep_graph.is_fully_enabled()
118 && self_hir_id < callee_hir_id
119 && caller_body.generator_kind.is_none()
121 self.tcx.optimized_mir(callsite.callee)
126 // This cannot result in a cycle since the callee MIR is from another crate
127 // and is already optimized.
128 self.tcx.optimized_mir(callsite.callee)
131 let callee_body = if self.consider_optimizing(callsite, callee_body) {
132 self.tcx.subst_and_normalize_erasing_regions(
141 // Copy only unevaluated constants from the callee_body into the caller_body.
142 // Although we are only pushing `ConstKind::Unevaluated` consts to
143 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
144 // because we are calling `subst_and_normalize_erasing_regions`.
145 caller_body.required_consts.extend(
146 callee_body.required_consts.iter().copied().filter(|&constant| {
147 matches!(constant.literal.val, ConstKind::Unevaluated(_, _, _))
151 let start = caller_body.basic_blocks().len();
152 debug!("attempting to inline callsite {:?} - body={:?}", callsite, callee_body);
153 if !self.inline_call(callsite, caller_body, callee_body) {
154 debug!("attempting to inline callsite {:?} - failure", callsite);
157 debug!("attempting to inline callsite {:?} - success", callsite);
159 // Add callsites from inlined function
160 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated().skip(start) {
161 if let Some(new_callsite) =
162 self.get_valid_function_call(bb, bb_data, caller_body, param_env)
164 // Don't inline the same function multiple times.
165 if callsite.callee != new_callsite.callee {
166 callsites.push_back(new_callsite);
180 // Simplify if we inlined anything.
182 debug!("running simplify cfg on {:?}", caller_body.source);
183 CfgSimplifier::new(caller_body).simplify();
184 remove_dead_blocks(caller_body);
188 fn get_valid_function_call(
191 bb_data: &BasicBlockData<'tcx>,
192 caller_body: &Body<'tcx>,
193 param_env: ParamEnv<'tcx>,
194 ) -> Option<CallSite<'tcx>> {
195 // Don't inline calls that are in cleanup blocks.
196 if bb_data.is_cleanup {
200 // Only consider direct calls to functions
201 let terminator = bb_data.terminator();
202 if let TerminatorKind::Call { func: ref op, .. } = terminator.kind {
203 if let ty::FnDef(callee_def_id, substs) = *op.ty(caller_body, self.tcx).kind() {
205 Instance::resolve(self.tcx, param_env, callee_def_id, substs).ok().flatten()?;
207 if let InstanceDef::Virtual(..) = instance.def {
211 return Some(CallSite {
212 callee: instance.def_id(),
213 substs: instance.substs,
215 location: terminator.source_info,
223 fn consider_optimizing(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
224 debug!("consider_optimizing({:?})", callsite);
225 self.should_inline(callsite, callee_body)
226 && self.tcx.consider_optimizing(|| {
227 format!("Inline {:?} into {:?}", callee_body.span, callsite)
231 fn should_inline(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
232 debug!("should_inline({:?})", callsite);
235 // Cannot inline generators which haven't been transformed yet
236 if callee_body.yield_ty.is_some() {
237 debug!(" yield ty present - not inlining");
241 let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee);
243 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::TRACK_CALLER) {
244 debug!("`#[track_caller]` present - not inlining");
248 let self_features = &self.codegen_fn_attrs.target_features;
249 let callee_features = &codegen_fn_attrs.target_features;
250 if callee_features.iter().any(|feature| !self_features.contains(feature)) {
251 debug!("`callee has extra target features - not inlining");
255 let self_no_sanitize =
256 self.codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
257 let callee_no_sanitize =
258 codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
259 if self_no_sanitize != callee_no_sanitize {
260 debug!("`callee has incompatible no_sanitize attribute - not inlining");
264 let hinted = match codegen_fn_attrs.inline {
265 // Just treat inline(always) as a hint for now,
266 // there are cases that prevent inlining that we
267 // need to check for first.
268 attr::InlineAttr::Always => true,
269 attr::InlineAttr::Never => {
270 debug!("`#[inline(never)]` present - not inlining");
273 attr::InlineAttr::Hint => true,
274 attr::InlineAttr::None => false,
277 // Only inline local functions if they would be eligible for cross-crate
278 // inlining. This is to ensure that the final crate doesn't have MIR that
279 // reference unexported symbols
280 if callsite.callee.is_local() {
281 if callsite.substs.non_erasable_generics().count() == 0 && !hinted {
282 debug!(" callee is an exported function - not inlining");
287 let mut threshold = if hinted { HINT_THRESHOLD } else { DEFAULT_THRESHOLD };
289 // Significantly lower the threshold for inlining cold functions
290 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
294 // Give a bonus functions with a small number of blocks,
295 // We normally have two or three blocks for even
296 // very small functions.
297 if callee_body.basic_blocks().len() <= 3 {
298 threshold += threshold / 4;
300 debug!(" final inline threshold = {}", threshold);
302 // FIXME: Give a bonus to functions with only a single caller
304 let param_env = tcx.param_env(callee_body.source.def_id());
306 let mut first_block = true;
309 // Traverse the MIR manually so we can account for the effects of
310 // inlining on the CFG.
311 let mut work_list = vec![START_BLOCK];
312 let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
313 while let Some(bb) = work_list.pop() {
314 if !visited.insert(bb.index()) {
317 let blk = &callee_body.basic_blocks()[bb];
319 for stmt in &blk.statements {
320 // Don't count StorageLive/StorageDead in the inlining cost.
322 StatementKind::StorageLive(_)
323 | StatementKind::StorageDead(_)
324 | StatementKind::Nop => {}
325 _ => cost += INSTR_COST,
328 let term = blk.terminator();
329 let mut is_drop = false;
331 TerminatorKind::Drop { ref place, target, unwind }
332 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
334 work_list.push(target);
335 // If the place doesn't actually need dropping, treat it like
337 let ty = place.ty(callee_body, tcx).subst(tcx, callsite.substs).ty;
338 if ty.needs_drop(tcx, param_env) {
339 cost += CALL_PENALTY;
340 if let Some(unwind) = unwind {
341 cost += LANDINGPAD_PENALTY;
342 work_list.push(unwind);
349 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
352 // If the function always diverges, don't inline
353 // unless the cost is zero
357 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
358 if let ty::FnDef(def_id, _) = *f.literal.ty.kind() {
359 // Don't give intrinsics the extra penalty for calls
360 let f = tcx.fn_sig(def_id);
361 if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
364 cost += CALL_PENALTY;
367 cost += CALL_PENALTY;
369 if cleanup.is_some() {
370 cost += LANDINGPAD_PENALTY;
373 TerminatorKind::Assert { cleanup, .. } => {
374 cost += CALL_PENALTY;
376 if cleanup.is_some() {
377 cost += LANDINGPAD_PENALTY;
380 TerminatorKind::Resume => cost += RESUME_PENALTY,
381 _ => cost += INSTR_COST,
385 for &succ in term.successors() {
386 work_list.push(succ);
393 // Count up the cost of local variables and temps, if we know the size
394 // use that, otherwise we use a moderately-large dummy cost.
396 let ptr_size = tcx.data_layout.pointer_size.bytes();
398 for v in callee_body.vars_and_temps_iter() {
399 let v = &callee_body.local_decls[v];
400 let ty = v.ty.subst(tcx, callsite.substs);
401 // Cost of the var is the size in machine-words, if we know
403 if let Some(size) = type_size_of(tcx, param_env, ty) {
404 cost += (size / ptr_size) as usize;
406 cost += UNKNOWN_SIZE_COST;
410 if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
411 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
414 if cost <= threshold {
415 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
418 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
426 callsite: CallSite<'tcx>,
427 caller_body: &mut Body<'tcx>,
428 mut callee_body: Body<'tcx>,
430 let terminator = caller_body[callsite.bb].terminator.take().unwrap();
431 match terminator.kind {
432 // FIXME: Handle inlining of diverging calls
433 TerminatorKind::Call { args, destination: Some(destination), cleanup, .. } => {
434 debug!("inlined {:?} into {:?}", callsite.callee, caller_body.source);
436 let mut local_map = IndexVec::with_capacity(callee_body.local_decls.len());
437 let mut scope_map = IndexVec::with_capacity(callee_body.source_scopes.len());
439 for mut scope in callee_body.source_scopes.iter().cloned() {
440 if scope.parent_scope.is_none() {
441 scope.parent_scope = Some(callsite.location.scope);
442 // FIXME(eddyb) is this really needed?
443 // (also note that it's always overwritten below)
444 scope.span = callee_body.span;
447 // FIXME(eddyb) this doesn't seem right at all.
448 // The inlined source scopes should probably be annotated as
449 // such, but also contain all of the original information.
450 scope.span = callsite.location.span;
452 let idx = caller_body.source_scopes.push(scope);
456 for loc in callee_body.vars_and_temps_iter() {
457 let mut local = callee_body.local_decls[loc].clone();
459 local.source_info.scope = scope_map[local.source_info.scope];
460 local.source_info.span = callsite.location.span;
462 let idx = caller_body.local_decls.push(local);
466 // If the call is something like `a[*i] = f(i)`, where
467 // `i : &mut usize`, then just duplicating the `a[*i]`
468 // Place could result in two different locations if `f`
469 // writes to `i`. To prevent this we need to create a temporary
470 // borrow of the place and pass the destination as `*temp` instead.
471 fn dest_needs_borrow(place: Place<'_>) -> bool {
472 for elem in place.projection.iter() {
474 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
482 let dest = if dest_needs_borrow(destination.0) {
483 debug!("creating temp for return destination");
484 let dest = Rvalue::Ref(
485 self.tcx.lifetimes.re_erased,
486 BorrowKind::Mut { allow_two_phase_borrow: false },
490 let ty = dest.ty(caller_body, self.tcx);
492 let temp = LocalDecl::new(ty, callsite.location.span);
494 let tmp = caller_body.local_decls.push(temp);
495 let tmp = Place::from(tmp);
497 let stmt = Statement {
498 source_info: callsite.location,
499 kind: StatementKind::Assign(box (tmp, dest)),
501 caller_body[callsite.bb].statements.push(stmt);
502 self.tcx.mk_place_deref(tmp)
507 let return_block = destination.1;
509 // Copy the arguments if needed.
510 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, return_block);
512 let bb_len = caller_body.basic_blocks().len();
513 let mut integrator = Integrator {
520 cleanup_block: cleanup,
521 in_cleanup_block: false,
525 for mut var_debug_info in callee_body.var_debug_info.drain(..) {
526 integrator.visit_var_debug_info(&mut var_debug_info);
527 caller_body.var_debug_info.push(var_debug_info);
530 for (bb, mut block) in callee_body.basic_blocks_mut().drain_enumerated(..) {
531 integrator.visit_basic_block_data(bb, &mut block);
532 caller_body.basic_blocks_mut().push(block);
535 let terminator = Terminator {
536 source_info: callsite.location,
537 kind: TerminatorKind::Goto { target: BasicBlock::new(bb_len) },
540 caller_body[callsite.bb].terminator = Some(terminator);
545 caller_body[callsite.bb].terminator =
546 Some(Terminator { source_info: terminator.source_info, kind });
554 args: Vec<Operand<'tcx>>,
555 callsite: &CallSite<'tcx>,
556 caller_body: &mut Body<'tcx>,
557 return_block: BasicBlock,
561 // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
562 // The caller provides the arguments wrapped up in a tuple:
564 // tuple_tmp = (a, b, c)
565 // Fn::call(closure_ref, tuple_tmp)
567 // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
568 // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
569 // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
572 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
574 // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
575 // if we "spill" that into *another* temporary, so that we can map the argument
576 // variable in the callee MIR directly to an argument variable on our side.
577 // So we introduce temporaries like:
579 // tmp0 = tuple_tmp.0
580 // tmp1 = tuple_tmp.1
581 // tmp2 = tuple_tmp.2
583 // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
584 if tcx.is_closure(callsite.callee) {
585 let mut args = args.into_iter();
586 let self_ = self.create_temp_if_necessary(
587 args.next().unwrap(),
592 let tuple = self.create_temp_if_necessary(
593 args.next().unwrap(),
598 assert!(args.next().is_none());
600 let tuple = Place::from(tuple);
601 let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.kind() {
604 bug!("Closure arguments are not passed as a tuple");
607 // The `closure_ref` in our example above.
608 let closure_ref_arg = iter::once(self_);
610 // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
611 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
612 // This is e.g., `tuple_tmp.0` in our example above.
614 Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty.expect_ty()));
616 // Spill to a local to make e.g., `tmp0`.
617 self.create_temp_if_necessary(tuple_field, callsite, caller_body, return_block)
620 closure_ref_arg.chain(tuple_tmp_args).collect()
623 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body, return_block))
628 /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
629 /// temporary `T` and an instruction `T = arg`, and returns `T`.
630 fn create_temp_if_necessary(
633 callsite: &CallSite<'tcx>,
634 caller_body: &mut Body<'tcx>,
635 return_block: BasicBlock,
637 // FIXME: Analysis of the usage of the arguments to avoid
638 // unnecessary temporaries.
640 if let Operand::Move(place) = &arg {
641 if let Some(local) = place.as_local() {
642 if caller_body.local_kind(local) == LocalKind::Temp {
643 // Reuse the operand if it's a temporary already
649 debug!("creating temp for argument {:?}", arg);
650 // Otherwise, create a temporary for the arg
651 let arg = Rvalue::Use(arg);
653 let ty = arg.ty(caller_body, self.tcx);
655 let arg_tmp = LocalDecl::new(ty, callsite.location.span);
656 let arg_tmp = caller_body.local_decls.push(arg_tmp);
658 caller_body[callsite.bb].statements.push(Statement {
659 source_info: callsite.location,
660 kind: StatementKind::StorageLive(arg_tmp),
662 caller_body[callsite.bb].statements.push(Statement {
663 source_info: callsite.location,
664 kind: StatementKind::Assign(box (Place::from(arg_tmp), arg)),
666 caller_body[return_block].statements.insert(
668 Statement { source_info: callsite.location, kind: StatementKind::StorageDead(arg_tmp) },
675 fn type_size_of<'tcx>(
677 param_env: ty::ParamEnv<'tcx>,
680 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
686 * Integrates blocks from the callee function into the calling function.
687 * Updates block indices, references to locals and other control flow
690 struct Integrator<'a, 'tcx> {
693 local_map: IndexVec<Local, Local>,
694 scope_map: IndexVec<SourceScope, SourceScope>,
695 destination: Place<'tcx>,
696 return_block: BasicBlock,
697 cleanup_block: Option<BasicBlock>,
698 in_cleanup_block: bool,
702 impl<'a, 'tcx> Integrator<'a, 'tcx> {
703 fn update_target(&self, tgt: BasicBlock) -> BasicBlock {
704 let new = BasicBlock::new(tgt.index() + self.block_idx);
705 debug!("updating target `{:?}`, new: `{:?}`", tgt, new);
709 fn make_integrate_local(&self, local: Local) -> Local {
710 if local == RETURN_PLACE {
711 return self.destination.local;
714 let idx = local.index() - 1;
715 if idx < self.args.len() {
716 return self.args[idx];
719 self.local_map[Local::new(idx - self.args.len())]
723 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
724 fn tcx(&self) -> TyCtxt<'tcx> {
728 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
729 *local = self.make_integrate_local(*local);
732 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
733 // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
734 let dest_proj_len = self.destination.projection.len();
735 if place.local == RETURN_PLACE && dest_proj_len > 0 {
736 let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
737 projs.extend(self.destination.projection);
738 projs.extend(place.projection);
740 place.projection = self.tcx.intern_place_elems(&*projs);
742 // Handles integrating any locals that occur in the base
744 self.super_place(place, context, location)
747 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
748 self.in_cleanup_block = data.is_cleanup;
749 self.super_basic_block_data(block, data);
750 self.in_cleanup_block = false;
753 fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
754 self.super_retag(kind, place, loc);
756 // We have to patch all inlined retags to be aware that they are no longer
757 // happening on function entry.
758 if *kind == RetagKind::FnEntry {
759 *kind = RetagKind::Default;
763 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
764 // Don't try to modify the implicit `_0` access on return (`return` terminators are
765 // replaced down below anyways).
766 if !matches!(terminator.kind, TerminatorKind::Return) {
767 self.super_terminator(terminator, loc);
770 match terminator.kind {
771 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
772 TerminatorKind::Goto { ref mut target } => {
773 *target = self.update_target(*target);
775 TerminatorKind::SwitchInt { ref mut targets, .. } => {
777 *tgt = self.update_target(*tgt);
780 TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
781 | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
782 *target = self.update_target(*target);
783 if let Some(tgt) = *unwind {
784 *unwind = Some(self.update_target(tgt));
785 } else if !self.in_cleanup_block {
786 // Unless this drop is in a cleanup block, add an unwind edge to
787 // the original call's cleanup block
788 *unwind = self.cleanup_block;
791 TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
792 if let Some((_, ref mut tgt)) = *destination {
793 *tgt = self.update_target(*tgt);
795 if let Some(tgt) = *cleanup {
796 *cleanup = Some(self.update_target(tgt));
797 } else if !self.in_cleanup_block {
798 // Unless this call is in a cleanup block, add an unwind edge to
799 // the original call's cleanup block
800 *cleanup = self.cleanup_block;
803 TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
804 *target = self.update_target(*target);
805 if let Some(tgt) = *cleanup {
806 *cleanup = Some(self.update_target(tgt));
807 } else if !self.in_cleanup_block {
808 // Unless this assert is in a cleanup block, add an unwind edge to
809 // the original call's cleanup block
810 *cleanup = self.cleanup_block;
813 TerminatorKind::Return => {
814 terminator.kind = TerminatorKind::Goto { target: self.return_block };
816 TerminatorKind::Resume => {
817 if let Some(tgt) = self.cleanup_block {
818 terminator.kind = TerminatorKind::Goto { target: tgt }
821 TerminatorKind::Abort => {}
822 TerminatorKind::Unreachable => {}
823 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
824 *real_target = self.update_target(*real_target);
825 *imaginary_target = self.update_target(*imaginary_target);
827 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
828 // see the ordering of passes in the optimized_mir query.
830 bug!("False unwinds should have been removed before inlining")
832 TerminatorKind::InlineAsm { ref mut destination, .. } => {
833 if let Some(ref mut tgt) = *destination {
834 *tgt = self.update_target(*tgt);
840 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
841 *scope = self.scope_map[*scope];