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