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