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