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