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