]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/inline.rs
Rollup merge of #77918 - wcampbell0x2a:cleanup-network-tests, r=m-ou-se
[rust.git] / compiler / rustc_mir / src / transform / inline.rs
1 //! Inlining pass for MIR functions
2
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;
13
14 use super::simplify::{remove_dead_blocks, CfgSimplifier};
15 use crate::transform::MirPass;
16 use std::collections::VecDeque;
17 use std::iter;
18
19 const DEFAULT_THRESHOLD: usize = 50;
20 const HINT_THRESHOLD: usize = 100;
21
22 const INSTR_COST: usize = 5;
23 const CALL_PENALTY: usize = 25;
24 const LANDINGPAD_PENALTY: usize = 50;
25 const RESUME_PENALTY: usize = 45;
26
27 const UNKNOWN_SIZE_COST: usize = 10;
28
29 pub struct Inline;
30
31 #[derive(Copy, Clone, Debug)]
32 struct CallSite<'tcx> {
33     callee: DefId,
34     substs: SubstsRef<'tcx>,
35     bb: BasicBlock,
36     location: SourceInfo,
37 }
38
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-
45                 // based function.
46                 debug!("function inlining is disabled when compiling with `instrument_coverage`");
47             } else {
48                 Inliner {
49                     tcx,
50                     param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
51                     codegen_fn_attrs: tcx.codegen_fn_attrs(body.source.def_id()),
52                 }
53                 .run_pass(body);
54             }
55         }
56     }
57 }
58
59 struct Inliner<'tcx> {
60     tcx: TyCtxt<'tcx>,
61     param_env: ParamEnv<'tcx>,
62     codegen_fn_attrs: &'tcx CodegenFnAttrs,
63 }
64
65 impl Inliner<'tcx> {
66     fn run_pass(&self, caller_body: &mut Body<'tcx>) {
67         // Keep a queue of callsites to try inlining on. We take
68         // advantage of the fact that queries detect cycles here to
69         // allow us to try and fetch the fully optimized MIR of a
70         // call; if it succeeds, we can inline it and we know that
71         // they do not call us.  Otherwise, we just don't try to
72         // inline.
73         //
74         // We use a queue so that we inline "broadly" before we inline
75         // in depth. It is unclear if this is the best heuristic,
76         // really, but that's true of all the heuristics in this
77         // file. =)
78
79         let mut callsites = VecDeque::new();
80
81         let def_id = caller_body.source.def_id();
82
83         // Only do inlining into fn bodies.
84         let self_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
85         if self.tcx.hir().body_owner_kind(self_hir_id).is_fn_or_closure()
86             && caller_body.source.promoted.is_none()
87         {
88             for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated() {
89                 if let Some(callsite) = self.get_valid_function_call(bb, bb_data, caller_body) {
90                     callsites.push_back(callsite);
91                 }
92             }
93         } else {
94             return;
95         }
96
97         let mut local_change;
98         let mut changed = false;
99
100         loop {
101             local_change = false;
102             while let Some(callsite) = callsites.pop_front() {
103                 debug!("checking whether to inline callsite {:?}", callsite);
104                 if !self.tcx.is_mir_available(callsite.callee) {
105                     debug!("checking whether to inline callsite {:?} - MIR unavailable", callsite);
106                     continue;
107                 }
108
109                 let callee_body = if let Some(callee_def_id) = callsite.callee.as_local() {
110                     let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
111                     // Avoid a cycle here by only using `optimized_mir` only if we have
112                     // a lower `HirId` than the callee. This ensures that the callee will
113                     // not inline us. This trick only works without incremental compilation.
114                     // So don't do it if that is enabled. Also avoid inlining into generators,
115                     // since their `optimized_mir` is used for layout computation, which can
116                     // create a cycle, even when no attempt is made to inline the function
117                     // in the other direction.
118                     if !self.tcx.dep_graph.is_fully_enabled()
119                         && self_hir_id < callee_hir_id
120                         && caller_body.generator_kind.is_none()
121                     {
122                         self.tcx.optimized_mir(callsite.callee)
123                     } else {
124                         continue;
125                     }
126                 } else {
127                     // This cannot result in a cycle since the callee MIR is from another crate
128                     // and is already optimized.
129                     self.tcx.optimized_mir(callsite.callee)
130                 };
131
132                 let callee_body = if self.consider_optimizing(callsite, callee_body) {
133                     self.tcx.subst_and_normalize_erasing_regions(
134                         &callsite.substs,
135                         self.param_env,
136                         callee_body,
137                     )
138                 } else {
139                     continue;
140                 };
141
142                 // Copy only unevaluated constants from the callee_body into the caller_body.
143                 // Although we are only pushing `ConstKind::Unevaluated` consts to
144                 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
145                 // because we are calling `subst_and_normalize_erasing_regions`.
146                 caller_body.required_consts.extend(
147                     callee_body.required_consts.iter().copied().filter(|&constant| {
148                         matches!(constant.literal.val, ConstKind::Unevaluated(_, _, _))
149                     }),
150                 );
151
152                 let start = caller_body.basic_blocks().len();
153                 debug!("attempting to inline callsite {:?} - body={:?}", callsite, callee_body);
154                 if !self.inline_call(callsite, caller_body, callee_body) {
155                     debug!("attempting to inline callsite {:?} - failure", callsite);
156                     continue;
157                 }
158                 debug!("attempting to inline callsite {:?} - success", callsite);
159
160                 // Add callsites from inlined function
161                 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated().skip(start) {
162                     if let Some(new_callsite) =
163                         self.get_valid_function_call(bb, bb_data, caller_body)
164                     {
165                         // Don't inline the same function multiple times.
166                         if callsite.callee != new_callsite.callee {
167                             callsites.push_back(new_callsite);
168                         }
169                     }
170                 }
171
172                 local_change = true;
173                 changed = true;
174             }
175
176             if !local_change {
177                 break;
178             }
179         }
180
181         // Simplify if we inlined anything.
182         if changed {
183             debug!("running simplify cfg on {:?}", caller_body.source);
184             CfgSimplifier::new(caller_body).simplify();
185             remove_dead_blocks(caller_body);
186         }
187     }
188
189     fn get_valid_function_call(
190         &self,
191         bb: BasicBlock,
192         bb_data: &BasicBlockData<'tcx>,
193         caller_body: &Body<'tcx>,
194     ) -> Option<CallSite<'tcx>> {
195         // Don't inline calls that are in cleanup blocks.
196         if bb_data.is_cleanup {
197             return None;
198         }
199
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() {
204                 // To resolve an instance its substs have to be fully normalized, so
205                 // we do this here.
206                 let normalized_substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
207                 let instance =
208                     Instance::resolve(self.tcx, self.param_env, callee_def_id, normalized_substs)
209                         .ok()
210                         .flatten()?;
211
212                 if let InstanceDef::Virtual(..) = instance.def {
213                     return None;
214                 }
215
216                 return Some(CallSite {
217                     callee: instance.def_id(),
218                     substs: instance.substs,
219                     bb,
220                     location: terminator.source_info,
221                 });
222             }
223         }
224
225         None
226     }
227
228     fn consider_optimizing(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
229         debug!("consider_optimizing({:?})", callsite);
230         self.should_inline(callsite, callee_body)
231             && self.tcx.consider_optimizing(|| {
232                 format!("Inline {:?} into {:?}", callee_body.span, callsite)
233             })
234     }
235
236     fn should_inline(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
237         debug!("should_inline({:?})", callsite);
238         let tcx = self.tcx;
239
240         // Cannot inline generators which haven't been transformed yet
241         if callee_body.yield_ty.is_some() {
242             debug!("    yield ty present - not inlining");
243             return false;
244         }
245
246         let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee);
247
248         if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::TRACK_CALLER) {
249             debug!("`#[track_caller]` present - not inlining");
250             return false;
251         }
252
253         let self_features = &self.codegen_fn_attrs.target_features;
254         let callee_features = &codegen_fn_attrs.target_features;
255         if callee_features.iter().any(|feature| !self_features.contains(feature)) {
256             debug!("`callee has extra target features - not inlining");
257             return false;
258         }
259
260         let self_no_sanitize =
261             self.codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
262         let callee_no_sanitize =
263             codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
264         if self_no_sanitize != callee_no_sanitize {
265             debug!("`callee has incompatible no_sanitize attribute - not inlining");
266             return false;
267         }
268
269         let hinted = match codegen_fn_attrs.inline {
270             // Just treat inline(always) as a hint for now,
271             // there are cases that prevent inlining that we
272             // need to check for first.
273             attr::InlineAttr::Always => true,
274             attr::InlineAttr::Never => {
275                 debug!("`#[inline(never)]` present - not inlining");
276                 return false;
277             }
278             attr::InlineAttr::Hint => true,
279             attr::InlineAttr::None => false,
280         };
281
282         // Only inline local functions if they would be eligible for cross-crate
283         // inlining. This is to ensure that the final crate doesn't have MIR that
284         // reference unexported symbols
285         if callsite.callee.is_local() {
286             if callsite.substs.non_erasable_generics().count() == 0 && !hinted {
287                 debug!("    callee is an exported function - not inlining");
288                 return false;
289             }
290         }
291
292         let mut threshold = if hinted { HINT_THRESHOLD } else { DEFAULT_THRESHOLD };
293
294         // Significantly lower the threshold for inlining cold functions
295         if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
296             threshold /= 5;
297         }
298
299         // Give a bonus functions with a small number of blocks,
300         // We normally have two or three blocks for even
301         // very small functions.
302         if callee_body.basic_blocks().len() <= 3 {
303             threshold += threshold / 4;
304         }
305         debug!("    final inline threshold = {}", threshold);
306
307         // FIXME: Give a bonus to functions with only a single caller
308         let mut first_block = true;
309         let mut cost = 0;
310
311         // Traverse the MIR manually so we can account for the effects of
312         // inlining on the CFG.
313         let mut work_list = vec![START_BLOCK];
314         let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
315         while let Some(bb) = work_list.pop() {
316             if !visited.insert(bb.index()) {
317                 continue;
318             }
319             let blk = &callee_body.basic_blocks()[bb];
320
321             for stmt in &blk.statements {
322                 // Don't count StorageLive/StorageDead in the inlining cost.
323                 match stmt.kind {
324                     StatementKind::StorageLive(_)
325                     | StatementKind::StorageDead(_)
326                     | StatementKind::Nop => {}
327                     _ => cost += INSTR_COST,
328                 }
329             }
330             let term = blk.terminator();
331             let mut is_drop = false;
332             match term.kind {
333                 TerminatorKind::Drop { ref place, target, unwind }
334                 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
335                     is_drop = true;
336                     work_list.push(target);
337                     // If the place doesn't actually need dropping, treat it like
338                     // a regular goto.
339                     let ty = place.ty(callee_body, tcx).subst(tcx, callsite.substs).ty;
340                     if ty.needs_drop(tcx, self.param_env) {
341                         cost += CALL_PENALTY;
342                         if let Some(unwind) = unwind {
343                             cost += LANDINGPAD_PENALTY;
344                             work_list.push(unwind);
345                         }
346                     } else {
347                         cost += INSTR_COST;
348                     }
349                 }
350
351                 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
352                     if first_block =>
353                 {
354                     // If the function always diverges, don't inline
355                     // unless the cost is zero
356                     threshold = 0;
357                 }
358
359                 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
360                     if let ty::FnDef(def_id, _) = *f.literal.ty.kind() {
361                         // Don't give intrinsics the extra penalty for calls
362                         let f = tcx.fn_sig(def_id);
363                         if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
364                             cost += INSTR_COST;
365                         } else {
366                             cost += CALL_PENALTY;
367                         }
368                     } else {
369                         cost += CALL_PENALTY;
370                     }
371                     if cleanup.is_some() {
372                         cost += LANDINGPAD_PENALTY;
373                     }
374                 }
375                 TerminatorKind::Assert { cleanup, .. } => {
376                     cost += CALL_PENALTY;
377
378                     if cleanup.is_some() {
379                         cost += LANDINGPAD_PENALTY;
380                     }
381                 }
382                 TerminatorKind::Resume => cost += RESUME_PENALTY,
383                 _ => cost += INSTR_COST,
384             }
385
386             if !is_drop {
387                 for &succ in term.successors() {
388                     work_list.push(succ);
389                 }
390             }
391
392             first_block = false;
393         }
394
395         // Count up the cost of local variables and temps, if we know the size
396         // use that, otherwise we use a moderately-large dummy cost.
397
398         let ptr_size = tcx.data_layout.pointer_size.bytes();
399
400         for v in callee_body.vars_and_temps_iter() {
401             let v = &callee_body.local_decls[v];
402             let ty = v.ty.subst(tcx, callsite.substs);
403             // Cost of the var is the size in machine-words, if we know
404             // it.
405             if let Some(size) = type_size_of(tcx, self.param_env, ty) {
406                 cost += (size / ptr_size) as usize;
407             } else {
408                 cost += UNKNOWN_SIZE_COST;
409             }
410         }
411
412         if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
413             debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
414             true
415         } else {
416             if cost <= threshold {
417                 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
418                 true
419             } else {
420                 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
421                 false
422             }
423         }
424     }
425
426     fn inline_call(
427         &self,
428         callsite: CallSite<'tcx>,
429         caller_body: &mut Body<'tcx>,
430         mut callee_body: Body<'tcx>,
431     ) -> bool {
432         let terminator = caller_body[callsite.bb].terminator.take().unwrap();
433         match terminator.kind {
434             // FIXME: Handle inlining of diverging calls
435             TerminatorKind::Call { args, destination: Some(destination), cleanup, .. } => {
436                 debug!("inlined {:?} into {:?}", callsite.callee, caller_body.source);
437
438                 let mut local_map = IndexVec::with_capacity(callee_body.local_decls.len());
439                 let mut scope_map = IndexVec::with_capacity(callee_body.source_scopes.len());
440
441                 for mut scope in callee_body.source_scopes.iter().cloned() {
442                     if scope.parent_scope.is_none() {
443                         scope.parent_scope = Some(callsite.location.scope);
444                         // FIXME(eddyb) is this really needed?
445                         // (also note that it's always overwritten below)
446                         scope.span = callee_body.span;
447                     }
448
449                     // FIXME(eddyb) this doesn't seem right at all.
450                     // The inlined source scopes should probably be annotated as
451                     // such, but also contain all of the original information.
452                     scope.span = callsite.location.span;
453
454                     let idx = caller_body.source_scopes.push(scope);
455                     scope_map.push(idx);
456                 }
457
458                 for loc in callee_body.vars_and_temps_iter() {
459                     let mut local = callee_body.local_decls[loc].clone();
460
461                     local.source_info.scope = scope_map[local.source_info.scope];
462                     local.source_info.span = callsite.location.span;
463
464                     let idx = caller_body.local_decls.push(local);
465                     local_map.push(idx);
466                 }
467
468                 // If the call is something like `a[*i] = f(i)`, where
469                 // `i : &mut usize`, then just duplicating the `a[*i]`
470                 // Place could result in two different locations if `f`
471                 // writes to `i`. To prevent this we need to create a temporary
472                 // borrow of the place and pass the destination as `*temp` instead.
473                 fn dest_needs_borrow(place: Place<'_>) -> bool {
474                     for elem in place.projection.iter() {
475                         match elem {
476                             ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
477                             _ => {}
478                         }
479                     }
480
481                     false
482                 }
483
484                 let dest = if dest_needs_borrow(destination.0) {
485                     debug!("creating temp for return destination");
486                     let dest = Rvalue::Ref(
487                         self.tcx.lifetimes.re_erased,
488                         BorrowKind::Mut { allow_two_phase_borrow: false },
489                         destination.0,
490                     );
491
492                     let ty = dest.ty(caller_body, self.tcx);
493
494                     let temp = LocalDecl::new(ty, callsite.location.span);
495
496                     let tmp = caller_body.local_decls.push(temp);
497                     let tmp = Place::from(tmp);
498
499                     let stmt = Statement {
500                         source_info: callsite.location,
501                         kind: StatementKind::Assign(box (tmp, dest)),
502                     };
503                     caller_body[callsite.bb].statements.push(stmt);
504                     self.tcx.mk_place_deref(tmp)
505                 } else {
506                     destination.0
507                 };
508
509                 let return_block = destination.1;
510
511                 // Copy the arguments if needed.
512                 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, return_block);
513
514                 let bb_len = caller_body.basic_blocks().len();
515                 let mut integrator = Integrator {
516                     block_idx: bb_len,
517                     args: &args,
518                     local_map,
519                     scope_map,
520                     destination: dest,
521                     return_block,
522                     cleanup_block: cleanup,
523                     in_cleanup_block: false,
524                     tcx: self.tcx,
525                 };
526
527                 for mut var_debug_info in callee_body.var_debug_info.drain(..) {
528                     integrator.visit_var_debug_info(&mut var_debug_info);
529                     caller_body.var_debug_info.push(var_debug_info);
530                 }
531
532                 for (bb, mut block) in callee_body.basic_blocks_mut().drain_enumerated(..) {
533                     integrator.visit_basic_block_data(bb, &mut block);
534                     caller_body.basic_blocks_mut().push(block);
535                 }
536
537                 let terminator = Terminator {
538                     source_info: callsite.location,
539                     kind: TerminatorKind::Goto { target: BasicBlock::new(bb_len) },
540                 };
541
542                 caller_body[callsite.bb].terminator = Some(terminator);
543
544                 true
545             }
546             kind => {
547                 caller_body[callsite.bb].terminator =
548                     Some(Terminator { source_info: terminator.source_info, kind });
549                 false
550             }
551         }
552     }
553
554     fn make_call_args(
555         &self,
556         args: Vec<Operand<'tcx>>,
557         callsite: &CallSite<'tcx>,
558         caller_body: &mut Body<'tcx>,
559         return_block: BasicBlock,
560     ) -> Vec<Local> {
561         let tcx = self.tcx;
562
563         // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
564         // The caller provides the arguments wrapped up in a tuple:
565         //
566         //     tuple_tmp = (a, b, c)
567         //     Fn::call(closure_ref, tuple_tmp)
568         //
569         // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
570         // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
571         // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
572         // a vector like
573         //
574         //     [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
575         //
576         // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
577         // if we "spill" that into *another* temporary, so that we can map the argument
578         // variable in the callee MIR directly to an argument variable on our side.
579         // So we introduce temporaries like:
580         //
581         //     tmp0 = tuple_tmp.0
582         //     tmp1 = tuple_tmp.1
583         //     tmp2 = tuple_tmp.2
584         //
585         // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
586         if tcx.is_closure(callsite.callee) {
587             let mut args = args.into_iter();
588             let self_ = self.create_temp_if_necessary(
589                 args.next().unwrap(),
590                 callsite,
591                 caller_body,
592                 return_block,
593             );
594             let tuple = self.create_temp_if_necessary(
595                 args.next().unwrap(),
596                 callsite,
597                 caller_body,
598                 return_block,
599             );
600             assert!(args.next().is_none());
601
602             let tuple = Place::from(tuple);
603             let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.kind() {
604                 s
605             } else {
606                 bug!("Closure arguments are not passed as a tuple");
607             };
608
609             // The `closure_ref` in our example above.
610             let closure_ref_arg = iter::once(self_);
611
612             // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
613             let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
614                 // This is e.g., `tuple_tmp.0` in our example above.
615                 let tuple_field =
616                     Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty.expect_ty()));
617
618                 // Spill to a local to make e.g., `tmp0`.
619                 self.create_temp_if_necessary(tuple_field, callsite, caller_body, return_block)
620             });
621
622             closure_ref_arg.chain(tuple_tmp_args).collect()
623         } else {
624             args.into_iter()
625                 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body, return_block))
626                 .collect()
627         }
628     }
629
630     /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
631     /// temporary `T` and an instruction `T = arg`, and returns `T`.
632     fn create_temp_if_necessary(
633         &self,
634         arg: Operand<'tcx>,
635         callsite: &CallSite<'tcx>,
636         caller_body: &mut Body<'tcx>,
637         return_block: BasicBlock,
638     ) -> Local {
639         // FIXME: Analysis of the usage of the arguments to avoid
640         // unnecessary temporaries.
641
642         if let Operand::Move(place) = &arg {
643             if let Some(local) = place.as_local() {
644                 if caller_body.local_kind(local) == LocalKind::Temp {
645                     // Reuse the operand if it's a temporary already
646                     return local;
647                 }
648             }
649         }
650
651         debug!("creating temp for argument {:?}", arg);
652         // Otherwise, create a temporary for the arg
653         let arg = Rvalue::Use(arg);
654
655         let ty = arg.ty(caller_body, self.tcx);
656
657         let arg_tmp = LocalDecl::new(ty, callsite.location.span);
658         let arg_tmp = caller_body.local_decls.push(arg_tmp);
659
660         caller_body[callsite.bb].statements.push(Statement {
661             source_info: callsite.location,
662             kind: StatementKind::StorageLive(arg_tmp),
663         });
664         caller_body[callsite.bb].statements.push(Statement {
665             source_info: callsite.location,
666             kind: StatementKind::Assign(box (Place::from(arg_tmp), arg)),
667         });
668         caller_body[return_block].statements.insert(
669             0,
670             Statement { source_info: callsite.location, kind: StatementKind::StorageDead(arg_tmp) },
671         );
672
673         arg_tmp
674     }
675 }
676
677 fn type_size_of<'tcx>(
678     tcx: TyCtxt<'tcx>,
679     param_env: ty::ParamEnv<'tcx>,
680     ty: Ty<'tcx>,
681 ) -> Option<u64> {
682     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
683 }
684
685 /**
686  * Integrator.
687  *
688  * Integrates blocks from the callee function into the calling function.
689  * Updates block indices, references to locals and other control flow
690  * stuff.
691 */
692 struct Integrator<'a, 'tcx> {
693     block_idx: usize,
694     args: &'a [Local],
695     local_map: IndexVec<Local, Local>,
696     scope_map: IndexVec<SourceScope, SourceScope>,
697     destination: Place<'tcx>,
698     return_block: BasicBlock,
699     cleanup_block: Option<BasicBlock>,
700     in_cleanup_block: bool,
701     tcx: TyCtxt<'tcx>,
702 }
703
704 impl<'a, 'tcx> Integrator<'a, 'tcx> {
705     fn update_target(&self, tgt: BasicBlock) -> BasicBlock {
706         let new = BasicBlock::new(tgt.index() + self.block_idx);
707         debug!("updating target `{:?}`, new: `{:?}`", tgt, new);
708         new
709     }
710
711     fn make_integrate_local(&self, local: Local) -> Local {
712         if local == RETURN_PLACE {
713             return self.destination.local;
714         }
715
716         let idx = local.index() - 1;
717         if idx < self.args.len() {
718             return self.args[idx];
719         }
720
721         self.local_map[Local::new(idx - self.args.len())]
722     }
723 }
724
725 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
726     fn tcx(&self) -> TyCtxt<'tcx> {
727         self.tcx
728     }
729
730     fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
731         *local = self.make_integrate_local(*local);
732     }
733
734     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
735         // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
736         let dest_proj_len = self.destination.projection.len();
737         if place.local == RETURN_PLACE && dest_proj_len > 0 {
738             let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
739             projs.extend(self.destination.projection);
740             projs.extend(place.projection);
741
742             place.projection = self.tcx.intern_place_elems(&*projs);
743         }
744         // Handles integrating any locals that occur in the base
745         // or projections
746         self.super_place(place, context, location)
747     }
748
749     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
750         self.in_cleanup_block = data.is_cleanup;
751         self.super_basic_block_data(block, data);
752         self.in_cleanup_block = false;
753     }
754
755     fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
756         self.super_retag(kind, place, loc);
757
758         // We have to patch all inlined retags to be aware that they are no longer
759         // happening on function entry.
760         if *kind == RetagKind::FnEntry {
761             *kind = RetagKind::Default;
762         }
763     }
764
765     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
766         // Don't try to modify the implicit `_0` access on return (`return` terminators are
767         // replaced down below anyways).
768         if !matches!(terminator.kind, TerminatorKind::Return) {
769             self.super_terminator(terminator, loc);
770         }
771
772         match terminator.kind {
773             TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
774             TerminatorKind::Goto { ref mut target } => {
775                 *target = self.update_target(*target);
776             }
777             TerminatorKind::SwitchInt { ref mut targets, .. } => {
778                 for tgt in targets.all_targets_mut() {
779                     *tgt = self.update_target(*tgt);
780                 }
781             }
782             TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
783             | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
784                 *target = self.update_target(*target);
785                 if let Some(tgt) = *unwind {
786                     *unwind = Some(self.update_target(tgt));
787                 } else if !self.in_cleanup_block {
788                     // Unless this drop is in a cleanup block, add an unwind edge to
789                     // the original call's cleanup block
790                     *unwind = self.cleanup_block;
791                 }
792             }
793             TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
794                 if let Some((_, ref mut tgt)) = *destination {
795                     *tgt = self.update_target(*tgt);
796                 }
797                 if let Some(tgt) = *cleanup {
798                     *cleanup = Some(self.update_target(tgt));
799                 } else if !self.in_cleanup_block {
800                     // Unless this call is in a cleanup block, add an unwind edge to
801                     // the original call's cleanup block
802                     *cleanup = self.cleanup_block;
803                 }
804             }
805             TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
806                 *target = self.update_target(*target);
807                 if let Some(tgt) = *cleanup {
808                     *cleanup = Some(self.update_target(tgt));
809                 } else if !self.in_cleanup_block {
810                     // Unless this assert is in a cleanup block, add an unwind edge to
811                     // the original call's cleanup block
812                     *cleanup = self.cleanup_block;
813                 }
814             }
815             TerminatorKind::Return => {
816                 terminator.kind = TerminatorKind::Goto { target: self.return_block };
817             }
818             TerminatorKind::Resume => {
819                 if let Some(tgt) = self.cleanup_block {
820                     terminator.kind = TerminatorKind::Goto { target: tgt }
821                 }
822             }
823             TerminatorKind::Abort => {}
824             TerminatorKind::Unreachable => {}
825             TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
826                 *real_target = self.update_target(*real_target);
827                 *imaginary_target = self.update_target(*imaginary_target);
828             }
829             TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
830             // see the ordering of passes in the optimized_mir query.
831             {
832                 bug!("False unwinds should have been removed before inlining")
833             }
834             TerminatorKind::InlineAsm { ref mut destination, .. } => {
835                 if let Some(ref mut tgt) = *destination {
836                     *tgt = self.update_target(*tgt);
837                 }
838             }
839         }
840     }
841
842     fn visit_source_scope(&mut self, scope: &mut SourceScope) {
843         *scope = self.scope_map[*scope];
844     }
845 }