rustc_mir_transform/
cross_crate_inline.rs

1use rustc_attr_data_structures::InlineAttr;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::LocalDefId;
4use rustc_middle::mir::visit::Visitor;
5use rustc_middle::mir::*;
6use rustc_middle::query::Providers;
7use rustc_middle::ty::TyCtxt;
8use rustc_session::config::{InliningThreshold, OptLevel};
9use rustc_span::sym;
10
11use crate::{inline, pass_manager as pm};
12
13pub(super) fn provide(providers: &mut Providers) {
14    providers.cross_crate_inlinable = cross_crate_inlinable;
15}
16
17fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
18    let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
19    // If this has an extern indicator, then this function is globally shared and thus will not
20    // generate cgu-internal copies which would make it cross-crate inlinable.
21    if codegen_fn_attrs.contains_extern_indicator() {
22        return false;
23    }
24
25    // This just reproduces the logic from Instance::requires_inline.
26    match tcx.def_kind(def_id) {
27        DefKind::Ctor(..) | DefKind::Closure | DefKind::SyntheticCoroutineBody => return true,
28        DefKind::Fn | DefKind::AssocFn => {}
29        _ => return false,
30    }
31
32    // From this point on, it is valid to return true or false.
33    if tcx.sess.opts.unstable_opts.cross_crate_inline_threshold == InliningThreshold::Always {
34        return true;
35    }
36
37    if tcx.has_attr(def_id, sym::rustc_intrinsic) {
38        // Intrinsic fallback bodies are always cross-crate inlineable.
39        // To ensure that the MIR inliner doesn't cluelessly try to inline fallback
40        // bodies even when the backend would implement something better, we stop
41        // the MIR inliner from ever inlining an intrinsic.
42        return true;
43    }
44
45    // Obey source annotations first; this is important because it means we can use
46    // #[inline(never)] to force code generation.
47    match codegen_fn_attrs.inline {
48        InlineAttr::Never => return false,
49        InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. } => return true,
50        _ => {}
51    }
52
53    // If the crate is likely to be mostly unused, use cross-crate inlining to defer codegen until
54    // the function is referenced, in order to skip codegen for unused functions. This is
55    // intentionally after the check for `inline(never)`, so that `inline(never)` wins.
56    if tcx.sess.opts.unstable_opts.hint_mostly_unused {
57        return true;
58    }
59
60    let sig = tcx.fn_sig(def_id).instantiate_identity();
61    for ty in sig.inputs().skip_binder().iter().chain(std::iter::once(&sig.output().skip_binder()))
62    {
63        // FIXME(f16_f128): in order to avoid crashes building `core`, always inline to skip
64        // codegen if the function is not used.
65        if ty == &tcx.types.f16 || ty == &tcx.types.f128 {
66            return true;
67        }
68    }
69
70    // Don't do any inference when incremental compilation is enabled; the additional inlining that
71    // inference permits also creates more work for small edits.
72    if tcx.sess.opts.incremental.is_some() {
73        return false;
74    }
75
76    // Don't do any inference if codegen optimizations are disabled and also MIR inlining is not
77    // enabled. This ensures that we do inference even if someone only passes -Zinline-mir,
78    // which is less confusing than having to also enable -Copt-level=1.
79    let inliner_will_run = pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
80        || inline::ForceInline::should_run_pass_for_callee(tcx, def_id.to_def_id());
81    if matches!(tcx.sess.opts.optimize, OptLevel::No) && !inliner_will_run {
82        return false;
83    }
84
85    if !tcx.is_mir_available(def_id) {
86        return false;
87    }
88
89    let threshold = match tcx.sess.opts.unstable_opts.cross_crate_inline_threshold {
90        InliningThreshold::Always => return true,
91        InliningThreshold::Sometimes(threshold) => threshold,
92        InliningThreshold::Never => return false,
93    };
94
95    let mir = tcx.optimized_mir(def_id);
96    let mut checker =
97        CostChecker { tcx, callee_body: mir, calls: 0, statements: 0, landing_pads: 0, resumes: 0 };
98    checker.visit_body(mir);
99    checker.calls == 0
100        && checker.resumes == 0
101        && checker.landing_pads == 0
102        && checker.statements <= threshold
103}
104
105struct CostChecker<'b, 'tcx> {
106    tcx: TyCtxt<'tcx>,
107    callee_body: &'b Body<'tcx>,
108    calls: usize,
109    statements: usize,
110    landing_pads: usize,
111    resumes: usize,
112}
113
114impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> {
115    fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
116        // Don't count StorageLive/StorageDead in the inlining cost.
117        match statement.kind {
118            StatementKind::StorageLive(_)
119            | StatementKind::StorageDead(_)
120            | StatementKind::Deinit(_)
121            | StatementKind::Nop => {}
122            _ => self.statements += 1,
123        }
124    }
125
126    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, _: Location) {
127        let tcx = self.tcx;
128        match terminator.kind {
129            TerminatorKind::Drop { ref place, unwind, .. } => {
130                let ty = place.ty(self.callee_body, tcx).ty;
131                if !ty.is_trivially_pure_clone_copy() {
132                    self.calls += 1;
133                    if let UnwindAction::Cleanup(_) = unwind {
134                        self.landing_pads += 1;
135                    }
136                }
137            }
138            TerminatorKind::Call { unwind, .. } => {
139                self.calls += 1;
140                if let UnwindAction::Cleanup(_) = unwind {
141                    self.landing_pads += 1;
142                }
143            }
144            TerminatorKind::Assert { unwind, .. } => {
145                self.calls += 1;
146                if let UnwindAction::Cleanup(_) = unwind {
147                    self.landing_pads += 1;
148                }
149            }
150            TerminatorKind::UnwindResume => self.resumes += 1,
151            TerminatorKind::InlineAsm { unwind, .. } => {
152                self.statements += 1;
153                if let UnwindAction::Cleanup(_) = unwind {
154                    self.landing_pads += 1;
155                }
156            }
157            TerminatorKind::Return => {}
158            _ => self.statements += 1,
159        }
160    }
161}