]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/inline.rs
Rollup merge of #82728 - calebsander:refactor/bufreader-buf, r=m-ou-se
[rust.git] / compiler / rustc_mir / src / transform / inline.rs
1 //! Inlining pass for MIR functions
2
3 use rustc_attr::InlineAttr;
4 use rustc_hir as hir;
5 use rustc_index::bit_set::BitSet;
6 use rustc_index::vec::Idx;
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;
11 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
12 use rustc_span::{hygiene::ExpnKind, ExpnData, Span};
13 use rustc_target::spec::abi::Abi;
14
15 use super::simplify::{remove_dead_blocks, CfgSimplifier};
16 use crate::transform::MirPass;
17 use std::iter;
18 use std::ops::{Range, RangeFrom};
19
20 crate mod cycle;
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: Instance<'tcx>,
34     fn_sig: ty::PolyFnSig<'tcx>,
35     block: BasicBlock,
36     target: Option<BasicBlock>,
37     source_info: SourceInfo,
38 }
39
40 /// Returns true if MIR inlining is enabled in the current compilation session.
41 crate fn is_enabled(tcx: TyCtxt<'_>) -> bool {
42     if tcx.sess.opts.debugging_opts.instrument_coverage {
43         // Since `Inline` happens after `InstrumentCoverage`, the function-specific coverage
44         // counters can be invalidated, such as by merging coverage counter statements from
45         // a pre-inlined function into a different function. This kind of change is invalid,
46         // so inlining must be skipped. Note: This check is performed here so inlining can
47         // be disabled without preventing other optimizations (regardless of `mir_opt_level`).
48         return false;
49     }
50
51     if let Some(enabled) = tcx.sess.opts.debugging_opts.inline_mir {
52         return enabled;
53     }
54
55     tcx.sess.opts.debugging_opts.mir_opt_level >= 2
56 }
57
58 impl<'tcx> MirPass<'tcx> for Inline {
59     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
60         if !is_enabled(tcx) {
61             return;
62         }
63
64         let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
65         let _guard = span.enter();
66         if inline(tcx, body) {
67             debug!("running simplify cfg on {:?}", body.source);
68             CfgSimplifier::new(body).simplify();
69             remove_dead_blocks(body);
70         }
71     }
72 }
73
74 fn inline(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
75     let def_id = body.source.def_id();
76     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
77
78     // Only do inlining into fn bodies.
79     if !tcx.hir().body_owner_kind(hir_id).is_fn_or_closure() {
80         return false;
81     }
82     if body.source.promoted.is_some() {
83         return false;
84     }
85
86     let mut this = Inliner {
87         tcx,
88         param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
89         codegen_fn_attrs: tcx.codegen_fn_attrs(body.source.def_id()),
90         hir_id,
91         history: Vec::new(),
92         changed: false,
93     };
94     let blocks = BasicBlock::new(0)..body.basic_blocks().next_index();
95     this.process_blocks(body, blocks);
96     this.changed
97 }
98
99 struct Inliner<'tcx> {
100     tcx: TyCtxt<'tcx>,
101     param_env: ParamEnv<'tcx>,
102     /// Caller codegen attributes.
103     codegen_fn_attrs: &'tcx CodegenFnAttrs,
104     /// Caller HirID.
105     hir_id: hir::HirId,
106     /// Stack of inlined Instances.
107     history: Vec<ty::Instance<'tcx>>,
108     /// Indicates that the caller body has been modified.
109     changed: bool,
110 }
111
112 impl Inliner<'tcx> {
113     fn process_blocks(&mut self, caller_body: &mut Body<'tcx>, blocks: Range<BasicBlock>) {
114         for bb in blocks {
115             let bb_data = &caller_body[bb];
116             if bb_data.is_cleanup {
117                 continue;
118             }
119
120             let callsite = match self.resolve_callsite(caller_body, bb, bb_data) {
121                 None => continue,
122                 Some(it) => it,
123             };
124
125             let span = trace_span!("process_blocks", %callsite.callee, ?bb);
126             let _guard = span.enter();
127
128             match self.try_inlining(caller_body, &callsite) {
129                 Err(reason) => {
130                     debug!("not-inlined {} [{}]", callsite.callee, reason);
131                     continue;
132                 }
133                 Ok(new_blocks) => {
134                     debug!("inlined {}", callsite.callee);
135                     self.changed = true;
136                     self.history.push(callsite.callee);
137                     self.process_blocks(caller_body, new_blocks);
138                     self.history.pop();
139                 }
140             }
141         }
142     }
143
144     /// Attempts to inline a callsite into the caller body. When successful returns basic blocks
145     /// containing the inlined body. Otherwise returns an error describing why inlining didn't take
146     /// place.
147     fn try_inlining(
148         &self,
149         caller_body: &mut Body<'tcx>,
150         callsite: &CallSite<'tcx>,
151     ) -> Result<std::ops::Range<BasicBlock>, &'static str> {
152         let callee_attrs = self.tcx.codegen_fn_attrs(callsite.callee.def_id());
153         self.check_codegen_attributes(callsite, callee_attrs)?;
154         self.check_mir_is_available(caller_body, &callsite.callee)?;
155         let callee_body = self.tcx.instance_mir(callsite.callee.def);
156         self.check_mir_body(callsite, callee_body, callee_attrs)?;
157
158         if !self.tcx.consider_optimizing(|| {
159             format!("Inline {:?} into {}", callee_body.span, callsite.callee)
160         }) {
161             return Err("optimization fuel exhausted");
162         }
163
164         let callee_body = callsite.callee.subst_mir_and_normalize_erasing_regions(
165             self.tcx,
166             self.param_env,
167             callee_body.clone(),
168         );
169
170         let old_blocks = caller_body.basic_blocks().next_index();
171         self.inline_call(caller_body, &callsite, callee_body);
172         let new_blocks = old_blocks..caller_body.basic_blocks().next_index();
173
174         Ok(new_blocks)
175     }
176
177     fn check_mir_is_available(
178         &self,
179         caller_body: &Body<'tcx>,
180         callee: &Instance<'tcx>,
181     ) -> Result<(), &'static str> {
182         if callee.def_id() == caller_body.source.def_id() {
183             return Err("self-recursion");
184         }
185
186         match callee.def {
187             InstanceDef::Item(_) => {
188                 // If there is no MIR available (either because it was not in metadata or
189                 // because it has no MIR because it's an extern function), then the inliner
190                 // won't cause cycles on this.
191                 if !self.tcx.is_mir_available(callee.def_id()) {
192                     return Err("item MIR unavailable");
193                 }
194             }
195             // These have no own callable MIR.
196             InstanceDef::Intrinsic(_) | InstanceDef::Virtual(..) => {
197                 return Err("instance without MIR (intrinsic / virtual)");
198             }
199             // This cannot result in an immediate cycle since the callee MIR is a shim, which does
200             // not get any optimizations run on it. Any subsequent inlining may cause cycles, but we
201             // do not need to catch this here, we can wait until the inliner decides to continue
202             // inlining a second time.
203             InstanceDef::VtableShim(_)
204             | InstanceDef::ReifyShim(_)
205             | InstanceDef::FnPtrShim(..)
206             | InstanceDef::ClosureOnceShim { .. }
207             | InstanceDef::DropGlue(..)
208             | InstanceDef::CloneShim(..) => return Ok(()),
209         }
210
211         if self.tcx.is_constructor(callee.def_id()) {
212             trace!("constructors always have MIR");
213             // Constructor functions cannot cause a query cycle.
214             return Ok(());
215         }
216
217         if let Some(callee_def_id) = callee.def_id().as_local() {
218             let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
219             // Avoid inlining into generators,
220             // since their `optimized_mir` is used for layout computation, which can
221             // create a cycle, even when no attempt is made to inline the function
222             // in the other direction.
223             if caller_body.generator.is_some() {
224                 return Err("local generator (query cycle avoidance)");
225             }
226
227             // Avoid a cycle here by only using `instance_mir` only if we have
228             // a lower `HirId` than the callee. This ensures that the callee will
229             // not inline us. This trick only works without incremental compilation.
230             // So don't do it if that is enabled.
231             if !self.tcx.dep_graph.is_fully_enabled() && self.hir_id < callee_hir_id {
232                 return Ok(());
233             }
234
235             // If we know for sure that the function we're calling will itself try to
236             // call us, then we avoid inlining that function.
237             if self
238                 .tcx
239                 .mir_callgraph_reachable((*callee, caller_body.source.def_id().expect_local()))
240             {
241                 return Err("caller might be reachable from callee (query cycle avoidance)");
242             }
243
244             Ok(())
245         } else {
246             // This cannot result in an immediate cycle since the callee MIR is from another crate
247             // and is already optimized. Any subsequent inlining may cause cycles, but we do
248             // not need to catch this here, we can wait until the inliner decides to continue
249             // inlining a second time.
250             trace!("functions from other crates always have MIR");
251             Ok(())
252         }
253     }
254
255     fn resolve_callsite(
256         &self,
257         caller_body: &Body<'tcx>,
258         bb: BasicBlock,
259         bb_data: &BasicBlockData<'tcx>,
260     ) -> Option<CallSite<'tcx>> {
261         // Only consider direct calls to functions
262         let terminator = bb_data.terminator();
263         if let TerminatorKind::Call { ref func, ref destination, .. } = terminator.kind {
264             let func_ty = func.ty(caller_body, self.tcx);
265             if let ty::FnDef(def_id, substs) = *func_ty.kind() {
266                 // To resolve an instance its substs have to be fully normalized.
267                 let substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
268                 let callee =
269                     Instance::resolve(self.tcx, self.param_env, def_id, substs).ok().flatten()?;
270
271                 if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def {
272                     return None;
273                 }
274
275                 let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs);
276
277                 return Some(CallSite {
278                     callee,
279                     fn_sig,
280                     block: bb,
281                     target: destination.map(|(_, target)| target),
282                     source_info: terminator.source_info,
283                 });
284             }
285         }
286
287         None
288     }
289
290     /// Returns an error if inlining is not possible based on codegen attributes alone. A success
291     /// indicates that inlining decision should be based on other criteria.
292     fn check_codegen_attributes(
293         &self,
294         callsite: &CallSite<'tcx>,
295         callee_attrs: &CodegenFnAttrs,
296     ) -> Result<(), &'satic str> {
297         if let InlineAttr::Never = callee_attrs.inline {
298             return Err("never inline hint");
299         }
300
301         // Only inline local functions if they would be eligible for cross-crate
302         // inlining. This is to ensure that the final crate doesn't have MIR that
303         // reference unexported symbols
304         if callsite.callee.def_id().is_local() {
305             let is_generic = callsite.callee.substs.non_erasable_generics().next().is_some();
306             if !is_generic && !callee_attrs.requests_inline() {
307                 return Err("not exported");
308             }
309         }
310
311         if callsite.fn_sig.c_variadic() {
312             return Err("C variadic");
313         }
314
315         if callee_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
316             return Err("naked");
317         }
318
319         if callee_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
320             return Err("cold");
321         }
322
323         if callee_attrs.no_sanitize != self.codegen_fn_attrs.no_sanitize {
324             return Err("incompatible sanitizer set");
325         }
326
327         if callee_attrs.instruction_set != self.codegen_fn_attrs.instruction_set {
328             return Err("incompatible instruction set");
329         }
330
331         for feature in &callee_attrs.target_features {
332             if !self.codegen_fn_attrs.target_features.contains(feature) {
333                 return Err("incompatible target feature");
334             }
335         }
336
337         Ok(())
338     }
339
340     /// Returns inlining decision that is based on the examination of callee MIR body.
341     /// Assumes that codegen attributes have been checked for compatibility already.
342     #[instrument(level = "debug", skip(self, callee_body))]
343     fn check_mir_body(
344         &self,
345         callsite: &CallSite<'tcx>,
346         callee_body: &Body<'tcx>,
347         callee_attrs: &CodegenFnAttrs,
348     ) -> Result<(), &'static str> {
349         let tcx = self.tcx;
350
351         let mut threshold = if callee_attrs.requests_inline() {
352             self.tcx.sess.opts.debugging_opts.inline_mir_hint_threshold.unwrap_or(100)
353         } else {
354             self.tcx.sess.opts.debugging_opts.inline_mir_threshold.unwrap_or(50)
355         };
356
357         // Give a bonus functions with a small number of blocks,
358         // We normally have two or three blocks for even
359         // very small functions.
360         if callee_body.basic_blocks().len() <= 3 {
361             threshold += threshold / 4;
362         }
363         debug!("    final inline threshold = {}", threshold);
364
365         // FIXME: Give a bonus to functions with only a single caller
366         let mut first_block = true;
367         let mut cost = 0;
368
369         // Traverse the MIR manually so we can account for the effects of
370         // inlining on the CFG.
371         let mut work_list = vec![START_BLOCK];
372         let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
373         while let Some(bb) = work_list.pop() {
374             if !visited.insert(bb.index()) {
375                 continue;
376             }
377             let blk = &callee_body.basic_blocks()[bb];
378
379             for stmt in &blk.statements {
380                 // Don't count StorageLive/StorageDead in the inlining cost.
381                 match stmt.kind {
382                     StatementKind::StorageLive(_)
383                     | StatementKind::StorageDead(_)
384                     | StatementKind::Nop => {}
385                     _ => cost += INSTR_COST,
386                 }
387             }
388             let term = blk.terminator();
389             let mut is_drop = false;
390             match term.kind {
391                 TerminatorKind::Drop { ref place, target, unwind }
392                 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
393                     is_drop = true;
394                     work_list.push(target);
395                     // If the place doesn't actually need dropping, treat it like
396                     // a regular goto.
397                     let ty = callsite.callee.subst_mir(self.tcx, &place.ty(callee_body, tcx).ty);
398                     if ty.needs_drop(tcx, self.param_env) {
399                         cost += CALL_PENALTY;
400                         if let Some(unwind) = unwind {
401                             cost += LANDINGPAD_PENALTY;
402                             work_list.push(unwind);
403                         }
404                     } else {
405                         cost += INSTR_COST;
406                     }
407                 }
408
409                 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
410                     if first_block =>
411                 {
412                     // If the function always diverges, don't inline
413                     // unless the cost is zero
414                     threshold = 0;
415                 }
416
417                 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
418                     if let ty::FnDef(def_id, substs) =
419                         *callsite.callee.subst_mir(self.tcx, &f.literal.ty).kind()
420                     {
421                         let substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
422                         if let Ok(Some(instance)) =
423                             Instance::resolve(self.tcx, self.param_env, def_id, substs)
424                         {
425                             if callsite.callee.def_id() == instance.def_id() {
426                                 return Err("self-recursion");
427                             } else if self.history.contains(&instance) {
428                                 return Err("already inlined");
429                             }
430                         }
431                         // Don't give intrinsics the extra penalty for calls
432                         let f = tcx.fn_sig(def_id);
433                         if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
434                             cost += INSTR_COST;
435                         } else {
436                             cost += CALL_PENALTY;
437                         }
438                     } else {
439                         cost += CALL_PENALTY;
440                     }
441                     if cleanup.is_some() {
442                         cost += LANDINGPAD_PENALTY;
443                     }
444                 }
445                 TerminatorKind::Assert { cleanup, .. } => {
446                     cost += CALL_PENALTY;
447
448                     if cleanup.is_some() {
449                         cost += LANDINGPAD_PENALTY;
450                     }
451                 }
452                 TerminatorKind::Resume => cost += RESUME_PENALTY,
453                 _ => cost += INSTR_COST,
454             }
455
456             if !is_drop {
457                 for &succ in term.successors() {
458                     work_list.push(succ);
459                 }
460             }
461
462             first_block = false;
463         }
464
465         // Count up the cost of local variables and temps, if we know the size
466         // use that, otherwise we use a moderately-large dummy cost.
467
468         let ptr_size = tcx.data_layout.pointer_size.bytes();
469
470         for v in callee_body.vars_and_temps_iter() {
471             let ty = callsite.callee.subst_mir(self.tcx, &callee_body.local_decls[v].ty);
472             // Cost of the var is the size in machine-words, if we know
473             // it.
474             if let Some(size) = type_size_of(tcx, self.param_env, ty) {
475                 cost += ((size + ptr_size - 1) / ptr_size) as usize;
476             } else {
477                 cost += UNKNOWN_SIZE_COST;
478             }
479         }
480
481         if let InlineAttr::Always = callee_attrs.inline {
482             debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
483             Ok(())
484         } else {
485             if cost <= threshold {
486                 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
487                 Ok(())
488             } else {
489                 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
490                 Err("cost above threshold")
491             }
492         }
493     }
494
495     fn inline_call(
496         &self,
497         caller_body: &mut Body<'tcx>,
498         callsite: &CallSite<'tcx>,
499         mut callee_body: Body<'tcx>,
500     ) {
501         let terminator = caller_body[callsite.block].terminator.take().unwrap();
502         match terminator.kind {
503             TerminatorKind::Call { args, destination, cleanup, .. } => {
504                 // If the call is something like `a[*i] = f(i)`, where
505                 // `i : &mut usize`, then just duplicating the `a[*i]`
506                 // Place could result in two different locations if `f`
507                 // writes to `i`. To prevent this we need to create a temporary
508                 // borrow of the place and pass the destination as `*temp` instead.
509                 fn dest_needs_borrow(place: Place<'_>) -> bool {
510                     for elem in place.projection.iter() {
511                         match elem {
512                             ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
513                             _ => {}
514                         }
515                     }
516
517                     false
518                 }
519
520                 let dest = if let Some((destination_place, _)) = destination {
521                     if dest_needs_borrow(destination_place) {
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 },
526                             destination_place,
527                         );
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 (temp, dest)),
533                         });
534                         self.tcx.mk_place_deref(temp)
535                     } else {
536                         destination_place
537                     }
538                 } else {
539                     trace!("creating temp for return place");
540                     Place::from(self.new_call_temp(caller_body, &callsite, callee_body.return_ty()))
541                 };
542
543                 // Copy the arguments if needed.
544                 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, &callee_body);
545
546                 let mut integrator = Integrator {
547                     args: &args,
548                     new_locals: Local::new(caller_body.local_decls.len())..,
549                     new_scopes: SourceScope::new(caller_body.source_scopes.len())..,
550                     new_blocks: BasicBlock::new(caller_body.basic_blocks().len())..,
551                     destination: dest,
552                     return_block: callsite.target,
553                     cleanup_block: cleanup,
554                     in_cleanup_block: false,
555                     tcx: self.tcx,
556                     callsite_span: callsite.source_info.span,
557                     body_span: callee_body.span,
558                     always_live_locals: BitSet::new_filled(callee_body.local_decls.len()),
559                 };
560
561                 // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
562                 // (or existing ones, in a few special cases) in the caller.
563                 integrator.visit_body(&mut callee_body);
564
565                 for scope in &mut callee_body.source_scopes {
566                     // FIXME(eddyb) move this into a `fn visit_scope_data` in `Integrator`.
567                     if scope.parent_scope.is_none() {
568                         let callsite_scope = &caller_body.source_scopes[callsite.source_info.scope];
569
570                         // Attach the outermost callee scope as a child of the callsite
571                         // scope, via the `parent_scope` and `inlined_parent_scope` chains.
572                         scope.parent_scope = Some(callsite.source_info.scope);
573                         assert_eq!(scope.inlined_parent_scope, None);
574                         scope.inlined_parent_scope = if callsite_scope.inlined.is_some() {
575                             Some(callsite.source_info.scope)
576                         } else {
577                             callsite_scope.inlined_parent_scope
578                         };
579
580                         // Mark the outermost callee scope as an inlined one.
581                         assert_eq!(scope.inlined, None);
582                         scope.inlined = Some((callsite.callee, callsite.source_info.span));
583                     } else if scope.inlined_parent_scope.is_none() {
584                         // Make it easy to find the scope with `inlined` set above.
585                         scope.inlined_parent_scope =
586                             Some(integrator.map_scope(OUTERMOST_SOURCE_SCOPE));
587                     }
588                 }
589
590                 // If there are any locals without storage markers, give them storage only for the
591                 // duration of the call.
592                 for local in callee_body.vars_and_temps_iter() {
593                     if integrator.always_live_locals.contains(local) {
594                         let new_local = integrator.map_local(local);
595                         caller_body[callsite.block].statements.push(Statement {
596                             source_info: callsite.source_info,
597                             kind: StatementKind::StorageLive(new_local),
598                         });
599                     }
600                 }
601                 if let Some(block) = callsite.target {
602                     // To avoid repeated O(n) insert, push any new statements to the end and rotate
603                     // the slice once.
604                     let mut n = 0;
605                     for local in callee_body.vars_and_temps_iter().rev() {
606                         if integrator.always_live_locals.contains(local) {
607                             let new_local = integrator.map_local(local);
608                             caller_body[block].statements.push(Statement {
609                                 source_info: callsite.source_info,
610                                 kind: StatementKind::StorageDead(new_local),
611                             });
612                             n += 1;
613                         }
614                     }
615                     caller_body[block].statements.rotate_right(n);
616                 }
617
618                 // Insert all of the (mapped) parts of the callee body into the caller.
619                 caller_body.local_decls.extend(
620                     // FIXME(eddyb) make `Range<Local>` iterable so that we can use
621                     // `callee_body.local_decls.drain(callee_body.vars_and_temps())`
622                     callee_body
623                         .vars_and_temps_iter()
624                         .map(|local| callee_body.local_decls[local].clone()),
625                 );
626                 caller_body.source_scopes.extend(callee_body.source_scopes.drain(..));
627                 caller_body.var_debug_info.extend(callee_body.var_debug_info.drain(..));
628                 caller_body.basic_blocks_mut().extend(callee_body.basic_blocks_mut().drain(..));
629
630                 caller_body[callsite.block].terminator = Some(Terminator {
631                     source_info: callsite.source_info,
632                     kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
633                 });
634
635                 // Copy only unevaluated constants from the callee_body into the caller_body.
636                 // Although we are only pushing `ConstKind::Unevaluated` consts to
637                 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
638                 // because we are calling `subst_and_normalize_erasing_regions`.
639                 caller_body.required_consts.extend(
640                     callee_body.required_consts.iter().copied().filter(|&constant| {
641                         matches!(constant.literal.val, ConstKind::Unevaluated(_, _, _))
642                     }),
643                 );
644             }
645             kind => bug!("unexpected terminator kind {:?}", kind),
646         }
647     }
648
649     fn make_call_args(
650         &self,
651         args: Vec<Operand<'tcx>>,
652         callsite: &CallSite<'tcx>,
653         caller_body: &mut Body<'tcx>,
654         callee_body: &Body<'tcx>,
655     ) -> Vec<Local> {
656         let tcx = self.tcx;
657
658         // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
659         // The caller provides the arguments wrapped up in a tuple:
660         //
661         //     tuple_tmp = (a, b, c)
662         //     Fn::call(closure_ref, tuple_tmp)
663         //
664         // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
665         // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
666         // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
667         // a vector like
668         //
669         //     [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
670         //
671         // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
672         // if we "spill" that into *another* temporary, so that we can map the argument
673         // variable in the callee MIR directly to an argument variable on our side.
674         // So we introduce temporaries like:
675         //
676         //     tmp0 = tuple_tmp.0
677         //     tmp1 = tuple_tmp.1
678         //     tmp2 = tuple_tmp.2
679         //
680         // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
681         if callsite.fn_sig.abi() == Abi::RustCall && callee_body.spread_arg.is_none() {
682             let mut args = args.into_iter();
683             let self_ = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
684             let tuple = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
685             assert!(args.next().is_none());
686
687             let tuple = Place::from(tuple);
688             let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.kind() {
689                 s
690             } else {
691                 bug!("Closure arguments are not passed as a tuple");
692             };
693
694             // The `closure_ref` in our example above.
695             let closure_ref_arg = iter::once(self_);
696
697             // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
698             let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
699                 // This is e.g., `tuple_tmp.0` in our example above.
700                 let tuple_field =
701                     Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty.expect_ty()));
702
703                 // Spill to a local to make e.g., `tmp0`.
704                 self.create_temp_if_necessary(tuple_field, callsite, caller_body)
705             });
706
707             closure_ref_arg.chain(tuple_tmp_args).collect()
708         } else {
709             args.into_iter()
710                 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body))
711                 .collect()
712         }
713     }
714
715     /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
716     /// temporary `T` and an instruction `T = arg`, and returns `T`.
717     fn create_temp_if_necessary(
718         &self,
719         arg: Operand<'tcx>,
720         callsite: &CallSite<'tcx>,
721         caller_body: &mut Body<'tcx>,
722     ) -> Local {
723         // Reuse the operand if it is a moved temporary.
724         if let Operand::Move(place) = &arg {
725             if let Some(local) = place.as_local() {
726                 if caller_body.local_kind(local) == LocalKind::Temp {
727                     return local;
728                 }
729             }
730         }
731
732         // Otherwise, create a temporary for the argument.
733         trace!("creating temp for argument {:?}", arg);
734         let arg_ty = arg.ty(caller_body, self.tcx);
735         let local = self.new_call_temp(caller_body, callsite, arg_ty);
736         caller_body[callsite.block].statements.push(Statement {
737             source_info: callsite.source_info,
738             kind: StatementKind::Assign(box (Place::from(local), Rvalue::Use(arg))),
739         });
740         local
741     }
742
743     /// Introduces a new temporary into the caller body that is live for the duration of the call.
744     fn new_call_temp(
745         &self,
746         caller_body: &mut Body<'tcx>,
747         callsite: &CallSite<'tcx>,
748         ty: Ty<'tcx>,
749     ) -> Local {
750         let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
751
752         caller_body[callsite.block].statements.push(Statement {
753             source_info: callsite.source_info,
754             kind: StatementKind::StorageLive(local),
755         });
756
757         if let Some(block) = callsite.target {
758             caller_body[block].statements.insert(
759                 0,
760                 Statement {
761                     source_info: callsite.source_info,
762                     kind: StatementKind::StorageDead(local),
763                 },
764             );
765         }
766
767         local
768     }
769 }
770
771 fn type_size_of<'tcx>(
772     tcx: TyCtxt<'tcx>,
773     param_env: ty::ParamEnv<'tcx>,
774     ty: Ty<'tcx>,
775 ) -> Option<u64> {
776     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
777 }
778
779 /**
780  * Integrator.
781  *
782  * Integrates blocks from the callee function into the calling function.
783  * Updates block indices, references to locals and other control flow
784  * stuff.
785 */
786 struct Integrator<'a, 'tcx> {
787     args: &'a [Local],
788     new_locals: RangeFrom<Local>,
789     new_scopes: RangeFrom<SourceScope>,
790     new_blocks: RangeFrom<BasicBlock>,
791     destination: Place<'tcx>,
792     return_block: Option<BasicBlock>,
793     cleanup_block: Option<BasicBlock>,
794     in_cleanup_block: bool,
795     tcx: TyCtxt<'tcx>,
796     callsite_span: Span,
797     body_span: Span,
798     always_live_locals: BitSet<Local>,
799 }
800
801 impl<'a, 'tcx> Integrator<'a, 'tcx> {
802     fn map_local(&self, local: Local) -> Local {
803         let new = if local == RETURN_PLACE {
804             self.destination.local
805         } else {
806             let idx = local.index() - 1;
807             if idx < self.args.len() {
808                 self.args[idx]
809             } else {
810                 Local::new(self.new_locals.start.index() + (idx - self.args.len()))
811             }
812         };
813         trace!("mapping local `{:?}` to `{:?}`", local, new);
814         new
815     }
816
817     fn map_scope(&self, scope: SourceScope) -> SourceScope {
818         let new = SourceScope::new(self.new_scopes.start.index() + scope.index());
819         trace!("mapping scope `{:?}` to `{:?}`", scope, new);
820         new
821     }
822
823     fn map_block(&self, block: BasicBlock) -> BasicBlock {
824         let new = BasicBlock::new(self.new_blocks.start.index() + block.index());
825         trace!("mapping block `{:?}` to `{:?}`", block, new);
826         new
827     }
828 }
829
830 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
831     fn tcx(&self) -> TyCtxt<'tcx> {
832         self.tcx
833     }
834
835     fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
836         *local = self.map_local(*local);
837     }
838
839     fn visit_source_scope(&mut self, scope: &mut SourceScope) {
840         *scope = self.map_scope(*scope);
841     }
842
843     fn visit_span(&mut self, span: &mut Span) {
844         let mut expn_data =
845             ExpnData::default(ExpnKind::Inlined, *span, self.tcx.sess.edition(), None);
846         expn_data.def_site = self.body_span;
847         // Make sure that all spans track the fact that they were inlined.
848         *span = self.callsite_span.fresh_expansion(expn_data);
849     }
850
851     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
852         for elem in place.projection {
853             // FIXME: Make sure that return place is not used in an indexing projection, since it
854             // won't be rebased as it is supposed to be.
855             assert_ne!(ProjectionElem::Index(RETURN_PLACE), elem);
856         }
857
858         // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
859         let dest_proj_len = self.destination.projection.len();
860         if place.local == RETURN_PLACE && dest_proj_len > 0 {
861             let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
862             projs.extend(self.destination.projection);
863             projs.extend(place.projection);
864
865             place.projection = self.tcx.intern_place_elems(&*projs);
866         }
867         // Handles integrating any locals that occur in the base
868         // or projections
869         self.super_place(place, context, location)
870     }
871
872     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
873         self.in_cleanup_block = data.is_cleanup;
874         self.super_basic_block_data(block, data);
875         self.in_cleanup_block = false;
876     }
877
878     fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
879         self.super_retag(kind, place, loc);
880
881         // We have to patch all inlined retags to be aware that they are no longer
882         // happening on function entry.
883         if *kind == RetagKind::FnEntry {
884             *kind = RetagKind::Default;
885         }
886     }
887
888     fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
889         if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
890             statement.kind
891         {
892             self.always_live_locals.remove(local);
893         }
894         self.super_statement(statement, location);
895     }
896
897     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
898         // Don't try to modify the implicit `_0` access on return (`return` terminators are
899         // replaced down below anyways).
900         if !matches!(terminator.kind, TerminatorKind::Return) {
901             self.super_terminator(terminator, loc);
902         }
903
904         match terminator.kind {
905             TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
906             TerminatorKind::Goto { ref mut target } => {
907                 *target = self.map_block(*target);
908             }
909             TerminatorKind::SwitchInt { ref mut targets, .. } => {
910                 for tgt in targets.all_targets_mut() {
911                     *tgt = self.map_block(*tgt);
912                 }
913             }
914             TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
915             | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
916                 *target = self.map_block(*target);
917                 if let Some(tgt) = *unwind {
918                     *unwind = Some(self.map_block(tgt));
919                 } else if !self.in_cleanup_block {
920                     // Unless this drop is in a cleanup block, add an unwind edge to
921                     // the original call's cleanup block
922                     *unwind = self.cleanup_block;
923                 }
924             }
925             TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
926                 if let Some((_, ref mut tgt)) = *destination {
927                     *tgt = self.map_block(*tgt);
928                 }
929                 if let Some(tgt) = *cleanup {
930                     *cleanup = Some(self.map_block(tgt));
931                 } else if !self.in_cleanup_block {
932                     // Unless this call is in a cleanup block, add an unwind edge to
933                     // the original call's cleanup block
934                     *cleanup = self.cleanup_block;
935                 }
936             }
937             TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
938                 *target = self.map_block(*target);
939                 if let Some(tgt) = *cleanup {
940                     *cleanup = Some(self.map_block(tgt));
941                 } else if !self.in_cleanup_block {
942                     // Unless this assert is in a cleanup block, add an unwind edge to
943                     // the original call's cleanup block
944                     *cleanup = self.cleanup_block;
945                 }
946             }
947             TerminatorKind::Return => {
948                 terminator.kind = if let Some(tgt) = self.return_block {
949                     TerminatorKind::Goto { target: tgt }
950                 } else {
951                     TerminatorKind::Unreachable
952                 }
953             }
954             TerminatorKind::Resume => {
955                 if let Some(tgt) = self.cleanup_block {
956                     terminator.kind = TerminatorKind::Goto { target: tgt }
957                 }
958             }
959             TerminatorKind::Abort => {}
960             TerminatorKind::Unreachable => {}
961             TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
962                 *real_target = self.map_block(*real_target);
963                 *imaginary_target = self.map_block(*imaginary_target);
964             }
965             TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
966             // see the ordering of passes in the optimized_mir query.
967             {
968                 bug!("False unwinds should have been removed before inlining")
969             }
970             TerminatorKind::InlineAsm { ref mut destination, .. } => {
971                 if let Some(ref mut tgt) = *destination {
972                     *tgt = self.map_block(*tgt);
973                 }
974             }
975         }
976     }
977 }