LLVM 24.0.0git
InlineCost.h
Go to the documentation of this file.
1//===- InlineCost.h - Cost analysis for inliner -----------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements heuristics for inlining decisions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ANALYSIS_INLINECOST_H
14#define LLVM_ANALYSIS_INLINECOST_H
15
16#include "llvm/ADT/APInt.h"
19#include "llvm/IR/PassManager.h"
21#include <cassert>
22#include <climits>
23#include <optional>
24
25namespace llvm {
26class AssumptionCache;
29class CallBase;
30class DataLayout;
31class Function;
32class LLVMContext;
37
38namespace InlineConstants {
39// Various thresholds used by inline cost analysis.
40/// Use when optsize (-Os) is specified.
41const int OptSizeThreshold = 50;
42
43/// Use when minsize (-Oz) is specified.
44const int OptMinSizeThreshold = 5;
45
46/// Use when -O3 is specified.
47const int OptAggressiveThreshold = 250;
48
49/// Return -inline-instr-cost.
51
52// Various magic constants used to adjust heuristics.
53const int IndirectCallThreshold = 100;
54const int LoopPenalty = 25;
55const int ColdccPenalty = 2000;
56/// Do not inline functions which allocate this many bytes on the stack
57/// when the caller is recursive.
58const unsigned TotalAllocaSizeRecursiveCaller = 1024;
59/// Do not inline dynamic allocas that have been constant propagated to be
60/// static allocas above this amount in bytes.
62
64 "function-inline-cost-multiplier";
65
66const char MaxInlineStackSizeAttributeName[] = "inline-max-stacksize";
67} // namespace InlineConstants
68
69// The cost-benefit pair computed by cost-benefit analysis.
71public:
73 : Cost(std::move(Cost)), Benefit(std::move(Benefit)) {}
74
75 const APInt &getCost() const { return Cost; }
76
77 const APInt &getBenefit() const { return Benefit; }
78
79private:
80 APInt Cost;
81 APInt Benefit;
82};
83
84/// Represents the cost of inlining a function.
85///
86/// This supports special values for functions which should "always" or
87/// "never" be inlined. Otherwise, the cost represents a unitless amount;
88/// smaller values increase the likelihood of the function being inlined.
89///
90/// Objects of this type also provide the adjusted threshold for inlining
91/// based on the information available for a particular callsite. They can be
92/// directly tested to determine if inlining should occur given the cost and
93/// threshold for this cost metric.
94class InlineCost {
95 enum SentinelValues { AlwaysInlineCost = INT_MIN, NeverInlineCost = INT_MAX };
96
97 /// The estimated cost of inlining this callsite.
98 int Cost = 0;
99
100 /// The adjusted threshold against which this cost was computed.
101 int Threshold = 0;
102
103 /// The amount of StaticBonus that has been applied.
104 int StaticBonusApplied = 0;
105
106 /// Must be set for Always and Never instances.
107 const char *Reason = nullptr;
108
109 /// The cost-benefit pair computed by cost-benefit analysis.
110 std::optional<CostBenefitPair> CostBenefit;
111
112 // Trivial constructor, interesting logic in the factory functions below.
113 InlineCost(int Cost, int Threshold, int StaticBonusApplied,
114 const char *Reason = nullptr,
115 std::optional<CostBenefitPair> CostBenefit = std::nullopt)
116 : Cost(Cost), Threshold(Threshold),
117 StaticBonusApplied(StaticBonusApplied), Reason(Reason),
118 CostBenefit(CostBenefit) {
119 assert((isVariable() || Reason) &&
120 "Reason must be provided for Never or Always");
121 }
122
123public:
124 static InlineCost get(int Cost, int Threshold, int StaticBonus = 0) {
125 assert(Cost > AlwaysInlineCost && "Cost crosses sentinel value");
126 assert(Cost < NeverInlineCost && "Cost crosses sentinel value");
127 return InlineCost(Cost, Threshold, StaticBonus);
128 }
129 static InlineCost
130 getAlways(const char *Reason,
131 std::optional<CostBenefitPair> CostBenefit = std::nullopt) {
132 return InlineCost(AlwaysInlineCost, 0, 0, Reason, CostBenefit);
133 }
134 static InlineCost
135 getNever(const char *Reason,
136 std::optional<CostBenefitPair> CostBenefit = std::nullopt) {
137 return InlineCost(NeverInlineCost, 0, 0, Reason, CostBenefit);
138 }
139
140 /// Test whether the inline cost is low enough for inlining.
141 explicit operator bool() const { return Cost < Threshold; }
142
143 bool isAlways() const { return Cost == AlwaysInlineCost; }
144 bool isNever() const { return Cost == NeverInlineCost; }
145 bool isVariable() const { return !isAlways() && !isNever(); }
146
147 /// Get the inline cost estimate.
148 /// It is an error to call this on an "always" or "never" InlineCost.
149 int getCost() const {
150 assert(isVariable() && "Invalid access of InlineCost");
151 return Cost;
152 }
153
154 /// Get the threshold against which the cost was computed
155 int getThreshold() const {
156 assert(isVariable() && "Invalid access of InlineCost");
157 return Threshold;
158 }
159
160 /// Get the amount of StaticBonus applied.
162 assert(isVariable() && "Invalid access of InlineCost");
163 return StaticBonusApplied;
164 }
165
166 /// Get the cost-benefit pair which was computed by cost-benefit analysis
167 std::optional<CostBenefitPair> getCostBenefit() const { return CostBenefit; }
168
169 /// Get the reason of Always or Never.
170 const char *getReason() const {
171 assert((Reason || isVariable()) &&
172 "InlineCost reason must be set for Always or Never");
173 return Reason;
174 }
175
176 /// Get the cost delta from the threshold for inlining.
177 /// Only valid if the cost is of the variable kind. Returns a negative
178 /// value if the cost is too high to inline.
179 int getCostDelta() const { return Threshold - getCost(); }
180};
181
182/// InlineResult is basically true or false. For false results the message
183/// describes a reason.
184class InlineResult {
185 const char *Message = nullptr;
186 InlineResult(const char *Message = nullptr) : Message(Message) {}
187
188public:
189 static InlineResult success() { return {}; }
190 static InlineResult failure(const char *Reason) {
191 return InlineResult(Reason);
192 }
193 bool isSuccess() const { return Message == nullptr; }
194 const char *getFailureReason() const {
195 assert(!isSuccess() &&
196 "getFailureReason should only be called in failure cases");
197 return Message;
198 }
199};
200
201/// Thresholds to tune inline cost analysis. The inline cost analysis decides
202/// the condition to apply a threshold and applies it. Otherwise,
203/// DefaultThreshold is used. If a threshold is Optional, it is applied only
204/// when it has a valid value. Typically, users of inline cost analysis
205/// obtain an InlineParams object through one of the \c getInlineParams methods
206/// and pass it to \c getInlineCost. Some specialized versions of inliner
207/// (such as the pre-inliner) might have custom logic to compute \c InlineParams
208/// object.
209
211 /// The default threshold to start with for a callee.
213
214 /// Threshold to use for callees with inline hint.
215 std::optional<int> HintThreshold;
216
217 /// Threshold to use for callees with inline hint, when the caller is
218 /// optimized for size.
219 std::optional<int> OptSizeHintThreshold;
220
221 /// Threshold to use for cold callees.
222 std::optional<int> ColdThreshold;
223
224 /// Threshold to use when the caller is optimized for size.
225 std::optional<int> OptSizeThreshold;
226
227 /// Threshold to use when the caller is optimized for minsize.
228 std::optional<int> OptMinSizeThreshold;
229
230 /// Threshold to use when the callsite is considered hot.
231 std::optional<int> HotCallSiteThreshold;
232
233 /// Threshold to use when the callsite is considered hot relative to function
234 /// entry.
235 std::optional<int> LocallyHotCallSiteThreshold;
236
237 /// Threshold to use when the callsite is considered cold.
238 std::optional<int> ColdCallSiteThreshold;
239
240 /// Compute inline cost even when the cost has exceeded the threshold.
241 std::optional<bool> ComputeFullInlineCost;
242
243 /// Indicate whether we should allow inline deferral.
244 std::optional<bool> EnableDeferral;
245
246 /// Indicate whether we allow inlining for recursive call.
247 std::optional<bool> AllowRecursiveCall = false;
248
249 /// Indicate whether to ignore profile information. If set, the inline cost
250 /// analysis is performed without the profile summary and block frequency
251 /// info.
252 std::optional<bool> IgnoreProfile = false;
253};
254
255LLVM_ABI std::optional<int> getStringFnAttrAsInt(CallBase &CB,
256 StringRef AttrKind);
257
258/// Generate the parameters to tune the inline cost analysis based only on the
259/// commandline options.
261
262/// Generate the parameters to tune the inline cost analysis based on command
263/// line options. If -inline-threshold option is not explicitly passed,
264/// \p Threshold is used as the default threshold.
265LLVM_ABI InlineParams getInlineParams(const LLVMContext &C, int Threshold);
266
267/// Generate the parameters to tune the inline cost analysis based on command
268/// line options. If -inline-threshold option is not explicitly passed,
269/// the default threshold is computed from \p OptLevel.
270/// An \p OptLevel value above 3 is considered an aggressive optimization mode.
271/// Optimization for size is handled via separate thresholds for
272/// optsize/minsize, rather than changes to the default threshold.
274 unsigned OptLevel);
275
276/// Return the cost associated with a callsite, including parameter passing
277/// and the call/return instruction.
279 const CallBase &Call, const DataLayout &DL);
280
281/// Get an InlineCost object representing the cost of inlining this
282/// callsite.
283///
284/// Note that a default threshold is passed into this function. This threshold
285/// could be modified based on callsite's properties and only costs below this
286/// new threshold are computed with any accuracy. The new threshold can be
287/// used to bound the computation necessary to determine whether the cost is
288/// sufficiently low to warrant inlining.
289///
290/// Also note that calling this function *dynamically* computes the cost of
291/// inlining the callsite. It is an expensive, heavyweight call.
293 CallBase &Call, const InlineParams &Params, TargetTransformInfo &CallerTTI,
294 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
295 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
296 function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
297 ProfileSummaryInfo *PSI = nullptr, OptimizationRemarkEmitter *ORE = nullptr,
298 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache =
299 nullptr);
300
301/// Get an InlineCost with the callee explicitly specified.
302/// This allows you to calculate the cost of inlining a function via a
303/// pointer. This behaves exactly as the version with no explicit callee
304/// parameter in all other respects.
305//
307 CallBase &Call, Function *Callee, const InlineParams &Params,
308 TargetTransformInfo &CallerTTI,
309 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
310 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
311 function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
312 ProfileSummaryInfo *PSI = nullptr, OptimizationRemarkEmitter *ORE = nullptr,
313 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache =
314 nullptr);
315
316/// Returns InlineResult::success() if the call site should be always inlined
317/// because of user directives, and the inlining is viable. Returns
318/// InlineResult::failure() if the inlining may never happen because of user
319/// directives or incompatibilities detectable without needing callee traversal.
320/// Otherwise returns std::nullopt, meaning that inlining should be decided
321/// based on other criteria (e.g. cost modeling).
322LLVM_ABI std::optional<InlineResult> getAttributeBasedInliningDecision(
323 CallBase &Call, Function *Callee, TargetTransformInfo &CallerTTI,
324 function_ref<const TargetLibraryInfo &(Function &)> GetTLI);
325
326/// Get the cost estimate ignoring thresholds. This is similar to getInlineCost
327/// when passed InlineParams::ComputeFullInlineCost, or a non-null ORE. It
328/// uses default InlineParams otherwise.
329/// Contrary to getInlineCost, which makes a threshold-based final evaluation of
330/// should/shouldn't inline, captured in InlineResult, getInliningCostEstimate
331/// returns:
332/// - std::nullopt, if the inlining cannot happen (is illegal)
333/// - an integer, representing the cost.
334LLVM_ABI std::optional<int> getInliningCostEstimate(
335 CallBase &Call, TargetTransformInfo &CallerTTI,
336 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
337 function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
338 function_ref<const TargetLibraryInfo &(Function &)> GetTLI = nullptr,
339 ProfileSummaryInfo *PSI = nullptr,
340 OptimizationRemarkEmitter *ORE = nullptr);
341
342/// Get the expanded cost features. The features are returned unconditionally,
343/// even if inlining is impossible.
344LLVM_ABI std::optional<InlineCostFeatures> getInliningCostFeatures(
345 CallBase &Call, TargetTransformInfo &CallerTTI,
346 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
347 function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
348 function_ref<const TargetLibraryInfo &(Function &)> GetTLI = nullptr,
349 ProfileSummaryInfo *PSI = nullptr,
350 OptimizationRemarkEmitter *ORE = nullptr);
351
352/// Check if it is mechanically possible to inline the function \p Callee, based
353/// on the contents of the function.
354///
355/// See also \p CanInlineCallSite as an additional precondition necessary to
356/// perform a valid inline in a particular use context.
358
359// This pass is used to annotate instructions during the inline process for
360// debugging and analysis. The main purpose of the pass is to see and test
361// inliner's decisions when creating new optimizations to InlineCost.
370} // namespace llvm
371
372#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
FunctionAnalysisManager FAM
Class for arbitrary precision integers.
Definition APInt.h:78
A cache of @llvm.assume calls within a function.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
const APInt & getBenefit() const
Definition InlineCost.h:77
CostBenefitPair(APInt Cost, APInt Benefit)
Definition InlineCost.h:72
const APInt & getCost() const
Definition InlineCost.h:75
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A cache of ephemeral values within a function.
Represents the cost of inlining a function.
Definition InlineCost.h:94
std::optional< CostBenefitPair > getCostBenefit() const
Get the cost-benefit pair which was computed by cost-benefit analysis.
Definition InlineCost.h:167
int getThreshold() const
Get the threshold against which the cost was computed.
Definition InlineCost.h:155
const char * getReason() const
Get the reason of Always or Never.
Definition InlineCost.h:170
int getStaticBonusApplied() const
Get the amount of StaticBonus applied.
Definition InlineCost.h:161
int getCost() const
Get the inline cost estimate.
Definition InlineCost.h:149
static InlineCost getNever(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:135
static InlineCost getAlways(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:130
static InlineCost get(int Cost, int Threshold, int StaticBonus=0)
Definition InlineCost.h:124
bool isAlways() const
Definition InlineCost.h:143
int getCostDelta() const
Get the cost delta from the threshold for inlining.
Definition InlineCost.h:179
bool isVariable() const
Definition InlineCost.h:145
bool isNever() const
Definition InlineCost.h:144
InlineResult is basically true or false.
Definition InlineCost.h:184
static InlineResult success()
Definition InlineCost.h:189
static InlineResult failure(const char *Reason)
Definition InlineCost.h:190
bool isSuccess() const
Definition InlineCost.h:193
const char * getFailureReason() const
Definition InlineCost.h:194
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
The optimization diagnostic interface.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Analysis providing profile information.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
LLVM_ABI int getInstrCost(const LLVMContext &C)
Return -inline-instr-cost.
const int ColdccPenalty
Definition InlineCost.h:55
const char FunctionInlineCostMultiplierAttributeName[]
Definition InlineCost.h:63
const int OptSizeThreshold
Use when optsize (-Os) is specified.
Definition InlineCost.h:41
const int OptMinSizeThreshold
Use when minsize (-Oz) is specified.
Definition InlineCost.h:44
const uint64_t MaxSimplifiedDynamicAllocaToInline
Do not inline dynamic allocas that have been constant propagated to be static allocas above this amou...
Definition InlineCost.h:61
const int IndirectCallThreshold
Definition InlineCost.h:53
const int OptAggressiveThreshold
Use when -O3 is specified.
Definition InlineCost.h:47
const char MaxInlineStackSizeAttributeName[]
Definition InlineCost.h:66
const unsigned TotalAllocaSizeRecursiveCaller
Do not inline functions which allocate this many bytes on the stack when the caller is recursive.
Definition InlineCost.h:58
This is an optimization pass for GlobalISel generic memory operations.
InstructionCost Cost
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
LLVM_ABI InlineParams getInlineParams(const LLVMContext &C)
Generate the parameters to tune the inline cost analysis based only on the commandline options.
LLVM_ABI std::optional< int > getStringFnAttrAsInt(CallBase &CB, StringRef AttrKind)
LLVM_ABI std::optional< InlineResult > getAttributeBasedInliningDecision(CallBase &Call, Function *Callee, TargetTransformInfo &CallerTTI, function_ref< const TargetLibraryInfo &(Function &)> GetTLI)
Returns InlineResult::success() if the call site should be always inlined because of user directives,...
LLVM_ABI InlineResult isInlineViable(Function &Callee)
Check if it is mechanically possible to inline the function Callee, based on the contents of the func...
LLVM_ABI InlineParams getInlineParamsFromOptLevel(const LLVMContext &C, unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
TargetTransformInfo TTI
LLVM_ABI std::optional< int > getInliningCostEstimate(CallBase &Call, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, function_ref< const TargetLibraryInfo &(Function &)> GetTLI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Get the cost estimate ignoring thresholds.
LLVM_ABI int getCallsiteCost(const TargetTransformInfo &TTI, const CallBase &Call, const DataLayout &DL)
Return the cost associated with a callsite, including parameter passing and the call/return instructi...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI std::optional< InlineCostFeatures > getInliningCostFeatures(CallBase &Call, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, function_ref< const TargetLibraryInfo &(Function &)> GetTLI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Get the expanded cost features.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
InlineCostAnnotationPrinterPass(raw_ostream &OS)
Definition InlineCost.h:367
Thresholds to tune inline cost analysis.
Definition InlineCost.h:210
std::optional< int > OptMinSizeThreshold
Threshold to use when the caller is optimized for minsize.
Definition InlineCost.h:228
std::optional< int > OptSizeThreshold
Threshold to use when the caller is optimized for size.
Definition InlineCost.h:225
std::optional< int > OptSizeHintThreshold
Threshold to use for callees with inline hint, when the caller is optimized for size.
Definition InlineCost.h:219
std::optional< int > ColdCallSiteThreshold
Threshold to use when the callsite is considered cold.
Definition InlineCost.h:238
std::optional< int > ColdThreshold
Threshold to use for cold callees.
Definition InlineCost.h:222
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition InlineCost.h:231
std::optional< bool > IgnoreProfile
Indicate whether to ignore profile information.
Definition InlineCost.h:252
std::optional< bool > AllowRecursiveCall
Indicate whether we allow inlining for recursive call.
Definition InlineCost.h:247
int DefaultThreshold
The default threshold to start with for a callee.
Definition InlineCost.h:212
std::optional< bool > EnableDeferral
Indicate whether we should allow inline deferral.
Definition InlineCost.h:244
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition InlineCost.h:215
std::optional< int > LocallyHotCallSiteThreshold
Threshold to use when the callsite is considered hot relative to function entry.
Definition InlineCost.h:235
std::optional< bool > ComputeFullInlineCost
Compute inline cost even when the cost has exceeded the threshold.
Definition InlineCost.h:241
A CRTP mix-in for passes that should not be skipped.