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