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