Skip to main content

rustc_mir_transform/
cost_checker.rs

1use rustc_middle::mir::visit::*;
2use rustc_middle::mir::*;
3use rustc_middle::ty::{self, Ty, TyCtxt};
4use rustc_span::bug;
5
6const INSTR_COST: usize = 5;
7const CALL_PENALTY: usize = 25;
8const LANDINGPAD_PENALTY: usize = 50;
9const RESUME_PENALTY: usize = 45;
10const LARGE_SWITCH_PENALTY: usize = 20;
11const CONST_SWITCH_BONUS: usize = 10;
12
13/// Verify that the callee body is compatible with the caller.
14#[derive(#[automatically_derived]impl<'b, 'tcx> ::core::clone::Clone for
    CostChecker<'b, 'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        CostChecker {
            tcx: ::core::clone::Clone::clone(&self.tcx),
            typing_env: ::core::clone::Clone::clone(&self.typing_env),
            penalty: ::core::clone::Clone::clone(&self.penalty),
            bonus: ::core::clone::Clone::clone(&self.bonus),
            callee_body: ::core::clone::Clone::clone(&self.callee_body),
            instance: ::core::clone::Clone::clone(&self.instance),
        }
    }
}Clone)]
15pub(super) struct CostChecker<'b, 'tcx> {
16    tcx: TyCtxt<'tcx>,
17    typing_env: ty::TypingEnv<'tcx>,
18    penalty: usize,
19    bonus: usize,
20    callee_body: &'b Body<'tcx>,
21    instance: Option<ty::Instance<'tcx>>,
22}
23
24impl<'b, 'tcx> CostChecker<'b, 'tcx> {
25    pub(super) fn new(
26        tcx: TyCtxt<'tcx>,
27        typing_env: ty::TypingEnv<'tcx>,
28        instance: Option<ty::Instance<'tcx>>,
29        callee_body: &'b Body<'tcx>,
30    ) -> CostChecker<'b, 'tcx> {
31        CostChecker { tcx, typing_env, callee_body, instance, penalty: 0, bonus: 0 }
32    }
33
34    /// Add function-level costs not well-represented by the block-level costs.
35    ///
36    /// Needed because the `CostChecker` is used sometimes for just blocks,
37    /// and even the full `Inline` doesn't call `visit_body`, so there's nowhere
38    /// to put this logic in the visitor.
39    pub(super) fn add_function_level_costs(&mut self) {
40        // If the only has one Call (or similar), inlining isn't increasing the total
41        // number of calls, so give extra encouragement to inlining that.
42        if self.callee_body.basic_blocks.iter().filter(|bbd| is_call_like(bbd.terminator())).count()
43            == 1
44        {
45            self.bonus += CALL_PENALTY;
46        }
47    }
48
49    pub(super) fn cost(&self) -> usize {
50        usize::saturating_sub(self.penalty, self.bonus)
51    }
52
53    fn instantiate_ty(&self, v: Ty<'tcx>) -> Ty<'tcx> {
54        if let Some(instance) = self.instance {
55            instance.instantiate_mir(self.tcx, ty::EarlyBinder::bind(self.tcx, v))
56        } else {
57            v
58        }
59    }
60}
61
62impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> {
63    fn visit_operand(&mut self, operand: &Operand<'tcx>, _: Location) {
64        match operand {
65            Operand::RuntimeChecks(RuntimeChecks::UbChecks) => {
66                if !self
67                    .tcx
68                    .sess
69                    .opts
70                    .unstable_opts
71                    .inline_mir_preserve_debug
72                    .unwrap_or(self.tcx.sess.ub_checks())
73                {
74                    // If this is in optimized MIR it's because it's used later, so if we don't need UB
75                    // checks this session, give a bonus here to offset the cost of the call later.
76                    self.bonus += CALL_PENALTY;
77                }
78            }
79            _ => {}
80        }
81    }
82
83    fn visit_statement(&mut self, statement: &Statement<'tcx>, loc: Location) {
84        // Most costs are in rvalues and terminators, not in statements.
85        match statement.kind {
86            StatementKind::Intrinsic(ref ndi) => {
87                self.penalty += match **ndi {
88                    NonDivergingIntrinsic::Assume(..) => INSTR_COST,
89                    NonDivergingIntrinsic::CopyNonOverlapping(..) => CALL_PENALTY,
90                };
91            }
92            StatementKind::Assign((_, Rvalue::Use(Operand::Constant(ref constant), _)))
93                if #[allow(non_exhaustive_omitted_patterns)] match constant.const_ {
    Const::Val(ConstValue::ZeroSized, _) => true,
    _ => false,
}matches!(constant.const_, Const::Val(ConstValue::ZeroSized, _)) =>
94            {
95                // Assigning a ZST constant emits no code.
96            }
97            StatementKind::Assign(..) => self.penalty += INSTR_COST,
98            _ => {}
99        }
100        self.super_statement(statement, loc)
101    }
102
103    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, loc: Location) {
104        match &terminator.kind {
105            TerminatorKind::Drop { place, unwind, .. } => {
106                // If the place doesn't actually need dropping, treat it like a regular goto.
107                let ty = self.instantiate_ty(place.ty(self.callee_body, self.tcx).ty);
108                if ty.needs_drop(self.tcx, self.typing_env) {
109                    self.penalty += CALL_PENALTY;
110                    if let UnwindAction::Cleanup(_) = unwind {
111                        self.penalty += LANDINGPAD_PENALTY;
112                    }
113                }
114            }
115            TerminatorKind::Call { func, unwind, .. } => {
116                self.penalty += if let Some((def_id, ..)) = func.const_fn_def()
117                    && self.tcx.intrinsic(def_id).is_some()
118                {
119                    // Don't give intrinsics the extra penalty for calls
120                    INSTR_COST
121                } else {
122                    CALL_PENALTY
123                };
124                if let UnwindAction::Cleanup(_) = unwind {
125                    self.penalty += LANDINGPAD_PENALTY;
126                }
127            }
128            TerminatorKind::TailCall { .. } => {
129                self.penalty += CALL_PENALTY;
130            }
131            TerminatorKind::SwitchInt { discr, targets } => {
132                if #[allow(non_exhaustive_omitted_patterns)] match discr {
    Operand::Constant(_) | Operand::RuntimeChecks(_) => true,
    _ => false,
}matches!(discr, Operand::Constant(_) | Operand::RuntimeChecks(_)) {
133                    // Not only will this become a `Goto`, but likely other
134                    // things will be removable as unreachable.
135                    self.bonus += CONST_SWITCH_BONUS;
136                } else if targets.all_targets().len() > 3 {
137                    // More than false/true/unreachable gets extra cost.
138                    self.penalty += LARGE_SWITCH_PENALTY;
139                } else {
140                    self.penalty += INSTR_COST;
141                }
142            }
143            TerminatorKind::Assert { unwind, msg, .. } => {
144                self.penalty += if msg.is_optional_overflow_check()
145                    && !self
146                        .tcx
147                        .sess
148                        .opts
149                        .unstable_opts
150                        .inline_mir_preserve_debug
151                        .unwrap_or(self.tcx.sess.overflow_checks())
152                {
153                    INSTR_COST
154                } else {
155                    CALL_PENALTY
156                };
157                if let UnwindAction::Cleanup(_) = unwind {
158                    self.penalty += LANDINGPAD_PENALTY;
159                }
160            }
161            TerminatorKind::UnwindResume => self.penalty += RESUME_PENALTY,
162            TerminatorKind::InlineAsm { unwind, .. } => {
163                self.penalty += INSTR_COST;
164                if let UnwindAction::Cleanup(_) = unwind {
165                    self.penalty += LANDINGPAD_PENALTY;
166                }
167            }
168            TerminatorKind::Unreachable => {
169                self.bonus += INSTR_COST;
170            }
171            TerminatorKind::Goto { .. } | TerminatorKind::Return => {}
172            TerminatorKind::UnwindTerminate(..) => {}
173            kind @ (TerminatorKind::FalseUnwind { .. }
174            | TerminatorKind::FalseEdge { .. }
175            | TerminatorKind::Yield { .. }
176            | TerminatorKind::CoroutineDrop) => {
177                ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} should not be in runtime MIR", kind),
    Location::caller());bug!("{kind:?} should not be in runtime MIR");
178            }
179        }
180        self.super_terminator(terminator, loc)
181    }
182}
183
184/// A terminator that's more call-like (might do a bunch of work, might panic, etc)
185/// than it is goto-/return-like (no side effects, etc).
186///
187/// Used to treat multi-call functions (which could inline exponentially)
188/// different from those that only do one or none of these "complex" things.
189pub(super) fn is_call_like(terminator: &Terminator<'_>) -> bool {
190    use TerminatorKind::*;
191    match terminator.kind {
192        Call { .. } | TailCall { .. } | Drop { .. } | Assert { .. } | InlineAsm { .. } => true,
193
194        Goto { .. }
195        | SwitchInt { .. }
196        | UnwindResume
197        | UnwindTerminate(_)
198        | Return
199        | Unreachable => false,
200
201        Yield { .. } | CoroutineDrop | FalseEdge { .. } | FalseUnwind { .. } => {
202            ::core::panicking::unreachable_default_msg()unreachable!()
203        }
204    }
205}