1use std::ops::{Range, RangeFrom};
4use std::{debug_assert_matches, iter};
5
6use rustc_abi::{ExternAbi, FieldIdx};
7use rustc_data_structures::thin_vec::ThinVec;
8use rustc_hir::attrs::{InlineAttr, OptimizeAttr};
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::DefId;
11use rustc_index::Idx;
12use rustc_index::bit_set::DenseBitSet;
13use rustc_middle::bug;
14use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
15use rustc_middle::mir::visit::*;
16use rustc_middle::mir::*;
17use rustc_middle::ty::{
18 self, Instance, InstanceKind, ShimKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt, Unnormalized,
19};
20use rustc_session::config::{DebugInfo, OptLevel};
21use rustc_span::Spanned;
22use tracing::{debug, instrument, trace, trace_span};
23
24use crate::cost_checker::{CostChecker, is_call_like};
25use crate::simplify::{UsedInStmtLocals, simplify_cfg};
26use crate::validate::validate_types;
27use crate::{PassPolicy, check_inline, util};
28
29pub(crate) mod cycle;
30
31const HISTORY_DEPTH_LIMIT: usize = 20;
32const TOP_DOWN_DEPTH_LIMIT: usize = 5;
33
34#[derive(Clone, Debug)]
35struct CallSite<'tcx> {
36 callee: Instance<'tcx>,
37 fn_sig: ty::PolyFnSig<'tcx>,
38 block: BasicBlock,
39 source_info: SourceInfo,
40}
41
42pub struct Inline;
45
46impl<'tcx> crate::MirPass<'tcx> for Inline {
47 fn policy(&self, sess: &rustc_session::Session) -> PassPolicy {
48 let enabled_by_default =
49 sess.opts.unstable_opts.inline_mir.unwrap_or_else(|| match sess.mir_opt_level() {
50 0 | 1 => false,
51 2 => {
52 (sess.opts.optimize == OptLevel::More
53 || sess.opts.optimize == OptLevel::Aggressive)
54 && sess.opts.incremental == None
55 }
56 _ => true,
57 });
58 PassPolicy::optimization(enabled_by_default)
59 }
60
61 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
62 let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
63 let _guard = span.enter();
64 if inline::<NormalInliner<'tcx>>(tcx, body) {
65 debug!("running simplify cfg on {:?}", body.source);
66 simplify_cfg(tcx, body);
67 }
68 }
69}
70
71pub struct ForceInline;
72
73impl ForceInline {
74 pub fn should_run_pass_for_callee<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
75 matches!(tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
76 }
77}
78
79impl<'tcx> crate::MirPass<'tcx> for ForceInline {
80 fn policy(&self, _sess: &rustc_session::Session) -> PassPolicy {
81 PassPolicy::Required
83 }
84
85 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
86 let span = trace_span!("force_inline", body = %tcx.def_path_str(body.source.def_id()));
87 let _guard = span.enter();
88 if inline::<ForceInliner<'tcx>>(tcx, body) {
89 debug!("running simplify cfg on {:?}", body.source);
90 simplify_cfg(tcx, body);
91 }
92 }
93}
94
95trait Inliner<'tcx> {
96 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self;
97
98 fn tcx(&self) -> TyCtxt<'tcx>;
99 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
100 fn history(&self) -> &[DefId];
101 fn caller_def_id(&self) -> DefId;
102
103 fn changed(self) -> bool;
105
106 fn should_inline_for_callee(&self, def_id: DefId) -> bool;
108
109 fn check_codegen_attributes_extra(
110 &self,
111 callee_attrs: &CodegenFnAttrs,
112 ) -> Result<(), &'static str>;
113
114 fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool;
115
116 fn check_callee_mir_body(
119 &self,
120 callsite: &CallSite<'tcx>,
121 callee_body: &Body<'tcx>,
122 callee_attrs: &CodegenFnAttrs,
123 ) -> Result<(), &'static str>;
124
125 fn on_inline_success(
127 &mut self,
128 callsite: &CallSite<'tcx>,
129 caller_body: &mut Body<'tcx>,
130 new_blocks: std::ops::Range<BasicBlock>,
131 );
132
133 fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str);
135}
136
137struct ForceInliner<'tcx> {
138 tcx: TyCtxt<'tcx>,
139 typing_env: ty::TypingEnv<'tcx>,
140 def_id: DefId,
142 history: Vec<DefId>,
148 changed: bool,
150}
151
152impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> {
153 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
154 Self { tcx, typing_env: body.typing_env(tcx), def_id, history: Vec::new(), changed: false }
155 }
156
157 fn tcx(&self) -> TyCtxt<'tcx> {
158 self.tcx
159 }
160
161 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
162 self.typing_env
163 }
164
165 fn history(&self) -> &[DefId] {
166 &self.history
167 }
168
169 fn caller_def_id(&self) -> DefId {
170 self.def_id
171 }
172
173 fn changed(self) -> bool {
174 self.changed
175 }
176
177 fn should_inline_for_callee(&self, def_id: DefId) -> bool {
178 ForceInline::should_run_pass_for_callee(self.tcx(), def_id)
179 }
180
181 fn check_codegen_attributes_extra(
182 &self,
183 callee_attrs: &CodegenFnAttrs,
184 ) -> Result<(), &'static str> {
185 debug_assert_matches!(callee_attrs.inline, InlineAttr::Force { .. });
186 Ok(())
187 }
188
189 fn check_caller_mir_body(&self, _: &Body<'tcx>) -> bool {
190 true
191 }
192
193 #[instrument(level = "debug", skip(self, callee_body))]
194 fn check_callee_mir_body(
195 &self,
196 _: &CallSite<'tcx>,
197 callee_body: &Body<'tcx>,
198 callee_attrs: &CodegenFnAttrs,
199 ) -> Result<(), &'static str> {
200 if callee_body.tainted_by_errors.is_some() {
201 return Err("body has errors");
202 }
203
204 let caller_attrs = self.tcx().codegen_fn_attrs(self.caller_def_id());
205 if callee_attrs.instruction_set != caller_attrs.instruction_set
206 && callee_body
207 .basic_blocks
208 .iter()
209 .any(|bb| matches!(bb.terminator().kind, TerminatorKind::InlineAsm { .. }))
210 {
211 Err("cannot move inline-asm across instruction sets")
217 } else {
218 Ok(())
219 }
220 }
221
222 fn on_inline_success(
223 &mut self,
224 callsite: &CallSite<'tcx>,
225 caller_body: &mut Body<'tcx>,
226 new_blocks: std::ops::Range<BasicBlock>,
227 ) {
228 self.changed = true;
229
230 self.history.push(callsite.callee.def_id());
231 process_blocks(self, caller_body, new_blocks);
232 self.history.pop();
233 }
234
235 fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str) {
236 let tcx = self.tcx();
237 let InlineAttr::Force { attr_span, reason: justification } =
238 tcx.codegen_instance_attrs(callsite.callee.def).inline
239 else {
240 bug!("called on item without required inlining");
241 };
242
243 let call_span = callsite.source_info.span;
244 let callee = tcx.def_path_str(callsite.callee.def_id());
245 tcx.dcx().emit_err(crate::diagnostics::ForceInlineFailure {
246 call_span,
247 attr_span,
248 caller_span: tcx.def_span(self.def_id),
249 caller: tcx.def_path_str(self.def_id),
250 callee_span: tcx.def_span(callsite.callee.def_id()),
251 callee: callee.clone(),
252 reason,
253 justification: justification
254 .map(|sym| crate::diagnostics::ForceInlineJustification { sym, callee }),
255 });
256 }
257}
258
259struct NormalInliner<'tcx> {
260 tcx: TyCtxt<'tcx>,
261 typing_env: ty::TypingEnv<'tcx>,
262 def_id: DefId,
264 history: Vec<DefId>,
270 top_down_counter: usize,
274 changed: bool,
276 caller_is_inline_forwarder: bool,
279}
280
281impl<'tcx> NormalInliner<'tcx> {
282 fn past_depth_limit(&self) -> bool {
283 self.history.len() > HISTORY_DEPTH_LIMIT || self.top_down_counter > TOP_DOWN_DEPTH_LIMIT
284 }
285}
286
287impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> {
288 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
289 let typing_env = body.typing_env(tcx);
290 let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
291
292 Self {
293 tcx,
294 typing_env,
295 def_id,
296 history: Vec::new(),
297 top_down_counter: 0,
298 changed: false,
299 caller_is_inline_forwarder: matches!(
300 codegen_fn_attrs.inline,
301 InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. }
302 ) && body_is_forwarder(body),
303 }
304 }
305
306 fn tcx(&self) -> TyCtxt<'tcx> {
307 self.tcx
308 }
309
310 fn caller_def_id(&self) -> DefId {
311 self.def_id
312 }
313
314 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
315 self.typing_env
316 }
317
318 fn history(&self) -> &[DefId] {
319 &self.history
320 }
321
322 fn changed(self) -> bool {
323 self.changed
324 }
325
326 fn should_inline_for_callee(&self, _: DefId) -> bool {
327 true
328 }
329
330 fn check_codegen_attributes_extra(
331 &self,
332 callee_attrs: &CodegenFnAttrs,
333 ) -> Result<(), &'static str> {
334 if self.past_depth_limit() && matches!(callee_attrs.inline, InlineAttr::None) {
335 Err("Past depth limit so not inspecting unmarked callee")
336 } else {
337 Ok(())
338 }
339 }
340
341 fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool {
342 if body.coroutine.is_some() {
346 return false;
347 }
348
349 true
350 }
351
352 #[instrument(level = "debug", skip(self, callee_body))]
353 fn check_callee_mir_body(
354 &self,
355 callsite: &CallSite<'tcx>,
356 callee_body: &Body<'tcx>,
357 callee_attrs: &CodegenFnAttrs,
358 ) -> Result<(), &'static str> {
359 let tcx = self.tcx();
360
361 if let Some(_) = callee_body.tainted_by_errors {
362 return Err("body has errors");
363 }
364
365 if self.past_depth_limit() && callee_body.basic_blocks.len() > 1 {
366 return Err("Not inlining multi-block body as we're past a depth limit");
367 }
368
369 let mut threshold = if self.caller_is_inline_forwarder || self.past_depth_limit() {
370 tcx.sess.opts.unstable_opts.inline_mir_forwarder_threshold.unwrap_or(30)
371 } else if tcx.cross_crate_inlinable(callsite.callee.def_id()) {
372 tcx.sess.opts.unstable_opts.inline_mir_hint_threshold.unwrap_or(100)
373 } else {
374 tcx.sess.opts.unstable_opts.inline_mir_threshold.unwrap_or(50)
375 };
376
377 if callee_body.basic_blocks.len() <= 3 {
381 threshold += threshold / 4;
382 }
383 debug!(" final inline threshold = {}", threshold);
384
385 let mut checker =
388 CostChecker::new(tcx, self.typing_env(), Some(callsite.callee), callee_body);
389
390 checker.add_function_level_costs();
391
392 let mut work_list = vec![START_BLOCK];
394 let mut visited = DenseBitSet::new_empty(callee_body.basic_blocks.len());
395 while let Some(bb) = work_list.pop() {
396 if !visited.insert(bb.index()) {
397 continue;
398 }
399
400 let blk = &callee_body.basic_blocks[bb];
401 checker.visit_basic_block_data(bb, blk);
402
403 let term = blk.terminator();
404 let caller_attrs = tcx.codegen_fn_attrs(self.caller_def_id());
405 if let TerminatorKind::Drop { ref place, target, unwind, replace: _, drop: _ } =
406 term.kind
407 {
408 work_list.push(target);
409
410 let ty = callsite.callee.instantiate_mir(
412 tcx,
413 ty::EarlyBinder::bind(tcx, place.ty(callee_body, tcx).ty),
414 );
415 if ty.needs_drop(tcx, self.typing_env())
416 && let UnwindAction::Cleanup(unwind) = unwind
417 {
418 work_list.push(unwind);
419 }
420 } else if callee_attrs.instruction_set != caller_attrs.instruction_set
421 && matches!(term.kind, TerminatorKind::InlineAsm { .. })
422 {
423 return Err("cannot move inline-asm across instruction sets");
429 } else if let TerminatorKind::TailCall { .. } = term.kind {
430 return Err("can't inline functions with tail calls");
433 } else {
434 work_list.extend(term.successors())
435 }
436 }
437
438 let cost = checker.cost();
443 if cost <= threshold {
444 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
445 Ok(())
446 } else {
447 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
448 Err("cost above threshold")
449 }
450 }
451
452 fn on_inline_success(
453 &mut self,
454 callsite: &CallSite<'tcx>,
455 caller_body: &mut Body<'tcx>,
456 new_blocks: std::ops::Range<BasicBlock>,
457 ) {
458 self.changed = true;
459
460 let new_calls_count = new_blocks
461 .clone()
462 .filter(|&bb| is_call_like(caller_body.basic_blocks[bb].terminator()))
463 .count();
464 if new_calls_count > 1 {
465 self.top_down_counter += 1;
466 }
467
468 self.history.push(callsite.callee.def_id());
469 process_blocks(self, caller_body, new_blocks);
470 self.history.pop();
471
472 if self.history.is_empty() {
473 self.top_down_counter = 0;
474 }
475 }
476
477 fn on_inline_failure(&self, _: &CallSite<'tcx>, _: &'static str) {}
478}
479
480fn inline<'tcx, T: Inliner<'tcx>>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
481 let def_id = body.source.def_id();
482
483 if !tcx.hir_body_owner_kind(def_id).is_fn_or_closure() {
485 return false;
486 }
487
488 let mut inliner = T::new(tcx, def_id, body);
489 if !inliner.check_caller_mir_body(body) {
490 return false;
491 }
492
493 let blocks = START_BLOCK..body.basic_blocks.next_index();
494 process_blocks(&mut inliner, body, blocks);
495 inliner.changed()
496}
497
498fn process_blocks<'tcx, I: Inliner<'tcx>>(
499 inliner: &mut I,
500 caller_body: &mut Body<'tcx>,
501 blocks: Range<BasicBlock>,
502) {
503 for bb in blocks {
504 let bb_data = &caller_body[bb];
505 if bb_data.is_cleanup {
506 continue;
507 }
508
509 let Some(callsite) = resolve_callsite(inliner, caller_body, bb, bb_data) else {
510 continue;
511 };
512
513 let span = trace_span!("process_blocks", %callsite.callee, ?bb);
514 let _guard = span.enter();
515
516 match try_inlining(inliner, caller_body, &callsite) {
517 Err(reason) => {
518 debug!("not-inlined {} [{}]", callsite.callee, reason);
519 inliner.on_inline_failure(&callsite, reason);
520 }
521 Ok(new_blocks) => {
522 debug!("inlined {}", callsite.callee);
523 inliner.on_inline_success(&callsite, caller_body, new_blocks);
524 }
525 }
526 }
527}
528
529fn resolve_callsite<'tcx, I: Inliner<'tcx>>(
530 inliner: &I,
531 caller_body: &Body<'tcx>,
532 bb: BasicBlock,
533 bb_data: &BasicBlockData<'tcx>,
534) -> Option<CallSite<'tcx>> {
535 let tcx = inliner.tcx();
536 let terminator = bb_data.terminator();
538
539 if let TerminatorKind::Call { ref func, fn_span, .. } = terminator.kind {
541 let func_ty = func.ty(caller_body, tcx);
542 if let ty::FnDef(def_id, args) = *func_ty.kind() {
543 if !inliner.should_inline_for_callee(def_id) {
544 debug!("not enabled");
545 return None;
546 }
547
548 let args = tcx
550 .try_normalize_erasing_regions(inliner.typing_env(), Unnormalized::new_wip(args))
551 .ok()?
552 .no_bound_vars()
553 .unwrap();
554 let mut callee =
555 Instance::try_resolve(tcx, inliner.typing_env(), def_id, args).ok().flatten()?;
556
557 if let InstanceKind::Virtual(..) = callee.def {
558 return None;
559 }
560 if let InstanceKind::Intrinsic(..) = callee.def {
561 let intrinsic = tcx.intrinsic(def_id).unwrap();
562 if intrinsic.must_be_overridden {
563 return None; }
565 if !tcx.sess.fallback_intrinsics.contains(&intrinsic.name) {
566 return None; }
568 debug!("callsite is fallback body: {def_id:?}");
570 callee = ty::Instance { def: ty::InstanceKind::Item(def_id), args: callee.args };
571 }
572
573 if inliner.history().contains(&callee.def_id()) {
574 return None;
575 }
576
577 let fn_sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip();
578
579 if let InstanceKind::Item(instance_def_id) = callee.def
582 && tcx.def_kind(instance_def_id) == DefKind::AssocFn
583 && let instance_fn_sig = tcx.fn_sig(instance_def_id).skip_binder()
584 && instance_fn_sig.abi() != fn_sig.abi()
585 {
586 return None;
587 }
588
589 let source_info = SourceInfo { span: fn_span, ..terminator.source_info };
590
591 return Some(CallSite { callee, fn_sig, block: bb, source_info });
592 }
593 }
594
595 None
596}
597
598fn try_inlining<'tcx, I: Inliner<'tcx>>(
602 inliner: &I,
603 caller_body: &mut Body<'tcx>,
604 callsite: &CallSite<'tcx>,
605) -> Result<std::ops::Range<BasicBlock>, &'static str> {
606 let tcx = inliner.tcx();
607 check_mir_is_available(inliner, caller_body, callsite.callee)?;
608
609 let callee_attrs = tcx.codegen_instance_attrs(callsite.callee.def);
610 let callee_attrs = callee_attrs.as_ref();
611 check_inline::is_inline_valid_on_fn(tcx, callsite.callee.def_id())?;
612 check_codegen_attributes(inliner, callsite, callee_attrs)?;
613
614 let terminator = caller_body[callsite.block].terminator.as_ref().unwrap();
615 let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() };
616 let destination_ty = destination.ty(&caller_body.local_decls, tcx).ty;
617 for arg in args {
618 if !arg.node.ty(&caller_body.local_decls, tcx).is_sized(tcx, inliner.typing_env()) {
619 return Err("call has unsized argument");
622 }
623 }
624
625 let callee_body = try_instance_mir(tcx, callsite.callee.def)?;
626 check_inline::is_inline_valid_on_body(tcx, callee_body)?;
627 inliner.check_callee_mir_body(callsite, callee_body, callee_attrs)?;
628
629 let Ok(callee_body) = callsite.callee.try_instantiate_mir_and_normalize_erasing_regions(
630 tcx,
631 inliner.typing_env(),
632 ty::EarlyBinder::bind(tcx, callee_body.clone()),
633 ) else {
634 debug!("failed to normalize callee body");
635 return Err("implementation limitation -- could not normalize callee body");
636 };
637
638 if !validate_types(tcx, inliner.typing_env(), &callee_body, caller_body).is_empty() {
641 debug!("failed to validate callee body");
642 return Err("implementation limitation -- callee body failed validation");
643 }
644
645 let output_type = callee_body.return_ty();
649 if !util::sub_types(tcx, inliner.typing_env(), output_type, destination_ty) {
650 trace!(?output_type, ?destination_ty);
651 return Err("implementation limitation -- return type mismatch");
652 }
653 if callsite.fn_sig.abi() == ExternAbi::RustCall {
654 let (self_arg, arg_tuple) = match &args[..] {
655 [arg_tuple] => (None, arg_tuple),
656 [self_arg, arg_tuple] => (Some(self_arg), arg_tuple),
657 _ => bug!("Expected `rust-call` to have 1 or 2 args"),
658 };
659
660 let self_arg_ty = self_arg.map(|self_arg| self_arg.node.ty(&caller_body.local_decls, tcx));
661
662 let arg_tuple_ty = arg_tuple.node.ty(&caller_body.local_decls, tcx);
663 let arg_tys = if callee_body.spread_arg.is_some() {
664 std::slice::from_ref(&arg_tuple_ty)
665 } else {
666 let ty::Tuple(arg_tuple_tys) = *arg_tuple_ty.kind() else {
667 bug!("Closure arguments are not passed as a tuple");
668 };
669 arg_tuple_tys.as_slice()
670 };
671
672 for (arg_ty, input) in
673 self_arg_ty.into_iter().chain(arg_tys.iter().copied()).zip(callee_body.args_iter())
674 {
675 let input_type = callee_body.local_decls[input].ty;
676 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
677 trace!(?arg_ty, ?input_type);
678 debug!("failed to normalize tuple argument type");
679 return Err("implementation limitation");
680 }
681 }
682 } else {
683 for (arg, input) in args.iter().zip(callee_body.args_iter()) {
684 let input_type = callee_body.local_decls[input].ty;
685 let arg_ty = arg.node.ty(&caller_body.local_decls, tcx);
686 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
687 trace!(?arg_ty, ?input_type);
688 debug!("failed to normalize argument type");
689 return Err("implementation limitation -- arg mismatch");
690 }
691 }
692 }
693
694 let old_blocks = caller_body.basic_blocks.next_index();
695 inline_call(inliner, caller_body, callsite, callee_body);
696 let new_blocks = old_blocks..caller_body.basic_blocks.next_index();
697
698 Ok(new_blocks)
699}
700
701fn check_mir_is_available<'tcx, I: Inliner<'tcx>>(
702 inliner: &I,
703 caller_body: &Body<'tcx>,
704 callee: Instance<'tcx>,
705) -> Result<(), &'static str> {
706 let caller_def_id = caller_body.source.def_id();
707 let callee_def_id = callee.def_id();
708 if callee_def_id == caller_def_id {
709 return Err("self-recursion");
710 }
711
712 match callee.def {
713 InstanceKind::Item(_) => {
714 if !inliner.tcx().is_mir_available(callee_def_id) {
718 debug!("item MIR unavailable");
719 return Err("implementation limitation -- MIR unavailable");
720 }
721 }
722 InstanceKind::Intrinsic(_) | InstanceKind::LlvmIntrinsic(_) | InstanceKind::Virtual(..) => {
724 debug!("instance without MIR (intrinsic / virtual)");
725 return Err("implementation limitation -- cannot inline intrinsic");
726 }
727
728 InstanceKind::Shim(ShimKind::DropGlue(_, Some(ty)))
734 if ty.has_type_flags(TypeFlags::HAS_CT_PARAM) =>
735 {
736 debug!("still needs substitution");
737 return Err("implementation limitation -- HACK for dropping polymorphic type");
738 }
739 InstanceKind::Shim(ShimKind::AsyncDropGlue(_, ty))
740 | InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(_, ty)) => {
741 return if ty.still_further_specializable() {
742 Err("still needs substitution")
743 } else {
744 Ok(())
745 };
746 }
747 InstanceKind::Shim(ShimKind::FutureDropPoll(_, ty, ty2)) => {
748 return if ty.still_further_specializable() || ty2.still_further_specializable() {
749 Err("still needs substitution")
750 } else {
751 Ok(())
752 };
753 }
754
755 InstanceKind::Shim(ShimKind::VTable(_))
760 | InstanceKind::Shim(ShimKind::Reify(..))
761 | InstanceKind::Shim(ShimKind::FnPtr(..))
762 | InstanceKind::Shim(ShimKind::ClosureOnce { .. })
763 | InstanceKind::Shim(ShimKind::ConstructCoroutineInClosure { .. })
764 | InstanceKind::Shim(ShimKind::DropGlue(..))
765 | InstanceKind::Shim(ShimKind::Clone(..))
766 | InstanceKind::Shim(ShimKind::ThreadLocal(..))
767 | InstanceKind::Shim(ShimKind::FnPtrAddr(..)) => return Ok(()),
768 }
769
770 if inliner.tcx().is_constructor(callee_def_id) {
771 trace!("constructors always have MIR");
772 return Ok(());
774 }
775
776 if let Some(callee_def_id) = callee_def_id.as_local()
777 && !inliner
778 .tcx()
779 .is_lang_item(inliner.tcx().parent(caller_def_id), rustc_hir::LangItem::FnOnce)
780 {
781 let Some(cyclic_callees) = inliner.tcx().mir_callgraph_cyclic(caller_def_id.expect_local())
784 else {
785 return Err("call graph cycle detection bailed due to recursion limit");
786 };
787 if cyclic_callees.contains(&callee_def_id) {
788 debug!("query cycle avoidance");
789 return Err("caller might be reachable from callee");
790 }
791
792 Ok(())
793 } else {
794 trace!("functions from other crates always have MIR");
799 Ok(())
800 }
801}
802
803fn check_codegen_attributes<'tcx, I: Inliner<'tcx>>(
806 inliner: &I,
807 callsite: &CallSite<'tcx>,
808 callee_attrs: &CodegenFnAttrs,
809) -> Result<(), &'static str> {
810 let tcx = inliner.tcx();
811 if let InlineAttr::Never = callee_attrs.inline {
812 return Err("never inline attribute");
813 }
814
815 if let OptimizeAttr::DoNotOptimize = callee_attrs.optimize {
816 return Err("has DoNotOptimize attribute");
817 }
818
819 inliner.check_codegen_attributes_extra(callee_attrs)?;
820
821 let is_generic = callsite.callee.args.non_erasable_generics().next().is_some();
824 if !is_generic && !tcx.cross_crate_inlinable(callsite.callee.def_id()) {
825 return Err("not exported");
826 }
827
828 let codegen_fn_attrs = tcx.codegen_fn_attrs(inliner.caller_def_id());
829 if callee_attrs.sanitizers != codegen_fn_attrs.sanitizers {
830 return Err("incompatible sanitizer set");
831 }
832
833 if callee_attrs.instruction_set.is_some()
837 && callee_attrs.instruction_set != codegen_fn_attrs.instruction_set
838 {
839 return Err("incompatible instruction set");
840 }
841
842 let callee_feature_names = callee_attrs.target_features.iter().map(|f| f.name);
843 let this_feature_names = codegen_fn_attrs.target_features.iter().map(|f| f.name);
844 if callee_feature_names.ne(this_feature_names) {
845 return Err("incompatible target features");
851 }
852
853 Ok(())
854}
855
856fn inline_call<'tcx, I: Inliner<'tcx>>(
857 inliner: &I,
858 caller_body: &mut Body<'tcx>,
859 callsite: &CallSite<'tcx>,
860 mut callee_body: Body<'tcx>,
861) {
862 let tcx = inliner.tcx();
863 let terminator = caller_body[callsite.block].terminator.take().unwrap();
864 let TerminatorKind::Call { func, args, destination, unwind, target, .. } = terminator.kind
865 else {
866 bug!("unexpected terminator kind {:?}", terminator.kind);
867 };
868
869 let return_block = if let Some(block) = target {
870 let data = BasicBlockData::new(
873 Some(Terminator {
874 source_info: terminator.source_info,
875 kind: TerminatorKind::Goto { target: block },
876 attributes: ThinVec::new(),
877 }),
878 caller_body[block].is_cleanup,
879 );
880 Some(caller_body.basic_blocks_mut().push(data))
881 } else {
882 None
883 };
884
885 fn dest_needs_borrow(place: Place<'_>) -> bool {
891 for elem in place.projection.iter() {
892 match elem {
893 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
894 _ => {}
895 }
896 }
897
898 false
899 }
900
901 let dest = if dest_needs_borrow(destination) {
902 trace!("creating temp for return destination");
903 let dest = Rvalue::Ref(
904 tcx.lifetimes.re_erased,
905 BorrowKind::Mut { kind: MutBorrowKind::Default },
906 destination,
907 );
908 let dest_ty = dest.ty(caller_body, tcx);
909 let temp = Place::from(new_call_temp(caller_body, callsite, dest_ty, return_block));
910 caller_body[callsite.block].statements.push(Statement::new(
911 callsite.source_info,
912 StatementKind::Assign(Box::new((temp, dest))),
913 ));
914 tcx.mk_place_deref(temp)
915 } else {
916 destination
917 };
918
919 let (remap_destination, destination_local) = if let Some(d) = dest.as_local() {
922 (false, d)
923 } else {
924 (
925 true,
926 new_call_temp(caller_body, callsite, destination.ty(caller_body, tcx).ty, return_block),
927 )
928 };
929
930 let args = make_call_args(inliner, args, callsite, caller_body, &callee_body, return_block);
932
933 let mut integrator = Integrator {
934 args: &args,
935 new_locals: caller_body.local_decls.next_index()..,
936 new_scopes: caller_body.source_scopes.next_index()..,
937 new_blocks: caller_body.basic_blocks.next_index()..,
938 destination: destination_local,
939 callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
940 callsite,
941 cleanup_block: unwind,
942 in_cleanup_block: false,
943 return_block,
944 tcx,
945 always_live_locals: UsedInStmtLocals::new(&callee_body).locals,
946 };
947
948 integrator.visit_body(&mut callee_body);
951
952 for local in callee_body.vars_and_temps_iter() {
955 if integrator.always_live_locals.contains(local) {
956 let new_local = integrator.map_local(local);
957 caller_body[callsite.block]
958 .statements
959 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(new_local)));
960 }
961 }
962 if let Some(block) = return_block {
963 let mut n = 0;
966 if remap_destination {
967 caller_body[block].statements.push(Statement::new(
968 callsite.source_info,
969 StatementKind::Assign(Box::new((
970 dest,
971 Rvalue::Use(Operand::Move(destination_local.into()), WithRetag::Yes),
972 ))),
973 ));
974 n += 1;
975 }
976 for local in callee_body.vars_and_temps_iter().rev() {
977 if integrator.always_live_locals.contains(local) {
978 let new_local = integrator.map_local(local);
979 caller_body[block].statements.push(Statement::new(
980 callsite.source_info,
981 StatementKind::StorageDead(new_local),
982 ));
983 n += 1;
984 }
985 }
986 caller_body[block].statements.rotate_right(n);
987 }
988
989 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
991 caller_body.source_scopes.append(&mut callee_body.source_scopes);
992
993 if tcx
995 .sess
996 .opts
997 .unstable_opts
998 .inline_mir_preserve_debug
999 .unwrap_or(tcx.sess.opts.debuginfo == DebugInfo::Full)
1000 {
1001 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
1005 } else {
1006 for bb in callee_body.basic_blocks_mut() {
1007 bb.drop_debuginfo();
1008 }
1009 }
1010 caller_body.basic_blocks_mut().append(callee_body.basic_blocks_mut());
1011
1012 caller_body[callsite.block].terminator = Some(Terminator {
1013 source_info: callsite.source_info,
1014 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
1015 attributes: ThinVec::new(),
1016 });
1017
1018 caller_body.required_consts.as_mut().unwrap().extend(
1022 callee_body.required_consts().into_iter().filter(|ct| ct.const_.is_required_const()),
1023 );
1024 let callee_item = MentionedItem::Fn(func.ty(caller_body, tcx));
1032 let caller_mentioned_items = caller_body.mentioned_items.as_mut().unwrap();
1033 if let Some(idx) = caller_mentioned_items.iter().position(|item| item.node == callee_item) {
1034 caller_mentioned_items.remove(idx);
1036 caller_mentioned_items.extend(callee_body.mentioned_items());
1037 } else {
1038 }
1042}
1043
1044fn make_call_args<'tcx, I: Inliner<'tcx>>(
1045 inliner: &I,
1046 args: Box<[Spanned<Operand<'tcx>>]>,
1047 callsite: &CallSite<'tcx>,
1048 caller_body: &mut Body<'tcx>,
1049 callee_body: &Body<'tcx>,
1050 return_block: Option<BasicBlock>,
1051) -> Box<[Local]> {
1052 let tcx = inliner.tcx();
1053
1054 if callsite.fn_sig.abi() == ExternAbi::RustCall && callee_body.spread_arg.is_none() {
1078 let mut args = args.into_iter();
1079 let self_ = create_temp_if_necessary(
1080 inliner,
1081 args.next().unwrap().node,
1082 callsite,
1083 caller_body,
1084 return_block,
1085 );
1086 let tuple = create_temp_if_necessary(
1087 inliner,
1088 args.next().unwrap().node,
1089 callsite,
1090 caller_body,
1091 return_block,
1092 );
1093 assert!(args.next().is_none());
1094
1095 let tuple = Place::from(tuple);
1096 let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
1097 bug!("Closure arguments are not passed as a tuple");
1098 };
1099
1100 let closure_ref_arg = iter::once(self_);
1102
1103 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
1105 let tuple_field = Operand::Move(tcx.mk_place_field(tuple, FieldIdx::new(i), ty));
1107
1108 create_temp_if_necessary(inliner, tuple_field, callsite, caller_body, return_block)
1110 });
1111
1112 closure_ref_arg.chain(tuple_tmp_args).collect()
1113 } else {
1114 args.into_iter()
1115 .map(|a| create_temp_if_necessary(inliner, a.node, callsite, caller_body, return_block))
1116 .collect()
1117 }
1118}
1119
1120fn create_temp_if_necessary<'tcx, I: Inliner<'tcx>>(
1123 inliner: &I,
1124 arg: Operand<'tcx>,
1125 callsite: &CallSite<'tcx>,
1126 caller_body: &mut Body<'tcx>,
1127 return_block: Option<BasicBlock>,
1128) -> Local {
1129 if let Operand::Move(place) = &arg
1131 && let Some(local) = place.as_local()
1132 && caller_body.local_kind(local) == LocalKind::Temp
1133 {
1134 return local;
1135 }
1136
1137 trace!("creating temp for argument {:?}", arg);
1139 let arg_ty = arg.ty(caller_body, inliner.tcx());
1140 let local = new_call_temp(caller_body, callsite, arg_ty, return_block);
1141 caller_body[callsite.block].statements.push(Statement::new(
1142 callsite.source_info,
1143 StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg, WithRetag::Yes)))),
1144 ));
1145 local
1146}
1147
1148fn new_call_temp<'tcx>(
1150 caller_body: &mut Body<'tcx>,
1151 callsite: &CallSite<'tcx>,
1152 ty: Ty<'tcx>,
1153 return_block: Option<BasicBlock>,
1154) -> Local {
1155 let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
1156
1157 caller_body[callsite.block]
1158 .statements
1159 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(local)));
1160
1161 if let Some(block) = return_block {
1162 caller_body[block]
1163 .statements
1164 .insert(0, Statement::new(callsite.source_info, StatementKind::StorageDead(local)));
1165 }
1166
1167 local
1168}
1169
1170struct Integrator<'a, 'tcx> {
1178 args: &'a [Local],
1179 new_locals: RangeFrom<Local>,
1180 new_scopes: RangeFrom<SourceScope>,
1181 new_blocks: RangeFrom<BasicBlock>,
1182 destination: Local,
1183 callsite_scope: SourceScopeData<'tcx>,
1184 callsite: &'a CallSite<'tcx>,
1185 cleanup_block: UnwindAction,
1186 in_cleanup_block: bool,
1187 return_block: Option<BasicBlock>,
1188 tcx: TyCtxt<'tcx>,
1189 always_live_locals: DenseBitSet<Local>,
1190}
1191
1192impl Integrator<'_, '_> {
1193 fn map_local(&self, local: Local) -> Local {
1194 let new = if local == RETURN_PLACE {
1195 self.destination
1196 } else {
1197 let idx = local.index() - 1;
1198 if idx < self.args.len() {
1199 self.args[idx]
1200 } else {
1201 self.new_locals.start + (idx - self.args.len())
1202 }
1203 };
1204 trace!("mapping local `{:?}` to `{:?}`", local, new);
1205 new
1206 }
1207
1208 fn map_scope(&self, scope: SourceScope) -> SourceScope {
1209 let new = self.new_scopes.start + scope.index();
1210 trace!("mapping scope `{:?}` to `{:?}`", scope, new);
1211 new
1212 }
1213
1214 fn map_block(&self, block: BasicBlock) -> BasicBlock {
1215 let new = self.new_blocks.start + block.index();
1216 trace!("mapping block `{:?}` to `{:?}`", block, new);
1217 new
1218 }
1219
1220 fn map_unwind(&self, unwind: UnwindAction) -> UnwindAction {
1221 if self.in_cleanup_block {
1222 match unwind {
1223 UnwindAction::Cleanup(_) | UnwindAction::Continue => {
1224 bug!("cleanup on cleanup block");
1225 }
1226 UnwindAction::Unreachable | UnwindAction::Terminate(_) => return unwind,
1227 }
1228 }
1229
1230 match unwind {
1231 UnwindAction::Unreachable | UnwindAction::Terminate(_) => unwind,
1232 UnwindAction::Cleanup(target) => UnwindAction::Cleanup(self.map_block(target)),
1233 UnwindAction::Continue => self.cleanup_block,
1235 }
1236 }
1237}
1238
1239impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
1240 fn tcx(&self) -> TyCtxt<'tcx> {
1241 self.tcx
1242 }
1243
1244 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
1245 *local = self.map_local(*local);
1246 }
1247
1248 fn visit_source_scope_data(&mut self, scope_data: &mut SourceScopeData<'tcx>) {
1249 self.super_source_scope_data(scope_data);
1250 if scope_data.parent_scope.is_none() {
1251 scope_data.parent_scope = Some(self.callsite.source_info.scope);
1254 assert_eq!(scope_data.inlined_parent_scope, None);
1255 scope_data.inlined_parent_scope = if self.callsite_scope.inlined.is_some() {
1256 Some(self.callsite.source_info.scope)
1257 } else {
1258 self.callsite_scope.inlined_parent_scope
1259 };
1260
1261 assert_eq!(scope_data.inlined, None);
1263 scope_data.inlined = Some((self.callsite.callee, self.callsite.source_info.span));
1264 } else if scope_data.inlined_parent_scope.is_none() {
1265 scope_data.inlined_parent_scope = Some(self.map_scope(OUTERMOST_SOURCE_SCOPE));
1267 }
1268 }
1269
1270 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
1271 *scope = self.map_scope(*scope);
1272 }
1273
1274 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
1275 self.in_cleanup_block = data.is_cleanup;
1276 self.super_basic_block_data(block, data);
1277 self.in_cleanup_block = false;
1278 }
1279
1280 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1281 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
1282 statement.kind
1283 {
1284 self.always_live_locals.remove(local);
1285 }
1286 self.super_statement(statement, location);
1287 }
1288
1289 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
1290 if !matches!(terminator.kind, TerminatorKind::Return) {
1293 self.super_terminator(terminator, loc);
1294 } else {
1295 self.visit_source_info(&mut terminator.source_info);
1296 }
1297
1298 match terminator.kind {
1299 TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => bug!(),
1300 TerminatorKind::Goto { ref mut target } => {
1301 *target = self.map_block(*target);
1302 }
1303 TerminatorKind::SwitchInt { ref mut targets, .. } => {
1304 for tgt in targets.all_targets_mut() {
1305 *tgt = self.map_block(*tgt);
1306 }
1307 }
1308 TerminatorKind::Drop { ref mut target, ref mut unwind, .. } => {
1309 *target = self.map_block(*target);
1310 *unwind = self.map_unwind(*unwind);
1311 }
1312 TerminatorKind::TailCall { .. } => {
1313 unreachable!()
1315 }
1316 TerminatorKind::Call { ref mut target, ref mut unwind, .. } => {
1317 if let Some(ref mut tgt) = *target {
1318 *tgt = self.map_block(*tgt);
1319 }
1320 *unwind = self.map_unwind(*unwind);
1321 }
1322 TerminatorKind::Assert { ref mut target, ref mut unwind, .. } => {
1323 *target = self.map_block(*target);
1324 *unwind = self.map_unwind(*unwind);
1325 }
1326 TerminatorKind::Return => {
1327 terminator.kind = if let Some(tgt) = self.return_block {
1328 TerminatorKind::Goto { target: tgt }
1329 } else {
1330 TerminatorKind::Unreachable
1331 }
1332 }
1333 TerminatorKind::UnwindResume => {
1334 terminator.kind = match self.cleanup_block {
1335 UnwindAction::Cleanup(tgt) => TerminatorKind::Goto { target: tgt },
1336 UnwindAction::Continue => TerminatorKind::UnwindResume,
1337 UnwindAction::Unreachable => TerminatorKind::Unreachable,
1338 UnwindAction::Terminate(reason) => TerminatorKind::UnwindTerminate(reason),
1339 };
1340 }
1341 TerminatorKind::UnwindTerminate(_) => {}
1342 TerminatorKind::Unreachable => {}
1343 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
1344 *real_target = self.map_block(*real_target);
1345 *imaginary_target = self.map_block(*imaginary_target);
1346 }
1347 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
1348 {
1350 bug!("False unwinds should have been removed before inlining")
1351 }
1352 TerminatorKind::InlineAsm { ref mut targets, ref mut unwind, .. } => {
1353 for tgt in targets.iter_mut() {
1354 *tgt = self.map_block(*tgt);
1355 }
1356 *unwind = self.map_unwind(*unwind);
1357 }
1358 }
1359 }
1360}
1361
1362#[instrument(skip(tcx), level = "debug")]
1363fn try_instance_mir<'tcx>(
1364 tcx: TyCtxt<'tcx>,
1365 instance: InstanceKind<'tcx>,
1366) -> Result<&'tcx Body<'tcx>, &'static str> {
1367 if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, Some(ty)))
1368 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(_, ty)) = instance
1369 && let ty::Adt(def, args) = ty.kind()
1370 {
1371 let fields = def.all_fields();
1372 for field in fields {
1373 let field_ty = field.ty(tcx, args);
1374 if field_ty.has_param() && field_ty.has_aliases() {
1375 return Err("cannot build drop shim for polymorphic type");
1376 }
1377 }
1378 }
1379 Ok(tcx.instance_mir(instance))
1380}
1381
1382fn body_is_forwarder(body: &Body<'_>) -> bool {
1383 let TerminatorKind::Call { target, .. } = body.basic_blocks[START_BLOCK].terminator().kind
1384 else {
1385 return false;
1386 };
1387 if let Some(target) = target {
1388 let TerminatorKind::Return = body.basic_blocks[target].terminator().kind else {
1389 return false;
1390 };
1391 }
1392
1393 let max_blocks = if !body.is_polymorphic {
1394 2
1395 } else if target.is_none() {
1396 3
1397 } else {
1398 4
1399 };
1400 if body.basic_blocks.len() > max_blocks {
1401 return false;
1402 }
1403
1404 body.basic_blocks.iter_enumerated().all(|(bb, bb_data)| {
1405 bb == START_BLOCK
1406 || matches!(
1407 bb_data.terminator().kind,
1408 TerminatorKind::Return
1409 | TerminatorKind::Drop { .. }
1410 | TerminatorKind::UnwindResume
1411 | TerminatorKind::UnwindTerminate(_)
1412 )
1413 })
1414}