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