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