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