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