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.
1161//
1162// A linkonce_odr function marked likely_module_local counts as local too: no
1163// other module is expected to reference it, so we expect inlining the sole call
1164// to turn the original dead.
1165static bool isSoleCallToLocalFunction(const CallBase &CB,
1166 const Function &Callee) {
1167 bool Local = Callee.hasLocalLinkage() ||
1168 (Callee.hasLinkOnceODRLinkage() &&
1169 Callee.hasFnAttribute(Attribute::LikelyModuleLocal));
1170 return Local && Callee.hasOneLiveUse() && &Callee == CB.getCalledFunction();
1171}
1172
1173class InlineCostFeaturesAnalyzer final : public CallAnalyzer {
1174private:
1175 InlineCostFeatures Cost = {};
1176
1177 // FIXME: These constants are taken from the heuristic-based cost visitor.
1178 // These should be removed entirely in a later revision to avoid reliance on
1179 // heuristics in the ML inliner.
1180 static constexpr int JTCostMultiplier = 2;
1181 static constexpr int CaseClusterCostMultiplier = 2;
1182 static constexpr int SwitchDefaultDestCostMultiplier = 2;
1183 static constexpr int SwitchCostMultiplier = 2;
1184
1185 // FIXME: These are taken from the heuristic-based cost visitor: we should
1186 // eventually abstract these to the CallAnalyzer to avoid duplication.
1187 unsigned SROACostSavingOpportunities = 0;
1188 int VectorBonus = 0;
1189 int SingleBBBonus = 0;
1190 int Threshold = 5;
1191
1192 DenseMap<AllocaInst *, unsigned> SROACosts;
1193
1194 void increment(InlineCostFeatureIndex Feature, int64_t Delta = 1) {
1195 Cost[static_cast<size_t>(Feature)] += Delta;
1196 }
1197
1198 void set(InlineCostFeatureIndex Feature, int64_t Value) {
1199 Cost[static_cast<size_t>(Feature)] = Value;
1200 }
1201
1202 void onDisableSROA(AllocaInst *Arg) override {
1203 auto CostIt = SROACosts.find(Arg);
1204 if (CostIt == SROACosts.end())
1205 return;
1206
1207 increment(InlineCostFeatureIndex::sroa_losses, CostIt->second);
1208 SROACostSavingOpportunities -= CostIt->second;
1209 SROACosts.erase(CostIt);
1210 }
1211
1212 void onDisableLoadElimination() override {
1213 set(InlineCostFeatureIndex::load_elimination, 1);
1214 }
1215
1216 void onCallPenalty() override {
1217 increment(InlineCostFeatureIndex::call_penalty, Opts.inline_call_penalty);
1218 }
1219
1220 void onCallArgumentSetup(const CallBase &Call) override {
1221 increment(InlineCostFeatureIndex::call_argument_setup,
1222 Call.arg_size() * InstrCost);
1223 }
1224
1225 void onLoadRelativeIntrinsic() override {
1226 increment(InlineCostFeatureIndex::load_relative_intrinsic, 3 * InstrCost);
1227 }
1228
1229 void onLoweredCall(Function *F, CallBase &Call,
1230 bool IsIndirectCall) override {
1231 increment(InlineCostFeatureIndex::lowered_call_arg_setup,
1232 Call.arg_size() * InstrCost);
1233
1234 if (IsIndirectCall) {
1235 InlineParams IndirectCallParams = {/* DefaultThreshold*/ 0,
1236 /*HintThreshold*/ {},
1237 /*OptSizeHintThreshold*/ {},
1238 /*ColdThreshold*/ {},
1239 /*OptSizeThreshold*/ {},
1240 /*OptMinSizeThreshold*/ {},
1241 /*HotCallSiteThreshold*/ {},
1242 /*LocallyHotCallSiteThreshold*/ {},
1243 /*ColdCallSiteThreshold*/ {},
1244 /*ComputeFullInlineCost*/ true,
1245 /*EnableDeferral*/ true};
1246 IndirectCallParams.DefaultThreshold =
1248
1249 InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
1250 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE,
1251 false, true);
1252 if (CA.analyze().isSuccess()) {
1253 increment(InlineCostFeatureIndex::nested_inline_cost_estimate,
1254 CA.getCost());
1255 increment(InlineCostFeatureIndex::nested_inlines, 1);
1256 }
1257 } else {
1258 onCallPenalty();
1259 }
1260 }
1261
1262 void onFinalizeSwitch(unsigned JumpTableSize, unsigned NumCaseCluster,
1263 bool DefaultDestUnreachable) override {
1264 if (JumpTableSize) {
1265 if (!DefaultDestUnreachable)
1266 increment(InlineCostFeatureIndex::switch_default_dest_penalty,
1267 SwitchDefaultDestCostMultiplier * InstrCost);
1268 int64_t JTCost = static_cast<int64_t>(JumpTableSize) * InstrCost +
1269 JTCostMultiplier * InstrCost;
1270 increment(InlineCostFeatureIndex::jump_table_penalty, JTCost);
1271 return;
1272 }
1273
1274 if (NumCaseCluster <= 3) {
1275 increment(InlineCostFeatureIndex::case_cluster_penalty,
1276 (NumCaseCluster - DefaultDestUnreachable) *
1277 CaseClusterCostMultiplier * InstrCost);
1278 return;
1279 }
1280
1281 int64_t ExpectedNumberOfCompare =
1282 getExpectedNumberOfCompare(NumCaseCluster);
1283
1284 int64_t SwitchCost =
1285 ExpectedNumberOfCompare * SwitchCostMultiplier * InstrCost;
1286 increment(InlineCostFeatureIndex::switch_penalty, SwitchCost);
1287 }
1288
1289 void onMissedSimplification() override {
1290 increment(InlineCostFeatureIndex::unsimplified_common_instructions,
1291 InstrCost);
1292 }
1293
1294 void onInitializeSROAArg(AllocaInst *Arg) override {
1295 auto SROAArgCost = TTI.getCallerAllocaCost(&CandidateCall, Arg);
1296 SROACosts[Arg] = SROAArgCost;
1297 SROACostSavingOpportunities += SROAArgCost;
1298 }
1299
1300 void onAggregateSROAUse(AllocaInst *Arg) override {
1301 SROACosts.find(Arg)->second += InstrCost;
1302 SROACostSavingOpportunities += InstrCost;
1303 }
1304
1305 void onBlockAnalyzed(const BasicBlock *BB) override {
1306 if (BB->getTerminator()->getNumSuccessors() > 1)
1307 set(InlineCostFeatureIndex::is_multiple_blocks, 1);
1308 Threshold -= SingleBBBonus;
1309 }
1310
1311 InlineResult finalizeAnalysis() override {
1312 auto *Caller = CandidateCall.getFunction();
1313 if (Caller->hasMinSize()) {
1314 LoopInfo LI;
1315 LI.analyze(&F);
1316 for (Loop *L : LI) {
1317 // Ignore loops that will not be executed
1318 if (DeadBlocks.count(L->getHeader()))
1319 continue;
1320 increment(InlineCostFeatureIndex::num_loops,
1322 }
1323 }
1324 set(InlineCostFeatureIndex::dead_blocks, DeadBlocks.size());
1325 set(InlineCostFeatureIndex::simplified_instructions,
1326 NumInstructionsSimplified);
1327 set(InlineCostFeatureIndex::constant_args, NumConstantArgs);
1328 set(InlineCostFeatureIndex::constant_offset_ptr_args,
1329 NumConstantOffsetPtrArgs);
1330 set(InlineCostFeatureIndex::sroa_savings, SROACostSavingOpportunities);
1331
1332 if (NumVectorInstructions <= NumInstructions / 10)
1333 Threshold -= VectorBonus;
1334 else if (NumVectorInstructions <= NumInstructions / 2)
1335 Threshold -= VectorBonus / 2;
1336
1337 set(InlineCostFeatureIndex::threshold, Threshold);
1338
1339 return InlineResult::success();
1340 }
1341
1342 bool shouldStop() override { return false; }
1343
1344 void onLoadEliminationOpportunity() override {
1345 increment(InlineCostFeatureIndex::load_elimination, 1);
1346 }
1347
1348 InlineResult onAnalysisStart() override {
1349 increment(InlineCostFeatureIndex::callsite_cost,
1350 -1 * getCallsiteCost(TTI, this->CandidateCall, DL));
1351
1352 set(InlineCostFeatureIndex::cold_cc_penalty,
1353 (F.getCallingConv() == CallingConv::Cold));
1354
1355 set(InlineCostFeatureIndex::last_call_to_static_bonus,
1356 isSoleCallToLocalFunction(CandidateCall, F));
1357
1358 // FIXME: we shouldn't repeat this logic in both the Features and Cost
1359 // analyzer - instead, we should abstract it to a common method in the
1360 // CallAnalyzer
1361 int SingleBBBonusPercent = 50;
1362 int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
1363 Threshold += TTI.adjustInliningThreshold(&CandidateCall);
1364 Threshold *= TTI.getInliningThresholdMultiplier();
1365 SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
1366 VectorBonus = Threshold * VectorBonusPercent / 100;
1367 Threshold += (SingleBBBonus + VectorBonus);
1368
1369 return InlineResult::success();
1370 }
1371
1372public:
1373 InlineCostFeaturesAnalyzer(
1374 const TargetTransformInfo &TTI,
1375 function_ref<AssumptionCache &(Function &)> &GetAssumptionCache,
1376 function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
1377 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
1378 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee,
1379 CallBase &Call)
1380 : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, GetTLI,
1381 PSI) {}
1382
1383 const InlineCostFeatures &features() const { return Cost; }
1384};
1385
1386} // namespace
1387
1388/// Test whether the given value is an Alloca-derived function argument.
1389bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
1390 return SROAArgValues.count(V);
1391}
1392
1393void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
1394 onDisableSROA(SROAArg);
1395 EnabledSROAAllocas.erase(SROAArg);
1396 disableLoadElimination();
1397}
1398
1399void InlineCostAnnotationWriter::emitInstructionAnnot(
1400 const Instruction *I, formatted_raw_ostream &OS) {
1401 // The cost of inlining of the given instruction is printed always.
1402 // The threshold delta is printed only when it is non-zero. It happens
1403 // when we decided to give a bonus at a particular instruction.
1404 std::optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
1405 if (!Record)
1406 OS << "; No analysis for the instruction";
1407 else {
1408 OS << "; cost before = " << Record->CostBefore
1409 << ", cost after = " << Record->CostAfter
1410 << ", threshold before = " << Record->ThresholdBefore
1411 << ", threshold after = " << Record->ThresholdAfter << ", ";
1412 OS << "cost delta = " << Record->getCostDelta();
1413 if (Record->hasThresholdChanged())
1414 OS << ", threshold delta = " << Record->getThresholdDelta();
1415 }
1416 auto *V = ICCA->getSimplifiedValueUnchecked(const_cast<Instruction *>(I));
1417 if (V) {
1418 OS << ", simplified to ";
1419 V->print(OS, true);
1420 if (auto *VI = dyn_cast<Instruction>(V)) {
1421 if (VI->getFunction() != I->getFunction())
1422 OS << " (caller instruction)";
1423 } else if (auto *VArg = dyn_cast<Argument>(V)) {
1424 if (VArg->getParent() != I->getFunction())
1425 OS << " (caller argument)";
1426 }
1427 }
1428 OS << "\n";
1429}
1430
1431/// If 'V' maps to a SROA candidate, disable SROA for it.
1432void CallAnalyzer::disableSROA(Value *V) {
1433 if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
1434 disableSROAForArg(SROAArg);
1435 }
1436}
1437
1438void CallAnalyzer::disableLoadElimination() {
1439 if (EnableLoadElimination) {
1440 onDisableLoadElimination();
1441 EnableLoadElimination = false;
1442 }
1443}
1444
1445/// Accumulate a constant GEP offset into an APInt if possible.
1446///
1447/// Returns false if unable to compute the offset for any reason. Respects any
1448/// simplified values known during the analysis of this callsite.
1449bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
1450 unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
1451 assert(IntPtrWidth == Offset.getBitWidth());
1452
1454 GTI != GTE; ++GTI) {
1455 ConstantInt *OpC =
1456 getDirectOrSimplifiedValue<ConstantInt>(GTI.getOperand());
1457 if (!OpC)
1458 return false;
1459 if (OpC->isZero())
1460 continue;
1461
1462 // Handle a struct index, which adds its field offset to the pointer.
1463 if (StructType *STy = GTI.getStructTypeOrNull()) {
1464 unsigned ElementIdx = OpC->getZExtValue();
1465 const StructLayout *SL = DL.getStructLayout(STy);
1466 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
1467 continue;
1468 }
1469
1470 APInt TypeSize(IntPtrWidth, GTI.getSequentialElementStride(DL));
1471 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
1472 }
1473 return true;
1474}
1475
1476/// Use TTI to check whether a GEP is free.
1477///
1478/// Respects any simplified values known during the analysis of this callsite.
1479bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
1480 SmallVector<Value *, 4> Operands;
1481 Operands.push_back(GEP.getOperand(0));
1482 for (const Use &Op : GEP.indices())
1483 if (Constant *SimpleOp = getSimplifiedValue<Constant>(Op))
1484 Operands.push_back(SimpleOp);
1485 else
1486 Operands.push_back(Op);
1490}
1491
1492bool CallAnalyzer::visitAlloca(AllocaInst &I) {
1493 disableSROA(I.getOperand(0));
1494
1495 // Check whether inlining will turn a dynamic alloca into a static
1496 // alloca and handle that case.
1497 if (I.isArrayAllocation()) {
1498 Constant *Size = getSimplifiedValue<Constant>(I.getArraySize());
1499 if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
1500 // Sometimes a dynamic alloca could be converted into a static alloca
1501 // after this constant prop, and become a huge static alloca on an
1502 // unconditional CFG path. Avoid inlining if this is going to happen above
1503 // a threshold.
1504 // FIXME: If the threshold is removed or lowered too much, we could end up
1505 // being too pessimistic and prevent inlining non-problematic code. This
1506 // could result in unintended perf regressions. A better overall strategy
1507 // is needed to track stack usage during inlining.
1508 AllocatedSize = SaturatingMultiplyAdd(
1509 AllocSize->getLimitedValue(),
1510 I.getAllocationBaseSize(DL).getKnownMinValue(), AllocatedSize);
1512 HasDynamicAlloca = true;
1513 return false;
1514 }
1515 }
1516
1517 if (I.isStaticAlloca()) {
1518 // Accumulate the allocated size if constant and executed once.
1519 // Note: if AllocSize is a vscale value, this is an underestimate of the
1520 // allocated size, and it also requires some of the cost of a dynamic
1521 // alloca, but is recorded here as a constant size alloca.
1522 TypeSize AllocSize = I.getAllocationSize(DL).value_or(TypeSize::getZero());
1523 AllocatedSize = SaturatingAdd(AllocSize.getKnownMinValue(), AllocatedSize);
1524 } else {
1525 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
1526 // a variety of reasons, and so we would like to not inline them into
1527 // functions which don't currently have a dynamic alloca. This simply
1528 // disables inlining altogether in the presence of a dynamic alloca.
1529 HasDynamicAlloca = true;
1530 }
1531
1532 return false;
1533}
1534
1535bool CallAnalyzer::visitPHI(PHINode &I) {
1536 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
1537 // though we don't want to propagate it's bonuses. The idea is to disable
1538 // SROA if it *might* be used in an inappropriate manner.
1539
1540 // Phi nodes are always zero-cost.
1541 // FIXME: Pointer sizes may differ between different address spaces, so do we
1542 // need to use correct address space in the call to getPointerSizeInBits here?
1543 // Or could we skip the getPointerSizeInBits call completely? As far as I can
1544 // see the ZeroOffset is used as a dummy value, so we can probably use any
1545 // bit width for the ZeroOffset?
1546 APInt ZeroOffset = APInt::getZero(DL.getPointerSizeInBits(0));
1547 bool CheckSROA = I.getType()->isPointerTy();
1548
1549 // Track the constant or pointer with constant offset we've seen so far.
1550 Constant *FirstC = nullptr;
1551 std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
1552 Value *FirstV = nullptr;
1553
1554 for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
1555 BasicBlock *Pred = I.getIncomingBlock(i);
1556 // If the incoming block is dead, skip the incoming block.
1557 if (DeadBlocks.count(Pred))
1558 continue;
1559 // If the parent block of phi is not the known successor of the incoming
1560 // block, skip the incoming block.
1561 BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
1562 if (KnownSuccessor && KnownSuccessor != I.getParent())
1563 continue;
1564
1565 Value *V = I.getIncomingValue(i);
1566 // If the incoming value is this phi itself, skip the incoming value.
1567 if (&I == V)
1568 continue;
1569
1570 Constant *C = getDirectOrSimplifiedValue<Constant>(V);
1571
1572 std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
1573 if (!C && CheckSROA)
1574 BaseAndOffset = ConstantOffsetPtrs.lookup(V);
1575
1576 if (!C && !BaseAndOffset.first)
1577 // The incoming value is neither a constant nor a pointer with constant
1578 // offset, exit early.
1579 return true;
1580
1581 if (FirstC) {
1582 if (FirstC == C)
1583 // If we've seen a constant incoming value before and it is the same
1584 // constant we see this time, continue checking the next incoming value.
1585 continue;
1586 // Otherwise early exit because we either see a different constant or saw
1587 // a constant before but we have a pointer with constant offset this time.
1588 return true;
1589 }
1590
1591 if (FirstV) {
1592 // The same logic as above, but check pointer with constant offset here.
1593 if (FirstBaseAndOffset == BaseAndOffset)
1594 continue;
1595 return true;
1596 }
1597
1598 if (C) {
1599 // This is the 1st time we've seen a constant, record it.
1600 FirstC = C;
1601 continue;
1602 }
1603
1604 // The remaining case is that this is the 1st time we've seen a pointer with
1605 // constant offset, record it.
1606 FirstV = V;
1607 FirstBaseAndOffset = BaseAndOffset;
1608 }
1609
1610 // Check if we can map phi to a constant.
1611 if (FirstC) {
1612 SimplifiedValues[&I] = FirstC;
1613 return true;
1614 }
1615
1616 // Check if we can map phi to a pointer with constant offset.
1617 if (FirstBaseAndOffset.first) {
1618 ConstantOffsetPtrs[&I] = std::move(FirstBaseAndOffset);
1619
1620 if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
1621 SROAArgValues[&I] = SROAArg;
1622 }
1623
1624 return true;
1625}
1626
1627/// Check we can fold GEPs of constant-offset call site argument pointers.
1628/// This requires target data and inbounds GEPs.
1629///
1630/// \return true if the specified GEP can be folded.
1631bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
1632 // Check if we have a base + offset for the pointer.
1633 std::pair<Value *, APInt> BaseAndOffset =
1634 ConstantOffsetPtrs.lookup(I.getPointerOperand());
1635 if (!BaseAndOffset.first)
1636 return false;
1637
1638 // Check if the offset of this GEP is constant, and if so accumulate it
1639 // into Offset.
1640 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1641 return false;
1642
1643 // Add the result as a new mapping to Base + Offset.
1644 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1645
1646 return true;
1647}
1648
1649bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
1650 auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
1651
1652 // Lambda to check whether a GEP's indices are all constant.
1653 auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
1654 for (const Use &Op : GEP.indices())
1655 if (!getDirectOrSimplifiedValue<Constant>(Op))
1656 return false;
1657 return true;
1658 };
1659
1660 if (Opts.gep_const_evaluation)
1662 return true;
1663
1664 if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
1665 if (SROAArg)
1666 SROAArgValues[&I] = SROAArg;
1667
1668 // Constant GEPs are modeled as free.
1669 return true;
1670 }
1671
1672 // Variable GEPs will require math and will disable SROA.
1673 if (SROAArg)
1674 disableSROAForArg(SROAArg);
1675 return isGEPFree(I);
1676}
1677
1678// Simplify \p Cmp if RHS is const and we can ValueTrack LHS.
1679// This handles the case only when the Cmp instruction is guarding a recursive
1680// call that will cause the Cmp to fail/succeed for the recursive call.
1681bool CallAnalyzer::simplifyCmpInstForRecCall(CmpInst &Cmp) {
1682 // Bail out if LHS is not a function argument or RHS is NOT const:
1683 if (!isa<Argument>(Cmp.getOperand(0)) || !isa<Constant>(Cmp.getOperand(1)))
1684 return false;
1685 auto *CmpOp = Cmp.getOperand(0);
1686 // Make sure that the callsite is recursive:
1687 if (CandidateCall.getCaller() != &F)
1688 return false;
1689 // Only handle the case when the callsite has a single predecessor:
1690 auto *CallBB = CandidateCall.getParent();
1691 auto *Predecessor = CallBB->getSinglePredecessor();
1692 if (!Predecessor)
1693 return false;
1694 // Check if the callsite is guarded by the same Cmp instruction:
1695 auto *Br = dyn_cast<CondBrInst>(Predecessor->getTerminator());
1696 if (!Br || Br->getCondition() != &Cmp)
1697 return false;
1698
1699 // Check if there is any arg of the recursive callsite is affecting the cmp
1700 // instr:
1701 bool ArgFound = false;
1702 Value *FuncArg = nullptr, *CallArg = nullptr;
1703 for (unsigned ArgNum = 0;
1704 ArgNum < F.arg_size() && ArgNum < CandidateCall.arg_size(); ArgNum++) {
1705 FuncArg = F.getArg(ArgNum);
1706 CallArg = CandidateCall.getArgOperand(ArgNum);
1707 if (FuncArg == CmpOp && CallArg != CmpOp) {
1708 ArgFound = true;
1709 break;
1710 }
1711 }
1712 if (!ArgFound)
1713 return false;
1714
1715 // Now we have a recursive call that is guarded by a cmp instruction.
1716 // Check if this cmp can be simplified:
1717 SimplifyQuery SQ(DL, dyn_cast<Instruction>(CallArg));
1718 CondContext CC(&Cmp);
1719 CC.Invert = (CallBB != Br->getSuccessor(0));
1720 SQ.CC = &CC;
1721 CC.AffectedValues.insert(FuncArg);
1722 Value *SimplifiedInstruction = llvm::simplifyInstructionWithOperands(
1723 cast<CmpInst>(&Cmp), {CallArg, Cmp.getOperand(1)}, SQ);
1724 if (auto *ConstVal = dyn_cast_or_null<ConstantInt>(SimplifiedInstruction)) {
1725 // Make sure that the BB of the recursive call is NOT the true successor
1726 // of the icmp. In other words, make sure that the recursion depth is 1.
1727 if ((ConstVal->isOne() && CC.Invert) ||
1728 (ConstVal->isZero() && !CC.Invert)) {
1729 SimplifiedValues[&Cmp] = ConstVal;
1730 return true;
1731 }
1732 }
1733 return false;
1734}
1735
1736/// Simplify \p I if its operands are constants and update SimplifiedValues.
1737bool CallAnalyzer::simplifyInstruction(Instruction &I) {
1739 for (Value *Op : I.operands()) {
1740 Constant *COp = getDirectOrSimplifiedValue<Constant>(Op);
1741 if (!COp)
1742 return false;
1743 COps.push_back(COp);
1744 }
1745 auto *C = ConstantFoldInstOperands(&I, COps, DL);
1746 if (!C)
1747 return false;
1748 SimplifiedValues[&I] = C;
1749 return true;
1750}
1751
1752/// Try to simplify a call to llvm.is.constant.
1753///
1754/// Duplicate the argument checking from CallAnalyzer::simplifyCallSite since
1755/// we expect calls of this specific intrinsic to be infrequent.
1756///
1757/// FIXME: Given that we know CB's parent (F) caller
1758/// (CandidateCall->getParent()->getParent()), we might be able to determine
1759/// whether inlining F into F's caller would change how the call to
1760/// llvm.is.constant would evaluate.
1761bool CallAnalyzer::simplifyIntrinsicCallIsConstant(CallBase &CB) {
1762 Value *Arg = CB.getArgOperand(0);
1763 auto *C = getDirectOrSimplifiedValue<Constant>(Arg);
1764
1765 Type *RT = CB.getFunctionType()->getReturnType();
1766 SimplifiedValues[&CB] = ConstantInt::get(RT, C ? 1 : 0);
1767 return true;
1768}
1769
1770bool CallAnalyzer::simplifyIntrinsicCallObjectSize(CallBase &CB) {
1771 // As per the langref, "The fourth argument to llvm.objectsize determines if
1772 // the value should be evaluated at runtime."
1773 if (cast<ConstantInt>(CB.getArgOperand(3))->isOne())
1774 return false;
1775
1777 /*MustSucceed=*/true);
1779 if (C)
1780 SimplifiedValues[&CB] = C;
1781 return C;
1782}
1783
1784bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1785 // Propagate constants through bitcasts.
1787 return true;
1788
1789 // Track base/offsets through casts
1790 std::pair<Value *, APInt> BaseAndOffset =
1791 ConstantOffsetPtrs.lookup(I.getOperand(0));
1792 // Casts don't change the offset, just wrap it up.
1793 if (BaseAndOffset.first)
1794 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1795
1796 // Also look for SROA candidates here.
1797 if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
1798 SROAArgValues[&I] = SROAArg;
1799
1800 // Bitcasts are always zero cost.
1801 return true;
1802}
1803
1804bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
1805 // Propagate constants through ptrtoint.
1807 return true;
1808
1809 // Track base/offset pairs when converted to a plain integer provided the
1810 // integer is large enough to represent the pointer.
1811 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
1812 unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1813 if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1814 std::pair<Value *, APInt> BaseAndOffset =
1815 ConstantOffsetPtrs.lookup(I.getOperand(0));
1816 if (BaseAndOffset.first)
1817 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1818 }
1819
1820 // This is really weird. Technically, ptrtoint will disable SROA. However,
1821 // unless that ptrtoint is *used* somewhere in the live basic blocks after
1822 // inlining, it will be nuked, and SROA should proceed. All of the uses which
1823 // would block SROA would also block SROA if applied directly to a pointer,
1824 // and so we can just add the integer in here. The only places where SROA is
1825 // preserved either cannot fire on an integer, or won't in-and-of themselves
1826 // disable SROA (ext) w/o some later use that we would see and disable.
1827 if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
1828 SROAArgValues[&I] = SROAArg;
1829
1832}
1833
1834bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
1835 // Propagate constants through ptrtoint.
1837 return true;
1838
1839 // Track base/offset pairs when round-tripped through a pointer without
1840 // modifications provided the integer is not too large.
1841 Value *Op = I.getOperand(0);
1842 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
1843 if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
1844 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
1845 if (BaseAndOffset.first)
1846 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1847 }
1848
1849 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
1850 if (auto *SROAArg = getSROAArgForValueOrNull(Op))
1851 SROAArgValues[&I] = SROAArg;
1852
1855}
1856
1857bool CallAnalyzer::visitCastInst(CastInst &I) {
1858 // Propagate constants through casts.
1860 return true;
1861
1862 // Disable SROA in the face of arbitrary casts we don't explicitly list
1863 // elsewhere.
1864 disableSROA(I.getOperand(0));
1865
1866 // If this is a floating-point cast, and the target says this operation
1867 // is expensive, this may eventually become a library call. Treat the cost
1868 // as such.
1869 switch (I.getOpcode()) {
1870 case Instruction::FPTrunc:
1871 case Instruction::FPExt:
1872 case Instruction::UIToFP:
1873 case Instruction::SIToFP:
1874 case Instruction::FPToUI:
1875 case Instruction::FPToSI:
1877 onCallPenalty();
1878 break;
1879 default:
1880 break;
1881 }
1882
1885}
1886
1887bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1888 return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
1889}
1890
1891bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
1892 // Does the *call site* have the NonNull attribute set on an argument? We
1893 // use the attribute on the call site to memoize any analysis done in the
1894 // caller. This will also trip if the callee function has a non-null
1895 // parameter attribute, but that's a less interesting case because hopefully
1896 // the callee would already have been simplified based on that.
1897 if (Argument *A = dyn_cast<Argument>(V))
1898 if (paramHasAttr(A, Attribute::NonNull))
1899 return true;
1900
1901 // Is this an alloca in the caller? This is distinct from the attribute case
1902 // above because attributes aren't updated within the inliner itself and we
1903 // always want to catch the alloca derived case.
1904 if (isAllocaDerivedArg(V))
1905 // We can actually predict the result of comparisons between an
1906 // alloca-derived value and null. Note that this fires regardless of
1907 // SROA firing.
1908 return true;
1909
1910 return false;
1911}
1912
1913bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
1914 // If the normal destination of the invoke or the parent block of the call
1915 // site is unreachable-terminated, there is little point in inlining this
1916 // unless there is literally zero cost.
1917 // FIXME: Note that it is possible that an unreachable-terminated block has a
1918 // hot entry. For example, in below scenario inlining hot_call_X() may be
1919 // beneficial :
1920 // main() {
1921 // hot_call_1();
1922 // ...
1923 // hot_call_N()
1924 // exit(0);
1925 // }
1926 // For now, we are not handling this corner case here as it is rare in real
1927 // code. In future, we should elaborate this based on BPI and BFI in more
1928 // general threshold adjusting heuristics in updateThreshold().
1929 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
1930 if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
1931 return false;
1932 } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
1933 return false;
1934
1935 return true;
1936}
1937
1938bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1939 BlockFrequencyInfo *CallerBFI) {
1940 // If global profile summary is available, then callsite's coldness is
1941 // determined based on that.
1942 if (PSI && PSI->hasProfileSummary())
1943 return PSI->isColdCallSite(Call, CallerBFI);
1944
1945 // Otherwise we need BFI to be available.
1946 if (!CallerBFI)
1947 return false;
1948
1949 // Determine if the callsite is cold relative to caller's entry. We could
1950 // potentially cache the computation of scaled entry frequency, but the added
1951 // complexity is not worth it unless this scaling shows up high in the
1952 // profiles.
1953 const BranchProbability ColdProb(Opts.cold_callsite_rel_freq, 100);
1954 auto CallSiteBB = Call.getParent();
1955 auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1956 auto CallerEntryFreq =
1957 CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1958 return CallSiteFreq < CallerEntryFreq * ColdProb;
1959}
1960
1961std::optional<int>
1962InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1963 BlockFrequencyInfo *CallerBFI) {
1964
1965 // If global profile summary is available, then callsite's hotness is
1966 // determined based on that.
1967 if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
1968 return Params.HotCallSiteThreshold;
1969
1970 // Otherwise we need BFI to be available and to have a locally hot callsite
1971 // threshold.
1972 if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1973 return std::nullopt;
1974
1975 // Determine if the callsite is hot relative to caller's entry. We could
1976 // potentially cache the computation of scaled entry frequency, but the added
1977 // complexity is not worth it unless this scaling shows up high in the
1978 // profiles.
1979 const BasicBlock *CallSiteBB = Call.getParent();
1980 BlockFrequency CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1981 BlockFrequency CallerEntryFreq = CallerBFI->getEntryFreq();
1982 std::optional<BlockFrequency> Limit =
1983 CallerEntryFreq.mul(Opts.hot_callsite_rel_freq);
1984 if (Limit && CallSiteFreq >= *Limit)
1985 return Params.LocallyHotCallSiteThreshold;
1986
1987 // Otherwise treat it normally.
1988 return std::nullopt;
1989}
1990
1991void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
1992 // If no size growth is allowed for this inlining, set Threshold to 0.
1993 if (!allowSizeGrowth(Call)) {
1994 Threshold = 0;
1995 return;
1996 }
1997
1999
2000 // return min(A, B) if B is valid.
2001 auto MinIfValid = [](int A, std::optional<int> B) {
2002 return B ? std::min(A, *B) : A;
2003 };
2004
2005 // return max(A, B) if B is valid.
2006 auto MaxIfValid = [](int A, std::optional<int> B) {
2007 return B ? std::max(A, *B) : A;
2008 };
2009
2010 // Various bonus percentages. These are multiplied by Threshold to get the
2011 // bonus values.
2012 // SingleBBBonus: This bonus is applied if the callee has a single reachable
2013 // basic block at the given callsite context. This is speculatively applied
2014 // and withdrawn if more than one basic block is seen.
2015 //
2016 // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
2017 // of the last call to a static function as inlining such functions is
2018 // guaranteed to reduce code size.
2019 //
2020 // These bonus percentages may be set to 0 based on properties of the caller
2021 // and the callsite.
2022 int SingleBBBonusPercent = 50;
2023 int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
2024 int LastCallToStaticBonus = TTI.getInliningLastCallToStaticBonus();
2025
2026 // Lambda to set all the above bonus and bonus percentages to 0.
2027 auto DisallowAllBonuses = [&]() {
2028 SingleBBBonusPercent = 0;
2029 VectorBonusPercent = 0;
2030 LastCallToStaticBonus = 0;
2031 };
2032
2033 // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
2034 // and reduce the threshold if the caller has the necessary attribute.
2035 if (Caller->hasMinSize()) {
2036 Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
2037 // For minsize, we want to disable the single BB bonus and the vector
2038 // bonuses, but not the last-call-to-static bonus. Inlining the last call to
2039 // a static function will, at the minimum, eliminate the parameter setup and
2040 // call/return instructions.
2041 SingleBBBonusPercent = 0;
2042 VectorBonusPercent = 0;
2043 } else if (Caller->hasOptSize())
2044 Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
2045
2046 // Adjust the threshold based on inlinehint attribute and profile based
2047 // hotness information if the caller does not have MinSize attribute.
2048 if (!Caller->hasMinSize()) {
2049 std::optional<int> HintThreshold = Caller->hasOptSize()
2050 ? Params.OptSizeHintThreshold
2051 : Params.HintThreshold;
2052 if (Callee.hasFnAttribute(Attribute::InlineHint))
2053 Threshold = MaxIfValid(Threshold, HintThreshold);
2054
2055 // FIXME: After switching to the new passmanager, simplify the logic below
2056 // by checking only the callsite hotness/coldness as we will reliably
2057 // have local profile information.
2058 //
2059 // Callsite hotness and coldness can be determined if sample profile is
2060 // used (which adds hotness metadata to calls) or if caller's
2061 // BlockFrequencyInfo is available.
2062 BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
2063 auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
2064 if (!Caller->hasOptSize() && HotCallSiteThreshold) {
2065 LLVM_DEBUG(dbgs() << "Hot callsite.\n");
2066 // FIXME: This should update the threshold only if it exceeds the
2067 // current threshold, but AutoFDO + ThinLTO currently relies on this
2068 // behavior to prevent inlining of hot callsites during ThinLTO
2069 // compile phase.
2070 Threshold = *HotCallSiteThreshold;
2071 } else if (isCallableCC(Caller->getCallingConv()) &&
2072 isColdCallSite(Call, CallerBFI)) {
2073 // In a function that is a hardware entry point rather than something
2074 // callable, e.g. a GPU kernel, register allocation is whole-function and
2075 // occupancy is set by the worst case over it. A call left out of line
2076 // there costs the hot path too, however cold the call itself is, so the
2077 // reduced threshold does not apply.
2078 LLVM_DEBUG(dbgs() << "Cold callsite.\n");
2079 // Do not apply bonuses for a cold callsite including the
2080 // LastCallToStatic bonus. While this bonus might result in code size
2081 // reduction, it can cause the size of a non-cold caller to increase
2082 // preventing it from being inlined.
2083 DisallowAllBonuses();
2084 Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
2085 } else if (PSI) {
2086 // Use callee's global profile information only if we have no way of
2087 // determining this via callsite information.
2088 if (PSI->isFunctionEntryHot(&Callee)) {
2089 LLVM_DEBUG(dbgs() << "Hot callee.\n");
2090 // If callsite hotness can not be determined, we may still know
2091 // that the callee is hot and treat it as a weaker hint for threshold
2092 // increase.
2093 Threshold = MaxIfValid(Threshold, HintThreshold);
2094 } else if (PSI->isFunctionEntryCold(&Callee)) {
2095 LLVM_DEBUG(dbgs() << "Cold callee.\n");
2096 // Do not apply bonuses for a cold callee including the
2097 // LastCallToStatic bonus. While this bonus might result in code size
2098 // reduction, it can cause the size of a non-cold caller to increase
2099 // preventing it from being inlined.
2100 DisallowAllBonuses();
2101 Threshold = MinIfValid(Threshold, Params.ColdThreshold);
2102 }
2103 }
2104 }
2105
2106 Threshold += TTI.adjustInliningThreshold(&Call);
2107
2108 // Finally, take the target-specific inlining threshold multiplier into
2109 // account.
2110 Threshold *= TTI.getInliningThresholdMultiplier();
2111
2112 SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
2113 VectorBonus = Threshold * VectorBonusPercent / 100;
2114
2115 // If there is only one call of the function, and it has internal linkage,
2116 // the cost of inlining it drops dramatically. It may seem odd to update
2117 // Cost in updateThreshold, but the bonus depends on the logic in this method.
2118 if (isSoleCallToLocalFunction(Call, F)) {
2119 addCost(-LastCallToStaticBonus);
2120 StaticBonusApplied = LastCallToStaticBonus;
2121 }
2122}
2123
2124bool CallAnalyzer::visitCmpInst(CmpInst &I) {
2125 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2126 // First try to handle simplified comparisons.
2128 return true;
2129
2130 // Try to handle comparison that can be simplified using ValueTracking.
2131 if (simplifyCmpInstForRecCall(I))
2132 return true;
2133
2134 if (I.getOpcode() == Instruction::FCmp)
2135 return false;
2136
2137 // Otherwise look for a comparison between constant offset pointers with
2138 // a common base.
2139 Value *LHSBase, *RHSBase;
2140 APInt LHSOffset, RHSOffset;
2141 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
2142 if (LHSBase) {
2143 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
2144 if (RHSBase && LHSBase == RHSBase) {
2145 // We have common bases, fold the icmp to a constant based on the
2146 // offsets.
2147 SimplifiedValues[&I] = ConstantInt::getBool(
2148 I.getType(),
2149 ICmpInst::compare(LHSOffset, RHSOffset, I.getPredicate()));
2150 ++NumConstantPtrCmps;
2151 return true;
2152 }
2153 }
2154
2155 auto isImplicitNullCheckCmp = [](const CmpInst &I) {
2156 for (auto *User : I.users())
2157 if (auto *Instr = dyn_cast<Instruction>(User))
2158 if (!Instr->getMetadata(LLVMContext::MD_make_implicit))
2159 return false;
2160 return true;
2161 };
2162
2163 // If the comparison is an equality comparison with null, we can simplify it
2164 // if we know the value (argument) can't be null
2165 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1))) {
2166 if (isKnownNonNullInCallee(I.getOperand(0))) {
2167 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
2168 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
2169 : ConstantInt::getFalse(I.getType());
2170 return true;
2171 }
2172 // Implicit null checks act as unconditional branches and their comparisons
2173 // should be treated as simplified and free of cost.
2174 if (isImplicitNullCheckCmp(I))
2175 return true;
2176 }
2177 return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
2178}
2179
2180bool CallAnalyzer::visitSub(BinaryOperator &I) {
2181 // Try to handle a special case: we can fold computing the difference of two
2182 // constant-related pointers.
2183 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2184 Value *LHSBase, *RHSBase;
2185 APInt LHSOffset, RHSOffset;
2186 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
2187 if (LHSBase) {
2188 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
2189 if (RHSBase && LHSBase == RHSBase) {
2190 // We have common bases, fold the subtract to a constant based on the
2191 // offsets.
2192 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
2193 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
2194 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
2195 SimplifiedValues[&I] = C;
2196 ++NumConstantPtrDiffs;
2197 return true;
2198 }
2199 }
2200 }
2201
2202 // Otherwise, fall back to the generic logic for simplifying and handling
2203 // instructions.
2204 return Base::visitSub(I);
2205}
2206
2207bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
2208 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2209 Constant *CLHS = getDirectOrSimplifiedValue<Constant>(LHS);
2210 Constant *CRHS = getDirectOrSimplifiedValue<Constant>(RHS);
2211
2212 Value *SimpleV = nullptr;
2213 if (auto FI = dyn_cast<FPMathOperator>(&I))
2214 SimpleV = simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
2215 FI->getFastMathFlags(), DL);
2216 else
2217 SimpleV =
2218 simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
2219
2220 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2221 SimplifiedValues[&I] = C;
2222
2223 if (SimpleV)
2224 return true;
2225
2226 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
2227 disableSROA(LHS);
2228 disableSROA(RHS);
2229
2230 // If the instruction is floating point, and the target says this operation
2231 // is expensive, this may eventually become a library call. Treat the cost
2232 // as such. Unless it's fneg which can be implemented with an xor.
2233 using namespace llvm::PatternMatch;
2234 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2235 if (I.getType()->isFloatingPointTy() &&
2238 onCallPenalty();
2239
2240 // Free binary operators are, in practice, often fused vector idioms and logic
2241 // on i1 conditions. Skip the TTI query, which is comparatively expensive, for
2242 // the scalar operations that dominate most code.
2243 Type *Ty = I.getType();
2244 if (!Ty->isVectorTy() && !Ty->isIntegerTy(1))
2245 return false;
2246
2249}
2250
2251bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
2252 Value *Op = I.getOperand(0);
2253 Constant *COp = getDirectOrSimplifiedValue<Constant>(Op);
2254
2255 Value *SimpleV = simplifyFNegInst(
2256 COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
2257
2258 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2259 SimplifiedValues[&I] = C;
2260
2261 if (SimpleV)
2262 return true;
2263
2264 // Disable any SROA on arguments to arbitrary, unsimplified fneg.
2265 disableSROA(Op);
2266
2267 return false;
2268}
2269
2270bool CallAnalyzer::visitLoad(LoadInst &I) {
2271 if (handleSROA(I.getPointerOperand(), I.isSimple()))
2272 return true;
2273
2274 // If the data is already loaded from this address and hasn't been clobbered
2275 // by any stores or calls, this load is likely to be redundant and can be
2276 // eliminated.
2277 if (EnableLoadElimination &&
2278 !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
2279 onLoadEliminationOpportunity();
2280 return true;
2281 }
2282
2283 onMemAccess();
2284 return false;
2285}
2286
2287bool CallAnalyzer::visitStore(StoreInst &I) {
2288 if (handleSROA(I.getPointerOperand(), I.isSimple()))
2289 return true;
2290
2291 // The store can potentially clobber loads and prevent repeated loads from
2292 // being eliminated.
2293 // FIXME:
2294 // 1. We can probably keep an initial set of eliminatable loads substracted
2295 // from the cost even when we finally see a store. We just need to disable
2296 // *further* accumulation of elimination savings.
2297 // 2. We should probably at some point thread MemorySSA for the callee into
2298 // this and then use that to actually compute *really* precise savings.
2299 disableLoadElimination();
2300
2301 onMemAccess();
2302 return false;
2303}
2304
2305bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
2306 Value *Op = I.getAggregateOperand();
2307
2308 // Special handling, because we want to simplify extractvalue with a
2309 // potential insertvalue from the caller.
2310 if (Value *SimpleOp = getSimplifiedValueUnchecked(Op)) {
2311 SimplifyQuery SQ(DL);
2312 Value *SimpleV = simplifyExtractValueInst(SimpleOp, I.getIndices(), SQ);
2313 if (SimpleV) {
2314 SimplifiedValues[&I] = SimpleV;
2315 return true;
2316 }
2317 }
2318
2319 // SROA can't look through these, but they may be free.
2320 return Base::visitExtractValue(I);
2321}
2322
2323bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
2324 // Constant folding for insert value is trivial.
2326 return true;
2327
2328 // SROA can't look through these, but they may be free.
2329 return Base::visitInsertValue(I);
2330}
2331
2332/// Try to simplify a call site.
2333///
2334/// Takes a concrete function and callsite and tries to actually simplify it by
2335/// analyzing the arguments and call itself with instsimplify. Returns true if
2336/// it has simplified the callsite to some other entity (a constant), making it
2337/// free.
2338bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
2339 // FIXME: Using the instsimplify logic directly for this is inefficient
2340 // because we have to continually rebuild the argument list even when no
2341 // simplifications can be performed. Until that is fixed with remapping
2342 // inside of instsimplify, directly constant fold calls here.
2344 return false;
2345
2346 // Try to re-map the arguments to constants.
2347 SmallVector<Constant *, 4> ConstantArgs;
2348 ConstantArgs.reserve(Call.arg_size());
2349 for (Value *I : Call.args()) {
2350 Constant *C = getDirectOrSimplifiedValue<Constant>(I);
2351 if (!C)
2352 return false; // This argument doesn't map to a constant.
2353
2354 ConstantArgs.push_back(C);
2355 }
2356 if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
2357 SimplifiedValues[&Call] = C;
2358 return true;
2359 }
2360
2361 return false;
2362}
2363
2364bool CallAnalyzer::isLoweredToCall(Function *F, CallBase &Call) {
2365 const TargetLibraryInfo *TLI = GetTLI ? &GetTLI(*F) : nullptr;
2366 if (!TLI)
2367 return TTI.isLoweredToCall(F);
2368
2369 LibFunc LF = TLI->getLibFunc(*F);
2370 if (!TLI->has(LF))
2371 return TTI.isLoweredToCall(F);
2372
2373 switch (LF) {
2374 case LibFunc_memcpy_chk:
2375 case LibFunc_memmove_chk:
2376 case LibFunc_mempcpy_chk:
2377 case LibFunc_memset_chk: {
2378 // Calls to __memcpy_chk whose length is known to fit within the object
2379 // size will eventually be replaced by inline stores. Therefore, these
2380 // should not incur a call penalty. This is only really relevant on
2381 // platforms whose headers redirect memcpy to __memcpy_chk (e.g. Darwin), as
2382 // other platforms use memcpy intrinsics, which are already exempt from the
2383 // call penalty.
2384 auto *LenOp = getDirectOrSimplifiedValue<ConstantInt>(Call.getOperand(2));
2385 auto *ObjSizeOp =
2386 getDirectOrSimplifiedValue<ConstantInt>(Call.getOperand(3));
2387 if (LenOp && ObjSizeOp &&
2388 LenOp->getLimitedValue() <= ObjSizeOp->getLimitedValue()) {
2389 return false;
2390 }
2391 break;
2392 }
2393 default:
2394 break;
2395 }
2396
2397 return TTI.isLoweredToCall(F);
2398}
2399
2400bool CallAnalyzer::visitCallBase(CallBase &Call) {
2401 if (!onCallBaseVisitStart(Call))
2402 return true;
2403
2404 if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
2405 !F.hasFnAttribute(Attribute::ReturnsTwice)) {
2406 // This aborts the entire analysis.
2407 ExposesReturnsTwice = true;
2408 return false;
2409 }
2410 if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
2411 ContainsNoDuplicateCall = true;
2412
2413 if (InlineAsm *InlineAsmOp = dyn_cast<InlineAsm>(Call.getCalledOperand()))
2414 onInlineAsm(*InlineAsmOp);
2415
2417 bool IsIndirectCall = !F;
2418 if (IsIndirectCall) {
2419 // Check if this happens to be an indirect function call to a known function
2420 // in this inline context. If not, we've done all we can.
2422 F = getSimplifiedValue<Function>(Callee);
2423 if (!F || F->getFunctionType() != Call.getFunctionType()) {
2424 onCallArgumentSetup(Call);
2425
2426 if (!Call.onlyReadsMemory())
2427 disableLoadElimination();
2428 return Base::visitCallBase(Call);
2429 }
2430 }
2431
2432 assert(F && "Expected a call to a known function");
2433
2434 // When we have a concrete function, first try to simplify it directly.
2435 if (simplifyCallSite(F, Call))
2436 return true;
2437
2438 // Next check if it is an intrinsic we know about.
2439 // FIXME: Lift this into part of the InstVisitor.
2440 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
2441 switch (II->getIntrinsicID()) {
2442 default:
2444 disableLoadElimination();
2445 return Base::visitCallBase(Call);
2446
2447 case Intrinsic::load_relative:
2448 onLoadRelativeIntrinsic();
2449 return false;
2450
2451 case Intrinsic::memset:
2452 case Intrinsic::memcpy:
2453 case Intrinsic::memmove:
2454 disableLoadElimination();
2455 // SROA can usually chew through these intrinsics, but they aren't free.
2456 return false;
2457 case Intrinsic::icall_branch_funnel:
2458 case Intrinsic::localescape:
2459 HasUninlineableIntrinsic = true;
2460 return false;
2461 case Intrinsic::vastart:
2462 InitsVargArgs = true;
2463 return false;
2464 case Intrinsic::launder_invariant_group:
2465 if (auto *SROAArg = getSROAArgForValueOrNull(II->getOperand(0)))
2466 SROAArgValues[II] = SROAArg;
2467 return true;
2468 case Intrinsic::is_constant:
2469 return simplifyIntrinsicCallIsConstant(Call);
2470 case Intrinsic::objectsize:
2471 return simplifyIntrinsicCallObjectSize(Call);
2472 }
2473 }
2474
2475 if (F == Call.getFunction()) {
2476 // This flag will fully abort the analysis, so don't bother with anything
2477 // else.
2478 IsRecursiveCall = true;
2479 if (!AllowRecursiveCall)
2480 return false;
2481 }
2482
2483 if (isLoweredToCall(F, Call)) {
2484 onLoweredCall(F, Call, IsIndirectCall);
2485 }
2486
2487 if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
2488 disableLoadElimination();
2489 return Base::visitCallBase(Call);
2490}
2491
2492bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
2493 // At least one return instruction will be free after inlining.
2494 bool Free = !HasReturn;
2495 HasReturn = true;
2496 return Free;
2497}
2498
2499bool CallAnalyzer::visitUncondBrInst(UncondBrInst &BI) {
2500 // We model unconditional branches as essentially free -- they really
2501 // shouldn't exist at all, but handling them makes the behavior of the
2502 // inliner more regular and predictable.
2503 return true;
2504}
2505
2506bool CallAnalyzer::visitCondBrInst(CondBrInst &BI) {
2507 // Conditional branches which will fold away are free.
2508 return getDirectOrSimplifiedValue<ConstantInt>(BI.getCondition()) ||
2509 BI.getMetadata(LLVMContext::MD_make_implicit);
2510}
2511
2512bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
2513 bool CheckSROA = SI.getType()->isPointerTy();
2514 Value *TrueVal = SI.getTrueValue();
2515 Value *FalseVal = SI.getFalseValue();
2516
2517 Constant *TrueC = getDirectOrSimplifiedValue<Constant>(TrueVal);
2518 Constant *FalseC = getDirectOrSimplifiedValue<Constant>(FalseVal);
2519 Constant *CondC = getSimplifiedValue<Constant>(SI.getCondition());
2520
2521 if (!CondC) {
2522 // Select C, X, X => X
2523 if (TrueC == FalseC && TrueC) {
2524 SimplifiedValues[&SI] = TrueC;
2525 return true;
2526 }
2527
2528 if (!CheckSROA)
2529 return Base::visitSelectInst(SI);
2530
2531 std::pair<Value *, APInt> TrueBaseAndOffset =
2532 ConstantOffsetPtrs.lookup(TrueVal);
2533 std::pair<Value *, APInt> FalseBaseAndOffset =
2534 ConstantOffsetPtrs.lookup(FalseVal);
2535 if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
2536 ConstantOffsetPtrs[&SI] = std::move(TrueBaseAndOffset);
2537
2538 if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
2539 SROAArgValues[&SI] = SROAArg;
2540 return true;
2541 }
2542
2543 return Base::visitSelectInst(SI);
2544 }
2545
2546 // Select condition is a constant.
2547 Value *SelectedV = CondC->isAllOnesValue() ? TrueVal
2548 : (CondC->isNullValue()) ? FalseVal
2549 : nullptr;
2550 if (!SelectedV) {
2551 // Condition is a vector constant that is not all 1s or all 0s. If all
2552 // operands are constants, ConstantFoldSelectInstruction() can handle the
2553 // cases such as select vectors.
2554 if (TrueC && FalseC) {
2555 if (auto *C = ConstantFoldSelectInstruction(CondC, TrueC, FalseC)) {
2556 SimplifiedValues[&SI] = C;
2557 return true;
2558 }
2559 }
2560 return Base::visitSelectInst(SI);
2561 }
2562
2563 // Condition is either all 1s or all 0s. SI can be simplified.
2564 if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
2565 SimplifiedValues[&SI] = SelectedC;
2566 return true;
2567 }
2568
2569 if (!CheckSROA)
2570 return true;
2571
2572 std::pair<Value *, APInt> BaseAndOffset =
2573 ConstantOffsetPtrs.lookup(SelectedV);
2574 if (BaseAndOffset.first) {
2575 ConstantOffsetPtrs[&SI] = std::move(BaseAndOffset);
2576
2577 if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
2578 SROAArgValues[&SI] = SROAArg;
2579 }
2580
2581 return true;
2582}
2583
2584bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
2585 // We model unconditional switches as free, see the comments on handling
2586 // branches.
2587 if (getDirectOrSimplifiedValue<ConstantInt>(SI.getCondition()))
2588 return true;
2589
2590 // Assume the most general case where the switch is lowered into
2591 // either a jump table, bit test, or a balanced binary tree consisting of
2592 // case clusters without merging adjacent clusters with the same
2593 // destination. We do not consider the switches that are lowered with a mix
2594 // of jump table/bit test/binary search tree. The cost of the switch is
2595 // proportional to the size of the tree or the size of jump table range.
2596 //
2597 // NB: We convert large switches which are just used to initialize large phi
2598 // nodes to lookup tables instead in simplifycfg, so this shouldn't prevent
2599 // inlining those. It will prevent inlining in cases where the optimization
2600 // does not (yet) fire.
2601
2602 unsigned JumpTableSize = 0;
2603 BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2604 unsigned NumCaseCluster =
2605 TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2606
2607 onFinalizeSwitch(JumpTableSize, NumCaseCluster, SI.defaultDestUnreachable());
2608 return false;
2609}
2610
2611bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
2612 // We never want to inline functions that contain an indirectbr. This is
2613 // incorrect because all the blockaddress's (in static global initializers
2614 // for example) would be referring to the original function, and this
2615 // indirect jump would jump from the inlined copy of the function into the
2616 // original function which is extremely undefined behavior.
2617 // FIXME: This logic isn't really right; we can safely inline functions with
2618 // indirectbr's as long as no other function or global references the
2619 // blockaddress of a block within the current function.
2620 HasIndirectBr = true;
2621 return false;
2622}
2623
2624bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
2625 // FIXME: It's not clear that a single instruction is an accurate model for
2626 // the inline cost of a resume instruction.
2627 return false;
2628}
2629
2630bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
2631 // FIXME: It's not clear that a single instruction is an accurate model for
2632 // the inline cost of a cleanupret instruction.
2633 return false;
2634}
2635
2636bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
2637 // FIXME: It's not clear that a single instruction is an accurate model for
2638 // the inline cost of a catchret instruction.
2639 return false;
2640}
2641
2642bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
2643 // FIXME: It might be reasonably to discount the cost of instructions leading
2644 // to unreachable as they have the lowest possible impact on both runtime and
2645 // code size.
2646 return true; // No actual code is needed for unreachable.
2647}
2648
2649bool CallAnalyzer::visitInstruction(Instruction &I) {
2650 // Some instructions are free. All of the free intrinsics can also be
2651 // handled by SROA, etc.
2654 return true;
2655
2656 // We found something we don't understand or can't handle. Mark any SROA-able
2657 // values in the operand list as no longer viable.
2658 for (const Use &Op : I.operands())
2659 disableSROA(Op);
2660
2661 return false;
2662}
2663
2664/// Analyze a basic block for its contribution to the inline cost.
2665///
2666/// This method walks the analyzer over every instruction in the given basic
2667/// block and accounts for their cost during inlining at this callsite. It
2668/// aborts early if the threshold has been exceeded or an impossible to inline
2669/// construct has been detected. It returns false if inlining is no longer
2670/// viable, and true if inlining remains viable.
2671InlineResult
2672CallAnalyzer::analyzeBlock(BasicBlock *BB,
2673 const SmallPtrSetImpl<const Value *> &EphValues) {
2674 for (Instruction &I : *BB) {
2675 // FIXME: Currently, the number of instructions in a function regardless of
2676 // our ability to simplify them during inline to constants or dead code,
2677 // are actually used by the vector bonus heuristic. As long as that's true,
2678 // we have to special case pseudo-probes here to prevent differences in
2679 // inlining due to sample profiling. Eventually, the number of unsimplified
2680 // instructions shouldn't factor into the cost computation, but until then,
2681 // hack around it here.
2683 continue;
2684
2685 // Skip ephemeral values.
2686 if (EphValues.count(&I))
2687 continue;
2688
2689 ++NumInstructions;
2690 if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
2691 ++NumVectorInstructions;
2692
2693 // If the instruction simplified to a constant, there is no cost to this
2694 // instruction. Visit the instructions using our InstVisitor to account for
2695 // all of the per-instruction logic. The visit tree returns true if we
2696 // consumed the instruction in any way, and false if the instruction's base
2697 // cost should count against inlining.
2698 onInstructionAnalysisStart(&I);
2699
2700 if (Base::visit(&I))
2701 ++NumInstructionsSimplified;
2702 else
2703 onMissedSimplification();
2704
2705 onInstructionAnalysisFinish(&I);
2706 using namespace ore;
2707 // If the visit this instruction detected an uninlinable pattern, abort.
2708 InlineResult IR = InlineResult::success();
2709 if (IsRecursiveCall && !AllowRecursiveCall)
2710 IR = InlineResult::failure("recursive");
2711 else if (ExposesReturnsTwice)
2712 IR = InlineResult::failure("exposes returns twice");
2713 else if (HasDynamicAlloca)
2714 IR = InlineResult::failure("dynamic alloca");
2715 else if (HasIndirectBr)
2716 IR = InlineResult::failure("indirect branch");
2717 else if (HasUninlineableIntrinsic)
2718 IR = InlineResult::failure("uninlinable intrinsic");
2719 else if (InitsVargArgs)
2720 IR = InlineResult::failure("varargs");
2721 if (!IR.isSuccess()) {
2722 if (ORE)
2723 ORE->emit([&]() {
2724 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2725 &CandidateCall)
2726 << NV("Callee", &F) << " has uninlinable pattern ("
2727 << NV("InlineResult", IR.getFailureReason())
2728 << ") and cost is not fully computed";
2729 });
2730 return IR;
2731 }
2732
2733 // If the caller is a recursive function then we don't want to inline
2734 // functions which allocate a lot of stack space because it would increase
2735 // the caller stack usage dramatically.
2736 if (IsCallerRecursive &&
2737 AllocatedSize > Opts.recursive_inline_max_stacksize) {
2738 auto IR =
2739 InlineResult::failure("recursive and allocates too much stack space");
2740 if (ORE)
2741 ORE->emit([&]() {
2742 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2743 &CandidateCall)
2744 << NV("Callee", &F) << " is "
2745 << NV("InlineResult", IR.getFailureReason())
2746 << ". Cost is not fully computed";
2747 });
2748 return IR;
2749 }
2750
2751 if (shouldStop())
2752 return InlineResult::failure(
2753 "Call site analysis is not favorable to inlining.");
2754 }
2755
2756 return InlineResult::success();
2757}
2758
2759/// Compute the base pointer and cumulative constant offsets for V.
2760///
2761/// This strips all constant offsets off of V, leaving it the base pointer, and
2762/// accumulates the total constant offset applied in the returned constant. It
2763/// returns 0 if V is not a pointer, and returns the constant '0' if there are
2764/// no constant offsets applied.
2765ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
2766 if (!V->getType()->isPointerTy())
2767 return nullptr;
2768
2769 unsigned AS = V->getType()->getPointerAddressSpace();
2770 unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
2771 APInt Offset = APInt::getZero(IntPtrWidth);
2772
2773 // Even though we don't look through PHI nodes, we could be called on an
2774 // instruction in an unreachable block, which may be on a cycle.
2775 SmallPtrSet<Value *, 4> Visited;
2776 Visited.insert(V);
2777 do {
2778 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2779 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
2780 return nullptr;
2781 V = GEP->getPointerOperand();
2782 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2783 if (GA->isInterposable())
2784 break;
2785 V = GA->getAliasee();
2786 } else {
2787 break;
2788 }
2789 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2790 } while (Visited.insert(V).second);
2791
2792 Type *IdxPtrTy = DL.getIndexType(V->getType());
2793 return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
2794}
2795
2796/// Find dead blocks due to deleted CFG edges during inlining.
2797///
2798/// If we know the successor of the current block, \p CurrBB, has to be \p
2799/// NextBB, the other successors of \p CurrBB are dead if these successors have
2800/// no live incoming CFG edges. If one block is found to be dead, we can
2801/// continue growing the dead block list by checking the successors of the dead
2802/// blocks to see if all their incoming edges are dead or not.
2803void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
2804 auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
2805 // A CFG edge is dead if the predecessor is dead or the predecessor has a
2806 // known successor which is not the one under exam.
2807 if (DeadBlocks.count(Pred))
2808 return true;
2809 BasicBlock *KnownSucc = KnownSuccessors[Pred];
2810 return KnownSucc && KnownSucc != Succ;
2811 };
2812
2813 auto IsNewlyDead = [&](BasicBlock *BB) {
2814 // If all the edges to a block are dead, the block is also dead.
2815 return (!DeadBlocks.count(BB) &&
2817 [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
2818 };
2819
2820 for (BasicBlock *Succ : successors(CurrBB)) {
2821 if (Succ == NextBB || !IsNewlyDead(Succ))
2822 continue;
2824 NewDead.push_back(Succ);
2825 while (!NewDead.empty()) {
2826 BasicBlock *Dead = NewDead.pop_back_val();
2827 if (DeadBlocks.insert(Dead).second)
2828 // Continue growing the dead block lists.
2829 for (BasicBlock *S : successors(Dead))
2830 if (IsNewlyDead(S))
2831 NewDead.push_back(S);
2832 }
2833 }
2834}
2835
2836/// Analyze a call site for potential inlining.
2837///
2838/// Returns true if inlining this call is viable, and false if it is not
2839/// viable. It computes the cost and adjusts the threshold based on numerous
2840/// factors and heuristics. If this method returns false but the computed cost
2841/// is below the computed threshold, then inlining was forcibly disabled by
2842/// some artifact of the routine.
2843InlineResult CallAnalyzer::analyze() {
2844 ++NumCallsAnalyzed;
2845
2846 auto Result = onAnalysisStart();
2847 if (!Result.isSuccess())
2848 return Result;
2849
2850 if (F.empty())
2851 return InlineResult::success();
2852
2853 Function *Caller = CandidateCall.getFunction();
2854 // Check if the caller function is recursive itself.
2855 for (User *U : Caller->users()) {
2856 CallBase *Call = dyn_cast<CallBase>(U);
2857 if (Call && Call->getFunction() == Caller) {
2858 IsCallerRecursive = true;
2859 break;
2860 }
2861 }
2862
2863 // Populate our simplified values by mapping from function arguments to call
2864 // arguments with known important simplifications.
2865 auto CAI = CandidateCall.arg_begin();
2866 for (Argument &FAI : F.args()) {
2867 assert(CAI != CandidateCall.arg_end());
2868 SimplifiedValues[&FAI] = *CAI;
2869 if (isa<Constant>(*CAI))
2870 ++NumConstantArgs;
2871
2872 Value *PtrArg = *CAI;
2873 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
2874 ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
2875
2876 // We can SROA any pointer arguments derived from alloca instructions.
2877 if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
2878 SROAArgValues[&FAI] = SROAArg;
2879 onInitializeSROAArg(SROAArg);
2880 EnabledSROAAllocas.insert(SROAArg);
2881 }
2882 }
2883 ++CAI;
2884 }
2885 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
2886 NumAllocaArgs = SROAArgValues.size();
2887
2888 // Collecting the ephemeral values of `F` can be expensive, so use the
2889 // ephemeral values cache if available.
2890 SmallPtrSet<const Value *, 32> EphValuesStorage;
2891 const SmallPtrSetImpl<const Value *> *EphValues = &EphValuesStorage;
2892 if (GetEphValuesCache)
2893 EphValues = &GetEphValuesCache(F).ephValues();
2894 else
2895 CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F),
2896 EphValuesStorage);
2897
2898 // The worklist of live basic blocks in the callee *after* inlining. We avoid
2899 // adding basic blocks of the callee which can be proven to be dead for this
2900 // particular call site in order to get more accurate cost estimates. This
2901 // requires a somewhat heavyweight iteration pattern: we need to walk the
2902 // basic blocks in a breadth-first order as we insert live successors. To
2903 // accomplish this, prioritizing for small iterations because we exit after
2904 // crossing our threshold, we use a small-size optimized SetVector.
2905 typedef SmallSetVector<BasicBlock *, 16> BBSetVector;
2906 BBSetVector BBWorklist;
2907 BBWorklist.insert(&F.getEntryBlock());
2908
2909 // Note that we *must not* cache the size, this loop grows the worklist.
2910 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
2911 if (shouldStop())
2912 break;
2913
2914 BasicBlock *BB = BBWorklist[Idx];
2915 if (BB->empty())
2916 continue;
2917
2918 onBlockStart(BB);
2919
2920 // Disallow inlining a blockaddress.
2921 // A blockaddress only has defined behavior for an indirect branch in the
2922 // same function, and we do not currently support inlining indirect
2923 // branches. But, the inliner may not see an indirect branch that ends up
2924 // being dead code at a particular call site. If the blockaddress escapes
2925 // the function, e.g., via a global variable, inlining may lead to an
2926 // invalid cross-function reference.
2927 // FIXME: pr/39560: continue relaxing this overt restriction.
2928 if (BB->hasAddressTaken())
2929 return InlineResult::failure("blockaddress used");
2930
2931 // Analyze the cost of this block. If we blow through the threshold, this
2932 // returns false, and we can bail on out.
2933 InlineResult IR = analyzeBlock(BB, *EphValues);
2934 if (!IR.isSuccess())
2935 return IR;
2936
2937 Instruction *TI = BB->getTerminator();
2938
2939 // Add in the live successors by first checking whether we have terminator
2940 // that may be simplified based on the values simplified by this call.
2941 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
2942 Value *Cond = BI->getCondition();
2943 if (ConstantInt *SimpleCond = getSimplifiedValue<ConstantInt>(Cond)) {
2944 BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
2945 BBWorklist.insert(NextBB);
2946 KnownSuccessors[BB] = NextBB;
2947 findDeadBlocks(BB, NextBB);
2948 continue;
2949 }
2950 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2951 Value *Cond = SI->getCondition();
2952 if (ConstantInt *SimpleCond = getSimplifiedValue<ConstantInt>(Cond)) {
2953 BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
2954 BBWorklist.insert(NextBB);
2955 KnownSuccessors[BB] = NextBB;
2956 findDeadBlocks(BB, NextBB);
2957 continue;
2958 }
2959 }
2960
2961 // If we're unable to select a particular successor, just count all of
2962 // them.
2963 BBWorklist.insert_range(successors(BB));
2964
2965 onBlockAnalyzed(BB);
2966 }
2967
2968 // If this is a noduplicate call, we can still inline as long as
2969 // inlining this would cause the removal of the caller (so the instruction
2970 // is not actually duplicated, just moved).
2971 if (!isSoleCallToLocalFunction(CandidateCall, F) && ContainsNoDuplicateCall)
2972 return InlineResult::failure("noduplicate");
2973
2974 // If the callee's stack size exceeds the user-specified threshold,
2975 // do not let it be inlined.
2976 // The command line option overrides a limit set in the function attributes.
2977 size_t FinalStackSizeThreshold = std::numeric_limits<size_t>::max();
2978 if (Opts.inline_max_stacksize)
2979 FinalStackSizeThreshold = *Opts.inline_max_stacksize;
2980 else if (std::optional<int> AttrMaxStackSize = getStringFnAttrAsInt(
2982 FinalStackSizeThreshold = *AttrMaxStackSize;
2983 if (AllocatedSize > FinalStackSizeThreshold)
2984 return InlineResult::failure("stacksize");
2985
2986 return finalizeAnalysis();
2987}
2988
2989void InlineCostCallAnalyzer::print(raw_ostream &OS) {
2990#define DEBUG_PRINT_STAT(x) OS << " " #x ": " << x << "\n"
2991 if (PrintInstructionComments)
2992 F.print(OS, &Writer);
2993 DEBUG_PRINT_STAT(NumConstantArgs);
2994 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
2995 DEBUG_PRINT_STAT(NumAllocaArgs);
2996 DEBUG_PRINT_STAT(NumConstantPtrCmps);
2997 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
2998 DEBUG_PRINT_STAT(NumInstructionsSimplified);
2999 DEBUG_PRINT_STAT(NumInstructions);
3000 DEBUG_PRINT_STAT(NumInlineAsmInstructions);
3001 DEBUG_PRINT_STAT(SROACostSavings);
3002 DEBUG_PRINT_STAT(SROACostSavingsLost);
3003 DEBUG_PRINT_STAT(LoadEliminationCost);
3004 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
3006 DEBUG_PRINT_STAT(Threshold);
3007#undef DEBUG_PRINT_STAT
3008}
3009
3010#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3011/// Dump stats about this call's analysis.
3012LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { print(dbgs()); }
3013#endif
3014
3015/// Test that there are no attribute conflicts between Caller and Callee
3016/// that prevent inlining.
3018 const AnalysisOptions &Opts, Function *Caller, Function *Callee,
3019 function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
3020 // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
3021 // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
3022 // object, and always returns the same object (which is overwritten on each
3023 // GetTLI call). Therefore we copy the first result.
3024 auto CalleeTLI = GetTLI(*Callee);
3025 return GetTLI(*Caller).areInlineCompatible(
3026 CalleeTLI, Opts.inline_caller_superset_nobuiltin) &&
3027 AttributeFuncs::areInlineCompatible(*Caller, *Callee);
3028}
3029
3031 const DataLayout &DL) {
3032 int64_t Cost = 0;
3033 for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
3034 if (Call.isByValArgument(I)) {
3035 // We approximate the number of loads and stores needed by dividing the
3036 // size of the byval type by the target's pointer size.
3037 PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
3038 unsigned TypeSize = DL.getTypeSizeInBits(Call.getParamByValType(I));
3039 unsigned AS = PTy->getAddressSpace();
3040 unsigned PointerSize = DL.getPointerSizeInBits(AS);
3041 // Ceiling division.
3042 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
3043
3044 // If it generates more than 8 stores it is likely to be expanded as an
3045 // inline memcpy so we take that as an upper bound. Otherwise we assume
3046 // one load and one store per word copied.
3047 // FIXME: The maxStoresPerMemcpy setting from the target should be used
3048 // here instead of a magic number of 8, but it's not available via
3049 // DataLayout.
3050 NumStores = std::min(NumStores, 8U);
3051
3052 Cost += 2 * NumStores * InstrCost;
3053 } else {
3054 // For non-byval arguments subtract off one instruction per call
3055 // argument.
3056 Cost += InstrCost;
3057 }
3058 }
3059 // The call instruction also disappears after inlining.
3060 Cost += InstrCost;
3061 Cost += TTI.getInlineCallPenalty(
3062 Call.getCaller(), Call,
3063 getAnalysisOptions(Call.getContext()).inline_call_penalty);
3064
3065 return std::min<int64_t>(Cost, INT_MAX);
3066}
3067
3069 CallBase &Call, const InlineParams &Params, TargetTransformInfo &CallerTTI,
3070 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3071 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3074 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
3075 return getInlineCost(Call, Call.getCalledFunction(), Params, CallerTTI,
3076 GetAssumptionCache, GetTLI, GetBFI, PSI, ORE,
3077 GetEphValuesCache);
3078}
3079
3081 CallBase &Call, TargetTransformInfo &CallerTTI,
3082 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3084 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3086 const InlineParams Params = {/* DefaultThreshold*/ 0,
3087 /*HintThreshold*/ {},
3088 /*OptSizeHintThreshold*/ {},
3089 /*ColdThreshold*/ {},
3090 /*OptSizeThreshold*/ {},
3091 /*OptMinSizeThreshold*/ {},
3092 /*HotCallSiteThreshold*/ {},
3093 /*LocallyHotCallSiteThreshold*/ {},
3094 /*ColdCallSiteThreshold*/ {},
3095 /*ComputeFullInlineCost*/ true,
3096 /*EnableDeferral*/ true};
3097
3098 InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CallerTTI,
3099 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE, true,
3100 /*IgnoreThreshold*/ true);
3101 auto R = CA.analyze();
3102 if (!R.isSuccess())
3103 return std::nullopt;
3104 return CA.getCost();
3105}
3106
3107std::optional<InlineCostFeatures> llvm::getInliningCostFeatures(
3108 CallBase &Call, TargetTransformInfo &CallerTTI,
3109 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3111 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3113 InlineCostFeaturesAnalyzer CFA(CallerTTI, GetAssumptionCache, GetBFI, GetTLI,
3114 PSI, ORE, *Call.getCalledFunction(), Call);
3115 auto R = CFA.analyze();
3116 if (!R.isSuccess())
3117 return std::nullopt;
3118 return CFA.features();
3119}
3120
3122 CallBase &Call, Function *Callee, TargetTransformInfo &CallerTTI,
3123 function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
3124
3125 // Cannot inline indirect calls.
3126 if (!Callee)
3127 return InlineResult::failure("indirect call");
3128
3129 // When callee coroutine function is inlined into caller coroutine function
3130 // before coro-split pass,
3131 // coro-early pass can not handle this quiet well.
3132 // So we won't inline the coroutine function if it have not been unsplited
3133 if (Callee->isPresplitCoroutine())
3134 return InlineResult::failure("unsplited coroutine call");
3135
3136 // Inlining into a function with less target features is unsound, so enforce
3137 // this even if alwaysinline is used.
3138 Function *Caller = Call.getCaller();
3139 const AnalysisOptions &Opts = getAnalysisOptions(*Caller);
3140 if (!Opts.ignore_tti_inline_compatible &&
3141 !CallerTTI.areInlineCompatible(Caller, Callee))
3142 return InlineResult::failure("conflicting target features");
3143
3144 // Calls to functions with always-inline attributes should be inlined
3145 // whenever possible.
3146 if (Call.hasFnAttr(Attribute::AlwaysInline)) {
3147 if (Call.getAttributes().hasFnAttr(Attribute::NoInline))
3148 return InlineResult::failure("noinline call site attribute");
3149
3150 if (!AttributeFuncs::isStrictFPInlineCompatible(*Caller, *Callee))
3151 return InlineResult::failure("incompatible strictfp attributes");
3152
3153 auto IsViable = isInlineViable(*Callee);
3154 if (IsViable.isSuccess())
3155 return InlineResult::success();
3156 return InlineResult::failure(IsViable.getFailureReason());
3157 }
3158
3159 // Never inline functions with conflicting attributes (unless callee has
3160 // always-inline attribute).
3161 if (!functionsHaveCompatibleAttributes(Opts, Caller, Callee, GetTLI))
3162 return InlineResult::failure("conflicting attributes");
3163
3164 // Flatten: inline all viable calls from flatten functions regardless of cost.
3165 // Checked before optnone so that flatten takes priority.
3166 if (Caller->hasFnAttribute(Attribute::Flatten)) {
3167 auto IsViable = isInlineViable(*Callee);
3168 if (IsViable.isSuccess())
3169 return InlineResult::success();
3170 return InlineResult::failure(IsViable.getFailureReason());
3171 }
3172
3173 // Don't inline this call if the caller has the optnone attribute.
3174 if (Caller->hasOptNone())
3175 return InlineResult::failure("optnone attribute");
3176
3177 // Don't inline functions which can be interposed at link-time.
3178 if (Callee->isInterposable(/*CheckNoIPA=*/false))
3179 return InlineResult::failure("interposable");
3180
3181 // Don't inline functions marked noinline.
3182 if (Callee->hasFnAttribute(Attribute::NoInline))
3183 return InlineResult::failure("noinline function attribute");
3184
3185 // Don't inline call sites marked noinline.
3186 if (Call.isNoInline())
3187 return InlineResult::failure("noinline call site attribute");
3188
3189 // Don't inline functions that are loader replaceable.
3190 if (Callee->hasFnAttribute("loader-replaceable"))
3191 return InlineResult::failure("loader replaceable function attribute");
3192
3193 return std::nullopt;
3194}
3195
3197 CallBase &Call, Function *Callee, const InlineParams &Params,
3198 TargetTransformInfo &CallerTTI,
3199 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3200 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3203 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
3204
3205 auto UserDecision =
3206 llvm::getAttributeBasedInliningDecision(Call, Callee, CallerTTI, GetTLI);
3207
3208 if (UserDecision) {
3209 if (UserDecision->isSuccess())
3210 return llvm::InlineCost::getAlways("always inline attribute");
3211 return llvm::InlineCost::getNever(UserDecision->getFailureReason());
3212 }
3213
3214 if (getAnalysisOptions(*Callee).inline_all_viable_calls &&
3215 isInlineViable(*Callee).isSuccess())
3217 "Inlining forced by -inline-all-viable-calls");
3218
3219 LLVM_DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
3220 << "... (caller:" << Call.getCaller()->getName()
3221 << ")\n");
3222
3223 // If requested, make the analysis independent of any profile information by
3224 // not providing the profile summary or block frequency info.
3225 const bool IgnoreProfile = Params.IgnoreProfile.value_or(false);
3226 function_ref<BlockFrequencyInfo &(Function &)> GetBFIForAnalysis =
3227 IgnoreProfile ? nullptr : GetBFI;
3228 InlineCostCallAnalyzer CA(
3229 *Callee, Call, Params, CallerTTI, GetAssumptionCache, GetBFIForAnalysis,
3230 GetTLI, IgnoreProfile ? nullptr : PSI, ORE,
3231 /*BoostIndirect=*/true, /*IgnoreThreshold=*/false, GetEphValuesCache);
3232 InlineResult ShouldInline = CA.analyze();
3233
3234 LLVM_DEBUG(CA.dump());
3235
3236 // Always make cost benefit based decision explicit.
3237 // We use always/never here since threshold is not meaningful,
3238 // as it's not what drives cost-benefit analysis.
3239 if (CA.wasDecidedByCostBenefit()) {
3240 if (ShouldInline.isSuccess())
3241 return InlineCost::getAlways("benefit over cost",
3242 CA.getCostBenefitPair());
3243 else
3244 return InlineCost::getNever("cost over benefit", CA.getCostBenefitPair());
3245 }
3246
3247 if (CA.wasDecidedByCostThreshold())
3248 return InlineCost::get(CA.getCost(), CA.getThreshold(),
3249 CA.getStaticBonusApplied());
3250
3251 // No details on how the decision was made, simply return always or never.
3252 return ShouldInline.isSuccess()
3253 ? InlineCost::getAlways("empty function")
3254 : InlineCost::getNever(ShouldInline.getFailureReason());
3255}
3256
3258 bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
3259 for (BasicBlock &BB : F) {
3260 // Disallow inlining of functions which contain indirect branches.
3262 return InlineResult::failure("contains indirect branches");
3263
3264 // Disallow inlining of blockaddresses.
3265 if (BB.hasAddressTaken())
3266 return InlineResult::failure("blockaddress used");
3267
3268 for (auto &II : BB) {
3270 if (!Call)
3271 continue;
3272
3273 // Disallow recursive calls.
3274 Function *Callee = Call->getCalledFunction();
3275 if (&F == Callee)
3276 return InlineResult::failure("recursive call");
3277
3278 // Disallow calls which expose returns-twice to a function not previously
3279 // attributed as such.
3280 if (!ReturnsTwice && isa<CallInst>(Call) &&
3281 cast<CallInst>(Call)->canReturnTwice())
3282 return InlineResult::failure("exposes returns-twice attribute");
3283
3284 if (Callee)
3285 switch (Callee->getIntrinsicID()) {
3286 default:
3287 break;
3288 case llvm::Intrinsic::icall_branch_funnel:
3289 // Disallow inlining of @llvm.icall.branch.funnel because current
3290 // backend can't separate call targets from call arguments.
3291 return InlineResult::failure(
3292 "disallowed inlining of @llvm.icall.branch.funnel");
3293 case llvm::Intrinsic::localescape:
3294 // Disallow inlining functions that call @llvm.localescape. Doing this
3295 // correctly would require major changes to the inliner.
3296 return InlineResult::failure(
3297 "disallowed inlining of @llvm.localescape");
3298 case llvm::Intrinsic::vastart:
3299 // Disallow inlining of functions that initialize VarArgs with
3300 // va_start.
3301 return InlineResult::failure(
3302 "contains VarArgs initialized with va_start");
3303 }
3304 }
3305 }
3306
3307 return InlineResult::success();
3308}
3309
3310// APIs to create InlineParams based on command line flags and/or other
3311// parameters.
3312
3314 InlineParams Params;
3315
3316 // This field is the threshold to use for a callee by default. This is
3317 // derived from one or more of:
3318 // * optimization or size-optimization levels,
3319 // * a value passed to createFunctionInliningPass function, or
3320 // * the -inline-threshold flag.
3321 // If the -inline-threshold flag is explicitly specified, that is used
3322 // irrespective of anything else.
3323 if (InlineThreshold.getNumOccurrences() > 0)
3325 else
3326 Params.DefaultThreshold = Threshold;
3327
3328 // Set the HintThreshold knob from the -inlinehint-threshold.
3330 // Use same threshold for optsize by default.
3332
3333 // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
3335
3336 // If the -locally-hot-callsite-threshold is explicitly specified, use it to
3337 // populate LocallyHotCallSiteThreshold. Later, we populate
3338 // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
3339 // we know that optimization level is O3 (in the getInlineParams variant that
3340 // takes the opt and size levels).
3341 // FIXME: Remove this check (and make the assignment unconditional) after
3342 // addressing size regression issues at O2.
3343 if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
3345
3346 // Set the ColdCallSiteThreshold knob from the
3347 // -inline-cold-callsite-threshold.
3349
3350 // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
3351 // -inlinehint-threshold commandline option is not explicitly given. If that
3352 // option is present, then its value applies even for callees with size and
3353 // minsize attributes.
3354 // If the -inline-threshold is not specified, set the ColdThreshold from the
3355 // -inlinecold-threshold even if it is not explicitly passed. If
3356 // -inline-threshold is specified, then -inlinecold-threshold needs to be
3357 // explicitly specified to set the ColdThreshold knob
3358 if (InlineThreshold.getNumOccurrences() == 0) {
3362 } else if (ColdThreshold.getNumOccurrences() > 0) {
3364 }
3365 return Params;
3366}
3367
3371
3373 auto Params =
3376 // At O3, use the value of -locally-hot-callsite-threshold option to populate
3377 // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
3378 // when it is specified explicitly.
3379 if (OptLevel > 2)
3381 return Params;
3382}
3383
3387 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
3388 [&](Function &F) -> AssumptionCache & {
3389 return FAM.getResult<AssumptionAnalysis>(F);
3390 };
3391
3392 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
3393 ProfileSummaryInfo *PSI =
3394 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3395 const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
3396
3397 // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
3398 // In the current implementation, the type of InlineParams doesn't matter as
3399 // the pass serves only for verification of inliner's decisions.
3400 // We can add a flag which determines InlineParams for this run. Right now,
3401 // the default InlineParams are used.
3402 const InlineParams Params = llvm::getInlineParams();
3403 for (BasicBlock &BB : F) {
3404 for (Instruction &I : BB) {
3405 if (auto *CB = dyn_cast<CallBase>(&I)) {
3406 Function *CalledFunction = CB->getCalledFunction();
3407 if (!CalledFunction || CalledFunction->isDeclaration())
3408 continue;
3409 OptimizationRemarkEmitter ORE(CalledFunction);
3410 InlineCostCallAnalyzer ICCA(*CalledFunction, *CB, Params, TTI,
3411 GetAssumptionCache, nullptr, nullptr, PSI,
3412 &ORE, /*BoostIndirect=*/true,
3413 /*IgnoreThreshold=*/false,
3414 /*GetEphValuesCache=*/nullptr,
3415 /*PrintInstructionComments=*/true);
3416 ICCA.analyze();
3417 OS << " Analyzing call of " << CalledFunction->getName()
3418 << "... (caller:" << CB->getCaller()->getName() << ")\n";
3419 ICCA.print(OS);
3420 OS << "\n";
3421 }
3422 }
3423 }
3424 return PreservedAnalyses::all();
3425}
const TargetLowering & TLI
SDValue Pred
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.
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
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
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
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
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
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
@ 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 std::optional< InlineResult > getAttributeBasedInliningDecision(CallBase &Call, Function *Callee, TargetTransformInfo &CallerTTI, function_ref< const TargetLibraryInfo &(Function &)> GetTLI)
Returns InlineResult::success() if the call site should be always inlined because of user directives,...
LLVM_ABI 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
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.
TargetTransformInfo TTI
LLVM_ABI std::optional< int > getInliningCostEstimate(CallBase &Call, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, function_ref< const TargetLibraryInfo &(Function &)> GetTLI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Get the cost estimate ignoring thresholds.
LLVM_ABI 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)
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
LLVM_ABI std::optional< InlineCostFeatures > getInliningCostFeatures(CallBase &Call, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, function_ref< const TargetLibraryInfo &(Function &)> GetTLI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Get the expanded cost features.
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