Skip to main content

rustc_mir_transform/
inline.rs

1//! Inlining pass for MIR functions.
2
3use std::ops::{Range, RangeFrom};
4use std::{debug_assert_matches, iter};
5
6use rustc_abi::{ExternAbi, FieldIdx};
7use rustc_hir::attrs::{InlineAttr, OptimizeAttr};
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::DefId;
10use rustc_index::Idx;
11use rustc_index::bit_set::DenseBitSet;
12use rustc_middle::bug;
13use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
14use rustc_middle::mir::visit::*;
15use rustc_middle::mir::*;
16use rustc_middle::ty::{self, Instance, InstanceKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt};
17use rustc_session::config::{DebugInfo, OptLevel};
18use rustc_span::Spanned;
19use tracing::{debug, instrument, trace, trace_span};
20
21use crate::cost_checker::{CostChecker, is_call_like};
22use crate::simplify::{UsedInStmtLocals, simplify_cfg};
23use crate::validate::validate_types;
24use crate::{check_inline, util};
25
26pub(crate) mod cycle;
27
28const HISTORY_DEPTH_LIMIT: usize = 20;
29const TOP_DOWN_DEPTH_LIMIT: usize = 5;
30
31#[derive(Clone, Debug)]
32struct CallSite<'tcx> {
33    callee: Instance<'tcx>,
34    fn_sig: ty::PolyFnSig<'tcx>,
35    block: BasicBlock,
36    source_info: SourceInfo,
37}
38
39// Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
40// by custom rustc drivers, running all the steps by themselves. See #114628.
41pub struct Inline;
42
43impl<'tcx> crate::MirPass<'tcx> for Inline {
44    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
45        if let Some(enabled) = sess.opts.unstable_opts.inline_mir {
46            return enabled;
47        }
48
49        match sess.mir_opt_level() {
50            0 | 1 => false,
51            2 => {
52                (sess.opts.optimize == OptLevel::More || sess.opts.optimize == OptLevel::Aggressive)
53                    && sess.opts.incremental == None
54            }
55            _ => true,
56        }
57    }
58
59    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
60        let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
61        let _guard = span.enter();
62        if inline::<NormalInliner<'tcx>>(tcx, body) {
63            debug!("running simplify cfg on {:?}", body.source);
64            simplify_cfg(tcx, body);
65        }
66    }
67
68    fn is_required(&self) -> bool {
69        false
70    }
71}
72
73pub struct ForceInline;
74
75impl ForceInline {
76    pub fn should_run_pass_for_callee<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
77        matches!(tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
78    }
79}
80
81impl<'tcx> crate::MirPass<'tcx> for ForceInline {
82    fn is_enabled(&self, _: &rustc_session::Session) -> bool {
83        true
84    }
85
86    fn can_be_overridden(&self) -> bool {
87        false
88    }
89
90    fn is_required(&self) -> bool {
91        true
92    }
93
94    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
95        let span = trace_span!("force_inline", body = %tcx.def_path_str(body.source.def_id()));
96        let _guard = span.enter();
97        if inline::<ForceInliner<'tcx>>(tcx, body) {
98            debug!("running simplify cfg on {:?}", body.source);
99            simplify_cfg(tcx, body);
100        }
101    }
102}
103
104trait Inliner<'tcx> {
105    fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self;
106
107    fn tcx(&self) -> TyCtxt<'tcx>;
108    fn typing_env(&self) -> ty::TypingEnv<'tcx>;
109    fn history(&self) -> &[DefId];
110    fn caller_def_id(&self) -> DefId;
111
112    /// Has the caller body been changed?
113    fn changed(self) -> bool;
114
115    /// Should inlining happen for a given callee?
116    fn should_inline_for_callee(&self, def_id: DefId) -> bool;
117
118    fn check_codegen_attributes_extra(
119        &self,
120        callee_attrs: &CodegenFnAttrs,
121    ) -> Result<(), &'static str>;
122
123    fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool;
124
125    /// Returns inlining decision that is based on the examination of callee MIR body.
126    /// Assumes that codegen attributes have been checked for compatibility already.
127    fn check_callee_mir_body(
128        &self,
129        callsite: &CallSite<'tcx>,
130        callee_body: &Body<'tcx>,
131        callee_attrs: &CodegenFnAttrs,
132    ) -> Result<(), &'static str>;
133
134    /// Called when inlining succeeds.
135    fn on_inline_success(
136        &mut self,
137        callsite: &CallSite<'tcx>,
138        caller_body: &mut Body<'tcx>,
139        new_blocks: std::ops::Range<BasicBlock>,
140    );
141
142    /// Called when inlining failed or was not performed.
143    fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str);
144}
145
146struct ForceInliner<'tcx> {
147    tcx: TyCtxt<'tcx>,
148    typing_env: ty::TypingEnv<'tcx>,
149    /// `DefId` of caller.
150    def_id: DefId,
151    /// Stack of inlined instances.
152    /// We only check the `DefId` and not the args because we want to
153    /// avoid inlining cases of polymorphic recursion.
154    /// The number of `DefId`s is finite, so checking history is enough
155    /// to ensure that we do not loop endlessly while inlining.
156    history: Vec<DefId>,
157    /// Indicates that the caller body has been modified.
158    changed: bool,
159}
160
161impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> {
162    fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
163        Self { tcx, typing_env: body.typing_env(tcx), def_id, history: Vec::new(), changed: false }
164    }
165
166    fn tcx(&self) -> TyCtxt<'tcx> {
167        self.tcx
168    }
169
170    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
171        self.typing_env
172    }
173
174    fn history(&self) -> &[DefId] {
175        &self.history
176    }
177
178    fn caller_def_id(&self) -> DefId {
179        self.def_id
180    }
181
182    fn changed(self) -> bool {
183        self.changed
184    }
185
186    fn should_inline_for_callee(&self, def_id: DefId) -> bool {
187        ForceInline::should_run_pass_for_callee(self.tcx(), def_id)
188    }
189
190    fn check_codegen_attributes_extra(
191        &self,
192        callee_attrs: &CodegenFnAttrs,
193    ) -> Result<(), &'static str> {
194        debug_assert_matches!(callee_attrs.inline, InlineAttr::Force { .. });
195        Ok(())
196    }
197
198    fn check_caller_mir_body(&self, _: &Body<'tcx>) -> bool {
199        true
200    }
201
202    #[instrument(level = "debug", skip(self, callee_body))]
203    fn check_callee_mir_body(
204        &self,
205        _: &CallSite<'tcx>,
206        callee_body: &Body<'tcx>,
207        callee_attrs: &CodegenFnAttrs,
208    ) -> Result<(), &'static str> {
209        if callee_body.tainted_by_errors.is_some() {
210            return Err("body has errors");
211        }
212
213        let caller_attrs = self.tcx().codegen_fn_attrs(self.caller_def_id());
214        if callee_attrs.instruction_set != caller_attrs.instruction_set
215            && callee_body
216                .basic_blocks
217                .iter()
218                .any(|bb| matches!(bb.terminator().kind, TerminatorKind::InlineAsm { .. }))
219        {
220            // During the attribute checking stage we allow a callee with no
221            // instruction_set assigned to count as compatible with a function that does
222            // assign one. However, during this stage we require an exact match when any
223            // inline-asm is detected. LLVM will still possibly do an inline later on
224            // if the no-attribute function ends up with the same instruction set anyway.
225            Err("cannot move inline-asm across instruction sets")
226        } else {
227            Ok(())
228        }
229    }
230
231    fn on_inline_success(
232        &mut self,
233        callsite: &CallSite<'tcx>,
234        caller_body: &mut Body<'tcx>,
235        new_blocks: std::ops::Range<BasicBlock>,
236    ) {
237        self.changed = true;
238
239        self.history.push(callsite.callee.def_id());
240        process_blocks(self, caller_body, new_blocks);
241        self.history.pop();
242    }
243
244    fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str) {
245        let tcx = self.tcx();
246        let InlineAttr::Force { attr_span, reason: justification } =
247            tcx.codegen_instance_attrs(callsite.callee.def).inline
248        else {
249            bug!("called on item without required inlining");
250        };
251
252        let call_span = callsite.source_info.span;
253        let callee = tcx.def_path_str(callsite.callee.def_id());
254        tcx.dcx().emit_err(crate::errors::ForceInlineFailure {
255            call_span,
256            attr_span,
257            caller_span: tcx.def_span(self.def_id),
258            caller: tcx.def_path_str(self.def_id),
259            callee_span: tcx.def_span(callsite.callee.def_id()),
260            callee: callee.clone(),
261            reason,
262            justification: justification
263                .map(|sym| crate::errors::ForceInlineJustification { sym, callee }),
264        });
265    }
266}
267
268struct NormalInliner<'tcx> {
269    tcx: TyCtxt<'tcx>,
270    typing_env: ty::TypingEnv<'tcx>,
271    /// `DefId` of caller.
272    def_id: DefId,
273    /// Stack of inlined instances.
274    /// We only check the `DefId` and not the args because we want to
275    /// avoid inlining cases of polymorphic recursion.
276    /// The number of `DefId`s is finite, so checking history is enough
277    /// to ensure that we do not loop endlessly while inlining.
278    history: Vec<DefId>,
279    /// How many (multi-call) callsites have we inlined for the top-level call?
280    ///
281    /// We need to limit this in order to prevent super-linear growth in MIR size.
282    top_down_counter: usize,
283    /// Indicates that the caller body has been modified.
284    changed: bool,
285    /// Indicates that the caller is #[inline] and just calls another function,
286    /// and thus we can inline less into it as it'll be inlined itself.
287    caller_is_inline_forwarder: bool,
288}
289
290impl<'tcx> NormalInliner<'tcx> {
291    fn past_depth_limit(&self) -> bool {
292        self.history.len() > HISTORY_DEPTH_LIMIT || self.top_down_counter > TOP_DOWN_DEPTH_LIMIT
293    }
294}
295
296impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> {
297    fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
298        let typing_env = body.typing_env(tcx);
299        let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
300
301        Self {
302            tcx,
303            typing_env,
304            def_id,
305            history: Vec::new(),
306            top_down_counter: 0,
307            changed: false,
308            caller_is_inline_forwarder: matches!(
309                codegen_fn_attrs.inline,
310                InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. }
311            ) && body_is_forwarder(body),
312        }
313    }
314
315    fn tcx(&self) -> TyCtxt<'tcx> {
316        self.tcx
317    }
318
319    fn caller_def_id(&self) -> DefId {
320        self.def_id
321    }
322
323    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
324        self.typing_env
325    }
326
327    fn history(&self) -> &[DefId] {
328        &self.history
329    }
330
331    fn changed(self) -> bool {
332        self.changed
333    }
334
335    fn should_inline_for_callee(&self, _: DefId) -> bool {
336        true
337    }
338
339    fn check_codegen_attributes_extra(
340        &self,
341        callee_attrs: &CodegenFnAttrs,
342    ) -> Result<(), &'static str> {
343        if self.past_depth_limit() && matches!(callee_attrs.inline, InlineAttr::None) {
344            Err("Past depth limit so not inspecting unmarked callee")
345        } else {
346            Ok(())
347        }
348    }
349
350    fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool {
351        // Avoid inlining into coroutines, since their `optimized_mir` is used for layout computation,
352        // which can create a cycle, even when no attempt is made to inline the function in the other
353        // direction.
354        if body.coroutine.is_some() {
355            return false;
356        }
357
358        true
359    }
360
361    #[instrument(level = "debug", skip(self, callee_body))]
362    fn check_callee_mir_body(
363        &self,
364        callsite: &CallSite<'tcx>,
365        callee_body: &Body<'tcx>,
366        callee_attrs: &CodegenFnAttrs,
367    ) -> Result<(), &'static str> {
368        let tcx = self.tcx();
369
370        if let Some(_) = callee_body.tainted_by_errors {
371            return Err("body has errors");
372        }
373
374        if self.past_depth_limit() && callee_body.basic_blocks.len() > 1 {
375            return Err("Not inlining multi-block body as we're past a depth limit");
376        }
377
378        let mut threshold = if self.caller_is_inline_forwarder || self.past_depth_limit() {
379            tcx.sess.opts.unstable_opts.inline_mir_forwarder_threshold.unwrap_or(30)
380        } else if tcx.cross_crate_inlinable(callsite.callee.def_id()) {
381            tcx.sess.opts.unstable_opts.inline_mir_hint_threshold.unwrap_or(100)
382        } else {
383            tcx.sess.opts.unstable_opts.inline_mir_threshold.unwrap_or(50)
384        };
385
386        // Give a bonus functions with a small number of blocks,
387        // We normally have two or three blocks for even
388        // very small functions.
389        if callee_body.basic_blocks.len() <= 3 {
390            threshold += threshold / 4;
391        }
392        debug!("    final inline threshold = {}", threshold);
393
394        // FIXME: Give a bonus to functions with only a single caller
395
396        let mut checker =
397            CostChecker::new(tcx, self.typing_env(), Some(callsite.callee), callee_body);
398
399        checker.add_function_level_costs();
400
401        // Traverse the MIR manually so we can account for the effects of inlining on the CFG.
402        let mut work_list = vec![START_BLOCK];
403        let mut visited = DenseBitSet::new_empty(callee_body.basic_blocks.len());
404        while let Some(bb) = work_list.pop() {
405            if !visited.insert(bb.index()) {
406                continue;
407            }
408
409            let blk = &callee_body.basic_blocks[bb];
410            checker.visit_basic_block_data(bb, blk);
411
412            let term = blk.terminator();
413            let caller_attrs = tcx.codegen_fn_attrs(self.caller_def_id());
414            if let TerminatorKind::Drop {
415                ref place,
416                target,
417                unwind,
418                replace: _,
419                drop: _,
420                async_fut: _,
421            } = term.kind
422            {
423                work_list.push(target);
424
425                // If the place doesn't actually need dropping, treat it like a regular goto.
426                let ty = callsite
427                    .callee
428                    .instantiate_mir(tcx, ty::EarlyBinder::bind(&place.ty(callee_body, tcx).ty));
429                if ty.needs_drop(tcx, self.typing_env())
430                    && let UnwindAction::Cleanup(unwind) = unwind
431                {
432                    work_list.push(unwind);
433                }
434            } else if callee_attrs.instruction_set != caller_attrs.instruction_set
435                && matches!(term.kind, TerminatorKind::InlineAsm { .. })
436            {
437                // During the attribute checking stage we allow a callee with no
438                // instruction_set assigned to count as compatible with a function that does
439                // assign one. However, during this stage we require an exact match when any
440                // inline-asm is detected. LLVM will still possibly do an inline later on
441                // if the no-attribute function ends up with the same instruction set anyway.
442                return Err("cannot move inline-asm across instruction sets");
443            } else if let TerminatorKind::TailCall { .. } = term.kind {
444                // FIXME(explicit_tail_calls): figure out how exactly functions containing tail
445                // calls can be inlined (and if they even should)
446                return Err("can't inline functions with tail calls");
447            } else {
448                work_list.extend(term.successors())
449            }
450        }
451
452        // N.B. We still apply our cost threshold to #[inline(always)] functions.
453        // That attribute is often applied to very large functions that exceed LLVM's (very
454        // generous) inlining threshold. Such functions are very poor MIR inlining candidates.
455        // Always inlining #[inline(always)] functions in MIR, on net, slows down the compiler.
456        let cost = checker.cost();
457        if cost <= threshold {
458            debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
459            Ok(())
460        } else {
461            debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
462            Err("cost above threshold")
463        }
464    }
465
466    fn on_inline_success(
467        &mut self,
468        callsite: &CallSite<'tcx>,
469        caller_body: &mut Body<'tcx>,
470        new_blocks: std::ops::Range<BasicBlock>,
471    ) {
472        self.changed = true;
473
474        let new_calls_count = new_blocks
475            .clone()
476            .filter(|&bb| is_call_like(caller_body.basic_blocks[bb].terminator()))
477            .count();
478        if new_calls_count > 1 {
479            self.top_down_counter += 1;
480        }
481
482        self.history.push(callsite.callee.def_id());
483        process_blocks(self, caller_body, new_blocks);
484        self.history.pop();
485
486        if self.history.is_empty() {
487            self.top_down_counter = 0;
488        }
489    }
490
491    fn on_inline_failure(&self, _: &CallSite<'tcx>, _: &'static str) {}
492}
493
494fn inline<'tcx, T: Inliner<'tcx>>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
495    let def_id = body.source.def_id();
496
497    // Only do inlining into fn bodies.
498    if !tcx.hir_body_owner_kind(def_id).is_fn_or_closure() {
499        return false;
500    }
501
502    let mut inliner = T::new(tcx, def_id, body);
503    if !inliner.check_caller_mir_body(body) {
504        return false;
505    }
506
507    let blocks = START_BLOCK..body.basic_blocks.next_index();
508    process_blocks(&mut inliner, body, blocks);
509    inliner.changed()
510}
511
512fn process_blocks<'tcx, I: Inliner<'tcx>>(
513    inliner: &mut I,
514    caller_body: &mut Body<'tcx>,
515    blocks: Range<BasicBlock>,
516) {
517    for bb in blocks {
518        let bb_data = &caller_body[bb];
519        if bb_data.is_cleanup {
520            continue;
521        }
522
523        let Some(callsite) = resolve_callsite(inliner, caller_body, bb, bb_data) else {
524            continue;
525        };
526
527        let span = trace_span!("process_blocks", %callsite.callee, ?bb);
528        let _guard = span.enter();
529
530        match try_inlining(inliner, caller_body, &callsite) {
531            Err(reason) => {
532                debug!("not-inlined {} [{}]", callsite.callee, reason);
533                inliner.on_inline_failure(&callsite, reason);
534            }
535            Ok(new_blocks) => {
536                debug!("inlined {}", callsite.callee);
537                inliner.on_inline_success(&callsite, caller_body, new_blocks);
538            }
539        }
540    }
541}
542
543fn resolve_callsite<'tcx, I: Inliner<'tcx>>(
544    inliner: &I,
545    caller_body: &Body<'tcx>,
546    bb: BasicBlock,
547    bb_data: &BasicBlockData<'tcx>,
548) -> Option<CallSite<'tcx>> {
549    let tcx = inliner.tcx();
550    // Only consider direct calls to functions
551    let terminator = bb_data.terminator();
552
553    // FIXME(explicit_tail_calls): figure out if we can inline tail calls
554    if let TerminatorKind::Call { ref func, fn_span, .. } = terminator.kind {
555        let func_ty = func.ty(caller_body, tcx);
556        if let ty::FnDef(def_id, args) = *func_ty.kind() {
557            if !inliner.should_inline_for_callee(def_id) {
558                debug!("not enabled");
559                return None;
560            }
561
562            // To resolve an instance its args have to be fully normalized.
563            let args = tcx.try_normalize_erasing_regions(inliner.typing_env(), args).ok()?;
564            let callee =
565                Instance::try_resolve(tcx, inliner.typing_env(), def_id, args).ok().flatten()?;
566
567            if let InstanceKind::Virtual(..) | InstanceKind::Intrinsic(_) = callee.def {
568                return None;
569            }
570
571            if inliner.history().contains(&callee.def_id()) {
572                return None;
573            }
574
575            let fn_sig = tcx.fn_sig(def_id).instantiate(tcx, args);
576
577            // Additionally, check that the body that we're inlining actually agrees
578            // with the ABI of the trait that the item comes from.
579            if let InstanceKind::Item(instance_def_id) = callee.def
580                && tcx.def_kind(instance_def_id) == DefKind::AssocFn
581                && let instance_fn_sig = tcx.fn_sig(instance_def_id).skip_binder()
582                && instance_fn_sig.abi() != fn_sig.abi()
583            {
584                return None;
585            }
586
587            let source_info = SourceInfo { span: fn_span, ..terminator.source_info };
588
589            return Some(CallSite { callee, fn_sig, block: bb, source_info });
590        }
591    }
592
593    None
594}
595
596/// Attempts to inline a callsite into the caller body. When successful returns basic blocks
597/// containing the inlined body. Otherwise returns an error describing why inlining didn't take
598/// place.
599fn try_inlining<'tcx, I: Inliner<'tcx>>(
600    inliner: &I,
601    caller_body: &mut Body<'tcx>,
602    callsite: &CallSite<'tcx>,
603) -> Result<std::ops::Range<BasicBlock>, &'static str> {
604    let tcx = inliner.tcx();
605    check_mir_is_available(inliner, caller_body, callsite.callee)?;
606
607    let callee_attrs = tcx.codegen_instance_attrs(callsite.callee.def);
608    let callee_attrs = callee_attrs.as_ref();
609    check_inline::is_inline_valid_on_fn(tcx, callsite.callee.def_id())?;
610    check_codegen_attributes(inliner, callsite, callee_attrs)?;
611
612    let terminator = caller_body[callsite.block].terminator.as_ref().unwrap();
613    let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() };
614    let destination_ty = destination.ty(&caller_body.local_decls, tcx).ty;
615    for arg in args {
616        if !arg.node.ty(&caller_body.local_decls, tcx).is_sized(tcx, inliner.typing_env()) {
617            // We do not allow inlining functions with unsized params. Inlining these functions
618            // could create unsized locals, which are unsound and being phased out.
619            return Err("call has unsized argument");
620        }
621    }
622
623    let callee_body = try_instance_mir(tcx, callsite.callee.def)?;
624    check_inline::is_inline_valid_on_body(tcx, callee_body)?;
625    inliner.check_callee_mir_body(callsite, callee_body, callee_attrs)?;
626
627    let Ok(callee_body) = callsite.callee.try_instantiate_mir_and_normalize_erasing_regions(
628        tcx,
629        inliner.typing_env(),
630        ty::EarlyBinder::bind(callee_body.clone()),
631    ) else {
632        debug!("failed to normalize callee body");
633        return Err("implementation limitation -- could not normalize callee body");
634    };
635
636    // Normally, this shouldn't be required, but trait normalization failure can create a
637    // validation ICE.
638    if !validate_types(tcx, inliner.typing_env(), &callee_body, caller_body).is_empty() {
639        debug!("failed to validate callee body");
640        return Err("implementation limitation -- callee body failed validation");
641    }
642
643    // Check call signature compatibility.
644    // Normally, this shouldn't be required, but trait normalization failure can create a
645    // validation ICE.
646    let output_type = callee_body.return_ty();
647    if !util::sub_types(tcx, inliner.typing_env(), output_type, destination_ty) {
648        trace!(?output_type, ?destination_ty);
649        return Err("implementation limitation -- return type mismatch");
650    }
651    if callsite.fn_sig.abi() == ExternAbi::RustCall {
652        let (self_arg, arg_tuple) = match &args[..] {
653            [arg_tuple] => (None, arg_tuple),
654            [self_arg, arg_tuple] => (Some(self_arg), arg_tuple),
655            _ => bug!("Expected `rust-call` to have 1 or 2 args"),
656        };
657
658        let self_arg_ty = self_arg.map(|self_arg| self_arg.node.ty(&caller_body.local_decls, tcx));
659
660        let arg_tuple_ty = arg_tuple.node.ty(&caller_body.local_decls, tcx);
661        let arg_tys = if callee_body.spread_arg.is_some() {
662            std::slice::from_ref(&arg_tuple_ty)
663        } else {
664            let ty::Tuple(arg_tuple_tys) = *arg_tuple_ty.kind() else {
665                bug!("Closure arguments are not passed as a tuple");
666            };
667            arg_tuple_tys.as_slice()
668        };
669
670        for (arg_ty, input) in
671            self_arg_ty.into_iter().chain(arg_tys.iter().copied()).zip(callee_body.args_iter())
672        {
673            let input_type = callee_body.local_decls[input].ty;
674            if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
675                trace!(?arg_ty, ?input_type);
676                debug!("failed to normalize tuple argument type");
677                return Err("implementation limitation");
678            }
679        }
680    } else {
681        for (arg, input) in args.iter().zip(callee_body.args_iter()) {
682            let input_type = callee_body.local_decls[input].ty;
683            let arg_ty = arg.node.ty(&caller_body.local_decls, tcx);
684            if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
685                trace!(?arg_ty, ?input_type);
686                debug!("failed to normalize argument type");
687                return Err("implementation limitation -- arg mismatch");
688            }
689        }
690    }
691
692    let old_blocks = caller_body.basic_blocks.next_index();
693    inline_call(inliner, caller_body, callsite, callee_body);
694    let new_blocks = old_blocks..caller_body.basic_blocks.next_index();
695
696    Ok(new_blocks)
697}
698
699fn check_mir_is_available<'tcx, I: Inliner<'tcx>>(
700    inliner: &I,
701    caller_body: &Body<'tcx>,
702    callee: Instance<'tcx>,
703) -> Result<(), &'static str> {
704    let caller_def_id = caller_body.source.def_id();
705    let callee_def_id = callee.def_id();
706    if callee_def_id == caller_def_id {
707        return Err("self-recursion");
708    }
709
710    match callee.def {
711        InstanceKind::Item(_) => {
712            // If there is no MIR available (either because it was not in metadata or
713            // because it has no MIR because it's an extern function), then the inliner
714            // won't cause cycles on this.
715            if !inliner.tcx().is_mir_available(callee_def_id) {
716                debug!("item MIR unavailable");
717                return Err("implementation limitation -- MIR unavailable");
718            }
719        }
720        // These have no own callable MIR.
721        InstanceKind::Intrinsic(_) | InstanceKind::Virtual(..) => {
722            debug!("instance without MIR (intrinsic / virtual)");
723            return Err("implementation limitation -- cannot inline intrinsic");
724        }
725
726        // FIXME(#127030): `ConstParamHasTy` has bad interactions with
727        // the drop shim builder, which does not evaluate predicates in
728        // the correct param-env for types being dropped. Stall resolving
729        // the MIR for this instance until all of its const params are
730        // substituted.
731        InstanceKind::DropGlue(_, Some(ty)) if ty.has_type_flags(TypeFlags::HAS_CT_PARAM) => {
732            debug!("still needs substitution");
733            return Err("implementation limitation -- HACK for dropping polymorphic type");
734        }
735        InstanceKind::AsyncDropGlue(_, ty) | InstanceKind::AsyncDropGlueCtorShim(_, ty) => {
736            return if ty.still_further_specializable() {
737                Err("still needs substitution")
738            } else {
739                Ok(())
740            };
741        }
742        InstanceKind::FutureDropPollShim(_, ty, ty2) => {
743            return if ty.still_further_specializable() || ty2.still_further_specializable() {
744                Err("still needs substitution")
745            } else {
746                Ok(())
747            };
748        }
749
750        // This cannot result in an immediate cycle since the callee MIR is a shim, which does
751        // not get any optimizations run on it. Any subsequent inlining may cause cycles, but we
752        // do not need to catch this here, we can wait until the inliner decides to continue
753        // inlining a second time.
754        InstanceKind::VTableShim(_)
755        | InstanceKind::ReifyShim(..)
756        | InstanceKind::FnPtrShim(..)
757        | InstanceKind::ClosureOnceShim { .. }
758        | InstanceKind::ConstructCoroutineInClosureShim { .. }
759        | InstanceKind::DropGlue(..)
760        | InstanceKind::CloneShim(..)
761        | InstanceKind::ThreadLocalShim(..)
762        | InstanceKind::FnPtrAddrShim(..) => return Ok(()),
763    }
764
765    if inliner.tcx().is_constructor(callee_def_id) {
766        trace!("constructors always have MIR");
767        // Constructor functions cannot cause a query cycle.
768        return Ok(());
769    }
770
771    if let Some(callee_def_id) = callee_def_id.as_local()
772        && !inliner
773            .tcx()
774            .is_lang_item(inliner.tcx().parent(caller_def_id), rustc_hir::LangItem::FnOnce)
775    {
776        // If we know for sure that the function we're calling will itself try to
777        // call us, then we avoid inlining that function.
778        let Some(cyclic_callees) = inliner.tcx().mir_callgraph_cyclic(caller_def_id.expect_local())
779        else {
780            return Err("call graph cycle detection bailed due to recursion limit");
781        };
782        if cyclic_callees.contains(&callee_def_id) {
783            debug!("query cycle avoidance");
784            return Err("caller might be reachable from callee");
785        }
786
787        Ok(())
788    } else {
789        // This cannot result in an immediate cycle since the callee MIR is from another crate
790        // and is already optimized. Any subsequent inlining may cause cycles, but we do
791        // not need to catch this here, we can wait until the inliner decides to continue
792        // inlining a second time.
793        trace!("functions from other crates always have MIR");
794        Ok(())
795    }
796}
797
798/// Returns an error if inlining is not possible based on codegen attributes alone. A success
799/// indicates that inlining decision should be based on other criteria.
800fn check_codegen_attributes<'tcx, I: Inliner<'tcx>>(
801    inliner: &I,
802    callsite: &CallSite<'tcx>,
803    callee_attrs: &CodegenFnAttrs,
804) -> Result<(), &'static str> {
805    let tcx = inliner.tcx();
806    if let InlineAttr::Never = callee_attrs.inline {
807        return Err("never inline attribute");
808    }
809
810    if let OptimizeAttr::DoNotOptimize = callee_attrs.optimize {
811        return Err("has DoNotOptimize attribute");
812    }
813
814    inliner.check_codegen_attributes_extra(callee_attrs)?;
815
816    // Reachability pass defines which functions are eligible for inlining. Generally inlining
817    // other functions is incorrect because they could reference symbols that aren't exported.
818    let is_generic = callsite.callee.args.non_erasable_generics().next().is_some();
819    if !is_generic && !tcx.cross_crate_inlinable(callsite.callee.def_id()) {
820        return Err("not exported");
821    }
822
823    let codegen_fn_attrs = tcx.codegen_fn_attrs(inliner.caller_def_id());
824    if callee_attrs.sanitizers != codegen_fn_attrs.sanitizers {
825        return Err("incompatible sanitizer set");
826    }
827
828    // Two functions are compatible if the callee has no attribute (meaning
829    // that it's codegen agnostic), or sets an attribute that is identical
830    // to this function's attribute.
831    if callee_attrs.instruction_set.is_some()
832        && callee_attrs.instruction_set != codegen_fn_attrs.instruction_set
833    {
834        return Err("incompatible instruction set");
835    }
836
837    let callee_feature_names = callee_attrs.target_features.iter().map(|f| f.name);
838    let this_feature_names = codegen_fn_attrs.target_features.iter().map(|f| f.name);
839    if callee_feature_names.ne(this_feature_names) {
840        // In general it is not correct to inline a callee with target features that are a
841        // subset of the caller. This is because the callee might contain calls, and the ABI of
842        // those calls depends on the target features of the surrounding function. By moving a
843        // `Call` terminator from one MIR body to another with more target features, we might
844        // change the ABI of that call!
845        return Err("incompatible target features");
846    }
847
848    Ok(())
849}
850
851fn inline_call<'tcx, I: Inliner<'tcx>>(
852    inliner: &I,
853    caller_body: &mut Body<'tcx>,
854    callsite: &CallSite<'tcx>,
855    mut callee_body: Body<'tcx>,
856) {
857    let tcx = inliner.tcx();
858    let terminator = caller_body[callsite.block].terminator.take().unwrap();
859    let TerminatorKind::Call { func, args, destination, unwind, target, .. } = terminator.kind
860    else {
861        bug!("unexpected terminator kind {:?}", terminator.kind);
862    };
863
864    let return_block = if let Some(block) = target {
865        // Prepare a new block for code that should execute when call returns. We don't use
866        // target block directly since it might have other predecessors.
867        let data = BasicBlockData::new(
868            Some(Terminator {
869                source_info: terminator.source_info,
870                kind: TerminatorKind::Goto { target: block },
871            }),
872            caller_body[block].is_cleanup,
873        );
874        Some(caller_body.basic_blocks_mut().push(data))
875    } else {
876        None
877    };
878
879    // If the call is something like `a[*i] = f(i)`, where
880    // `i : &mut usize`, then just duplicating the `a[*i]`
881    // Place could result in two different locations if `f`
882    // writes to `i`. To prevent this we need to create a temporary
883    // borrow of the place and pass the destination as `*temp` instead.
884    fn dest_needs_borrow(place: Place<'_>) -> bool {
885        for elem in place.projection.iter() {
886            match elem {
887                ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
888                _ => {}
889            }
890        }
891
892        false
893    }
894
895    let dest = if dest_needs_borrow(destination) {
896        trace!("creating temp for return destination");
897        let dest = Rvalue::Ref(
898            tcx.lifetimes.re_erased,
899            BorrowKind::Mut { kind: MutBorrowKind::Default },
900            destination,
901        );
902        let dest_ty = dest.ty(caller_body, tcx);
903        let temp = Place::from(new_call_temp(caller_body, callsite, dest_ty, return_block));
904        caller_body[callsite.block].statements.push(Statement::new(
905            callsite.source_info,
906            StatementKind::Assign(Box::new((temp, dest))),
907        ));
908        tcx.mk_place_deref(temp)
909    } else {
910        destination
911    };
912
913    // Always create a local to hold the destination, as `RETURN_PLACE` may appear
914    // where a full `Place` is not allowed.
915    let (remap_destination, destination_local) = if let Some(d) = dest.as_local() {
916        (false, d)
917    } else {
918        (
919            true,
920            new_call_temp(caller_body, callsite, destination.ty(caller_body, tcx).ty, return_block),
921        )
922    };
923
924    // Copy the arguments if needed.
925    let args = make_call_args(inliner, args, callsite, caller_body, &callee_body, return_block);
926
927    let mut integrator = Integrator {
928        args: &args,
929        new_locals: caller_body.local_decls.next_index()..,
930        new_scopes: caller_body.source_scopes.next_index()..,
931        new_blocks: caller_body.basic_blocks.next_index()..,
932        destination: destination_local,
933        callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
934        callsite,
935        cleanup_block: unwind,
936        in_cleanup_block: false,
937        return_block,
938        tcx,
939        always_live_locals: UsedInStmtLocals::new(&callee_body).locals,
940    };
941
942    // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
943    // (or existing ones, in a few special cases) in the caller.
944    integrator.visit_body(&mut callee_body);
945
946    // If there are any locals without storage markers, give them storage only for the
947    // duration of the call.
948    for local in callee_body.vars_and_temps_iter() {
949        if integrator.always_live_locals.contains(local) {
950            let new_local = integrator.map_local(local);
951            caller_body[callsite.block]
952                .statements
953                .push(Statement::new(callsite.source_info, StatementKind::StorageLive(new_local)));
954        }
955    }
956    if let Some(block) = return_block {
957        // To avoid repeated O(n) insert, push any new statements to the end and rotate
958        // the slice once.
959        let mut n = 0;
960        if remap_destination {
961            caller_body[block].statements.push(Statement::new(
962                callsite.source_info,
963                StatementKind::Assign(Box::new((
964                    dest,
965                    Rvalue::Use(Operand::Move(destination_local.into())),
966                ))),
967            ));
968            n += 1;
969        }
970        for local in callee_body.vars_and_temps_iter().rev() {
971            if integrator.always_live_locals.contains(local) {
972                let new_local = integrator.map_local(local);
973                caller_body[block].statements.push(Statement::new(
974                    callsite.source_info,
975                    StatementKind::StorageDead(new_local),
976                ));
977                n += 1;
978            }
979        }
980        caller_body[block].statements.rotate_right(n);
981    }
982
983    // Insert all of the (mapped) parts of the callee body into the caller.
984    caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
985    caller_body.source_scopes.append(&mut callee_body.source_scopes);
986
987    // only "full" debug promises any variable-level information
988    if tcx
989        .sess
990        .opts
991        .unstable_opts
992        .inline_mir_preserve_debug
993        .unwrap_or(tcx.sess.opts.debuginfo == DebugInfo::Full)
994    {
995        // -Zinline-mir-preserve-debug is enabled when building the standard library, so that
996        // people working on rust can build with or without debuginfo while
997        // still getting consistent results from the mir-opt tests.
998        caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
999    } else {
1000        for bb in callee_body.basic_blocks_mut() {
1001            bb.drop_debuginfo();
1002        }
1003    }
1004    caller_body.basic_blocks_mut().append(callee_body.basic_blocks_mut());
1005
1006    caller_body[callsite.block].terminator = Some(Terminator {
1007        source_info: callsite.source_info,
1008        kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
1009    });
1010
1011    // Copy required constants from the callee_body into the caller_body. Although we are only
1012    // pushing unevaluated consts to `required_consts`, here they may have been evaluated
1013    // because we are calling `instantiate_and_normalize_erasing_regions` -- so we filter again.
1014    caller_body.required_consts.as_mut().unwrap().extend(
1015        callee_body.required_consts().into_iter().filter(|ct| ct.const_.is_required_const()),
1016    );
1017    // Now that we incorporated the callee's `required_consts`, we can remove the callee from
1018    // `mentioned_items` -- but we have to take their `mentioned_items` in return. This does
1019    // some extra work here to save the monomorphization collector work later. It helps a lot,
1020    // since monomorphization can avoid a lot of work when the "mentioned items" are similar to
1021    // the actually used items. By doing this we can entirely avoid visiting the callee!
1022    // We need to reconstruct the `required_item` for the callee so that we can find and
1023    // remove it.
1024    let callee_item = MentionedItem::Fn(func.ty(caller_body, tcx));
1025    let caller_mentioned_items = caller_body.mentioned_items.as_mut().unwrap();
1026    if let Some(idx) = caller_mentioned_items.iter().position(|item| item.node == callee_item) {
1027        // We found the callee, so remove it and add its items instead.
1028        caller_mentioned_items.remove(idx);
1029        caller_mentioned_items.extend(callee_body.mentioned_items());
1030    } else {
1031        // If we can't find the callee, there's no point in adding its items. Probably it
1032        // already got removed by being inlined elsewhere in the same function, so we already
1033        // took its items.
1034    }
1035}
1036
1037fn make_call_args<'tcx, I: Inliner<'tcx>>(
1038    inliner: &I,
1039    args: Box<[Spanned<Operand<'tcx>>]>,
1040    callsite: &CallSite<'tcx>,
1041    caller_body: &mut Body<'tcx>,
1042    callee_body: &Body<'tcx>,
1043    return_block: Option<BasicBlock>,
1044) -> Box<[Local]> {
1045    let tcx = inliner.tcx();
1046
1047    // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
1048    // The caller provides the arguments wrapped up in a tuple:
1049    //
1050    //     tuple_tmp = (a, b, c)
1051    //     Fn::call(closure_ref, tuple_tmp)
1052    //
1053    // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
1054    // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
1055    // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
1056    // a vector like
1057    //
1058    //     [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
1059    //
1060    // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
1061    // if we "spill" that into *another* temporary, so that we can map the argument
1062    // variable in the callee MIR directly to an argument variable on our side.
1063    // So we introduce temporaries like:
1064    //
1065    //     tmp0 = tuple_tmp.0
1066    //     tmp1 = tuple_tmp.1
1067    //     tmp2 = tuple_tmp.2
1068    //
1069    // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
1070    if callsite.fn_sig.abi() == ExternAbi::RustCall && callee_body.spread_arg.is_none() {
1071        // FIXME(edition_2024): switch back to a normal method call.
1072        let mut args = <_>::into_iter(args);
1073        let self_ = create_temp_if_necessary(
1074            inliner,
1075            args.next().unwrap().node,
1076            callsite,
1077            caller_body,
1078            return_block,
1079        );
1080        let tuple = create_temp_if_necessary(
1081            inliner,
1082            args.next().unwrap().node,
1083            callsite,
1084            caller_body,
1085            return_block,
1086        );
1087        assert!(args.next().is_none());
1088
1089        let tuple = Place::from(tuple);
1090        let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
1091            bug!("Closure arguments are not passed as a tuple");
1092        };
1093
1094        // The `closure_ref` in our example above.
1095        let closure_ref_arg = iter::once(self_);
1096
1097        // The `tmp0`, `tmp1`, and `tmp2` in our example above.
1098        let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
1099            // This is e.g., `tuple_tmp.0` in our example above.
1100            let tuple_field = Operand::Move(tcx.mk_place_field(tuple, FieldIdx::new(i), ty));
1101
1102            // Spill to a local to make e.g., `tmp0`.
1103            create_temp_if_necessary(inliner, tuple_field, callsite, caller_body, return_block)
1104        });
1105
1106        closure_ref_arg.chain(tuple_tmp_args).collect()
1107    } else {
1108        args.into_iter()
1109            .map(|a| create_temp_if_necessary(inliner, a.node, callsite, caller_body, return_block))
1110            .collect()
1111    }
1112}
1113
1114/// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh temporary `T` and an
1115/// instruction `T = arg`, and returns `T`.
1116fn create_temp_if_necessary<'tcx, I: Inliner<'tcx>>(
1117    inliner: &I,
1118    arg: Operand<'tcx>,
1119    callsite: &CallSite<'tcx>,
1120    caller_body: &mut Body<'tcx>,
1121    return_block: Option<BasicBlock>,
1122) -> Local {
1123    // Reuse the operand if it is a moved temporary.
1124    if let Operand::Move(place) = &arg
1125        && let Some(local) = place.as_local()
1126        && caller_body.local_kind(local) == LocalKind::Temp
1127    {
1128        return local;
1129    }
1130
1131    // Otherwise, create a temporary for the argument.
1132    trace!("creating temp for argument {:?}", arg);
1133    let arg_ty = arg.ty(caller_body, inliner.tcx());
1134    let local = new_call_temp(caller_body, callsite, arg_ty, return_block);
1135    caller_body[callsite.block].statements.push(Statement::new(
1136        callsite.source_info,
1137        StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg)))),
1138    ));
1139    local
1140}
1141
1142/// Introduces a new temporary into the caller body that is live for the duration of the call.
1143fn new_call_temp<'tcx>(
1144    caller_body: &mut Body<'tcx>,
1145    callsite: &CallSite<'tcx>,
1146    ty: Ty<'tcx>,
1147    return_block: Option<BasicBlock>,
1148) -> Local {
1149    let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
1150
1151    caller_body[callsite.block]
1152        .statements
1153        .push(Statement::new(callsite.source_info, StatementKind::StorageLive(local)));
1154
1155    if let Some(block) = return_block {
1156        caller_body[block]
1157            .statements
1158            .insert(0, Statement::new(callsite.source_info, StatementKind::StorageDead(local)));
1159    }
1160
1161    local
1162}
1163
1164/**
1165 * Integrator.
1166 *
1167 * Integrates blocks from the callee function into the calling function.
1168 * Updates block indices, references to locals and other control flow
1169 * stuff.
1170*/
1171struct Integrator<'a, 'tcx> {
1172    args: &'a [Local],
1173    new_locals: RangeFrom<Local>,
1174    new_scopes: RangeFrom<SourceScope>,
1175    new_blocks: RangeFrom<BasicBlock>,
1176    destination: Local,
1177    callsite_scope: SourceScopeData<'tcx>,
1178    callsite: &'a CallSite<'tcx>,
1179    cleanup_block: UnwindAction,
1180    in_cleanup_block: bool,
1181    return_block: Option<BasicBlock>,
1182    tcx: TyCtxt<'tcx>,
1183    always_live_locals: DenseBitSet<Local>,
1184}
1185
1186impl Integrator<'_, '_> {
1187    fn map_local(&self, local: Local) -> Local {
1188        let new = if local == RETURN_PLACE {
1189            self.destination
1190        } else {
1191            let idx = local.index() - 1;
1192            if idx < self.args.len() {
1193                self.args[idx]
1194            } else {
1195                self.new_locals.start + (idx - self.args.len())
1196            }
1197        };
1198        trace!("mapping local `{:?}` to `{:?}`", local, new);
1199        new
1200    }
1201
1202    fn map_scope(&self, scope: SourceScope) -> SourceScope {
1203        let new = self.new_scopes.start + scope.index();
1204        trace!("mapping scope `{:?}` to `{:?}`", scope, new);
1205        new
1206    }
1207
1208    fn map_block(&self, block: BasicBlock) -> BasicBlock {
1209        let new = self.new_blocks.start + block.index();
1210        trace!("mapping block `{:?}` to `{:?}`", block, new);
1211        new
1212    }
1213
1214    fn map_unwind(&self, unwind: UnwindAction) -> UnwindAction {
1215        if self.in_cleanup_block {
1216            match unwind {
1217                UnwindAction::Cleanup(_) | UnwindAction::Continue => {
1218                    bug!("cleanup on cleanup block");
1219                }
1220                UnwindAction::Unreachable | UnwindAction::Terminate(_) => return unwind,
1221            }
1222        }
1223
1224        match unwind {
1225            UnwindAction::Unreachable | UnwindAction::Terminate(_) => unwind,
1226            UnwindAction::Cleanup(target) => UnwindAction::Cleanup(self.map_block(target)),
1227            // Add an unwind edge to the original call's cleanup block
1228            UnwindAction::Continue => self.cleanup_block,
1229        }
1230    }
1231}
1232
1233impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
1234    fn tcx(&self) -> TyCtxt<'tcx> {
1235        self.tcx
1236    }
1237
1238    fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
1239        *local = self.map_local(*local);
1240    }
1241
1242    fn visit_source_scope_data(&mut self, scope_data: &mut SourceScopeData<'tcx>) {
1243        self.super_source_scope_data(scope_data);
1244        if scope_data.parent_scope.is_none() {
1245            // Attach the outermost callee scope as a child of the callsite
1246            // scope, via the `parent_scope` and `inlined_parent_scope` chains.
1247            scope_data.parent_scope = Some(self.callsite.source_info.scope);
1248            assert_eq!(scope_data.inlined_parent_scope, None);
1249            scope_data.inlined_parent_scope = if self.callsite_scope.inlined.is_some() {
1250                Some(self.callsite.source_info.scope)
1251            } else {
1252                self.callsite_scope.inlined_parent_scope
1253            };
1254
1255            // Mark the outermost callee scope as an inlined one.
1256            assert_eq!(scope_data.inlined, None);
1257            scope_data.inlined = Some((self.callsite.callee, self.callsite.source_info.span));
1258        } else if scope_data.inlined_parent_scope.is_none() {
1259            // Make it easy to find the scope with `inlined` set above.
1260            scope_data.inlined_parent_scope = Some(self.map_scope(OUTERMOST_SOURCE_SCOPE));
1261        }
1262    }
1263
1264    fn visit_source_scope(&mut self, scope: &mut SourceScope) {
1265        *scope = self.map_scope(*scope);
1266    }
1267
1268    fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
1269        self.in_cleanup_block = data.is_cleanup;
1270        self.super_basic_block_data(block, data);
1271        self.in_cleanup_block = false;
1272    }
1273
1274    fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
1275        self.super_retag(kind, place, loc);
1276
1277        // We have to patch all inlined retags to be aware that they are no longer
1278        // happening on function entry.
1279        if *kind == RetagKind::FnEntry {
1280            *kind = RetagKind::Default;
1281        }
1282    }
1283
1284    fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1285        if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
1286            statement.kind
1287        {
1288            self.always_live_locals.remove(local);
1289        }
1290        self.super_statement(statement, location);
1291    }
1292
1293    fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
1294        // Don't try to modify the implicit `_0` access on return (`return` terminators are
1295        // replaced down below anyways).
1296        if !matches!(terminator.kind, TerminatorKind::Return) {
1297            self.super_terminator(terminator, loc);
1298        } else {
1299            self.visit_source_info(&mut terminator.source_info);
1300        }
1301
1302        match terminator.kind {
1303            TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => bug!(),
1304            TerminatorKind::Goto { ref mut target } => {
1305                *target = self.map_block(*target);
1306            }
1307            TerminatorKind::SwitchInt { ref mut targets, .. } => {
1308                for tgt in targets.all_targets_mut() {
1309                    *tgt = self.map_block(*tgt);
1310                }
1311            }
1312            TerminatorKind::Drop { ref mut target, ref mut unwind, .. } => {
1313                *target = self.map_block(*target);
1314                *unwind = self.map_unwind(*unwind);
1315            }
1316            TerminatorKind::TailCall { .. } => {
1317                // check_mir_body forbids tail calls
1318                unreachable!()
1319            }
1320            TerminatorKind::Call { ref mut target, ref mut unwind, .. } => {
1321                if let Some(ref mut tgt) = *target {
1322                    *tgt = self.map_block(*tgt);
1323                }
1324                *unwind = self.map_unwind(*unwind);
1325            }
1326            TerminatorKind::Assert { ref mut target, ref mut unwind, .. } => {
1327                *target = self.map_block(*target);
1328                *unwind = self.map_unwind(*unwind);
1329            }
1330            TerminatorKind::Return => {
1331                terminator.kind = if let Some(tgt) = self.return_block {
1332                    TerminatorKind::Goto { target: tgt }
1333                } else {
1334                    TerminatorKind::Unreachable
1335                }
1336            }
1337            TerminatorKind::UnwindResume => {
1338                terminator.kind = match self.cleanup_block {
1339                    UnwindAction::Cleanup(tgt) => TerminatorKind::Goto { target: tgt },
1340                    UnwindAction::Continue => TerminatorKind::UnwindResume,
1341                    UnwindAction::Unreachable => TerminatorKind::Unreachable,
1342                    UnwindAction::Terminate(reason) => TerminatorKind::UnwindTerminate(reason),
1343                };
1344            }
1345            TerminatorKind::UnwindTerminate(_) => {}
1346            TerminatorKind::Unreachable => {}
1347            TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
1348                *real_target = self.map_block(*real_target);
1349                *imaginary_target = self.map_block(*imaginary_target);
1350            }
1351            TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
1352            // see the ordering of passes in the optimized_mir query.
1353            {
1354                bug!("False unwinds should have been removed before inlining")
1355            }
1356            TerminatorKind::InlineAsm { ref mut targets, ref mut unwind, .. } => {
1357                for tgt in targets.iter_mut() {
1358                    *tgt = self.map_block(*tgt);
1359                }
1360                *unwind = self.map_unwind(*unwind);
1361            }
1362        }
1363    }
1364}
1365
1366#[instrument(skip(tcx), level = "debug")]
1367fn try_instance_mir<'tcx>(
1368    tcx: TyCtxt<'tcx>,
1369    instance: InstanceKind<'tcx>,
1370) -> Result<&'tcx Body<'tcx>, &'static str> {
1371    if let ty::InstanceKind::DropGlue(_, Some(ty)) | ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) =
1372        instance
1373        && let ty::Adt(def, args) = ty.kind()
1374    {
1375        let fields = def.all_fields();
1376        for field in fields {
1377            let field_ty = field.ty(tcx, args);
1378            if field_ty.has_param() && field_ty.has_aliases() {
1379                return Err("cannot build drop shim for polymorphic type");
1380            }
1381        }
1382    }
1383    Ok(tcx.instance_mir(instance))
1384}
1385
1386fn body_is_forwarder(body: &Body<'_>) -> bool {
1387    let TerminatorKind::Call { target, .. } = body.basic_blocks[START_BLOCK].terminator().kind
1388    else {
1389        return false;
1390    };
1391    if let Some(target) = target {
1392        let TerminatorKind::Return = body.basic_blocks[target].terminator().kind else {
1393            return false;
1394        };
1395    }
1396
1397    let max_blocks = if !body.is_polymorphic {
1398        2
1399    } else if target.is_none() {
1400        3
1401    } else {
1402        4
1403    };
1404    if body.basic_blocks.len() > max_blocks {
1405        return false;
1406    }
1407
1408    body.basic_blocks.iter_enumerated().all(|(bb, bb_data)| {
1409        bb == START_BLOCK
1410            || matches!(
1411                bb_data.terminator().kind,
1412                TerminatorKind::Return
1413                    | TerminatorKind::Drop { .. }
1414                    | TerminatorKind::UnwindResume
1415                    | TerminatorKind::UnwindTerminate(_)
1416            )
1417    })
1418}