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