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