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