1 //! Inlining pass for MIR functions
3 use rustc::hir::CodegenFnAttrFlags;
4 use rustc::hir::def_id::DefId;
6 use rustc_data_structures::bit_set::BitSet;
7 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
10 use rustc::mir::visit::*;
11 use rustc::ty::{self, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
12 use rustc::ty::subst::{Subst, SubstsRef};
14 use std::collections::VecDeque;
16 use crate::transform::{MirPass, MirSource};
17 use super::simplify::{remove_dead_blocks, CfgSimplifier};
20 use rustc_target::spec::abi::Abi;
22 const DEFAULT_THRESHOLD: usize = 50;
23 const HINT_THRESHOLD: usize = 100;
25 const INSTR_COST: usize = 5;
26 const CALL_PENALTY: usize = 25;
28 const UNKNOWN_SIZE_COST: usize = 10;
32 #[derive(Copy, Clone, Debug)]
33 struct CallSite<'tcx> {
35 substs: SubstsRef<'tcx>,
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);
48 struct Inliner<'tcx> {
50 source: MirSource<'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
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
67 let mut callsites = VecDeque::new();
69 let param_env = self.tcx.param_env(self.source.def_id());
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()
76 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated() {
77 if let Some(callsite) = self.get_valid_function_call(bb,
81 callsites.push_back(callsite);
89 let mut changed = 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);
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);
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)
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)
120 let callee_body = if self.consider_optimizing(callsite, callee_body) {
121 self.tcx.subst_and_normalize_erasing_regions(
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);
136 debug!("attempting to inline callsite {:?} - success", callsite);
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,
144 // Don't inline the same function multiple times.
145 if callsite.callee != new_callsite.callee {
146 callsites.push_back(new_callsite);
160 // Simplify if we inlined anything.
162 debug!("running simplify cfg on {:?}", self.source);
163 CfgSimplifier::new(caller_body).simplify();
164 remove_dead_blocks(caller_body);
168 fn get_valid_function_call(&self,
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; }
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,
186 if let InstanceDef::Virtual(..) = instance.def {
190 return Some(CallSite {
191 callee: instance.def_id(),
192 substs: instance.substs,
194 location: terminator.source_info
202 fn consider_optimizing(&self,
203 callsite: CallSite<'tcx>,
204 callee_body: &Body<'tcx>)
207 debug!("consider_optimizing({:?})", callsite);
208 self.should_inline(callsite, callee_body)
209 && self.tcx.consider_optimizing(|| format!("Inline {:?} into {:?}",
214 fn should_inline(&self,
215 callsite: CallSite<'tcx>,
216 callee_body: &Body<'tcx>)
219 debug!("should_inline({:?})", callsite);
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");
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");
235 let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee);
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");
246 attr::InlineAttr::Hint => true,
247 attr::InlineAttr::None => false,
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");
260 let mut threshold = if hinted {
266 // Significantly lower the threshold for inlining cold functions
267 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
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;
277 debug!(" final inline threshold = {}", threshold);
279 // FIXME: Give a bonus to functions with only a single caller
281 let param_env = tcx.param_env(self.source.def_id());
283 let mut first_block = true;
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];
294 for stmt in &blk.statements {
295 // Don't count StorageLive/StorageDead in the inlining cost.
297 StatementKind::StorageLive(_) |
298 StatementKind::StorageDead(_) |
299 StatementKind::Nop => {}
300 _ => cost += INSTR_COST
303 let term = blk.terminator();
304 let mut is_drop = false;
306 TerminatorKind::Drop { ref location, target, unwind } |
307 TerminatorKind::DropAndReplace { ref location, target, unwind, .. } => {
309 work_list.push(target);
310 // If the location doesn't actually need dropping, treat it like
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);
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
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 {
337 cost += CALL_PENALTY;
341 TerminatorKind::Assert { .. } => cost += CALL_PENALTY,
342 _ => cost += INSTR_COST
346 for &succ in term.successors() {
347 work_list.push(succ);
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.
357 let ptr_size = tcx.data_layout.pointer_size.bytes();
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
364 if let Some(size) = type_size_of(tcx, param_env.clone(), ty) {
365 cost += (size / ptr_size) as usize;
367 cost += UNKNOWN_SIZE_COST;
371 if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
372 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
375 if cost <= threshold {
376 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
379 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
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);
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());
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;
404 scope.span = callsite.location.span;
406 let idx = caller_body.source_scopes.push(scope);
410 for loc in callee_body.vars_and_temps_iter() {
411 let mut local = callee_body.local_decls[loc].clone();
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];
418 let idx = caller_body.local_decls.push(local);
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 {
431 ProjectionElem::Deref |
432 ProjectionElem::Index(_) => return true,
438 // Static variables need a borrow because the callee
439 // might modify the same static.
440 PlaceBase::Static(_) => true,
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 },
453 let ty = dest.ty(caller_body, self.tcx);
455 let temp = LocalDecl::new_temp(ty, callsite.location.span);
457 let tmp = caller_body.local_decls.push(temp);
458 let tmp = Place::from(tmp);
460 let stmt = Statement {
461 source_info: callsite.location,
462 kind: StatementKind::Assign(tmp.clone(), box dest)
464 caller_body[callsite.bb]
465 .statements.push(stmt);
471 let return_block = destination.1;
473 // Copy the arguments if needed.
474 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body);
476 let bb_len = caller_body.basic_blocks().len();
477 let mut integrator = Integrator {
485 cleanup_block: cleanup,
486 in_cleanup_block: false,
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);
496 let terminator = Terminator {
497 source_info: callsite.location,
498 kind: TerminatorKind::Goto { target: BasicBlock::new(bb_len) }
501 caller_body[callsite.bb].terminator = Some(terminator);
506 caller_body[callsite.bb].terminator = Some(Terminator {
507 source_info: terminator.source_info,
517 args: Vec<Operand<'tcx>>,
518 callsite: &CallSite<'tcx>,
519 caller_body: &mut Body<'tcx>,
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:
526 // tuple_tmp = (a, b, c)
527 // Fn::call(closure_ref, tuple_tmp)
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
534 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
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:
541 // tmp0 = tuple_tmp.0
542 // tmp1 = tuple_tmp.1
543 // tmp2 = tuple_tmp.2
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());
552 let tuple = Place::from(tuple);
553 let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.sty {
556 bug!("Closure arguments are not passed as a tuple");
559 // The `closure_ref` in our example above.
560 let closure_ref_arg = iter::once(self_);
562 // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
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(
571 // Spill to a local to make e.g., `tmp0`.
572 self.create_temp_if_necessary(tuple_field, callsite, caller_body)
575 closure_ref_arg.chain(tuple_tmp_args).collect()
578 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body))
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(
588 callsite: &CallSite<'tcx>,
589 caller_body: &mut Body<'tcx>,
591 // FIXME: Analysis of the usage of the arguments to avoid
592 // unnecessary temporaries.
594 if let Operand::Move(Place {
595 base: PlaceBase::Local(local),
598 if caller_body.local_kind(local) == LocalKind::Temp {
599 // Reuse the operand if it's a temporary already
604 debug!("creating temp for argument {:?}", arg);
605 // Otherwise, create a temporary for the arg
606 let arg = Rvalue::Use(arg);
608 let ty = arg.ty(caller_body, self.tcx);
610 let arg_tmp = LocalDecl::new_temp(ty, callsite.location.span);
611 let arg_tmp = caller_body.local_decls.push(arg_tmp);
613 let stmt = Statement {
614 source_info: callsite.location,
615 kind: StatementKind::Assign(Place::from(arg_tmp), box arg),
617 caller_body[callsite.bb].statements.push(stmt);
622 fn type_size_of<'tcx>(
624 param_env: ty::ParamEnv<'tcx>,
627 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
633 * Integrates blocks from the callee function into the calling function.
634 * Updates block indices, references to locals and other control flow
637 struct Integrator<'a, 'tcx> {
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,
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);
658 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
659 fn visit_local(&mut self,
662 _location: Location) {
663 if *local == RETURN_PLACE {
664 match self.destination {
666 base: PlaceBase::Local(l),
672 ref place => bug!("Return place is {:?}, not local", place)
675 let idx = local.index() - 1;
676 if idx < self.args.len() {
677 *local = self.args[idx];
680 *local = self.local_map[Local::new(idx - self.args.len())];
683 fn visit_place(&mut self,
684 place: &mut Place<'tcx>,
686 _location: Location) {
690 base: PlaceBase::Local(RETURN_PLACE),
693 // Return pointer; update the place itself
694 *place = self.destination.clone();
697 base: PlaceBase::Static(box Static {
698 kind: StaticKind::Promoted(_, substs),
703 let adjusted_substs = substs.subst(self.tcx, self.callsite.substs);
704 debug!("replacing substs {:?} with {:?}", substs, adjusted_substs);
705 *substs = adjusted_substs;
707 _ => self.super_place(place, _ctxt, _location)
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;
719 kind: &mut RetagKind,
720 place: &mut Place<'tcx>,
723 self.super_retag(kind, place, loc);
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;
732 fn visit_terminator_kind(&mut self,
733 kind: &mut TerminatorKind<'tcx>, loc: Location) {
734 self.super_terminator_kind(kind, loc);
737 TerminatorKind::GeneratorDrop |
738 TerminatorKind::Yield { .. } => bug!(),
739 TerminatorKind::Goto { ref mut target} => {
740 *target = self.update_target(*target);
742 TerminatorKind::SwitchInt { ref mut targets, .. } => {
744 *tgt = self.update_target(*tgt);
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;
758 TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
759 if let Some((_, ref mut tgt)) = *destination {
760 *tgt = self.update_target(*tgt);
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;
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;
780 TerminatorKind::Return => {
781 *kind = TerminatorKind::Goto { target: self.return_block };
783 TerminatorKind::Resume => {
784 if let Some(tgt) = self.cleanup_block {
785 *kind = TerminatorKind::Goto { target: tgt }
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);
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")
800 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
801 *scope = self.scope_map[*scope];