1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements inline cost analysis.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/InlineCost.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/BlockFrequencyInfo.h"
22 #include "llvm/Analysis/CodeMetrics.h"
23 #include "llvm/Analysis/ConstantFolding.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/ProfileSummaryInfo.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/GetElementPtrTypeIterator.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/InstVisitor.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "inline-cost"
41 
42 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
43 
44 static cl::opt<int> InlineThreshold(
45     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
46     cl::desc("Control the amount of inlining to perform (default = 225)"));
47 
48 static cl::opt<int> HintThreshold(
49     "inlinehint-threshold", cl::Hidden, cl::init(325),
50     cl::desc("Threshold for inlining functions with inline hint"));
51 
52 static cl::opt<int>
53     ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
54                           cl::init(45),
55                           cl::desc("Threshold for inlining cold callsites"));
56 
57 // We introduce this threshold to help performance of instrumentation based
58 // PGO before we actually hook up inliner with analysis passes such as BPI and
59 // BFI.
60 static cl::opt<int> ColdThreshold(
61     "inlinecold-threshold", cl::Hidden, cl::init(45),
62     cl::desc("Threshold for inlining functions with cold attribute"));
63 
64 static cl::opt<int>
65     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
66                          cl::ZeroOrMore,
67                          cl::desc("Threshold for hot callsites "));
68 
69 static cl::opt<int> ColdCallSiteRelFreq(
70     "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
71     cl::desc("Maxmimum block frequency, expressed as a percentage of caller's "
72              "entry frequency, for a callsite to be cold in the absence of "
73              "profile information."));
74 
75 namespace {
76 
77 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
78   typedef InstVisitor<CallAnalyzer, bool> Base;
79   friend class InstVisitor<CallAnalyzer, bool>;
80 
81   /// The TargetTransformInfo available for this compilation.
82   const TargetTransformInfo &TTI;
83 
84   /// Getter for the cache of @llvm.assume intrinsics.
85   std::function<AssumptionCache &(Function &)> &GetAssumptionCache;
86 
87   /// Getter for BlockFrequencyInfo
88   Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI;
89 
90   /// Profile summary information.
91   ProfileSummaryInfo *PSI;
92 
93   /// The called function.
94   Function &F;
95 
96   // Cache the DataLayout since we use it a lot.
97   const DataLayout &DL;
98 
99   /// The candidate callsite being analyzed. Please do not use this to do
100   /// analysis in the caller function; we want the inline cost query to be
101   /// easily cacheable. Instead, use the cover function paramHasAttr.
102   CallSite CandidateCS;
103 
104   /// Tunable parameters that control the analysis.
105   const InlineParams &Params;
106 
107   int Threshold;
108   int Cost;
109 
110   bool IsCallerRecursive;
111   bool IsRecursiveCall;
112   bool ExposesReturnsTwice;
113   bool HasDynamicAlloca;
114   bool ContainsNoDuplicateCall;
115   bool HasReturn;
116   bool HasIndirectBr;
117   bool HasFrameEscape;
118 
119   /// Number of bytes allocated statically by the callee.
120   uint64_t AllocatedSize;
121   unsigned NumInstructions, NumVectorInstructions;
122   int VectorBonus, TenPercentVectorBonus;
123   // Bonus to be applied when the callee has only one reachable basic block.
124   int SingleBBBonus;
125 
126   /// While we walk the potentially-inlined instructions, we build up and
127   /// maintain a mapping of simplified values specific to this callsite. The
128   /// idea is to propagate any special information we have about arguments to
129   /// this call through the inlinable section of the function, and account for
130   /// likely simplifications post-inlining. The most important aspect we track
131   /// is CFG altering simplifications -- when we prove a basic block dead, that
132   /// can cause dramatic shifts in the cost of inlining a function.
133   DenseMap<Value *, Constant *> SimplifiedValues;
134 
135   /// Keep track of the values which map back (through function arguments) to
136   /// allocas on the caller stack which could be simplified through SROA.
137   DenseMap<Value *, Value *> SROAArgValues;
138 
139   /// The mapping of caller Alloca values to their accumulated cost savings. If
140   /// we have to disable SROA for one of the allocas, this tells us how much
141   /// cost must be added.
142   DenseMap<Value *, int> SROAArgCosts;
143 
144   /// Keep track of values which map to a pointer base and constant offset.
145   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
146 
147   // Custom simplification helper routines.
148   bool isAllocaDerivedArg(Value *V);
149   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
150                             DenseMap<Value *, int>::iterator &CostIt);
151   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
152   void disableSROA(Value *V);
153   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
154                           int InstructionCost);
155   bool isGEPFree(GetElementPtrInst &GEP);
156   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
157   bool simplifyCallSite(Function *F, CallSite CS);
158   template <typename Callable>
159   bool simplifyInstruction(Instruction &I, Callable Evaluate);
160   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
161 
162   /// Return true if the given argument to the function being considered for
163   /// inlining has the given attribute set either at the call site or the
164   /// function declaration.  Primarily used to inspect call site specific
165   /// attributes since these can be more precise than the ones on the callee
166   /// itself.
167   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
168 
169   /// Return true if the given value is known non null within the callee if
170   /// inlined through this particular callsite.
171   bool isKnownNonNullInCallee(Value *V);
172 
173   /// Update Threshold based on callsite properties such as callee
174   /// attributes and callee hotness for PGO builds. The Callee is explicitly
175   /// passed to support analyzing indirect calls whose target is inferred by
176   /// analysis.
177   void updateThreshold(CallSite CS, Function &Callee);
178 
179   /// Return true if size growth is allowed when inlining the callee at CS.
180   bool allowSizeGrowth(CallSite CS);
181 
182   /// Return true if \p CS is a cold callsite.
183   bool isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI);
184 
185   // Custom analysis routines.
186   bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
187 
188   // Disable several entry points to the visitor so we don't accidentally use
189   // them by declaring but not defining them here.
190   void visit(Module *);
191   void visit(Module &);
192   void visit(Function *);
193   void visit(Function &);
194   void visit(BasicBlock *);
195   void visit(BasicBlock &);
196 
197   // Provide base case for our instruction visit.
198   bool visitInstruction(Instruction &I);
199 
200   // Our visit overrides.
201   bool visitAlloca(AllocaInst &I);
202   bool visitPHI(PHINode &I);
203   bool visitGetElementPtr(GetElementPtrInst &I);
204   bool visitBitCast(BitCastInst &I);
205   bool visitPtrToInt(PtrToIntInst &I);
206   bool visitIntToPtr(IntToPtrInst &I);
207   bool visitCastInst(CastInst &I);
208   bool visitUnaryInstruction(UnaryInstruction &I);
209   bool visitCmpInst(CmpInst &I);
210   bool visitSub(BinaryOperator &I);
211   bool visitBinaryOperator(BinaryOperator &I);
212   bool visitLoad(LoadInst &I);
213   bool visitStore(StoreInst &I);
214   bool visitExtractValue(ExtractValueInst &I);
215   bool visitInsertValue(InsertValueInst &I);
216   bool visitCallSite(CallSite CS);
217   bool visitReturnInst(ReturnInst &RI);
218   bool visitBranchInst(BranchInst &BI);
219   bool visitSwitchInst(SwitchInst &SI);
220   bool visitIndirectBrInst(IndirectBrInst &IBI);
221   bool visitResumeInst(ResumeInst &RI);
222   bool visitCleanupReturnInst(CleanupReturnInst &RI);
223   bool visitCatchReturnInst(CatchReturnInst &RI);
224   bool visitUnreachableInst(UnreachableInst &I);
225 
226 public:
227   CallAnalyzer(const TargetTransformInfo &TTI,
228                std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
229                Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI,
230                ProfileSummaryInfo *PSI, Function &Callee, CallSite CSArg,
231                const InlineParams &Params)
232       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
233         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()),
234         CandidateCS(CSArg), Params(Params), Threshold(Params.DefaultThreshold),
235         Cost(0), IsCallerRecursive(false), IsRecursiveCall(false),
236         ExposesReturnsTwice(false), HasDynamicAlloca(false),
237         ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
238         HasFrameEscape(false), AllocatedSize(0), NumInstructions(0),
239         NumVectorInstructions(0), VectorBonus(0), SingleBBBonus(0),
240         NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
241         NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
242         NumInstructionsSimplified(0), SROACostSavings(0),
243         SROACostSavingsLost(0) {}
244 
245   bool analyzeCall(CallSite CS);
246 
247   int getThreshold() { return Threshold; }
248   int getCost() { return Cost; }
249 
250   // Keep a bunch of stats about the cost savings found so we can print them
251   // out when debugging.
252   unsigned NumConstantArgs;
253   unsigned NumConstantOffsetPtrArgs;
254   unsigned NumAllocaArgs;
255   unsigned NumConstantPtrCmps;
256   unsigned NumConstantPtrDiffs;
257   unsigned NumInstructionsSimplified;
258   unsigned SROACostSavings;
259   unsigned SROACostSavingsLost;
260 
261   void dump();
262 };
263 
264 } // namespace
265 
266 /// \brief Test whether the given value is an Alloca-derived function argument.
267 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
268   return SROAArgValues.count(V);
269 }
270 
271 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
272 /// Returns false if V does not map to a SROA-candidate.
273 bool CallAnalyzer::lookupSROAArgAndCost(
274     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
275   if (SROAArgValues.empty() || SROAArgCosts.empty())
276     return false;
277 
278   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
279   if (ArgIt == SROAArgValues.end())
280     return false;
281 
282   Arg = ArgIt->second;
283   CostIt = SROAArgCosts.find(Arg);
284   return CostIt != SROAArgCosts.end();
285 }
286 
287 /// \brief Disable SROA for the candidate marked by this cost iterator.
288 ///
289 /// This marks the candidate as no longer viable for SROA, and adds the cost
290 /// savings associated with it back into the inline cost measurement.
291 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
292   // If we're no longer able to perform SROA we need to undo its cost savings
293   // and prevent subsequent analysis.
294   Cost += CostIt->second;
295   SROACostSavings -= CostIt->second;
296   SROACostSavingsLost += CostIt->second;
297   SROAArgCosts.erase(CostIt);
298 }
299 
300 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
301 void CallAnalyzer::disableSROA(Value *V) {
302   Value *SROAArg;
303   DenseMap<Value *, int>::iterator CostIt;
304   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
305     disableSROA(CostIt);
306 }
307 
308 /// \brief Accumulate the given cost for a particular SROA candidate.
309 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
310                                       int InstructionCost) {
311   CostIt->second += InstructionCost;
312   SROACostSavings += InstructionCost;
313 }
314 
315 /// \brief Accumulate a constant GEP offset into an APInt if possible.
316 ///
317 /// Returns false if unable to compute the offset for any reason. Respects any
318 /// simplified values known during the analysis of this callsite.
319 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
320   unsigned IntPtrWidth = DL.getPointerSizeInBits();
321   assert(IntPtrWidth == Offset.getBitWidth());
322 
323   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
324        GTI != GTE; ++GTI) {
325     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
326     if (!OpC)
327       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
328         OpC = dyn_cast<ConstantInt>(SimpleOp);
329     if (!OpC)
330       return false;
331     if (OpC->isZero())
332       continue;
333 
334     // Handle a struct index, which adds its field offset to the pointer.
335     if (StructType *STy = GTI.getStructTypeOrNull()) {
336       unsigned ElementIdx = OpC->getZExtValue();
337       const StructLayout *SL = DL.getStructLayout(STy);
338       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
339       continue;
340     }
341 
342     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
343     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
344   }
345   return true;
346 }
347 
348 /// \brief Use TTI to check whether a GEP is free.
349 ///
350 /// Respects any simplified values known during the analysis of this callsite.
351 bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
352   SmallVector<Value *, 4> Operands;
353   Operands.push_back(GEP.getOperand(0));
354   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
355     if (Constant *SimpleOp = SimplifiedValues.lookup(*I))
356        Operands.push_back(SimpleOp);
357      else
358        Operands.push_back(*I);
359   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands);
360 }
361 
362 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
363   // Check whether inlining will turn a dynamic alloca into a static
364   // alloca and handle that case.
365   if (I.isArrayAllocation()) {
366     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
367     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
368       Type *Ty = I.getAllocatedType();
369       AllocatedSize = SaturatingMultiplyAdd(
370           AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty), AllocatedSize);
371       return Base::visitAlloca(I);
372     }
373   }
374 
375   // Accumulate the allocated size.
376   if (I.isStaticAlloca()) {
377     Type *Ty = I.getAllocatedType();
378     AllocatedSize = SaturatingAdd(DL.getTypeAllocSize(Ty), AllocatedSize);
379   }
380 
381   // We will happily inline static alloca instructions.
382   if (I.isStaticAlloca())
383     return Base::visitAlloca(I);
384 
385   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
386   // a variety of reasons, and so we would like to not inline them into
387   // functions which don't currently have a dynamic alloca. This simply
388   // disables inlining altogether in the presence of a dynamic alloca.
389   HasDynamicAlloca = true;
390   return false;
391 }
392 
393 bool CallAnalyzer::visitPHI(PHINode &I) {
394   // FIXME: We should potentially be tracking values through phi nodes,
395   // especially when they collapse to a single value due to deleted CFG edges
396   // during inlining.
397 
398   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
399   // though we don't want to propagate it's bonuses. The idea is to disable
400   // SROA if it *might* be used in an inappropriate manner.
401 
402   // Phi nodes are always zero-cost.
403   return true;
404 }
405 
406 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
407   Value *SROAArg;
408   DenseMap<Value *, int>::iterator CostIt;
409   bool SROACandidate =
410       lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt);
411 
412   // Try to fold GEPs of constant-offset call site argument pointers. This
413   // requires target data and inbounds GEPs.
414   if (I.isInBounds()) {
415     // Check if we have a base + offset for the pointer.
416     Value *Ptr = I.getPointerOperand();
417     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
418     if (BaseAndOffset.first) {
419       // Check if the offset of this GEP is constant, and if so accumulate it
420       // into Offset.
421       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
422         // Non-constant GEPs aren't folded, and disable SROA.
423         if (SROACandidate)
424           disableSROA(CostIt);
425         return isGEPFree(I);
426       }
427 
428       // Add the result as a new mapping to Base + Offset.
429       ConstantOffsetPtrs[&I] = BaseAndOffset;
430 
431       // Also handle SROA candidates here, we already know that the GEP is
432       // all-constant indexed.
433       if (SROACandidate)
434         SROAArgValues[&I] = SROAArg;
435 
436       return true;
437     }
438   }
439 
440   // Lambda to check whether a GEP's indices are all constant.
441   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
442     for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
443       if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
444         return false;
445     return true;
446   };
447 
448   if (IsGEPOffsetConstant(I)) {
449     if (SROACandidate)
450       SROAArgValues[&I] = SROAArg;
451 
452     // Constant GEPs are modeled as free.
453     return true;
454   }
455 
456   // Variable GEPs will require math and will disable SROA.
457   if (SROACandidate)
458     disableSROA(CostIt);
459   return isGEPFree(I);
460 }
461 
462 /// Simplify \p I if its operands are constants and update SimplifiedValues.
463 /// \p Evaluate is a callable specific to instruction type that evaluates the
464 /// instruction when all the operands are constants.
465 template <typename Callable>
466 bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
467   SmallVector<Constant *, 2> COps;
468   for (Value *Op : I.operands()) {
469     Constant *COp = dyn_cast<Constant>(Op);
470     if (!COp)
471       COp = SimplifiedValues.lookup(Op);
472     if (!COp)
473       return false;
474     COps.push_back(COp);
475   }
476   auto *C = Evaluate(COps);
477   if (!C)
478     return false;
479   SimplifiedValues[&I] = C;
480   return true;
481 }
482 
483 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
484   // Propagate constants through bitcasts.
485   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
486         return ConstantExpr::getBitCast(COps[0], I.getType());
487       }))
488     return true;
489 
490   // Track base/offsets through casts
491   std::pair<Value *, APInt> BaseAndOffset =
492       ConstantOffsetPtrs.lookup(I.getOperand(0));
493   // Casts don't change the offset, just wrap it up.
494   if (BaseAndOffset.first)
495     ConstantOffsetPtrs[&I] = BaseAndOffset;
496 
497   // Also look for SROA candidates here.
498   Value *SROAArg;
499   DenseMap<Value *, int>::iterator CostIt;
500   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
501     SROAArgValues[&I] = SROAArg;
502 
503   // Bitcasts are always zero cost.
504   return true;
505 }
506 
507 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
508   // Propagate constants through ptrtoint.
509   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
510         return ConstantExpr::getPtrToInt(COps[0], I.getType());
511       }))
512     return true;
513 
514   // Track base/offset pairs when converted to a plain integer provided the
515   // integer is large enough to represent the pointer.
516   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
517   if (IntegerSize >= DL.getPointerSizeInBits()) {
518     std::pair<Value *, APInt> BaseAndOffset =
519         ConstantOffsetPtrs.lookup(I.getOperand(0));
520     if (BaseAndOffset.first)
521       ConstantOffsetPtrs[&I] = BaseAndOffset;
522   }
523 
524   // This is really weird. Technically, ptrtoint will disable SROA. However,
525   // unless that ptrtoint is *used* somewhere in the live basic blocks after
526   // inlining, it will be nuked, and SROA should proceed. All of the uses which
527   // would block SROA would also block SROA if applied directly to a pointer,
528   // and so we can just add the integer in here. The only places where SROA is
529   // preserved either cannot fire on an integer, or won't in-and-of themselves
530   // disable SROA (ext) w/o some later use that we would see and disable.
531   Value *SROAArg;
532   DenseMap<Value *, int>::iterator CostIt;
533   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
534     SROAArgValues[&I] = SROAArg;
535 
536   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
537 }
538 
539 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
540   // Propagate constants through ptrtoint.
541   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
542         return ConstantExpr::getIntToPtr(COps[0], I.getType());
543       }))
544     return true;
545 
546   // Track base/offset pairs when round-tripped through a pointer without
547   // modifications provided the integer is not too large.
548   Value *Op = I.getOperand(0);
549   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
550   if (IntegerSize <= DL.getPointerSizeInBits()) {
551     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
552     if (BaseAndOffset.first)
553       ConstantOffsetPtrs[&I] = BaseAndOffset;
554   }
555 
556   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
557   Value *SROAArg;
558   DenseMap<Value *, int>::iterator CostIt;
559   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
560     SROAArgValues[&I] = SROAArg;
561 
562   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
563 }
564 
565 bool CallAnalyzer::visitCastInst(CastInst &I) {
566   // Propagate constants through ptrtoint.
567   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
568         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
569       }))
570     return true;
571 
572   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
573   disableSROA(I.getOperand(0));
574 
575   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
576 }
577 
578 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
579   Value *Operand = I.getOperand(0);
580   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
581         return ConstantFoldInstOperands(&I, COps[0], DL);
582       }))
583     return true;
584 
585   // Disable any SROA on the argument to arbitrary unary operators.
586   disableSROA(Operand);
587 
588   return false;
589 }
590 
591 bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
592   return CandidateCS.paramHasAttr(A->getArgNo(), Attr);
593 }
594 
595 bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
596   // Does the *call site* have the NonNull attribute set on an argument?  We
597   // use the attribute on the call site to memoize any analysis done in the
598   // caller. This will also trip if the callee function has a non-null
599   // parameter attribute, but that's a less interesting case because hopefully
600   // the callee would already have been simplified based on that.
601   if (Argument *A = dyn_cast<Argument>(V))
602     if (paramHasAttr(A, Attribute::NonNull))
603       return true;
604 
605   // Is this an alloca in the caller?  This is distinct from the attribute case
606   // above because attributes aren't updated within the inliner itself and we
607   // always want to catch the alloca derived case.
608   if (isAllocaDerivedArg(V))
609     // We can actually predict the result of comparisons between an
610     // alloca-derived value and null. Note that this fires regardless of
611     // SROA firing.
612     return true;
613 
614   return false;
615 }
616 
617 bool CallAnalyzer::allowSizeGrowth(CallSite CS) {
618   // If the normal destination of the invoke or the parent block of the call
619   // site is unreachable-terminated, there is little point in inlining this
620   // unless there is literally zero cost.
621   // FIXME: Note that it is possible that an unreachable-terminated block has a
622   // hot entry. For example, in below scenario inlining hot_call_X() may be
623   // beneficial :
624   // main() {
625   //   hot_call_1();
626   //   ...
627   //   hot_call_N()
628   //   exit(0);
629   // }
630   // For now, we are not handling this corner case here as it is rare in real
631   // code. In future, we should elaborate this based on BPI and BFI in more
632   // general threshold adjusting heuristics in updateThreshold().
633   Instruction *Instr = CS.getInstruction();
634   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
635     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
636       return false;
637   } else if (isa<UnreachableInst>(Instr->getParent()->getTerminator()))
638     return false;
639 
640   return true;
641 }
642 
643 bool CallAnalyzer::isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI) {
644   // If global profile summary is available, then callsite's coldness is
645   // determined based on that.
646   if (PSI->hasProfileSummary())
647     return PSI->isColdCallSite(CS, CallerBFI);
648   if (!CallerBFI)
649     return false;
650 
651   // In the absence of global profile summary, determine if the callsite is cold
652   // relative to caller's entry. We could potentially cache the computation of
653   // scaled entry frequency, but the added complexity is not worth it unless
654   // this scaling shows up high in the profiles.
655   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
656   auto CallSiteBB = CS.getInstruction()->getParent();
657   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
658   auto CallerEntryFreq =
659       CallerBFI->getBlockFreq(&(CS.getCaller()->getEntryBlock()));
660   return CallSiteFreq < CallerEntryFreq * ColdProb;
661 }
662 
663 void CallAnalyzer::updateThreshold(CallSite CS, Function &Callee) {
664   // If no size growth is allowed for this inlining, set Threshold to 0.
665   if (!allowSizeGrowth(CS)) {
666     Threshold = 0;
667     return;
668   }
669 
670   Function *Caller = CS.getCaller();
671 
672   // return min(A, B) if B is valid.
673   auto MinIfValid = [](int A, Optional<int> B) {
674     return B ? std::min(A, B.getValue()) : A;
675   };
676 
677   // return max(A, B) if B is valid.
678   auto MaxIfValid = [](int A, Optional<int> B) {
679     return B ? std::max(A, B.getValue()) : A;
680   };
681 
682   // Various bonus percentages. These are multiplied by Threshold to get the
683   // bonus values.
684   // SingleBBBonus: This bonus is applied if the callee has a single reachable
685   // basic block at the given callsite context. This is speculatively applied
686   // and withdrawn if more than one basic block is seen.
687   //
688   // Vector bonuses: We want to more aggressively inline vector-dense kernels
689   // and apply this bonus based on the percentage of vector instructions. A
690   // bonus is applied if the vector instructions exceed 50% and half that amount
691   // is applied if it exceeds 10%. Note that these bonuses are some what
692   // arbitrary and evolved over time by accident as much as because they are
693   // principled bonuses.
694   // FIXME: It would be nice to base the bonus values on something more
695   // scientific.
696   //
697   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
698   // of the last call to a static function as inlining such functions is
699   // guaranteed to reduce code size.
700   //
701   // These bonus percentages may be set to 0 based on properties of the caller
702   // and the callsite.
703   int SingleBBBonusPercent = 50;
704   int VectorBonusPercent = 150;
705   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
706 
707   // Lambda to set all the above bonus and bonus percentages to 0.
708   auto DisallowAllBonuses = [&]() {
709     SingleBBBonusPercent = 0;
710     VectorBonusPercent = 0;
711     LastCallToStaticBonus = 0;
712   };
713 
714   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
715   // and reduce the threshold if the caller has the necessary attribute.
716   if (Caller->optForMinSize()) {
717     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
718     // For minsize, we want to disable the single BB bonus and the vector
719     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
720     // a static function will, at the minimum, eliminate the parameter setup and
721     // call/return instructions.
722     SingleBBBonusPercent = 0;
723     VectorBonusPercent = 0;
724   } else if (Caller->optForSize())
725     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
726 
727   // Adjust the threshold based on inlinehint attribute and profile based
728   // hotness information if the caller does not have MinSize attribute.
729   if (!Caller->optForMinSize()) {
730     if (Callee.hasFnAttribute(Attribute::InlineHint))
731       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
732     if (PSI) {
733       BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr;
734       // FIXME: After switching to the new passmanager, simplify the logic below
735       // by checking only the callsite hotness/coldness. The check for CallerBFI
736       // exists only because we do not have BFI available with the old PM.
737       //
738       // Use callee's hotness information only if we have no way of determining
739       // callsite's hotness information. Callsite hotness can be determined if
740       // sample profile is used (which adds hotness metadata to calls) or if
741       // caller's BlockFrequencyInfo is available.
742       if (CallerBFI || PSI->hasSampleProfile()) {
743         if (PSI->isHotCallSite(CS, CallerBFI)) {
744           DEBUG(dbgs() << "Hot callsite.\n");
745           Threshold = Params.HotCallSiteThreshold.getValue();
746         } else if (isColdCallSite(CS, CallerBFI)) {
747           DEBUG(dbgs() << "Cold callsite.\n");
748           // Do not apply bonuses for a cold callsite including the
749           // LastCallToStatic bonus. While this bonus might result in code size
750           // reduction, it can cause the size of a non-cold caller to increase
751           // preventing it from being inlined.
752           DisallowAllBonuses();
753           Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
754         }
755       } else {
756         if (PSI->isFunctionEntryHot(&Callee)) {
757           DEBUG(dbgs() << "Hot callee.\n");
758           // If callsite hotness can not be determined, we may still know
759           // that the callee is hot and treat it as a weaker hint for threshold
760           // increase.
761           Threshold = MaxIfValid(Threshold, Params.HintThreshold);
762         } else if (PSI->isFunctionEntryCold(&Callee)) {
763           DEBUG(dbgs() << "Cold callee.\n");
764           // Do not apply bonuses for a cold callee including the
765           // LastCallToStatic bonus. While this bonus might result in code size
766           // reduction, it can cause the size of a non-cold caller to increase
767           // preventing it from being inlined.
768           DisallowAllBonuses();
769           Threshold = MinIfValid(Threshold, Params.ColdThreshold);
770         }
771       }
772     }
773   }
774 
775   // Finally, take the target-specific inlining threshold multiplier into
776   // account.
777   Threshold *= TTI.getInliningThresholdMultiplier();
778 
779   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
780   VectorBonus = Threshold * VectorBonusPercent / 100;
781 
782   bool OnlyOneCallAndLocalLinkage =
783       F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction();
784   // If there is only one call of the function, and it has internal linkage,
785   // the cost of inlining it drops dramatically. It may seem odd to update
786   // Cost in updateThreshold, but the bonus depends on the logic in this method.
787   if (OnlyOneCallAndLocalLinkage)
788     Cost -= LastCallToStaticBonus;
789 }
790 
791 bool CallAnalyzer::visitCmpInst(CmpInst &I) {
792   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
793   // First try to handle simplified comparisons.
794   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
795         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
796       }))
797     return true;
798 
799   if (I.getOpcode() == Instruction::FCmp)
800     return false;
801 
802   // Otherwise look for a comparison between constant offset pointers with
803   // a common base.
804   Value *LHSBase, *RHSBase;
805   APInt LHSOffset, RHSOffset;
806   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
807   if (LHSBase) {
808     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
809     if (RHSBase && LHSBase == RHSBase) {
810       // We have common bases, fold the icmp to a constant based on the
811       // offsets.
812       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
813       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
814       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
815         SimplifiedValues[&I] = C;
816         ++NumConstantPtrCmps;
817         return true;
818       }
819     }
820   }
821 
822   // If the comparison is an equality comparison with null, we can simplify it
823   // if we know the value (argument) can't be null
824   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
825       isKnownNonNullInCallee(I.getOperand(0))) {
826     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
827     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
828                                       : ConstantInt::getFalse(I.getType());
829     return true;
830   }
831   // Finally check for SROA candidates in comparisons.
832   Value *SROAArg;
833   DenseMap<Value *, int>::iterator CostIt;
834   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
835     if (isa<ConstantPointerNull>(I.getOperand(1))) {
836       accumulateSROACost(CostIt, InlineConstants::InstrCost);
837       return true;
838     }
839 
840     disableSROA(CostIt);
841   }
842 
843   return false;
844 }
845 
846 bool CallAnalyzer::visitSub(BinaryOperator &I) {
847   // Try to handle a special case: we can fold computing the difference of two
848   // constant-related pointers.
849   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
850   Value *LHSBase, *RHSBase;
851   APInt LHSOffset, RHSOffset;
852   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
853   if (LHSBase) {
854     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
855     if (RHSBase && LHSBase == RHSBase) {
856       // We have common bases, fold the subtract to a constant based on the
857       // offsets.
858       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
859       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
860       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
861         SimplifiedValues[&I] = C;
862         ++NumConstantPtrDiffs;
863         return true;
864       }
865     }
866   }
867 
868   // Otherwise, fall back to the generic logic for simplifying and handling
869   // instructions.
870   return Base::visitSub(I);
871 }
872 
873 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
874   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
875   auto Evaluate = [&](SmallVectorImpl<Constant *> &COps) {
876     Value *SimpleV = nullptr;
877     if (auto FI = dyn_cast<FPMathOperator>(&I))
878       SimpleV = SimplifyFPBinOp(I.getOpcode(), COps[0], COps[1],
879                                 FI->getFastMathFlags(), DL);
880     else
881       SimpleV = SimplifyBinOp(I.getOpcode(), COps[0], COps[1], DL);
882     return dyn_cast_or_null<Constant>(SimpleV);
883   };
884 
885   if (simplifyInstruction(I, Evaluate))
886     return true;
887 
888   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
889   disableSROA(LHS);
890   disableSROA(RHS);
891 
892   return false;
893 }
894 
895 bool CallAnalyzer::visitLoad(LoadInst &I) {
896   Value *SROAArg;
897   DenseMap<Value *, int>::iterator CostIt;
898   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
899     if (I.isSimple()) {
900       accumulateSROACost(CostIt, InlineConstants::InstrCost);
901       return true;
902     }
903 
904     disableSROA(CostIt);
905   }
906 
907   return false;
908 }
909 
910 bool CallAnalyzer::visitStore(StoreInst &I) {
911   Value *SROAArg;
912   DenseMap<Value *, int>::iterator CostIt;
913   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
914     if (I.isSimple()) {
915       accumulateSROACost(CostIt, InlineConstants::InstrCost);
916       return true;
917     }
918 
919     disableSROA(CostIt);
920   }
921 
922   return false;
923 }
924 
925 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
926   // Constant folding for extract value is trivial.
927   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
928         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
929       }))
930     return true;
931 
932   // SROA can look through these but give them a cost.
933   return false;
934 }
935 
936 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
937   // Constant folding for insert value is trivial.
938   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
939         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
940                                             /*InsertedValueOperand*/ COps[1],
941                                             I.getIndices());
942       }))
943     return true;
944 
945   // SROA can look through these but give them a cost.
946   return false;
947 }
948 
949 /// \brief Try to simplify a call site.
950 ///
951 /// Takes a concrete function and callsite and tries to actually simplify it by
952 /// analyzing the arguments and call itself with instsimplify. Returns true if
953 /// it has simplified the callsite to some other entity (a constant), making it
954 /// free.
955 bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
956   // FIXME: Using the instsimplify logic directly for this is inefficient
957   // because we have to continually rebuild the argument list even when no
958   // simplifications can be performed. Until that is fixed with remapping
959   // inside of instsimplify, directly constant fold calls here.
960   if (!canConstantFoldCallTo(CS, F))
961     return false;
962 
963   // Try to re-map the arguments to constants.
964   SmallVector<Constant *, 4> ConstantArgs;
965   ConstantArgs.reserve(CS.arg_size());
966   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E;
967        ++I) {
968     Constant *C = dyn_cast<Constant>(*I);
969     if (!C)
970       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
971     if (!C)
972       return false; // This argument doesn't map to a constant.
973 
974     ConstantArgs.push_back(C);
975   }
976   if (Constant *C = ConstantFoldCall(CS, F, ConstantArgs)) {
977     SimplifiedValues[CS.getInstruction()] = C;
978     return true;
979   }
980 
981   return false;
982 }
983 
984 bool CallAnalyzer::visitCallSite(CallSite CS) {
985   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
986       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
987     // This aborts the entire analysis.
988     ExposesReturnsTwice = true;
989     return false;
990   }
991   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->cannotDuplicate())
992     ContainsNoDuplicateCall = true;
993 
994   if (Function *F = CS.getCalledFunction()) {
995     // When we have a concrete function, first try to simplify it directly.
996     if (simplifyCallSite(F, CS))
997       return true;
998 
999     // Next check if it is an intrinsic we know about.
1000     // FIXME: Lift this into part of the InstVisitor.
1001     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
1002       switch (II->getIntrinsicID()) {
1003       default:
1004         return Base::visitCallSite(CS);
1005 
1006       case Intrinsic::load_relative:
1007         // This is normally lowered to 4 LLVM instructions.
1008         Cost += 3 * InlineConstants::InstrCost;
1009         return false;
1010 
1011       case Intrinsic::memset:
1012       case Intrinsic::memcpy:
1013       case Intrinsic::memmove:
1014         // SROA can usually chew through these intrinsics, but they aren't free.
1015         return false;
1016       case Intrinsic::localescape:
1017         HasFrameEscape = true;
1018         return false;
1019       }
1020     }
1021 
1022     if (F == CS.getInstruction()->getParent()->getParent()) {
1023       // This flag will fully abort the analysis, so don't bother with anything
1024       // else.
1025       IsRecursiveCall = true;
1026       return false;
1027     }
1028 
1029     if (TTI.isLoweredToCall(F)) {
1030       // We account for the average 1 instruction per call argument setup
1031       // here.
1032       Cost += CS.arg_size() * InlineConstants::InstrCost;
1033 
1034       // Everything other than inline ASM will also have a significant cost
1035       // merely from making the call.
1036       if (!isa<InlineAsm>(CS.getCalledValue()))
1037         Cost += InlineConstants::CallPenalty;
1038     }
1039 
1040     return Base::visitCallSite(CS);
1041   }
1042 
1043   // Otherwise we're in a very special case -- an indirect function call. See
1044   // if we can be particularly clever about this.
1045   Value *Callee = CS.getCalledValue();
1046 
1047   // First, pay the price of the argument setup. We account for the average
1048   // 1 instruction per call argument setup here.
1049   Cost += CS.arg_size() * InlineConstants::InstrCost;
1050 
1051   // Next, check if this happens to be an indirect function call to a known
1052   // function in this inline context. If not, we've done all we can.
1053   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
1054   if (!F)
1055     return Base::visitCallSite(CS);
1056 
1057   // If we have a constant that we are calling as a function, we can peer
1058   // through it and see the function target. This happens not infrequently
1059   // during devirtualization and so we want to give it a hefty bonus for
1060   // inlining, but cap that bonus in the event that inlining wouldn't pan
1061   // out. Pretend to inline the function, with a custom threshold.
1062   auto IndirectCallParams = Params;
1063   IndirectCallParams.DefaultThreshold = InlineConstants::IndirectCallThreshold;
1064   CallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, *F, CS,
1065                   IndirectCallParams);
1066   if (CA.analyzeCall(CS)) {
1067     // We were able to inline the indirect call! Subtract the cost from the
1068     // threshold to get the bonus we want to apply, but don't go below zero.
1069     Cost -= std::max(0, CA.getThreshold() - CA.getCost());
1070   }
1071 
1072   return Base::visitCallSite(CS);
1073 }
1074 
1075 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
1076   // At least one return instruction will be free after inlining.
1077   bool Free = !HasReturn;
1078   HasReturn = true;
1079   return Free;
1080 }
1081 
1082 bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
1083   // We model unconditional branches as essentially free -- they really
1084   // shouldn't exist at all, but handling them makes the behavior of the
1085   // inliner more regular and predictable. Interestingly, conditional branches
1086   // which will fold away are also free.
1087   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
1088          dyn_cast_or_null<ConstantInt>(
1089              SimplifiedValues.lookup(BI.getCondition()));
1090 }
1091 
1092 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
1093   // We model unconditional switches as free, see the comments on handling
1094   // branches.
1095   if (isa<ConstantInt>(SI.getCondition()))
1096     return true;
1097   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
1098     if (isa<ConstantInt>(V))
1099       return true;
1100 
1101   // Assume the most general case where the switch is lowered into
1102   // either a jump table, bit test, or a balanced binary tree consisting of
1103   // case clusters without merging adjacent clusters with the same
1104   // destination. We do not consider the switches that are lowered with a mix
1105   // of jump table/bit test/binary search tree. The cost of the switch is
1106   // proportional to the size of the tree or the size of jump table range.
1107   //
1108   // NB: We convert large switches which are just used to initialize large phi
1109   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
1110   // inlining those. It will prevent inlining in cases where the optimization
1111   // does not (yet) fire.
1112 
1113   // Maximum valid cost increased in this function.
1114   int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
1115 
1116   // Exit early for a large switch, assuming one case needs at least one
1117   // instruction.
1118   // FIXME: This is not true for a bit test, but ignore such case for now to
1119   // save compile-time.
1120   int64_t CostLowerBound =
1121       std::min((int64_t)CostUpperBound,
1122                (int64_t)SI.getNumCases() * InlineConstants::InstrCost + Cost);
1123 
1124   if (CostLowerBound > Threshold) {
1125     Cost = CostLowerBound;
1126     return false;
1127   }
1128 
1129   unsigned JumpTableSize = 0;
1130   unsigned NumCaseCluster =
1131       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize);
1132 
1133   // If suitable for a jump table, consider the cost for the table size and
1134   // branch to destination.
1135   if (JumpTableSize) {
1136     int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
1137                      4 * InlineConstants::InstrCost;
1138 
1139     Cost = std::min((int64_t)CostUpperBound, JTCost + Cost);
1140     return false;
1141   }
1142 
1143   // Considering forming a binary search, we should find the number of nodes
1144   // which is same as the number of comparisons when lowered. For a given
1145   // number of clusters, n, we can define a recursive function, f(n), to find
1146   // the number of nodes in the tree. The recursion is :
1147   // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
1148   // and f(n) = n, when n <= 3.
1149   // This will lead a binary tree where the leaf should be either f(2) or f(3)
1150   // when n > 3.  So, the number of comparisons from leaves should be n, while
1151   // the number of non-leaf should be :
1152   //   2^(log2(n) - 1) - 1
1153   //   = 2^log2(n) * 2^-1 - 1
1154   //   = n / 2 - 1.
1155   // Considering comparisons from leaf and non-leaf nodes, we can estimate the
1156   // number of comparisons in a simple closed form :
1157   //   n + n / 2 - 1 = n * 3 / 2 - 1
1158   if (NumCaseCluster <= 3) {
1159     // Suppose a comparison includes one compare and one conditional branch.
1160     Cost += NumCaseCluster * 2 * InlineConstants::InstrCost;
1161     return false;
1162   }
1163 
1164   int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1;
1165   int64_t SwitchCost =
1166       ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
1167 
1168   Cost = std::min((int64_t)CostUpperBound, SwitchCost + Cost);
1169   return false;
1170 }
1171 
1172 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
1173   // We never want to inline functions that contain an indirectbr.  This is
1174   // incorrect because all the blockaddress's (in static global initializers
1175   // for example) would be referring to the original function, and this
1176   // indirect jump would jump from the inlined copy of the function into the
1177   // original function which is extremely undefined behavior.
1178   // FIXME: This logic isn't really right; we can safely inline functions with
1179   // indirectbr's as long as no other function or global references the
1180   // blockaddress of a block within the current function.
1181   HasIndirectBr = true;
1182   return false;
1183 }
1184 
1185 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
1186   // FIXME: It's not clear that a single instruction is an accurate model for
1187   // the inline cost of a resume instruction.
1188   return false;
1189 }
1190 
1191 bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
1192   // FIXME: It's not clear that a single instruction is an accurate model for
1193   // the inline cost of a cleanupret instruction.
1194   return false;
1195 }
1196 
1197 bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
1198   // FIXME: It's not clear that a single instruction is an accurate model for
1199   // the inline cost of a catchret instruction.
1200   return false;
1201 }
1202 
1203 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
1204   // FIXME: It might be reasonably to discount the cost of instructions leading
1205   // to unreachable as they have the lowest possible impact on both runtime and
1206   // code size.
1207   return true; // No actual code is needed for unreachable.
1208 }
1209 
1210 bool CallAnalyzer::visitInstruction(Instruction &I) {
1211   // Some instructions are free. All of the free intrinsics can also be
1212   // handled by SROA, etc.
1213   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
1214     return true;
1215 
1216   // We found something we don't understand or can't handle. Mark any SROA-able
1217   // values in the operand list as no longer viable.
1218   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
1219     disableSROA(*OI);
1220 
1221   return false;
1222 }
1223 
1224 /// \brief Analyze a basic block for its contribution to the inline cost.
1225 ///
1226 /// This method walks the analyzer over every instruction in the given basic
1227 /// block and accounts for their cost during inlining at this callsite. It
1228 /// aborts early if the threshold has been exceeded or an impossible to inline
1229 /// construct has been detected. It returns false if inlining is no longer
1230 /// viable, and true if inlining remains viable.
1231 bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
1232                                 SmallPtrSetImpl<const Value *> &EphValues) {
1233   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1234     // FIXME: Currently, the number of instructions in a function regardless of
1235     // our ability to simplify them during inline to constants or dead code,
1236     // are actually used by the vector bonus heuristic. As long as that's true,
1237     // we have to special case debug intrinsics here to prevent differences in
1238     // inlining due to debug symbols. Eventually, the number of unsimplified
1239     // instructions shouldn't factor into the cost computation, but until then,
1240     // hack around it here.
1241     if (isa<DbgInfoIntrinsic>(I))
1242       continue;
1243 
1244     // Skip ephemeral values.
1245     if (EphValues.count(&*I))
1246       continue;
1247 
1248     ++NumInstructions;
1249     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
1250       ++NumVectorInstructions;
1251 
1252     // If the instruction is floating point, and the target says this operation
1253     // is expensive or the function has the "use-soft-float" attribute, this may
1254     // eventually become a library call. Treat the cost as such.
1255     if (I->getType()->isFloatingPointTy()) {
1256       // If the function has the "use-soft-float" attribute, mark it as
1257       // expensive.
1258       if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
1259           (F.getFnAttribute("use-soft-float").getValueAsString() == "true"))
1260         Cost += InlineConstants::CallPenalty;
1261     }
1262 
1263     // If the instruction simplified to a constant, there is no cost to this
1264     // instruction. Visit the instructions using our InstVisitor to account for
1265     // all of the per-instruction logic. The visit tree returns true if we
1266     // consumed the instruction in any way, and false if the instruction's base
1267     // cost should count against inlining.
1268     if (Base::visit(&*I))
1269       ++NumInstructionsSimplified;
1270     else
1271       Cost += InlineConstants::InstrCost;
1272 
1273     // If the visit this instruction detected an uninlinable pattern, abort.
1274     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
1275         HasIndirectBr || HasFrameEscape)
1276       return false;
1277 
1278     // If the caller is a recursive function then we don't want to inline
1279     // functions which allocate a lot of stack space because it would increase
1280     // the caller stack usage dramatically.
1281     if (IsCallerRecursive &&
1282         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1283       return false;
1284 
1285     // Check if we've past the maximum possible threshold so we don't spin in
1286     // huge basic blocks that will never inline.
1287     if (Cost > Threshold)
1288       return false;
1289   }
1290 
1291   return true;
1292 }
1293 
1294 /// \brief Compute the base pointer and cumulative constant offsets for V.
1295 ///
1296 /// This strips all constant offsets off of V, leaving it the base pointer, and
1297 /// accumulates the total constant offset applied in the returned constant. It
1298 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
1299 /// no constant offsets applied.
1300 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
1301   if (!V->getType()->isPointerTy())
1302     return nullptr;
1303 
1304   unsigned IntPtrWidth = DL.getPointerSizeInBits();
1305   APInt Offset = APInt::getNullValue(IntPtrWidth);
1306 
1307   // Even though we don't look through PHI nodes, we could be called on an
1308   // instruction in an unreachable block, which may be on a cycle.
1309   SmallPtrSet<Value *, 4> Visited;
1310   Visited.insert(V);
1311   do {
1312     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1313       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
1314         return nullptr;
1315       V = GEP->getPointerOperand();
1316     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1317       V = cast<Operator>(V)->getOperand(0);
1318     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1319       if (GA->isInterposable())
1320         break;
1321       V = GA->getAliasee();
1322     } else {
1323       break;
1324     }
1325     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1326   } while (Visited.insert(V).second);
1327 
1328   Type *IntPtrTy = DL.getIntPtrType(V->getContext());
1329   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
1330 }
1331 
1332 /// \brief Analyze a call site for potential inlining.
1333 ///
1334 /// Returns true if inlining this call is viable, and false if it is not
1335 /// viable. It computes the cost and adjusts the threshold based on numerous
1336 /// factors and heuristics. If this method returns false but the computed cost
1337 /// is below the computed threshold, then inlining was forcibly disabled by
1338 /// some artifact of the routine.
1339 bool CallAnalyzer::analyzeCall(CallSite CS) {
1340   ++NumCallsAnalyzed;
1341 
1342   // Perform some tweaks to the cost and threshold based on the direct
1343   // callsite information.
1344 
1345   // We want to more aggressively inline vector-dense kernels, so up the
1346   // threshold, and we'll lower it if the % of vector instructions gets too
1347   // low. Note that these bonuses are some what arbitrary and evolved over time
1348   // by accident as much as because they are principled bonuses.
1349   //
1350   // FIXME: It would be nice to remove all such bonuses. At least it would be
1351   // nice to base the bonus values on something more scientific.
1352   assert(NumInstructions == 0);
1353   assert(NumVectorInstructions == 0);
1354 
1355   // Update the threshold based on callsite properties
1356   updateThreshold(CS, F);
1357 
1358   // Speculatively apply all possible bonuses to Threshold. If cost exceeds
1359   // this Threshold any time, and cost cannot decrease, we can stop processing
1360   // the rest of the function body.
1361   Threshold += (SingleBBBonus + VectorBonus);
1362 
1363   // Give out bonuses for the callsite, as the instructions setting them up
1364   // will be gone after inlining.
1365   Cost -= getCallsiteCost(CS, DL);
1366 
1367   // If this function uses the coldcc calling convention, prefer not to inline
1368   // it.
1369   if (F.getCallingConv() == CallingConv::Cold)
1370     Cost += InlineConstants::ColdccPenalty;
1371 
1372   // Check if we're done. This can happen due to bonuses and penalties.
1373   if (Cost > Threshold)
1374     return false;
1375 
1376   if (F.empty())
1377     return true;
1378 
1379   Function *Caller = CS.getInstruction()->getParent()->getParent();
1380   // Check if the caller function is recursive itself.
1381   for (User *U : Caller->users()) {
1382     CallSite Site(U);
1383     if (!Site)
1384       continue;
1385     Instruction *I = Site.getInstruction();
1386     if (I->getParent()->getParent() == Caller) {
1387       IsCallerRecursive = true;
1388       break;
1389     }
1390   }
1391 
1392   // Populate our simplified values by mapping from function arguments to call
1393   // arguments with known important simplifications.
1394   CallSite::arg_iterator CAI = CS.arg_begin();
1395   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
1396        FAI != FAE; ++FAI, ++CAI) {
1397     assert(CAI != CS.arg_end());
1398     if (Constant *C = dyn_cast<Constant>(CAI))
1399       SimplifiedValues[&*FAI] = C;
1400 
1401     Value *PtrArg = *CAI;
1402     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1403       ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
1404 
1405       // We can SROA any pointer arguments derived from alloca instructions.
1406       if (isa<AllocaInst>(PtrArg)) {
1407         SROAArgValues[&*FAI] = PtrArg;
1408         SROAArgCosts[PtrArg] = 0;
1409       }
1410     }
1411   }
1412   NumConstantArgs = SimplifiedValues.size();
1413   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1414   NumAllocaArgs = SROAArgValues.size();
1415 
1416   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
1417   // the ephemeral values multiple times (and they're completely determined by
1418   // the callee, so this is purely duplicate work).
1419   SmallPtrSet<const Value *, 32> EphValues;
1420   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
1421 
1422   // The worklist of live basic blocks in the callee *after* inlining. We avoid
1423   // adding basic blocks of the callee which can be proven to be dead for this
1424   // particular call site in order to get more accurate cost estimates. This
1425   // requires a somewhat heavyweight iteration pattern: we need to walk the
1426   // basic blocks in a breadth-first order as we insert live successors. To
1427   // accomplish this, prioritizing for small iterations because we exit after
1428   // crossing our threshold, we use a small-size optimized SetVector.
1429   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1430                     SmallPtrSet<BasicBlock *, 16>>
1431       BBSetVector;
1432   BBSetVector BBWorklist;
1433   BBWorklist.insert(&F.getEntryBlock());
1434   bool SingleBB = true;
1435   // Note that we *must not* cache the size, this loop grows the worklist.
1436   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1437     // Bail out the moment we cross the threshold. This means we'll under-count
1438     // the cost, but only when undercounting doesn't matter.
1439     if (Cost > Threshold)
1440       break;
1441 
1442     BasicBlock *BB = BBWorklist[Idx];
1443     if (BB->empty())
1444       continue;
1445 
1446     // Disallow inlining a blockaddress. A blockaddress only has defined
1447     // behavior for an indirect branch in the same function, and we do not
1448     // currently support inlining indirect branches. But, the inliner may not
1449     // see an indirect branch that ends up being dead code at a particular call
1450     // site. If the blockaddress escapes the function, e.g., via a global
1451     // variable, inlining may lead to an invalid cross-function reference.
1452     if (BB->hasAddressTaken())
1453       return false;
1454 
1455     // Analyze the cost of this block. If we blow through the threshold, this
1456     // returns false, and we can bail on out.
1457     if (!analyzeBlock(BB, EphValues))
1458       return false;
1459 
1460     TerminatorInst *TI = BB->getTerminator();
1461 
1462     // Add in the live successors by first checking whether we have terminator
1463     // that may be simplified based on the values simplified by this call.
1464     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1465       if (BI->isConditional()) {
1466         Value *Cond = BI->getCondition();
1467         if (ConstantInt *SimpleCond =
1468                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1469           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1470           continue;
1471         }
1472       }
1473     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1474       Value *Cond = SI->getCondition();
1475       if (ConstantInt *SimpleCond =
1476               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1477         BBWorklist.insert(SI->findCaseValue(SimpleCond)->getCaseSuccessor());
1478         continue;
1479       }
1480     }
1481 
1482     // If we're unable to select a particular successor, just count all of
1483     // them.
1484     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1485          ++TIdx)
1486       BBWorklist.insert(TI->getSuccessor(TIdx));
1487 
1488     // If we had any successors at this point, than post-inlining is likely to
1489     // have them as well. Note that we assume any basic blocks which existed
1490     // due to branches or switches which folded above will also fold after
1491     // inlining.
1492     if (SingleBB && TI->getNumSuccessors() > 1) {
1493       // Take off the bonus we applied to the threshold.
1494       Threshold -= SingleBBBonus;
1495       SingleBB = false;
1496     }
1497   }
1498 
1499   bool OnlyOneCallAndLocalLinkage =
1500       F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction();
1501   // If this is a noduplicate call, we can still inline as long as
1502   // inlining this would cause the removal of the caller (so the instruction
1503   // is not actually duplicated, just moved).
1504   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1505     return false;
1506 
1507   // We applied the maximum possible vector bonus at the beginning. Now,
1508   // subtract the excess bonus, if any, from the Threshold before
1509   // comparing against Cost.
1510   if (NumVectorInstructions <= NumInstructions / 10)
1511     Threshold -= VectorBonus;
1512   else if (NumVectorInstructions <= NumInstructions / 2)
1513     Threshold -= VectorBonus/2;
1514 
1515   return Cost < std::max(1, Threshold);
1516 }
1517 
1518 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1519 /// \brief Dump stats about this call's analysis.
1520 LLVM_DUMP_METHOD void CallAnalyzer::dump() {
1521 #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
1522   DEBUG_PRINT_STAT(NumConstantArgs);
1523   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1524   DEBUG_PRINT_STAT(NumAllocaArgs);
1525   DEBUG_PRINT_STAT(NumConstantPtrCmps);
1526   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1527   DEBUG_PRINT_STAT(NumInstructionsSimplified);
1528   DEBUG_PRINT_STAT(NumInstructions);
1529   DEBUG_PRINT_STAT(SROACostSavings);
1530   DEBUG_PRINT_STAT(SROACostSavingsLost);
1531   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
1532   DEBUG_PRINT_STAT(Cost);
1533   DEBUG_PRINT_STAT(Threshold);
1534 #undef DEBUG_PRINT_STAT
1535 }
1536 #endif
1537 
1538 /// \brief Test that there are no attribute conflicts between Caller and Callee
1539 ///        that prevent inlining.
1540 static bool functionsHaveCompatibleAttributes(Function *Caller,
1541                                               Function *Callee,
1542                                               TargetTransformInfo &TTI) {
1543   return TTI.areInlineCompatible(Caller, Callee) &&
1544          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
1545 }
1546 
1547 int llvm::getCallsiteCost(CallSite CS, const DataLayout &DL) {
1548   int Cost = 0;
1549   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
1550     if (CS.isByValArgument(I)) {
1551       // We approximate the number of loads and stores needed by dividing the
1552       // size of the byval type by the target's pointer size.
1553       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
1554       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
1555       unsigned PointerSize = DL.getPointerSizeInBits();
1556       // Ceiling division.
1557       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
1558 
1559       // If it generates more than 8 stores it is likely to be expanded as an
1560       // inline memcpy so we take that as an upper bound. Otherwise we assume
1561       // one load and one store per word copied.
1562       // FIXME: The maxStoresPerMemcpy setting from the target should be used
1563       // here instead of a magic number of 8, but it's not available via
1564       // DataLayout.
1565       NumStores = std::min(NumStores, 8U);
1566 
1567       Cost += 2 * NumStores * InlineConstants::InstrCost;
1568     } else {
1569       // For non-byval arguments subtract off one instruction per call
1570       // argument.
1571       Cost += InlineConstants::InstrCost;
1572     }
1573   }
1574   // The call instruction also disappears after inlining.
1575   Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty;
1576   return Cost;
1577 }
1578 
1579 InlineCost llvm::getInlineCost(
1580     CallSite CS, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
1581     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
1582     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
1583     ProfileSummaryInfo *PSI) {
1584   return getInlineCost(CS, CS.getCalledFunction(), Params, CalleeTTI,
1585                        GetAssumptionCache, GetBFI, PSI);
1586 }
1587 
1588 InlineCost llvm::getInlineCost(
1589     CallSite CS, Function *Callee, const InlineParams &Params,
1590     TargetTransformInfo &CalleeTTI,
1591     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
1592     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
1593     ProfileSummaryInfo *PSI) {
1594 
1595   // Cannot inline indirect calls.
1596   if (!Callee)
1597     return llvm::InlineCost::getNever();
1598 
1599   // Calls to functions with always-inline attributes should be inlined
1600   // whenever possible.
1601   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
1602     if (isInlineViable(*Callee))
1603       return llvm::InlineCost::getAlways();
1604     return llvm::InlineCost::getNever();
1605   }
1606 
1607   // Never inline functions with conflicting attributes (unless callee has
1608   // always-inline attribute).
1609   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee, CalleeTTI))
1610     return llvm::InlineCost::getNever();
1611 
1612   // Don't inline this call if the caller has the optnone attribute.
1613   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
1614     return llvm::InlineCost::getNever();
1615 
1616   // Don't inline functions which can be interposed at link-time.  Don't inline
1617   // functions marked noinline or call sites marked noinline.
1618   // Note: inlining non-exact non-interposable functions is fine, since we know
1619   // we have *a* correct implementation of the source level function.
1620   if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
1621       CS.isNoInline())
1622     return llvm::InlineCost::getNever();
1623 
1624   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
1625                      << "...\n");
1626 
1627   CallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, *Callee, CS,
1628                   Params);
1629   bool ShouldInline = CA.analyzeCall(CS);
1630 
1631   DEBUG(CA.dump());
1632 
1633   // Check if there was a reason to force inlining or no inlining.
1634   if (!ShouldInline && CA.getCost() < CA.getThreshold())
1635     return InlineCost::getNever();
1636   if (ShouldInline && CA.getCost() >= CA.getThreshold())
1637     return InlineCost::getAlways();
1638 
1639   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
1640 }
1641 
1642 bool llvm::isInlineViable(Function &F) {
1643   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
1644   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1645     // Disallow inlining of functions which contain indirect branches or
1646     // blockaddresses.
1647     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
1648       return false;
1649 
1650     for (auto &II : *BI) {
1651       CallSite CS(&II);
1652       if (!CS)
1653         continue;
1654 
1655       // Disallow recursive calls.
1656       if (&F == CS.getCalledFunction())
1657         return false;
1658 
1659       // Disallow calls which expose returns-twice to a function not previously
1660       // attributed as such.
1661       if (!ReturnsTwice && CS.isCall() &&
1662           cast<CallInst>(CS.getInstruction())->canReturnTwice())
1663         return false;
1664 
1665       // Disallow inlining functions that call @llvm.localescape. Doing this
1666       // correctly would require major changes to the inliner.
1667       if (CS.getCalledFunction() &&
1668           CS.getCalledFunction()->getIntrinsicID() ==
1669               llvm::Intrinsic::localescape)
1670         return false;
1671     }
1672   }
1673 
1674   return true;
1675 }
1676 
1677 // APIs to create InlineParams based on command line flags and/or other
1678 // parameters.
1679 
1680 InlineParams llvm::getInlineParams(int Threshold) {
1681   InlineParams Params;
1682 
1683   // This field is the threshold to use for a callee by default. This is
1684   // derived from one or more of:
1685   //  * optimization or size-optimization levels,
1686   //  * a value passed to createFunctionInliningPass function, or
1687   //  * the -inline-threshold flag.
1688   //  If the -inline-threshold flag is explicitly specified, that is used
1689   //  irrespective of anything else.
1690   if (InlineThreshold.getNumOccurrences() > 0)
1691     Params.DefaultThreshold = InlineThreshold;
1692   else
1693     Params.DefaultThreshold = Threshold;
1694 
1695   // Set the HintThreshold knob from the -inlinehint-threshold.
1696   Params.HintThreshold = HintThreshold;
1697 
1698   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
1699   Params.HotCallSiteThreshold = HotCallSiteThreshold;
1700 
1701   // Set the ColdCallSiteThreshold knob from the -inline-cold-callsite-threshold.
1702   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
1703 
1704   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
1705   // -inlinehint-threshold commandline option is not explicitly given. If that
1706   // option is present, then its value applies even for callees with size and
1707   // minsize attributes.
1708   // If the -inline-threshold is not specified, set the ColdThreshold from the
1709   // -inlinecold-threshold even if it is not explicitly passed. If
1710   // -inline-threshold is specified, then -inlinecold-threshold needs to be
1711   // explicitly specified to set the ColdThreshold knob
1712   if (InlineThreshold.getNumOccurrences() == 0) {
1713     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
1714     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
1715     Params.ColdThreshold = ColdThreshold;
1716   } else if (ColdThreshold.getNumOccurrences() > 0) {
1717     Params.ColdThreshold = ColdThreshold;
1718   }
1719   return Params;
1720 }
1721 
1722 InlineParams llvm::getInlineParams() {
1723   return getInlineParams(InlineThreshold);
1724 }
1725 
1726 // Compute the default threshold for inlining based on the opt level and the
1727 // size opt level.
1728 static int computeThresholdFromOptLevels(unsigned OptLevel,
1729                                          unsigned SizeOptLevel) {
1730   if (OptLevel > 2)
1731     return InlineConstants::OptAggressiveThreshold;
1732   if (SizeOptLevel == 1) // -Os
1733     return InlineConstants::OptSizeThreshold;
1734   if (SizeOptLevel == 2) // -Oz
1735     return InlineConstants::OptMinSizeThreshold;
1736   return InlineThreshold;
1737 }
1738 
1739 InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
1740   return getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
1741 }
1742