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