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