17adc3a2bSChandler Carruth //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
27adc3a2bSChandler Carruth //
37adc3a2bSChandler Carruth //                     The LLVM Compiler Infrastructure
47adc3a2bSChandler Carruth //
57adc3a2bSChandler Carruth // This file is distributed under the University of Illinois Open Source
67adc3a2bSChandler Carruth // License. See LICENSE.TXT for details.
77adc3a2bSChandler Carruth //
87adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
97adc3a2bSChandler Carruth //
107adc3a2bSChandler Carruth // This file implements inline cost analysis.
117adc3a2bSChandler Carruth //
127adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
137adc3a2bSChandler Carruth 
147adc3a2bSChandler Carruth #include "llvm/Analysis/InlineCost.h"
157adc3a2bSChandler Carruth #include "llvm/ADT/STLExtras.h"
167adc3a2bSChandler Carruth #include "llvm/ADT/SetVector.h"
177adc3a2bSChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
187adc3a2bSChandler Carruth #include "llvm/ADT/SmallVector.h"
197adc3a2bSChandler Carruth #include "llvm/ADT/Statistic.h"
20aec2fa35SDaniel Jasper #include "llvm/Analysis/AssumptionCache.h"
2112585b01SEaswaran Raman #include "llvm/Analysis/BlockFrequencyInfo.h"
227adc3a2bSChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
237adc3a2bSChandler Carruth #include "llvm/Analysis/ConstantFolding.h"
247adc3a2bSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h"
2571069cf6SEaswaran Raman #include "llvm/Analysis/ProfileSummaryInfo.h"
267adc3a2bSChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
277adc3a2bSChandler Carruth #include "llvm/IR/CallSite.h"
287adc3a2bSChandler Carruth #include "llvm/IR/CallingConv.h"
297adc3a2bSChandler Carruth #include "llvm/IR/DataLayout.h"
307adc3a2bSChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
317adc3a2bSChandler Carruth #include "llvm/IR/GlobalAlias.h"
327adc3a2bSChandler Carruth #include "llvm/IR/InstVisitor.h"
337adc3a2bSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
347adc3a2bSChandler Carruth #include "llvm/IR/Operator.h"
357adc3a2bSChandler Carruth #include "llvm/Support/Debug.h"
367adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h"
377adc3a2bSChandler Carruth 
387adc3a2bSChandler Carruth using namespace llvm;
397adc3a2bSChandler Carruth 
407adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost"
417adc3a2bSChandler Carruth 
427adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
437adc3a2bSChandler Carruth 
441c57cc2bSEaswaran Raman static cl::opt<int> InlineThreshold(
45f4bb2f0dSEaswaran Raman     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
46f4bb2f0dSEaswaran Raman     cl::desc("Control the amount of inlining to perform (default = 225)"));
47f4bb2f0dSEaswaran Raman 
48f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold(
49f4bb2f0dSEaswaran Raman     "inlinehint-threshold", cl::Hidden, cl::init(325),
50f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with inline hint"));
51f4bb2f0dSEaswaran Raman 
5212585b01SEaswaran Raman static cl::opt<int>
5312585b01SEaswaran Raman     ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
5412585b01SEaswaran Raman                           cl::init(45),
5512585b01SEaswaran Raman                           cl::desc("Threshold for inlining cold callsites"));
5612585b01SEaswaran Raman 
57f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based
58f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and
59f4bb2f0dSEaswaran Raman // BFI.
60f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold(
61c103ef89SEaswaran Raman     "inlinecold-threshold", cl::Hidden, cl::init(45),
62f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with cold attribute"));
63f4bb2f0dSEaswaran Raman 
64de39cb93SDehao Chen static cl::opt<int>
65de39cb93SDehao Chen     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
66de39cb93SDehao Chen                          cl::ZeroOrMore,
67de39cb93SDehao Chen                          cl::desc("Threshold for hot callsites "));
68de39cb93SDehao Chen 
69974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold(
70974d4eeaSEaswaran Raman     "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore,
71974d4eeaSEaswaran Raman     cl::desc("Threshold for locally hot callsites "));
72974d4eeaSEaswaran Raman 
73c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq(
74c5fa6358SEaswaran Raman     "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
75c5fa6358SEaswaran Raman     cl::desc("Maxmimum block frequency, expressed as a percentage of caller's "
76c5fa6358SEaswaran Raman              "entry frequency, for a callsite to be cold in the absence of "
77c5fa6358SEaswaran Raman              "profile information."));
78c5fa6358SEaswaran Raman 
79974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq(
80974d4eeaSEaswaran Raman     "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore,
81ff77cc75SEaswaran Raman     cl::desc("Minimum block frequency, expressed as a multiple of caller's "
82974d4eeaSEaswaran Raman              "entry frequency, for a callsite to be hot in the absence of "
83974d4eeaSEaswaran Raman              "profile information."));
84974d4eeaSEaswaran Raman 
854924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost(
860812c5beSHaicheng Wu     "inline-cost-full", cl::Hidden, cl::init(false),
870812c5beSHaicheng Wu     cl::desc("Compute the full inline cost of a call site even when the cost "
880812c5beSHaicheng Wu              "exceeds the threshold."));
890812c5beSHaicheng Wu 
907adc3a2bSChandler Carruth namespace {
917adc3a2bSChandler Carruth 
927adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
937adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
947adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
957adc3a2bSChandler Carruth 
967adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
977adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
987adc3a2bSChandler Carruth 
99aec2fa35SDaniel Jasper   /// Getter for the cache of @llvm.assume intrinsics.
100aec2fa35SDaniel Jasper   std::function<AssumptionCache &(Function &)> &GetAssumptionCache;
101aec2fa35SDaniel Jasper 
10212585b01SEaswaran Raman   /// Getter for BlockFrequencyInfo
10312585b01SEaswaran Raman   Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI;
10412585b01SEaswaran Raman 
10571069cf6SEaswaran Raman   /// Profile summary information.
10671069cf6SEaswaran Raman   ProfileSummaryInfo *PSI;
10771069cf6SEaswaran Raman 
108f3d122cdSPiotr Padlewski   /// The called function.
1097adc3a2bSChandler Carruth   Function &F;
1107adc3a2bSChandler Carruth 
11185be8ca8SEric Christopher   // Cache the DataLayout since we use it a lot.
11285be8ca8SEric Christopher   const DataLayout &DL;
11385be8ca8SEric Christopher 
1140812c5beSHaicheng Wu   /// The OptimizationRemarkEmitter available for this compilation.
1150812c5beSHaicheng Wu   OptimizationRemarkEmitter *ORE;
1160812c5beSHaicheng Wu 
117f3d122cdSPiotr Padlewski   /// The candidate callsite being analyzed. Please do not use this to do
118f3d122cdSPiotr Padlewski   /// analysis in the caller function; we want the inline cost query to be
119f3d122cdSPiotr Padlewski   /// easily cacheable. Instead, use the cover function paramHasAttr.
1207adc3a2bSChandler Carruth   CallSite CandidateCS;
1217adc3a2bSChandler Carruth 
122f3d122cdSPiotr Padlewski   /// Tunable parameters that control the analysis.
1231c57cc2bSEaswaran Raman   const InlineParams &Params;
1241c57cc2bSEaswaran Raman 
1257adc3a2bSChandler Carruth   int Threshold;
1267adc3a2bSChandler Carruth   int Cost;
1274924bb00SEaswaran Raman   bool ComputeFullInlineCost;
1287adc3a2bSChandler Carruth 
1297adc3a2bSChandler Carruth   bool IsCallerRecursive;
1307adc3a2bSChandler Carruth   bool IsRecursiveCall;
1317adc3a2bSChandler Carruth   bool ExposesReturnsTwice;
1327adc3a2bSChandler Carruth   bool HasDynamicAlloca;
1337adc3a2bSChandler Carruth   bool ContainsNoDuplicateCall;
1347adc3a2bSChandler Carruth   bool HasReturn;
1357adc3a2bSChandler Carruth   bool HasIndirectBr;
1367adc3a2bSChandler Carruth   bool HasFrameEscape;
1377adc3a2bSChandler Carruth 
1387adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
1397adc3a2bSChandler Carruth   uint64_t AllocatedSize;
1407adc3a2bSChandler Carruth   unsigned NumInstructions, NumVectorInstructions;
14151b809bfSEaswaran Raman   int VectorBonus, TenPercentVectorBonus;
14251b809bfSEaswaran Raman   // Bonus to be applied when the callee has only one reachable basic block.
14351b809bfSEaswaran Raman   int SingleBBBonus;
1447adc3a2bSChandler Carruth 
145f3d122cdSPiotr Padlewski   /// While we walk the potentially-inlined instructions, we build up and
146f3d122cdSPiotr Padlewski   /// maintain a mapping of simplified values specific to this callsite. The
147f3d122cdSPiotr Padlewski   /// idea is to propagate any special information we have about arguments to
148f3d122cdSPiotr Padlewski   /// this call through the inlinable section of the function, and account for
149f3d122cdSPiotr Padlewski   /// likely simplifications post-inlining. The most important aspect we track
150f3d122cdSPiotr Padlewski   /// is CFG altering simplifications -- when we prove a basic block dead, that
151f3d122cdSPiotr Padlewski   /// can cause dramatic shifts in the cost of inlining a function.
1527adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
1537adc3a2bSChandler Carruth 
154f3d122cdSPiotr Padlewski   /// Keep track of the values which map back (through function arguments) to
155f3d122cdSPiotr Padlewski   /// allocas on the caller stack which could be simplified through SROA.
1567adc3a2bSChandler Carruth   DenseMap<Value *, Value *> SROAArgValues;
1577adc3a2bSChandler Carruth 
158f3d122cdSPiotr Padlewski   /// The mapping of caller Alloca values to their accumulated cost savings. If
159f3d122cdSPiotr Padlewski   /// we have to disable SROA for one of the allocas, this tells us how much
160f3d122cdSPiotr Padlewski   /// cost must be added.
1617adc3a2bSChandler Carruth   DenseMap<Value *, int> SROAArgCosts;
1627adc3a2bSChandler Carruth 
163f3d122cdSPiotr Padlewski   /// Keep track of values which map to a pointer base and constant offset.
1647adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
1657adc3a2bSChandler Carruth 
1667adc3a2bSChandler Carruth   // Custom simplification helper routines.
1677adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
1687adc3a2bSChandler Carruth   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
1697adc3a2bSChandler Carruth                             DenseMap<Value *, int>::iterator &CostIt);
1707adc3a2bSChandler Carruth   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
1717adc3a2bSChandler Carruth   void disableSROA(Value *V);
1727adc3a2bSChandler Carruth   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
1737adc3a2bSChandler Carruth                           int InstructionCost);
174201b191bSHaicheng Wu   bool isGEPFree(GetElementPtrInst &GEP);
1757adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
1767adc3a2bSChandler Carruth   bool simplifyCallSite(Function *F, CallSite CS);
177617f6364SEaswaran Raman   template <typename Callable>
178617f6364SEaswaran Raman   bool simplifyInstruction(Instruction &I, Callable Evaluate);
1797adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
1807adc3a2bSChandler Carruth 
1817adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
1827adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
1837adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
1847adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
1857adc3a2bSChandler Carruth   /// itself.
1867adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
1877adc3a2bSChandler Carruth 
1887adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
1897adc3a2bSChandler Carruth   /// inlined through this particular callsite.
1907adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
1917adc3a2bSChandler Carruth 
192f4bb2f0dSEaswaran Raman   /// Update Threshold based on callsite properties such as callee
193f4bb2f0dSEaswaran Raman   /// attributes and callee hotness for PGO builds. The Callee is explicitly
194f4bb2f0dSEaswaran Raman   /// passed to support analyzing indirect calls whose target is inferred by
195f4bb2f0dSEaswaran Raman   /// analysis.
196f4bb2f0dSEaswaran Raman   void updateThreshold(CallSite CS, Function &Callee);
197f4bb2f0dSEaswaran Raman 
1989a3fc17aSEaswaran Raman   /// Return true if size growth is allowed when inlining the callee at CS.
1999a3fc17aSEaswaran Raman   bool allowSizeGrowth(CallSite CS);
2009a3fc17aSEaswaran Raman 
201c5fa6358SEaswaran Raman   /// Return true if \p CS is a cold callsite.
202c5fa6358SEaswaran Raman   bool isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI);
203c5fa6358SEaswaran Raman 
204974d4eeaSEaswaran Raman   /// Return a higher threshold if \p CS is a hot callsite.
205974d4eeaSEaswaran Raman   Optional<int> getHotCallSiteThreshold(CallSite CS,
206974d4eeaSEaswaran Raman                                         BlockFrequencyInfo *CallerBFI);
207974d4eeaSEaswaran Raman 
2087adc3a2bSChandler Carruth   // Custom analysis routines.
2097adc3a2bSChandler Carruth   bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
2107adc3a2bSChandler Carruth 
2117adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
2127adc3a2bSChandler Carruth   // them by declaring but not defining them here.
213567556aaSChad Rosier   void visit(Module *);
214567556aaSChad Rosier   void visit(Module &);
215567556aaSChad Rosier   void visit(Function *);
216567556aaSChad Rosier   void visit(Function &);
217567556aaSChad Rosier   void visit(BasicBlock *);
218567556aaSChad Rosier   void visit(BasicBlock &);
2197adc3a2bSChandler Carruth 
2207adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
2217adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
2227adc3a2bSChandler Carruth 
2237adc3a2bSChandler Carruth   // Our visit overrides.
2247adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
2257adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
2267adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
2277adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
2287adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
2297adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
2307adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
2317adc3a2bSChandler Carruth   bool visitUnaryInstruction(UnaryInstruction &I);
2327adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
2332e1c050eSChad Rosier   bool visitAnd(BinaryOperator &I);
2342e1c050eSChad Rosier   bool visitOr(BinaryOperator &I);
2357adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
2367adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
2377adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
2387adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
2397adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
2407adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
2417adc3a2bSChandler Carruth   bool visitCallSite(CallSite CS);
2427adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
2437adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
244*3ec848bcSHaicheng Wu   bool visitSelectInst(SelectInst &SI);
2457adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
2467adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
2477adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
2487adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
2497adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
2507adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
2517adc3a2bSChandler Carruth 
2527adc3a2bSChandler Carruth public:
253ab6a6837SSean Silva   CallAnalyzer(const TargetTransformInfo &TTI,
254aec2fa35SDaniel Jasper                std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
25512585b01SEaswaran Raman                Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI,
2560812c5beSHaicheng Wu                ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE,
2570812c5beSHaicheng Wu                Function &Callee, CallSite CSArg, const InlineParams &Params)
25812585b01SEaswaran Raman       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
2590812c5beSHaicheng Wu         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
26085be8ca8SEric Christopher         CandidateCS(CSArg), Params(Params), Threshold(Params.DefaultThreshold),
2614924bb00SEaswaran Raman         Cost(0), ComputeFullInlineCost(OptComputeFullInlineCost ||
2624924bb00SEaswaran Raman                                        Params.ComputeFullInlineCost || ORE),
2634924bb00SEaswaran Raman         IsCallerRecursive(false), IsRecursiveCall(false),
26485be8ca8SEric Christopher         ExposesReturnsTwice(false), HasDynamicAlloca(false),
26585be8ca8SEric Christopher         ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
26685be8ca8SEric Christopher         HasFrameEscape(false), AllocatedSize(0), NumInstructions(0),
26751b809bfSEaswaran Raman         NumVectorInstructions(0), VectorBonus(0), SingleBBBonus(0),
26851b809bfSEaswaran Raman         NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
26951b809bfSEaswaran Raman         NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
27051b809bfSEaswaran Raman         NumInstructionsSimplified(0), SROACostSavings(0),
27151b809bfSEaswaran Raman         SROACostSavingsLost(0) {}
2727adc3a2bSChandler Carruth 
2737adc3a2bSChandler Carruth   bool analyzeCall(CallSite CS);
2747adc3a2bSChandler Carruth 
2757adc3a2bSChandler Carruth   int getThreshold() { return Threshold; }
2767adc3a2bSChandler Carruth   int getCost() { return Cost; }
2777adc3a2bSChandler Carruth 
2787adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
2797adc3a2bSChandler Carruth   // out when debugging.
2807adc3a2bSChandler Carruth   unsigned NumConstantArgs;
2817adc3a2bSChandler Carruth   unsigned NumConstantOffsetPtrArgs;
2827adc3a2bSChandler Carruth   unsigned NumAllocaArgs;
2837adc3a2bSChandler Carruth   unsigned NumConstantPtrCmps;
2847adc3a2bSChandler Carruth   unsigned NumConstantPtrDiffs;
2857adc3a2bSChandler Carruth   unsigned NumInstructionsSimplified;
2867adc3a2bSChandler Carruth   unsigned SROACostSavings;
2877adc3a2bSChandler Carruth   unsigned SROACostSavingsLost;
2887adc3a2bSChandler Carruth 
2897adc3a2bSChandler Carruth   void dump();
2907adc3a2bSChandler Carruth };
2917adc3a2bSChandler Carruth 
2927adc3a2bSChandler Carruth } // namespace
2937adc3a2bSChandler Carruth 
2947adc3a2bSChandler Carruth /// \brief Test whether the given value is an Alloca-derived function argument.
2957adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
2967adc3a2bSChandler Carruth   return SROAArgValues.count(V);
2977adc3a2bSChandler Carruth }
2987adc3a2bSChandler Carruth 
2997adc3a2bSChandler Carruth /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
3007adc3a2bSChandler Carruth /// Returns false if V does not map to a SROA-candidate.
3017adc3a2bSChandler Carruth bool CallAnalyzer::lookupSROAArgAndCost(
3027adc3a2bSChandler Carruth     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
3037adc3a2bSChandler Carruth   if (SROAArgValues.empty() || SROAArgCosts.empty())
3047adc3a2bSChandler Carruth     return false;
3057adc3a2bSChandler Carruth 
3067adc3a2bSChandler Carruth   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
3077adc3a2bSChandler Carruth   if (ArgIt == SROAArgValues.end())
3087adc3a2bSChandler Carruth     return false;
3097adc3a2bSChandler Carruth 
3107adc3a2bSChandler Carruth   Arg = ArgIt->second;
3117adc3a2bSChandler Carruth   CostIt = SROAArgCosts.find(Arg);
3127adc3a2bSChandler Carruth   return CostIt != SROAArgCosts.end();
3137adc3a2bSChandler Carruth }
3147adc3a2bSChandler Carruth 
3157adc3a2bSChandler Carruth /// \brief Disable SROA for the candidate marked by this cost iterator.
3167adc3a2bSChandler Carruth ///
3177adc3a2bSChandler Carruth /// This marks the candidate as no longer viable for SROA, and adds the cost
3187adc3a2bSChandler Carruth /// savings associated with it back into the inline cost measurement.
3197adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
3207adc3a2bSChandler Carruth   // If we're no longer able to perform SROA we need to undo its cost savings
3217adc3a2bSChandler Carruth   // and prevent subsequent analysis.
3227adc3a2bSChandler Carruth   Cost += CostIt->second;
3237adc3a2bSChandler Carruth   SROACostSavings -= CostIt->second;
3247adc3a2bSChandler Carruth   SROACostSavingsLost += CostIt->second;
3257adc3a2bSChandler Carruth   SROAArgCosts.erase(CostIt);
3267adc3a2bSChandler Carruth }
3277adc3a2bSChandler Carruth 
3287adc3a2bSChandler Carruth /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
3297adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
3307adc3a2bSChandler Carruth   Value *SROAArg;
3317adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
3327adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
3337adc3a2bSChandler Carruth     disableSROA(CostIt);
3347adc3a2bSChandler Carruth }
3357adc3a2bSChandler Carruth 
3367adc3a2bSChandler Carruth /// \brief Accumulate the given cost for a particular SROA candidate.
3377adc3a2bSChandler Carruth void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
3387adc3a2bSChandler Carruth                                       int InstructionCost) {
3397adc3a2bSChandler Carruth   CostIt->second += InstructionCost;
3407adc3a2bSChandler Carruth   SROACostSavings += InstructionCost;
3417adc3a2bSChandler Carruth }
3427adc3a2bSChandler Carruth 
3437adc3a2bSChandler Carruth /// \brief Accumulate a constant GEP offset into an APInt if possible.
3447adc3a2bSChandler Carruth ///
3457adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
3467adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
3477adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
3487adc3a2bSChandler Carruth   unsigned IntPtrWidth = DL.getPointerSizeInBits();
3497adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
3507adc3a2bSChandler Carruth 
3517adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
3527adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
3537adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
3547adc3a2bSChandler Carruth     if (!OpC)
3557adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
3567adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
3577adc3a2bSChandler Carruth     if (!OpC)
3587adc3a2bSChandler Carruth       return false;
359567556aaSChad Rosier     if (OpC->isZero())
360567556aaSChad Rosier       continue;
3617adc3a2bSChandler Carruth 
3627adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
363ab85225bSPeter Collingbourne     if (StructType *STy = GTI.getStructTypeOrNull()) {
3647adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
3657adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
3667adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
3677adc3a2bSChandler Carruth       continue;
3687adc3a2bSChandler Carruth     }
3697adc3a2bSChandler Carruth 
3707adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
3717adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
3727adc3a2bSChandler Carruth   }
3737adc3a2bSChandler Carruth   return true;
3747adc3a2bSChandler Carruth }
3757adc3a2bSChandler Carruth 
376201b191bSHaicheng Wu /// \brief Use TTI to check whether a GEP is free.
377201b191bSHaicheng Wu ///
378201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite.
379201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
38061c1bd5aSEvgeny Astigeevich   SmallVector<Value *, 4> Operands;
38161c1bd5aSEvgeny Astigeevich   Operands.push_back(GEP.getOperand(0));
382201b191bSHaicheng Wu   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
383201b191bSHaicheng Wu     if (Constant *SimpleOp = SimplifiedValues.lookup(*I))
38461c1bd5aSEvgeny Astigeevich        Operands.push_back(SimpleOp);
385201b191bSHaicheng Wu      else
38661c1bd5aSEvgeny Astigeevich        Operands.push_back(*I);
38761c1bd5aSEvgeny Astigeevich   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands);
388201b191bSHaicheng Wu }
389201b191bSHaicheng Wu 
3907adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
3917adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
3920f153424SSanjay Patel   // alloca and handle that case.
3937adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
3940f153424SSanjay Patel     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
3950f153424SSanjay Patel     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
3967adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
39722eb80a1SEaswaran Raman       AllocatedSize = SaturatingMultiplyAdd(
39822eb80a1SEaswaran Raman           AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty), AllocatedSize);
3997adc3a2bSChandler Carruth       return Base::visitAlloca(I);
4007adc3a2bSChandler Carruth     }
4017adc3a2bSChandler Carruth   }
4027adc3a2bSChandler Carruth 
4037adc3a2bSChandler Carruth   // Accumulate the allocated size.
4047adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
4057adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
40622eb80a1SEaswaran Raman     AllocatedSize = SaturatingAdd(DL.getTypeAllocSize(Ty), AllocatedSize);
4077adc3a2bSChandler Carruth   }
4087adc3a2bSChandler Carruth 
4097adc3a2bSChandler Carruth   // We will happily inline static alloca instructions.
4107adc3a2bSChandler Carruth   if (I.isStaticAlloca())
4117adc3a2bSChandler Carruth     return Base::visitAlloca(I);
4127adc3a2bSChandler Carruth 
4137adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
4147adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
4157adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
4167adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
4177adc3a2bSChandler Carruth   HasDynamicAlloca = true;
4187adc3a2bSChandler Carruth   return false;
4197adc3a2bSChandler Carruth }
4207adc3a2bSChandler Carruth 
4217adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
4227adc3a2bSChandler Carruth   // FIXME: We should potentially be tracking values through phi nodes,
4237adc3a2bSChandler Carruth   // especially when they collapse to a single value due to deleted CFG edges
4247adc3a2bSChandler Carruth   // during inlining.
4257adc3a2bSChandler Carruth 
4267adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
4277adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
4287adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
4297adc3a2bSChandler Carruth 
4307adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
4317adc3a2bSChandler Carruth   return true;
4327adc3a2bSChandler Carruth }
4337adc3a2bSChandler Carruth 
4347adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
4357adc3a2bSChandler Carruth   Value *SROAArg;
4367adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
437567556aaSChad Rosier   bool SROACandidate =
438567556aaSChad Rosier       lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt);
4397adc3a2bSChandler Carruth 
4407adc3a2bSChandler Carruth   // Try to fold GEPs of constant-offset call site argument pointers. This
4417adc3a2bSChandler Carruth   // requires target data and inbounds GEPs.
4427adc3a2bSChandler Carruth   if (I.isInBounds()) {
4437adc3a2bSChandler Carruth     // Check if we have a base + offset for the pointer.
4447adc3a2bSChandler Carruth     Value *Ptr = I.getPointerOperand();
4457adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
4467adc3a2bSChandler Carruth     if (BaseAndOffset.first) {
4477adc3a2bSChandler Carruth       // Check if the offset of this GEP is constant, and if so accumulate it
4487adc3a2bSChandler Carruth       // into Offset.
4497adc3a2bSChandler Carruth       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
4507adc3a2bSChandler Carruth         // Non-constant GEPs aren't folded, and disable SROA.
4517adc3a2bSChandler Carruth         if (SROACandidate)
4527adc3a2bSChandler Carruth           disableSROA(CostIt);
453201b191bSHaicheng Wu         return isGEPFree(I);
4547adc3a2bSChandler Carruth       }
4557adc3a2bSChandler Carruth 
4567adc3a2bSChandler Carruth       // Add the result as a new mapping to Base + Offset.
4577adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
4587adc3a2bSChandler Carruth 
4597adc3a2bSChandler Carruth       // Also handle SROA candidates here, we already know that the GEP is
4607adc3a2bSChandler Carruth       // all-constant indexed.
4617adc3a2bSChandler Carruth       if (SROACandidate)
4627adc3a2bSChandler Carruth         SROAArgValues[&I] = SROAArg;
4637adc3a2bSChandler Carruth 
4647adc3a2bSChandler Carruth       return true;
4657adc3a2bSChandler Carruth     }
4667adc3a2bSChandler Carruth   }
4677adc3a2bSChandler Carruth 
468a8b9cdc9SEaswaran Raman   // Lambda to check whether a GEP's indices are all constant.
469a8b9cdc9SEaswaran Raman   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
470a8b9cdc9SEaswaran Raman     for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
471a8b9cdc9SEaswaran Raman       if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
472a8b9cdc9SEaswaran Raman         return false;
473a8b9cdc9SEaswaran Raman     return true;
474a8b9cdc9SEaswaran Raman   };
475a8b9cdc9SEaswaran Raman 
476a8b9cdc9SEaswaran Raman   if (IsGEPOffsetConstant(I)) {
4777adc3a2bSChandler Carruth     if (SROACandidate)
4787adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
4797adc3a2bSChandler Carruth 
4807adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
4817adc3a2bSChandler Carruth     return true;
4827adc3a2bSChandler Carruth   }
4837adc3a2bSChandler Carruth 
4847adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
4857adc3a2bSChandler Carruth   if (SROACandidate)
4867adc3a2bSChandler Carruth     disableSROA(CostIt);
487201b191bSHaicheng Wu   return isGEPFree(I);
4887adc3a2bSChandler Carruth }
4897adc3a2bSChandler Carruth 
490617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues.
491617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the
492617f6364SEaswaran Raman /// instruction when all the operands are constants.
493617f6364SEaswaran Raman template <typename Callable>
494617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
495617f6364SEaswaran Raman   SmallVector<Constant *, 2> COps;
496617f6364SEaswaran Raman   for (Value *Op : I.operands()) {
497617f6364SEaswaran Raman     Constant *COp = dyn_cast<Constant>(Op);
4987adc3a2bSChandler Carruth     if (!COp)
499617f6364SEaswaran Raman       COp = SimplifiedValues.lookup(Op);
500617f6364SEaswaran Raman     if (!COp)
501617f6364SEaswaran Raman       return false;
502617f6364SEaswaran Raman     COps.push_back(COp);
503617f6364SEaswaran Raman   }
504617f6364SEaswaran Raman   auto *C = Evaluate(COps);
505617f6364SEaswaran Raman   if (!C)
506617f6364SEaswaran Raman     return false;
5077adc3a2bSChandler Carruth   SimplifiedValues[&I] = C;
5087adc3a2bSChandler Carruth   return true;
5097adc3a2bSChandler Carruth }
5107adc3a2bSChandler Carruth 
511617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) {
512617f6364SEaswaran Raman   // Propagate constants through bitcasts.
513617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
514617f6364SEaswaran Raman         return ConstantExpr::getBitCast(COps[0], I.getType());
515617f6364SEaswaran Raman       }))
516617f6364SEaswaran Raman     return true;
517617f6364SEaswaran Raman 
5187adc3a2bSChandler Carruth   // Track base/offsets through casts
519567556aaSChad Rosier   std::pair<Value *, APInt> BaseAndOffset =
520567556aaSChad Rosier       ConstantOffsetPtrs.lookup(I.getOperand(0));
5217adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
5227adc3a2bSChandler Carruth   if (BaseAndOffset.first)
5237adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
5247adc3a2bSChandler Carruth 
5257adc3a2bSChandler Carruth   // Also look for SROA candidates here.
5267adc3a2bSChandler Carruth   Value *SROAArg;
5277adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
5287adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
5297adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
5307adc3a2bSChandler Carruth 
5317adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
5327adc3a2bSChandler Carruth   return true;
5337adc3a2bSChandler Carruth }
5347adc3a2bSChandler Carruth 
5357adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
5367adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
537617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
538617f6364SEaswaran Raman         return ConstantExpr::getPtrToInt(COps[0], I.getType());
539617f6364SEaswaran Raman       }))
5407adc3a2bSChandler Carruth     return true;
5417adc3a2bSChandler Carruth 
5427adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
5437adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
5447adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
5457adc3a2bSChandler Carruth   if (IntegerSize >= DL.getPointerSizeInBits()) {
546567556aaSChad Rosier     std::pair<Value *, APInt> BaseAndOffset =
547567556aaSChad Rosier         ConstantOffsetPtrs.lookup(I.getOperand(0));
5487adc3a2bSChandler Carruth     if (BaseAndOffset.first)
5497adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
5507adc3a2bSChandler Carruth   }
5517adc3a2bSChandler Carruth 
5527adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
5537adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
5547adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
5557adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
5567adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
5577adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
5587adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
5597adc3a2bSChandler Carruth   Value *SROAArg;
5607adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
5617adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
5627adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
5637adc3a2bSChandler Carruth 
5647adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
5657adc3a2bSChandler Carruth }
5667adc3a2bSChandler Carruth 
5677adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
5687adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
569617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
570617f6364SEaswaran Raman         return ConstantExpr::getIntToPtr(COps[0], I.getType());
571617f6364SEaswaran Raman       }))
5727adc3a2bSChandler Carruth     return true;
5737adc3a2bSChandler Carruth 
5747adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
5757adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
5767adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
5777adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
5787adc3a2bSChandler Carruth   if (IntegerSize <= DL.getPointerSizeInBits()) {
5797adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
5807adc3a2bSChandler Carruth     if (BaseAndOffset.first)
5817adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
5827adc3a2bSChandler Carruth   }
5837adc3a2bSChandler Carruth 
5847adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
5857adc3a2bSChandler Carruth   Value *SROAArg;
5867adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
5877adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
5887adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
5897adc3a2bSChandler Carruth 
5907adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
5917adc3a2bSChandler Carruth }
5927adc3a2bSChandler Carruth 
5937adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
5947adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
595617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
596617f6364SEaswaran Raman         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
597617f6364SEaswaran Raman       }))
5987adc3a2bSChandler Carruth     return true;
5997adc3a2bSChandler Carruth 
6007adc3a2bSChandler Carruth   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
6017adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
6027adc3a2bSChandler Carruth 
6037adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
6047adc3a2bSChandler Carruth }
6057adc3a2bSChandler Carruth 
6067adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
6077adc3a2bSChandler Carruth   Value *Operand = I.getOperand(0);
608617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
609617f6364SEaswaran Raman         return ConstantFoldInstOperands(&I, COps[0], DL);
610617f6364SEaswaran Raman       }))
6117adc3a2bSChandler Carruth     return true;
6127adc3a2bSChandler Carruth 
6137adc3a2bSChandler Carruth   // Disable any SROA on the argument to arbitrary unary operators.
6147adc3a2bSChandler Carruth   disableSROA(Operand);
6157adc3a2bSChandler Carruth 
6167adc3a2bSChandler Carruth   return false;
6177adc3a2bSChandler Carruth }
6187adc3a2bSChandler Carruth 
6197adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
620fb502d2fSReid Kleckner   return CandidateCS.paramHasAttr(A->getArgNo(), Attr);
6217adc3a2bSChandler Carruth }
6227adc3a2bSChandler Carruth 
6237adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
6247adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
6257adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
6267adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
6277adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
6287adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
6297adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
6307adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
6317adc3a2bSChandler Carruth       return true;
6327adc3a2bSChandler Carruth 
6337adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
6347adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
6357adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
6367adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
6377adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
6387adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
6397adc3a2bSChandler Carruth     // SROA firing.
6407adc3a2bSChandler Carruth     return true;
6417adc3a2bSChandler Carruth 
6427adc3a2bSChandler Carruth   return false;
6437adc3a2bSChandler Carruth }
6447adc3a2bSChandler Carruth 
6459a3fc17aSEaswaran Raman bool CallAnalyzer::allowSizeGrowth(CallSite CS) {
6469a3fc17aSEaswaran Raman   // If the normal destination of the invoke or the parent block of the call
6479a3fc17aSEaswaran Raman   // site is unreachable-terminated, there is little point in inlining this
6489a3fc17aSEaswaran Raman   // unless there is literally zero cost.
6499a3fc17aSEaswaran Raman   // FIXME: Note that it is possible that an unreachable-terminated block has a
6509a3fc17aSEaswaran Raman   // hot entry. For example, in below scenario inlining hot_call_X() may be
6519a3fc17aSEaswaran Raman   // beneficial :
6529a3fc17aSEaswaran Raman   // main() {
6539a3fc17aSEaswaran Raman   //   hot_call_1();
6549a3fc17aSEaswaran Raman   //   ...
6559a3fc17aSEaswaran Raman   //   hot_call_N()
6569a3fc17aSEaswaran Raman   //   exit(0);
6579a3fc17aSEaswaran Raman   // }
6589a3fc17aSEaswaran Raman   // For now, we are not handling this corner case here as it is rare in real
6599a3fc17aSEaswaran Raman   // code. In future, we should elaborate this based on BPI and BFI in more
6609a3fc17aSEaswaran Raman   // general threshold adjusting heuristics in updateThreshold().
6619a3fc17aSEaswaran Raman   Instruction *Instr = CS.getInstruction();
6629a3fc17aSEaswaran Raman   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
6639a3fc17aSEaswaran Raman     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
6649a3fc17aSEaswaran Raman       return false;
6659a3fc17aSEaswaran Raman   } else if (isa<UnreachableInst>(Instr->getParent()->getTerminator()))
6669a3fc17aSEaswaran Raman     return false;
6679a3fc17aSEaswaran Raman 
6689a3fc17aSEaswaran Raman   return true;
6699a3fc17aSEaswaran Raman }
6709a3fc17aSEaswaran Raman 
671c5fa6358SEaswaran Raman bool CallAnalyzer::isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI) {
672c5fa6358SEaswaran Raman   // If global profile summary is available, then callsite's coldness is
673c5fa6358SEaswaran Raman   // determined based on that.
674bba762a1SChandler Carruth   if (PSI && PSI->hasProfileSummary())
675c5fa6358SEaswaran Raman     return PSI->isColdCallSite(CS, CallerBFI);
676bba762a1SChandler Carruth 
677bba762a1SChandler Carruth   // Otherwise we need BFI to be available.
678c5fa6358SEaswaran Raman   if (!CallerBFI)
679c5fa6358SEaswaran Raman     return false;
680c5fa6358SEaswaran Raman 
681bba762a1SChandler Carruth   // Determine if the callsite is cold relative to caller's entry. We could
682bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
683bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
684bba762a1SChandler Carruth   // profiles.
685c5fa6358SEaswaran Raman   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
686c5fa6358SEaswaran Raman   auto CallSiteBB = CS.getInstruction()->getParent();
687c5fa6358SEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
688c5fa6358SEaswaran Raman   auto CallerEntryFreq =
689c5fa6358SEaswaran Raman       CallerBFI->getBlockFreq(&(CS.getCaller()->getEntryBlock()));
690c5fa6358SEaswaran Raman   return CallSiteFreq < CallerEntryFreq * ColdProb;
691c5fa6358SEaswaran Raman }
692c5fa6358SEaswaran Raman 
693974d4eeaSEaswaran Raman Optional<int>
694974d4eeaSEaswaran Raman CallAnalyzer::getHotCallSiteThreshold(CallSite CS,
695974d4eeaSEaswaran Raman                                       BlockFrequencyInfo *CallerBFI) {
696bba762a1SChandler Carruth 
697974d4eeaSEaswaran Raman   // If global profile summary is available, then callsite's hotness is
698974d4eeaSEaswaran Raman   // determined based on that.
699bba762a1SChandler Carruth   if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(CS, CallerBFI))
700bba762a1SChandler Carruth     return Params.HotCallSiteThreshold;
701974d4eeaSEaswaran Raman 
702bba762a1SChandler Carruth   // Otherwise we need BFI to be available and to have a locally hot callsite
703bba762a1SChandler Carruth   // threshold.
704bba762a1SChandler Carruth   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
705974d4eeaSEaswaran Raman     return None;
706974d4eeaSEaswaran Raman 
707bba762a1SChandler Carruth   // Determine if the callsite is hot relative to caller's entry. We could
708bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
709bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
710bba762a1SChandler Carruth   // profiles.
711974d4eeaSEaswaran Raman   auto CallSiteBB = CS.getInstruction()->getParent();
712974d4eeaSEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
713974d4eeaSEaswaran Raman   auto CallerEntryFreq = CallerBFI->getEntryFreq();
714974d4eeaSEaswaran Raman   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
715bba762a1SChandler Carruth     return Params.LocallyHotCallSiteThreshold;
716bba762a1SChandler Carruth 
717bba762a1SChandler Carruth   // Otherwise treat it normally.
718974d4eeaSEaswaran Raman   return None;
719974d4eeaSEaswaran Raman }
720974d4eeaSEaswaran Raman 
721f4bb2f0dSEaswaran Raman void CallAnalyzer::updateThreshold(CallSite CS, Function &Callee) {
7229a3fc17aSEaswaran Raman   // If no size growth is allowed for this inlining, set Threshold to 0.
7239a3fc17aSEaswaran Raman   if (!allowSizeGrowth(CS)) {
7249a3fc17aSEaswaran Raman     Threshold = 0;
7259a3fc17aSEaswaran Raman     return;
7269a3fc17aSEaswaran Raman   }
7279a3fc17aSEaswaran Raman 
728bb578ef0SEaswaran Raman   Function *Caller = CS.getCaller();
7291c57cc2bSEaswaran Raman 
7301c57cc2bSEaswaran Raman   // return min(A, B) if B is valid.
7311c57cc2bSEaswaran Raman   auto MinIfValid = [](int A, Optional<int> B) {
7321c57cc2bSEaswaran Raman     return B ? std::min(A, B.getValue()) : A;
7331c57cc2bSEaswaran Raman   };
7341c57cc2bSEaswaran Raman 
7350d58fcacSEaswaran Raman   // return max(A, B) if B is valid.
7360d58fcacSEaswaran Raman   auto MaxIfValid = [](int A, Optional<int> B) {
7370d58fcacSEaswaran Raman     return B ? std::max(A, B.getValue()) : A;
7380d58fcacSEaswaran Raman   };
7390d58fcacSEaswaran Raman 
74051b809bfSEaswaran Raman   // Various bonus percentages. These are multiplied by Threshold to get the
74151b809bfSEaswaran Raman   // bonus values.
74251b809bfSEaswaran Raman   // SingleBBBonus: This bonus is applied if the callee has a single reachable
74351b809bfSEaswaran Raman   // basic block at the given callsite context. This is speculatively applied
74451b809bfSEaswaran Raman   // and withdrawn if more than one basic block is seen.
74551b809bfSEaswaran Raman   //
74651b809bfSEaswaran Raman   // Vector bonuses: We want to more aggressively inline vector-dense kernels
74751b809bfSEaswaran Raman   // and apply this bonus based on the percentage of vector instructions. A
74851b809bfSEaswaran Raman   // bonus is applied if the vector instructions exceed 50% and half that amount
74951b809bfSEaswaran Raman   // is applied if it exceeds 10%. Note that these bonuses are some what
75051b809bfSEaswaran Raman   // arbitrary and evolved over time by accident as much as because they are
75151b809bfSEaswaran Raman   // principled bonuses.
75251b809bfSEaswaran Raman   // FIXME: It would be nice to base the bonus values on something more
75351b809bfSEaswaran Raman   // scientific.
75451b809bfSEaswaran Raman   //
75551b809bfSEaswaran Raman   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
75651b809bfSEaswaran Raman   // of the last call to a static function as inlining such functions is
75751b809bfSEaswaran Raman   // guaranteed to reduce code size.
75851b809bfSEaswaran Raman   //
75951b809bfSEaswaran Raman   // These bonus percentages may be set to 0 based on properties of the caller
76051b809bfSEaswaran Raman   // and the callsite.
76151b809bfSEaswaran Raman   int SingleBBBonusPercent = 50;
76251b809bfSEaswaran Raman   int VectorBonusPercent = 150;
76351b809bfSEaswaran Raman   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
76451b809bfSEaswaran Raman 
76551b809bfSEaswaran Raman   // Lambda to set all the above bonus and bonus percentages to 0.
76651b809bfSEaswaran Raman   auto DisallowAllBonuses = [&]() {
76751b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
76851b809bfSEaswaran Raman     VectorBonusPercent = 0;
76951b809bfSEaswaran Raman     LastCallToStaticBonus = 0;
77051b809bfSEaswaran Raman   };
77151b809bfSEaswaran Raman 
7721c57cc2bSEaswaran Raman   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
7731c57cc2bSEaswaran Raman   // and reduce the threshold if the caller has the necessary attribute.
77451b809bfSEaswaran Raman   if (Caller->optForMinSize()) {
7751c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
77651b809bfSEaswaran Raman     // For minsize, we want to disable the single BB bonus and the vector
77751b809bfSEaswaran Raman     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
77851b809bfSEaswaran Raman     // a static function will, at the minimum, eliminate the parameter setup and
77951b809bfSEaswaran Raman     // call/return instructions.
78051b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
78151b809bfSEaswaran Raman     VectorBonusPercent = 0;
78251b809bfSEaswaran Raman   } else if (Caller->optForSize())
7831c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
784f4bb2f0dSEaswaran Raman 
785e08b139dSEaswaran Raman   // Adjust the threshold based on inlinehint attribute and profile based
786e08b139dSEaswaran Raman   // hotness information if the caller does not have MinSize attribute.
787e08b139dSEaswaran Raman   if (!Caller->optForMinSize()) {
788e08b139dSEaswaran Raman     if (Callee.hasFnAttribute(Attribute::InlineHint))
7890d58fcacSEaswaran Raman       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
790bba762a1SChandler Carruth 
7913cd1479cSEaswaran Raman     // FIXME: After switching to the new passmanager, simplify the logic below
792bba762a1SChandler Carruth     // by checking only the callsite hotness/coldness as we will reliably
793bba762a1SChandler Carruth     // have local profile information.
7943cd1479cSEaswaran Raman     //
795bba762a1SChandler Carruth     // Callsite hotness and coldness can be determined if sample profile is
796bba762a1SChandler Carruth     // used (which adds hotness metadata to calls) or if caller's
797bba762a1SChandler Carruth     // BlockFrequencyInfo is available.
798bba762a1SChandler Carruth     BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr;
799974d4eeaSEaswaran Raman     auto HotCallSiteThreshold = getHotCallSiteThreshold(CS, CallerBFI);
800974d4eeaSEaswaran Raman     if (!Caller->optForSize() && HotCallSiteThreshold) {
80112585b01SEaswaran Raman       DEBUG(dbgs() << "Hot callsite.\n");
802974d4eeaSEaswaran Raman       // FIXME: This should update the threshold only if it exceeds the
803974d4eeaSEaswaran Raman       // current threshold, but AutoFDO + ThinLTO currently relies on this
804974d4eeaSEaswaran Raman       // behavior to prevent inlining of hot callsites during ThinLTO
805974d4eeaSEaswaran Raman       // compile phase.
806974d4eeaSEaswaran Raman       Threshold = HotCallSiteThreshold.getValue();
807c5fa6358SEaswaran Raman     } else if (isColdCallSite(CS, CallerBFI)) {
8083cd1479cSEaswaran Raman       DEBUG(dbgs() << "Cold callsite.\n");
80951b809bfSEaswaran Raman       // Do not apply bonuses for a cold callsite including the
81051b809bfSEaswaran Raman       // LastCallToStatic bonus. While this bonus might result in code size
81151b809bfSEaswaran Raman       // reduction, it can cause the size of a non-cold caller to increase
81251b809bfSEaswaran Raman       // preventing it from being inlined.
81351b809bfSEaswaran Raman       DisallowAllBonuses();
8143cd1479cSEaswaran Raman       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
815bba762a1SChandler Carruth     } else if (PSI) {
816bba762a1SChandler Carruth       // Use callee's global profile information only if we have no way of
817bba762a1SChandler Carruth       // determining this via callsite information.
8183cd1479cSEaswaran Raman       if (PSI->isFunctionEntryHot(&Callee)) {
81912585b01SEaswaran Raman         DEBUG(dbgs() << "Hot callee.\n");
820e08b139dSEaswaran Raman         // If callsite hotness can not be determined, we may still know
821e08b139dSEaswaran Raman         // that the callee is hot and treat it as a weaker hint for threshold
822e08b139dSEaswaran Raman         // increase.
823e08b139dSEaswaran Raman         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
824e08b139dSEaswaran Raman       } else if (PSI->isFunctionEntryCold(&Callee)) {
82512585b01SEaswaran Raman         DEBUG(dbgs() << "Cold callee.\n");
82651b809bfSEaswaran Raman         // Do not apply bonuses for a cold callee including the
82751b809bfSEaswaran Raman         // LastCallToStatic bonus. While this bonus might result in code size
82851b809bfSEaswaran Raman         // reduction, it can cause the size of a non-cold caller to increase
82951b809bfSEaswaran Raman         // preventing it from being inlined.
83051b809bfSEaswaran Raman         DisallowAllBonuses();
8311c57cc2bSEaswaran Raman         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
832e08b139dSEaswaran Raman       }
833e08b139dSEaswaran Raman     }
834e08b139dSEaswaran Raman   }
8358650a4daSJustin Lebar 
8368650a4daSJustin Lebar   // Finally, take the target-specific inlining threshold multiplier into
8378650a4daSJustin Lebar   // account.
8388650a4daSJustin Lebar   Threshold *= TTI.getInliningThresholdMultiplier();
83951b809bfSEaswaran Raman 
84051b809bfSEaswaran Raman   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
84151b809bfSEaswaran Raman   VectorBonus = Threshold * VectorBonusPercent / 100;
84251b809bfSEaswaran Raman 
84351b809bfSEaswaran Raman   bool OnlyOneCallAndLocalLinkage =
84451b809bfSEaswaran Raman       F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction();
84551b809bfSEaswaran Raman   // If there is only one call of the function, and it has internal linkage,
84651b809bfSEaswaran Raman   // the cost of inlining it drops dramatically. It may seem odd to update
84751b809bfSEaswaran Raman   // Cost in updateThreshold, but the bonus depends on the logic in this method.
84851b809bfSEaswaran Raman   if (OnlyOneCallAndLocalLinkage)
84951b809bfSEaswaran Raman     Cost -= LastCallToStaticBonus;
850f4bb2f0dSEaswaran Raman }
851f4bb2f0dSEaswaran Raman 
8527adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
8537adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
8547adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
855617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
856617f6364SEaswaran Raman         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
857617f6364SEaswaran Raman       }))
8587adc3a2bSChandler Carruth     return true;
8597adc3a2bSChandler Carruth 
8607adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
8617adc3a2bSChandler Carruth     return false;
8627adc3a2bSChandler Carruth 
8637adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
8647adc3a2bSChandler Carruth   // a common base.
8657adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
8667adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
8677adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
8687adc3a2bSChandler Carruth   if (LHSBase) {
8697adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
8707adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
8717adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
8727adc3a2bSChandler Carruth       // offsets.
8737adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
8747adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
8757adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
8767adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
8777adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
8787adc3a2bSChandler Carruth         return true;
8797adc3a2bSChandler Carruth       }
8807adc3a2bSChandler Carruth     }
8817adc3a2bSChandler Carruth   }
8827adc3a2bSChandler Carruth 
8837adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
8847adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
8857adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
8867adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
8877adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
8887adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
8897adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
8907adc3a2bSChandler Carruth     return true;
8917adc3a2bSChandler Carruth   }
8927adc3a2bSChandler Carruth   // Finally check for SROA candidates in comparisons.
8937adc3a2bSChandler Carruth   Value *SROAArg;
8947adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
8957adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
8967adc3a2bSChandler Carruth     if (isa<ConstantPointerNull>(I.getOperand(1))) {
8977adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
8987adc3a2bSChandler Carruth       return true;
8997adc3a2bSChandler Carruth     }
9007adc3a2bSChandler Carruth 
9017adc3a2bSChandler Carruth     disableSROA(CostIt);
9027adc3a2bSChandler Carruth   }
9037adc3a2bSChandler Carruth 
9047adc3a2bSChandler Carruth   return false;
9057adc3a2bSChandler Carruth }
9067adc3a2bSChandler Carruth 
9072e1c050eSChad Rosier bool CallAnalyzer::visitOr(BinaryOperator &I) {
9082e1c050eSChad Rosier   // This is necessary because the generic simplify instruction only works if
9092e1c050eSChad Rosier   // both operands are constants.
9102e1c050eSChad Rosier   for (unsigned i = 0; i < 2; ++i) {
9112e1c050eSChad Rosier     if (ConstantInt *C = dyn_cast_or_null<ConstantInt>(
9122e1c050eSChad Rosier             SimplifiedValues.lookup(I.getOperand(i))))
9132e1c050eSChad Rosier       if (C->isAllOnesValue()) {
9142e1c050eSChad Rosier         SimplifiedValues[&I] = C;
9152e1c050eSChad Rosier         return true;
9162e1c050eSChad Rosier       }
9172e1c050eSChad Rosier   }
9182e1c050eSChad Rosier   return Base::visitOr(I);
9192e1c050eSChad Rosier }
9202e1c050eSChad Rosier 
9212e1c050eSChad Rosier bool CallAnalyzer::visitAnd(BinaryOperator &I) {
9222e1c050eSChad Rosier   // This is necessary because the generic simplify instruction only works if
9232e1c050eSChad Rosier   // both operands are constants.
9242e1c050eSChad Rosier   for (unsigned i = 0; i < 2; ++i) {
9252e1c050eSChad Rosier     if (ConstantInt *C = dyn_cast_or_null<ConstantInt>(
9262e1c050eSChad Rosier             SimplifiedValues.lookup(I.getOperand(i))))
9272e1c050eSChad Rosier       if (C->isZero()) {
9282e1c050eSChad Rosier         SimplifiedValues[&I] = C;
9292e1c050eSChad Rosier         return true;
9302e1c050eSChad Rosier       }
9312e1c050eSChad Rosier   }
9322e1c050eSChad Rosier   return Base::visitAnd(I);
9332e1c050eSChad Rosier }
9342e1c050eSChad Rosier 
9357adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
9367adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
9377adc3a2bSChandler Carruth   // constant-related pointers.
9387adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
9397adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
9407adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
9417adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
9427adc3a2bSChandler Carruth   if (LHSBase) {
9437adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
9447adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
9457adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
9467adc3a2bSChandler Carruth       // offsets.
9477adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
9487adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
9497adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
9507adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
9517adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
9527adc3a2bSChandler Carruth         return true;
9537adc3a2bSChandler Carruth       }
9547adc3a2bSChandler Carruth     }
9557adc3a2bSChandler Carruth   }
9567adc3a2bSChandler Carruth 
9577adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
9587adc3a2bSChandler Carruth   // instructions.
9597adc3a2bSChandler Carruth   return Base::visitSub(I);
9607adc3a2bSChandler Carruth }
9617adc3a2bSChandler Carruth 
9627adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
9637adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
964617f6364SEaswaran Raman   auto Evaluate = [&](SmallVectorImpl<Constant *> &COps) {
9657adc3a2bSChandler Carruth     Value *SimpleV = nullptr;
9667adc3a2bSChandler Carruth     if (auto FI = dyn_cast<FPMathOperator>(&I))
967617f6364SEaswaran Raman       SimpleV = SimplifyFPBinOp(I.getOpcode(), COps[0], COps[1],
968617f6364SEaswaran Raman                                 FI->getFastMathFlags(), DL);
9697adc3a2bSChandler Carruth     else
970617f6364SEaswaran Raman       SimpleV = SimplifyBinOp(I.getOpcode(), COps[0], COps[1], DL);
971617f6364SEaswaran Raman     return dyn_cast_or_null<Constant>(SimpleV);
972617f6364SEaswaran Raman   };
9737adc3a2bSChandler Carruth 
974617f6364SEaswaran Raman   if (simplifyInstruction(I, Evaluate))
9757adc3a2bSChandler Carruth     return true;
9767adc3a2bSChandler Carruth 
9777adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
9787adc3a2bSChandler Carruth   disableSROA(LHS);
9797adc3a2bSChandler Carruth   disableSROA(RHS);
9807adc3a2bSChandler Carruth 
9817adc3a2bSChandler Carruth   return false;
9827adc3a2bSChandler Carruth }
9837adc3a2bSChandler Carruth 
9847adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
9857adc3a2bSChandler Carruth   Value *SROAArg;
9867adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
9877adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
9887adc3a2bSChandler Carruth     if (I.isSimple()) {
9897adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
9907adc3a2bSChandler Carruth       return true;
9917adc3a2bSChandler Carruth     }
9927adc3a2bSChandler Carruth 
9937adc3a2bSChandler Carruth     disableSROA(CostIt);
9947adc3a2bSChandler Carruth   }
9957adc3a2bSChandler Carruth 
9967adc3a2bSChandler Carruth   return false;
9977adc3a2bSChandler Carruth }
9987adc3a2bSChandler Carruth 
9997adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
10007adc3a2bSChandler Carruth   Value *SROAArg;
10017adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
10027adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
10037adc3a2bSChandler Carruth     if (I.isSimple()) {
10047adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
10057adc3a2bSChandler Carruth       return true;
10067adc3a2bSChandler Carruth     }
10077adc3a2bSChandler Carruth 
10087adc3a2bSChandler Carruth     disableSROA(CostIt);
10097adc3a2bSChandler Carruth   }
10107adc3a2bSChandler Carruth 
10117adc3a2bSChandler Carruth   return false;
10127adc3a2bSChandler Carruth }
10137adc3a2bSChandler Carruth 
10147adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
10157adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
1016617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1017617f6364SEaswaran Raman         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
1018617f6364SEaswaran Raman       }))
10197adc3a2bSChandler Carruth     return true;
10207adc3a2bSChandler Carruth 
10217adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
10227adc3a2bSChandler Carruth   return false;
10237adc3a2bSChandler Carruth }
10247adc3a2bSChandler Carruth 
10257adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
10267adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
1027617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1028617f6364SEaswaran Raman         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
1029617f6364SEaswaran Raman                                             /*InsertedValueOperand*/ COps[1],
1030617f6364SEaswaran Raman                                             I.getIndices());
1031617f6364SEaswaran Raman       }))
10327adc3a2bSChandler Carruth     return true;
10337adc3a2bSChandler Carruth 
10347adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
10357adc3a2bSChandler Carruth   return false;
10367adc3a2bSChandler Carruth }
10377adc3a2bSChandler Carruth 
10387adc3a2bSChandler Carruth /// \brief Try to simplify a call site.
10397adc3a2bSChandler Carruth ///
10407adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
10417adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
10427adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
10437adc3a2bSChandler Carruth /// free.
10447adc3a2bSChandler Carruth bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
10457adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
10467adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
10477adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
10487adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
1049647025f9SAndrew Kaylor   if (!canConstantFoldCallTo(CS, F))
10507adc3a2bSChandler Carruth     return false;
10517adc3a2bSChandler Carruth 
10527adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
10537adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
10547adc3a2bSChandler Carruth   ConstantArgs.reserve(CS.arg_size());
1055567556aaSChad Rosier   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E;
1056567556aaSChad Rosier        ++I) {
10577adc3a2bSChandler Carruth     Constant *C = dyn_cast<Constant>(*I);
10587adc3a2bSChandler Carruth     if (!C)
10597adc3a2bSChandler Carruth       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
10607adc3a2bSChandler Carruth     if (!C)
10617adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
10627adc3a2bSChandler Carruth 
10637adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
10647adc3a2bSChandler Carruth   }
1065647025f9SAndrew Kaylor   if (Constant *C = ConstantFoldCall(CS, F, ConstantArgs)) {
10667adc3a2bSChandler Carruth     SimplifiedValues[CS.getInstruction()] = C;
10677adc3a2bSChandler Carruth     return true;
10687adc3a2bSChandler Carruth   }
10697adc3a2bSChandler Carruth 
10707adc3a2bSChandler Carruth   return false;
10717adc3a2bSChandler Carruth }
10727adc3a2bSChandler Carruth 
10737adc3a2bSChandler Carruth bool CallAnalyzer::visitCallSite(CallSite CS) {
10747adc3a2bSChandler Carruth   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
10757adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
10767adc3a2bSChandler Carruth     // This aborts the entire analysis.
10777adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
10787adc3a2bSChandler Carruth     return false;
10797adc3a2bSChandler Carruth   }
1080567556aaSChad Rosier   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->cannotDuplicate())
10817adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
10827adc3a2bSChandler Carruth 
10837adc3a2bSChandler Carruth   if (Function *F = CS.getCalledFunction()) {
10847adc3a2bSChandler Carruth     // When we have a concrete function, first try to simplify it directly.
10857adc3a2bSChandler Carruth     if (simplifyCallSite(F, CS))
10867adc3a2bSChandler Carruth       return true;
10877adc3a2bSChandler Carruth 
10887adc3a2bSChandler Carruth     // Next check if it is an intrinsic we know about.
10897adc3a2bSChandler Carruth     // FIXME: Lift this into part of the InstVisitor.
10907adc3a2bSChandler Carruth     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
10917adc3a2bSChandler Carruth       switch (II->getIntrinsicID()) {
10927adc3a2bSChandler Carruth       default:
10937adc3a2bSChandler Carruth         return Base::visitCallSite(CS);
10947adc3a2bSChandler Carruth 
10957dd8dbf4SPeter Collingbourne       case Intrinsic::load_relative:
10967dd8dbf4SPeter Collingbourne         // This is normally lowered to 4 LLVM instructions.
10977dd8dbf4SPeter Collingbourne         Cost += 3 * InlineConstants::InstrCost;
10987dd8dbf4SPeter Collingbourne         return false;
10997dd8dbf4SPeter Collingbourne 
11007adc3a2bSChandler Carruth       case Intrinsic::memset:
11017adc3a2bSChandler Carruth       case Intrinsic::memcpy:
11027adc3a2bSChandler Carruth       case Intrinsic::memmove:
11037adc3a2bSChandler Carruth         // SROA can usually chew through these intrinsics, but they aren't free.
11047adc3a2bSChandler Carruth         return false;
11057adc3a2bSChandler Carruth       case Intrinsic::localescape:
11067adc3a2bSChandler Carruth         HasFrameEscape = true;
11077adc3a2bSChandler Carruth         return false;
11087adc3a2bSChandler Carruth       }
11097adc3a2bSChandler Carruth     }
11107adc3a2bSChandler Carruth 
11117adc3a2bSChandler Carruth     if (F == CS.getInstruction()->getParent()->getParent()) {
11127adc3a2bSChandler Carruth       // This flag will fully abort the analysis, so don't bother with anything
11137adc3a2bSChandler Carruth       // else.
11147adc3a2bSChandler Carruth       IsRecursiveCall = true;
11157adc3a2bSChandler Carruth       return false;
11167adc3a2bSChandler Carruth     }
11177adc3a2bSChandler Carruth 
11187adc3a2bSChandler Carruth     if (TTI.isLoweredToCall(F)) {
11197adc3a2bSChandler Carruth       // We account for the average 1 instruction per call argument setup
11207adc3a2bSChandler Carruth       // here.
11217adc3a2bSChandler Carruth       Cost += CS.arg_size() * InlineConstants::InstrCost;
11227adc3a2bSChandler Carruth 
11237adc3a2bSChandler Carruth       // Everything other than inline ASM will also have a significant cost
11247adc3a2bSChandler Carruth       // merely from making the call.
11257adc3a2bSChandler Carruth       if (!isa<InlineAsm>(CS.getCalledValue()))
11267adc3a2bSChandler Carruth         Cost += InlineConstants::CallPenalty;
11277adc3a2bSChandler Carruth     }
11287adc3a2bSChandler Carruth 
11297adc3a2bSChandler Carruth     return Base::visitCallSite(CS);
11307adc3a2bSChandler Carruth   }
11317adc3a2bSChandler Carruth 
11327adc3a2bSChandler Carruth   // Otherwise we're in a very special case -- an indirect function call. See
11337adc3a2bSChandler Carruth   // if we can be particularly clever about this.
11347adc3a2bSChandler Carruth   Value *Callee = CS.getCalledValue();
11357adc3a2bSChandler Carruth 
11367adc3a2bSChandler Carruth   // First, pay the price of the argument setup. We account for the average
11377adc3a2bSChandler Carruth   // 1 instruction per call argument setup here.
11387adc3a2bSChandler Carruth   Cost += CS.arg_size() * InlineConstants::InstrCost;
11397adc3a2bSChandler Carruth 
11407adc3a2bSChandler Carruth   // Next, check if this happens to be an indirect function call to a known
11417adc3a2bSChandler Carruth   // function in this inline context. If not, we've done all we can.
11427adc3a2bSChandler Carruth   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
11437adc3a2bSChandler Carruth   if (!F)
11447adc3a2bSChandler Carruth     return Base::visitCallSite(CS);
11457adc3a2bSChandler Carruth 
11467adc3a2bSChandler Carruth   // If we have a constant that we are calling as a function, we can peer
11477adc3a2bSChandler Carruth   // through it and see the function target. This happens not infrequently
11487adc3a2bSChandler Carruth   // during devirtualization and so we want to give it a hefty bonus for
11497adc3a2bSChandler Carruth   // inlining, but cap that bonus in the event that inlining wouldn't pan
11507adc3a2bSChandler Carruth   // out. Pretend to inline the function, with a custom threshold.
11511c57cc2bSEaswaran Raman   auto IndirectCallParams = Params;
11521c57cc2bSEaswaran Raman   IndirectCallParams.DefaultThreshold = InlineConstants::IndirectCallThreshold;
11530812c5beSHaicheng Wu   CallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F, CS,
115412585b01SEaswaran Raman                   IndirectCallParams);
11557adc3a2bSChandler Carruth   if (CA.analyzeCall(CS)) {
11567adc3a2bSChandler Carruth     // We were able to inline the indirect call! Subtract the cost from the
11576d90d9f1SEaswaran Raman     // threshold to get the bonus we want to apply, but don't go below zero.
11586d90d9f1SEaswaran Raman     Cost -= std::max(0, CA.getThreshold() - CA.getCost());
11597adc3a2bSChandler Carruth   }
11607adc3a2bSChandler Carruth 
11617adc3a2bSChandler Carruth   return Base::visitCallSite(CS);
11627adc3a2bSChandler Carruth }
11637adc3a2bSChandler Carruth 
11647adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
11657adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
11667adc3a2bSChandler Carruth   bool Free = !HasReturn;
11677adc3a2bSChandler Carruth   HasReturn = true;
11687adc3a2bSChandler Carruth   return Free;
11697adc3a2bSChandler Carruth }
11707adc3a2bSChandler Carruth 
11717adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
11727adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
11737adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
11747adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
11757adc3a2bSChandler Carruth   // which will fold away are also free.
11767adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
11777adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
11787adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
11797adc3a2bSChandler Carruth }
11807adc3a2bSChandler Carruth 
1181*3ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
1182*3ec848bcSHaicheng Wu   bool CheckSROA = SI.getType()->isPointerTy();
1183*3ec848bcSHaicheng Wu   Value *TrueVal = SI.getTrueValue();
1184*3ec848bcSHaicheng Wu   Value *FalseVal = SI.getFalseValue();
1185*3ec848bcSHaicheng Wu 
1186*3ec848bcSHaicheng Wu   Constant *TrueC = dyn_cast<Constant>(TrueVal);
1187*3ec848bcSHaicheng Wu   if (!TrueC)
1188*3ec848bcSHaicheng Wu     TrueC = SimplifiedValues.lookup(TrueVal);
1189*3ec848bcSHaicheng Wu   Constant *FalseC = dyn_cast<Constant>(FalseVal);
1190*3ec848bcSHaicheng Wu   if (!FalseC)
1191*3ec848bcSHaicheng Wu     FalseC = SimplifiedValues.lookup(FalseVal);
1192*3ec848bcSHaicheng Wu   Constant *CondC =
1193*3ec848bcSHaicheng Wu       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
1194*3ec848bcSHaicheng Wu 
1195*3ec848bcSHaicheng Wu   if (!CondC) {
1196*3ec848bcSHaicheng Wu     // Select C, X, X => X
1197*3ec848bcSHaicheng Wu     if (TrueC == FalseC && TrueC) {
1198*3ec848bcSHaicheng Wu       SimplifiedValues[&SI] = TrueC;
1199*3ec848bcSHaicheng Wu       return true;
1200*3ec848bcSHaicheng Wu     }
1201*3ec848bcSHaicheng Wu 
1202*3ec848bcSHaicheng Wu     if (!CheckSROA)
1203*3ec848bcSHaicheng Wu       return Base::visitSelectInst(SI);
1204*3ec848bcSHaicheng Wu 
1205*3ec848bcSHaicheng Wu     std::pair<Value *, APInt> TrueBaseAndOffset =
1206*3ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(TrueVal);
1207*3ec848bcSHaicheng Wu     std::pair<Value *, APInt> FalseBaseAndOffset =
1208*3ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(FalseVal);
1209*3ec848bcSHaicheng Wu     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
1210*3ec848bcSHaicheng Wu       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
1211*3ec848bcSHaicheng Wu 
1212*3ec848bcSHaicheng Wu       Value *SROAArg;
1213*3ec848bcSHaicheng Wu       DenseMap<Value *, int>::iterator CostIt;
1214*3ec848bcSHaicheng Wu       if (lookupSROAArgAndCost(TrueVal, SROAArg, CostIt))
1215*3ec848bcSHaicheng Wu         SROAArgValues[&SI] = SROAArg;
1216*3ec848bcSHaicheng Wu       return true;
1217*3ec848bcSHaicheng Wu     }
1218*3ec848bcSHaicheng Wu 
1219*3ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
1220*3ec848bcSHaicheng Wu   }
1221*3ec848bcSHaicheng Wu 
1222*3ec848bcSHaicheng Wu   // Select condition is a constant.
1223*3ec848bcSHaicheng Wu   Value *SelectedV = CondC->isAllOnesValue()
1224*3ec848bcSHaicheng Wu                          ? TrueVal
1225*3ec848bcSHaicheng Wu                          : (CondC->isNullValue()) ? FalseVal : nullptr;
1226*3ec848bcSHaicheng Wu   if (!SelectedV) {
1227*3ec848bcSHaicheng Wu     // Condition is a vector constant that is not all 1s or all 0s.  If all
1228*3ec848bcSHaicheng Wu     // operands are constants, ConstantExpr::getSelect() can handle the cases
1229*3ec848bcSHaicheng Wu     // such as select vectors.
1230*3ec848bcSHaicheng Wu     if (TrueC && FalseC) {
1231*3ec848bcSHaicheng Wu       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
1232*3ec848bcSHaicheng Wu         SimplifiedValues[&SI] = C;
1233*3ec848bcSHaicheng Wu         return true;
1234*3ec848bcSHaicheng Wu       }
1235*3ec848bcSHaicheng Wu     }
1236*3ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
1237*3ec848bcSHaicheng Wu   }
1238*3ec848bcSHaicheng Wu 
1239*3ec848bcSHaicheng Wu   // Condition is either all 1s or all 0s. SI can be simplified.
1240*3ec848bcSHaicheng Wu   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
1241*3ec848bcSHaicheng Wu     SimplifiedValues[&SI] = SelectedC;
1242*3ec848bcSHaicheng Wu     return true;
1243*3ec848bcSHaicheng Wu   }
1244*3ec848bcSHaicheng Wu 
1245*3ec848bcSHaicheng Wu   if (!CheckSROA)
1246*3ec848bcSHaicheng Wu     return true;
1247*3ec848bcSHaicheng Wu 
1248*3ec848bcSHaicheng Wu   std::pair<Value *, APInt> BaseAndOffset =
1249*3ec848bcSHaicheng Wu       ConstantOffsetPtrs.lookup(SelectedV);
1250*3ec848bcSHaicheng Wu   if (BaseAndOffset.first) {
1251*3ec848bcSHaicheng Wu     ConstantOffsetPtrs[&SI] = BaseAndOffset;
1252*3ec848bcSHaicheng Wu 
1253*3ec848bcSHaicheng Wu     Value *SROAArg;
1254*3ec848bcSHaicheng Wu     DenseMap<Value *, int>::iterator CostIt;
1255*3ec848bcSHaicheng Wu     if (lookupSROAArgAndCost(SelectedV, SROAArg, CostIt))
1256*3ec848bcSHaicheng Wu       SROAArgValues[&SI] = SROAArg;
1257*3ec848bcSHaicheng Wu   }
1258*3ec848bcSHaicheng Wu 
1259*3ec848bcSHaicheng Wu   return true;
1260*3ec848bcSHaicheng Wu }
1261*3ec848bcSHaicheng Wu 
12627adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
12637adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
12647adc3a2bSChandler Carruth   // branches.
12657adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
12667adc3a2bSChandler Carruth     return true;
12677adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
12687adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
12697adc3a2bSChandler Carruth       return true;
12707adc3a2bSChandler Carruth 
12717ad02eeeSEric Christopher   // Assume the most general case where the switch is lowered into
1272919f9e8dSJun Bum Lim   // either a jump table, bit test, or a balanced binary tree consisting of
1273919f9e8dSJun Bum Lim   // case clusters without merging adjacent clusters with the same
1274919f9e8dSJun Bum Lim   // destination. We do not consider the switches that are lowered with a mix
1275919f9e8dSJun Bum Lim   // of jump table/bit test/binary search tree. The cost of the switch is
1276919f9e8dSJun Bum Lim   // proportional to the size of the tree or the size of jump table range.
12772960d41eSJun Bum Lim   //
12782960d41eSJun Bum Lim   // NB: We convert large switches which are just used to initialize large phi
12792960d41eSJun Bum Lim   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
12802960d41eSJun Bum Lim   // inlining those. It will prevent inlining in cases where the optimization
12812960d41eSJun Bum Lim   // does not (yet) fire.
1282919f9e8dSJun Bum Lim 
1283506cfb7aSJun Bum Lim   // Maximum valid cost increased in this function.
1284506cfb7aSJun Bum Lim   int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
1285506cfb7aSJun Bum Lim 
1286919f9e8dSJun Bum Lim   // Exit early for a large switch, assuming one case needs at least one
1287919f9e8dSJun Bum Lim   // instruction.
1288919f9e8dSJun Bum Lim   // FIXME: This is not true for a bit test, but ignore such case for now to
1289919f9e8dSJun Bum Lim   // save compile-time.
1290919f9e8dSJun Bum Lim   int64_t CostLowerBound =
1291506cfb7aSJun Bum Lim       std::min((int64_t)CostUpperBound,
1292919f9e8dSJun Bum Lim                (int64_t)SI.getNumCases() * InlineConstants::InstrCost + Cost);
1293919f9e8dSJun Bum Lim 
12940812c5beSHaicheng Wu   if (CostLowerBound > Threshold && !ComputeFullInlineCost) {
1295919f9e8dSJun Bum Lim     Cost = CostLowerBound;
1296919f9e8dSJun Bum Lim     return false;
1297919f9e8dSJun Bum Lim   }
1298919f9e8dSJun Bum Lim 
1299919f9e8dSJun Bum Lim   unsigned JumpTableSize = 0;
1300919f9e8dSJun Bum Lim   unsigned NumCaseCluster =
1301919f9e8dSJun Bum Lim       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize);
1302919f9e8dSJun Bum Lim 
1303919f9e8dSJun Bum Lim   // If suitable for a jump table, consider the cost for the table size and
1304919f9e8dSJun Bum Lim   // branch to destination.
1305919f9e8dSJun Bum Lim   if (JumpTableSize) {
1306919f9e8dSJun Bum Lim     int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
1307919f9e8dSJun Bum Lim                      4 * InlineConstants::InstrCost;
1308506cfb7aSJun Bum Lim 
1309506cfb7aSJun Bum Lim     Cost = std::min((int64_t)CostUpperBound, JTCost + Cost);
1310919f9e8dSJun Bum Lim     return false;
1311919f9e8dSJun Bum Lim   }
1312919f9e8dSJun Bum Lim 
1313919f9e8dSJun Bum Lim   // Considering forming a binary search, we should find the number of nodes
1314919f9e8dSJun Bum Lim   // which is same as the number of comparisons when lowered. For a given
1315919f9e8dSJun Bum Lim   // number of clusters, n, we can define a recursive function, f(n), to find
1316919f9e8dSJun Bum Lim   // the number of nodes in the tree. The recursion is :
1317919f9e8dSJun Bum Lim   // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
1318919f9e8dSJun Bum Lim   // and f(n) = n, when n <= 3.
1319919f9e8dSJun Bum Lim   // This will lead a binary tree where the leaf should be either f(2) or f(3)
1320919f9e8dSJun Bum Lim   // when n > 3.  So, the number of comparisons from leaves should be n, while
1321919f9e8dSJun Bum Lim   // the number of non-leaf should be :
1322919f9e8dSJun Bum Lim   //   2^(log2(n) - 1) - 1
1323919f9e8dSJun Bum Lim   //   = 2^log2(n) * 2^-1 - 1
1324919f9e8dSJun Bum Lim   //   = n / 2 - 1.
1325919f9e8dSJun Bum Lim   // Considering comparisons from leaf and non-leaf nodes, we can estimate the
1326919f9e8dSJun Bum Lim   // number of comparisons in a simple closed form :
1327919f9e8dSJun Bum Lim   //   n + n / 2 - 1 = n * 3 / 2 - 1
1328919f9e8dSJun Bum Lim   if (NumCaseCluster <= 3) {
1329919f9e8dSJun Bum Lim     // Suppose a comparison includes one compare and one conditional branch.
1330919f9e8dSJun Bum Lim     Cost += NumCaseCluster * 2 * InlineConstants::InstrCost;
1331919f9e8dSJun Bum Lim     return false;
1332919f9e8dSJun Bum Lim   }
1333506cfb7aSJun Bum Lim 
1334506cfb7aSJun Bum Lim   int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1;
1335506cfb7aSJun Bum Lim   int64_t SwitchCost =
1336919f9e8dSJun Bum Lim       ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
1337506cfb7aSJun Bum Lim 
1338506cfb7aSJun Bum Lim   Cost = std::min((int64_t)CostUpperBound, SwitchCost + Cost);
1339919f9e8dSJun Bum Lim   return false;
1340919f9e8dSJun Bum Lim }
1341919f9e8dSJun Bum Lim 
13427adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
13437adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
13447adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
13457adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
13467adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
13477adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
13487adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
13497adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
13507adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
13517adc3a2bSChandler Carruth   HasIndirectBr = true;
13527adc3a2bSChandler Carruth   return false;
13537adc3a2bSChandler Carruth }
13547adc3a2bSChandler Carruth 
13557adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
13567adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
13577adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
13587adc3a2bSChandler Carruth   return false;
13597adc3a2bSChandler Carruth }
13607adc3a2bSChandler Carruth 
13617adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
13627adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
13637adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
13647adc3a2bSChandler Carruth   return false;
13657adc3a2bSChandler Carruth }
13667adc3a2bSChandler Carruth 
13677adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
13687adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
13698220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
13707adc3a2bSChandler Carruth   return false;
13717adc3a2bSChandler Carruth }
13727adc3a2bSChandler Carruth 
13737adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
13747adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
13757adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
13767adc3a2bSChandler Carruth   // code size.
13777adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
13787adc3a2bSChandler Carruth }
13797adc3a2bSChandler Carruth 
13807adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
13817adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
13827adc3a2bSChandler Carruth   // handled by SROA, etc.
13837adc3a2bSChandler Carruth   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
13847adc3a2bSChandler Carruth     return true;
13857adc3a2bSChandler Carruth 
13867adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
13877adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
13887adc3a2bSChandler Carruth   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
13897adc3a2bSChandler Carruth     disableSROA(*OI);
13907adc3a2bSChandler Carruth 
13917adc3a2bSChandler Carruth   return false;
13927adc3a2bSChandler Carruth }
13937adc3a2bSChandler Carruth 
13947adc3a2bSChandler Carruth /// \brief Analyze a basic block for its contribution to the inline cost.
13957adc3a2bSChandler Carruth ///
13967adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
13977adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
13987adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
13997adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
14007adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
14017adc3a2bSChandler Carruth bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
14027adc3a2bSChandler Carruth                                 SmallPtrSetImpl<const Value *> &EphValues) {
14037adc3a2bSChandler Carruth   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
14047adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
14057adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
14067adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
14077adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
14087adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
14097adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
14107adc3a2bSChandler Carruth     // hack around it here.
14117adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
14127adc3a2bSChandler Carruth       continue;
14137adc3a2bSChandler Carruth 
14147adc3a2bSChandler Carruth     // Skip ephemeral values.
14155a82c916SDuncan P. N. Exon Smith     if (EphValues.count(&*I))
14167adc3a2bSChandler Carruth       continue;
14177adc3a2bSChandler Carruth 
14187adc3a2bSChandler Carruth     ++NumInstructions;
14197adc3a2bSChandler Carruth     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
14207adc3a2bSChandler Carruth       ++NumVectorInstructions;
14217adc3a2bSChandler Carruth 
1422e9434e80SSanjay Patel     // If the instruction is floating point, and the target says this operation
1423e9434e80SSanjay Patel     // is expensive or the function has the "use-soft-float" attribute, this may
14247adc3a2bSChandler Carruth     // eventually become a library call. Treat the cost as such.
14257adc3a2bSChandler Carruth     if (I->getType()->isFloatingPointTy()) {
1426e9434e80SSanjay Patel       // If the function has the "use-soft-float" attribute, mark it as
1427e9434e80SSanjay Patel       // expensive.
14287adc3a2bSChandler Carruth       if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
1429908ed7f2SEric Christopher           (F.getFnAttribute("use-soft-float").getValueAsString() == "true"))
14307adc3a2bSChandler Carruth         Cost += InlineConstants::CallPenalty;
14317adc3a2bSChandler Carruth     }
14327adc3a2bSChandler Carruth 
14337adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
14347adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
14357adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
14367adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
14377adc3a2bSChandler Carruth     // cost should count against inlining.
14385a82c916SDuncan P. N. Exon Smith     if (Base::visit(&*I))
14397adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
14407adc3a2bSChandler Carruth     else
14417adc3a2bSChandler Carruth       Cost += InlineConstants::InstrCost;
14427adc3a2bSChandler Carruth 
14430812c5beSHaicheng Wu     using namespace ore;
14447adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
14457adc3a2bSChandler Carruth     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
14460812c5beSHaicheng Wu         HasIndirectBr || HasFrameEscape) {
14470812c5beSHaicheng Wu       if (ORE)
14480812c5beSHaicheng Wu         ORE->emit(OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
14490812c5beSHaicheng Wu                                            CandidateCS.getInstruction())
14500812c5beSHaicheng Wu                   << NV("Callee", &F)
14510812c5beSHaicheng Wu                   << " has uninlinable pattern and cost is not fully computed");
14527adc3a2bSChandler Carruth       return false;
14530812c5beSHaicheng Wu     }
14547adc3a2bSChandler Carruth 
14557adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
14567adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
14577adc3a2bSChandler Carruth     // the caller stack usage dramatically.
14587adc3a2bSChandler Carruth     if (IsCallerRecursive &&
14590812c5beSHaicheng Wu         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) {
14600812c5beSHaicheng Wu       if (ORE)
14610812c5beSHaicheng Wu         ORE->emit(
14620812c5beSHaicheng Wu             OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
14630812c5beSHaicheng Wu                                      CandidateCS.getInstruction())
14640812c5beSHaicheng Wu             << NV("Callee", &F)
14650812c5beSHaicheng Wu             << " is recursive and allocates too much stack space. Cost is "
14660812c5beSHaicheng Wu                "not fully computed");
14677adc3a2bSChandler Carruth       return false;
14680812c5beSHaicheng Wu     }
14697adc3a2bSChandler Carruth 
14707adc3a2bSChandler Carruth     // Check if we've past the maximum possible threshold so we don't spin in
14717adc3a2bSChandler Carruth     // huge basic blocks that will never inline.
147261995364SHaicheng Wu     if (Cost >= Threshold && !ComputeFullInlineCost)
14737adc3a2bSChandler Carruth       return false;
14747adc3a2bSChandler Carruth   }
14757adc3a2bSChandler Carruth 
14767adc3a2bSChandler Carruth   return true;
14777adc3a2bSChandler Carruth }
14787adc3a2bSChandler Carruth 
14797adc3a2bSChandler Carruth /// \brief Compute the base pointer and cumulative constant offsets for V.
14807adc3a2bSChandler Carruth ///
14817adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
14827adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
14837adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
14847adc3a2bSChandler Carruth /// no constant offsets applied.
14857adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
14867adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
14877adc3a2bSChandler Carruth     return nullptr;
14887adc3a2bSChandler Carruth 
14897adc3a2bSChandler Carruth   unsigned IntPtrWidth = DL.getPointerSizeInBits();
14907adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
14917adc3a2bSChandler Carruth 
14927adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
14937adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
14947adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
14957adc3a2bSChandler Carruth   Visited.insert(V);
14967adc3a2bSChandler Carruth   do {
14977adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
14987adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
14997adc3a2bSChandler Carruth         return nullptr;
15007adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
15017adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
15027adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
15037adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
15045ce32728SSanjoy Das       if (GA->isInterposable())
15057adc3a2bSChandler Carruth         break;
15067adc3a2bSChandler Carruth       V = GA->getAliasee();
15077adc3a2bSChandler Carruth     } else {
15087adc3a2bSChandler Carruth       break;
15097adc3a2bSChandler Carruth     }
15107adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
15117adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
15127adc3a2bSChandler Carruth 
15137adc3a2bSChandler Carruth   Type *IntPtrTy = DL.getIntPtrType(V->getContext());
15147adc3a2bSChandler Carruth   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
15157adc3a2bSChandler Carruth }
15167adc3a2bSChandler Carruth 
15177adc3a2bSChandler Carruth /// \brief Analyze a call site for potential inlining.
15187adc3a2bSChandler Carruth ///
15197adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
15207adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
15217adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
15227adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
15237adc3a2bSChandler Carruth /// some artifact of the routine.
15247adc3a2bSChandler Carruth bool CallAnalyzer::analyzeCall(CallSite CS) {
15257adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
15267adc3a2bSChandler Carruth 
15277adc3a2bSChandler Carruth   // Perform some tweaks to the cost and threshold based on the direct
15287adc3a2bSChandler Carruth   // callsite information.
15297adc3a2bSChandler Carruth 
15307adc3a2bSChandler Carruth   // We want to more aggressively inline vector-dense kernels, so up the
15317adc3a2bSChandler Carruth   // threshold, and we'll lower it if the % of vector instructions gets too
15327adc3a2bSChandler Carruth   // low. Note that these bonuses are some what arbitrary and evolved over time
15337adc3a2bSChandler Carruth   // by accident as much as because they are principled bonuses.
15347adc3a2bSChandler Carruth   //
15357adc3a2bSChandler Carruth   // FIXME: It would be nice to remove all such bonuses. At least it would be
15367adc3a2bSChandler Carruth   // nice to base the bonus values on something more scientific.
15377adc3a2bSChandler Carruth   assert(NumInstructions == 0);
15387adc3a2bSChandler Carruth   assert(NumVectorInstructions == 0);
1539f4bb2f0dSEaswaran Raman 
1540f4bb2f0dSEaswaran Raman   // Update the threshold based on callsite properties
1541f4bb2f0dSEaswaran Raman   updateThreshold(CS, F);
1542f4bb2f0dSEaswaran Raman 
15437adc3a2bSChandler Carruth   // Speculatively apply all possible bonuses to Threshold. If cost exceeds
15447adc3a2bSChandler Carruth   // this Threshold any time, and cost cannot decrease, we can stop processing
15457adc3a2bSChandler Carruth   // the rest of the function body.
154651b809bfSEaswaran Raman   Threshold += (SingleBBBonus + VectorBonus);
15477adc3a2bSChandler Carruth 
1548351d9b01SXinliang David Li   // Give out bonuses for the callsite, as the instructions setting them up
1549351d9b01SXinliang David Li   // will be gone after inlining.
1550351d9b01SXinliang David Li   Cost -= getCallsiteCost(CS, DL);
15517adc3a2bSChandler Carruth 
15527adc3a2bSChandler Carruth   // If this function uses the coldcc calling convention, prefer not to inline
15537adc3a2bSChandler Carruth   // it.
15547adc3a2bSChandler Carruth   if (F.getCallingConv() == CallingConv::Cold)
15557adc3a2bSChandler Carruth     Cost += InlineConstants::ColdccPenalty;
15567adc3a2bSChandler Carruth 
15577adc3a2bSChandler Carruth   // Check if we're done. This can happen due to bonuses and penalties.
155861995364SHaicheng Wu   if (Cost >= Threshold && !ComputeFullInlineCost)
15597adc3a2bSChandler Carruth     return false;
15607adc3a2bSChandler Carruth 
15617adc3a2bSChandler Carruth   if (F.empty())
15627adc3a2bSChandler Carruth     return true;
15637adc3a2bSChandler Carruth 
15647adc3a2bSChandler Carruth   Function *Caller = CS.getInstruction()->getParent()->getParent();
15657adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
15667adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
15677adc3a2bSChandler Carruth     CallSite Site(U);
15687adc3a2bSChandler Carruth     if (!Site)
15697adc3a2bSChandler Carruth       continue;
15707adc3a2bSChandler Carruth     Instruction *I = Site.getInstruction();
15717adc3a2bSChandler Carruth     if (I->getParent()->getParent() == Caller) {
15727adc3a2bSChandler Carruth       IsCallerRecursive = true;
15737adc3a2bSChandler Carruth       break;
15747adc3a2bSChandler Carruth     }
15757adc3a2bSChandler Carruth   }
15767adc3a2bSChandler Carruth 
15777adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
15787adc3a2bSChandler Carruth   // arguments with known important simplifications.
15797adc3a2bSChandler Carruth   CallSite::arg_iterator CAI = CS.arg_begin();
15807adc3a2bSChandler Carruth   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
15817adc3a2bSChandler Carruth        FAI != FAE; ++FAI, ++CAI) {
15827adc3a2bSChandler Carruth     assert(CAI != CS.arg_end());
15837adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
15845a82c916SDuncan P. N. Exon Smith       SimplifiedValues[&*FAI] = C;
15857adc3a2bSChandler Carruth 
15867adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
15877adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
15885a82c916SDuncan P. N. Exon Smith       ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
15897adc3a2bSChandler Carruth 
15907adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
15917adc3a2bSChandler Carruth       if (isa<AllocaInst>(PtrArg)) {
15925a82c916SDuncan P. N. Exon Smith         SROAArgValues[&*FAI] = PtrArg;
15937adc3a2bSChandler Carruth         SROAArgCosts[PtrArg] = 0;
15947adc3a2bSChandler Carruth       }
15957adc3a2bSChandler Carruth     }
15967adc3a2bSChandler Carruth   }
15977adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
15987adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
15997adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
16007adc3a2bSChandler Carruth 
16017adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
16027adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
16037adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
16047adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
1605aec2fa35SDaniel Jasper   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
16067adc3a2bSChandler Carruth 
16077adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
16087adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
16097adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
16107adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
16117adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
16127adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
16137adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
16147adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1615567556aaSChad Rosier                     SmallPtrSet<BasicBlock *, 16>>
1616567556aaSChad Rosier       BBSetVector;
16177adc3a2bSChandler Carruth   BBSetVector BBWorklist;
16187adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
161951b809bfSEaswaran Raman   bool SingleBB = true;
16207adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
16217adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
16227adc3a2bSChandler Carruth     // Bail out the moment we cross the threshold. This means we'll under-count
16237adc3a2bSChandler Carruth     // the cost, but only when undercounting doesn't matter.
162461995364SHaicheng Wu     if (Cost >= Threshold && !ComputeFullInlineCost)
16257adc3a2bSChandler Carruth       break;
16267adc3a2bSChandler Carruth 
16277adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
16287adc3a2bSChandler Carruth     if (BB->empty())
16297adc3a2bSChandler Carruth       continue;
16307adc3a2bSChandler Carruth 
16317adc3a2bSChandler Carruth     // Disallow inlining a blockaddress. A blockaddress only has defined
16327adc3a2bSChandler Carruth     // behavior for an indirect branch in the same function, and we do not
16337adc3a2bSChandler Carruth     // currently support inlining indirect branches. But, the inliner may not
16347adc3a2bSChandler Carruth     // see an indirect branch that ends up being dead code at a particular call
16357adc3a2bSChandler Carruth     // site. If the blockaddress escapes the function, e.g., via a global
16367adc3a2bSChandler Carruth     // variable, inlining may lead to an invalid cross-function reference.
16377adc3a2bSChandler Carruth     if (BB->hasAddressTaken())
16387adc3a2bSChandler Carruth       return false;
16397adc3a2bSChandler Carruth 
16407adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
16417adc3a2bSChandler Carruth     // returns false, and we can bail on out.
1642d295b00aSEaswaran Raman     if (!analyzeBlock(BB, EphValues))
16437adc3a2bSChandler Carruth       return false;
16447adc3a2bSChandler Carruth 
16457adc3a2bSChandler Carruth     TerminatorInst *TI = BB->getTerminator();
16467adc3a2bSChandler Carruth 
16477adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
16487adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
16497adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
16507adc3a2bSChandler Carruth       if (BI->isConditional()) {
16517adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
1652567556aaSChad Rosier         if (ConstantInt *SimpleCond =
1653567556aaSChad Rosier                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
16547adc3a2bSChandler Carruth           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
16557adc3a2bSChandler Carruth           continue;
16567adc3a2bSChandler Carruth         }
16577adc3a2bSChandler Carruth       }
16587adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
16597adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
1660567556aaSChad Rosier       if (ConstantInt *SimpleCond =
1661567556aaSChad Rosier               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1662927d8e61SChandler Carruth         BBWorklist.insert(SI->findCaseValue(SimpleCond)->getCaseSuccessor());
16637adc3a2bSChandler Carruth         continue;
16647adc3a2bSChandler Carruth       }
16657adc3a2bSChandler Carruth     }
16667adc3a2bSChandler Carruth 
16677adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
16687adc3a2bSChandler Carruth     // them.
16697adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
16707adc3a2bSChandler Carruth          ++TIdx)
16717adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
16727adc3a2bSChandler Carruth 
16737adc3a2bSChandler Carruth     // If we had any successors at this point, than post-inlining is likely to
16747adc3a2bSChandler Carruth     // have them as well. Note that we assume any basic blocks which existed
16757adc3a2bSChandler Carruth     // due to branches or switches which folded above will also fold after
16767adc3a2bSChandler Carruth     // inlining.
16777adc3a2bSChandler Carruth     if (SingleBB && TI->getNumSuccessors() > 1) {
16787adc3a2bSChandler Carruth       // Take off the bonus we applied to the threshold.
16797adc3a2bSChandler Carruth       Threshold -= SingleBBBonus;
16807adc3a2bSChandler Carruth       SingleBB = false;
16817adc3a2bSChandler Carruth     }
16827adc3a2bSChandler Carruth   }
16837adc3a2bSChandler Carruth 
168451b809bfSEaswaran Raman   bool OnlyOneCallAndLocalLinkage =
168551b809bfSEaswaran Raman       F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction();
16867adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
16877adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
16887adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
16897adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
16907adc3a2bSChandler Carruth     return false;
16917adc3a2bSChandler Carruth 
16927adc3a2bSChandler Carruth   // We applied the maximum possible vector bonus at the beginning. Now,
16937adc3a2bSChandler Carruth   // subtract the excess bonus, if any, from the Threshold before
16947adc3a2bSChandler Carruth   // comparing against Cost.
16957adc3a2bSChandler Carruth   if (NumVectorInstructions <= NumInstructions / 10)
169651b809bfSEaswaran Raman     Threshold -= VectorBonus;
16977adc3a2bSChandler Carruth   else if (NumVectorInstructions <= NumInstructions / 2)
169851b809bfSEaswaran Raman     Threshold -= VectorBonus/2;
16997adc3a2bSChandler Carruth 
170000ab73dcSHans Wennborg   return Cost < std::max(1, Threshold);
17017adc3a2bSChandler Carruth }
17027adc3a2bSChandler Carruth 
17037adc3a2bSChandler Carruth #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
17047adc3a2bSChandler Carruth /// \brief Dump stats about this call's analysis.
1705eb2a2546SYaron Keren LLVM_DUMP_METHOD void CallAnalyzer::dump() {
17067adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
17077adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
17087adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
17097adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
17107adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
17117adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
17127adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
17137adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
17147adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
17157adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
17167adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
17177adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
17187adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
17197adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
17207adc3a2bSChandler Carruth }
17217adc3a2bSChandler Carruth #endif
17227adc3a2bSChandler Carruth 
17237adc3a2bSChandler Carruth /// \brief Test that there are no attribute conflicts between Caller and Callee
17247adc3a2bSChandler Carruth ///        that prevent inlining.
17257adc3a2bSChandler Carruth static bool functionsHaveCompatibleAttributes(Function *Caller,
17267adc3a2bSChandler Carruth                                               Function *Callee,
17277adc3a2bSChandler Carruth                                               TargetTransformInfo &TTI) {
17287adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
17291cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
17307adc3a2bSChandler Carruth }
17317adc3a2bSChandler Carruth 
1732351d9b01SXinliang David Li int llvm::getCallsiteCost(CallSite CS, const DataLayout &DL) {
1733351d9b01SXinliang David Li   int Cost = 0;
1734351d9b01SXinliang David Li   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
1735351d9b01SXinliang David Li     if (CS.isByValArgument(I)) {
1736351d9b01SXinliang David Li       // We approximate the number of loads and stores needed by dividing the
1737351d9b01SXinliang David Li       // size of the byval type by the target's pointer size.
1738351d9b01SXinliang David Li       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
1739351d9b01SXinliang David Li       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
1740351d9b01SXinliang David Li       unsigned PointerSize = DL.getPointerSizeInBits();
1741351d9b01SXinliang David Li       // Ceiling division.
1742351d9b01SXinliang David Li       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
1743351d9b01SXinliang David Li 
1744351d9b01SXinliang David Li       // If it generates more than 8 stores it is likely to be expanded as an
1745351d9b01SXinliang David Li       // inline memcpy so we take that as an upper bound. Otherwise we assume
1746351d9b01SXinliang David Li       // one load and one store per word copied.
1747351d9b01SXinliang David Li       // FIXME: The maxStoresPerMemcpy setting from the target should be used
1748351d9b01SXinliang David Li       // here instead of a magic number of 8, but it's not available via
1749351d9b01SXinliang David Li       // DataLayout.
1750351d9b01SXinliang David Li       NumStores = std::min(NumStores, 8U);
1751351d9b01SXinliang David Li 
1752351d9b01SXinliang David Li       Cost += 2 * NumStores * InlineConstants::InstrCost;
1753351d9b01SXinliang David Li     } else {
1754351d9b01SXinliang David Li       // For non-byval arguments subtract off one instruction per call
1755351d9b01SXinliang David Li       // argument.
1756351d9b01SXinliang David Li       Cost += InlineConstants::InstrCost;
1757351d9b01SXinliang David Li     }
1758351d9b01SXinliang David Li   }
1759351d9b01SXinliang David Li   // The call instruction also disappears after inlining.
1760351d9b01SXinliang David Li   Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty;
1761351d9b01SXinliang David Li   return Cost;
1762351d9b01SXinliang David Li }
1763351d9b01SXinliang David Li 
1764ab6a6837SSean Silva InlineCost llvm::getInlineCost(
17651c57cc2bSEaswaran Raman     CallSite CS, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
1766aec2fa35SDaniel Jasper     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
176712585b01SEaswaran Raman     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
17680812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
1769aec2fa35SDaniel Jasper   return getInlineCost(CS, CS.getCalledFunction(), Params, CalleeTTI,
17700812c5beSHaicheng Wu                        GetAssumptionCache, GetBFI, PSI, ORE);
1771b9f7120eSEaswaran Raman }
1772b9f7120eSEaswaran Raman 
1773ab6a6837SSean Silva InlineCost llvm::getInlineCost(
17741c57cc2bSEaswaran Raman     CallSite CS, Function *Callee, const InlineParams &Params,
1775aec2fa35SDaniel Jasper     TargetTransformInfo &CalleeTTI,
1776aec2fa35SDaniel Jasper     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
177712585b01SEaswaran Raman     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
17780812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
1779f4bb2f0dSEaswaran Raman 
17807adc3a2bSChandler Carruth   // Cannot inline indirect calls.
17817adc3a2bSChandler Carruth   if (!Callee)
17827adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
17837adc3a2bSChandler Carruth 
17847adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
17857adc3a2bSChandler Carruth   // whenever possible.
17867adc3a2bSChandler Carruth   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
17877adc3a2bSChandler Carruth     if (isInlineViable(*Callee))
17887adc3a2bSChandler Carruth       return llvm::InlineCost::getAlways();
17897adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
17907adc3a2bSChandler Carruth   }
17917adc3a2bSChandler Carruth 
17927adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
17937adc3a2bSChandler Carruth   // always-inline attribute).
17945ce28f4fSChad Rosier   Function *Caller = CS.getCaller();
17955ce28f4fSChad Rosier   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI))
17967adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
17977adc3a2bSChandler Carruth 
17987adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
17995ce28f4fSChad Rosier   if (Caller->hasFnAttribute(Attribute::OptimizeNone))
18007adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
18017adc3a2bSChandler Carruth 
18025ce32728SSanjoy Das   // Don't inline functions which can be interposed at link-time.  Don't inline
18035ce32728SSanjoy Das   // functions marked noinline or call sites marked noinline.
1804107b187dSCraig Topper   // Note: inlining non-exact non-interposable functions is fine, since we know
18055ce32728SSanjoy Das   // we have *a* correct implementation of the source level function.
1806567556aaSChad Rosier   if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
1807567556aaSChad Rosier       CS.isNoInline())
18087adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
18097adc3a2bSChandler Carruth 
18107adc3a2bSChandler Carruth   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
18114eb18742SChad Rosier                      << "... (caller:" << Caller->getName() << ")\n");
18127adc3a2bSChandler Carruth 
18130812c5beSHaicheng Wu   CallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE, *Callee, CS,
181412585b01SEaswaran Raman                   Params);
18157adc3a2bSChandler Carruth   bool ShouldInline = CA.analyzeCall(CS);
18167adc3a2bSChandler Carruth 
18177adc3a2bSChandler Carruth   DEBUG(CA.dump());
18187adc3a2bSChandler Carruth 
18197adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
18207adc3a2bSChandler Carruth   if (!ShouldInline && CA.getCost() < CA.getThreshold())
18217adc3a2bSChandler Carruth     return InlineCost::getNever();
18227adc3a2bSChandler Carruth   if (ShouldInline && CA.getCost() >= CA.getThreshold())
18237adc3a2bSChandler Carruth     return InlineCost::getAlways();
18247adc3a2bSChandler Carruth 
18257adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
18267adc3a2bSChandler Carruth }
18277adc3a2bSChandler Carruth 
1828b9f7120eSEaswaran Raman bool llvm::isInlineViable(Function &F) {
18297adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
18307adc3a2bSChandler Carruth   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
18317adc3a2bSChandler Carruth     // Disallow inlining of functions which contain indirect branches or
18327adc3a2bSChandler Carruth     // blockaddresses.
18337adc3a2bSChandler Carruth     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
18347adc3a2bSChandler Carruth       return false;
18357adc3a2bSChandler Carruth 
18365a82c916SDuncan P. N. Exon Smith     for (auto &II : *BI) {
18375a82c916SDuncan P. N. Exon Smith       CallSite CS(&II);
18387adc3a2bSChandler Carruth       if (!CS)
18397adc3a2bSChandler Carruth         continue;
18407adc3a2bSChandler Carruth 
18417adc3a2bSChandler Carruth       // Disallow recursive calls.
18427adc3a2bSChandler Carruth       if (&F == CS.getCalledFunction())
18437adc3a2bSChandler Carruth         return false;
18447adc3a2bSChandler Carruth 
18457adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
18467adc3a2bSChandler Carruth       // attributed as such.
18477adc3a2bSChandler Carruth       if (!ReturnsTwice && CS.isCall() &&
18487adc3a2bSChandler Carruth           cast<CallInst>(CS.getInstruction())->canReturnTwice())
18497adc3a2bSChandler Carruth         return false;
18507adc3a2bSChandler Carruth 
18517adc3a2bSChandler Carruth       // Disallow inlining functions that call @llvm.localescape. Doing this
18527adc3a2bSChandler Carruth       // correctly would require major changes to the inliner.
18537adc3a2bSChandler Carruth       if (CS.getCalledFunction() &&
18547adc3a2bSChandler Carruth           CS.getCalledFunction()->getIntrinsicID() ==
18557adc3a2bSChandler Carruth               llvm::Intrinsic::localescape)
18567adc3a2bSChandler Carruth         return false;
18577adc3a2bSChandler Carruth     }
18587adc3a2bSChandler Carruth   }
18597adc3a2bSChandler Carruth 
18607adc3a2bSChandler Carruth   return true;
18617adc3a2bSChandler Carruth }
18621c57cc2bSEaswaran Raman 
18631c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other
18641c57cc2bSEaswaran Raman // parameters.
18651c57cc2bSEaswaran Raman 
18661c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) {
18671c57cc2bSEaswaran Raman   InlineParams Params;
18681c57cc2bSEaswaran Raman 
18691c57cc2bSEaswaran Raman   // This field is the threshold to use for a callee by default. This is
18701c57cc2bSEaswaran Raman   // derived from one or more of:
18711c57cc2bSEaswaran Raman   //  * optimization or size-optimization levels,
18721c57cc2bSEaswaran Raman   //  * a value passed to createFunctionInliningPass function, or
18731c57cc2bSEaswaran Raman   //  * the -inline-threshold flag.
18741c57cc2bSEaswaran Raman   //  If the -inline-threshold flag is explicitly specified, that is used
18751c57cc2bSEaswaran Raman   //  irrespective of anything else.
18761c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() > 0)
18771c57cc2bSEaswaran Raman     Params.DefaultThreshold = InlineThreshold;
18781c57cc2bSEaswaran Raman   else
18791c57cc2bSEaswaran Raman     Params.DefaultThreshold = Threshold;
18801c57cc2bSEaswaran Raman 
18811c57cc2bSEaswaran Raman   // Set the HintThreshold knob from the -inlinehint-threshold.
18821c57cc2bSEaswaran Raman   Params.HintThreshold = HintThreshold;
18831c57cc2bSEaswaran Raman 
18841c57cc2bSEaswaran Raman   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
18851c57cc2bSEaswaran Raman   Params.HotCallSiteThreshold = HotCallSiteThreshold;
18861c57cc2bSEaswaran Raman 
1887974d4eeaSEaswaran Raman   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
1888974d4eeaSEaswaran Raman   // populate LocallyHotCallSiteThreshold. Later, we populate
1889974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
1890974d4eeaSEaswaran Raman   // we know that optimization level is O3 (in the getInlineParams variant that
1891974d4eeaSEaswaran Raman   // takes the opt and size levels).
1892974d4eeaSEaswaran Raman   // FIXME: Remove this check (and make the assignment unconditional) after
1893974d4eeaSEaswaran Raman   // addressing size regression issues at O2.
1894974d4eeaSEaswaran Raman   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
1895974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
1896974d4eeaSEaswaran Raman 
189712585b01SEaswaran Raman   // Set the ColdCallSiteThreshold knob from the -inline-cold-callsite-threshold.
189812585b01SEaswaran Raman   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
189912585b01SEaswaran Raman 
19001c57cc2bSEaswaran Raman   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
19011c57cc2bSEaswaran Raman   // -inlinehint-threshold commandline option is not explicitly given. If that
19021c57cc2bSEaswaran Raman   // option is present, then its value applies even for callees with size and
19031c57cc2bSEaswaran Raman   // minsize attributes.
19041c57cc2bSEaswaran Raman   // If the -inline-threshold is not specified, set the ColdThreshold from the
19051c57cc2bSEaswaran Raman   // -inlinecold-threshold even if it is not explicitly passed. If
19061c57cc2bSEaswaran Raman   // -inline-threshold is specified, then -inlinecold-threshold needs to be
19071c57cc2bSEaswaran Raman   // explicitly specified to set the ColdThreshold knob
19081c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() == 0) {
19091c57cc2bSEaswaran Raman     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
19101c57cc2bSEaswaran Raman     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
19111c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
19121c57cc2bSEaswaran Raman   } else if (ColdThreshold.getNumOccurrences() > 0) {
19131c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
19141c57cc2bSEaswaran Raman   }
19151c57cc2bSEaswaran Raman   return Params;
19161c57cc2bSEaswaran Raman }
19171c57cc2bSEaswaran Raman 
19181c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() {
19191c57cc2bSEaswaran Raman   return getInlineParams(InlineThreshold);
19201c57cc2bSEaswaran Raman }
19211c57cc2bSEaswaran Raman 
19221c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the
19231c57cc2bSEaswaran Raman // size opt level.
19241c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel,
19251c57cc2bSEaswaran Raman                                          unsigned SizeOptLevel) {
19261c57cc2bSEaswaran Raman   if (OptLevel > 2)
19271c57cc2bSEaswaran Raman     return InlineConstants::OptAggressiveThreshold;
19281c57cc2bSEaswaran Raman   if (SizeOptLevel == 1) // -Os
19291c57cc2bSEaswaran Raman     return InlineConstants::OptSizeThreshold;
19301c57cc2bSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
19311c57cc2bSEaswaran Raman     return InlineConstants::OptMinSizeThreshold;
19321c57cc2bSEaswaran Raman   return InlineThreshold;
19331c57cc2bSEaswaran Raman }
19341c57cc2bSEaswaran Raman 
19351c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
1936974d4eeaSEaswaran Raman   auto Params =
1937974d4eeaSEaswaran Raman       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
1938974d4eeaSEaswaran Raman   // At O3, use the value of -locally-hot-callsite-threshold option to populate
1939974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
1940974d4eeaSEaswaran Raman   // when it is specified explicitly.
1941974d4eeaSEaswaran Raman   if (OptLevel > 2)
1942974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
1943974d4eeaSEaswaran Raman   return Params;
19441c57cc2bSEaswaran Raman }
1945