LLVM 24.0.0git
InlineCost.cpp
Go to the documentation of this file.
1//===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
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 inline cost analysis.
10//
11//===----------------------------------------------------------------------===//
12
14#include "AnalysisOptions.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/Statistic.h"
34#include "llvm/Config/llvm-config.h"
36#include "llvm/IR/CallingConv.h"
37#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/GlobalAlias.h"
40#include "llvm/IR/InlineAsm.h"
41#include "llvm/IR/InstVisitor.h"
43#include "llvm/IR/Operator.h"
46#include "llvm/Support/Debug.h"
49#include <climits>
50#include <limits>
51#include <optional>
52
53using namespace llvm;
54
55#define DEBUG_TYPE "inline-cost"
56
57STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
58
59static cl::opt<int>
60 DefaultThreshold("inlinedefault-threshold", cl::Hidden, cl::init(225),
61 cl::desc("Default amount of inlining to perform"));
62
64 "inline-threshold", cl::Hidden, cl::init(225),
65 cl::desc("Control the amount of inlining to perform (default = 225)"));
66
68 "inlinehint-threshold", cl::Hidden, cl::init(325),
69 cl::desc("Threshold for inlining functions with inline hint"));
70
71static cl::opt<int>
72 ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
73 cl::init(45),
74 cl::desc("Threshold for inlining cold callsites"));
75
76// We introduce this threshold to help performance of instrumentation based
77// PGO before we actually hook up inliner with analysis passes such as BPI and
78// BFI.
80 "inlinecold-threshold", cl::Hidden, cl::init(45),
81 cl::desc("Threshold for inlining functions with cold attribute"));
82
83static cl::opt<int>
84 HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
85 cl::desc("Threshold for hot callsites "));
86
88 "locally-hot-callsite-threshold", cl::Hidden, cl::init(525),
89 cl::desc("Threshold for locally hot callsites "));
90
91static cl::opt<int>
92 InstrCost("inline-instr-cost", cl::Hidden, cl::init(5),
93 cl::desc("Cost of a single instruction when inlining"));
94
95namespace llvm {
96std::optional<int> getStringFnAttrAsInt(const Attribute &Attr) {
97 if (Attr.isValid()) {
98 int AttrValue = 0;
99 if (!Attr.getValueAsString().getAsInteger(10, AttrValue))
100 return AttrValue;
101 }
102 return std::nullopt;
103}
104
105std::optional<int> getStringFnAttrAsInt(CallBase &CB, StringRef AttrKind) {
106 return getStringFnAttrAsInt(CB.getFnAttr(AttrKind));
107}
108
109std::optional<int> getStringFnAttrAsInt(Function *F, StringRef AttrKind) {
110 return getStringFnAttrAsInt(F->getFnAttribute(AttrKind));
111}
112
113namespace InlineConstants {
114int getInstrCost() { return InstrCost; }
115
116} // namespace InlineConstants
117
118} // namespace llvm
119
120namespace {
121class InlineCostCallAnalyzer;
122
123// This struct is used to store information about inline cost of a
124// particular instruction
125struct InstructionCostDetail {
126 int CostBefore = 0;
127 int CostAfter = 0;
128 int ThresholdBefore = 0;
129 int ThresholdAfter = 0;
130
131 int getThresholdDelta() const { return ThresholdAfter - ThresholdBefore; }
132
133 int getCostDelta() const { return CostAfter - CostBefore; }
134
135 bool hasThresholdChanged() const { return ThresholdAfter != ThresholdBefore; }
136};
137
138class InlineCostAnnotationWriter : public AssemblyAnnotationWriter {
139private:
140 InlineCostCallAnalyzer *const ICCA;
141
142public:
143 InlineCostAnnotationWriter(InlineCostCallAnalyzer *ICCA) : ICCA(ICCA) {}
144 void emitInstructionAnnot(const Instruction *I,
145 formatted_raw_ostream &OS) override;
146};
147
148/// Carry out call site analysis, in order to evaluate inlinability.
149/// NOTE: the type is currently used as implementation detail of functions such
150/// as llvm::getInlineCost. Note the function_ref constructor parameters - the
151/// expectation is that they come from the outer scope, from the wrapper
152/// functions. If we want to support constructing CallAnalyzer objects where
153/// lambdas are provided inline at construction, or where the object needs to
154/// otherwise survive past the scope of the provided functions, we need to
155/// revisit the argument types.
156class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
157 typedef InstVisitor<CallAnalyzer, bool> Base;
158 friend class InstVisitor<CallAnalyzer, bool>;
159
160protected:
161 virtual ~CallAnalyzer() = default;
162 const AnalysisOptions &Opts;
163
164 /// The TargetTransformInfo available for this compilation.
165 const TargetTransformInfo &TTI;
166
167 /// Getter for the cache of @llvm.assume intrinsics.
168 function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
169
170 /// Getter for BlockFrequencyInfo
171 function_ref<BlockFrequencyInfo &(Function &)> GetBFI;
172
173 /// Getter for TargetLibraryInfo
174 function_ref<const TargetLibraryInfo &(Function &)> GetTLI;
175
176 /// Profile summary information.
177 ProfileSummaryInfo *PSI;
178
179 /// The called function.
180 Function &F;
181
182 // Cache the DataLayout since we use it a lot.
183 const DataLayout &DL;
184
185 /// The OptimizationRemarkEmitter available for this compilation.
186 OptimizationRemarkEmitter *ORE;
187
188 /// The candidate callsite being analyzed. Please do not use this to do
189 /// analysis in the caller function; we want the inline cost query to be
190 /// easily cacheable. Instead, use the cover function paramHasAttr.
191 CallBase &CandidateCall;
192
193 /// Getter for the cache of ephemeral values.
194 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache = nullptr;
195
196 /// Extension points for handling callsite features.
197 // Called before a basic block was analyzed.
198 virtual void onBlockStart(const BasicBlock *BB) {}
199
200 /// Called after a basic block was analyzed.
201 virtual void onBlockAnalyzed(const BasicBlock *BB) {}
202
203 /// Called before an instruction was analyzed
204 virtual void onInstructionAnalysisStart(const Instruction *I) {}
205
206 /// Called after an instruction was analyzed
207 virtual void onInstructionAnalysisFinish(const Instruction *I) {}
208
209 /// Called at the end of the analysis of the callsite. Return the outcome of
210 /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or
211 /// the reason it can't.
212 virtual InlineResult finalizeAnalysis() { return InlineResult::success(); }
213 /// Called when we're about to start processing a basic block, and every time
214 /// we are done processing an instruction. Return true if there is no point in
215 /// continuing the analysis (e.g. we've determined already the call site is
216 /// too expensive to inline)
217 virtual bool shouldStop() { return false; }
218
219 /// Called before the analysis of the callee body starts (with callsite
220 /// contexts propagated). It checks callsite-specific information. Return a
221 /// reason analysis can't continue if that's the case, or 'true' if it may
222 /// continue.
223 virtual InlineResult onAnalysisStart() { return InlineResult::success(); }
224 /// Called if the analysis engine decides SROA cannot be done for the given
225 /// alloca.
226 virtual void onDisableSROA(AllocaInst *Arg) {}
227
228 /// Called the analysis engine determines load elimination won't happen.
229 virtual void onDisableLoadElimination() {}
230
231 /// Called when we visit a CallBase, before the analysis starts. Return false
232 /// to stop further processing of the instruction.
233 virtual bool onCallBaseVisitStart(CallBase &Call) { return true; }
234
235 /// Called to account for a call.
236 virtual void onCallPenalty() {}
237
238 /// Called to account for a load or store.
239 virtual void onMemAccess(){};
240
241 /// Called to account for the expectation the inlining would result in a load
242 /// elimination.
243 virtual void onLoadEliminationOpportunity() {}
244
245 /// Called to account for the cost of argument setup for the Call in the
246 /// callee's body (not the callsite currently under analysis).
247 virtual void onCallArgumentSetup(const CallBase &Call) {}
248
249 /// Called to account for a load relative intrinsic.
250 virtual void onLoadRelativeIntrinsic() {}
251
252 /// Called to account for a lowered call.
253 virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) {
254 }
255
256 /// Account for a jump table of given size. Return false to stop further
257 /// processing the switch instruction
258 virtual bool onJumpTable(unsigned JumpTableSize) { return true; }
259
260 /// Account for a case cluster of given size. Return false to stop further
261 /// processing of the instruction.
262 virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; }
263
264 /// Called at the end of processing a switch instruction, with the given
265 /// number of case clusters.
266 virtual void onFinalizeSwitch(unsigned JumpTableSize, unsigned NumCaseCluster,
267 bool DefaultDestUnreachable) {}
268
269 /// Called to account for any other instruction not specifically accounted
270 /// for.
271 virtual void onMissedSimplification() {}
272
273 /// Account for inline assembly instructions.
274 virtual void onInlineAsm(const InlineAsm &Arg) {}
275
276 /// Start accounting potential benefits due to SROA for the given alloca.
277 virtual void onInitializeSROAArg(AllocaInst *Arg) {}
278
279 /// Account SROA savings for the AllocaInst value.
280 virtual void onAggregateSROAUse(AllocaInst *V) {}
281
282 bool handleSROA(Value *V, bool DoNotDisable) {
283 // Check for SROA candidates in comparisons.
284 if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
285 if (DoNotDisable) {
286 onAggregateSROAUse(SROAArg);
287 return true;
288 }
289 disableSROAForArg(SROAArg);
290 }
291 return false;
292 }
293
294 bool IsCallerRecursive = false;
295 bool IsRecursiveCall = false;
296 bool ExposesReturnsTwice = false;
297 bool HasDynamicAlloca = false;
298 bool ContainsNoDuplicateCall = false;
299 bool HasReturn = false;
300 bool HasIndirectBr = false;
301 bool HasUninlineableIntrinsic = false;
302 bool InitsVargArgs = false;
303
304 /// Number of bytes allocated statically by the callee.
305 uint64_t AllocatedSize = 0;
306 unsigned NumInstructions = 0;
307 unsigned NumInlineAsmInstructions = 0;
308 unsigned NumVectorInstructions = 0;
309
310 /// While we walk the potentially-inlined instructions, we build up and
311 /// maintain a mapping of simplified values specific to this callsite. The
312 /// idea is to propagate any special information we have about arguments to
313 /// this call through the inlinable section of the function, and account for
314 /// likely simplifications post-inlining. The most important aspect we track
315 /// is CFG altering simplifications -- when we prove a basic block dead, that
316 /// can cause dramatic shifts in the cost of inlining a function.
317 /// Note: The simplified Value may be owned by the caller function.
318 DenseMap<Value *, Value *> SimplifiedValues;
319
320 /// Keep track of the values which map back (through function arguments) to
321 /// allocas on the caller stack which could be simplified through SROA.
322 DenseMap<Value *, AllocaInst *> SROAArgValues;
323
324 /// Keep track of Allocas for which we believe we may get SROA optimization.
325 DenseSet<AllocaInst *> EnabledSROAAllocas;
326
327 /// Keep track of values which map to a pointer base and constant offset.
328 DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
329
330 /// Keep track of dead blocks due to the constant arguments.
331 SmallPtrSet<BasicBlock *, 16> DeadBlocks;
332
333 /// The mapping of the blocks to their known unique successors due to the
334 /// constant arguments.
335 DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
336
337 /// Model the elimination of repeated loads that is expected to happen
338 /// whenever we simplify away the stores that would otherwise cause them to be
339 /// loads.
340 bool EnableLoadElimination = true;
341
342 /// Whether we allow inlining for recursive call.
343 bool AllowRecursiveCall = false;
344
345 SmallPtrSet<Value *, 16> LoadAddrSet;
346
347 AllocaInst *getSROAArgForValueOrNull(Value *V) const {
348 auto It = SROAArgValues.find(V);
349 if (It == SROAArgValues.end() || EnabledSROAAllocas.count(It->second) == 0)
350 return nullptr;
351 return It->second;
352 }
353
354 /// Use a value in its given form directly if possible, otherwise try looking
355 /// for it in SimplifiedValues.
356 template <typename T> T *getDirectOrSimplifiedValue(Value *V) const {
357 if (auto *Direct = dyn_cast<T>(V))
358 return Direct;
359 return getSimplifiedValue<T>(V);
360 }
361
362 // Custom simplification helper routines.
363 bool isAllocaDerivedArg(Value *V);
364 void disableSROAForArg(AllocaInst *SROAArg);
365 void disableSROA(Value *V);
366 void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
367 void disableLoadElimination();
368 bool isGEPFree(GetElementPtrInst &GEP);
369 bool canFoldInboundsGEP(GetElementPtrInst &I);
370 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
371 bool simplifyCallSite(Function *F, CallBase &Call);
372 bool simplifyCmpInstForRecCall(CmpInst &Cmp);
373 bool simplifyInstruction(Instruction &I);
374 bool simplifyIntrinsicCallIsConstant(CallBase &CB);
375 bool simplifyIntrinsicCallObjectSize(CallBase &CB);
376 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
377 bool isLoweredToCall(Function *F, CallBase &Call);
378
379 /// Return true if the given argument to the function being considered for
380 /// inlining has the given attribute set either at the call site or the
381 /// function declaration. Primarily used to inspect call site specific
382 /// attributes since these can be more precise than the ones on the callee
383 /// itself.
384 bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
385
386 /// Return true if the given value is known non null within the callee if
387 /// inlined through this particular callsite.
388 bool isKnownNonNullInCallee(Value *V);
389
390 /// Return true if size growth is allowed when inlining the callee at \p Call.
391 bool allowSizeGrowth(CallBase &Call);
392
393 // Custom analysis routines.
394 InlineResult analyzeBlock(BasicBlock *BB,
395 const SmallPtrSetImpl<const Value *> &EphValues);
396
397 // Disable several entry points to the visitor so we don't accidentally use
398 // them by declaring but not defining them here.
399 void visit(Module *);
400 void visit(Module &);
401 void visit(Function *);
402 void visit(Function &);
403 void visit(BasicBlock *);
404 void visit(BasicBlock &);
405
406 // Provide base case for our instruction visit.
407 bool visitInstruction(Instruction &I);
408
409 // Our visit overrides.
410 bool visitAlloca(AllocaInst &I);
411 bool visitPHI(PHINode &I);
412 bool visitGetElementPtr(GetElementPtrInst &I);
413 bool visitBitCast(BitCastInst &I);
414 bool visitPtrToInt(PtrToIntInst &I);
415 bool visitIntToPtr(IntToPtrInst &I);
416 bool visitCastInst(CastInst &I);
417 bool visitCmpInst(CmpInst &I);
418 bool visitSub(BinaryOperator &I);
419 bool visitBinaryOperator(BinaryOperator &I);
420 bool visitFNeg(UnaryOperator &I);
421 bool visitLoad(LoadInst &I);
422 bool visitStore(StoreInst &I);
423 bool visitExtractValue(ExtractValueInst &I);
424 bool visitInsertValue(InsertValueInst &I);
425 bool visitCallBase(CallBase &Call);
426 bool visitReturnInst(ReturnInst &RI);
427 bool visitUncondBrInst(UncondBrInst &BI);
428 bool visitCondBrInst(CondBrInst &BI);
429 bool visitSelectInst(SelectInst &SI);
430 bool visitSwitchInst(SwitchInst &SI);
431 bool visitIndirectBrInst(IndirectBrInst &IBI);
432 bool visitResumeInst(ResumeInst &RI);
433 bool visitCleanupReturnInst(CleanupReturnInst &RI);
434 bool visitCatchReturnInst(CatchReturnInst &RI);
435 bool visitUnreachableInst(UnreachableInst &I);
436
437public:
438 CallAnalyzer(
439 Function &Callee, CallBase &Call, const TargetTransformInfo &TTI,
440 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
441 function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
442 function_ref<const TargetLibraryInfo &(Function &)> GetTLI = nullptr,
443 ProfileSummaryInfo *PSI = nullptr,
444 OptimizationRemarkEmitter *ORE = nullptr,
445 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache =
446 nullptr)
447 : Opts(getAnalysisOptions(Callee)), TTI(TTI),
448 GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI), GetTLI(GetTLI),
449 PSI(PSI), F(Callee), DL(F.getDataLayout()), ORE(ORE),
450 CandidateCall(Call), GetEphValuesCache(GetEphValuesCache) {}
451
452 InlineResult analyze();
453
454 /// Lookup simplified Value. May return a value owned by the caller.
455 Value *getSimplifiedValueUnchecked(Value *V) const {
456 return SimplifiedValues.lookup(V);
457 }
458
459 /// Lookup simplified Value, but return nullptr if the simplified value is
460 /// owned by the caller.
461 template <typename T> T *getSimplifiedValue(Value *V) const {
462 Value *SimpleV = SimplifiedValues.lookup(V);
463 if (!SimpleV)
464 return nullptr;
465
466 // Skip checks if we know T is a global. This has a small, but measurable
467 // impact on compile-time.
468 if constexpr (std::is_base_of_v<Constant, T>)
469 return dyn_cast<T>(SimpleV);
470
471 // Make sure the simplified Value is owned by this function
472 if (auto *I = dyn_cast<Instruction>(SimpleV)) {
473 if (I->getFunction() != &F)
474 return nullptr;
475 } else if (auto *Arg = dyn_cast<Argument>(SimpleV)) {
476 if (Arg->getParent() != &F)
477 return nullptr;
478 } else if (!isa<Constant>(SimpleV))
479 return nullptr;
480 return dyn_cast<T>(SimpleV);
481 }
482
483 // Keep a bunch of stats about the cost savings found so we can print them
484 // out when debugging.
485 unsigned NumConstantArgs = 0;
486 unsigned NumConstantOffsetPtrArgs = 0;
487 unsigned NumAllocaArgs = 0;
488 unsigned NumConstantPtrCmps = 0;
489 unsigned NumConstantPtrDiffs = 0;
490 unsigned NumInstructionsSimplified = 0;
491
492 void dump();
493};
494
495// Considering forming a binary search, we should find the number of nodes
496// which is same as the number of comparisons when lowered. For a given
497// number of clusters, n, we can define a recursive function, f(n), to find
498// the number of nodes in the tree. The recursion is :
499// f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
500// and f(n) = n, when n <= 3.
501// This will lead a binary tree where the leaf should be either f(2) or f(3)
502// when n > 3. So, the number of comparisons from leaves should be n, while
503// the number of non-leaf should be :
504// 2^(log2(n) - 1) - 1
505// = 2^log2(n) * 2^-1 - 1
506// = n / 2 - 1.
507// Considering comparisons from leaf and non-leaf nodes, we can estimate the
508// number of comparisons in a simple closed form :
509// n + n / 2 - 1 = n * 3 / 2 - 1
510int64_t getExpectedNumberOfCompare(int NumCaseCluster) {
511 return 3 * static_cast<int64_t>(NumCaseCluster) / 2 - 1;
512}
513
514/// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
515/// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
516class InlineCostCallAnalyzer final : public CallAnalyzer {
517 const bool ComputeFullInlineCost;
518 int LoadEliminationCost = 0;
519 /// Bonus to be applied when percentage of vector instructions in callee is
520 /// high (see more details in updateThreshold).
521 int VectorBonus = 0;
522 /// Bonus to be applied when the callee has only one reachable basic block.
523 int SingleBBBonus = 0;
524
525 /// Tunable parameters that control the analysis.
526 const InlineParams &Params;
527
528 // This DenseMap stores the delta change in cost and threshold after
529 // accounting for the given instruction. The map is filled only with the
530 // flag PrintInstructionComments on.
531 DenseMap<const Instruction *, InstructionCostDetail> InstructionCostDetailMap;
532
533 /// Upper bound for the inlining cost. Bonuses are being applied to account
534 /// for speculative "expected profit" of the inlining decision.
535 int Threshold = 0;
536
537 /// The amount of StaticBonus applied.
538 int StaticBonusApplied = 0;
539
540 /// Attempt to evaluate indirect calls to boost its inline cost.
541 const bool BoostIndirectCalls;
542
543 /// Ignore the threshold when finalizing analysis.
544 const bool IgnoreThreshold;
545
546 // True if the cost-benefit-analysis-based inliner is enabled.
547 const bool CostBenefitAnalysisEnabled;
548
549 const bool PrintInstructionComments;
550
551 /// Inlining cost measured in abstract units, accounts for all the
552 /// instructions expected to be executed for a given function invocation.
553 /// Instructions that are statically proven to be dead based on call-site
554 /// arguments are not counted here.
555 int Cost = 0;
556
557 // The cumulative cost at the beginning of the basic block being analyzed. At
558 // the end of analyzing each basic block, "Cost - CostAtBBStart" represents
559 // the size of that basic block.
560 int CostAtBBStart = 0;
561
562 // The static size of live but cold basic blocks. This is "static" in the
563 // sense that it's not weighted by profile counts at all.
564 int ColdSize = 0;
565
566 // Whether inlining is decided by cost-threshold analysis.
567 bool DecidedByCostThreshold = false;
568
569 // Whether inlining is decided by cost-benefit analysis.
570 bool DecidedByCostBenefit = false;
571
572 // The cost-benefit pair computed by cost-benefit analysis.
573 std::optional<CostBenefitPair> CostBenefit;
574
575 bool SingleBB = true;
576
577 unsigned SROACostSavings = 0;
578 unsigned SROACostSavingsLost = 0;
579
580 /// The mapping of caller Alloca values to their accumulated cost savings. If
581 /// we have to disable SROA for one of the allocas, this tells us how much
582 /// cost must be added.
583 DenseMap<AllocaInst *, int> SROAArgCosts;
584
585 /// Return true if \p Call is a cold callsite.
586 bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
587
588 /// Update Threshold based on callsite properties such as callee
589 /// attributes and callee hotness for PGO builds. The Callee is explicitly
590 /// passed to support analyzing indirect calls whose target is inferred by
591 /// analysis.
592 void updateThreshold(CallBase &Call, Function &Callee);
593 /// Return a higher threshold if \p Call is a hot callsite.
594 std::optional<int> getHotCallSiteThreshold(CallBase &Call,
595 BlockFrequencyInfo *CallerBFI);
596
597 /// Handle a capped 'int' increment for Cost.
598 void addCost(int64_t Inc) {
599 Inc = std::clamp<int64_t>(Inc, INT_MIN, INT_MAX);
600 Cost = std::clamp<int64_t>(Inc + Cost, INT_MIN, INT_MAX);
601 }
602
603 void onDisableSROA(AllocaInst *Arg) override {
604 auto CostIt = SROAArgCosts.find(Arg);
605 if (CostIt == SROAArgCosts.end())
606 return;
607 addCost(CostIt->second);
608 SROACostSavings -= CostIt->second;
609 SROACostSavingsLost += CostIt->second;
610 SROAArgCosts.erase(CostIt);
611 }
612
613 void onDisableLoadElimination() override {
614 addCost(LoadEliminationCost);
615 LoadEliminationCost = 0;
616 }
617
618 bool onCallBaseVisitStart(CallBase &Call) override {
619 if (std::optional<int> AttrCallThresholdBonus =
620 getStringFnAttrAsInt(Call, "call-threshold-bonus"))
621 Threshold += *AttrCallThresholdBonus;
622
623 if (std::optional<int> AttrCallCost =
624 getStringFnAttrAsInt(Call, "call-inline-cost")) {
625 addCost(*AttrCallCost);
626 // Prevent further processing of the call since we want to override its
627 // inline cost, not just add to it.
628 return false;
629 }
630 return true;
631 }
632
633 void onCallPenalty() override { addCost(Opts.inline_call_penalty); }
634
635 void onMemAccess() override { addCost(Opts.inline_memaccess_cost); }
636
637 void onCallArgumentSetup(const CallBase &Call) override {
638 // Pay the price of the argument setup. We account for the average 1
639 // instruction per call argument setup here.
640 addCost(Call.arg_size() * InstrCost);
641 }
642 void onLoadRelativeIntrinsic() override {
643 // This is normally lowered to 4 LLVM instructions.
644 addCost(3 * InstrCost);
645 }
646 void onLoweredCall(Function *F, CallBase &Call,
647 bool IsIndirectCall) override {
648 // We account for the average 1 instruction per call argument setup here.
649 addCost(Call.arg_size() * InstrCost);
650
651 // If we have a constant that we are calling as a function, we can peer
652 // through it and see the function target. This happens not infrequently
653 // during devirtualization and so we want to give it a hefty bonus for
654 // inlining, but cap that bonus in the event that inlining wouldn't pan out.
655 // Pretend to inline the function, with a custom threshold.
656 if (IsIndirectCall && BoostIndirectCalls) {
657 auto IndirectCallParams = Params;
658 IndirectCallParams.DefaultThreshold =
660 /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
661 /// to instantiate the derived class.
662 InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
663 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE,
664 false);
665 if (CA.analyze().isSuccess()) {
666 // We were able to inline the indirect call! Subtract the cost from the
667 // threshold to get the bonus we want to apply, but don't go below zero.
668 addCost(-std::max(0, CA.getThreshold() - CA.getCost()));
669 }
670 } else
671 // Otherwise simply add the cost for merely making the call.
672 addCost(TTI.getInlineCallPenalty(CandidateCall.getCaller(), Call,
673 Opts.inline_call_penalty));
674 }
675
676 void onFinalizeSwitch(unsigned JumpTableSize, unsigned NumCaseCluster,
677 bool DefaultDestUnreachable) override {
678 // If suitable for a jump table, consider the cost for the table size and
679 // branch to destination.
680 // Maximum valid cost increased in this function.
681 if (JumpTableSize) {
682 // Suppose a default branch includes one compare and one conditional
683 // branch if it's reachable.
684 if (!DefaultDestUnreachable)
685 addCost(2 * InstrCost);
686 // Suppose a jump table requires one load and one jump instruction.
687 int64_t JTCost =
688 static_cast<int64_t>(JumpTableSize) * InstrCost + 2 * InstrCost;
689 addCost(JTCost);
690 return;
691 }
692
693 if (NumCaseCluster <= 3) {
694 // Suppose a comparison includes one compare and one conditional branch.
695 // We can reduce a set of instructions if the default branch is
696 // undefined.
697 addCost((NumCaseCluster - DefaultDestUnreachable) * 2 * InstrCost);
698 return;
699 }
700
701 int64_t ExpectedNumberOfCompare =
702 getExpectedNumberOfCompare(NumCaseCluster);
703 int64_t SwitchCost = ExpectedNumberOfCompare * 2 * InstrCost;
704
705 addCost(SwitchCost);
706 }
707
708 // Parses the inline assembly argument to account for its cost. Inline
709 // assembly instructions incur higher costs for inlining since they cannot be
710 // analyzed and optimized.
711 void onInlineAsm(const InlineAsm &Arg) override {
712 if (!Opts.inline_asm_instr_cost)
713 return;
715 Arg.collectAsmStrs(AsmStrs);
716 int SectionLevel = 0;
717 int InlineAsmInstrCount = 0;
718 for (StringRef AsmStr : AsmStrs) {
719 // Trim whitespaces and comments.
720 StringRef Trimmed = AsmStr.trim();
721 size_t hashPos = Trimmed.find('#');
722 if (hashPos != StringRef::npos)
723 Trimmed = Trimmed.substr(0, hashPos);
724 // Ignore comments.
725 if (Trimmed.empty())
726 continue;
727 // Filter out the outlined assembly instructions from the cost by keeping
728 // track of the section level and only accounting for instructions at
729 // section level of zero. Note there will be duplication in outlined
730 // sections too, but is not accounted in the inlining cost model.
731 if (Trimmed.starts_with(".pushsection")) {
732 ++SectionLevel;
733 continue;
734 }
735 if (Trimmed.starts_with(".popsection")) {
736 --SectionLevel;
737 continue;
738 }
739 // Ignore directives and labels.
740 if (Trimmed.starts_with(".") || Trimmed.contains(":"))
741 continue;
742 if (SectionLevel == 0)
743 ++InlineAsmInstrCount;
744 }
745 NumInlineAsmInstructions += InlineAsmInstrCount;
746 addCost(InlineAsmInstrCount * Opts.inline_asm_instr_cost);
747 }
748
749 void onMissedSimplification() override { addCost(InstrCost); }
750
751 void onInitializeSROAArg(AllocaInst *Arg) override {
752 assert(Arg != nullptr &&
753 "Should not initialize SROA costs for null value.");
754 auto SROAArgCost = TTI.getCallerAllocaCost(&CandidateCall, Arg);
755 SROACostSavings += SROAArgCost;
756 SROAArgCosts[Arg] = SROAArgCost;
757 }
758
759 void onAggregateSROAUse(AllocaInst *SROAArg) override {
760 auto CostIt = SROAArgCosts.find(SROAArg);
761 assert(CostIt != SROAArgCosts.end() &&
762 "expected this argument to have a cost");
763 CostIt->second += InstrCost;
764 SROACostSavings += InstrCost;
765 }
766
767 void onBlockStart(const BasicBlock *BB) override { CostAtBBStart = Cost; }
768
769 void onBlockAnalyzed(const BasicBlock *BB) override {
770 if (CostBenefitAnalysisEnabled) {
771 // Keep track of the static size of live but cold basic blocks. For now,
772 // we define a cold basic block to be one that's never executed.
773 assert(GetBFI && "GetBFI must be available");
774 BlockFrequencyInfo *BFI = &(GetBFI(F));
775 assert(BFI && "BFI must be available");
776 auto ProfileCount = BFI->getBlockProfileCount(BB);
777 if (*ProfileCount == 0)
778 ColdSize += Cost - CostAtBBStart;
779 }
780
781 auto *TI = BB->getTerminator();
782 // If we had any successors at this point, than post-inlining is likely to
783 // have them as well. Note that we assume any basic blocks which existed
784 // due to branches or switches which folded above will also fold after
785 // inlining.
786 if (SingleBB && TI->getNumSuccessors() > 1) {
787 // Take off the bonus we applied to the threshold.
788 Threshold -= SingleBBBonus;
789 SingleBB = false;
790 }
791 }
792
793 void onInstructionAnalysisStart(const Instruction *I) override {
794 // This function is called to store the initial cost of inlining before
795 // the given instruction was assessed.
796 if (!PrintInstructionComments)
797 return;
798 auto &CostDetail = InstructionCostDetailMap[I];
799 CostDetail.CostBefore = Cost;
800 CostDetail.ThresholdBefore = Threshold;
801 }
802
803 void onInstructionAnalysisFinish(const Instruction *I) override {
804 // This function is called to find new values of cost and threshold after
805 // the instruction has been assessed.
806 if (!PrintInstructionComments)
807 return;
808 auto &CostDetail = InstructionCostDetailMap[I];
809 CostDetail.CostAfter = Cost;
810 CostDetail.ThresholdAfter = Threshold;
811 }
812
813 bool isCostBenefitAnalysisEnabled() {
814 if (!PSI || !PSI->hasProfileSummary())
815 return false;
816
817 if (!GetBFI)
818 return false;
819
820 // Unless the user requests otherwise, require instrumentation profile.
821 if (!valueOr(Opts.inline_enable_cost_benefit_analysis,
822 PSI->hasInstrumentationProfile()))
823 return false;
824
825 auto *Caller = CandidateCall.getParent()->getParent();
826 if (!Caller->getEntryCount())
827 return false;
828
829 BlockFrequencyInfo *CallerBFI = &(GetBFI(*Caller));
830 if (!CallerBFI)
831 return false;
832
833 // For now, limit to hot call site.
834 if (!PSI->isHotCallSite(CandidateCall, CallerBFI))
835 return false;
836
837 // Make sure we have a nonzero entry count.
838 auto EntryCount = F.getEntryCount();
839 if (!EntryCount || *EntryCount == 0)
840 return false;
841
842 BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
843 if (!CalleeBFI)
844 return false;
845
846 return true;
847 }
848
849 // A helper function to choose between command line override and default.
850 unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const {
851 return Opts.inline_savings_multiplier.value_or(
853 }
854
855 // A helper function to choose between command line override and default.
856 unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const {
857 return Opts.inline_savings_profitable_multiplier.value_or(
859 }
860
861 void OverrideCycleSavingsAndSizeForTesting(APInt &CycleSavings, int &Size) {
862 if (std::optional<int> AttrCycleSavings = getStringFnAttrAsInt(
863 CandidateCall, "inline-cycle-savings-for-test")) {
864 CycleSavings = *AttrCycleSavings;
865 }
866
867 if (std::optional<int> AttrRuntimeCost = getStringFnAttrAsInt(
868 CandidateCall, "inline-runtime-cost-for-test")) {
869 Size = *AttrRuntimeCost;
870 }
871 }
872
873 // Determine whether we should inline the given call site, taking into account
874 // both the size cost and the cycle savings. Return std::nullopt if we don't
875 // have sufficient profiling information to determine.
876 std::optional<bool> costBenefitAnalysis() {
877 if (!CostBenefitAnalysisEnabled)
878 return std::nullopt;
879
880 // buildInlinerPipeline in the pass builder sets HotCallSiteThreshold to 0
881 // for the prelink phase of the AutoFDO + ThinLTO build. Honor the logic by
882 // falling back to the cost-based metric.
883 // TODO: Improve this hacky condition.
884 if (Threshold == 0)
885 return std::nullopt;
886
887 assert(GetBFI);
888 BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
889 assert(CalleeBFI);
890
891 // The cycle savings expressed as the sum of InstrCost
892 // multiplied by the estimated dynamic count of each instruction we can
893 // avoid. Savings come from the call site cost, such as argument setup and
894 // the call instruction, as well as the instructions that are folded.
895 //
896 // We use 128-bit APInt here to avoid potential overflow. This variable
897 // should stay well below 10^^24 (or 2^^80) in practice. This "worst" case
898 // assumes that we can avoid or fold a billion instructions, each with a
899 // profile count of 10^^15 -- roughly the number of cycles for a 24-hour
900 // period on a 4GHz machine.
901 APInt CycleSavings(128, 0);
902
903 for (auto &BB : F) {
904 APInt CurrentSavings(128, 0);
905 for (auto &I : BB) {
906 if (CondBrInst *BI = dyn_cast<CondBrInst>(&I)) {
907 // Count a conditional branch as savings if it becomes unconditional.
908 if (getSimplifiedValue<ConstantInt>(BI->getCondition()))
909 CurrentSavings += InstrCost;
910 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) {
911 if (getSimplifiedValue<ConstantInt>(SI->getCondition()))
912 CurrentSavings += InstrCost;
913 } else if (SimplifiedValues.count(&I)) {
914 // Count an instruction as savings if we can fold it.
915 CurrentSavings += InstrCost;
916 }
917 }
918
919 auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB);
920 CurrentSavings *= *ProfileCount;
921 CycleSavings += CurrentSavings;
922 }
923
924 // Compute the cycle savings per call.
925 auto EntryProfileCount = F.getEntryCount();
926 assert(EntryProfileCount && *EntryProfileCount);
927 CycleSavings += *EntryProfileCount / 2;
928 CycleSavings = CycleSavings.udiv(*EntryProfileCount);
929
930 // Compute the total savings for the call site.
931 auto *CallerBB = CandidateCall.getParent();
932 BlockFrequencyInfo *CallerBFI = &(GetBFI(*(CallerBB->getParent())));
933 CycleSavings += getCallsiteCost(TTI, this->CandidateCall, DL);
934 CycleSavings *= *CallerBFI->getBlockProfileCount(CallerBB);
935
936 // Remove the cost of the cold basic blocks to model the runtime cost more
937 // accurately. Both machine block placement and function splitting could
938 // place cold blocks further from hot blocks.
939 int Size = Cost - ColdSize;
940
941 // Allow tiny callees to be inlined regardless of whether they meet the
942 // savings threshold.
943 Size = Size > Opts.inline_size_allowance ? Size - Opts.inline_size_allowance
944 : 1;
945
946 OverrideCycleSavingsAndSizeForTesting(CycleSavings, Size);
947 CostBenefit.emplace(APInt(128, Size), CycleSavings);
948
949 // Let R be the ratio of CycleSavings to Size. We accept the inlining
950 // opportunity if R is really high and reject if R is really low. If R is
951 // somewhere in the middle, we fall back to the cost-based analysis.
952 //
953 // Specifically, let R = CycleSavings / Size, we accept the inlining
954 // opportunity if:
955 //
956 // PSI->getOrCompHotCountThreshold()
957 // R > -------------------------------------------------
958 // getInliningCostBenefitAnalysisSavingsMultiplier()
959 //
960 // and reject the inlining opportunity if:
961 //
962 // PSI->getOrCompHotCountThreshold()
963 // R <= ----------------------------------------------------
964 // getInliningCostBenefitAnalysisProfitableMultiplier()
965 //
966 // Otherwise, we fall back to the cost-based analysis.
967 //
968 // Implementation-wise, use multiplication (CycleSavings * Multiplier,
969 // HotCountThreshold * Size) rather than division to avoid precision loss.
970 APInt Threshold(128, PSI->getOrCompHotCountThreshold());
971 Threshold *= Size;
972
973 APInt UpperBoundCycleSavings = CycleSavings;
974 UpperBoundCycleSavings *= getInliningCostBenefitAnalysisSavingsMultiplier();
975 if (UpperBoundCycleSavings.uge(Threshold))
976 return true;
977
978 APInt LowerBoundCycleSavings = CycleSavings;
979 LowerBoundCycleSavings *=
980 getInliningCostBenefitAnalysisProfitableMultiplier();
981 if (LowerBoundCycleSavings.ult(Threshold))
982 return false;
983
984 // Otherwise, fall back to the cost-based analysis.
985 return std::nullopt;
986 }
987
988 InlineResult finalizeAnalysis() override {
989 // Loops generally act a lot like calls in that they act like barriers to
990 // movement, require a certain amount of setup, etc. So when optimising for
991 // size, we penalise any call sites that perform loops. We do this after all
992 // other costs here, so will likely only be dealing with relatively small
993 // functions (and hence LI will hopefully be cheap).
994 auto *Caller = CandidateCall.getFunction();
995 if (Caller->hasMinSize()) {
996 LoopInfo LI;
997 LI.analyze(&F);
998 int NumLoops = 0;
999 for (Loop *L : LI) {
1000 // Ignore loops that will not be executed
1001 if (DeadBlocks.count(L->getHeader()))
1002 continue;
1003 NumLoops++;
1004 }
1005 addCost(NumLoops * InlineConstants::LoopPenalty);
1006 }
1007
1008 // We applied the maximum possible vector bonus at the beginning. Now,
1009 // subtract the excess bonus, if any, from the Threshold before
1010 // comparing against Cost.
1011 if (NumVectorInstructions <= NumInstructions / 10)
1012 Threshold -= VectorBonus;
1013 else if (NumVectorInstructions <= NumInstructions / 2)
1014 Threshold -= VectorBonus / 2;
1015
1016 if (std::optional<int> AttrCost =
1017 getStringFnAttrAsInt(CandidateCall, "function-inline-cost"))
1018 Cost = *AttrCost;
1019
1020 if (std::optional<int> AttrCostMult = getStringFnAttrAsInt(
1021 CandidateCall,
1023 Cost *= *AttrCostMult;
1024
1025 if (std::optional<int> AttrThreshold =
1026 getStringFnAttrAsInt(CandidateCall, "function-inline-threshold"))
1027 Threshold = *AttrThreshold;
1028
1029 if (auto Result = costBenefitAnalysis()) {
1030 DecidedByCostBenefit = true;
1031 if (*Result)
1032 return InlineResult::success();
1033 else
1034 return InlineResult::failure("Cost over threshold.");
1035 }
1036
1037 if (IgnoreThreshold)
1038 return InlineResult::success();
1039
1040 DecidedByCostThreshold = true;
1041 return Cost < std::max(1, Threshold)
1043 : InlineResult::failure("Cost over threshold.");
1044 }
1045
1046 bool shouldStop() override {
1047 if (IgnoreThreshold || ComputeFullInlineCost)
1048 return false;
1049 // Bail out the moment we cross the threshold. This means we'll under-count
1050 // the cost, but only when undercounting doesn't matter.
1051 if (Cost < Threshold)
1052 return false;
1053 DecidedByCostThreshold = true;
1054 return true;
1055 }
1056
1057 void onLoadEliminationOpportunity() override {
1058 LoadEliminationCost += InstrCost;
1059 }
1060
1061 InlineResult onAnalysisStart() override {
1062 // Perform some tweaks to the cost and threshold based on the direct
1063 // callsite information.
1064
1065 // We want to more aggressively inline vector-dense kernels, so up the
1066 // threshold, and we'll lower it if the % of vector instructions gets too
1067 // low. Note that these bonuses are some what arbitrary and evolved over
1068 // time by accident as much as because they are principled bonuses.
1069 //
1070 // FIXME: It would be nice to remove all such bonuses. At least it would be
1071 // nice to base the bonus values on something more scientific.
1072 assert(NumInstructions == 0);
1073 assert(NumVectorInstructions == 0);
1074
1075 // Update the threshold based on callsite properties
1076 updateThreshold(CandidateCall, F);
1077
1078 // While Threshold depends on commandline options that can take negative
1079 // values, we want to enforce the invariant that the computed threshold and
1080 // bonuses are non-negative.
1081 assert(Threshold >= 0);
1082 assert(SingleBBBonus >= 0);
1083 assert(VectorBonus >= 0);
1084
1085 // Speculatively apply all possible bonuses to Threshold. If cost exceeds
1086 // this Threshold any time, and cost cannot decrease, we can stop processing
1087 // the rest of the function body.
1088 Threshold += (SingleBBBonus + VectorBonus);
1089
1090 // Give out bonuses for the callsite, as the instructions setting them up
1091 // will be gone after inlining.
1092 addCost(-getCallsiteCost(TTI, this->CandidateCall, DL));
1093
1094 // If this function uses the coldcc calling convention, prefer not to inline
1095 // it.
1096 if (F.getCallingConv() == CallingConv::Cold)
1098
1099 LLVM_DEBUG(dbgs() << " Initial cost: " << Cost << "\n");
1100
1101 // Check if we're done. This can happen due to bonuses and penalties.
1102 if (Cost >= Threshold && !ComputeFullInlineCost)
1103 return InlineResult::failure("high cost");
1104
1105 return InlineResult::success();
1106 }
1107
1108public:
1109 InlineCostCallAnalyzer(
1110 Function &Callee, CallBase &Call, const InlineParams &Params,
1111 const TargetTransformInfo &TTI,
1112 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
1113 function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
1114 function_ref<const TargetLibraryInfo &(Function &)> GetTLI = nullptr,
1115 ProfileSummaryInfo *PSI = nullptr,
1116 OptimizationRemarkEmitter *ORE = nullptr, bool BoostIndirect = true,
1117 bool IgnoreThreshold = false,
1118 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache =
1119 nullptr,
1120 bool PrintInstructionComments = false)
1121 : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, GetTLI, PSI,
1122 ORE, GetEphValuesCache),
1123 ComputeFullInlineCost(Opts.inline_cost_full ||
1124 Params.ComputeFullInlineCost || ORE ||
1125 isCostBenefitAnalysisEnabled()),
1126 Params(Params), Threshold(Params.DefaultThreshold),
1127 BoostIndirectCalls(BoostIndirect), IgnoreThreshold(IgnoreThreshold),
1128 CostBenefitAnalysisEnabled(isCostBenefitAnalysisEnabled()),
1129 PrintInstructionComments(Opts.print_instruction_comments ||
1130 PrintInstructionComments),
1131 Writer(this) {
1132 AllowRecursiveCall = *Params.AllowRecursiveCall;
1133 }
1134
1135 /// Annotation Writer for instruction details
1136 InlineCostAnnotationWriter Writer;
1137
1138 void dump();
1139
1140 // Prints the same analysis as dump(), but its definition is not dependent
1141 // on the build.
1142 void print(raw_ostream &OS);
1143
1144 std::optional<InstructionCostDetail> getCostDetails(const Instruction *I) {
1145 auto It = InstructionCostDetailMap.find(I);
1146 if (It != InstructionCostDetailMap.end())
1147 return It->second;
1148 return std::nullopt;
1149 }
1150
1151 ~InlineCostCallAnalyzer() override = default;
1152 int getThreshold() const { return Threshold; }
1153 int getCost() const { return Cost; }
1154 int getStaticBonusApplied() const { return StaticBonusApplied; }
1155 std::optional<CostBenefitPair> getCostBenefitPair() { return CostBenefit; }
1156 bool wasDecidedByCostBenefit() const { return DecidedByCostBenefit; }
1157 bool wasDecidedByCostThreshold() const { return DecidedByCostThreshold; }
1158};
1159
1160// Return true if CB is the sole call to local function Callee.
1161static bool isSoleCallToLocalFunction(const CallBase &CB,
1162 const Function &Callee) {
1163 return Callee.hasLocalLinkage() && Callee.hasOneLiveUse() &&
1164 &Callee == CB.getCalledFunction();
1165}
1166
1167class InlineCostFeaturesAnalyzer final : public CallAnalyzer {
1168private:
1169 InlineCostFeatures Cost = {};
1170
1171 // FIXME: These constants are taken from the heuristic-based cost visitor.
1172 // These should be removed entirely in a later revision to avoid reliance on
1173 // heuristics in the ML inliner.
1174 static constexpr int JTCostMultiplier = 2;
1175 static constexpr int CaseClusterCostMultiplier = 2;
1176 static constexpr int SwitchDefaultDestCostMultiplier = 2;
1177 static constexpr int SwitchCostMultiplier = 2;
1178
1179 // FIXME: These are taken from the heuristic-based cost visitor: we should
1180 // eventually abstract these to the CallAnalyzer to avoid duplication.
1181 unsigned SROACostSavingOpportunities = 0;
1182 int VectorBonus = 0;
1183 int SingleBBBonus = 0;
1184 int Threshold = 5;
1185
1186 DenseMap<AllocaInst *, unsigned> SROACosts;
1187
1188 void increment(InlineCostFeatureIndex Feature, int64_t Delta = 1) {
1189 Cost[static_cast<size_t>(Feature)] += Delta;
1190 }
1191
1192 void set(InlineCostFeatureIndex Feature, int64_t Value) {
1193 Cost[static_cast<size_t>(Feature)] = Value;
1194 }
1195
1196 void onDisableSROA(AllocaInst *Arg) override {
1197 auto CostIt = SROACosts.find(Arg);
1198 if (CostIt == SROACosts.end())
1199 return;
1200
1201 increment(InlineCostFeatureIndex::sroa_losses, CostIt->second);
1202 SROACostSavingOpportunities -= CostIt->second;
1203 SROACosts.erase(CostIt);
1204 }
1205
1206 void onDisableLoadElimination() override {
1207 set(InlineCostFeatureIndex::load_elimination, 1);
1208 }
1209
1210 void onCallPenalty() override {
1211 increment(InlineCostFeatureIndex::call_penalty, Opts.inline_call_penalty);
1212 }
1213
1214 void onCallArgumentSetup(const CallBase &Call) override {
1215 increment(InlineCostFeatureIndex::call_argument_setup,
1216 Call.arg_size() * InstrCost);
1217 }
1218
1219 void onLoadRelativeIntrinsic() override {
1220 increment(InlineCostFeatureIndex::load_relative_intrinsic, 3 * InstrCost);
1221 }
1222
1223 void onLoweredCall(Function *F, CallBase &Call,
1224 bool IsIndirectCall) override {
1225 increment(InlineCostFeatureIndex::lowered_call_arg_setup,
1226 Call.arg_size() * InstrCost);
1227
1228 if (IsIndirectCall) {
1229 InlineParams IndirectCallParams = {/* DefaultThreshold*/ 0,
1230 /*HintThreshold*/ {},
1231 /*OptSizeHintThreshold*/ {},
1232 /*ColdThreshold*/ {},
1233 /*OptSizeThreshold*/ {},
1234 /*OptMinSizeThreshold*/ {},
1235 /*HotCallSiteThreshold*/ {},
1236 /*LocallyHotCallSiteThreshold*/ {},
1237 /*ColdCallSiteThreshold*/ {},
1238 /*ComputeFullInlineCost*/ true,
1239 /*EnableDeferral*/ true};
1240 IndirectCallParams.DefaultThreshold =
1242
1243 InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
1244 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE,
1245 false, true);
1246 if (CA.analyze().isSuccess()) {
1247 increment(InlineCostFeatureIndex::nested_inline_cost_estimate,
1248 CA.getCost());
1249 increment(InlineCostFeatureIndex::nested_inlines, 1);
1250 }
1251 } else {
1252 onCallPenalty();
1253 }
1254 }
1255
1256 void onFinalizeSwitch(unsigned JumpTableSize, unsigned NumCaseCluster,
1257 bool DefaultDestUnreachable) override {
1258 if (JumpTableSize) {
1259 if (!DefaultDestUnreachable)
1260 increment(InlineCostFeatureIndex::switch_default_dest_penalty,
1261 SwitchDefaultDestCostMultiplier * InstrCost);
1262 int64_t JTCost = static_cast<int64_t>(JumpTableSize) * InstrCost +
1263 JTCostMultiplier * InstrCost;
1264 increment(InlineCostFeatureIndex::jump_table_penalty, JTCost);
1265 return;
1266 }
1267
1268 if (NumCaseCluster <= 3) {
1269 increment(InlineCostFeatureIndex::case_cluster_penalty,
1270 (NumCaseCluster - DefaultDestUnreachable) *
1271 CaseClusterCostMultiplier * InstrCost);
1272 return;
1273 }
1274
1275 int64_t ExpectedNumberOfCompare =
1276 getExpectedNumberOfCompare(NumCaseCluster);
1277
1278 int64_t SwitchCost =
1279 ExpectedNumberOfCompare * SwitchCostMultiplier * InstrCost;
1280 increment(InlineCostFeatureIndex::switch_penalty, SwitchCost);
1281 }
1282
1283 void onMissedSimplification() override {
1284 increment(InlineCostFeatureIndex::unsimplified_common_instructions,
1285 InstrCost);
1286 }
1287
1288 void onInitializeSROAArg(AllocaInst *Arg) override {
1289 auto SROAArgCost = TTI.getCallerAllocaCost(&CandidateCall, Arg);
1290 SROACosts[Arg] = SROAArgCost;
1291 SROACostSavingOpportunities += SROAArgCost;
1292 }
1293
1294 void onAggregateSROAUse(AllocaInst *Arg) override {
1295 SROACosts.find(Arg)->second += InstrCost;
1296 SROACostSavingOpportunities += InstrCost;
1297 }
1298
1299 void onBlockAnalyzed(const BasicBlock *BB) override {
1300 if (BB->getTerminator()->getNumSuccessors() > 1)
1301 set(InlineCostFeatureIndex::is_multiple_blocks, 1);
1302 Threshold -= SingleBBBonus;
1303 }
1304
1305 InlineResult finalizeAnalysis() override {
1306 auto *Caller = CandidateCall.getFunction();
1307 if (Caller->hasMinSize()) {
1308 LoopInfo LI;
1309 LI.analyze(&F);
1310 for (Loop *L : LI) {
1311 // Ignore loops that will not be executed
1312 if (DeadBlocks.count(L->getHeader()))
1313 continue;
1314 increment(InlineCostFeatureIndex::num_loops,
1316 }
1317 }
1318 set(InlineCostFeatureIndex::dead_blocks, DeadBlocks.size());
1319 set(InlineCostFeatureIndex::simplified_instructions,
1320 NumInstructionsSimplified);
1321 set(InlineCostFeatureIndex::constant_args, NumConstantArgs);
1322 set(InlineCostFeatureIndex::constant_offset_ptr_args,
1323 NumConstantOffsetPtrArgs);
1324 set(InlineCostFeatureIndex::sroa_savings, SROACostSavingOpportunities);
1325
1326 if (NumVectorInstructions <= NumInstructions / 10)
1327 Threshold -= VectorBonus;
1328 else if (NumVectorInstructions <= NumInstructions / 2)
1329 Threshold -= VectorBonus / 2;
1330
1331 set(InlineCostFeatureIndex::threshold, Threshold);
1332
1333 return InlineResult::success();
1334 }
1335
1336 bool shouldStop() override { return false; }
1337
1338 void onLoadEliminationOpportunity() override {
1339 increment(InlineCostFeatureIndex::load_elimination, 1);
1340 }
1341
1342 InlineResult onAnalysisStart() override {
1343 increment(InlineCostFeatureIndex::callsite_cost,
1344 -1 * getCallsiteCost(TTI, this->CandidateCall, DL));
1345
1346 set(InlineCostFeatureIndex::cold_cc_penalty,
1347 (F.getCallingConv() == CallingConv::Cold));
1348
1349 set(InlineCostFeatureIndex::last_call_to_static_bonus,
1350 isSoleCallToLocalFunction(CandidateCall, F));
1351
1352 // FIXME: we shouldn't repeat this logic in both the Features and Cost
1353 // analyzer - instead, we should abstract it to a common method in the
1354 // CallAnalyzer
1355 int SingleBBBonusPercent = 50;
1356 int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
1357 Threshold += TTI.adjustInliningThreshold(&CandidateCall);
1358 Threshold *= TTI.getInliningThresholdMultiplier();
1359 SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
1360 VectorBonus = Threshold * VectorBonusPercent / 100;
1361 Threshold += (SingleBBBonus + VectorBonus);
1362
1363 return InlineResult::success();
1364 }
1365
1366public:
1367 InlineCostFeaturesAnalyzer(
1368 const TargetTransformInfo &TTI,
1369 function_ref<AssumptionCache &(Function &)> &GetAssumptionCache,
1370 function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
1371 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
1372 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee,
1373 CallBase &Call)
1374 : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, GetTLI,
1375 PSI) {}
1376
1377 const InlineCostFeatures &features() const { return Cost; }
1378};
1379
1380} // namespace
1381
1382/// Test whether the given value is an Alloca-derived function argument.
1383bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
1384 return SROAArgValues.count(V);
1385}
1386
1387void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
1388 onDisableSROA(SROAArg);
1389 EnabledSROAAllocas.erase(SROAArg);
1390 disableLoadElimination();
1391}
1392
1393void InlineCostAnnotationWriter::emitInstructionAnnot(
1394 const Instruction *I, formatted_raw_ostream &OS) {
1395 // The cost of inlining of the given instruction is printed always.
1396 // The threshold delta is printed only when it is non-zero. It happens
1397 // when we decided to give a bonus at a particular instruction.
1398 std::optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
1399 if (!Record)
1400 OS << "; No analysis for the instruction";
1401 else {
1402 OS << "; cost before = " << Record->CostBefore
1403 << ", cost after = " << Record->CostAfter
1404 << ", threshold before = " << Record->ThresholdBefore
1405 << ", threshold after = " << Record->ThresholdAfter << ", ";
1406 OS << "cost delta = " << Record->getCostDelta();
1407 if (Record->hasThresholdChanged())
1408 OS << ", threshold delta = " << Record->getThresholdDelta();
1409 }
1410 auto *V = ICCA->getSimplifiedValueUnchecked(const_cast<Instruction *>(I));
1411 if (V) {
1412 OS << ", simplified to ";
1413 V->print(OS, true);
1414 if (auto *VI = dyn_cast<Instruction>(V)) {
1415 if (VI->getFunction() != I->getFunction())
1416 OS << " (caller instruction)";
1417 } else if (auto *VArg = dyn_cast<Argument>(V)) {
1418 if (VArg->getParent() != I->getFunction())
1419 OS << " (caller argument)";
1420 }
1421 }
1422 OS << "\n";
1423}
1424
1425/// If 'V' maps to a SROA candidate, disable SROA for it.
1426void CallAnalyzer::disableSROA(Value *V) {
1427 if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
1428 disableSROAForArg(SROAArg);
1429 }
1430}
1431
1432void CallAnalyzer::disableLoadElimination() {
1433 if (EnableLoadElimination) {
1434 onDisableLoadElimination();
1435 EnableLoadElimination = false;
1436 }
1437}
1438
1439/// Accumulate a constant GEP offset into an APInt if possible.
1440///
1441/// Returns false if unable to compute the offset for any reason. Respects any
1442/// simplified values known during the analysis of this callsite.
1443bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
1444 unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
1445 assert(IntPtrWidth == Offset.getBitWidth());
1446
1448 GTI != GTE; ++GTI) {
1449 ConstantInt *OpC =
1450 getDirectOrSimplifiedValue<ConstantInt>(GTI.getOperand());
1451 if (!OpC)
1452 return false;
1453 if (OpC->isZero())
1454 continue;
1455
1456 // Handle a struct index, which adds its field offset to the pointer.
1457 if (StructType *STy = GTI.getStructTypeOrNull()) {
1458 unsigned ElementIdx = OpC->getZExtValue();
1459 const StructLayout *SL = DL.getStructLayout(STy);
1460 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
1461 continue;
1462 }
1463
1464 APInt TypeSize(IntPtrWidth, GTI.getSequentialElementStride(DL));
1465 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
1466 }
1467 return true;
1468}
1469
1470/// Use TTI to check whether a GEP is free.
1471///
1472/// Respects any simplified values known during the analysis of this callsite.
1473bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
1474 SmallVector<Value *, 4> Operands;
1475 Operands.push_back(GEP.getOperand(0));
1476 for (const Use &Op : GEP.indices())
1477 if (Constant *SimpleOp = getSimplifiedValue<Constant>(Op))
1478 Operands.push_back(SimpleOp);
1479 else
1480 Operands.push_back(Op);
1484}
1485
1486bool CallAnalyzer::visitAlloca(AllocaInst &I) {
1487 disableSROA(I.getOperand(0));
1488
1489 // Check whether inlining will turn a dynamic alloca into a static
1490 // alloca and handle that case.
1491 if (I.isArrayAllocation()) {
1492 Constant *Size = getSimplifiedValue<Constant>(I.getArraySize());
1493 if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
1494 // Sometimes a dynamic alloca could be converted into a static alloca
1495 // after this constant prop, and become a huge static alloca on an
1496 // unconditional CFG path. Avoid inlining if this is going to happen above
1497 // a threshold.
1498 // FIXME: If the threshold is removed or lowered too much, we could end up
1499 // being too pessimistic and prevent inlining non-problematic code. This
1500 // could result in unintended perf regressions. A better overall strategy
1501 // is needed to track stack usage during inlining.
1502 AllocatedSize = SaturatingMultiplyAdd(
1503 AllocSize->getLimitedValue(),
1504 I.getAllocationBaseSize(DL).getKnownMinValue(), AllocatedSize);
1506 HasDynamicAlloca = true;
1507 return false;
1508 }
1509 }
1510
1511 if (I.isStaticAlloca()) {
1512 // Accumulate the allocated size if constant and executed once.
1513 // Note: if AllocSize is a vscale value, this is an underestimate of the
1514 // allocated size, and it also requires some of the cost of a dynamic
1515 // alloca, but is recorded here as a constant size alloca.
1516 TypeSize AllocSize = I.getAllocationSize(DL).value_or(TypeSize::getZero());
1517 AllocatedSize = SaturatingAdd(AllocSize.getKnownMinValue(), AllocatedSize);
1518 } else {
1519 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
1520 // a variety of reasons, and so we would like to not inline them into
1521 // functions which don't currently have a dynamic alloca. This simply
1522 // disables inlining altogether in the presence of a dynamic alloca.
1523 HasDynamicAlloca = true;
1524 }
1525
1526 return false;
1527}
1528
1529bool CallAnalyzer::visitPHI(PHINode &I) {
1530 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
1531 // though we don't want to propagate it's bonuses. The idea is to disable
1532 // SROA if it *might* be used in an inappropriate manner.
1533
1534 // Phi nodes are always zero-cost.
1535 // FIXME: Pointer sizes may differ between different address spaces, so do we
1536 // need to use correct address space in the call to getPointerSizeInBits here?
1537 // Or could we skip the getPointerSizeInBits call completely? As far as I can
1538 // see the ZeroOffset is used as a dummy value, so we can probably use any
1539 // bit width for the ZeroOffset?
1540 APInt ZeroOffset = APInt::getZero(DL.getPointerSizeInBits(0));
1541 bool CheckSROA = I.getType()->isPointerTy();
1542
1543 // Track the constant or pointer with constant offset we've seen so far.
1544 Constant *FirstC = nullptr;
1545 std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
1546 Value *FirstV = nullptr;
1547
1548 for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
1549 BasicBlock *Pred = I.getIncomingBlock(i);
1550 // If the incoming block is dead, skip the incoming block.
1551 if (DeadBlocks.count(Pred))
1552 continue;
1553 // If the parent block of phi is not the known successor of the incoming
1554 // block, skip the incoming block.
1555 BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
1556 if (KnownSuccessor && KnownSuccessor != I.getParent())
1557 continue;
1558
1559 Value *V = I.getIncomingValue(i);
1560 // If the incoming value is this phi itself, skip the incoming value.
1561 if (&I == V)
1562 continue;
1563
1564 Constant *C = getDirectOrSimplifiedValue<Constant>(V);
1565
1566 std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
1567 if (!C && CheckSROA)
1568 BaseAndOffset = ConstantOffsetPtrs.lookup(V);
1569
1570 if (!C && !BaseAndOffset.first)
1571 // The incoming value is neither a constant nor a pointer with constant
1572 // offset, exit early.
1573 return true;
1574
1575 if (FirstC) {
1576 if (FirstC == C)
1577 // If we've seen a constant incoming value before and it is the same
1578 // constant we see this time, continue checking the next incoming value.
1579 continue;
1580 // Otherwise early exit because we either see a different constant or saw
1581 // a constant before but we have a pointer with constant offset this time.
1582 return true;
1583 }
1584
1585 if (FirstV) {
1586 // The same logic as above, but check pointer with constant offset here.
1587 if (FirstBaseAndOffset == BaseAndOffset)
1588 continue;
1589 return true;
1590 }
1591
1592 if (C) {
1593 // This is the 1st time we've seen a constant, record it.
1594 FirstC = C;
1595 continue;
1596 }
1597
1598 // The remaining case is that this is the 1st time we've seen a pointer with
1599 // constant offset, record it.
1600 FirstV = V;
1601 FirstBaseAndOffset = BaseAndOffset;
1602 }
1603
1604 // Check if we can map phi to a constant.
1605 if (FirstC) {
1606 SimplifiedValues[&I] = FirstC;
1607 return true;
1608 }
1609
1610 // Check if we can map phi to a pointer with constant offset.
1611 if (FirstBaseAndOffset.first) {
1612 ConstantOffsetPtrs[&I] = std::move(FirstBaseAndOffset);
1613
1614 if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
1615 SROAArgValues[&I] = SROAArg;
1616 }
1617
1618 return true;
1619}
1620
1621/// Check we can fold GEPs of constant-offset call site argument pointers.
1622/// This requires target data and inbounds GEPs.
1623///
1624/// \return true if the specified GEP can be folded.
1625bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
1626 // Check if we have a base + offset for the pointer.
1627 std::pair<Value *, APInt> BaseAndOffset =
1628 ConstantOffsetPtrs.lookup(I.getPointerOperand());
1629 if (!BaseAndOffset.first)
1630 return false;
1631
1632 // Check if the offset of this GEP is constant, and if so accumulate it
1633 // into Offset.
1634 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1635 return false;
1636
1637 // Add the result as a new mapping to Base + Offset.
1638 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1639
1640 return true;
1641}
1642
1643bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
1644 auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
1645
1646 // Lambda to check whether a GEP's indices are all constant.
1647 auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
1648 for (const Use &Op : GEP.indices())
1649 if (!getDirectOrSimplifiedValue<Constant>(Op))
1650 return false;
1651 return true;
1652 };
1653
1654 if (Opts.gep_const_evaluation)
1656 return true;
1657
1658 if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
1659 if (SROAArg)
1660 SROAArgValues[&I] = SROAArg;
1661
1662 // Constant GEPs are modeled as free.
1663 return true;
1664 }
1665
1666 // Variable GEPs will require math and will disable SROA.
1667 if (SROAArg)
1668 disableSROAForArg(SROAArg);
1669 return isGEPFree(I);
1670}
1671
1672// Simplify \p Cmp if RHS is const and we can ValueTrack LHS.
1673// This handles the case only when the Cmp instruction is guarding a recursive
1674// call that will cause the Cmp to fail/succeed for the recursive call.
1675bool CallAnalyzer::simplifyCmpInstForRecCall(CmpInst &Cmp) {
1676 // Bail out if LHS is not a function argument or RHS is NOT const:
1677 if (!isa<Argument>(Cmp.getOperand(0)) || !isa<Constant>(Cmp.getOperand(1)))
1678 return false;
1679 auto *CmpOp = Cmp.getOperand(0);
1680 // Make sure that the callsite is recursive:
1681 if (CandidateCall.getCaller() != &F)
1682 return false;
1683 // Only handle the case when the callsite has a single predecessor:
1684 auto *CallBB = CandidateCall.getParent();
1685 auto *Predecessor = CallBB->getSinglePredecessor();
1686 if (!Predecessor)
1687 return false;
1688 // Check if the callsite is guarded by the same Cmp instruction:
1689 auto *Br = dyn_cast<CondBrInst>(Predecessor->getTerminator());
1690 if (!Br || Br->getCondition() != &Cmp)
1691 return false;
1692
1693 // Check if there is any arg of the recursive callsite is affecting the cmp
1694 // instr:
1695 bool ArgFound = false;
1696 Value *FuncArg = nullptr, *CallArg = nullptr;
1697 for (unsigned ArgNum = 0;
1698 ArgNum < F.arg_size() && ArgNum < CandidateCall.arg_size(); ArgNum++) {
1699 FuncArg = F.getArg(ArgNum);
1700 CallArg = CandidateCall.getArgOperand(ArgNum);
1701 if (FuncArg == CmpOp && CallArg != CmpOp) {
1702 ArgFound = true;
1703 break;
1704 }
1705 }
1706 if (!ArgFound)
1707 return false;
1708
1709 // Now we have a recursive call that is guarded by a cmp instruction.
1710 // Check if this cmp can be simplified:
1711 SimplifyQuery SQ(DL, dyn_cast<Instruction>(CallArg));
1712 CondContext CC(&Cmp);
1713 CC.Invert = (CallBB != Br->getSuccessor(0));
1714 SQ.CC = &CC;
1715 CC.AffectedValues.insert(FuncArg);
1716 Value *SimplifiedInstruction = llvm::simplifyInstructionWithOperands(
1717 cast<CmpInst>(&Cmp), {CallArg, Cmp.getOperand(1)}, SQ);
1718 if (auto *ConstVal = dyn_cast_or_null<ConstantInt>(SimplifiedInstruction)) {
1719 // Make sure that the BB of the recursive call is NOT the true successor
1720 // of the icmp. In other words, make sure that the recursion depth is 1.
1721 if ((ConstVal->isOne() && CC.Invert) ||
1722 (ConstVal->isZero() && !CC.Invert)) {
1723 SimplifiedValues[&Cmp] = ConstVal;
1724 return true;
1725 }
1726 }
1727 return false;
1728}
1729
1730/// Simplify \p I if its operands are constants and update SimplifiedValues.
1731bool CallAnalyzer::simplifyInstruction(Instruction &I) {
1733 for (Value *Op : I.operands()) {
1734 Constant *COp = getDirectOrSimplifiedValue<Constant>(Op);
1735 if (!COp)
1736 return false;
1737 COps.push_back(COp);
1738 }
1739 auto *C = ConstantFoldInstOperands(&I, COps, DL);
1740 if (!C)
1741 return false;
1742 SimplifiedValues[&I] = C;
1743 return true;
1744}
1745
1746/// Try to simplify a call to llvm.is.constant.
1747///
1748/// Duplicate the argument checking from CallAnalyzer::simplifyCallSite since
1749/// we expect calls of this specific intrinsic to be infrequent.
1750///
1751/// FIXME: Given that we know CB's parent (F) caller
1752/// (CandidateCall->getParent()->getParent()), we might be able to determine
1753/// whether inlining F into F's caller would change how the call to
1754/// llvm.is.constant would evaluate.
1755bool CallAnalyzer::simplifyIntrinsicCallIsConstant(CallBase &CB) {
1756 Value *Arg = CB.getArgOperand(0);
1757 auto *C = getDirectOrSimplifiedValue<Constant>(Arg);
1758
1759 Type *RT = CB.getFunctionType()->getReturnType();
1760 SimplifiedValues[&CB] = ConstantInt::get(RT, C ? 1 : 0);
1761 return true;
1762}
1763
1764bool CallAnalyzer::simplifyIntrinsicCallObjectSize(CallBase &CB) {
1765 // As per the langref, "The fourth argument to llvm.objectsize determines if
1766 // the value should be evaluated at runtime."
1767 if (cast<ConstantInt>(CB.getArgOperand(3))->isOne())
1768 return false;
1769
1771 /*MustSucceed=*/true);
1773 if (C)
1774 SimplifiedValues[&CB] = C;
1775 return C;
1776}
1777
1778bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1779 // Propagate constants through bitcasts.
1781 return true;
1782
1783 // Track base/offsets through casts
1784 std::pair<Value *, APInt> BaseAndOffset =
1785 ConstantOffsetPtrs.lookup(I.getOperand(0));
1786 // Casts don't change the offset, just wrap it up.
1787 if (BaseAndOffset.first)
1788 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1789
1790 // Also look for SROA candidates here.
1791 if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
1792 SROAArgValues[&I] = SROAArg;
1793
1794 // Bitcasts are always zero cost.
1795 return true;
1796}
1797
1798bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
1799 // Propagate constants through ptrtoint.
1801 return true;
1802
1803 // Track base/offset pairs when converted to a plain integer provided the
1804 // integer is large enough to represent the pointer.
1805 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
1806 unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1807 if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1808 std::pair<Value *, APInt> BaseAndOffset =
1809 ConstantOffsetPtrs.lookup(I.getOperand(0));
1810 if (BaseAndOffset.first)
1811 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1812 }
1813
1814 // This is really weird. Technically, ptrtoint will disable SROA. However,
1815 // unless that ptrtoint is *used* somewhere in the live basic blocks after
1816 // inlining, it will be nuked, and SROA should proceed. All of the uses which
1817 // would block SROA would also block SROA if applied directly to a pointer,
1818 // and so we can just add the integer in here. The only places where SROA is
1819 // preserved either cannot fire on an integer, or won't in-and-of themselves
1820 // disable SROA (ext) w/o some later use that we would see and disable.
1821 if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
1822 SROAArgValues[&I] = SROAArg;
1823
1826}
1827
1828bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
1829 // Propagate constants through ptrtoint.
1831 return true;
1832
1833 // Track base/offset pairs when round-tripped through a pointer without
1834 // modifications provided the integer is not too large.
1835 Value *Op = I.getOperand(0);
1836 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
1837 if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
1838 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
1839 if (BaseAndOffset.first)
1840 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1841 }
1842
1843 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
1844 if (auto *SROAArg = getSROAArgForValueOrNull(Op))
1845 SROAArgValues[&I] = SROAArg;
1846
1849}
1850
1851bool CallAnalyzer::visitCastInst(CastInst &I) {
1852 // Propagate constants through casts.
1854 return true;
1855
1856 // Disable SROA in the face of arbitrary casts we don't explicitly list
1857 // elsewhere.
1858 disableSROA(I.getOperand(0));
1859
1860 // If this is a floating-point cast, and the target says this operation
1861 // is expensive, this may eventually become a library call. Treat the cost
1862 // as such.
1863 switch (I.getOpcode()) {
1864 case Instruction::FPTrunc:
1865 case Instruction::FPExt:
1866 case Instruction::UIToFP:
1867 case Instruction::SIToFP:
1868 case Instruction::FPToUI:
1869 case Instruction::FPToSI:
1871 onCallPenalty();
1872 break;
1873 default:
1874 break;
1875 }
1876
1879}
1880
1881bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1882 return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
1883}
1884
1885bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
1886 // Does the *call site* have the NonNull attribute set on an argument? We
1887 // use the attribute on the call site to memoize any analysis done in the
1888 // caller. This will also trip if the callee function has a non-null
1889 // parameter attribute, but that's a less interesting case because hopefully
1890 // the callee would already have been simplified based on that.
1891 if (Argument *A = dyn_cast<Argument>(V))
1892 if (paramHasAttr(A, Attribute::NonNull))
1893 return true;
1894
1895 // Is this an alloca in the caller? This is distinct from the attribute case
1896 // above because attributes aren't updated within the inliner itself and we
1897 // always want to catch the alloca derived case.
1898 if (isAllocaDerivedArg(V))
1899 // We can actually predict the result of comparisons between an
1900 // alloca-derived value and null. Note that this fires regardless of
1901 // SROA firing.
1902 return true;
1903
1904 return false;
1905}
1906
1907bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
1908 // If the normal destination of the invoke or the parent block of the call
1909 // site is unreachable-terminated, there is little point in inlining this
1910 // unless there is literally zero cost.
1911 // FIXME: Note that it is possible that an unreachable-terminated block has a
1912 // hot entry. For example, in below scenario inlining hot_call_X() may be
1913 // beneficial :
1914 // main() {
1915 // hot_call_1();
1916 // ...
1917 // hot_call_N()
1918 // exit(0);
1919 // }
1920 // For now, we are not handling this corner case here as it is rare in real
1921 // code. In future, we should elaborate this based on BPI and BFI in more
1922 // general threshold adjusting heuristics in updateThreshold().
1923 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
1924 if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
1925 return false;
1926 } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
1927 return false;
1928
1929 return true;
1930}
1931
1932bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1933 BlockFrequencyInfo *CallerBFI) {
1934 // If global profile summary is available, then callsite's coldness is
1935 // determined based on that.
1936 if (PSI && PSI->hasProfileSummary())
1937 return PSI->isColdCallSite(Call, CallerBFI);
1938
1939 // Otherwise we need BFI to be available.
1940 if (!CallerBFI)
1941 return false;
1942
1943 // Determine if the callsite is cold relative to caller's entry. We could
1944 // potentially cache the computation of scaled entry frequency, but the added
1945 // complexity is not worth it unless this scaling shows up high in the
1946 // profiles.
1947 const BranchProbability ColdProb(Opts.cold_callsite_rel_freq, 100);
1948 auto CallSiteBB = Call.getParent();
1949 auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1950 auto CallerEntryFreq =
1951 CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1952 return CallSiteFreq < CallerEntryFreq * ColdProb;
1953}
1954
1955std::optional<int>
1956InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1957 BlockFrequencyInfo *CallerBFI) {
1958
1959 // If global profile summary is available, then callsite's hotness is
1960 // determined based on that.
1961 if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
1962 return Params.HotCallSiteThreshold;
1963
1964 // Otherwise we need BFI to be available and to have a locally hot callsite
1965 // threshold.
1966 if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1967 return std::nullopt;
1968
1969 // Determine if the callsite is hot relative to caller's entry. We could
1970 // potentially cache the computation of scaled entry frequency, but the added
1971 // complexity is not worth it unless this scaling shows up high in the
1972 // profiles.
1973 const BasicBlock *CallSiteBB = Call.getParent();
1974 BlockFrequency CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1975 BlockFrequency CallerEntryFreq = CallerBFI->getEntryFreq();
1976 std::optional<BlockFrequency> Limit =
1977 CallerEntryFreq.mul(Opts.hot_callsite_rel_freq);
1978 if (Limit && CallSiteFreq >= *Limit)
1979 return Params.LocallyHotCallSiteThreshold;
1980
1981 // Otherwise treat it normally.
1982 return std::nullopt;
1983}
1984
1985void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
1986 // If no size growth is allowed for this inlining, set Threshold to 0.
1987 if (!allowSizeGrowth(Call)) {
1988 Threshold = 0;
1989 return;
1990 }
1991
1993
1994 // return min(A, B) if B is valid.
1995 auto MinIfValid = [](int A, std::optional<int> B) {
1996 return B ? std::min(A, *B) : A;
1997 };
1998
1999 // return max(A, B) if B is valid.
2000 auto MaxIfValid = [](int A, std::optional<int> B) {
2001 return B ? std::max(A, *B) : A;
2002 };
2003
2004 // Various bonus percentages. These are multiplied by Threshold to get the
2005 // bonus values.
2006 // SingleBBBonus: This bonus is applied if the callee has a single reachable
2007 // basic block at the given callsite context. This is speculatively applied
2008 // and withdrawn if more than one basic block is seen.
2009 //
2010 // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
2011 // of the last call to a static function as inlining such functions is
2012 // guaranteed to reduce code size.
2013 //
2014 // These bonus percentages may be set to 0 based on properties of the caller
2015 // and the callsite.
2016 int SingleBBBonusPercent = 50;
2017 int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
2018 int LastCallToStaticBonus = TTI.getInliningLastCallToStaticBonus();
2019
2020 // Lambda to set all the above bonus and bonus percentages to 0.
2021 auto DisallowAllBonuses = [&]() {
2022 SingleBBBonusPercent = 0;
2023 VectorBonusPercent = 0;
2024 LastCallToStaticBonus = 0;
2025 };
2026
2027 // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
2028 // and reduce the threshold if the caller has the necessary attribute.
2029 if (Caller->hasMinSize()) {
2030 Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
2031 // For minsize, we want to disable the single BB bonus and the vector
2032 // bonuses, but not the last-call-to-static bonus. Inlining the last call to
2033 // a static function will, at the minimum, eliminate the parameter setup and
2034 // call/return instructions.
2035 SingleBBBonusPercent = 0;
2036 VectorBonusPercent = 0;
2037 } else if (Caller->hasOptSize())
2038 Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
2039
2040 // Adjust the threshold based on inlinehint attribute and profile based
2041 // hotness information if the caller does not have MinSize attribute.
2042 if (!Caller->hasMinSize()) {
2043 std::optional<int> HintThreshold = Caller->hasOptSize()
2044 ? Params.OptSizeHintThreshold
2045 : Params.HintThreshold;
2046 if (Callee.hasFnAttribute(Attribute::InlineHint))
2047 Threshold = MaxIfValid(Threshold, HintThreshold);
2048
2049 // FIXME: After switching to the new passmanager, simplify the logic below
2050 // by checking only the callsite hotness/coldness as we will reliably
2051 // have local profile information.
2052 //
2053 // Callsite hotness and coldness can be determined if sample profile is
2054 // used (which adds hotness metadata to calls) or if caller's
2055 // BlockFrequencyInfo is available.
2056 BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
2057 auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
2058 if (!Caller->hasOptSize() && HotCallSiteThreshold) {
2059 LLVM_DEBUG(dbgs() << "Hot callsite.\n");
2060 // FIXME: This should update the threshold only if it exceeds the
2061 // current threshold, but AutoFDO + ThinLTO currently relies on this
2062 // behavior to prevent inlining of hot callsites during ThinLTO
2063 // compile phase.
2064 Threshold = *HotCallSiteThreshold;
2065 } else if (isCallableCC(Caller->getCallingConv()) &&
2066 isColdCallSite(Call, CallerBFI)) {
2067 // In a function that is a hardware entry point rather than something
2068 // callable, e.g. a GPU kernel, register allocation is whole-function and
2069 // occupancy is set by the worst case over it. A call left out of line
2070 // there costs the hot path too, however cold the call itself is, so the
2071 // reduced threshold does not apply.
2072 LLVM_DEBUG(dbgs() << "Cold callsite.\n");
2073 // Do not apply bonuses for a cold callsite including the
2074 // LastCallToStatic bonus. While this bonus might result in code size
2075 // reduction, it can cause the size of a non-cold caller to increase
2076 // preventing it from being inlined.
2077 DisallowAllBonuses();
2078 Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
2079 } else if (PSI) {
2080 // Use callee's global profile information only if we have no way of
2081 // determining this via callsite information.
2082 if (PSI->isFunctionEntryHot(&Callee)) {
2083 LLVM_DEBUG(dbgs() << "Hot callee.\n");
2084 // If callsite hotness can not be determined, we may still know
2085 // that the callee is hot and treat it as a weaker hint for threshold
2086 // increase.
2087 Threshold = MaxIfValid(Threshold, HintThreshold);
2088 } else if (PSI->isFunctionEntryCold(&Callee)) {
2089 LLVM_DEBUG(dbgs() << "Cold callee.\n");
2090 // Do not apply bonuses for a cold callee including the
2091 // LastCallToStatic bonus. While this bonus might result in code size
2092 // reduction, it can cause the size of a non-cold caller to increase
2093 // preventing it from being inlined.
2094 DisallowAllBonuses();
2095 Threshold = MinIfValid(Threshold, Params.ColdThreshold);
2096 }
2097 }
2098 }
2099
2100 Threshold += TTI.adjustInliningThreshold(&Call);
2101
2102 // Finally, take the target-specific inlining threshold multiplier into
2103 // account.
2104 Threshold *= TTI.getInliningThresholdMultiplier();
2105
2106 SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
2107 VectorBonus = Threshold * VectorBonusPercent / 100;
2108
2109 // If there is only one call of the function, and it has internal linkage,
2110 // the cost of inlining it drops dramatically. It may seem odd to update
2111 // Cost in updateThreshold, but the bonus depends on the logic in this method.
2112 if (isSoleCallToLocalFunction(Call, F)) {
2113 addCost(-LastCallToStaticBonus);
2114 StaticBonusApplied = LastCallToStaticBonus;
2115 }
2116}
2117
2118bool CallAnalyzer::visitCmpInst(CmpInst &I) {
2119 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2120 // First try to handle simplified comparisons.
2122 return true;
2123
2124 // Try to handle comparison that can be simplified using ValueTracking.
2125 if (simplifyCmpInstForRecCall(I))
2126 return true;
2127
2128 if (I.getOpcode() == Instruction::FCmp)
2129 return false;
2130
2131 // Otherwise look for a comparison between constant offset pointers with
2132 // a common base.
2133 Value *LHSBase, *RHSBase;
2134 APInt LHSOffset, RHSOffset;
2135 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
2136 if (LHSBase) {
2137 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
2138 if (RHSBase && LHSBase == RHSBase) {
2139 // We have common bases, fold the icmp to a constant based on the
2140 // offsets.
2141 SimplifiedValues[&I] = ConstantInt::getBool(
2142 I.getType(),
2143 ICmpInst::compare(LHSOffset, RHSOffset, I.getPredicate()));
2144 ++NumConstantPtrCmps;
2145 return true;
2146 }
2147 }
2148
2149 auto isImplicitNullCheckCmp = [](const CmpInst &I) {
2150 for (auto *User : I.users())
2151 if (auto *Instr = dyn_cast<Instruction>(User))
2152 if (!Instr->getMetadata(LLVMContext::MD_make_implicit))
2153 return false;
2154 return true;
2155 };
2156
2157 // If the comparison is an equality comparison with null, we can simplify it
2158 // if we know the value (argument) can't be null
2159 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1))) {
2160 if (isKnownNonNullInCallee(I.getOperand(0))) {
2161 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
2162 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
2163 : ConstantInt::getFalse(I.getType());
2164 return true;
2165 }
2166 // Implicit null checks act as unconditional branches and their comparisons
2167 // should be treated as simplified and free of cost.
2168 if (isImplicitNullCheckCmp(I))
2169 return true;
2170 }
2171 return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
2172}
2173
2174bool CallAnalyzer::visitSub(BinaryOperator &I) {
2175 // Try to handle a special case: we can fold computing the difference of two
2176 // constant-related pointers.
2177 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2178 Value *LHSBase, *RHSBase;
2179 APInt LHSOffset, RHSOffset;
2180 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
2181 if (LHSBase) {
2182 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
2183 if (RHSBase && LHSBase == RHSBase) {
2184 // We have common bases, fold the subtract to a constant based on the
2185 // offsets.
2186 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
2187 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
2188 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
2189 SimplifiedValues[&I] = C;
2190 ++NumConstantPtrDiffs;
2191 return true;
2192 }
2193 }
2194 }
2195
2196 // Otherwise, fall back to the generic logic for simplifying and handling
2197 // instructions.
2198 return Base::visitSub(I);
2199}
2200
2201bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
2202 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2203 Constant *CLHS = getDirectOrSimplifiedValue<Constant>(LHS);
2204 Constant *CRHS = getDirectOrSimplifiedValue<Constant>(RHS);
2205
2206 Value *SimpleV = nullptr;
2207 if (auto FI = dyn_cast<FPMathOperator>(&I))
2208 SimpleV = simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
2209 FI->getFastMathFlags(), DL);
2210 else
2211 SimpleV =
2212 simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
2213
2214 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2215 SimplifiedValues[&I] = C;
2216
2217 if (SimpleV)
2218 return true;
2219
2220 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
2221 disableSROA(LHS);
2222 disableSROA(RHS);
2223
2224 // If the instruction is floating point, and the target says this operation
2225 // is expensive, this may eventually become a library call. Treat the cost
2226 // as such. Unless it's fneg which can be implemented with an xor.
2227 using namespace llvm::PatternMatch;
2228 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2229 if (I.getType()->isFloatingPointTy() &&
2232 onCallPenalty();
2233
2234 return false;
2235}
2236
2237bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
2238 Value *Op = I.getOperand(0);
2239 Constant *COp = getDirectOrSimplifiedValue<Constant>(Op);
2240
2241 Value *SimpleV = simplifyFNegInst(
2242 COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
2243
2244 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2245 SimplifiedValues[&I] = C;
2246
2247 if (SimpleV)
2248 return true;
2249
2250 // Disable any SROA on arguments to arbitrary, unsimplified fneg.
2251 disableSROA(Op);
2252
2253 return false;
2254}
2255
2256bool CallAnalyzer::visitLoad(LoadInst &I) {
2257 if (handleSROA(I.getPointerOperand(), I.isSimple()))
2258 return true;
2259
2260 // If the data is already loaded from this address and hasn't been clobbered
2261 // by any stores or calls, this load is likely to be redundant and can be
2262 // eliminated.
2263 if (EnableLoadElimination &&
2264 !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
2265 onLoadEliminationOpportunity();
2266 return true;
2267 }
2268
2269 onMemAccess();
2270 return false;
2271}
2272
2273bool CallAnalyzer::visitStore(StoreInst &I) {
2274 if (handleSROA(I.getPointerOperand(), I.isSimple()))
2275 return true;
2276
2277 // The store can potentially clobber loads and prevent repeated loads from
2278 // being eliminated.
2279 // FIXME:
2280 // 1. We can probably keep an initial set of eliminatable loads substracted
2281 // from the cost even when we finally see a store. We just need to disable
2282 // *further* accumulation of elimination savings.
2283 // 2. We should probably at some point thread MemorySSA for the callee into
2284 // this and then use that to actually compute *really* precise savings.
2285 disableLoadElimination();
2286
2287 onMemAccess();
2288 return false;
2289}
2290
2291bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
2292 Value *Op = I.getAggregateOperand();
2293
2294 // Special handling, because we want to simplify extractvalue with a
2295 // potential insertvalue from the caller.
2296 if (Value *SimpleOp = getSimplifiedValueUnchecked(Op)) {
2297 SimplifyQuery SQ(DL);
2298 Value *SimpleV = simplifyExtractValueInst(SimpleOp, I.getIndices(), SQ);
2299 if (SimpleV) {
2300 SimplifiedValues[&I] = SimpleV;
2301 return true;
2302 }
2303 }
2304
2305 // SROA can't look through these, but they may be free.
2306 return Base::visitExtractValue(I);
2307}
2308
2309bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
2310 // Constant folding for insert value is trivial.
2312 return true;
2313
2314 // SROA can't look through these, but they may be free.
2315 return Base::visitInsertValue(I);
2316}
2317
2318/// Try to simplify a call site.
2319///
2320/// Takes a concrete function and callsite and tries to actually simplify it by
2321/// analyzing the arguments and call itself with instsimplify. Returns true if
2322/// it has simplified the callsite to some other entity (a constant), making it
2323/// free.
2324bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
2325 // FIXME: Using the instsimplify logic directly for this is inefficient
2326 // because we have to continually rebuild the argument list even when no
2327 // simplifications can be performed. Until that is fixed with remapping
2328 // inside of instsimplify, directly constant fold calls here.
2330 return false;
2331
2332 // Try to re-map the arguments to constants.
2333 SmallVector<Constant *, 4> ConstantArgs;
2334 ConstantArgs.reserve(Call.arg_size());
2335 for (Value *I : Call.args()) {
2336 Constant *C = getDirectOrSimplifiedValue<Constant>(I);
2337 if (!C)
2338 return false; // This argument doesn't map to a constant.
2339
2340 ConstantArgs.push_back(C);
2341 }
2342 if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
2343 SimplifiedValues[&Call] = C;
2344 return true;
2345 }
2346
2347 return false;
2348}
2349
2350bool CallAnalyzer::isLoweredToCall(Function *F, CallBase &Call) {
2351 const TargetLibraryInfo *TLI = GetTLI ? &GetTLI(*F) : nullptr;
2352 if (!TLI)
2353 return TTI.isLoweredToCall(F);
2354
2355 LibFunc LF = TLI->getLibFunc(*F);
2356 if (!TLI->has(LF))
2357 return TTI.isLoweredToCall(F);
2358
2359 switch (LF) {
2360 case LibFunc_memcpy_chk:
2361 case LibFunc_memmove_chk:
2362 case LibFunc_mempcpy_chk:
2363 case LibFunc_memset_chk: {
2364 // Calls to __memcpy_chk whose length is known to fit within the object
2365 // size will eventually be replaced by inline stores. Therefore, these
2366 // should not incur a call penalty. This is only really relevant on
2367 // platforms whose headers redirect memcpy to __memcpy_chk (e.g. Darwin), as
2368 // other platforms use memcpy intrinsics, which are already exempt from the
2369 // call penalty.
2370 auto *LenOp = getDirectOrSimplifiedValue<ConstantInt>(Call.getOperand(2));
2371 auto *ObjSizeOp =
2372 getDirectOrSimplifiedValue<ConstantInt>(Call.getOperand(3));
2373 if (LenOp && ObjSizeOp &&
2374 LenOp->getLimitedValue() <= ObjSizeOp->getLimitedValue()) {
2375 return false;
2376 }
2377 break;
2378 }
2379 default:
2380 break;
2381 }
2382
2383 return TTI.isLoweredToCall(F);
2384}
2385
2386bool CallAnalyzer::visitCallBase(CallBase &Call) {
2387 if (!onCallBaseVisitStart(Call))
2388 return true;
2389
2390 if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
2391 !F.hasFnAttribute(Attribute::ReturnsTwice)) {
2392 // This aborts the entire analysis.
2393 ExposesReturnsTwice = true;
2394 return false;
2395 }
2396 if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
2397 ContainsNoDuplicateCall = true;
2398
2399 if (InlineAsm *InlineAsmOp = dyn_cast<InlineAsm>(Call.getCalledOperand()))
2400 onInlineAsm(*InlineAsmOp);
2401
2403 bool IsIndirectCall = !F;
2404 if (IsIndirectCall) {
2405 // Check if this happens to be an indirect function call to a known function
2406 // in this inline context. If not, we've done all we can.
2408 F = getSimplifiedValue<Function>(Callee);
2409 if (!F || F->getFunctionType() != Call.getFunctionType()) {
2410 onCallArgumentSetup(Call);
2411
2412 if (!Call.onlyReadsMemory())
2413 disableLoadElimination();
2414 return Base::visitCallBase(Call);
2415 }
2416 }
2417
2418 assert(F && "Expected a call to a known function");
2419
2420 // When we have a concrete function, first try to simplify it directly.
2421 if (simplifyCallSite(F, Call))
2422 return true;
2423
2424 // Next check if it is an intrinsic we know about.
2425 // FIXME: Lift this into part of the InstVisitor.
2426 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
2427 switch (II->getIntrinsicID()) {
2428 default:
2430 disableLoadElimination();
2431 return Base::visitCallBase(Call);
2432
2433 case Intrinsic::load_relative:
2434 onLoadRelativeIntrinsic();
2435 return false;
2436
2437 case Intrinsic::memset:
2438 case Intrinsic::memcpy:
2439 case Intrinsic::memmove:
2440 disableLoadElimination();
2441 // SROA can usually chew through these intrinsics, but they aren't free.
2442 return false;
2443 case Intrinsic::icall_branch_funnel:
2444 case Intrinsic::localescape:
2445 HasUninlineableIntrinsic = true;
2446 return false;
2447 case Intrinsic::vastart:
2448 InitsVargArgs = true;
2449 return false;
2450 case Intrinsic::launder_invariant_group:
2451 if (auto *SROAArg = getSROAArgForValueOrNull(II->getOperand(0)))
2452 SROAArgValues[II] = SROAArg;
2453 return true;
2454 case Intrinsic::is_constant:
2455 return simplifyIntrinsicCallIsConstant(Call);
2456 case Intrinsic::objectsize:
2457 return simplifyIntrinsicCallObjectSize(Call);
2458 }
2459 }
2460
2461 if (F == Call.getFunction()) {
2462 // This flag will fully abort the analysis, so don't bother with anything
2463 // else.
2464 IsRecursiveCall = true;
2465 if (!AllowRecursiveCall)
2466 return false;
2467 }
2468
2469 if (isLoweredToCall(F, Call)) {
2470 onLoweredCall(F, Call, IsIndirectCall);
2471 }
2472
2473 if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
2474 disableLoadElimination();
2475 return Base::visitCallBase(Call);
2476}
2477
2478bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
2479 // At least one return instruction will be free after inlining.
2480 bool Free = !HasReturn;
2481 HasReturn = true;
2482 return Free;
2483}
2484
2485bool CallAnalyzer::visitUncondBrInst(UncondBrInst &BI) {
2486 // We model unconditional branches as essentially free -- they really
2487 // shouldn't exist at all, but handling them makes the behavior of the
2488 // inliner more regular and predictable.
2489 return true;
2490}
2491
2492bool CallAnalyzer::visitCondBrInst(CondBrInst &BI) {
2493 // Conditional branches which will fold away are free.
2494 return getDirectOrSimplifiedValue<ConstantInt>(BI.getCondition()) ||
2495 BI.getMetadata(LLVMContext::MD_make_implicit);
2496}
2497
2498bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
2499 bool CheckSROA = SI.getType()->isPointerTy();
2500 Value *TrueVal = SI.getTrueValue();
2501 Value *FalseVal = SI.getFalseValue();
2502
2503 Constant *TrueC = getDirectOrSimplifiedValue<Constant>(TrueVal);
2504 Constant *FalseC = getDirectOrSimplifiedValue<Constant>(FalseVal);
2505 Constant *CondC = getSimplifiedValue<Constant>(SI.getCondition());
2506
2507 if (!CondC) {
2508 // Select C, X, X => X
2509 if (TrueC == FalseC && TrueC) {
2510 SimplifiedValues[&SI] = TrueC;
2511 return true;
2512 }
2513
2514 if (!CheckSROA)
2515 return Base::visitSelectInst(SI);
2516
2517 std::pair<Value *, APInt> TrueBaseAndOffset =
2518 ConstantOffsetPtrs.lookup(TrueVal);
2519 std::pair<Value *, APInt> FalseBaseAndOffset =
2520 ConstantOffsetPtrs.lookup(FalseVal);
2521 if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
2522 ConstantOffsetPtrs[&SI] = std::move(TrueBaseAndOffset);
2523
2524 if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
2525 SROAArgValues[&SI] = SROAArg;
2526 return true;
2527 }
2528
2529 return Base::visitSelectInst(SI);
2530 }
2531
2532 // Select condition is a constant.
2533 Value *SelectedV = CondC->isAllOnesValue() ? TrueVal
2534 : (CondC->isNullValue()) ? FalseVal
2535 : nullptr;
2536 if (!SelectedV) {
2537 // Condition is a vector constant that is not all 1s or all 0s. If all
2538 // operands are constants, ConstantFoldSelectInstruction() can handle the
2539 // cases such as select vectors.
2540 if (TrueC && FalseC) {
2541 if (auto *C = ConstantFoldSelectInstruction(CondC, TrueC, FalseC)) {
2542 SimplifiedValues[&SI] = C;
2543 return true;
2544 }
2545 }
2546 return Base::visitSelectInst(SI);
2547 }
2548
2549 // Condition is either all 1s or all 0s. SI can be simplified.
2550 if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
2551 SimplifiedValues[&SI] = SelectedC;
2552 return true;
2553 }
2554
2555 if (!CheckSROA)
2556 return true;
2557
2558 std::pair<Value *, APInt> BaseAndOffset =
2559 ConstantOffsetPtrs.lookup(SelectedV);
2560 if (BaseAndOffset.first) {
2561 ConstantOffsetPtrs[&SI] = std::move(BaseAndOffset);
2562
2563 if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
2564 SROAArgValues[&SI] = SROAArg;
2565 }
2566
2567 return true;
2568}
2569
2570bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
2571 // We model unconditional switches as free, see the comments on handling
2572 // branches.
2573 if (getDirectOrSimplifiedValue<ConstantInt>(SI.getCondition()))
2574 return true;
2575
2576 // Assume the most general case where the switch is lowered into
2577 // either a jump table, bit test, or a balanced binary tree consisting of
2578 // case clusters without merging adjacent clusters with the same
2579 // destination. We do not consider the switches that are lowered with a mix
2580 // of jump table/bit test/binary search tree. The cost of the switch is
2581 // proportional to the size of the tree or the size of jump table range.
2582 //
2583 // NB: We convert large switches which are just used to initialize large phi
2584 // nodes to lookup tables instead in simplifycfg, so this shouldn't prevent
2585 // inlining those. It will prevent inlining in cases where the optimization
2586 // does not (yet) fire.
2587
2588 unsigned JumpTableSize = 0;
2589 BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2590 unsigned NumCaseCluster =
2591 TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2592
2593 onFinalizeSwitch(JumpTableSize, NumCaseCluster, SI.defaultDestUnreachable());
2594 return false;
2595}
2596
2597bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
2598 // We never want to inline functions that contain an indirectbr. This is
2599 // incorrect because all the blockaddress's (in static global initializers
2600 // for example) would be referring to the original function, and this
2601 // indirect jump would jump from the inlined copy of the function into the
2602 // original function which is extremely undefined behavior.
2603 // FIXME: This logic isn't really right; we can safely inline functions with
2604 // indirectbr's as long as no other function or global references the
2605 // blockaddress of a block within the current function.
2606 HasIndirectBr = true;
2607 return false;
2608}
2609
2610bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
2611 // FIXME: It's not clear that a single instruction is an accurate model for
2612 // the inline cost of a resume instruction.
2613 return false;
2614}
2615
2616bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
2617 // FIXME: It's not clear that a single instruction is an accurate model for
2618 // the inline cost of a cleanupret instruction.
2619 return false;
2620}
2621
2622bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
2623 // FIXME: It's not clear that a single instruction is an accurate model for
2624 // the inline cost of a catchret instruction.
2625 return false;
2626}
2627
2628bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
2629 // FIXME: It might be reasonably to discount the cost of instructions leading
2630 // to unreachable as they have the lowest possible impact on both runtime and
2631 // code size.
2632 return true; // No actual code is needed for unreachable.
2633}
2634
2635bool CallAnalyzer::visitInstruction(Instruction &I) {
2636 // Some instructions are free. All of the free intrinsics can also be
2637 // handled by SROA, etc.
2640 return true;
2641
2642 // We found something we don't understand or can't handle. Mark any SROA-able
2643 // values in the operand list as no longer viable.
2644 for (const Use &Op : I.operands())
2645 disableSROA(Op);
2646
2647 return false;
2648}
2649
2650/// Analyze a basic block for its contribution to the inline cost.
2651///
2652/// This method walks the analyzer over every instruction in the given basic
2653/// block and accounts for their cost during inlining at this callsite. It
2654/// aborts early if the threshold has been exceeded or an impossible to inline
2655/// construct has been detected. It returns false if inlining is no longer
2656/// viable, and true if inlining remains viable.
2657InlineResult
2658CallAnalyzer::analyzeBlock(BasicBlock *BB,
2659 const SmallPtrSetImpl<const Value *> &EphValues) {
2660 for (Instruction &I : *BB) {
2661 // FIXME: Currently, the number of instructions in a function regardless of
2662 // our ability to simplify them during inline to constants or dead code,
2663 // are actually used by the vector bonus heuristic. As long as that's true,
2664 // we have to special case pseudo-probes here to prevent differences in
2665 // inlining due to sample profiling. Eventually, the number of unsimplified
2666 // instructions shouldn't factor into the cost computation, but until then,
2667 // hack around it here.
2669 continue;
2670
2671 // Skip ephemeral values.
2672 if (EphValues.count(&I))
2673 continue;
2674
2675 ++NumInstructions;
2676 if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
2677 ++NumVectorInstructions;
2678
2679 // If the instruction simplified to a constant, there is no cost to this
2680 // instruction. Visit the instructions using our InstVisitor to account for
2681 // all of the per-instruction logic. The visit tree returns true if we
2682 // consumed the instruction in any way, and false if the instruction's base
2683 // cost should count against inlining.
2684 onInstructionAnalysisStart(&I);
2685
2686 if (Base::visit(&I))
2687 ++NumInstructionsSimplified;
2688 else
2689 onMissedSimplification();
2690
2691 onInstructionAnalysisFinish(&I);
2692 using namespace ore;
2693 // If the visit this instruction detected an uninlinable pattern, abort.
2694 InlineResult IR = InlineResult::success();
2695 if (IsRecursiveCall && !AllowRecursiveCall)
2696 IR = InlineResult::failure("recursive");
2697 else if (ExposesReturnsTwice)
2698 IR = InlineResult::failure("exposes returns twice");
2699 else if (HasDynamicAlloca)
2700 IR = InlineResult::failure("dynamic alloca");
2701 else if (HasIndirectBr)
2702 IR = InlineResult::failure("indirect branch");
2703 else if (HasUninlineableIntrinsic)
2704 IR = InlineResult::failure("uninlinable intrinsic");
2705 else if (InitsVargArgs)
2706 IR = InlineResult::failure("varargs");
2707 if (!IR.isSuccess()) {
2708 if (ORE)
2709 ORE->emit([&]() {
2710 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2711 &CandidateCall)
2712 << NV("Callee", &F) << " has uninlinable pattern ("
2713 << NV("InlineResult", IR.getFailureReason())
2714 << ") and cost is not fully computed";
2715 });
2716 return IR;
2717 }
2718
2719 // If the caller is a recursive function then we don't want to inline
2720 // functions which allocate a lot of stack space because it would increase
2721 // the caller stack usage dramatically.
2722 if (IsCallerRecursive &&
2723 AllocatedSize > Opts.recursive_inline_max_stacksize) {
2724 auto IR =
2725 InlineResult::failure("recursive and allocates too much stack space");
2726 if (ORE)
2727 ORE->emit([&]() {
2728 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2729 &CandidateCall)
2730 << NV("Callee", &F) << " is "
2731 << NV("InlineResult", IR.getFailureReason())
2732 << ". Cost is not fully computed";
2733 });
2734 return IR;
2735 }
2736
2737 if (shouldStop())
2738 return InlineResult::failure(
2739 "Call site analysis is not favorable to inlining.");
2740 }
2741
2742 return InlineResult::success();
2743}
2744
2745/// Compute the base pointer and cumulative constant offsets for V.
2746///
2747/// This strips all constant offsets off of V, leaving it the base pointer, and
2748/// accumulates the total constant offset applied in the returned constant. It
2749/// returns 0 if V is not a pointer, and returns the constant '0' if there are
2750/// no constant offsets applied.
2751ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
2752 if (!V->getType()->isPointerTy())
2753 return nullptr;
2754
2755 unsigned AS = V->getType()->getPointerAddressSpace();
2756 unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
2757 APInt Offset = APInt::getZero(IntPtrWidth);
2758
2759 // Even though we don't look through PHI nodes, we could be called on an
2760 // instruction in an unreachable block, which may be on a cycle.
2761 SmallPtrSet<Value *, 4> Visited;
2762 Visited.insert(V);
2763 do {
2764 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2765 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
2766 return nullptr;
2767 V = GEP->getPointerOperand();
2768 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2769 if (GA->isInterposable())
2770 break;
2771 V = GA->getAliasee();
2772 } else {
2773 break;
2774 }
2775 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2776 } while (Visited.insert(V).second);
2777
2778 Type *IdxPtrTy = DL.getIndexType(V->getType());
2779 return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
2780}
2781
2782/// Find dead blocks due to deleted CFG edges during inlining.
2783///
2784/// If we know the successor of the current block, \p CurrBB, has to be \p
2785/// NextBB, the other successors of \p CurrBB are dead if these successors have
2786/// no live incoming CFG edges. If one block is found to be dead, we can
2787/// continue growing the dead block list by checking the successors of the dead
2788/// blocks to see if all their incoming edges are dead or not.
2789void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
2790 auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
2791 // A CFG edge is dead if the predecessor is dead or the predecessor has a
2792 // known successor which is not the one under exam.
2793 if (DeadBlocks.count(Pred))
2794 return true;
2795 BasicBlock *KnownSucc = KnownSuccessors[Pred];
2796 return KnownSucc && KnownSucc != Succ;
2797 };
2798
2799 auto IsNewlyDead = [&](BasicBlock *BB) {
2800 // If all the edges to a block are dead, the block is also dead.
2801 return (!DeadBlocks.count(BB) &&
2803 [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
2804 };
2805
2806 for (BasicBlock *Succ : successors(CurrBB)) {
2807 if (Succ == NextBB || !IsNewlyDead(Succ))
2808 continue;
2810 NewDead.push_back(Succ);
2811 while (!NewDead.empty()) {
2812 BasicBlock *Dead = NewDead.pop_back_val();
2813 if (DeadBlocks.insert(Dead).second)
2814 // Continue growing the dead block lists.
2815 for (BasicBlock *S : successors(Dead))
2816 if (IsNewlyDead(S))
2817 NewDead.push_back(S);
2818 }
2819 }
2820}
2821
2822/// Analyze a call site for potential inlining.
2823///
2824/// Returns true if inlining this call is viable, and false if it is not
2825/// viable. It computes the cost and adjusts the threshold based on numerous
2826/// factors and heuristics. If this method returns false but the computed cost
2827/// is below the computed threshold, then inlining was forcibly disabled by
2828/// some artifact of the routine.
2829InlineResult CallAnalyzer::analyze() {
2830 ++NumCallsAnalyzed;
2831
2832 auto Result = onAnalysisStart();
2833 if (!Result.isSuccess())
2834 return Result;
2835
2836 if (F.empty())
2837 return InlineResult::success();
2838
2839 Function *Caller = CandidateCall.getFunction();
2840 // Check if the caller function is recursive itself.
2841 for (User *U : Caller->users()) {
2842 CallBase *Call = dyn_cast<CallBase>(U);
2843 if (Call && Call->getFunction() == Caller) {
2844 IsCallerRecursive = true;
2845 break;
2846 }
2847 }
2848
2849 // Populate our simplified values by mapping from function arguments to call
2850 // arguments with known important simplifications.
2851 auto CAI = CandidateCall.arg_begin();
2852 for (Argument &FAI : F.args()) {
2853 assert(CAI != CandidateCall.arg_end());
2854 SimplifiedValues[&FAI] = *CAI;
2855 if (isa<Constant>(*CAI))
2856 ++NumConstantArgs;
2857
2858 Value *PtrArg = *CAI;
2859 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
2860 ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
2861
2862 // We can SROA any pointer arguments derived from alloca instructions.
2863 if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
2864 SROAArgValues[&FAI] = SROAArg;
2865 onInitializeSROAArg(SROAArg);
2866 EnabledSROAAllocas.insert(SROAArg);
2867 }
2868 }
2869 ++CAI;
2870 }
2871 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
2872 NumAllocaArgs = SROAArgValues.size();
2873
2874 // Collecting the ephemeral values of `F` can be expensive, so use the
2875 // ephemeral values cache if available.
2876 SmallPtrSet<const Value *, 32> EphValuesStorage;
2877 const SmallPtrSetImpl<const Value *> *EphValues = &EphValuesStorage;
2878 if (GetEphValuesCache)
2879 EphValues = &GetEphValuesCache(F).ephValues();
2880 else
2881 CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F),
2882 EphValuesStorage);
2883
2884 // The worklist of live basic blocks in the callee *after* inlining. We avoid
2885 // adding basic blocks of the callee which can be proven to be dead for this
2886 // particular call site in order to get more accurate cost estimates. This
2887 // requires a somewhat heavyweight iteration pattern: we need to walk the
2888 // basic blocks in a breadth-first order as we insert live successors. To
2889 // accomplish this, prioritizing for small iterations because we exit after
2890 // crossing our threshold, we use a small-size optimized SetVector.
2891 typedef SmallSetVector<BasicBlock *, 16> BBSetVector;
2892 BBSetVector BBWorklist;
2893 BBWorklist.insert(&F.getEntryBlock());
2894
2895 // Note that we *must not* cache the size, this loop grows the worklist.
2896 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
2897 if (shouldStop())
2898 break;
2899
2900 BasicBlock *BB = BBWorklist[Idx];
2901 if (BB->empty())
2902 continue;
2903
2904 onBlockStart(BB);
2905
2906 // Disallow inlining a blockaddress.
2907 // A blockaddress only has defined behavior for an indirect branch in the
2908 // same function, and we do not currently support inlining indirect
2909 // branches. But, the inliner may not see an indirect branch that ends up
2910 // being dead code at a particular call site. If the blockaddress escapes
2911 // the function, e.g., via a global variable, inlining may lead to an
2912 // invalid cross-function reference.
2913 // FIXME: pr/39560: continue relaxing this overt restriction.
2914 if (BB->hasAddressTaken())
2915 return InlineResult::failure("blockaddress used");
2916
2917 // Analyze the cost of this block. If we blow through the threshold, this
2918 // returns false, and we can bail on out.
2919 InlineResult IR = analyzeBlock(BB, *EphValues);
2920 if (!IR.isSuccess())
2921 return IR;
2922
2923 Instruction *TI = BB->getTerminator();
2924
2925 // Add in the live successors by first checking whether we have terminator
2926 // that may be simplified based on the values simplified by this call.
2927 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
2928 Value *Cond = BI->getCondition();
2929 if (ConstantInt *SimpleCond = getSimplifiedValue<ConstantInt>(Cond)) {
2930 BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
2931 BBWorklist.insert(NextBB);
2932 KnownSuccessors[BB] = NextBB;
2933 findDeadBlocks(BB, NextBB);
2934 continue;
2935 }
2936 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2937 Value *Cond = SI->getCondition();
2938 if (ConstantInt *SimpleCond = getSimplifiedValue<ConstantInt>(Cond)) {
2939 BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
2940 BBWorklist.insert(NextBB);
2941 KnownSuccessors[BB] = NextBB;
2942 findDeadBlocks(BB, NextBB);
2943 continue;
2944 }
2945 }
2946
2947 // If we're unable to select a particular successor, just count all of
2948 // them.
2949 BBWorklist.insert_range(successors(BB));
2950
2951 onBlockAnalyzed(BB);
2952 }
2953
2954 // If this is a noduplicate call, we can still inline as long as
2955 // inlining this would cause the removal of the caller (so the instruction
2956 // is not actually duplicated, just moved).
2957 if (!isSoleCallToLocalFunction(CandidateCall, F) && ContainsNoDuplicateCall)
2958 return InlineResult::failure("noduplicate");
2959
2960 // If the callee's stack size exceeds the user-specified threshold,
2961 // do not let it be inlined.
2962 // The command line option overrides a limit set in the function attributes.
2963 size_t FinalStackSizeThreshold = std::numeric_limits<size_t>::max();
2964 if (Opts.inline_max_stacksize)
2965 FinalStackSizeThreshold = *Opts.inline_max_stacksize;
2966 else if (std::optional<int> AttrMaxStackSize = getStringFnAttrAsInt(
2968 FinalStackSizeThreshold = *AttrMaxStackSize;
2969 if (AllocatedSize > FinalStackSizeThreshold)
2970 return InlineResult::failure("stacksize");
2971
2972 return finalizeAnalysis();
2973}
2974
2975void InlineCostCallAnalyzer::print(raw_ostream &OS) {
2976#define DEBUG_PRINT_STAT(x) OS << " " #x ": " << x << "\n"
2977 if (PrintInstructionComments)
2978 F.print(OS, &Writer);
2979 DEBUG_PRINT_STAT(NumConstantArgs);
2980 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
2981 DEBUG_PRINT_STAT(NumAllocaArgs);
2982 DEBUG_PRINT_STAT(NumConstantPtrCmps);
2983 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
2984 DEBUG_PRINT_STAT(NumInstructionsSimplified);
2985 DEBUG_PRINT_STAT(NumInstructions);
2986 DEBUG_PRINT_STAT(NumInlineAsmInstructions);
2987 DEBUG_PRINT_STAT(SROACostSavings);
2988 DEBUG_PRINT_STAT(SROACostSavingsLost);
2989 DEBUG_PRINT_STAT(LoadEliminationCost);
2990 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
2992 DEBUG_PRINT_STAT(Threshold);
2993#undef DEBUG_PRINT_STAT
2994}
2995
2996#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2997/// Dump stats about this call's analysis.
2998LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { print(dbgs()); }
2999#endif
3000
3001/// Test that there are no attribute conflicts between Caller and Callee
3002/// that prevent inlining.
3004 const AnalysisOptions &Opts, Function *Caller, Function *Callee,
3005 function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
3006 // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
3007 // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
3008 // object, and always returns the same object (which is overwritten on each
3009 // GetTLI call). Therefore we copy the first result.
3010 auto CalleeTLI = GetTLI(*Callee);
3011 return GetTLI(*Caller).areInlineCompatible(
3012 CalleeTLI, Opts.inline_caller_superset_nobuiltin) &&
3013 AttributeFuncs::areInlineCompatible(*Caller, *Callee);
3014}
3015
3017 const DataLayout &DL) {
3018 int64_t Cost = 0;
3019 for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
3020 if (Call.isByValArgument(I)) {
3021 // We approximate the number of loads and stores needed by dividing the
3022 // size of the byval type by the target's pointer size.
3023 PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
3024 unsigned TypeSize = DL.getTypeSizeInBits(Call.getParamByValType(I));
3025 unsigned AS = PTy->getAddressSpace();
3026 unsigned PointerSize = DL.getPointerSizeInBits(AS);
3027 // Ceiling division.
3028 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
3029
3030 // If it generates more than 8 stores it is likely to be expanded as an
3031 // inline memcpy so we take that as an upper bound. Otherwise we assume
3032 // one load and one store per word copied.
3033 // FIXME: The maxStoresPerMemcpy setting from the target should be used
3034 // here instead of a magic number of 8, but it's not available via
3035 // DataLayout.
3036 NumStores = std::min(NumStores, 8U);
3037
3038 Cost += 2 * NumStores * InstrCost;
3039 } else {
3040 // For non-byval arguments subtract off one instruction per call
3041 // argument.
3042 Cost += InstrCost;
3043 }
3044 }
3045 // The call instruction also disappears after inlining.
3046 Cost += InstrCost;
3047 Cost += TTI.getInlineCallPenalty(
3048 Call.getCaller(), Call,
3049 getAnalysisOptions(Call.getContext()).inline_call_penalty);
3050
3051 return std::min<int64_t>(Cost, INT_MAX);
3052}
3053
3055 CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
3056 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3057 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3060 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
3061 return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
3062 GetAssumptionCache, GetTLI, GetBFI, PSI, ORE,
3063 GetEphValuesCache);
3064}
3065
3067 CallBase &Call, TargetTransformInfo &CalleeTTI,
3068 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3070 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3072 const InlineParams Params = {/* DefaultThreshold*/ 0,
3073 /*HintThreshold*/ {},
3074 /*OptSizeHintThreshold*/ {},
3075 /*ColdThreshold*/ {},
3076 /*OptSizeThreshold*/ {},
3077 /*OptMinSizeThreshold*/ {},
3078 /*HotCallSiteThreshold*/ {},
3079 /*LocallyHotCallSiteThreshold*/ {},
3080 /*ColdCallSiteThreshold*/ {},
3081 /*ComputeFullInlineCost*/ true,
3082 /*EnableDeferral*/ true};
3083
3084 InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
3085 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE, true,
3086 /*IgnoreThreshold*/ true);
3087 auto R = CA.analyze();
3088 if (!R.isSuccess())
3089 return std::nullopt;
3090 return CA.getCost();
3091}
3092
3093std::optional<InlineCostFeatures> llvm::getInliningCostFeatures(
3094 CallBase &Call, TargetTransformInfo &CalleeTTI,
3095 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3097 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3099 InlineCostFeaturesAnalyzer CFA(CalleeTTI, GetAssumptionCache, GetBFI, GetTLI,
3100 PSI, ORE, *Call.getCalledFunction(), Call);
3101 auto R = CFA.analyze();
3102 if (!R.isSuccess())
3103 return std::nullopt;
3104 return CFA.features();
3105}
3106
3108 CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
3109 function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
3110
3111 // Cannot inline indirect calls.
3112 if (!Callee)
3113 return InlineResult::failure("indirect call");
3114
3115 // When callee coroutine function is inlined into caller coroutine function
3116 // before coro-split pass,
3117 // coro-early pass can not handle this quiet well.
3118 // So we won't inline the coroutine function if it have not been unsplited
3119 if (Callee->isPresplitCoroutine())
3120 return InlineResult::failure("unsplited coroutine call");
3121
3122 // Inlining into a function with less target features is unsound, so enforce
3123 // this even if alwaysinline is used.
3124 Function *Caller = Call.getCaller();
3125 const AnalysisOptions &Opts = getAnalysisOptions(*Caller);
3126 if (!Opts.ignore_tti_inline_compatible &&
3127 !CalleeTTI.areInlineCompatible(Caller, Callee))
3128 return InlineResult::failure("conflicting target features");
3129
3130 // Calls to functions with always-inline attributes should be inlined
3131 // whenever possible.
3132 if (Call.hasFnAttr(Attribute::AlwaysInline)) {
3133 if (Call.getAttributes().hasFnAttr(Attribute::NoInline))
3134 return InlineResult::failure("noinline call site attribute");
3135
3136 if (!AttributeFuncs::isStrictFPInlineCompatible(*Caller, *Callee))
3137 return InlineResult::failure("incompatible strictfp attributes");
3138
3139 auto IsViable = isInlineViable(*Callee);
3140 if (IsViable.isSuccess())
3141 return InlineResult::success();
3142 return InlineResult::failure(IsViable.getFailureReason());
3143 }
3144
3145 // Never inline functions with conflicting attributes (unless callee has
3146 // always-inline attribute).
3147 if (!functionsHaveCompatibleAttributes(Opts, Caller, Callee, GetTLI))
3148 return InlineResult::failure("conflicting attributes");
3149
3150 // Flatten: inline all viable calls from flatten functions regardless of cost.
3151 // Checked before optnone so that flatten takes priority.
3152 if (Caller->hasFnAttribute(Attribute::Flatten)) {
3153 auto IsViable = isInlineViable(*Callee);
3154 if (IsViable.isSuccess())
3155 return InlineResult::success();
3156 return InlineResult::failure(IsViable.getFailureReason());
3157 }
3158
3159 // Don't inline this call if the caller has the optnone attribute.
3160 if (Caller->hasOptNone())
3161 return InlineResult::failure("optnone attribute");
3162
3163 // Don't inline functions which can be interposed at link-time.
3164 if (Callee->isInterposable(/*CheckNoIPA=*/false))
3165 return InlineResult::failure("interposable");
3166
3167 // Don't inline functions marked noinline.
3168 if (Callee->hasFnAttribute(Attribute::NoInline))
3169 return InlineResult::failure("noinline function attribute");
3170
3171 // Don't inline call sites marked noinline.
3172 if (Call.isNoInline())
3173 return InlineResult::failure("noinline call site attribute");
3174
3175 // Don't inline functions that are loader replaceable.
3176 if (Callee->hasFnAttribute("loader-replaceable"))
3177 return InlineResult::failure("loader replaceable function attribute");
3178
3179 return std::nullopt;
3180}
3181
3183 CallBase &Call, Function *Callee, const InlineParams &Params,
3184 TargetTransformInfo &CalleeTTI,
3185 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3186 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3189 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
3190
3191 auto UserDecision =
3192 llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
3193
3194 if (UserDecision) {
3195 if (UserDecision->isSuccess())
3196 return llvm::InlineCost::getAlways("always inline attribute");
3197 return llvm::InlineCost::getNever(UserDecision->getFailureReason());
3198 }
3199
3200 if (getAnalysisOptions(*Callee).inline_all_viable_calls &&
3201 isInlineViable(*Callee).isSuccess())
3203 "Inlining forced by -inline-all-viable-calls");
3204
3205 LLVM_DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
3206 << "... (caller:" << Call.getCaller()->getName()
3207 << ")\n");
3208
3209 // If requested, make the analysis independent of any profile information by
3210 // not providing the profile summary or block frequency info.
3211 const bool IgnoreProfile = Params.IgnoreProfile.value_or(false);
3212 function_ref<BlockFrequencyInfo &(Function &)> GetBFIForAnalysis =
3213 IgnoreProfile ? nullptr : GetBFI;
3214 InlineCostCallAnalyzer CA(
3215 *Callee, Call, Params, CalleeTTI, GetAssumptionCache, GetBFIForAnalysis,
3216 GetTLI, IgnoreProfile ? nullptr : PSI, ORE,
3217 /*BoostIndirect=*/true, /*IgnoreThreshold=*/false, GetEphValuesCache);
3218 InlineResult ShouldInline = CA.analyze();
3219
3220 LLVM_DEBUG(CA.dump());
3221
3222 // Always make cost benefit based decision explicit.
3223 // We use always/never here since threshold is not meaningful,
3224 // as it's not what drives cost-benefit analysis.
3225 if (CA.wasDecidedByCostBenefit()) {
3226 if (ShouldInline.isSuccess())
3227 return InlineCost::getAlways("benefit over cost",
3228 CA.getCostBenefitPair());
3229 else
3230 return InlineCost::getNever("cost over benefit", CA.getCostBenefitPair());
3231 }
3232
3233 if (CA.wasDecidedByCostThreshold())
3234 return InlineCost::get(CA.getCost(), CA.getThreshold(),
3235 CA.getStaticBonusApplied());
3236
3237 // No details on how the decision was made, simply return always or never.
3238 return ShouldInline.isSuccess()
3239 ? InlineCost::getAlways("empty function")
3240 : InlineCost::getNever(ShouldInline.getFailureReason());
3241}
3242
3244 bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
3245 for (BasicBlock &BB : F) {
3246 // Disallow inlining of functions which contain indirect branches.
3248 return InlineResult::failure("contains indirect branches");
3249
3250 // Disallow inlining of blockaddresses.
3251 if (BB.hasAddressTaken())
3252 return InlineResult::failure("blockaddress used");
3253
3254 for (auto &II : BB) {
3256 if (!Call)
3257 continue;
3258
3259 // Disallow recursive calls.
3260 Function *Callee = Call->getCalledFunction();
3261 if (&F == Callee)
3262 return InlineResult::failure("recursive call");
3263
3264 // Disallow calls which expose returns-twice to a function not previously
3265 // attributed as such.
3266 if (!ReturnsTwice && isa<CallInst>(Call) &&
3267 cast<CallInst>(Call)->canReturnTwice())
3268 return InlineResult::failure("exposes returns-twice attribute");
3269
3270 if (Callee)
3271 switch (Callee->getIntrinsicID()) {
3272 default:
3273 break;
3274 case llvm::Intrinsic::icall_branch_funnel:
3275 // Disallow inlining of @llvm.icall.branch.funnel because current
3276 // backend can't separate call targets from call arguments.
3277 return InlineResult::failure(
3278 "disallowed inlining of @llvm.icall.branch.funnel");
3279 case llvm::Intrinsic::localescape:
3280 // Disallow inlining functions that call @llvm.localescape. Doing this
3281 // correctly would require major changes to the inliner.
3282 return InlineResult::failure(
3283 "disallowed inlining of @llvm.localescape");
3284 case llvm::Intrinsic::vastart:
3285 // Disallow inlining of functions that initialize VarArgs with
3286 // va_start.
3287 return InlineResult::failure(
3288 "contains VarArgs initialized with va_start");
3289 }
3290 }
3291 }
3292
3293 return InlineResult::success();
3294}
3295
3296// APIs to create InlineParams based on command line flags and/or other
3297// parameters.
3298
3300 InlineParams Params;
3301
3302 // This field is the threshold to use for a callee by default. This is
3303 // derived from one or more of:
3304 // * optimization or size-optimization levels,
3305 // * a value passed to createFunctionInliningPass function, or
3306 // * the -inline-threshold flag.
3307 // If the -inline-threshold flag is explicitly specified, that is used
3308 // irrespective of anything else.
3309 if (InlineThreshold.getNumOccurrences() > 0)
3311 else
3312 Params.DefaultThreshold = Threshold;
3313
3314 // Set the HintThreshold knob from the -inlinehint-threshold.
3316 // Use same threshold for optsize by default.
3318
3319 // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
3321
3322 // If the -locally-hot-callsite-threshold is explicitly specified, use it to
3323 // populate LocallyHotCallSiteThreshold. Later, we populate
3324 // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
3325 // we know that optimization level is O3 (in the getInlineParams variant that
3326 // takes the opt and size levels).
3327 // FIXME: Remove this check (and make the assignment unconditional) after
3328 // addressing size regression issues at O2.
3329 if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
3331
3332 // Set the ColdCallSiteThreshold knob from the
3333 // -inline-cold-callsite-threshold.
3335
3336 // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
3337 // -inlinehint-threshold commandline option is not explicitly given. If that
3338 // option is present, then its value applies even for callees with size and
3339 // minsize attributes.
3340 // If the -inline-threshold is not specified, set the ColdThreshold from the
3341 // -inlinecold-threshold even if it is not explicitly passed. If
3342 // -inline-threshold is specified, then -inlinecold-threshold needs to be
3343 // explicitly specified to set the ColdThreshold knob
3344 if (InlineThreshold.getNumOccurrences() == 0) {
3348 } else if (ColdThreshold.getNumOccurrences() > 0) {
3350 }
3351 return Params;
3352}
3353
3357
3359 auto Params =
3362 // At O3, use the value of -locally-hot-callsite-threshold option to populate
3363 // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
3364 // when it is specified explicitly.
3365 if (OptLevel > 2)
3367 return Params;
3368}
3369
3373 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
3374 [&](Function &F) -> AssumptionCache & {
3375 return FAM.getResult<AssumptionAnalysis>(F);
3376 };
3377
3378 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
3379 ProfileSummaryInfo *PSI =
3380 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3381 const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
3382
3383 // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
3384 // In the current implementation, the type of InlineParams doesn't matter as
3385 // the pass serves only for verification of inliner's decisions.
3386 // We can add a flag which determines InlineParams for this run. Right now,
3387 // the default InlineParams are used.
3388 const InlineParams Params = llvm::getInlineParams();
3389 for (BasicBlock &BB : F) {
3390 for (Instruction &I : BB) {
3391 if (auto *CB = dyn_cast<CallBase>(&I)) {
3392 Function *CalledFunction = CB->getCalledFunction();
3393 if (!CalledFunction || CalledFunction->isDeclaration())
3394 continue;
3395 OptimizationRemarkEmitter ORE(CalledFunction);
3396 InlineCostCallAnalyzer ICCA(*CalledFunction, *CB, Params, TTI,
3397 GetAssumptionCache, nullptr, nullptr, PSI,
3398 &ORE, /*BoostIndirect=*/true,
3399 /*IgnoreThreshold=*/false,
3400 /*GetEphValuesCache=*/nullptr,
3401 /*PrintInstructionComments=*/true);
3402 ICCA.analyze();
3403 OS << " Analyzing call of " << CalledFunction->getName()
3404 << "... (caller:" << CB->getCaller()->getName() << ")\n";
3405 ICCA.print(OS);
3406 OS << "\n";
3407 }
3408 }
3409 }
3410 return PreservedAnalyses::all();
3411}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:690
static InstructionCost getCost(const AnalysisOptions &Opts, Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:33
static Value * accumulateGEPOffset(GetElementPtrInst *GEP, IRBuilder<> &Builder)
#define DEBUG_TYPE
static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI)
Return true if the block containing the call site has a BlockFrequency of less than ColdCCRelFreq% of...
Hexagon Common GEP
static bool IsIndirectCall(const MachineInstr *MI)
static cl::opt< int > InlineThreshold("inline-threshold", cl::Hidden, cl::init(225), cl::desc("Control the amount of inlining to perform (default = 225)"))
static cl::opt< int > HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000), cl::desc("Threshold for hot callsites "))
static bool functionsHaveCompatibleAttributes(const AnalysisOptions &Opts, Function *Caller, Function *Callee, function_ref< const TargetLibraryInfo &(Function &)> &GetTLI)
Test that there are no attribute conflicts between Caller and Callee that prevent inlining.
static cl::opt< int > ColdThreshold("inlinecold-threshold", cl::Hidden, cl::init(45), cl::desc("Threshold for inlining functions with cold attribute"))
static cl::opt< int > LocallyHotCallSiteThreshold("locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::desc("Threshold for locally hot callsites "))
static cl::opt< int > HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325), cl::desc("Threshold for inlining functions with inline hint"))
static cl::opt< int > ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden, cl::init(45), cl::desc("Threshold for inlining cold callsites"))
#define DEBUG_PRINT_STAT(x)
static cl::opt< int > InstrCost("inline-instr-cost", cl::Hidden, cl::init(5), cl::desc("Cost of a single instruction when inlining"))
static cl::opt< int > DefaultThreshold("inlinedefault-threshold", cl::Hidden, cl::init(225), cl::desc("Default amount of inlining to perform"))
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
SmallVector< MachineOperand, 4 > Cond
RISCVCC::CondCode CC
SI Fold Operands
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static bool paramHasAttr(const CallBase &Call, unsigned ArgIdx, Attribute::AttrKind Kind)
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
PointerType * getType() const
Overload to return most specific pointer type.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:262
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool empty() const
Definition BasicBlock.h:462
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
LLVM_ABI BlockFrequency getEntryFreq() const
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
LLVM_ABI std::optional< BlockFrequency > mul(uint64_t Factor) const
Multiplies frequency with Factor. Returns nullopt in case of overflow.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Attribute getFnAttr(StringRef Kind) const
Get the attribute of a given kind for the function.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:62
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
A cache of ephemeral values within a function.
Type * getReturnType() const
const BasicBlock & getEntryBlock() const
Definition Function.h:794
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
LLVM_ABI void collectAsmStrs(SmallVectorImpl< StringRef > &AsmStrs) const
Definition InlineAsm.cpp:63
Represents the cost of inlining a function.
Definition InlineCost.h:91
static InlineCost getNever(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:132
static InlineCost getAlways(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:127
static InlineCost get(int Cost, int Threshold, int StaticBonus=0)
Definition InlineCost.h:121
InlineResult is basically true or false.
Definition InlineCost.h:181
static InlineResult success()
Definition InlineCost.h:186
static InlineResult failure(const char *Reason)
Definition InlineCost.h:187
bool isSuccess() const
Definition InlineCost.h:190
const char * getFailureReason() const
Definition InlineCost.h:191
Base class for instruction visitors.
Definition InstVisitor.h:78
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
void analyze(ParentT F)
Create the loop forest for a function.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Class to represent pointers.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
size_type size() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void reserve(size_type N)
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Analysis pass providing the TargetTransformInfo.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI unsigned getInlineCallPenalty(const Function *F, const CallBase &Call, unsigned DefaultCallPenalty) const
Returns a penalty for invoking call Call in F.
LLVM_ABI unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const
LLVM_ABI unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI int getInliningLastCallToStaticBonus() const
LLVM_ABI unsigned adjustInliningThreshold(const CallBase *CB) const
LLVM_ABI unsigned getCallerAllocaCost(const CallBase *CB, const AllocaInst *AI) const
LLVM_ABI int getInlinerVectorBonusPercent() const
LLVM_ABI bool isLoweredToCall(const Function *F) const
Test whether calls to a function lower to actual program function calls.
LLVM_ABI unsigned getInliningThresholdMultiplier() const
@ TCC_Expensive
The cost of a 'div' instruction on x86.
@ TCC_Free
Expected to fold away in lowering.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const
LLVM_ABI bool areInlineCompatible(const Function *Caller, const Function *Callee) const
LLVM_ABI InstructionCost getFPOpCost(Type *Ty) const
Return the expected cost of supporting the floating point operation of the specified type.
static constexpr TypeSize getZero()
Definition TypeSize.h:358
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool erase(const ValueT &V)
Definition DenseSet.h:97
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
const int ColdccPenalty
Definition InlineCost.h:52
const char FunctionInlineCostMultiplierAttributeName[]
Definition InlineCost.h:60
const int OptSizeThreshold
Use when optsize (-Os) is specified.
Definition InlineCost.h:40
const int OptMinSizeThreshold
Use when minsize (-Oz) is specified.
Definition InlineCost.h:43
const uint64_t MaxSimplifiedDynamicAllocaToInline
Do not inline dynamic allocas that have been constant propagated to be static allocas above this amou...
Definition InlineCost.h:58
const int IndirectCallThreshold
Definition InlineCost.h:50
const int OptAggressiveThreshold
Use when -O3 is specified.
Definition InlineCost.h:46
const char MaxInlineStackSizeAttributeName[]
Definition InlineCost.h:63
LLVM_ABI int getInstrCost()
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
InstructionCost Cost
@ Dead
Unused definition.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::optional< int > getStringFnAttrAsInt(CallBase &CB, StringRef AttrKind)
auto successors(const MachineBasicBlock *BB)
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
LLVM_ABI Value * simplifyInstructionWithOperands(Instruction *I, ArrayRef< Value * > NewOps, const SimplifyQuery &Q)
Like simplifyInstruction but the operands of I are replaced with NewOps.
LogicalResult failure(bool IsFailure=true)
Utility function to generate a LogicalResult.
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI InlineResult isInlineViable(Function &Callee)
Check if it is mechanically possible to inline the function Callee, based on the contents of the func...
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI Value * simplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q)
Given operand for an FNeg, fold the result or return null.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
generic_gep_type_iterator<> gep_type_iterator
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:684
LLVM_ABI std::optional< InlineCostFeatures > getInliningCostFeatures(CallBase &Call, TargetTransformInfo &CalleeTTI, 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.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, 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.
TargetTransformInfo TTI
LLVM_ABI std::optional< InlineResult > getAttributeBasedInliningDecision(CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI, function_ref< const TargetLibraryInfo &(Function &)> GetTLI)
Returns InlineResult::success() if the call site should be always inlined because of user directives,...
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
DWARFExpression::Operation Op
LLVM_ABI InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
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...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::optional< int > getInliningCostEstimate(CallBase &Call, TargetTransformInfo &CalleeTTI, 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.
auto predecessors(const MachineBasicBlock *BB)
constexpr bool valueOr(BoolOrDefault X, bool Default)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
LLVM_ABI InlineParams getInlineParamsFromOptLevel(unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:609
constexpr bool isCallableCC(CallingConv::ID CC)
std::array< int, static_cast< size_t >(InlineCostFeatureIndex::NumberOfFeatures)> InlineCostFeatures
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
Thresholds to tune inline cost analysis.
Definition InlineCost.h:207
std::optional< int > OptMinSizeThreshold
Threshold to use when the caller is optimized for minsize.
Definition InlineCost.h:225
std::optional< int > OptSizeThreshold
Threshold to use when the caller is optimized for size.
Definition InlineCost.h:222
std::optional< int > OptSizeHintThreshold
Threshold to use for callees with inline hint, when the caller is optimized for size.
Definition InlineCost.h:216
std::optional< int > ColdCallSiteThreshold
Threshold to use when the callsite is considered cold.
Definition InlineCost.h:235
std::optional< int > ColdThreshold
Threshold to use for cold callees.
Definition InlineCost.h:219
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition InlineCost.h:228
std::optional< bool > IgnoreProfile
Indicate whether to ignore profile information.
Definition InlineCost.h:249
int DefaultThreshold
The default threshold to start with for a callee.
Definition InlineCost.h:209
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition InlineCost.h:212
std::optional< int > LocallyHotCallSiteThreshold
Threshold to use when the callsite is considered hot relative to function entry.
Definition InlineCost.h:232