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