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/TargetTransformInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Config/llvm-config.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/InstVisitor.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/IR/PatternMatch.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "inline-cost"
46 
47 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
48 
49 static cl::opt<int> InlineThreshold(
50     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
51     cl::desc("Control the amount of inlining to perform (default = 225)"));
52 
53 static cl::opt<int> HintThreshold(
54     "inlinehint-threshold", cl::Hidden, cl::init(325), cl::ZeroOrMore,
55     cl::desc("Threshold for inlining functions with inline hint"));
56 
57 static cl::opt<int>
58     ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
59                           cl::init(45), cl::ZeroOrMore,
60                           cl::desc("Threshold for inlining cold callsites"));
61 
62 // We introduce this threshold to help performance of instrumentation based
63 // PGO before we actually hook up inliner with analysis passes such as BPI and
64 // BFI.
65 static cl::opt<int> ColdThreshold(
66     "inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore,
67     cl::desc("Threshold for inlining functions with cold attribute"));
68 
69 static cl::opt<int>
70     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
71                          cl::ZeroOrMore,
72                          cl::desc("Threshold for hot callsites "));
73 
74 static cl::opt<int> LocallyHotCallSiteThreshold(
75     "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore,
76     cl::desc("Threshold for locally hot callsites "));
77 
78 static cl::opt<int> ColdCallSiteRelFreq(
79     "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
80     cl::desc("Maximum block frequency, expressed as a percentage of caller's "
81              "entry frequency, for a callsite to be cold in the absence of "
82              "profile information."));
83 
84 static cl::opt<int> HotCallSiteRelFreq(
85     "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore,
86     cl::desc("Minimum block frequency, expressed as a multiple of caller's "
87              "entry frequency, for a callsite to be hot in the absence of "
88              "profile information."));
89 
90 static cl::opt<bool> OptComputeFullInlineCost(
91     "inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore,
92     cl::desc("Compute the full inline cost of a call site even when the cost "
93              "exceeds the threshold."));
94 
95 namespace {
96 class InlineCostCallAnalyzer;
97 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
98   typedef InstVisitor<CallAnalyzer, bool> Base;
99   friend class InstVisitor<CallAnalyzer, bool>;
100 
101 protected:
102   virtual ~CallAnalyzer() {}
103   /// The TargetTransformInfo available for this compilation.
104   const TargetTransformInfo &TTI;
105 
106   /// Getter for the cache of @llvm.assume intrinsics.
107   std::function<AssumptionCache &(Function &)> &GetAssumptionCache;
108 
109   /// Getter for BlockFrequencyInfo
110   Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI;
111 
112   /// Profile summary information.
113   ProfileSummaryInfo *PSI;
114 
115   /// The called function.
116   Function &F;
117 
118   // Cache the DataLayout since we use it a lot.
119   const DataLayout &DL;
120 
121   /// The OptimizationRemarkEmitter available for this compilation.
122   OptimizationRemarkEmitter *ORE;
123 
124   /// The candidate callsite being analyzed. Please do not use this to do
125   /// analysis in the caller function; we want the inline cost query to be
126   /// easily cacheable. Instead, use the cover function paramHasAttr.
127   CallBase &CandidateCall;
128 
129   /// Extension points for handling callsite features.
130   /// Called after a basic block was analyzed.
131   virtual void onBlockAnalyzed(const BasicBlock *BB) {}
132 
133   /// Called at the end of the analysis of the callsite. Return the outcome of
134   /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or
135   /// the reason it can't.
136   virtual InlineResult finalizeAnalysis() { return InlineResult::success(); }
137   /// Called when we're about to start processing a basic block, and every time
138   /// we are done processing an instruction. Return true if there is no point in
139   /// continuing the analysis (e.g. we've determined already the call site is
140   /// too expensive to inline)
141   virtual bool shouldStop() { return false; }
142 
143   /// Called before the analysis of the callee body starts (with callsite
144   /// contexts propagated).  It checks callsite-specific information. Return a
145   /// reason analysis can't continue if that's the case, or 'true' if it may
146   /// continue.
147   virtual InlineResult onAnalysisStart() { return InlineResult::success(); }
148   /// Called if the analysis engine decides SROA cannot be done for the given
149   /// alloca.
150   virtual void onDisableSROA(AllocaInst *Arg) {}
151 
152   /// Called the analysis engine determines load elimination won't happen.
153   virtual void onDisableLoadElimination() {}
154 
155   /// Called to account for a call.
156   virtual void onCallPenalty() {}
157 
158   /// Called to account for the expectation the inlining would result in a load
159   /// elimination.
160   virtual void onLoadEliminationOpportunity() {}
161 
162   /// Called to account for the cost of argument setup for the Call in the
163   /// callee's body (not the callsite currently under analysis).
164   virtual void onCallArgumentSetup(const CallBase &Call) {}
165 
166   /// Called to account for a load relative intrinsic.
167   virtual void onLoadRelativeIntrinsic() {}
168 
169   /// Called to account for a lowered call.
170   virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) {
171   }
172 
173   /// Account for a jump table of given size. Return false to stop further
174   /// processing the switch instruction
175   virtual bool onJumpTable(unsigned JumpTableSize) { return true; }
176 
177   /// Account for a case cluster of given size. Return false to stop further
178   /// processing of the instruction.
179   virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; }
180 
181   /// Called at the end of processing a switch instruction, with the given
182   /// number of case clusters.
183   virtual void onFinalizeSwitch(unsigned JumpTableSize,
184                                 unsigned NumCaseCluster) {}
185 
186   /// Called to account for any other instruction not specifically accounted
187   /// for.
188   virtual void onMissedSimplification() {}
189 
190   /// Start accounting potential benefits due to SROA for the given alloca.
191   virtual void onInitializeSROAArg(AllocaInst *Arg) {}
192 
193   /// Account SROA savings for the AllocaInst value.
194   virtual void onAggregateSROAUse(AllocaInst *V) {}
195 
196   bool handleSROA(Value *V, bool DoNotDisable) {
197     // Check for SROA candidates in comparisons.
198     if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
199       if (DoNotDisable) {
200         onAggregateSROAUse(SROAArg);
201         return true;
202       }
203       disableSROAForArg(SROAArg);
204     }
205     return false;
206   }
207 
208   bool IsCallerRecursive = false;
209   bool IsRecursiveCall = false;
210   bool ExposesReturnsTwice = false;
211   bool HasDynamicAlloca = false;
212   bool ContainsNoDuplicateCall = false;
213   bool HasReturn = false;
214   bool HasIndirectBr = false;
215   bool HasUninlineableIntrinsic = false;
216   bool InitsVargArgs = false;
217 
218   /// Number of bytes allocated statically by the callee.
219   uint64_t AllocatedSize = 0;
220   unsigned NumInstructions = 0;
221   unsigned NumVectorInstructions = 0;
222 
223   /// While we walk the potentially-inlined instructions, we build up and
224   /// maintain a mapping of simplified values specific to this callsite. The
225   /// idea is to propagate any special information we have about arguments to
226   /// this call through the inlinable section of the function, and account for
227   /// likely simplifications post-inlining. The most important aspect we track
228   /// is CFG altering simplifications -- when we prove a basic block dead, that
229   /// can cause dramatic shifts in the cost of inlining a function.
230   DenseMap<Value *, Constant *> SimplifiedValues;
231 
232   /// Keep track of the values which map back (through function arguments) to
233   /// allocas on the caller stack which could be simplified through SROA.
234   DenseMap<Value *, AllocaInst *> SROAArgValues;
235 
236   /// Keep track of Allocas for which we believe we may get SROA optimization.
237   DenseSet<AllocaInst *> EnabledSROAAllocas;
238 
239   /// Keep track of values which map to a pointer base and constant offset.
240   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
241 
242   /// Keep track of dead blocks due to the constant arguments.
243   SetVector<BasicBlock *> DeadBlocks;
244 
245   /// The mapping of the blocks to their known unique successors due to the
246   /// constant arguments.
247   DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
248 
249   /// Model the elimination of repeated loads that is expected to happen
250   /// whenever we simplify away the stores that would otherwise cause them to be
251   /// loads.
252   bool EnableLoadElimination;
253   SmallPtrSet<Value *, 16> LoadAddrSet;
254 
255   AllocaInst *getSROAArgForValueOrNull(Value *V) const {
256     auto It = SROAArgValues.find(V);
257     if (It == SROAArgValues.end() || EnabledSROAAllocas.count(It->second) == 0)
258       return nullptr;
259     return It->second;
260   }
261 
262   // Custom simplification helper routines.
263   bool isAllocaDerivedArg(Value *V);
264   void disableSROAForArg(AllocaInst *SROAArg);
265   void disableSROA(Value *V);
266   void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
267   void disableLoadElimination();
268   bool isGEPFree(GetElementPtrInst &GEP);
269   bool canFoldInboundsGEP(GetElementPtrInst &I);
270   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
271   bool simplifyCallSite(Function *F, CallBase &Call);
272   template <typename Callable>
273   bool simplifyInstruction(Instruction &I, Callable Evaluate);
274   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
275 
276   /// Return true if the given argument to the function being considered for
277   /// inlining has the given attribute set either at the call site or the
278   /// function declaration.  Primarily used to inspect call site specific
279   /// attributes since these can be more precise than the ones on the callee
280   /// itself.
281   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
282 
283   /// Return true if the given value is known non null within the callee if
284   /// inlined through this particular callsite.
285   bool isKnownNonNullInCallee(Value *V);
286 
287   /// Return true if size growth is allowed when inlining the callee at \p Call.
288   bool allowSizeGrowth(CallBase &Call);
289 
290   // Custom analysis routines.
291   InlineResult analyzeBlock(BasicBlock *BB,
292                             SmallPtrSetImpl<const Value *> &EphValues);
293 
294   // Disable several entry points to the visitor so we don't accidentally use
295   // them by declaring but not defining them here.
296   void visit(Module *);
297   void visit(Module &);
298   void visit(Function *);
299   void visit(Function &);
300   void visit(BasicBlock *);
301   void visit(BasicBlock &);
302 
303   // Provide base case for our instruction visit.
304   bool visitInstruction(Instruction &I);
305 
306   // Our visit overrides.
307   bool visitAlloca(AllocaInst &I);
308   bool visitPHI(PHINode &I);
309   bool visitGetElementPtr(GetElementPtrInst &I);
310   bool visitBitCast(BitCastInst &I);
311   bool visitPtrToInt(PtrToIntInst &I);
312   bool visitIntToPtr(IntToPtrInst &I);
313   bool visitCastInst(CastInst &I);
314   bool visitUnaryInstruction(UnaryInstruction &I);
315   bool visitCmpInst(CmpInst &I);
316   bool visitSub(BinaryOperator &I);
317   bool visitBinaryOperator(BinaryOperator &I);
318   bool visitFNeg(UnaryOperator &I);
319   bool visitLoad(LoadInst &I);
320   bool visitStore(StoreInst &I);
321   bool visitExtractValue(ExtractValueInst &I);
322   bool visitInsertValue(InsertValueInst &I);
323   bool visitCallBase(CallBase &Call);
324   bool visitReturnInst(ReturnInst &RI);
325   bool visitBranchInst(BranchInst &BI);
326   bool visitSelectInst(SelectInst &SI);
327   bool visitSwitchInst(SwitchInst &SI);
328   bool visitIndirectBrInst(IndirectBrInst &IBI);
329   bool visitResumeInst(ResumeInst &RI);
330   bool visitCleanupReturnInst(CleanupReturnInst &RI);
331   bool visitCatchReturnInst(CatchReturnInst &RI);
332   bool visitUnreachableInst(UnreachableInst &I);
333 
334 public:
335   CallAnalyzer(const TargetTransformInfo &TTI,
336                std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
337                Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI,
338                ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE,
339                Function &Callee, CallBase &Call)
340       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
341         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
342         CandidateCall(Call), EnableLoadElimination(true) {}
343 
344   InlineResult analyze();
345 
346   // Keep a bunch of stats about the cost savings found so we can print them
347   // out when debugging.
348   unsigned NumConstantArgs = 0;
349   unsigned NumConstantOffsetPtrArgs = 0;
350   unsigned NumAllocaArgs = 0;
351   unsigned NumConstantPtrCmps = 0;
352   unsigned NumConstantPtrDiffs = 0;
353   unsigned NumInstructionsSimplified = 0;
354 
355   void dump();
356 };
357 
358 /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
359 /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
360 class InlineCostCallAnalyzer final : public CallAnalyzer {
361   const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
362   const bool ComputeFullInlineCost;
363   int LoadEliminationCost = 0;
364   /// Bonus to be applied when percentage of vector instructions in callee is
365   /// high (see more details in updateThreshold).
366   int VectorBonus = 0;
367   /// Bonus to be applied when the callee has only one reachable basic block.
368   int SingleBBBonus = 0;
369 
370   /// Tunable parameters that control the analysis.
371   const InlineParams &Params;
372 
373   /// Upper bound for the inlining cost. Bonuses are being applied to account
374   /// for speculative "expected profit" of the inlining decision.
375   int Threshold = 0;
376 
377   /// Attempt to evaluate indirect calls to boost its inline cost.
378   const bool BoostIndirectCalls;
379 
380   /// Inlining cost measured in abstract units, accounts for all the
381   /// instructions expected to be executed for a given function invocation.
382   /// Instructions that are statically proven to be dead based on call-site
383   /// arguments are not counted here.
384   int Cost = 0;
385 
386   bool SingleBB = true;
387 
388   unsigned SROACostSavings = 0;
389   unsigned SROACostSavingsLost = 0;
390 
391   /// The mapping of caller Alloca values to their accumulated cost savings. If
392   /// we have to disable SROA for one of the allocas, this tells us how much
393   /// cost must be added.
394   DenseMap<AllocaInst *, int> SROAArgCosts;
395 
396   /// Return true if \p Call is a cold callsite.
397   bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
398 
399   /// Update Threshold based on callsite properties such as callee
400   /// attributes and callee hotness for PGO builds. The Callee is explicitly
401   /// passed to support analyzing indirect calls whose target is inferred by
402   /// analysis.
403   void updateThreshold(CallBase &Call, Function &Callee);
404   /// Return a higher threshold if \p Call is a hot callsite.
405   Optional<int> getHotCallSiteThreshold(CallBase &Call,
406                                         BlockFrequencyInfo *CallerBFI);
407 
408   /// Handle a capped 'int' increment for Cost.
409   void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
410     assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound");
411     Cost = (int)std::min(UpperBound, Cost + Inc);
412   }
413 
414   void onDisableSROA(AllocaInst *Arg) override {
415     auto CostIt = SROAArgCosts.find(Arg);
416     if (CostIt == SROAArgCosts.end())
417       return;
418     addCost(CostIt->second);
419     SROACostSavings -= CostIt->second;
420     SROACostSavingsLost += CostIt->second;
421     SROAArgCosts.erase(CostIt);
422   }
423 
424   void onDisableLoadElimination() override {
425     addCost(LoadEliminationCost);
426     LoadEliminationCost = 0;
427   }
428   void onCallPenalty() override { addCost(InlineConstants::CallPenalty); }
429   void onCallArgumentSetup(const CallBase &Call) override {
430     // Pay the price of the argument setup. We account for the average 1
431     // instruction per call argument setup here.
432     addCost(Call.arg_size() * InlineConstants::InstrCost);
433   }
434   void onLoadRelativeIntrinsic() override {
435     // This is normally lowered to 4 LLVM instructions.
436     addCost(3 * InlineConstants::InstrCost);
437   }
438   void onLoweredCall(Function *F, CallBase &Call,
439                      bool IsIndirectCall) override {
440     // We account for the average 1 instruction per call argument setup here.
441     addCost(Call.arg_size() * InlineConstants::InstrCost);
442 
443     // If we have a constant that we are calling as a function, we can peer
444     // through it and see the function target. This happens not infrequently
445     // during devirtualization and so we want to give it a hefty bonus for
446     // inlining, but cap that bonus in the event that inlining wouldn't pan out.
447     // Pretend to inline the function, with a custom threshold.
448     if (IsIndirectCall && BoostIndirectCalls) {
449       auto IndirectCallParams = Params;
450       IndirectCallParams.DefaultThreshold =
451           InlineConstants::IndirectCallThreshold;
452       /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
453       /// to instantiate the derived class.
454       InlineCostCallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F,
455                                 Call, IndirectCallParams, false);
456       if (CA.analyze().isSuccess()) {
457         // We were able to inline the indirect call! Subtract the cost from the
458         // threshold to get the bonus we want to apply, but don't go below zero.
459         Cost -= std::max(0, CA.getThreshold() - CA.getCost());
460       }
461     } else
462       // Otherwise simply add the cost for merely making the call.
463       addCost(InlineConstants::CallPenalty);
464   }
465 
466   void onFinalizeSwitch(unsigned JumpTableSize,
467                         unsigned NumCaseCluster) override {
468     // If suitable for a jump table, consider the cost for the table size and
469     // branch to destination.
470     // Maximum valid cost increased in this function.
471     if (JumpTableSize) {
472       int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
473                        4 * InlineConstants::InstrCost;
474 
475       addCost(JTCost, (int64_t)CostUpperBound);
476       return;
477     }
478     // Considering forming a binary search, we should find the number of nodes
479     // which is same as the number of comparisons when lowered. For a given
480     // number of clusters, n, we can define a recursive function, f(n), to find
481     // the number of nodes in the tree. The recursion is :
482     // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
483     // and f(n) = n, when n <= 3.
484     // This will lead a binary tree where the leaf should be either f(2) or f(3)
485     // when n > 3.  So, the number of comparisons from leaves should be n, while
486     // the number of non-leaf should be :
487     //   2^(log2(n) - 1) - 1
488     //   = 2^log2(n) * 2^-1 - 1
489     //   = n / 2 - 1.
490     // Considering comparisons from leaf and non-leaf nodes, we can estimate the
491     // number of comparisons in a simple closed form :
492     //   n + n / 2 - 1 = n * 3 / 2 - 1
493     if (NumCaseCluster <= 3) {
494       // Suppose a comparison includes one compare and one conditional branch.
495       addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
496       return;
497     }
498 
499     int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1;
500     int64_t SwitchCost =
501         ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
502 
503     addCost(SwitchCost, (int64_t)CostUpperBound);
504   }
505   void onMissedSimplification() override {
506     addCost(InlineConstants::InstrCost);
507   }
508 
509   void onInitializeSROAArg(AllocaInst *Arg) override {
510     assert(Arg != nullptr &&
511            "Should not initialize SROA costs for null value.");
512     SROAArgCosts[Arg] = 0;
513   }
514 
515   void onAggregateSROAUse(AllocaInst *SROAArg) override {
516     auto CostIt = SROAArgCosts.find(SROAArg);
517     assert(CostIt != SROAArgCosts.end() &&
518            "expected this argument to have a cost");
519     CostIt->second += InlineConstants::InstrCost;
520     SROACostSavings += InlineConstants::InstrCost;
521   }
522 
523   void onBlockAnalyzed(const BasicBlock *BB) override {
524     auto *TI = BB->getTerminator();
525     // If we had any successors at this point, than post-inlining is likely to
526     // have them as well. Note that we assume any basic blocks which existed
527     // due to branches or switches which folded above will also fold after
528     // inlining.
529     if (SingleBB && TI->getNumSuccessors() > 1) {
530       // Take off the bonus we applied to the threshold.
531       Threshold -= SingleBBBonus;
532       SingleBB = false;
533     }
534   }
535 
536   InlineResult finalizeAnalysis() override {
537     // Loops generally act a lot like calls in that they act like barriers to
538     // movement, require a certain amount of setup, etc. So when optimising for
539     // size, we penalise any call sites that perform loops. We do this after all
540     // other costs here, so will likely only be dealing with relatively small
541     // functions (and hence DT and LI will hopefully be cheap).
542     auto *Caller = CandidateCall.getFunction();
543     if (Caller->hasMinSize()) {
544       DominatorTree DT(F);
545       LoopInfo LI(DT);
546       int NumLoops = 0;
547       for (Loop *L : LI) {
548         // Ignore loops that will not be executed
549         if (DeadBlocks.count(L->getHeader()))
550           continue;
551         NumLoops++;
552       }
553       addCost(NumLoops * InlineConstants::CallPenalty);
554     }
555 
556     // We applied the maximum possible vector bonus at the beginning. Now,
557     // subtract the excess bonus, if any, from the Threshold before
558     // comparing against Cost.
559     if (NumVectorInstructions <= NumInstructions / 10)
560       Threshold -= VectorBonus;
561     else if (NumVectorInstructions <= NumInstructions / 2)
562       Threshold -= VectorBonus / 2;
563 
564     if (Cost < std::max(1, Threshold))
565       return InlineResult::success();
566     return InlineResult::failure("Cost over threshold.");
567   }
568   bool shouldStop() override {
569     // Bail out the moment we cross the threshold. This means we'll under-count
570     // the cost, but only when undercounting doesn't matter.
571     return Cost >= Threshold && !ComputeFullInlineCost;
572   }
573 
574   void onLoadEliminationOpportunity() override {
575     LoadEliminationCost += InlineConstants::InstrCost;
576   }
577 
578   InlineResult onAnalysisStart() override {
579     // Perform some tweaks to the cost and threshold based on the direct
580     // callsite information.
581 
582     // We want to more aggressively inline vector-dense kernels, so up the
583     // threshold, and we'll lower it if the % of vector instructions gets too
584     // low. Note that these bonuses are some what arbitrary and evolved over
585     // time by accident as much as because they are principled bonuses.
586     //
587     // FIXME: It would be nice to remove all such bonuses. At least it would be
588     // nice to base the bonus values on something more scientific.
589     assert(NumInstructions == 0);
590     assert(NumVectorInstructions == 0);
591 
592     // Update the threshold based on callsite properties
593     updateThreshold(CandidateCall, F);
594 
595     // While Threshold depends on commandline options that can take negative
596     // values, we want to enforce the invariant that the computed threshold and
597     // bonuses are non-negative.
598     assert(Threshold >= 0);
599     assert(SingleBBBonus >= 0);
600     assert(VectorBonus >= 0);
601 
602     // Speculatively apply all possible bonuses to Threshold. If cost exceeds
603     // this Threshold any time, and cost cannot decrease, we can stop processing
604     // the rest of the function body.
605     Threshold += (SingleBBBonus + VectorBonus);
606 
607     // Give out bonuses for the callsite, as the instructions setting them up
608     // will be gone after inlining.
609     addCost(-getCallsiteCost(this->CandidateCall, DL));
610 
611     // If this function uses the coldcc calling convention, prefer not to inline
612     // it.
613     if (F.getCallingConv() == CallingConv::Cold)
614       Cost += InlineConstants::ColdccPenalty;
615 
616     // Check if we're done. This can happen due to bonuses and penalties.
617     if (Cost >= Threshold && !ComputeFullInlineCost)
618       return InlineResult::failure("high cost");
619 
620     return InlineResult::success();
621   }
622 
623 public:
624   InlineCostCallAnalyzer(
625       const TargetTransformInfo &TTI,
626       std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
627       Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI,
628       ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee,
629       CallBase &Call, const InlineParams &Params, bool BoostIndirect = true)
630       : CallAnalyzer(TTI, GetAssumptionCache, GetBFI, PSI, ORE, Callee, Call),
631         ComputeFullInlineCost(OptComputeFullInlineCost ||
632                               Params.ComputeFullInlineCost || ORE),
633         Params(Params), Threshold(Params.DefaultThreshold),
634         BoostIndirectCalls(BoostIndirect) {}
635   void dump();
636 
637   virtual ~InlineCostCallAnalyzer() {}
638   int getThreshold() { return Threshold; }
639   int getCost() { return Cost; }
640 };
641 } // namespace
642 
643 /// Test whether the given value is an Alloca-derived function argument.
644 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
645   return SROAArgValues.count(V);
646 }
647 
648 void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
649   onDisableSROA(SROAArg);
650   EnabledSROAAllocas.erase(SROAArg);
651   disableLoadElimination();
652 }
653 /// If 'V' maps to a SROA candidate, disable SROA for it.
654 void CallAnalyzer::disableSROA(Value *V) {
655   if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
656     disableSROAForArg(SROAArg);
657   }
658 }
659 
660 void CallAnalyzer::disableLoadElimination() {
661   if (EnableLoadElimination) {
662     onDisableLoadElimination();
663     EnableLoadElimination = false;
664   }
665 }
666 
667 /// Accumulate a constant GEP offset into an APInt if possible.
668 ///
669 /// Returns false if unable to compute the offset for any reason. Respects any
670 /// simplified values known during the analysis of this callsite.
671 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
672   unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
673   assert(IntPtrWidth == Offset.getBitWidth());
674 
675   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
676        GTI != GTE; ++GTI) {
677     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
678     if (!OpC)
679       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
680         OpC = dyn_cast<ConstantInt>(SimpleOp);
681     if (!OpC)
682       return false;
683     if (OpC->isZero())
684       continue;
685 
686     // Handle a struct index, which adds its field offset to the pointer.
687     if (StructType *STy = GTI.getStructTypeOrNull()) {
688       unsigned ElementIdx = OpC->getZExtValue();
689       const StructLayout *SL = DL.getStructLayout(STy);
690       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
691       continue;
692     }
693 
694     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
695     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
696   }
697   return true;
698 }
699 
700 /// Use TTI to check whether a GEP is free.
701 ///
702 /// Respects any simplified values known during the analysis of this callsite.
703 bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
704   SmallVector<Value *, 4> Operands;
705   Operands.push_back(GEP.getOperand(0));
706   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
707     if (Constant *SimpleOp = SimplifiedValues.lookup(*I))
708       Operands.push_back(SimpleOp);
709     else
710       Operands.push_back(*I);
711   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands);
712 }
713 
714 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
715   // Check whether inlining will turn a dynamic alloca into a static
716   // alloca and handle that case.
717   if (I.isArrayAllocation()) {
718     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
719     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
720       Type *Ty = I.getAllocatedType();
721       AllocatedSize = SaturatingMultiplyAdd(
722           AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty).getFixedSize(),
723           AllocatedSize);
724       return Base::visitAlloca(I);
725     }
726   }
727 
728   // Accumulate the allocated size.
729   if (I.isStaticAlloca()) {
730     Type *Ty = I.getAllocatedType();
731     AllocatedSize =
732         SaturatingAdd(DL.getTypeAllocSize(Ty).getFixedSize(), AllocatedSize);
733   }
734 
735   // We will happily inline static alloca instructions.
736   if (I.isStaticAlloca())
737     return Base::visitAlloca(I);
738 
739   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
740   // a variety of reasons, and so we would like to not inline them into
741   // functions which don't currently have a dynamic alloca. This simply
742   // disables inlining altogether in the presence of a dynamic alloca.
743   HasDynamicAlloca = true;
744   return false;
745 }
746 
747 bool CallAnalyzer::visitPHI(PHINode &I) {
748   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
749   // though we don't want to propagate it's bonuses. The idea is to disable
750   // SROA if it *might* be used in an inappropriate manner.
751 
752   // Phi nodes are always zero-cost.
753   // FIXME: Pointer sizes may differ between different address spaces, so do we
754   // need to use correct address space in the call to getPointerSizeInBits here?
755   // Or could we skip the getPointerSizeInBits call completely? As far as I can
756   // see the ZeroOffset is used as a dummy value, so we can probably use any
757   // bit width for the ZeroOffset?
758   APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0));
759   bool CheckSROA = I.getType()->isPointerTy();
760 
761   // Track the constant or pointer with constant offset we've seen so far.
762   Constant *FirstC = nullptr;
763   std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
764   Value *FirstV = nullptr;
765 
766   for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
767     BasicBlock *Pred = I.getIncomingBlock(i);
768     // If the incoming block is dead, skip the incoming block.
769     if (DeadBlocks.count(Pred))
770       continue;
771     // If the parent block of phi is not the known successor of the incoming
772     // block, skip the incoming block.
773     BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
774     if (KnownSuccessor && KnownSuccessor != I.getParent())
775       continue;
776 
777     Value *V = I.getIncomingValue(i);
778     // If the incoming value is this phi itself, skip the incoming value.
779     if (&I == V)
780       continue;
781 
782     Constant *C = dyn_cast<Constant>(V);
783     if (!C)
784       C = SimplifiedValues.lookup(V);
785 
786     std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
787     if (!C && CheckSROA)
788       BaseAndOffset = ConstantOffsetPtrs.lookup(V);
789 
790     if (!C && !BaseAndOffset.first)
791       // The incoming value is neither a constant nor a pointer with constant
792       // offset, exit early.
793       return true;
794 
795     if (FirstC) {
796       if (FirstC == C)
797         // If we've seen a constant incoming value before and it is the same
798         // constant we see this time, continue checking the next incoming value.
799         continue;
800       // Otherwise early exit because we either see a different constant or saw
801       // a constant before but we have a pointer with constant offset this time.
802       return true;
803     }
804 
805     if (FirstV) {
806       // The same logic as above, but check pointer with constant offset here.
807       if (FirstBaseAndOffset == BaseAndOffset)
808         continue;
809       return true;
810     }
811 
812     if (C) {
813       // This is the 1st time we've seen a constant, record it.
814       FirstC = C;
815       continue;
816     }
817 
818     // The remaining case is that this is the 1st time we've seen a pointer with
819     // constant offset, record it.
820     FirstV = V;
821     FirstBaseAndOffset = BaseAndOffset;
822   }
823 
824   // Check if we can map phi to a constant.
825   if (FirstC) {
826     SimplifiedValues[&I] = FirstC;
827     return true;
828   }
829 
830   // Check if we can map phi to a pointer with constant offset.
831   if (FirstBaseAndOffset.first) {
832     ConstantOffsetPtrs[&I] = FirstBaseAndOffset;
833 
834     if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
835       SROAArgValues[&I] = SROAArg;
836   }
837 
838   return true;
839 }
840 
841 /// Check we can fold GEPs of constant-offset call site argument pointers.
842 /// This requires target data and inbounds GEPs.
843 ///
844 /// \return true if the specified GEP can be folded.
845 bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
846   // Check if we have a base + offset for the pointer.
847   std::pair<Value *, APInt> BaseAndOffset =
848       ConstantOffsetPtrs.lookup(I.getPointerOperand());
849   if (!BaseAndOffset.first)
850     return false;
851 
852   // Check if the offset of this GEP is constant, and if so accumulate it
853   // into Offset.
854   if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
855     return false;
856 
857   // Add the result as a new mapping to Base + Offset.
858   ConstantOffsetPtrs[&I] = BaseAndOffset;
859 
860   return true;
861 }
862 
863 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
864   auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
865 
866   // Lambda to check whether a GEP's indices are all constant.
867   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
868     for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
869       if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
870         return false;
871     return true;
872   };
873 
874   if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
875     if (SROAArg)
876       SROAArgValues[&I] = SROAArg;
877 
878     // Constant GEPs are modeled as free.
879     return true;
880   }
881 
882   // Variable GEPs will require math and will disable SROA.
883   if (SROAArg)
884     disableSROAForArg(SROAArg);
885   return isGEPFree(I);
886 }
887 
888 /// Simplify \p I if its operands are constants and update SimplifiedValues.
889 /// \p Evaluate is a callable specific to instruction type that evaluates the
890 /// instruction when all the operands are constants.
891 template <typename Callable>
892 bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
893   SmallVector<Constant *, 2> COps;
894   for (Value *Op : I.operands()) {
895     Constant *COp = dyn_cast<Constant>(Op);
896     if (!COp)
897       COp = SimplifiedValues.lookup(Op);
898     if (!COp)
899       return false;
900     COps.push_back(COp);
901   }
902   auto *C = Evaluate(COps);
903   if (!C)
904     return false;
905   SimplifiedValues[&I] = C;
906   return true;
907 }
908 
909 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
910   // Propagate constants through bitcasts.
911   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
912         return ConstantExpr::getBitCast(COps[0], I.getType());
913       }))
914     return true;
915 
916   // Track base/offsets through casts
917   std::pair<Value *, APInt> BaseAndOffset =
918       ConstantOffsetPtrs.lookup(I.getOperand(0));
919   // Casts don't change the offset, just wrap it up.
920   if (BaseAndOffset.first)
921     ConstantOffsetPtrs[&I] = BaseAndOffset;
922 
923   // Also look for SROA candidates here.
924   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
925     SROAArgValues[&I] = SROAArg;
926 
927   // Bitcasts are always zero cost.
928   return true;
929 }
930 
931 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
932   // Propagate constants through ptrtoint.
933   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
934         return ConstantExpr::getPtrToInt(COps[0], I.getType());
935       }))
936     return true;
937 
938   // Track base/offset pairs when converted to a plain integer provided the
939   // integer is large enough to represent the pointer.
940   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
941   unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
942   if (IntegerSize >= DL.getPointerSizeInBits(AS)) {
943     std::pair<Value *, APInt> BaseAndOffset =
944         ConstantOffsetPtrs.lookup(I.getOperand(0));
945     if (BaseAndOffset.first)
946       ConstantOffsetPtrs[&I] = BaseAndOffset;
947   }
948 
949   // This is really weird. Technically, ptrtoint will disable SROA. However,
950   // unless that ptrtoint is *used* somewhere in the live basic blocks after
951   // inlining, it will be nuked, and SROA should proceed. All of the uses which
952   // would block SROA would also block SROA if applied directly to a pointer,
953   // and so we can just add the integer in here. The only places where SROA is
954   // preserved either cannot fire on an integer, or won't in-and-of themselves
955   // disable SROA (ext) w/o some later use that we would see and disable.
956   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
957     SROAArgValues[&I] = SROAArg;
958 
959   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
960 }
961 
962 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
963   // Propagate constants through ptrtoint.
964   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
965         return ConstantExpr::getIntToPtr(COps[0], I.getType());
966       }))
967     return true;
968 
969   // Track base/offset pairs when round-tripped through a pointer without
970   // modifications provided the integer is not too large.
971   Value *Op = I.getOperand(0);
972   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
973   if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
974     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
975     if (BaseAndOffset.first)
976       ConstantOffsetPtrs[&I] = BaseAndOffset;
977   }
978 
979   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
980   if (auto *SROAArg = getSROAArgForValueOrNull(Op))
981     SROAArgValues[&I] = SROAArg;
982 
983   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
984 }
985 
986 bool CallAnalyzer::visitCastInst(CastInst &I) {
987   // Propagate constants through casts.
988   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
989         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
990       }))
991     return true;
992 
993   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
994   disableSROA(I.getOperand(0));
995 
996   // If this is a floating-point cast, and the target says this operation
997   // is expensive, this may eventually become a library call. Treat the cost
998   // as such.
999   switch (I.getOpcode()) {
1000   case Instruction::FPTrunc:
1001   case Instruction::FPExt:
1002   case Instruction::UIToFP:
1003   case Instruction::SIToFP:
1004   case Instruction::FPToUI:
1005   case Instruction::FPToSI:
1006     if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive)
1007       onCallPenalty();
1008     break;
1009   default:
1010     break;
1011   }
1012 
1013   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
1014 }
1015 
1016 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
1017   Value *Operand = I.getOperand(0);
1018   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1019         return ConstantFoldInstOperands(&I, COps[0], DL);
1020       }))
1021     return true;
1022 
1023   // Disable any SROA on the argument to arbitrary unary instructions.
1024   disableSROA(Operand);
1025 
1026   return false;
1027 }
1028 
1029 bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1030   return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
1031 }
1032 
1033 bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
1034   // Does the *call site* have the NonNull attribute set on an argument?  We
1035   // use the attribute on the call site to memoize any analysis done in the
1036   // caller. This will also trip if the callee function has a non-null
1037   // parameter attribute, but that's a less interesting case because hopefully
1038   // the callee would already have been simplified based on that.
1039   if (Argument *A = dyn_cast<Argument>(V))
1040     if (paramHasAttr(A, Attribute::NonNull))
1041       return true;
1042 
1043   // Is this an alloca in the caller?  This is distinct from the attribute case
1044   // above because attributes aren't updated within the inliner itself and we
1045   // always want to catch the alloca derived case.
1046   if (isAllocaDerivedArg(V))
1047     // We can actually predict the result of comparisons between an
1048     // alloca-derived value and null. Note that this fires regardless of
1049     // SROA firing.
1050     return true;
1051 
1052   return false;
1053 }
1054 
1055 bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
1056   // If the normal destination of the invoke or the parent block of the call
1057   // site is unreachable-terminated, there is little point in inlining this
1058   // unless there is literally zero cost.
1059   // FIXME: Note that it is possible that an unreachable-terminated block has a
1060   // hot entry. For example, in below scenario inlining hot_call_X() may be
1061   // beneficial :
1062   // main() {
1063   //   hot_call_1();
1064   //   ...
1065   //   hot_call_N()
1066   //   exit(0);
1067   // }
1068   // For now, we are not handling this corner case here as it is rare in real
1069   // code. In future, we should elaborate this based on BPI and BFI in more
1070   // general threshold adjusting heuristics in updateThreshold().
1071   if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
1072     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
1073       return false;
1074   } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
1075     return false;
1076 
1077   return true;
1078 }
1079 
1080 bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1081                                             BlockFrequencyInfo *CallerBFI) {
1082   // If global profile summary is available, then callsite's coldness is
1083   // determined based on that.
1084   if (PSI && PSI->hasProfileSummary())
1085     return PSI->isColdCallSite(CallSite(&Call), CallerBFI);
1086 
1087   // Otherwise we need BFI to be available.
1088   if (!CallerBFI)
1089     return false;
1090 
1091   // Determine if the callsite is cold relative to caller's entry. We could
1092   // potentially cache the computation of scaled entry frequency, but the added
1093   // complexity is not worth it unless this scaling shows up high in the
1094   // profiles.
1095   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
1096   auto CallSiteBB = Call.getParent();
1097   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1098   auto CallerEntryFreq =
1099       CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1100   return CallSiteFreq < CallerEntryFreq * ColdProb;
1101 }
1102 
1103 Optional<int>
1104 InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1105                                                 BlockFrequencyInfo *CallerBFI) {
1106 
1107   // If global profile summary is available, then callsite's hotness is
1108   // determined based on that.
1109   if (PSI && PSI->hasProfileSummary() &&
1110       PSI->isHotCallSite(CallSite(&Call), CallerBFI))
1111     return Params.HotCallSiteThreshold;
1112 
1113   // Otherwise we need BFI to be available and to have a locally hot callsite
1114   // threshold.
1115   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1116     return None;
1117 
1118   // Determine if the callsite is hot relative to caller's entry. We could
1119   // potentially cache the computation of scaled entry frequency, but the added
1120   // complexity is not worth it unless this scaling shows up high in the
1121   // profiles.
1122   auto CallSiteBB = Call.getParent();
1123   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
1124   auto CallerEntryFreq = CallerBFI->getEntryFreq();
1125   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
1126     return Params.LocallyHotCallSiteThreshold;
1127 
1128   // Otherwise treat it normally.
1129   return None;
1130 }
1131 
1132 void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
1133   // If no size growth is allowed for this inlining, set Threshold to 0.
1134   if (!allowSizeGrowth(Call)) {
1135     Threshold = 0;
1136     return;
1137   }
1138 
1139   Function *Caller = Call.getCaller();
1140 
1141   // return min(A, B) if B is valid.
1142   auto MinIfValid = [](int A, Optional<int> B) {
1143     return B ? std::min(A, B.getValue()) : A;
1144   };
1145 
1146   // return max(A, B) if B is valid.
1147   auto MaxIfValid = [](int A, Optional<int> B) {
1148     return B ? std::max(A, B.getValue()) : A;
1149   };
1150 
1151   // Various bonus percentages. These are multiplied by Threshold to get the
1152   // bonus values.
1153   // SingleBBBonus: This bonus is applied if the callee has a single reachable
1154   // basic block at the given callsite context. This is speculatively applied
1155   // and withdrawn if more than one basic block is seen.
1156   //
1157   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
1158   // of the last call to a static function as inlining such functions is
1159   // guaranteed to reduce code size.
1160   //
1161   // These bonus percentages may be set to 0 based on properties of the caller
1162   // and the callsite.
1163   int SingleBBBonusPercent = 50;
1164   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
1165   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
1166 
1167   // Lambda to set all the above bonus and bonus percentages to 0.
1168   auto DisallowAllBonuses = [&]() {
1169     SingleBBBonusPercent = 0;
1170     VectorBonusPercent = 0;
1171     LastCallToStaticBonus = 0;
1172   };
1173 
1174   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
1175   // and reduce the threshold if the caller has the necessary attribute.
1176   if (Caller->hasMinSize()) {
1177     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
1178     // For minsize, we want to disable the single BB bonus and the vector
1179     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
1180     // a static function will, at the minimum, eliminate the parameter setup and
1181     // call/return instructions.
1182     SingleBBBonusPercent = 0;
1183     VectorBonusPercent = 0;
1184   } else if (Caller->hasOptSize())
1185     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
1186 
1187   // Adjust the threshold based on inlinehint attribute and profile based
1188   // hotness information if the caller does not have MinSize attribute.
1189   if (!Caller->hasMinSize()) {
1190     if (Callee.hasFnAttribute(Attribute::InlineHint))
1191       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1192 
1193     // FIXME: After switching to the new passmanager, simplify the logic below
1194     // by checking only the callsite hotness/coldness as we will reliably
1195     // have local profile information.
1196     //
1197     // Callsite hotness and coldness can be determined if sample profile is
1198     // used (which adds hotness metadata to calls) or if caller's
1199     // BlockFrequencyInfo is available.
1200     BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr;
1201     auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
1202     if (!Caller->hasOptSize() && HotCallSiteThreshold) {
1203       LLVM_DEBUG(dbgs() << "Hot callsite.\n");
1204       // FIXME: This should update the threshold only if it exceeds the
1205       // current threshold, but AutoFDO + ThinLTO currently relies on this
1206       // behavior to prevent inlining of hot callsites during ThinLTO
1207       // compile phase.
1208       Threshold = HotCallSiteThreshold.getValue();
1209     } else if (isColdCallSite(Call, CallerBFI)) {
1210       LLVM_DEBUG(dbgs() << "Cold callsite.\n");
1211       // Do not apply bonuses for a cold callsite including the
1212       // LastCallToStatic bonus. While this bonus might result in code size
1213       // reduction, it can cause the size of a non-cold caller to increase
1214       // preventing it from being inlined.
1215       DisallowAllBonuses();
1216       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
1217     } else if (PSI) {
1218       // Use callee's global profile information only if we have no way of
1219       // determining this via callsite information.
1220       if (PSI->isFunctionEntryHot(&Callee)) {
1221         LLVM_DEBUG(dbgs() << "Hot callee.\n");
1222         // If callsite hotness can not be determined, we may still know
1223         // that the callee is hot and treat it as a weaker hint for threshold
1224         // increase.
1225         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1226       } else if (PSI->isFunctionEntryCold(&Callee)) {
1227         LLVM_DEBUG(dbgs() << "Cold callee.\n");
1228         // Do not apply bonuses for a cold callee including the
1229         // LastCallToStatic bonus. While this bonus might result in code size
1230         // reduction, it can cause the size of a non-cold caller to increase
1231         // preventing it from being inlined.
1232         DisallowAllBonuses();
1233         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
1234       }
1235     }
1236   }
1237 
1238   // Finally, take the target-specific inlining threshold multiplier into
1239   // account.
1240   Threshold *= TTI.getInliningThresholdMultiplier();
1241 
1242   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
1243   VectorBonus = Threshold * VectorBonusPercent / 100;
1244 
1245   bool OnlyOneCallAndLocalLinkage =
1246       F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction();
1247   // If there is only one call of the function, and it has internal linkage,
1248   // the cost of inlining it drops dramatically. It may seem odd to update
1249   // Cost in updateThreshold, but the bonus depends on the logic in this method.
1250   if (OnlyOneCallAndLocalLinkage)
1251     Cost -= LastCallToStaticBonus;
1252 }
1253 
1254 bool CallAnalyzer::visitCmpInst(CmpInst &I) {
1255   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1256   // First try to handle simplified comparisons.
1257   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1258         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
1259       }))
1260     return true;
1261 
1262   if (I.getOpcode() == Instruction::FCmp)
1263     return false;
1264 
1265   // Otherwise look for a comparison between constant offset pointers with
1266   // a common base.
1267   Value *LHSBase, *RHSBase;
1268   APInt LHSOffset, RHSOffset;
1269   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
1270   if (LHSBase) {
1271     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
1272     if (RHSBase && LHSBase == RHSBase) {
1273       // We have common bases, fold the icmp to a constant based on the
1274       // offsets.
1275       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
1276       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
1277       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
1278         SimplifiedValues[&I] = C;
1279         ++NumConstantPtrCmps;
1280         return true;
1281       }
1282     }
1283   }
1284 
1285   // If the comparison is an equality comparison with null, we can simplify it
1286   // if we know the value (argument) can't be null
1287   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
1288       isKnownNonNullInCallee(I.getOperand(0))) {
1289     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
1290     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
1291                                       : ConstantInt::getFalse(I.getType());
1292     return true;
1293   }
1294   return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
1295 }
1296 
1297 bool CallAnalyzer::visitSub(BinaryOperator &I) {
1298   // Try to handle a special case: we can fold computing the difference of two
1299   // constant-related pointers.
1300   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1301   Value *LHSBase, *RHSBase;
1302   APInt LHSOffset, RHSOffset;
1303   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
1304   if (LHSBase) {
1305     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
1306     if (RHSBase && LHSBase == RHSBase) {
1307       // We have common bases, fold the subtract to a constant based on the
1308       // offsets.
1309       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
1310       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
1311       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
1312         SimplifiedValues[&I] = C;
1313         ++NumConstantPtrDiffs;
1314         return true;
1315       }
1316     }
1317   }
1318 
1319   // Otherwise, fall back to the generic logic for simplifying and handling
1320   // instructions.
1321   return Base::visitSub(I);
1322 }
1323 
1324 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
1325   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1326   Constant *CLHS = dyn_cast<Constant>(LHS);
1327   if (!CLHS)
1328     CLHS = SimplifiedValues.lookup(LHS);
1329   Constant *CRHS = dyn_cast<Constant>(RHS);
1330   if (!CRHS)
1331     CRHS = SimplifiedValues.lookup(RHS);
1332 
1333   Value *SimpleV = nullptr;
1334   if (auto FI = dyn_cast<FPMathOperator>(&I))
1335     SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
1336                             FI->getFastMathFlags(), DL);
1337   else
1338     SimpleV =
1339         SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
1340 
1341   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
1342     SimplifiedValues[&I] = C;
1343 
1344   if (SimpleV)
1345     return true;
1346 
1347   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
1348   disableSROA(LHS);
1349   disableSROA(RHS);
1350 
1351   // If the instruction is floating point, and the target says this operation
1352   // is expensive, this may eventually become a library call. Treat the cost
1353   // as such. Unless it's fneg which can be implemented with an xor.
1354   using namespace llvm::PatternMatch;
1355   if (I.getType()->isFloatingPointTy() &&
1356       TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive &&
1357       !match(&I, m_FNeg(m_Value())))
1358     onCallPenalty();
1359 
1360   return false;
1361 }
1362 
1363 bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
1364   Value *Op = I.getOperand(0);
1365   Constant *COp = dyn_cast<Constant>(Op);
1366   if (!COp)
1367     COp = SimplifiedValues.lookup(Op);
1368 
1369   Value *SimpleV = SimplifyFNegInst(
1370       COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
1371 
1372   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
1373     SimplifiedValues[&I] = C;
1374 
1375   if (SimpleV)
1376     return true;
1377 
1378   // Disable any SROA on arguments to arbitrary, unsimplified fneg.
1379   disableSROA(Op);
1380 
1381   return false;
1382 }
1383 
1384 bool CallAnalyzer::visitLoad(LoadInst &I) {
1385   if (handleSROA(I.getPointerOperand(), I.isSimple()))
1386     return true;
1387 
1388   // If the data is already loaded from this address and hasn't been clobbered
1389   // by any stores or calls, this load is likely to be redundant and can be
1390   // eliminated.
1391   if (EnableLoadElimination &&
1392       !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
1393     onLoadEliminationOpportunity();
1394     return true;
1395   }
1396 
1397   return false;
1398 }
1399 
1400 bool CallAnalyzer::visitStore(StoreInst &I) {
1401   if (handleSROA(I.getPointerOperand(), I.isSimple()))
1402     return true;
1403 
1404   // The store can potentially clobber loads and prevent repeated loads from
1405   // being eliminated.
1406   // FIXME:
1407   // 1. We can probably keep an initial set of eliminatable loads substracted
1408   // from the cost even when we finally see a store. We just need to disable
1409   // *further* accumulation of elimination savings.
1410   // 2. We should probably at some point thread MemorySSA for the callee into
1411   // this and then use that to actually compute *really* precise savings.
1412   disableLoadElimination();
1413   return false;
1414 }
1415 
1416 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
1417   // Constant folding for extract value is trivial.
1418   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1419         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
1420       }))
1421     return true;
1422 
1423   // SROA can look through these but give them a cost.
1424   return false;
1425 }
1426 
1427 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
1428   // Constant folding for insert value is trivial.
1429   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1430         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
1431                                             /*InsertedValueOperand*/ COps[1],
1432                                             I.getIndices());
1433       }))
1434     return true;
1435 
1436   // SROA can look through these but give them a cost.
1437   return false;
1438 }
1439 
1440 /// Try to simplify a call site.
1441 ///
1442 /// Takes a concrete function and callsite and tries to actually simplify it by
1443 /// analyzing the arguments and call itself with instsimplify. Returns true if
1444 /// it has simplified the callsite to some other entity (a constant), making it
1445 /// free.
1446 bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
1447   // FIXME: Using the instsimplify logic directly for this is inefficient
1448   // because we have to continually rebuild the argument list even when no
1449   // simplifications can be performed. Until that is fixed with remapping
1450   // inside of instsimplify, directly constant fold calls here.
1451   if (!canConstantFoldCallTo(&Call, F))
1452     return false;
1453 
1454   // Try to re-map the arguments to constants.
1455   SmallVector<Constant *, 4> ConstantArgs;
1456   ConstantArgs.reserve(Call.arg_size());
1457   for (Value *I : Call.args()) {
1458     Constant *C = dyn_cast<Constant>(I);
1459     if (!C)
1460       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
1461     if (!C)
1462       return false; // This argument doesn't map to a constant.
1463 
1464     ConstantArgs.push_back(C);
1465   }
1466   if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
1467     SimplifiedValues[&Call] = C;
1468     return true;
1469   }
1470 
1471   return false;
1472 }
1473 
1474 bool CallAnalyzer::visitCallBase(CallBase &Call) {
1475   if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
1476       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
1477     // This aborts the entire analysis.
1478     ExposesReturnsTwice = true;
1479     return false;
1480   }
1481   if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
1482     ContainsNoDuplicateCall = true;
1483 
1484   Value *Callee = Call.getCalledOperand();
1485   Function *F = dyn_cast_or_null<Function>(Callee);
1486   bool IsIndirectCall = !F;
1487   if (IsIndirectCall) {
1488     // Check if this happens to be an indirect function call to a known function
1489     // in this inline context. If not, we've done all we can.
1490     F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
1491     if (!F) {
1492       onCallArgumentSetup(Call);
1493 
1494       if (!Call.onlyReadsMemory())
1495         disableLoadElimination();
1496       return Base::visitCallBase(Call);
1497     }
1498   }
1499 
1500   assert(F && "Expected a call to a known function");
1501 
1502   // When we have a concrete function, first try to simplify it directly.
1503   if (simplifyCallSite(F, Call))
1504     return true;
1505 
1506   // Next check if it is an intrinsic we know about.
1507   // FIXME: Lift this into part of the InstVisitor.
1508   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
1509     switch (II->getIntrinsicID()) {
1510     default:
1511       if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II))
1512         disableLoadElimination();
1513       return Base::visitCallBase(Call);
1514 
1515     case Intrinsic::load_relative:
1516       onLoadRelativeIntrinsic();
1517       return false;
1518 
1519     case Intrinsic::memset:
1520     case Intrinsic::memcpy:
1521     case Intrinsic::memmove:
1522       disableLoadElimination();
1523       // SROA can usually chew through these intrinsics, but they aren't free.
1524       return false;
1525     case Intrinsic::icall_branch_funnel:
1526     case Intrinsic::localescape:
1527       HasUninlineableIntrinsic = true;
1528       return false;
1529     case Intrinsic::vastart:
1530       InitsVargArgs = true;
1531       return false;
1532     }
1533   }
1534 
1535   if (F == Call.getFunction()) {
1536     // This flag will fully abort the analysis, so don't bother with anything
1537     // else.
1538     IsRecursiveCall = true;
1539     return false;
1540   }
1541 
1542   if (TTI.isLoweredToCall(F)) {
1543     onLoweredCall(F, Call, IsIndirectCall);
1544   }
1545 
1546   if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
1547     disableLoadElimination();
1548   return Base::visitCallBase(Call);
1549 }
1550 
1551 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
1552   // At least one return instruction will be free after inlining.
1553   bool Free = !HasReturn;
1554   HasReturn = true;
1555   return Free;
1556 }
1557 
1558 bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
1559   // We model unconditional branches as essentially free -- they really
1560   // shouldn't exist at all, but handling them makes the behavior of the
1561   // inliner more regular and predictable. Interestingly, conditional branches
1562   // which will fold away are also free.
1563   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
1564          dyn_cast_or_null<ConstantInt>(
1565              SimplifiedValues.lookup(BI.getCondition()));
1566 }
1567 
1568 bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
1569   bool CheckSROA = SI.getType()->isPointerTy();
1570   Value *TrueVal = SI.getTrueValue();
1571   Value *FalseVal = SI.getFalseValue();
1572 
1573   Constant *TrueC = dyn_cast<Constant>(TrueVal);
1574   if (!TrueC)
1575     TrueC = SimplifiedValues.lookup(TrueVal);
1576   Constant *FalseC = dyn_cast<Constant>(FalseVal);
1577   if (!FalseC)
1578     FalseC = SimplifiedValues.lookup(FalseVal);
1579   Constant *CondC =
1580       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
1581 
1582   if (!CondC) {
1583     // Select C, X, X => X
1584     if (TrueC == FalseC && TrueC) {
1585       SimplifiedValues[&SI] = TrueC;
1586       return true;
1587     }
1588 
1589     if (!CheckSROA)
1590       return Base::visitSelectInst(SI);
1591 
1592     std::pair<Value *, APInt> TrueBaseAndOffset =
1593         ConstantOffsetPtrs.lookup(TrueVal);
1594     std::pair<Value *, APInt> FalseBaseAndOffset =
1595         ConstantOffsetPtrs.lookup(FalseVal);
1596     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
1597       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
1598 
1599       if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
1600         SROAArgValues[&SI] = SROAArg;
1601       return true;
1602     }
1603 
1604     return Base::visitSelectInst(SI);
1605   }
1606 
1607   // Select condition is a constant.
1608   Value *SelectedV = CondC->isAllOnesValue()
1609                          ? TrueVal
1610                          : (CondC->isNullValue()) ? FalseVal : nullptr;
1611   if (!SelectedV) {
1612     // Condition is a vector constant that is not all 1s or all 0s.  If all
1613     // operands are constants, ConstantExpr::getSelect() can handle the cases
1614     // such as select vectors.
1615     if (TrueC && FalseC) {
1616       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
1617         SimplifiedValues[&SI] = C;
1618         return true;
1619       }
1620     }
1621     return Base::visitSelectInst(SI);
1622   }
1623 
1624   // Condition is either all 1s or all 0s. SI can be simplified.
1625   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
1626     SimplifiedValues[&SI] = SelectedC;
1627     return true;
1628   }
1629 
1630   if (!CheckSROA)
1631     return true;
1632 
1633   std::pair<Value *, APInt> BaseAndOffset =
1634       ConstantOffsetPtrs.lookup(SelectedV);
1635   if (BaseAndOffset.first) {
1636     ConstantOffsetPtrs[&SI] = BaseAndOffset;
1637 
1638     if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
1639       SROAArgValues[&SI] = SROAArg;
1640   }
1641 
1642   return true;
1643 }
1644 
1645 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
1646   // We model unconditional switches as free, see the comments on handling
1647   // branches.
1648   if (isa<ConstantInt>(SI.getCondition()))
1649     return true;
1650   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
1651     if (isa<ConstantInt>(V))
1652       return true;
1653 
1654   // Assume the most general case where the switch is lowered into
1655   // either a jump table, bit test, or a balanced binary tree consisting of
1656   // case clusters without merging adjacent clusters with the same
1657   // destination. We do not consider the switches that are lowered with a mix
1658   // of jump table/bit test/binary search tree. The cost of the switch is
1659   // proportional to the size of the tree or the size of jump table range.
1660   //
1661   // NB: We convert large switches which are just used to initialize large phi
1662   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
1663   // inlining those. It will prevent inlining in cases where the optimization
1664   // does not (yet) fire.
1665 
1666   unsigned JumpTableSize = 0;
1667   BlockFrequencyInfo *BFI = GetBFI ? &((*GetBFI)(F)) : nullptr;
1668   unsigned NumCaseCluster =
1669       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
1670 
1671   onFinalizeSwitch(JumpTableSize, NumCaseCluster);
1672   return false;
1673 }
1674 
1675 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
1676   // We never want to inline functions that contain an indirectbr.  This is
1677   // incorrect because all the blockaddress's (in static global initializers
1678   // for example) would be referring to the original function, and this
1679   // indirect jump would jump from the inlined copy of the function into the
1680   // original function which is extremely undefined behavior.
1681   // FIXME: This logic isn't really right; we can safely inline functions with
1682   // indirectbr's as long as no other function or global references the
1683   // blockaddress of a block within the current function.
1684   HasIndirectBr = true;
1685   return false;
1686 }
1687 
1688 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
1689   // FIXME: It's not clear that a single instruction is an accurate model for
1690   // the inline cost of a resume instruction.
1691   return false;
1692 }
1693 
1694 bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
1695   // FIXME: It's not clear that a single instruction is an accurate model for
1696   // the inline cost of a cleanupret instruction.
1697   return false;
1698 }
1699 
1700 bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
1701   // FIXME: It's not clear that a single instruction is an accurate model for
1702   // the inline cost of a catchret instruction.
1703   return false;
1704 }
1705 
1706 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
1707   // FIXME: It might be reasonably to discount the cost of instructions leading
1708   // to unreachable as they have the lowest possible impact on both runtime and
1709   // code size.
1710   return true; // No actual code is needed for unreachable.
1711 }
1712 
1713 bool CallAnalyzer::visitInstruction(Instruction &I) {
1714   // Some instructions are free. All of the free intrinsics can also be
1715   // handled by SROA, etc.
1716   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
1717     return true;
1718 
1719   // We found something we don't understand or can't handle. Mark any SROA-able
1720   // values in the operand list as no longer viable.
1721   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
1722     disableSROA(*OI);
1723 
1724   return false;
1725 }
1726 
1727 /// Analyze a basic block for its contribution to the inline cost.
1728 ///
1729 /// This method walks the analyzer over every instruction in the given basic
1730 /// block and accounts for their cost during inlining at this callsite. It
1731 /// aborts early if the threshold has been exceeded or an impossible to inline
1732 /// construct has been detected. It returns false if inlining is no longer
1733 /// viable, and true if inlining remains viable.
1734 InlineResult
1735 CallAnalyzer::analyzeBlock(BasicBlock *BB,
1736                            SmallPtrSetImpl<const Value *> &EphValues) {
1737   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1738     // FIXME: Currently, the number of instructions in a function regardless of
1739     // our ability to simplify them during inline to constants or dead code,
1740     // are actually used by the vector bonus heuristic. As long as that's true,
1741     // we have to special case debug intrinsics here to prevent differences in
1742     // inlining due to debug symbols. Eventually, the number of unsimplified
1743     // instructions shouldn't factor into the cost computation, but until then,
1744     // hack around it here.
1745     if (isa<DbgInfoIntrinsic>(I))
1746       continue;
1747 
1748     // Skip ephemeral values.
1749     if (EphValues.count(&*I))
1750       continue;
1751 
1752     ++NumInstructions;
1753     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
1754       ++NumVectorInstructions;
1755 
1756     // If the instruction simplified to a constant, there is no cost to this
1757     // instruction. Visit the instructions using our InstVisitor to account for
1758     // all of the per-instruction logic. The visit tree returns true if we
1759     // consumed the instruction in any way, and false if the instruction's base
1760     // cost should count against inlining.
1761     if (Base::visit(&*I))
1762       ++NumInstructionsSimplified;
1763     else
1764       onMissedSimplification();
1765 
1766     using namespace ore;
1767     // If the visit this instruction detected an uninlinable pattern, abort.
1768     InlineResult IR = InlineResult::success();
1769     if (IsRecursiveCall)
1770       IR = InlineResult::failure("recursive");
1771     else if (ExposesReturnsTwice)
1772       IR = InlineResult::failure("exposes returns twice");
1773     else if (HasDynamicAlloca)
1774       IR = InlineResult::failure("dynamic alloca");
1775     else if (HasIndirectBr)
1776       IR = InlineResult::failure("indirect branch");
1777     else if (HasUninlineableIntrinsic)
1778       IR = InlineResult::failure("uninlinable intrinsic");
1779     else if (InitsVargArgs)
1780       IR = InlineResult::failure("varargs");
1781     if (!IR.isSuccess()) {
1782       if (ORE)
1783         ORE->emit([&]() {
1784           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
1785                                           &CandidateCall)
1786                  << NV("Callee", &F) << " has uninlinable pattern ("
1787                  << NV("InlineResult", IR.getFailureReason())
1788                  << ") and cost is not fully computed";
1789         });
1790       return IR;
1791     }
1792 
1793     // If the caller is a recursive function then we don't want to inline
1794     // functions which allocate a lot of stack space because it would increase
1795     // the caller stack usage dramatically.
1796     if (IsCallerRecursive &&
1797         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) {
1798       auto IR =
1799           InlineResult::failure("recursive and allocates too much stack space");
1800       if (ORE)
1801         ORE->emit([&]() {
1802           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
1803                                           &CandidateCall)
1804                  << NV("Callee", &F) << " is "
1805                  << NV("InlineResult", IR.getFailureReason())
1806                  << ". Cost is not fully computed";
1807         });
1808       return IR;
1809     }
1810 
1811     if (shouldStop())
1812       return InlineResult::failure(
1813           "Call site analysis is not favorable to inlining.");
1814   }
1815 
1816   return InlineResult::success();
1817 }
1818 
1819 /// Compute the base pointer and cumulative constant offsets for V.
1820 ///
1821 /// This strips all constant offsets off of V, leaving it the base pointer, and
1822 /// accumulates the total constant offset applied in the returned constant. It
1823 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
1824 /// no constant offsets applied.
1825 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
1826   if (!V->getType()->isPointerTy())
1827     return nullptr;
1828 
1829   unsigned AS = V->getType()->getPointerAddressSpace();
1830   unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
1831   APInt Offset = APInt::getNullValue(IntPtrWidth);
1832 
1833   // Even though we don't look through PHI nodes, we could be called on an
1834   // instruction in an unreachable block, which may be on a cycle.
1835   SmallPtrSet<Value *, 4> Visited;
1836   Visited.insert(V);
1837   do {
1838     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1839       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
1840         return nullptr;
1841       V = GEP->getPointerOperand();
1842     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1843       V = cast<Operator>(V)->getOperand(0);
1844     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1845       if (GA->isInterposable())
1846         break;
1847       V = GA->getAliasee();
1848     } else {
1849       break;
1850     }
1851     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1852   } while (Visited.insert(V).second);
1853 
1854   Type *IdxPtrTy = DL.getIndexType(V->getType());
1855   return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
1856 }
1857 
1858 /// Find dead blocks due to deleted CFG edges during inlining.
1859 ///
1860 /// If we know the successor of the current block, \p CurrBB, has to be \p
1861 /// NextBB, the other successors of \p CurrBB are dead if these successors have
1862 /// no live incoming CFG edges.  If one block is found to be dead, we can
1863 /// continue growing the dead block list by checking the successors of the dead
1864 /// blocks to see if all their incoming edges are dead or not.
1865 void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
1866   auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
1867     // A CFG edge is dead if the predecessor is dead or the predecessor has a
1868     // known successor which is not the one under exam.
1869     return (DeadBlocks.count(Pred) ||
1870             (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
1871   };
1872 
1873   auto IsNewlyDead = [&](BasicBlock *BB) {
1874     // If all the edges to a block are dead, the block is also dead.
1875     return (!DeadBlocks.count(BB) &&
1876             llvm::all_of(predecessors(BB),
1877                          [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
1878   };
1879 
1880   for (BasicBlock *Succ : successors(CurrBB)) {
1881     if (Succ == NextBB || !IsNewlyDead(Succ))
1882       continue;
1883     SmallVector<BasicBlock *, 4> NewDead;
1884     NewDead.push_back(Succ);
1885     while (!NewDead.empty()) {
1886       BasicBlock *Dead = NewDead.pop_back_val();
1887       if (DeadBlocks.insert(Dead))
1888         // Continue growing the dead block lists.
1889         for (BasicBlock *S : successors(Dead))
1890           if (IsNewlyDead(S))
1891             NewDead.push_back(S);
1892     }
1893   }
1894 }
1895 
1896 /// Analyze a call site for potential inlining.
1897 ///
1898 /// Returns true if inlining this call is viable, and false if it is not
1899 /// viable. It computes the cost and adjusts the threshold based on numerous
1900 /// factors and heuristics. If this method returns false but the computed cost
1901 /// is below the computed threshold, then inlining was forcibly disabled by
1902 /// some artifact of the routine.
1903 InlineResult CallAnalyzer::analyze() {
1904   ++NumCallsAnalyzed;
1905 
1906   auto Result = onAnalysisStart();
1907   if (!Result.isSuccess())
1908     return Result;
1909 
1910   if (F.empty())
1911     return InlineResult::success();
1912 
1913   Function *Caller = CandidateCall.getFunction();
1914   // Check if the caller function is recursive itself.
1915   for (User *U : Caller->users()) {
1916     CallBase *Call = dyn_cast<CallBase>(U);
1917     if (Call && Call->getFunction() == Caller) {
1918       IsCallerRecursive = true;
1919       break;
1920     }
1921   }
1922 
1923   // Populate our simplified values by mapping from function arguments to call
1924   // arguments with known important simplifications.
1925   auto CAI = CandidateCall.arg_begin();
1926   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
1927        FAI != FAE; ++FAI, ++CAI) {
1928     assert(CAI != CandidateCall.arg_end());
1929     if (Constant *C = dyn_cast<Constant>(CAI))
1930       SimplifiedValues[&*FAI] = C;
1931 
1932     Value *PtrArg = *CAI;
1933     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1934       ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
1935 
1936       // We can SROA any pointer arguments derived from alloca instructions.
1937       if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
1938         SROAArgValues[&*FAI] = SROAArg;
1939         onInitializeSROAArg(SROAArg);
1940         EnabledSROAAllocas.insert(SROAArg);
1941       }
1942     }
1943   }
1944   NumConstantArgs = SimplifiedValues.size();
1945   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1946   NumAllocaArgs = SROAArgValues.size();
1947 
1948   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
1949   // the ephemeral values multiple times (and they're completely determined by
1950   // the callee, so this is purely duplicate work).
1951   SmallPtrSet<const Value *, 32> EphValues;
1952   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
1953 
1954   // The worklist of live basic blocks in the callee *after* inlining. We avoid
1955   // adding basic blocks of the callee which can be proven to be dead for this
1956   // particular call site in order to get more accurate cost estimates. This
1957   // requires a somewhat heavyweight iteration pattern: we need to walk the
1958   // basic blocks in a breadth-first order as we insert live successors. To
1959   // accomplish this, prioritizing for small iterations because we exit after
1960   // crossing our threshold, we use a small-size optimized SetVector.
1961   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1962                     SmallPtrSet<BasicBlock *, 16>>
1963       BBSetVector;
1964   BBSetVector BBWorklist;
1965   BBWorklist.insert(&F.getEntryBlock());
1966 
1967   // Note that we *must not* cache the size, this loop grows the worklist.
1968   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1969     if (shouldStop())
1970       break;
1971 
1972     BasicBlock *BB = BBWorklist[Idx];
1973     if (BB->empty())
1974       continue;
1975 
1976     // Disallow inlining a blockaddress with uses other than strictly callbr.
1977     // A blockaddress only has defined behavior for an indirect branch in the
1978     // same function, and we do not currently support inlining indirect
1979     // branches.  But, the inliner may not see an indirect branch that ends up
1980     // being dead code at a particular call site. If the blockaddress escapes
1981     // the function, e.g., via a global variable, inlining may lead to an
1982     // invalid cross-function reference.
1983     // FIXME: pr/39560: continue relaxing this overt restriction.
1984     if (BB->hasAddressTaken())
1985       for (User *U : BlockAddress::get(&*BB)->users())
1986         if (!isa<CallBrInst>(*U))
1987           return InlineResult::failure("blockaddress used outside of callbr");
1988 
1989     // Analyze the cost of this block. If we blow through the threshold, this
1990     // returns false, and we can bail on out.
1991     InlineResult IR = analyzeBlock(BB, EphValues);
1992     if (!IR.isSuccess())
1993       return IR;
1994 
1995     Instruction *TI = BB->getTerminator();
1996 
1997     // Add in the live successors by first checking whether we have terminator
1998     // that may be simplified based on the values simplified by this call.
1999     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2000       if (BI->isConditional()) {
2001         Value *Cond = BI->getCondition();
2002         if (ConstantInt *SimpleCond =
2003                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
2004           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
2005           BBWorklist.insert(NextBB);
2006           KnownSuccessors[BB] = NextBB;
2007           findDeadBlocks(BB, NextBB);
2008           continue;
2009         }
2010       }
2011     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2012       Value *Cond = SI->getCondition();
2013       if (ConstantInt *SimpleCond =
2014               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
2015         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
2016         BBWorklist.insert(NextBB);
2017         KnownSuccessors[BB] = NextBB;
2018         findDeadBlocks(BB, NextBB);
2019         continue;
2020       }
2021     }
2022 
2023     // If we're unable to select a particular successor, just count all of
2024     // them.
2025     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
2026          ++TIdx)
2027       BBWorklist.insert(TI->getSuccessor(TIdx));
2028 
2029     onBlockAnalyzed(BB);
2030   }
2031 
2032   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
2033                                     &F == CandidateCall.getCalledFunction();
2034   // If this is a noduplicate call, we can still inline as long as
2035   // inlining this would cause the removal of the caller (so the instruction
2036   // is not actually duplicated, just moved).
2037   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
2038     return InlineResult::failure("noduplicate");
2039 
2040   return finalizeAnalysis();
2041 }
2042 
2043 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2044 /// Dump stats about this call's analysis.
2045 LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() {
2046 #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
2047   DEBUG_PRINT_STAT(NumConstantArgs);
2048   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
2049   DEBUG_PRINT_STAT(NumAllocaArgs);
2050   DEBUG_PRINT_STAT(NumConstantPtrCmps);
2051   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
2052   DEBUG_PRINT_STAT(NumInstructionsSimplified);
2053   DEBUG_PRINT_STAT(NumInstructions);
2054   DEBUG_PRINT_STAT(SROACostSavings);
2055   DEBUG_PRINT_STAT(SROACostSavingsLost);
2056   DEBUG_PRINT_STAT(LoadEliminationCost);
2057   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
2058   DEBUG_PRINT_STAT(Cost);
2059   DEBUG_PRINT_STAT(Threshold);
2060 #undef DEBUG_PRINT_STAT
2061 }
2062 #endif
2063 
2064 /// Test that there are no attribute conflicts between Caller and Callee
2065 ///        that prevent inlining.
2066 static bool functionsHaveCompatibleAttributes(Function *Caller,
2067                                               Function *Callee,
2068                                               TargetTransformInfo &TTI) {
2069   return TTI.areInlineCompatible(Caller, Callee) &&
2070          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
2071 }
2072 
2073 int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) {
2074   int Cost = 0;
2075   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
2076     if (Call.isByValArgument(I)) {
2077       // We approximate the number of loads and stores needed by dividing the
2078       // size of the byval type by the target's pointer size.
2079       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
2080       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
2081       unsigned AS = PTy->getAddressSpace();
2082       unsigned PointerSize = DL.getPointerSizeInBits(AS);
2083       // Ceiling division.
2084       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
2085 
2086       // If it generates more than 8 stores it is likely to be expanded as an
2087       // inline memcpy so we take that as an upper bound. Otherwise we assume
2088       // one load and one store per word copied.
2089       // FIXME: The maxStoresPerMemcpy setting from the target should be used
2090       // here instead of a magic number of 8, but it's not available via
2091       // DataLayout.
2092       NumStores = std::min(NumStores, 8U);
2093 
2094       Cost += 2 * NumStores * InlineConstants::InstrCost;
2095     } else {
2096       // For non-byval arguments subtract off one instruction per call
2097       // argument.
2098       Cost += InlineConstants::InstrCost;
2099     }
2100   }
2101   // The call instruction also disappears after inlining.
2102   Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty;
2103   return Cost;
2104 }
2105 
2106 InlineCost llvm::getInlineCost(
2107     CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
2108     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
2109     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
2110     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2111   return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
2112                        GetAssumptionCache, GetBFI, PSI, ORE);
2113 }
2114 
2115 InlineCost llvm::getInlineCost(
2116     CallBase &Call, Function *Callee, const InlineParams &Params,
2117     TargetTransformInfo &CalleeTTI,
2118     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
2119     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
2120     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2121 
2122   // Cannot inline indirect calls.
2123   if (!Callee)
2124     return llvm::InlineCost::getNever("indirect call");
2125 
2126   // Never inline calls with byval arguments that does not have the alloca
2127   // address space. Since byval arguments can be replaced with a copy to an
2128   // alloca, the inlined code would need to be adjusted to handle that the
2129   // argument is in the alloca address space (so it is a little bit complicated
2130   // to solve).
2131   unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace();
2132   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I)
2133     if (Call.isByValArgument(I)) {
2134       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
2135       if (PTy->getAddressSpace() != AllocaAS)
2136         return llvm::InlineCost::getNever("byval arguments without alloca"
2137                                           " address space");
2138     }
2139 
2140   // Calls to functions with always-inline attributes should be inlined
2141   // whenever possible.
2142   if (Call.hasFnAttr(Attribute::AlwaysInline)) {
2143     auto IsViable = isInlineViable(*Callee);
2144     if (IsViable.isSuccess())
2145       return llvm::InlineCost::getAlways("always inline attribute");
2146     return llvm::InlineCost::getNever(IsViable.getFailureReason());
2147   }
2148 
2149   // Never inline functions with conflicting attributes (unless callee has
2150   // always-inline attribute).
2151   Function *Caller = Call.getCaller();
2152   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI))
2153     return llvm::InlineCost::getNever("conflicting attributes");
2154 
2155   // Don't inline this call if the caller has the optnone attribute.
2156   if (Caller->hasOptNone())
2157     return llvm::InlineCost::getNever("optnone attribute");
2158 
2159   // Don't inline a function that treats null pointer as valid into a caller
2160   // that does not have this attribute.
2161   if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined())
2162     return llvm::InlineCost::getNever("nullptr definitions incompatible");
2163 
2164   // Don't inline functions which can be interposed at link-time.
2165   if (Callee->isInterposable())
2166     return llvm::InlineCost::getNever("interposable");
2167 
2168   // Don't inline functions marked noinline.
2169   if (Callee->hasFnAttribute(Attribute::NoInline))
2170     return llvm::InlineCost::getNever("noinline function attribute");
2171 
2172   // Don't inline call sites marked noinline.
2173   if (Call.isNoInline())
2174     return llvm::InlineCost::getNever("noinline call site attribute");
2175 
2176   LLVM_DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
2177                           << "... (caller:" << Caller->getName() << ")\n");
2178 
2179   InlineCostCallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE,
2180                             *Callee, Call, Params);
2181   InlineResult ShouldInline = CA.analyze();
2182 
2183   LLVM_DEBUG(CA.dump());
2184 
2185   // Check if there was a reason to force inlining or no inlining.
2186   if (!ShouldInline.isSuccess() && CA.getCost() < CA.getThreshold())
2187     return InlineCost::getNever(ShouldInline.getFailureReason());
2188   if (ShouldInline.isSuccess() && CA.getCost() >= CA.getThreshold())
2189     return InlineCost::getAlways("empty function");
2190 
2191   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
2192 }
2193 
2194 InlineResult llvm::isInlineViable(Function &F) {
2195   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
2196   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
2197     // Disallow inlining of functions which contain indirect branches.
2198     if (isa<IndirectBrInst>(BI->getTerminator()))
2199       return InlineResult::failure("contains indirect branches");
2200 
2201     // Disallow inlining of blockaddresses which are used by non-callbr
2202     // instructions.
2203     if (BI->hasAddressTaken())
2204       for (User *U : BlockAddress::get(&*BI)->users())
2205         if (!isa<CallBrInst>(*U))
2206           return InlineResult::failure("blockaddress used outside of callbr");
2207 
2208     for (auto &II : *BI) {
2209       CallBase *Call = dyn_cast<CallBase>(&II);
2210       if (!Call)
2211         continue;
2212 
2213       // Disallow recursive calls.
2214       if (&F == Call->getCalledFunction())
2215         return InlineResult::failure("recursive call");
2216 
2217       // Disallow calls which expose returns-twice to a function not previously
2218       // attributed as such.
2219       if (!ReturnsTwice && isa<CallInst>(Call) &&
2220           cast<CallInst>(Call)->canReturnTwice())
2221         return InlineResult::failure("exposes returns-twice attribute");
2222 
2223       if (Call->getCalledFunction())
2224         switch (Call->getCalledFunction()->getIntrinsicID()) {
2225         default:
2226           break;
2227         case llvm::Intrinsic::icall_branch_funnel:
2228           // Disallow inlining of @llvm.icall.branch.funnel because current
2229           // backend can't separate call targets from call arguments.
2230           return InlineResult::failure(
2231               "disallowed inlining of @llvm.icall.branch.funnel");
2232         case llvm::Intrinsic::localescape:
2233           // Disallow inlining functions that call @llvm.localescape. Doing this
2234           // correctly would require major changes to the inliner.
2235           return InlineResult::failure(
2236               "disallowed inlining of @llvm.localescape");
2237         case llvm::Intrinsic::vastart:
2238           // Disallow inlining of functions that initialize VarArgs with
2239           // va_start.
2240           return InlineResult::failure(
2241               "contains VarArgs initialized with va_start");
2242         }
2243     }
2244   }
2245 
2246   return InlineResult::success();
2247 }
2248 
2249 // APIs to create InlineParams based on command line flags and/or other
2250 // parameters.
2251 
2252 InlineParams llvm::getInlineParams(int Threshold) {
2253   InlineParams Params;
2254 
2255   // This field is the threshold to use for a callee by default. This is
2256   // derived from one or more of:
2257   //  * optimization or size-optimization levels,
2258   //  * a value passed to createFunctionInliningPass function, or
2259   //  * the -inline-threshold flag.
2260   //  If the -inline-threshold flag is explicitly specified, that is used
2261   //  irrespective of anything else.
2262   if (InlineThreshold.getNumOccurrences() > 0)
2263     Params.DefaultThreshold = InlineThreshold;
2264   else
2265     Params.DefaultThreshold = Threshold;
2266 
2267   // Set the HintThreshold knob from the -inlinehint-threshold.
2268   Params.HintThreshold = HintThreshold;
2269 
2270   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
2271   Params.HotCallSiteThreshold = HotCallSiteThreshold;
2272 
2273   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
2274   // populate LocallyHotCallSiteThreshold. Later, we populate
2275   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
2276   // we know that optimization level is O3 (in the getInlineParams variant that
2277   // takes the opt and size levels).
2278   // FIXME: Remove this check (and make the assignment unconditional) after
2279   // addressing size regression issues at O2.
2280   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
2281     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2282 
2283   // Set the ColdCallSiteThreshold knob from the
2284   // -inline-cold-callsite-threshold.
2285   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
2286 
2287   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
2288   // -inlinehint-threshold commandline option is not explicitly given. If that
2289   // option is present, then its value applies even for callees with size and
2290   // minsize attributes.
2291   // If the -inline-threshold is not specified, set the ColdThreshold from the
2292   // -inlinecold-threshold even if it is not explicitly passed. If
2293   // -inline-threshold is specified, then -inlinecold-threshold needs to be
2294   // explicitly specified to set the ColdThreshold knob
2295   if (InlineThreshold.getNumOccurrences() == 0) {
2296     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
2297     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
2298     Params.ColdThreshold = ColdThreshold;
2299   } else if (ColdThreshold.getNumOccurrences() > 0) {
2300     Params.ColdThreshold = ColdThreshold;
2301   }
2302   return Params;
2303 }
2304 
2305 InlineParams llvm::getInlineParams() {
2306   return getInlineParams(InlineThreshold);
2307 }
2308 
2309 // Compute the default threshold for inlining based on the opt level and the
2310 // size opt level.
2311 static int computeThresholdFromOptLevels(unsigned OptLevel,
2312                                          unsigned SizeOptLevel) {
2313   if (OptLevel > 2)
2314     return InlineConstants::OptAggressiveThreshold;
2315   if (SizeOptLevel == 1) // -Os
2316     return InlineConstants::OptSizeThreshold;
2317   if (SizeOptLevel == 2) // -Oz
2318     return InlineConstants::OptMinSizeThreshold;
2319   return InlineThreshold;
2320 }
2321 
2322 InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
2323   auto Params =
2324       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
2325   // At O3, use the value of -locally-hot-callsite-threshold option to populate
2326   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
2327   // when it is specified explicitly.
2328   if (OptLevel > 2)
2329     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2330   return Params;
2331 }
2332