1 //! Inlining pass for MIR functions
2 use crate::deref_separator::deref_finder;
3 use rustc_attr::InlineAttr;
4 use rustc_index::bit_set::BitSet;
5 use rustc_index::vec::Idx;
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::traits::ObligationCause;
10 use rustc_middle::ty::subst::Subst;
11 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
12 use rustc_span::{hygiene::ExpnKind, ExpnData, LocalExpnId, Span};
13 use rustc_target::spec::abi::Abi;
15 use super::simplify::{remove_dead_blocks, CfgSimplifier};
18 use std::ops::{Range, RangeFrom};
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> {
33 callee: Instance<'tcx>,
34 fn_sig: ty::PolyFnSig<'tcx>,
36 target: Option<BasicBlock>,
37 source_info: SourceInfo,
40 impl<'tcx> MirPass<'tcx> for Inline {
41 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
42 if let Some(enabled) = sess.opts.debugging_opts.inline_mir {
46 sess.opts.mir_opt_level() >= 3
49 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
50 let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
51 let _guard = span.enter();
52 if inline(tcx, body) {
53 debug!("running simplify cfg on {:?}", body.source);
54 CfgSimplifier::new(body).simplify();
55 remove_dead_blocks(tcx, body);
56 deref_finder(tcx, body);
61 fn inline<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
62 let def_id = body.source.def_id().expect_local();
64 // Only do inlining into fn bodies.
65 if !tcx.hir().body_owner_kind(def_id).is_fn_or_closure() {
68 if body.source.promoted.is_some() {
71 // Avoid inlining into generators, since their `optimized_mir` is used for layout computation,
72 // which can create a cycle, even when no attempt is made to inline the function in the other
74 if body.generator.is_some() {
78 let param_env = tcx.param_env_reveal_all_normalized(def_id);
79 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
80 let param_env = rustc_trait_selection::traits::normalize_param_env_or_error(
84 ObligationCause::misc(body.span, hir_id),
87 let mut this = Inliner {
90 codegen_fn_attrs: tcx.codegen_fn_attrs(def_id),
94 let blocks = BasicBlock::new(0)..body.basic_blocks().next_index();
95 this.process_blocks(body, blocks);
99 struct Inliner<'tcx> {
101 param_env: ParamEnv<'tcx>,
102 /// Caller codegen attributes.
103 codegen_fn_attrs: &'tcx CodegenFnAttrs,
104 /// Stack of inlined Instances.
105 history: Vec<ty::Instance<'tcx>>,
106 /// Indicates that the caller body has been modified.
110 impl<'tcx> Inliner<'tcx> {
111 fn process_blocks(&mut self, caller_body: &mut Body<'tcx>, blocks: Range<BasicBlock>) {
113 let bb_data = &caller_body[bb];
114 if bb_data.is_cleanup {
118 let Some(callsite) = self.resolve_callsite(caller_body, bb, bb_data) else {
122 let span = trace_span!("process_blocks", %callsite.callee, ?bb);
123 let _guard = span.enter();
125 match self.try_inlining(caller_body, &callsite) {
127 debug!("not-inlined {} [{}]", callsite.callee, reason);
131 debug!("inlined {}", callsite.callee);
133 self.history.push(callsite.callee);
134 self.process_blocks(caller_body, new_blocks);
141 /// Attempts to inline a callsite into the caller body. When successful returns basic blocks
142 /// containing the inlined body. Otherwise returns an error describing why inlining didn't take
146 caller_body: &mut Body<'tcx>,
147 callsite: &CallSite<'tcx>,
148 ) -> Result<std::ops::Range<BasicBlock>, &'static str> {
149 let callee_attrs = self.tcx.codegen_fn_attrs(callsite.callee.def_id());
150 self.check_codegen_attributes(callsite, callee_attrs)?;
151 self.check_mir_is_available(caller_body, &callsite.callee)?;
152 let callee_body = self.tcx.instance_mir(callsite.callee.def);
153 self.check_mir_body(callsite, callee_body, callee_attrs)?;
155 if !self.tcx.consider_optimizing(|| {
156 format!("Inline {:?} into {:?}", callsite.callee, caller_body.source)
158 return Err("optimization fuel exhausted");
161 let Ok(callee_body) = callsite.callee.try_subst_mir_and_normalize_erasing_regions(
166 return Err("failed to normalize callee body");
169 let old_blocks = caller_body.basic_blocks().next_index();
170 self.inline_call(caller_body, &callsite, callee_body);
171 let new_blocks = old_blocks..caller_body.basic_blocks().next_index();
176 fn check_mir_is_available(
178 caller_body: &Body<'tcx>,
179 callee: &Instance<'tcx>,
180 ) -> Result<(), &'static str> {
181 let caller_def_id = caller_body.source.def_id();
182 let callee_def_id = callee.def_id();
183 if callee_def_id == caller_def_id {
184 return Err("self-recursion");
188 InstanceDef::Item(_) => {
189 // If there is no MIR available (either because it was not in metadata or
190 // because it has no MIR because it's an extern function), then the inliner
191 // won't cause cycles on this.
192 if !self.tcx.is_mir_available(callee_def_id) {
193 return Err("item MIR unavailable");
196 // These have no own callable MIR.
197 InstanceDef::Intrinsic(_) | InstanceDef::Virtual(..) => {
198 return Err("instance without MIR (intrinsic / virtual)");
200 // This cannot result in an immediate cycle since the callee MIR is a shim, which does
201 // not get any optimizations run on it. Any subsequent inlining may cause cycles, but we
202 // do not need to catch this here, we can wait until the inliner decides to continue
203 // inlining a second time.
204 InstanceDef::VtableShim(_)
205 | InstanceDef::ReifyShim(_)
206 | InstanceDef::FnPtrShim(..)
207 | InstanceDef::ClosureOnceShim { .. }
208 | InstanceDef::DropGlue(..)
209 | InstanceDef::CloneShim(..) => return Ok(()),
212 if self.tcx.is_constructor(callee_def_id) {
213 trace!("constructors always have MIR");
214 // Constructor functions cannot cause a query cycle.
218 if callee_def_id.is_local() {
219 // Avoid a cycle here by only using `instance_mir` only if we have
220 // a lower `DefPathHash` than the callee. This ensures that the callee will
221 // not inline us. This trick even works with incremental compilation,
222 // since `DefPathHash` is stable.
223 if self.tcx.def_path_hash(caller_def_id).local_hash()
224 < self.tcx.def_path_hash(callee_def_id).local_hash()
229 // If we know for sure that the function we're calling will itself try to
230 // call us, then we avoid inlining that function.
231 if self.tcx.mir_callgraph_reachable((*callee, caller_def_id.expect_local())) {
232 return Err("caller might be reachable from callee (query cycle avoidance)");
237 // This cannot result in an immediate cycle since the callee MIR is from another crate
238 // and is already optimized. Any subsequent inlining may cause cycles, but we do
239 // not need to catch this here, we can wait until the inliner decides to continue
240 // inlining a second time.
241 trace!("functions from other crates always have MIR");
248 caller_body: &Body<'tcx>,
250 bb_data: &BasicBlockData<'tcx>,
251 ) -> Option<CallSite<'tcx>> {
252 // Only consider direct calls to functions
253 let terminator = bb_data.terminator();
254 if let TerminatorKind::Call { ref func, target, .. } = terminator.kind {
255 let func_ty = func.ty(caller_body, self.tcx);
256 if let ty::FnDef(def_id, substs) = *func_ty.kind() {
257 // To resolve an instance its substs have to be fully normalized.
258 let substs = self.tcx.try_normalize_erasing_regions(self.param_env, substs).ok()?;
260 Instance::resolve(self.tcx, self.param_env, def_id, substs).ok().flatten()?;
262 if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def {
266 let fn_sig = self.tcx.bound_fn_sig(def_id).subst(self.tcx, substs);
268 return Some(CallSite {
273 source_info: terminator.source_info,
281 /// Returns an error if inlining is not possible based on codegen attributes alone. A success
282 /// indicates that inlining decision should be based on other criteria.
283 fn check_codegen_attributes(
285 callsite: &CallSite<'tcx>,
286 callee_attrs: &CodegenFnAttrs,
287 ) -> Result<(), &'static str> {
288 if let InlineAttr::Never = callee_attrs.inline {
289 return Err("never inline hint");
292 // Only inline local functions if they would be eligible for cross-crate
293 // inlining. This is to ensure that the final crate doesn't have MIR that
294 // reference unexported symbols
295 if callsite.callee.def_id().is_local() {
296 let is_generic = callsite.callee.substs.non_erasable_generics().next().is_some();
297 if !is_generic && !callee_attrs.requests_inline() {
298 return Err("not exported");
302 if callsite.fn_sig.c_variadic() {
303 return Err("C variadic");
306 if callee_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
310 if callee_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
314 if callee_attrs.no_sanitize != self.codegen_fn_attrs.no_sanitize {
315 return Err("incompatible sanitizer set");
318 if callee_attrs.instruction_set != self.codegen_fn_attrs.instruction_set {
319 return Err("incompatible instruction set");
322 for feature in &callee_attrs.target_features {
323 if !self.codegen_fn_attrs.target_features.contains(feature) {
324 return Err("incompatible target feature");
331 /// Returns inlining decision that is based on the examination of callee MIR body.
332 /// Assumes that codegen attributes have been checked for compatibility already.
333 #[instrument(level = "debug", skip(self, callee_body))]
336 callsite: &CallSite<'tcx>,
337 callee_body: &Body<'tcx>,
338 callee_attrs: &CodegenFnAttrs,
339 ) -> Result<(), &'static str> {
342 let mut threshold = if callee_attrs.requests_inline() {
343 self.tcx.sess.opts.debugging_opts.inline_mir_hint_threshold.unwrap_or(100)
345 self.tcx.sess.opts.debugging_opts.inline_mir_threshold.unwrap_or(50)
348 // Give a bonus functions with a small number of blocks,
349 // We normally have two or three blocks for even
350 // very small functions.
351 if callee_body.basic_blocks().len() <= 3 {
352 threshold += threshold / 4;
354 debug!(" final inline threshold = {}", threshold);
356 // FIXME: Give a bonus to functions with only a single caller
357 let mut first_block = true;
360 // Traverse the MIR manually so we can account for the effects of
361 // inlining on the CFG.
362 let mut work_list = vec![START_BLOCK];
363 let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
364 while let Some(bb) = work_list.pop() {
365 if !visited.insert(bb.index()) {
368 let blk = &callee_body.basic_blocks()[bb];
370 for stmt in &blk.statements {
371 // Don't count StorageLive/StorageDead in the inlining cost.
373 StatementKind::StorageLive(_)
374 | StatementKind::StorageDead(_)
375 | StatementKind::Deinit(_)
376 | StatementKind::Nop => {}
377 _ => cost += INSTR_COST,
380 let term = blk.terminator();
381 let mut is_drop = false;
383 TerminatorKind::Drop { ref place, target, unwind }
384 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
386 work_list.push(target);
387 // If the place doesn't actually need dropping, treat it like
389 let ty = callsite.callee.subst_mir(self.tcx, &place.ty(callee_body, tcx).ty);
390 if ty.needs_drop(tcx, self.param_env) {
391 cost += CALL_PENALTY;
392 if let Some(unwind) = unwind {
393 cost += LANDINGPAD_PENALTY;
394 work_list.push(unwind);
401 TerminatorKind::Unreachable | TerminatorKind::Call { target: None, .. }
404 // If the function always diverges, don't inline
405 // unless the cost is zero
409 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
410 if let ty::FnDef(def_id, substs) =
411 *callsite.callee.subst_mir(self.tcx, &f.literal.ty()).kind()
414 self.tcx.try_normalize_erasing_regions(self.param_env, substs)
416 if let Ok(Some(instance)) =
417 Instance::resolve(self.tcx, self.param_env, def_id, substs)
419 if callsite.callee.def_id() == instance.def_id() {
420 return Err("self-recursion");
421 } else if self.history.contains(&instance) {
422 return Err("already inlined");
426 // Don't give intrinsics the extra penalty for calls
427 if tcx.is_intrinsic(def_id) {
430 cost += CALL_PENALTY;
433 cost += CALL_PENALTY;
435 if cleanup.is_some() {
436 cost += LANDINGPAD_PENALTY;
439 TerminatorKind::Assert { cleanup, .. } => {
440 cost += CALL_PENALTY;
442 if cleanup.is_some() {
443 cost += LANDINGPAD_PENALTY;
446 TerminatorKind::Resume => cost += RESUME_PENALTY,
447 TerminatorKind::InlineAsm { cleanup, .. } => {
450 if cleanup.is_some() {
451 cost += LANDINGPAD_PENALTY;
454 _ => cost += INSTR_COST,
458 for succ in term.successors() {
459 work_list.push(succ);
466 // Count up the cost of local variables and temps, if we know the size
467 // use that, otherwise we use a moderately-large dummy cost.
469 let ptr_size = tcx.data_layout.pointer_size.bytes();
471 for v in callee_body.vars_and_temps_iter() {
472 let ty = callsite.callee.subst_mir(self.tcx, &callee_body.local_decls[v].ty);
473 // Cost of the var is the size in machine-words, if we know
475 if let Some(size) = type_size_of(tcx, self.param_env, ty) {
476 cost += ((size + ptr_size - 1) / ptr_size) as usize;
478 cost += UNKNOWN_SIZE_COST;
482 if let InlineAttr::Always = callee_attrs.inline {
483 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
486 if cost <= threshold {
487 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
490 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
491 Err("cost above threshold")
498 caller_body: &mut Body<'tcx>,
499 callsite: &CallSite<'tcx>,
500 mut callee_body: Body<'tcx>,
502 let terminator = caller_body[callsite.block].terminator.take().unwrap();
503 match terminator.kind {
504 TerminatorKind::Call { args, destination, cleanup, .. } => {
505 // If the call is something like `a[*i] = f(i)`, where
506 // `i : &mut usize`, then just duplicating the `a[*i]`
507 // Place could result in two different locations if `f`
508 // writes to `i`. To prevent this we need to create a temporary
509 // borrow of the place and pass the destination as `*temp` instead.
510 fn dest_needs_borrow(place: Place<'_>) -> bool {
511 for elem in place.projection.iter() {
513 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
521 let dest = if dest_needs_borrow(destination) {
522 trace!("creating temp for return destination");
523 let dest = Rvalue::Ref(
524 self.tcx.lifetimes.re_erased,
525 BorrowKind::Mut { allow_two_phase_borrow: false },
528 let dest_ty = dest.ty(caller_body, self.tcx);
529 let temp = Place::from(self.new_call_temp(caller_body, &callsite, dest_ty));
530 caller_body[callsite.block].statements.push(Statement {
531 source_info: callsite.source_info,
532 kind: StatementKind::Assign(Box::new((temp, dest))),
534 self.tcx.mk_place_deref(temp)
539 // Copy the arguments if needed.
540 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, &callee_body);
542 let mut expn_data = ExpnData::default(
544 callsite.source_info.span,
545 self.tcx.sess.edition(),
549 expn_data.def_site = callee_body.span;
551 LocalExpnId::fresh(expn_data, self.tcx.create_stable_hashing_context());
552 let mut integrator = Integrator {
554 new_locals: Local::new(caller_body.local_decls.len())..,
555 new_scopes: SourceScope::new(caller_body.source_scopes.len())..,
556 new_blocks: BasicBlock::new(caller_body.basic_blocks().len())..,
558 callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
560 cleanup_block: cleanup,
561 in_cleanup_block: false,
564 always_live_locals: BitSet::new_filled(callee_body.local_decls.len()),
567 // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
568 // (or existing ones, in a few special cases) in the caller.
569 integrator.visit_body(&mut callee_body);
571 // If there are any locals without storage markers, give them storage only for the
572 // duration of the call.
573 for local in callee_body.vars_and_temps_iter() {
574 if integrator.always_live_locals.contains(local) {
575 let new_local = integrator.map_local(local);
576 caller_body[callsite.block].statements.push(Statement {
577 source_info: callsite.source_info,
578 kind: StatementKind::StorageLive(new_local),
582 if let Some(block) = callsite.target {
583 // To avoid repeated O(n) insert, push any new statements to the end and rotate
586 for local in callee_body.vars_and_temps_iter().rev() {
587 if integrator.always_live_locals.contains(local) {
588 let new_local = integrator.map_local(local);
589 caller_body[block].statements.push(Statement {
590 source_info: callsite.source_info,
591 kind: StatementKind::StorageDead(new_local),
596 caller_body[block].statements.rotate_right(n);
599 // Insert all of the (mapped) parts of the callee body into the caller.
600 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
601 caller_body.source_scopes.extend(&mut callee_body.source_scopes.drain(..));
602 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
603 caller_body.basic_blocks_mut().extend(callee_body.basic_blocks_mut().drain(..));
605 caller_body[callsite.block].terminator = Some(Terminator {
606 source_info: callsite.source_info,
607 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
610 // Copy only unevaluated constants from the callee_body into the caller_body.
611 // Although we are only pushing `ConstKind::Unevaluated` consts to
612 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
613 // because we are calling `subst_and_normalize_erasing_regions`.
614 caller_body.required_consts.extend(
615 callee_body.required_consts.iter().copied().filter(|&ct| {
616 match ct.literal.const_for_ty() {
617 Some(ct) => matches!(ct.kind(), ConstKind::Unevaluated(_)),
623 kind => bug!("unexpected terminator kind {:?}", kind),
629 args: Vec<Operand<'tcx>>,
630 callsite: &CallSite<'tcx>,
631 caller_body: &mut Body<'tcx>,
632 callee_body: &Body<'tcx>,
636 // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
637 // The caller provides the arguments wrapped up in a tuple:
639 // tuple_tmp = (a, b, c)
640 // Fn::call(closure_ref, tuple_tmp)
642 // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
643 // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
644 // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
647 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
649 // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
650 // if we "spill" that into *another* temporary, so that we can map the argument
651 // variable in the callee MIR directly to an argument variable on our side.
652 // So we introduce temporaries like:
654 // tmp0 = tuple_tmp.0
655 // tmp1 = tuple_tmp.1
656 // tmp2 = tuple_tmp.2
658 // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
659 if callsite.fn_sig.abi() == Abi::RustCall && callee_body.spread_arg.is_none() {
660 let mut args = args.into_iter();
661 let self_ = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
662 let tuple = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
663 assert!(args.next().is_none());
665 let tuple = Place::from(tuple);
666 let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
667 bug!("Closure arguments are not passed as a tuple");
670 // The `closure_ref` in our example above.
671 let closure_ref_arg = iter::once(self_);
673 // The `tmp0`, `tmp1`, and `tmp2` in our example above.
674 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
675 // This is e.g., `tuple_tmp.0` in our example above.
676 let tuple_field = Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty));
678 // Spill to a local to make e.g., `tmp0`.
679 self.create_temp_if_necessary(tuple_field, callsite, caller_body)
682 closure_ref_arg.chain(tuple_tmp_args).collect()
685 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body))
690 /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
691 /// temporary `T` and an instruction `T = arg`, and returns `T`.
692 fn create_temp_if_necessary(
695 callsite: &CallSite<'tcx>,
696 caller_body: &mut Body<'tcx>,
698 // Reuse the operand if it is a moved temporary.
699 if let Operand::Move(place) = &arg
700 && let Some(local) = place.as_local()
701 && caller_body.local_kind(local) == LocalKind::Temp
706 // Otherwise, create a temporary for the argument.
707 trace!("creating temp for argument {:?}", arg);
708 let arg_ty = arg.ty(caller_body, self.tcx);
709 let local = self.new_call_temp(caller_body, callsite, arg_ty);
710 caller_body[callsite.block].statements.push(Statement {
711 source_info: callsite.source_info,
712 kind: StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg)))),
717 /// Introduces a new temporary into the caller body that is live for the duration of the call.
720 caller_body: &mut Body<'tcx>,
721 callsite: &CallSite<'tcx>,
724 let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
726 caller_body[callsite.block].statements.push(Statement {
727 source_info: callsite.source_info,
728 kind: StatementKind::StorageLive(local),
731 if let Some(block) = callsite.target {
732 caller_body[block].statements.insert(
735 source_info: callsite.source_info,
736 kind: StatementKind::StorageDead(local),
745 fn type_size_of<'tcx>(
747 param_env: ty::ParamEnv<'tcx>,
750 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
756 * Integrates blocks from the callee function into the calling function.
757 * Updates block indices, references to locals and other control flow
760 struct Integrator<'a, 'tcx> {
762 new_locals: RangeFrom<Local>,
763 new_scopes: RangeFrom<SourceScope>,
764 new_blocks: RangeFrom<BasicBlock>,
765 destination: Place<'tcx>,
766 callsite_scope: SourceScopeData<'tcx>,
767 callsite: &'a CallSite<'tcx>,
768 cleanup_block: Option<BasicBlock>,
769 in_cleanup_block: bool,
771 expn_data: LocalExpnId,
772 always_live_locals: BitSet<Local>,
775 impl Integrator<'_, '_> {
776 fn map_local(&self, local: Local) -> Local {
777 let new = if local == RETURN_PLACE {
778 self.destination.local
780 let idx = local.index() - 1;
781 if idx < self.args.len() {
784 Local::new(self.new_locals.start.index() + (idx - self.args.len()))
787 trace!("mapping local `{:?}` to `{:?}`", local, new);
791 fn map_scope(&self, scope: SourceScope) -> SourceScope {
792 let new = SourceScope::new(self.new_scopes.start.index() + scope.index());
793 trace!("mapping scope `{:?}` to `{:?}`", scope, new);
797 fn map_block(&self, block: BasicBlock) -> BasicBlock {
798 let new = BasicBlock::new(self.new_blocks.start.index() + block.index());
799 trace!("mapping block `{:?}` to `{:?}`", block, new);
804 impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
805 fn tcx(&self) -> TyCtxt<'tcx> {
809 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
810 *local = self.map_local(*local);
813 fn visit_source_scope_data(&mut self, scope_data: &mut SourceScopeData<'tcx>) {
814 self.super_source_scope_data(scope_data);
815 if scope_data.parent_scope.is_none() {
816 // Attach the outermost callee scope as a child of the callsite
817 // scope, via the `parent_scope` and `inlined_parent_scope` chains.
818 scope_data.parent_scope = Some(self.callsite.source_info.scope);
819 assert_eq!(scope_data.inlined_parent_scope, None);
820 scope_data.inlined_parent_scope = if self.callsite_scope.inlined.is_some() {
821 Some(self.callsite.source_info.scope)
823 self.callsite_scope.inlined_parent_scope
826 // Mark the outermost callee scope as an inlined one.
827 assert_eq!(scope_data.inlined, None);
828 scope_data.inlined = Some((self.callsite.callee, self.callsite.source_info.span));
829 } else if scope_data.inlined_parent_scope.is_none() {
830 // Make it easy to find the scope with `inlined` set above.
831 scope_data.inlined_parent_scope = Some(self.map_scope(OUTERMOST_SOURCE_SCOPE));
835 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
836 *scope = self.map_scope(*scope);
839 fn visit_span(&mut self, span: &mut Span) {
840 // Make sure that all spans track the fact that they were inlined.
841 *span = span.fresh_expansion(self.expn_data);
844 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
845 for elem in place.projection {
846 // FIXME: Make sure that return place is not used in an indexing projection, since it
847 // won't be rebased as it is supposed to be.
848 assert_ne!(ProjectionElem::Index(RETURN_PLACE), elem);
851 // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
852 let dest_proj_len = self.destination.projection.len();
853 if place.local == RETURN_PLACE && dest_proj_len > 0 {
854 let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
855 projs.extend(self.destination.projection);
856 projs.extend(place.projection);
858 place.projection = self.tcx.intern_place_elems(&*projs);
860 // Handles integrating any locals that occur in the base
862 self.super_place(place, context, location)
865 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
866 self.in_cleanup_block = data.is_cleanup;
867 self.super_basic_block_data(block, data);
868 self.in_cleanup_block = false;
871 fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
872 self.super_retag(kind, place, loc);
874 // We have to patch all inlined retags to be aware that they are no longer
875 // happening on function entry.
876 if *kind == RetagKind::FnEntry {
877 *kind = RetagKind::Default;
881 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
882 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
885 self.always_live_locals.remove(local);
887 self.super_statement(statement, location);
890 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
891 // Don't try to modify the implicit `_0` access on return (`return` terminators are
892 // replaced down below anyways).
893 if !matches!(terminator.kind, TerminatorKind::Return) {
894 self.super_terminator(terminator, loc);
897 match terminator.kind {
898 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
899 TerminatorKind::Goto { ref mut target } => {
900 *target = self.map_block(*target);
902 TerminatorKind::SwitchInt { ref mut targets, .. } => {
903 for tgt in targets.all_targets_mut() {
904 *tgt = self.map_block(*tgt);
907 TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
908 | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
909 *target = self.map_block(*target);
910 if let Some(tgt) = *unwind {
911 *unwind = Some(self.map_block(tgt));
912 } else if !self.in_cleanup_block {
913 // Unless this drop is in a cleanup block, add an unwind edge to
914 // the original call's cleanup block
915 *unwind = self.cleanup_block;
918 TerminatorKind::Call { ref mut target, ref mut cleanup, .. } => {
919 if let Some(ref mut tgt) = *target {
920 *tgt = self.map_block(*tgt);
922 if let Some(tgt) = *cleanup {
923 *cleanup = Some(self.map_block(tgt));
924 } else if !self.in_cleanup_block {
925 // Unless this call is in a cleanup block, add an unwind edge to
926 // the original call's cleanup block
927 *cleanup = self.cleanup_block;
930 TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
931 *target = self.map_block(*target);
932 if let Some(tgt) = *cleanup {
933 *cleanup = Some(self.map_block(tgt));
934 } else if !self.in_cleanup_block {
935 // Unless this assert is in a cleanup block, add an unwind edge to
936 // the original call's cleanup block
937 *cleanup = self.cleanup_block;
940 TerminatorKind::Return => {
941 terminator.kind = if let Some(tgt) = self.callsite.target {
942 TerminatorKind::Goto { target: tgt }
944 TerminatorKind::Unreachable
947 TerminatorKind::Resume => {
948 if let Some(tgt) = self.cleanup_block {
949 terminator.kind = TerminatorKind::Goto { target: tgt }
952 TerminatorKind::Abort => {}
953 TerminatorKind::Unreachable => {}
954 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
955 *real_target = self.map_block(*real_target);
956 *imaginary_target = self.map_block(*imaginary_target);
958 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
959 // see the ordering of passes in the optimized_mir query.
961 bug!("False unwinds should have been removed before inlining")
963 TerminatorKind::InlineAsm { ref mut destination, ref mut cleanup, .. } => {
964 if let Some(ref mut tgt) = *destination {
965 *tgt = self.map_block(*tgt);
966 } else if !self.in_cleanup_block {
967 // Unless this inline asm is in a cleanup block, add an unwind edge to
968 // the original call's cleanup block
969 *cleanup = self.cleanup_block;