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 
69c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq(
70c5fa6358SEaswaran Raman     "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
71c5fa6358SEaswaran Raman     cl::desc("Maxmimum block frequency, expressed as a percentage of caller's "
72c5fa6358SEaswaran Raman              "entry frequency, for a callsite to be cold in the absence of "
73c5fa6358SEaswaran Raman              "profile information."));
74c5fa6358SEaswaran Raman 
757adc3a2bSChandler Carruth namespace {
767adc3a2bSChandler Carruth 
777adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
787adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
797adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
807adc3a2bSChandler Carruth 
817adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
827adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
837adc3a2bSChandler Carruth 
84aec2fa35SDaniel Jasper   /// Getter for the cache of @llvm.assume intrinsics.
85aec2fa35SDaniel Jasper   std::function<AssumptionCache &(Function &)> &GetAssumptionCache;
86aec2fa35SDaniel Jasper 
8712585b01SEaswaran Raman   /// Getter for BlockFrequencyInfo
8812585b01SEaswaran Raman   Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI;
8912585b01SEaswaran Raman 
9071069cf6SEaswaran Raman   /// Profile summary information.
9171069cf6SEaswaran Raman   ProfileSummaryInfo *PSI;
9271069cf6SEaswaran Raman 
93f3d122cdSPiotr Padlewski   /// The called function.
947adc3a2bSChandler Carruth   Function &F;
957adc3a2bSChandler Carruth 
9685be8ca8SEric Christopher   // Cache the DataLayout since we use it a lot.
9785be8ca8SEric Christopher   const DataLayout &DL;
9885be8ca8SEric Christopher 
99f3d122cdSPiotr Padlewski   /// The candidate callsite being analyzed. Please do not use this to do
100f3d122cdSPiotr Padlewski   /// analysis in the caller function; we want the inline cost query to be
101f3d122cdSPiotr Padlewski   /// easily cacheable. Instead, use the cover function paramHasAttr.
1027adc3a2bSChandler Carruth   CallSite CandidateCS;
1037adc3a2bSChandler Carruth 
104f3d122cdSPiotr Padlewski   /// Tunable parameters that control the analysis.
1051c57cc2bSEaswaran Raman   const InlineParams &Params;
1061c57cc2bSEaswaran Raman 
1077adc3a2bSChandler Carruth   int Threshold;
1087adc3a2bSChandler Carruth   int Cost;
1097adc3a2bSChandler Carruth 
1107adc3a2bSChandler Carruth   bool IsCallerRecursive;
1117adc3a2bSChandler Carruth   bool IsRecursiveCall;
1127adc3a2bSChandler Carruth   bool ExposesReturnsTwice;
1137adc3a2bSChandler Carruth   bool HasDynamicAlloca;
1147adc3a2bSChandler Carruth   bool ContainsNoDuplicateCall;
1157adc3a2bSChandler Carruth   bool HasReturn;
1167adc3a2bSChandler Carruth   bool HasIndirectBr;
1177adc3a2bSChandler Carruth   bool HasFrameEscape;
1187adc3a2bSChandler Carruth 
1197adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
1207adc3a2bSChandler Carruth   uint64_t AllocatedSize;
1217adc3a2bSChandler Carruth   unsigned NumInstructions, NumVectorInstructions;
1227adc3a2bSChandler Carruth   int FiftyPercentVectorBonus, TenPercentVectorBonus;
1237adc3a2bSChandler Carruth   int VectorBonus;
1247adc3a2bSChandler Carruth 
125f3d122cdSPiotr Padlewski   /// While we walk the potentially-inlined instructions, we build up and
126f3d122cdSPiotr Padlewski   /// maintain a mapping of simplified values specific to this callsite. The
127f3d122cdSPiotr Padlewski   /// idea is to propagate any special information we have about arguments to
128f3d122cdSPiotr Padlewski   /// this call through the inlinable section of the function, and account for
129f3d122cdSPiotr Padlewski   /// likely simplifications post-inlining. The most important aspect we track
130f3d122cdSPiotr Padlewski   /// is CFG altering simplifications -- when we prove a basic block dead, that
131f3d122cdSPiotr Padlewski   /// can cause dramatic shifts in the cost of inlining a function.
1327adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
1337adc3a2bSChandler Carruth 
134f3d122cdSPiotr Padlewski   /// Keep track of the values which map back (through function arguments) to
135f3d122cdSPiotr Padlewski   /// allocas on the caller stack which could be simplified through SROA.
1367adc3a2bSChandler Carruth   DenseMap<Value *, Value *> SROAArgValues;
1377adc3a2bSChandler Carruth 
138f3d122cdSPiotr Padlewski   /// The mapping of caller Alloca values to their accumulated cost savings. If
139f3d122cdSPiotr Padlewski   /// we have to disable SROA for one of the allocas, this tells us how much
140f3d122cdSPiotr Padlewski   /// cost must be added.
1417adc3a2bSChandler Carruth   DenseMap<Value *, int> SROAArgCosts;
1427adc3a2bSChandler Carruth 
143f3d122cdSPiotr Padlewski   /// Keep track of values which map to a pointer base and constant offset.
1447adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
1457adc3a2bSChandler Carruth 
1467adc3a2bSChandler Carruth   // Custom simplification helper routines.
1477adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
1487adc3a2bSChandler Carruth   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
1497adc3a2bSChandler Carruth                             DenseMap<Value *, int>::iterator &CostIt);
1507adc3a2bSChandler Carruth   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
1517adc3a2bSChandler Carruth   void disableSROA(Value *V);
1527adc3a2bSChandler Carruth   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
1537adc3a2bSChandler Carruth                           int InstructionCost);
154201b191bSHaicheng Wu   bool isGEPFree(GetElementPtrInst &GEP);
1557adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
1567adc3a2bSChandler Carruth   bool simplifyCallSite(Function *F, CallSite CS);
157617f6364SEaswaran Raman   template <typename Callable>
158617f6364SEaswaran Raman   bool simplifyInstruction(Instruction &I, Callable Evaluate);
1597adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
1607adc3a2bSChandler Carruth 
1617adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
1627adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
1637adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
1647adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
1657adc3a2bSChandler Carruth   /// itself.
1667adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
1677adc3a2bSChandler Carruth 
1687adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
1697adc3a2bSChandler Carruth   /// inlined through this particular callsite.
1707adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
1717adc3a2bSChandler Carruth 
172f4bb2f0dSEaswaran Raman   /// Update Threshold based on callsite properties such as callee
173f4bb2f0dSEaswaran Raman   /// attributes and callee hotness for PGO builds. The Callee is explicitly
174f4bb2f0dSEaswaran Raman   /// passed to support analyzing indirect calls whose target is inferred by
175f4bb2f0dSEaswaran Raman   /// analysis.
176f4bb2f0dSEaswaran Raman   void updateThreshold(CallSite CS, Function &Callee);
177f4bb2f0dSEaswaran Raman 
1789a3fc17aSEaswaran Raman   /// Return true if size growth is allowed when inlining the callee at CS.
1799a3fc17aSEaswaran Raman   bool allowSizeGrowth(CallSite CS);
1809a3fc17aSEaswaran Raman 
181c5fa6358SEaswaran Raman   /// Return true if \p CS is a cold callsite.
182c5fa6358SEaswaran Raman   bool isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI);
183c5fa6358SEaswaran Raman 
1847adc3a2bSChandler Carruth   // Custom analysis routines.
1857adc3a2bSChandler Carruth   bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
1867adc3a2bSChandler Carruth 
1877adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
1887adc3a2bSChandler Carruth   // them by declaring but not defining them here.
189567556aaSChad Rosier   void visit(Module *);
190567556aaSChad Rosier   void visit(Module &);
191567556aaSChad Rosier   void visit(Function *);
192567556aaSChad Rosier   void visit(Function &);
193567556aaSChad Rosier   void visit(BasicBlock *);
194567556aaSChad Rosier   void visit(BasicBlock &);
1957adc3a2bSChandler Carruth 
1967adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
1977adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
1987adc3a2bSChandler Carruth 
1997adc3a2bSChandler Carruth   // Our visit overrides.
2007adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
2017adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
2027adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
2037adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
2047adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
2057adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
2067adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
2077adc3a2bSChandler Carruth   bool visitUnaryInstruction(UnaryInstruction &I);
2087adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
2097adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
2107adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
2117adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
2127adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
2137adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
2147adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
2157adc3a2bSChandler Carruth   bool visitCallSite(CallSite CS);
2167adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
2177adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
2187adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
2197adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
2207adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
2217adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
2227adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
2237adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
2247adc3a2bSChandler Carruth 
2257adc3a2bSChandler Carruth public:
226ab6a6837SSean Silva   CallAnalyzer(const TargetTransformInfo &TTI,
227aec2fa35SDaniel Jasper                std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
22812585b01SEaswaran Raman                Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI,
2291c57cc2bSEaswaran Raman                ProfileSummaryInfo *PSI, Function &Callee, CallSite CSArg,
2301c57cc2bSEaswaran Raman                const InlineParams &Params)
23112585b01SEaswaran Raman       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
23285be8ca8SEric Christopher         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()),
23385be8ca8SEric Christopher         CandidateCS(CSArg), Params(Params), Threshold(Params.DefaultThreshold),
23485be8ca8SEric Christopher         Cost(0), IsCallerRecursive(false), IsRecursiveCall(false),
23585be8ca8SEric Christopher         ExposesReturnsTwice(false), HasDynamicAlloca(false),
23685be8ca8SEric Christopher         ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
23785be8ca8SEric Christopher         HasFrameEscape(false), AllocatedSize(0), NumInstructions(0),
23885be8ca8SEric Christopher         NumVectorInstructions(0), FiftyPercentVectorBonus(0),
23985be8ca8SEric Christopher         TenPercentVectorBonus(0), VectorBonus(0), NumConstantArgs(0),
24085be8ca8SEric Christopher         NumConstantOffsetPtrArgs(0), NumAllocaArgs(0), NumConstantPtrCmps(0),
24185be8ca8SEric Christopher         NumConstantPtrDiffs(0), NumInstructionsSimplified(0),
24285be8ca8SEric Christopher         SROACostSavings(0), SROACostSavingsLost(0) {}
2437adc3a2bSChandler Carruth 
2447adc3a2bSChandler Carruth   bool analyzeCall(CallSite CS);
2457adc3a2bSChandler Carruth 
2467adc3a2bSChandler Carruth   int getThreshold() { return Threshold; }
2477adc3a2bSChandler Carruth   int getCost() { return Cost; }
2487adc3a2bSChandler Carruth 
2497adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
2507adc3a2bSChandler Carruth   // out when debugging.
2517adc3a2bSChandler Carruth   unsigned NumConstantArgs;
2527adc3a2bSChandler Carruth   unsigned NumConstantOffsetPtrArgs;
2537adc3a2bSChandler Carruth   unsigned NumAllocaArgs;
2547adc3a2bSChandler Carruth   unsigned NumConstantPtrCmps;
2557adc3a2bSChandler Carruth   unsigned NumConstantPtrDiffs;
2567adc3a2bSChandler Carruth   unsigned NumInstructionsSimplified;
2577adc3a2bSChandler Carruth   unsigned SROACostSavings;
2587adc3a2bSChandler Carruth   unsigned SROACostSavingsLost;
2597adc3a2bSChandler Carruth 
2607adc3a2bSChandler Carruth   void dump();
2617adc3a2bSChandler Carruth };
2627adc3a2bSChandler Carruth 
2637adc3a2bSChandler Carruth } // namespace
2647adc3a2bSChandler Carruth 
2657adc3a2bSChandler Carruth /// \brief Test whether the given value is an Alloca-derived function argument.
2667adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
2677adc3a2bSChandler Carruth   return SROAArgValues.count(V);
2687adc3a2bSChandler Carruth }
2697adc3a2bSChandler Carruth 
2707adc3a2bSChandler Carruth /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
2717adc3a2bSChandler Carruth /// Returns false if V does not map to a SROA-candidate.
2727adc3a2bSChandler Carruth bool CallAnalyzer::lookupSROAArgAndCost(
2737adc3a2bSChandler Carruth     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
2747adc3a2bSChandler Carruth   if (SROAArgValues.empty() || SROAArgCosts.empty())
2757adc3a2bSChandler Carruth     return false;
2767adc3a2bSChandler Carruth 
2777adc3a2bSChandler Carruth   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
2787adc3a2bSChandler Carruth   if (ArgIt == SROAArgValues.end())
2797adc3a2bSChandler Carruth     return false;
2807adc3a2bSChandler Carruth 
2817adc3a2bSChandler Carruth   Arg = ArgIt->second;
2827adc3a2bSChandler Carruth   CostIt = SROAArgCosts.find(Arg);
2837adc3a2bSChandler Carruth   return CostIt != SROAArgCosts.end();
2847adc3a2bSChandler Carruth }
2857adc3a2bSChandler Carruth 
2867adc3a2bSChandler Carruth /// \brief Disable SROA for the candidate marked by this cost iterator.
2877adc3a2bSChandler Carruth ///
2887adc3a2bSChandler Carruth /// This marks the candidate as no longer viable for SROA, and adds the cost
2897adc3a2bSChandler Carruth /// savings associated with it back into the inline cost measurement.
2907adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
2917adc3a2bSChandler Carruth   // If we're no longer able to perform SROA we need to undo its cost savings
2927adc3a2bSChandler Carruth   // and prevent subsequent analysis.
2937adc3a2bSChandler Carruth   Cost += CostIt->second;
2947adc3a2bSChandler Carruth   SROACostSavings -= CostIt->second;
2957adc3a2bSChandler Carruth   SROACostSavingsLost += CostIt->second;
2967adc3a2bSChandler Carruth   SROAArgCosts.erase(CostIt);
2977adc3a2bSChandler Carruth }
2987adc3a2bSChandler Carruth 
2997adc3a2bSChandler Carruth /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
3007adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
3017adc3a2bSChandler Carruth   Value *SROAArg;
3027adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
3037adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
3047adc3a2bSChandler Carruth     disableSROA(CostIt);
3057adc3a2bSChandler Carruth }
3067adc3a2bSChandler Carruth 
3077adc3a2bSChandler Carruth /// \brief Accumulate the given cost for a particular SROA candidate.
3087adc3a2bSChandler Carruth void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
3097adc3a2bSChandler Carruth                                       int InstructionCost) {
3107adc3a2bSChandler Carruth   CostIt->second += InstructionCost;
3117adc3a2bSChandler Carruth   SROACostSavings += InstructionCost;
3127adc3a2bSChandler Carruth }
3137adc3a2bSChandler Carruth 
3147adc3a2bSChandler Carruth /// \brief Accumulate a constant GEP offset into an APInt if possible.
3157adc3a2bSChandler Carruth ///
3167adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
3177adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
3187adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
3197adc3a2bSChandler Carruth   unsigned IntPtrWidth = DL.getPointerSizeInBits();
3207adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
3217adc3a2bSChandler Carruth 
3227adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
3237adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
3247adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
3257adc3a2bSChandler Carruth     if (!OpC)
3267adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
3277adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
3287adc3a2bSChandler Carruth     if (!OpC)
3297adc3a2bSChandler Carruth       return false;
330567556aaSChad Rosier     if (OpC->isZero())
331567556aaSChad Rosier       continue;
3327adc3a2bSChandler Carruth 
3337adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
334ab85225bSPeter Collingbourne     if (StructType *STy = GTI.getStructTypeOrNull()) {
3357adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
3367adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
3377adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
3387adc3a2bSChandler Carruth       continue;
3397adc3a2bSChandler Carruth     }
3407adc3a2bSChandler Carruth 
3417adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
3427adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
3437adc3a2bSChandler Carruth   }
3447adc3a2bSChandler Carruth   return true;
3457adc3a2bSChandler Carruth }
3467adc3a2bSChandler Carruth 
347201b191bSHaicheng Wu /// \brief Use TTI to check whether a GEP is free.
348201b191bSHaicheng Wu ///
349201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite.
350201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
351*61c1bd5aSEvgeny Astigeevich   SmallVector<Value *, 4> Operands;
352*61c1bd5aSEvgeny Astigeevich   Operands.push_back(GEP.getOperand(0));
353201b191bSHaicheng Wu   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
354201b191bSHaicheng Wu     if (Constant *SimpleOp = SimplifiedValues.lookup(*I))
355*61c1bd5aSEvgeny Astigeevich        Operands.push_back(SimpleOp);
356201b191bSHaicheng Wu      else
357*61c1bd5aSEvgeny Astigeevich        Operands.push_back(*I);
358*61c1bd5aSEvgeny Astigeevich   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands);
359201b191bSHaicheng Wu }
360201b191bSHaicheng Wu 
3617adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
3627adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
3630f153424SSanjay Patel   // alloca and handle that case.
3647adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
3650f153424SSanjay Patel     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
3660f153424SSanjay Patel     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
3677adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
36822eb80a1SEaswaran Raman       AllocatedSize = SaturatingMultiplyAdd(
36922eb80a1SEaswaran Raman           AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty), AllocatedSize);
3707adc3a2bSChandler Carruth       return Base::visitAlloca(I);
3717adc3a2bSChandler Carruth     }
3727adc3a2bSChandler Carruth   }
3737adc3a2bSChandler Carruth 
3747adc3a2bSChandler Carruth   // Accumulate the allocated size.
3757adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
3767adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
37722eb80a1SEaswaran Raman     AllocatedSize = SaturatingAdd(DL.getTypeAllocSize(Ty), AllocatedSize);
3787adc3a2bSChandler Carruth   }
3797adc3a2bSChandler Carruth 
3807adc3a2bSChandler Carruth   // We will happily inline static alloca instructions.
3817adc3a2bSChandler Carruth   if (I.isStaticAlloca())
3827adc3a2bSChandler Carruth     return Base::visitAlloca(I);
3837adc3a2bSChandler Carruth 
3847adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
3857adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
3867adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
3877adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
3887adc3a2bSChandler Carruth   HasDynamicAlloca = true;
3897adc3a2bSChandler Carruth   return false;
3907adc3a2bSChandler Carruth }
3917adc3a2bSChandler Carruth 
3927adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
3937adc3a2bSChandler Carruth   // FIXME: We should potentially be tracking values through phi nodes,
3947adc3a2bSChandler Carruth   // especially when they collapse to a single value due to deleted CFG edges
3957adc3a2bSChandler Carruth   // during inlining.
3967adc3a2bSChandler Carruth 
3977adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
3987adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
3997adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
4007adc3a2bSChandler Carruth 
4017adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
4027adc3a2bSChandler Carruth   return true;
4037adc3a2bSChandler Carruth }
4047adc3a2bSChandler Carruth 
4057adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
4067adc3a2bSChandler Carruth   Value *SROAArg;
4077adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
408567556aaSChad Rosier   bool SROACandidate =
409567556aaSChad Rosier       lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt);
4107adc3a2bSChandler Carruth 
4117adc3a2bSChandler Carruth   // Try to fold GEPs of constant-offset call site argument pointers. This
4127adc3a2bSChandler Carruth   // requires target data and inbounds GEPs.
4137adc3a2bSChandler Carruth   if (I.isInBounds()) {
4147adc3a2bSChandler Carruth     // Check if we have a base + offset for the pointer.
4157adc3a2bSChandler Carruth     Value *Ptr = I.getPointerOperand();
4167adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
4177adc3a2bSChandler Carruth     if (BaseAndOffset.first) {
4187adc3a2bSChandler Carruth       // Check if the offset of this GEP is constant, and if so accumulate it
4197adc3a2bSChandler Carruth       // into Offset.
4207adc3a2bSChandler Carruth       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
4217adc3a2bSChandler Carruth         // Non-constant GEPs aren't folded, and disable SROA.
4227adc3a2bSChandler Carruth         if (SROACandidate)
4237adc3a2bSChandler Carruth           disableSROA(CostIt);
424201b191bSHaicheng Wu         return isGEPFree(I);
4257adc3a2bSChandler Carruth       }
4267adc3a2bSChandler Carruth 
4277adc3a2bSChandler Carruth       // Add the result as a new mapping to Base + Offset.
4287adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
4297adc3a2bSChandler Carruth 
4307adc3a2bSChandler Carruth       // Also handle SROA candidates here, we already know that the GEP is
4317adc3a2bSChandler Carruth       // all-constant indexed.
4327adc3a2bSChandler Carruth       if (SROACandidate)
4337adc3a2bSChandler Carruth         SROAArgValues[&I] = SROAArg;
4347adc3a2bSChandler Carruth 
4357adc3a2bSChandler Carruth       return true;
4367adc3a2bSChandler Carruth     }
4377adc3a2bSChandler Carruth   }
4387adc3a2bSChandler Carruth 
439a8b9cdc9SEaswaran Raman   // Lambda to check whether a GEP's indices are all constant.
440a8b9cdc9SEaswaran Raman   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
441a8b9cdc9SEaswaran Raman     for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
442a8b9cdc9SEaswaran Raman       if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
443a8b9cdc9SEaswaran Raman         return false;
444a8b9cdc9SEaswaran Raman     return true;
445a8b9cdc9SEaswaran Raman   };
446a8b9cdc9SEaswaran Raman 
447a8b9cdc9SEaswaran Raman   if (IsGEPOffsetConstant(I)) {
4487adc3a2bSChandler Carruth     if (SROACandidate)
4497adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
4507adc3a2bSChandler Carruth 
4517adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
4527adc3a2bSChandler Carruth     return true;
4537adc3a2bSChandler Carruth   }
4547adc3a2bSChandler Carruth 
4557adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
4567adc3a2bSChandler Carruth   if (SROACandidate)
4577adc3a2bSChandler Carruth     disableSROA(CostIt);
458201b191bSHaicheng Wu   return isGEPFree(I);
4597adc3a2bSChandler Carruth }
4607adc3a2bSChandler Carruth 
461617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues.
462617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the
463617f6364SEaswaran Raman /// instruction when all the operands are constants.
464617f6364SEaswaran Raman template <typename Callable>
465617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
466617f6364SEaswaran Raman   SmallVector<Constant *, 2> COps;
467617f6364SEaswaran Raman   for (Value *Op : I.operands()) {
468617f6364SEaswaran Raman     Constant *COp = dyn_cast<Constant>(Op);
4697adc3a2bSChandler Carruth     if (!COp)
470617f6364SEaswaran Raman       COp = SimplifiedValues.lookup(Op);
471617f6364SEaswaran Raman     if (!COp)
472617f6364SEaswaran Raman       return false;
473617f6364SEaswaran Raman     COps.push_back(COp);
474617f6364SEaswaran Raman   }
475617f6364SEaswaran Raman   auto *C = Evaluate(COps);
476617f6364SEaswaran Raman   if (!C)
477617f6364SEaswaran Raman     return false;
4787adc3a2bSChandler Carruth   SimplifiedValues[&I] = C;
4797adc3a2bSChandler Carruth   return true;
4807adc3a2bSChandler Carruth }
4817adc3a2bSChandler Carruth 
482617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) {
483617f6364SEaswaran Raman   // Propagate constants through bitcasts.
484617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
485617f6364SEaswaran Raman         return ConstantExpr::getBitCast(COps[0], I.getType());
486617f6364SEaswaran Raman       }))
487617f6364SEaswaran Raman     return true;
488617f6364SEaswaran Raman 
4897adc3a2bSChandler Carruth   // Track base/offsets through casts
490567556aaSChad Rosier   std::pair<Value *, APInt> BaseAndOffset =
491567556aaSChad Rosier       ConstantOffsetPtrs.lookup(I.getOperand(0));
4927adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
4937adc3a2bSChandler Carruth   if (BaseAndOffset.first)
4947adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
4957adc3a2bSChandler Carruth 
4967adc3a2bSChandler Carruth   // Also look for SROA candidates here.
4977adc3a2bSChandler Carruth   Value *SROAArg;
4987adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
4997adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
5007adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
5017adc3a2bSChandler Carruth 
5027adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
5037adc3a2bSChandler Carruth   return true;
5047adc3a2bSChandler Carruth }
5057adc3a2bSChandler Carruth 
5067adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
5077adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
508617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
509617f6364SEaswaran Raman         return ConstantExpr::getPtrToInt(COps[0], I.getType());
510617f6364SEaswaran Raman       }))
5117adc3a2bSChandler Carruth     return true;
5127adc3a2bSChandler Carruth 
5137adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
5147adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
5157adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
5167adc3a2bSChandler Carruth   if (IntegerSize >= DL.getPointerSizeInBits()) {
517567556aaSChad Rosier     std::pair<Value *, APInt> BaseAndOffset =
518567556aaSChad Rosier         ConstantOffsetPtrs.lookup(I.getOperand(0));
5197adc3a2bSChandler Carruth     if (BaseAndOffset.first)
5207adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
5217adc3a2bSChandler Carruth   }
5227adc3a2bSChandler Carruth 
5237adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
5247adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
5257adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
5267adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
5277adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
5287adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
5297adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
5307adc3a2bSChandler Carruth   Value *SROAArg;
5317adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
5327adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
5337adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
5347adc3a2bSChandler Carruth 
5357adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
5367adc3a2bSChandler Carruth }
5377adc3a2bSChandler Carruth 
5387adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
5397adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
540617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
541617f6364SEaswaran Raman         return ConstantExpr::getIntToPtr(COps[0], I.getType());
542617f6364SEaswaran Raman       }))
5437adc3a2bSChandler Carruth     return true;
5447adc3a2bSChandler Carruth 
5457adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
5467adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
5477adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
5487adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
5497adc3a2bSChandler Carruth   if (IntegerSize <= DL.getPointerSizeInBits()) {
5507adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
5517adc3a2bSChandler Carruth     if (BaseAndOffset.first)
5527adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
5537adc3a2bSChandler Carruth   }
5547adc3a2bSChandler Carruth 
5557adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
5567adc3a2bSChandler Carruth   Value *SROAArg;
5577adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
5587adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
5597adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
5607adc3a2bSChandler Carruth 
5617adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
5627adc3a2bSChandler Carruth }
5637adc3a2bSChandler Carruth 
5647adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
5657adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
566617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
567617f6364SEaswaran Raman         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
568617f6364SEaswaran Raman       }))
5697adc3a2bSChandler Carruth     return true;
5707adc3a2bSChandler Carruth 
5717adc3a2bSChandler Carruth   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
5727adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
5737adc3a2bSChandler Carruth 
5747adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
5757adc3a2bSChandler Carruth }
5767adc3a2bSChandler Carruth 
5777adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
5787adc3a2bSChandler Carruth   Value *Operand = I.getOperand(0);
579617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
580617f6364SEaswaran Raman         return ConstantFoldInstOperands(&I, COps[0], DL);
581617f6364SEaswaran Raman       }))
5827adc3a2bSChandler Carruth     return true;
5837adc3a2bSChandler Carruth 
5847adc3a2bSChandler Carruth   // Disable any SROA on the argument to arbitrary unary operators.
5857adc3a2bSChandler Carruth   disableSROA(Operand);
5867adc3a2bSChandler Carruth 
5877adc3a2bSChandler Carruth   return false;
5887adc3a2bSChandler Carruth }
5897adc3a2bSChandler Carruth 
5907adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
591fb502d2fSReid Kleckner   return CandidateCS.paramHasAttr(A->getArgNo(), Attr);
5927adc3a2bSChandler Carruth }
5937adc3a2bSChandler Carruth 
5947adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
5957adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
5967adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
5977adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
5987adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
5997adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
6007adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
6017adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
6027adc3a2bSChandler Carruth       return true;
6037adc3a2bSChandler Carruth 
6047adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
6057adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
6067adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
6077adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
6087adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
6097adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
6107adc3a2bSChandler Carruth     // SROA firing.
6117adc3a2bSChandler Carruth     return true;
6127adc3a2bSChandler Carruth 
6137adc3a2bSChandler Carruth   return false;
6147adc3a2bSChandler Carruth }
6157adc3a2bSChandler Carruth 
6169a3fc17aSEaswaran Raman bool CallAnalyzer::allowSizeGrowth(CallSite CS) {
6179a3fc17aSEaswaran Raman   // If the normal destination of the invoke or the parent block of the call
6189a3fc17aSEaswaran Raman   // site is unreachable-terminated, there is little point in inlining this
6199a3fc17aSEaswaran Raman   // unless there is literally zero cost.
6209a3fc17aSEaswaran Raman   // FIXME: Note that it is possible that an unreachable-terminated block has a
6219a3fc17aSEaswaran Raman   // hot entry. For example, in below scenario inlining hot_call_X() may be
6229a3fc17aSEaswaran Raman   // beneficial :
6239a3fc17aSEaswaran Raman   // main() {
6249a3fc17aSEaswaran Raman   //   hot_call_1();
6259a3fc17aSEaswaran Raman   //   ...
6269a3fc17aSEaswaran Raman   //   hot_call_N()
6279a3fc17aSEaswaran Raman   //   exit(0);
6289a3fc17aSEaswaran Raman   // }
6299a3fc17aSEaswaran Raman   // For now, we are not handling this corner case here as it is rare in real
6309a3fc17aSEaswaran Raman   // code. In future, we should elaborate this based on BPI and BFI in more
6319a3fc17aSEaswaran Raman   // general threshold adjusting heuristics in updateThreshold().
6329a3fc17aSEaswaran Raman   Instruction *Instr = CS.getInstruction();
6339a3fc17aSEaswaran Raman   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
6349a3fc17aSEaswaran Raman     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
6359a3fc17aSEaswaran Raman       return false;
6369a3fc17aSEaswaran Raman   } else if (isa<UnreachableInst>(Instr->getParent()->getTerminator()))
6379a3fc17aSEaswaran Raman     return false;
6389a3fc17aSEaswaran Raman 
6399a3fc17aSEaswaran Raman   return true;
6409a3fc17aSEaswaran Raman }
6419a3fc17aSEaswaran Raman 
642c5fa6358SEaswaran Raman bool CallAnalyzer::isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI) {
643c5fa6358SEaswaran Raman   // If global profile summary is available, then callsite's coldness is
644c5fa6358SEaswaran Raman   // determined based on that.
645c5fa6358SEaswaran Raman   if (PSI->hasProfileSummary())
646c5fa6358SEaswaran Raman     return PSI->isColdCallSite(CS, CallerBFI);
647c5fa6358SEaswaran Raman   if (!CallerBFI)
648c5fa6358SEaswaran Raman     return false;
649c5fa6358SEaswaran Raman 
650c5fa6358SEaswaran Raman   // In the absence of global profile summary, determine if the callsite is cold
651c5fa6358SEaswaran Raman   // relative to caller's entry. We could potentially cache the computation of
652c5fa6358SEaswaran Raman   // scaled entry frequency, but the added complexity is not worth it unless
653c5fa6358SEaswaran Raman   // this scaling shows up high in the profiles.
654c5fa6358SEaswaran Raman   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
655c5fa6358SEaswaran Raman   auto CallSiteBB = CS.getInstruction()->getParent();
656c5fa6358SEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
657c5fa6358SEaswaran Raman   auto CallerEntryFreq =
658c5fa6358SEaswaran Raman       CallerBFI->getBlockFreq(&(CS.getCaller()->getEntryBlock()));
659c5fa6358SEaswaran Raman   return CallSiteFreq < CallerEntryFreq * ColdProb;
660c5fa6358SEaswaran Raman }
661c5fa6358SEaswaran Raman 
662f4bb2f0dSEaswaran Raman void CallAnalyzer::updateThreshold(CallSite CS, Function &Callee) {
6639a3fc17aSEaswaran Raman   // If no size growth is allowed for this inlining, set Threshold to 0.
6649a3fc17aSEaswaran Raman   if (!allowSizeGrowth(CS)) {
6659a3fc17aSEaswaran Raman     Threshold = 0;
6669a3fc17aSEaswaran Raman     return;
6679a3fc17aSEaswaran Raman   }
6689a3fc17aSEaswaran Raman 
669bb578ef0SEaswaran Raman   Function *Caller = CS.getCaller();
6701c57cc2bSEaswaran Raman 
6711c57cc2bSEaswaran Raman   // return min(A, B) if B is valid.
6721c57cc2bSEaswaran Raman   auto MinIfValid = [](int A, Optional<int> B) {
6731c57cc2bSEaswaran Raman     return B ? std::min(A, B.getValue()) : A;
6741c57cc2bSEaswaran Raman   };
6751c57cc2bSEaswaran Raman 
6760d58fcacSEaswaran Raman   // return max(A, B) if B is valid.
6770d58fcacSEaswaran Raman   auto MaxIfValid = [](int A, Optional<int> B) {
6780d58fcacSEaswaran Raman     return B ? std::max(A, B.getValue()) : A;
6790d58fcacSEaswaran Raman   };
6800d58fcacSEaswaran Raman 
6811c57cc2bSEaswaran Raman   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
6821c57cc2bSEaswaran Raman   // and reduce the threshold if the caller has the necessary attribute.
6831c57cc2bSEaswaran Raman   if (Caller->optForMinSize())
6841c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
6851c57cc2bSEaswaran Raman   else if (Caller->optForSize())
6861c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
687f4bb2f0dSEaswaran Raman 
688e08b139dSEaswaran Raman   // Adjust the threshold based on inlinehint attribute and profile based
689e08b139dSEaswaran Raman   // hotness information if the caller does not have MinSize attribute.
690e08b139dSEaswaran Raman   if (!Caller->optForMinSize()) {
691e08b139dSEaswaran Raman     if (Callee.hasFnAttribute(Attribute::InlineHint))
6920d58fcacSEaswaran Raman       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
693e08b139dSEaswaran Raman     if (PSI) {
69412585b01SEaswaran Raman       BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr;
6953cd1479cSEaswaran Raman       // FIXME: After switching to the new passmanager, simplify the logic below
6963cd1479cSEaswaran Raman       // by checking only the callsite hotness/coldness. The check for CallerBFI
6973cd1479cSEaswaran Raman       // exists only because we do not have BFI available with the old PM.
6983cd1479cSEaswaran Raman       //
6993cd1479cSEaswaran Raman       // Use callee's hotness information only if we have no way of determining
7003cd1479cSEaswaran Raman       // callsite's hotness information. Callsite hotness can be determined if
7013cd1479cSEaswaran Raman       // sample profile is used (which adds hotness metadata to calls) or if
7023cd1479cSEaswaran Raman       // caller's BlockFrequencyInfo is available.
7033cd1479cSEaswaran Raman       if (CallerBFI || PSI->hasSampleProfile()) {
70412585b01SEaswaran Raman         if (PSI->isHotCallSite(CS, CallerBFI)) {
70512585b01SEaswaran Raman           DEBUG(dbgs() << "Hot callsite.\n");
7069907e9d8SDehao Chen           Threshold = Params.HotCallSiteThreshold.getValue();
707c5fa6358SEaswaran Raman         } else if (isColdCallSite(CS, CallerBFI)) {
7083cd1479cSEaswaran Raman           DEBUG(dbgs() << "Cold callsite.\n");
7093cd1479cSEaswaran Raman           Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
7103cd1479cSEaswaran Raman         }
7113cd1479cSEaswaran Raman       } else {
7123cd1479cSEaswaran Raman         if (PSI->isFunctionEntryHot(&Callee)) {
71312585b01SEaswaran Raman           DEBUG(dbgs() << "Hot callee.\n");
714e08b139dSEaswaran Raman           // If callsite hotness can not be determined, we may still know
715e08b139dSEaswaran Raman           // that the callee is hot and treat it as a weaker hint for threshold
716e08b139dSEaswaran Raman           // increase.
717e08b139dSEaswaran Raman           Threshold = MaxIfValid(Threshold, Params.HintThreshold);
718e08b139dSEaswaran Raman         } else if (PSI->isFunctionEntryCold(&Callee)) {
71912585b01SEaswaran Raman           DEBUG(dbgs() << "Cold callee.\n");
7201c57cc2bSEaswaran Raman           Threshold = MinIfValid(Threshold, Params.ColdThreshold);
721e08b139dSEaswaran Raman         }
722e08b139dSEaswaran Raman       }
723e08b139dSEaswaran Raman     }
7243cd1479cSEaswaran Raman   }
7258650a4daSJustin Lebar 
7268650a4daSJustin Lebar   // Finally, take the target-specific inlining threshold multiplier into
7278650a4daSJustin Lebar   // account.
7288650a4daSJustin Lebar   Threshold *= TTI.getInliningThresholdMultiplier();
729f4bb2f0dSEaswaran Raman }
730f4bb2f0dSEaswaran Raman 
7317adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
7327adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
7337adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
734617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
735617f6364SEaswaran Raman         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
736617f6364SEaswaran Raman       }))
7377adc3a2bSChandler Carruth     return true;
7387adc3a2bSChandler Carruth 
7397adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
7407adc3a2bSChandler Carruth     return false;
7417adc3a2bSChandler Carruth 
7427adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
7437adc3a2bSChandler Carruth   // a common base.
7447adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
7457adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
7467adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
7477adc3a2bSChandler Carruth   if (LHSBase) {
7487adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
7497adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
7507adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
7517adc3a2bSChandler Carruth       // offsets.
7527adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
7537adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
7547adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
7557adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
7567adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
7577adc3a2bSChandler Carruth         return true;
7587adc3a2bSChandler Carruth       }
7597adc3a2bSChandler Carruth     }
7607adc3a2bSChandler Carruth   }
7617adc3a2bSChandler Carruth 
7627adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
7637adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
7647adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
7657adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
7667adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
7677adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
7687adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
7697adc3a2bSChandler Carruth     return true;
7707adc3a2bSChandler Carruth   }
7717adc3a2bSChandler Carruth   // Finally check for SROA candidates in comparisons.
7727adc3a2bSChandler Carruth   Value *SROAArg;
7737adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
7747adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
7757adc3a2bSChandler Carruth     if (isa<ConstantPointerNull>(I.getOperand(1))) {
7767adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
7777adc3a2bSChandler Carruth       return true;
7787adc3a2bSChandler Carruth     }
7797adc3a2bSChandler Carruth 
7807adc3a2bSChandler Carruth     disableSROA(CostIt);
7817adc3a2bSChandler Carruth   }
7827adc3a2bSChandler Carruth 
7837adc3a2bSChandler Carruth   return false;
7847adc3a2bSChandler Carruth }
7857adc3a2bSChandler Carruth 
7867adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
7877adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
7887adc3a2bSChandler Carruth   // constant-related pointers.
7897adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
7907adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
7917adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
7927adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
7937adc3a2bSChandler Carruth   if (LHSBase) {
7947adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
7957adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
7967adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
7977adc3a2bSChandler Carruth       // offsets.
7987adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
7997adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
8007adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
8017adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
8027adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
8037adc3a2bSChandler Carruth         return true;
8047adc3a2bSChandler Carruth       }
8057adc3a2bSChandler Carruth     }
8067adc3a2bSChandler Carruth   }
8077adc3a2bSChandler Carruth 
8087adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
8097adc3a2bSChandler Carruth   // instructions.
8107adc3a2bSChandler Carruth   return Base::visitSub(I);
8117adc3a2bSChandler Carruth }
8127adc3a2bSChandler Carruth 
8137adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
8147adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
815617f6364SEaswaran Raman   auto Evaluate = [&](SmallVectorImpl<Constant *> &COps) {
8167adc3a2bSChandler Carruth     Value *SimpleV = nullptr;
8177adc3a2bSChandler Carruth     if (auto FI = dyn_cast<FPMathOperator>(&I))
818617f6364SEaswaran Raman       SimpleV = SimplifyFPBinOp(I.getOpcode(), COps[0], COps[1],
819617f6364SEaswaran Raman                                 FI->getFastMathFlags(), DL);
8207adc3a2bSChandler Carruth     else
821617f6364SEaswaran Raman       SimpleV = SimplifyBinOp(I.getOpcode(), COps[0], COps[1], DL);
822617f6364SEaswaran Raman     return dyn_cast_or_null<Constant>(SimpleV);
823617f6364SEaswaran Raman   };
8247adc3a2bSChandler Carruth 
825617f6364SEaswaran Raman   if (simplifyInstruction(I, Evaluate))
8267adc3a2bSChandler Carruth     return true;
8277adc3a2bSChandler Carruth 
8287adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
8297adc3a2bSChandler Carruth   disableSROA(LHS);
8307adc3a2bSChandler Carruth   disableSROA(RHS);
8317adc3a2bSChandler Carruth 
8327adc3a2bSChandler Carruth   return false;
8337adc3a2bSChandler Carruth }
8347adc3a2bSChandler Carruth 
8357adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
8367adc3a2bSChandler Carruth   Value *SROAArg;
8377adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
8387adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
8397adc3a2bSChandler Carruth     if (I.isSimple()) {
8407adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
8417adc3a2bSChandler Carruth       return true;
8427adc3a2bSChandler Carruth     }
8437adc3a2bSChandler Carruth 
8447adc3a2bSChandler Carruth     disableSROA(CostIt);
8457adc3a2bSChandler Carruth   }
8467adc3a2bSChandler Carruth 
8477adc3a2bSChandler Carruth   return false;
8487adc3a2bSChandler Carruth }
8497adc3a2bSChandler Carruth 
8507adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
8517adc3a2bSChandler Carruth   Value *SROAArg;
8527adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
8537adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
8547adc3a2bSChandler Carruth     if (I.isSimple()) {
8557adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
8567adc3a2bSChandler Carruth       return true;
8577adc3a2bSChandler Carruth     }
8587adc3a2bSChandler Carruth 
8597adc3a2bSChandler Carruth     disableSROA(CostIt);
8607adc3a2bSChandler Carruth   }
8617adc3a2bSChandler Carruth 
8627adc3a2bSChandler Carruth   return false;
8637adc3a2bSChandler Carruth }
8647adc3a2bSChandler Carruth 
8657adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
8667adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
867617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
868617f6364SEaswaran Raman         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
869617f6364SEaswaran Raman       }))
8707adc3a2bSChandler Carruth     return true;
8717adc3a2bSChandler Carruth 
8727adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
8737adc3a2bSChandler Carruth   return false;
8747adc3a2bSChandler Carruth }
8757adc3a2bSChandler Carruth 
8767adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
8777adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
878617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
879617f6364SEaswaran Raman         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
880617f6364SEaswaran Raman                                             /*InsertedValueOperand*/ COps[1],
881617f6364SEaswaran Raman                                             I.getIndices());
882617f6364SEaswaran Raman       }))
8837adc3a2bSChandler Carruth     return true;
8847adc3a2bSChandler Carruth 
8857adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
8867adc3a2bSChandler Carruth   return false;
8877adc3a2bSChandler Carruth }
8887adc3a2bSChandler Carruth 
8897adc3a2bSChandler Carruth /// \brief Try to simplify a call site.
8907adc3a2bSChandler Carruth ///
8917adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
8927adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
8937adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
8947adc3a2bSChandler Carruth /// free.
8957adc3a2bSChandler Carruth bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
8967adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
8977adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
8987adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
8997adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
900647025f9SAndrew Kaylor   if (!canConstantFoldCallTo(CS, F))
9017adc3a2bSChandler Carruth     return false;
9027adc3a2bSChandler Carruth 
9037adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
9047adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
9057adc3a2bSChandler Carruth   ConstantArgs.reserve(CS.arg_size());
906567556aaSChad Rosier   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E;
907567556aaSChad Rosier        ++I) {
9087adc3a2bSChandler Carruth     Constant *C = dyn_cast<Constant>(*I);
9097adc3a2bSChandler Carruth     if (!C)
9107adc3a2bSChandler Carruth       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
9117adc3a2bSChandler Carruth     if (!C)
9127adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
9137adc3a2bSChandler Carruth 
9147adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
9157adc3a2bSChandler Carruth   }
916647025f9SAndrew Kaylor   if (Constant *C = ConstantFoldCall(CS, F, ConstantArgs)) {
9177adc3a2bSChandler Carruth     SimplifiedValues[CS.getInstruction()] = C;
9187adc3a2bSChandler Carruth     return true;
9197adc3a2bSChandler Carruth   }
9207adc3a2bSChandler Carruth 
9217adc3a2bSChandler Carruth   return false;
9227adc3a2bSChandler Carruth }
9237adc3a2bSChandler Carruth 
9247adc3a2bSChandler Carruth bool CallAnalyzer::visitCallSite(CallSite CS) {
9257adc3a2bSChandler Carruth   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
9267adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
9277adc3a2bSChandler Carruth     // This aborts the entire analysis.
9287adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
9297adc3a2bSChandler Carruth     return false;
9307adc3a2bSChandler Carruth   }
931567556aaSChad Rosier   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->cannotDuplicate())
9327adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
9337adc3a2bSChandler Carruth 
9347adc3a2bSChandler Carruth   if (Function *F = CS.getCalledFunction()) {
9357adc3a2bSChandler Carruth     // When we have a concrete function, first try to simplify it directly.
9367adc3a2bSChandler Carruth     if (simplifyCallSite(F, CS))
9377adc3a2bSChandler Carruth       return true;
9387adc3a2bSChandler Carruth 
9397adc3a2bSChandler Carruth     // Next check if it is an intrinsic we know about.
9407adc3a2bSChandler Carruth     // FIXME: Lift this into part of the InstVisitor.
9417adc3a2bSChandler Carruth     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
9427adc3a2bSChandler Carruth       switch (II->getIntrinsicID()) {
9437adc3a2bSChandler Carruth       default:
9447adc3a2bSChandler Carruth         return Base::visitCallSite(CS);
9457adc3a2bSChandler Carruth 
9467dd8dbf4SPeter Collingbourne       case Intrinsic::load_relative:
9477dd8dbf4SPeter Collingbourne         // This is normally lowered to 4 LLVM instructions.
9487dd8dbf4SPeter Collingbourne         Cost += 3 * InlineConstants::InstrCost;
9497dd8dbf4SPeter Collingbourne         return false;
9507dd8dbf4SPeter Collingbourne 
9517adc3a2bSChandler Carruth       case Intrinsic::memset:
9527adc3a2bSChandler Carruth       case Intrinsic::memcpy:
9537adc3a2bSChandler Carruth       case Intrinsic::memmove:
9547adc3a2bSChandler Carruth         // SROA can usually chew through these intrinsics, but they aren't free.
9557adc3a2bSChandler Carruth         return false;
9567adc3a2bSChandler Carruth       case Intrinsic::localescape:
9577adc3a2bSChandler Carruth         HasFrameEscape = true;
9587adc3a2bSChandler Carruth         return false;
9597adc3a2bSChandler Carruth       }
9607adc3a2bSChandler Carruth     }
9617adc3a2bSChandler Carruth 
9627adc3a2bSChandler Carruth     if (F == CS.getInstruction()->getParent()->getParent()) {
9637adc3a2bSChandler Carruth       // This flag will fully abort the analysis, so don't bother with anything
9647adc3a2bSChandler Carruth       // else.
9657adc3a2bSChandler Carruth       IsRecursiveCall = true;
9667adc3a2bSChandler Carruth       return false;
9677adc3a2bSChandler Carruth     }
9687adc3a2bSChandler Carruth 
9697adc3a2bSChandler Carruth     if (TTI.isLoweredToCall(F)) {
9707adc3a2bSChandler Carruth       // We account for the average 1 instruction per call argument setup
9717adc3a2bSChandler Carruth       // here.
9727adc3a2bSChandler Carruth       Cost += CS.arg_size() * InlineConstants::InstrCost;
9737adc3a2bSChandler Carruth 
9747adc3a2bSChandler Carruth       // Everything other than inline ASM will also have a significant cost
9757adc3a2bSChandler Carruth       // merely from making the call.
9767adc3a2bSChandler Carruth       if (!isa<InlineAsm>(CS.getCalledValue()))
9777adc3a2bSChandler Carruth         Cost += InlineConstants::CallPenalty;
9787adc3a2bSChandler Carruth     }
9797adc3a2bSChandler Carruth 
9807adc3a2bSChandler Carruth     return Base::visitCallSite(CS);
9817adc3a2bSChandler Carruth   }
9827adc3a2bSChandler Carruth 
9837adc3a2bSChandler Carruth   // Otherwise we're in a very special case -- an indirect function call. See
9847adc3a2bSChandler Carruth   // if we can be particularly clever about this.
9857adc3a2bSChandler Carruth   Value *Callee = CS.getCalledValue();
9867adc3a2bSChandler Carruth 
9877adc3a2bSChandler Carruth   // First, pay the price of the argument setup. We account for the average
9887adc3a2bSChandler Carruth   // 1 instruction per call argument setup here.
9897adc3a2bSChandler Carruth   Cost += CS.arg_size() * InlineConstants::InstrCost;
9907adc3a2bSChandler Carruth 
9917adc3a2bSChandler Carruth   // Next, check if this happens to be an indirect function call to a known
9927adc3a2bSChandler Carruth   // function in this inline context. If not, we've done all we can.
9937adc3a2bSChandler Carruth   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
9947adc3a2bSChandler Carruth   if (!F)
9957adc3a2bSChandler Carruth     return Base::visitCallSite(CS);
9967adc3a2bSChandler Carruth 
9977adc3a2bSChandler Carruth   // If we have a constant that we are calling as a function, we can peer
9987adc3a2bSChandler Carruth   // through it and see the function target. This happens not infrequently
9997adc3a2bSChandler Carruth   // during devirtualization and so we want to give it a hefty bonus for
10007adc3a2bSChandler Carruth   // inlining, but cap that bonus in the event that inlining wouldn't pan
10017adc3a2bSChandler Carruth   // out. Pretend to inline the function, with a custom threshold.
10021c57cc2bSEaswaran Raman   auto IndirectCallParams = Params;
10031c57cc2bSEaswaran Raman   IndirectCallParams.DefaultThreshold = InlineConstants::IndirectCallThreshold;
100412585b01SEaswaran Raman   CallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, *F, CS,
100512585b01SEaswaran Raman                   IndirectCallParams);
10067adc3a2bSChandler Carruth   if (CA.analyzeCall(CS)) {
10077adc3a2bSChandler Carruth     // We were able to inline the indirect call! Subtract the cost from the
10086d90d9f1SEaswaran Raman     // threshold to get the bonus we want to apply, but don't go below zero.
10096d90d9f1SEaswaran Raman     Cost -= std::max(0, CA.getThreshold() - CA.getCost());
10107adc3a2bSChandler Carruth   }
10117adc3a2bSChandler Carruth 
10127adc3a2bSChandler Carruth   return Base::visitCallSite(CS);
10137adc3a2bSChandler Carruth }
10147adc3a2bSChandler Carruth 
10157adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
10167adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
10177adc3a2bSChandler Carruth   bool Free = !HasReturn;
10187adc3a2bSChandler Carruth   HasReturn = true;
10197adc3a2bSChandler Carruth   return Free;
10207adc3a2bSChandler Carruth }
10217adc3a2bSChandler Carruth 
10227adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
10237adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
10247adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
10257adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
10267adc3a2bSChandler Carruth   // which will fold away are also free.
10277adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
10287adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
10297adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
10307adc3a2bSChandler Carruth }
10317adc3a2bSChandler Carruth 
10327adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
10337adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
10347adc3a2bSChandler Carruth   // branches.
10357adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
10367adc3a2bSChandler Carruth     return true;
10377adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
10387adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
10397adc3a2bSChandler Carruth       return true;
10407adc3a2bSChandler Carruth 
10417ad02eeeSEric Christopher   // Assume the most general case where the switch is lowered into
1042919f9e8dSJun Bum Lim   // either a jump table, bit test, or a balanced binary tree consisting of
1043919f9e8dSJun Bum Lim   // case clusters without merging adjacent clusters with the same
1044919f9e8dSJun Bum Lim   // destination. We do not consider the switches that are lowered with a mix
1045919f9e8dSJun Bum Lim   // of jump table/bit test/binary search tree. The cost of the switch is
1046919f9e8dSJun Bum Lim   // proportional to the size of the tree or the size of jump table range.
10472960d41eSJun Bum Lim   //
10482960d41eSJun Bum Lim   // NB: We convert large switches which are just used to initialize large phi
10492960d41eSJun Bum Lim   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
10502960d41eSJun Bum Lim   // inlining those. It will prevent inlining in cases where the optimization
10512960d41eSJun Bum Lim   // does not (yet) fire.
1052919f9e8dSJun Bum Lim 
1053506cfb7aSJun Bum Lim   // Maximum valid cost increased in this function.
1054506cfb7aSJun Bum Lim   int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
1055506cfb7aSJun Bum Lim 
1056919f9e8dSJun Bum Lim   // Exit early for a large switch, assuming one case needs at least one
1057919f9e8dSJun Bum Lim   // instruction.
1058919f9e8dSJun Bum Lim   // FIXME: This is not true for a bit test, but ignore such case for now to
1059919f9e8dSJun Bum Lim   // save compile-time.
1060919f9e8dSJun Bum Lim   int64_t CostLowerBound =
1061506cfb7aSJun Bum Lim       std::min((int64_t)CostUpperBound,
1062919f9e8dSJun Bum Lim                (int64_t)SI.getNumCases() * InlineConstants::InstrCost + Cost);
1063919f9e8dSJun Bum Lim 
1064919f9e8dSJun Bum Lim   if (CostLowerBound > Threshold) {
1065919f9e8dSJun Bum Lim     Cost = CostLowerBound;
1066919f9e8dSJun Bum Lim     return false;
1067919f9e8dSJun Bum Lim   }
1068919f9e8dSJun Bum Lim 
1069919f9e8dSJun Bum Lim   unsigned JumpTableSize = 0;
1070919f9e8dSJun Bum Lim   unsigned NumCaseCluster =
1071919f9e8dSJun Bum Lim       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize);
1072919f9e8dSJun Bum Lim 
1073919f9e8dSJun Bum Lim   // If suitable for a jump table, consider the cost for the table size and
1074919f9e8dSJun Bum Lim   // branch to destination.
1075919f9e8dSJun Bum Lim   if (JumpTableSize) {
1076919f9e8dSJun Bum Lim     int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
1077919f9e8dSJun Bum Lim                      4 * InlineConstants::InstrCost;
1078506cfb7aSJun Bum Lim 
1079506cfb7aSJun Bum Lim     Cost = std::min((int64_t)CostUpperBound, JTCost + Cost);
1080919f9e8dSJun Bum Lim     return false;
1081919f9e8dSJun Bum Lim   }
1082919f9e8dSJun Bum Lim 
1083919f9e8dSJun Bum Lim   // Considering forming a binary search, we should find the number of nodes
1084919f9e8dSJun Bum Lim   // which is same as the number of comparisons when lowered. For a given
1085919f9e8dSJun Bum Lim   // number of clusters, n, we can define a recursive function, f(n), to find
1086919f9e8dSJun Bum Lim   // the number of nodes in the tree. The recursion is :
1087919f9e8dSJun Bum Lim   // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
1088919f9e8dSJun Bum Lim   // and f(n) = n, when n <= 3.
1089919f9e8dSJun Bum Lim   // This will lead a binary tree where the leaf should be either f(2) or f(3)
1090919f9e8dSJun Bum Lim   // when n > 3.  So, the number of comparisons from leaves should be n, while
1091919f9e8dSJun Bum Lim   // the number of non-leaf should be :
1092919f9e8dSJun Bum Lim   //   2^(log2(n) - 1) - 1
1093919f9e8dSJun Bum Lim   //   = 2^log2(n) * 2^-1 - 1
1094919f9e8dSJun Bum Lim   //   = n / 2 - 1.
1095919f9e8dSJun Bum Lim   // Considering comparisons from leaf and non-leaf nodes, we can estimate the
1096919f9e8dSJun Bum Lim   // number of comparisons in a simple closed form :
1097919f9e8dSJun Bum Lim   //   n + n / 2 - 1 = n * 3 / 2 - 1
1098919f9e8dSJun Bum Lim   if (NumCaseCluster <= 3) {
1099919f9e8dSJun Bum Lim     // Suppose a comparison includes one compare and one conditional branch.
1100919f9e8dSJun Bum Lim     Cost += NumCaseCluster * 2 * InlineConstants::InstrCost;
1101919f9e8dSJun Bum Lim     return false;
1102919f9e8dSJun Bum Lim   }
1103506cfb7aSJun Bum Lim 
1104506cfb7aSJun Bum Lim   int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1;
1105506cfb7aSJun Bum Lim   int64_t SwitchCost =
1106919f9e8dSJun Bum Lim       ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
1107506cfb7aSJun Bum Lim 
1108506cfb7aSJun Bum Lim   Cost = std::min((int64_t)CostUpperBound, SwitchCost + Cost);
1109919f9e8dSJun Bum Lim   return false;
1110919f9e8dSJun Bum Lim }
1111919f9e8dSJun Bum Lim 
11127adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
11137adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
11147adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
11157adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
11167adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
11177adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
11187adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
11197adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
11207adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
11217adc3a2bSChandler Carruth   HasIndirectBr = true;
11227adc3a2bSChandler Carruth   return false;
11237adc3a2bSChandler Carruth }
11247adc3a2bSChandler Carruth 
11257adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
11267adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
11277adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
11287adc3a2bSChandler Carruth   return false;
11297adc3a2bSChandler Carruth }
11307adc3a2bSChandler Carruth 
11317adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
11327adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
11337adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
11347adc3a2bSChandler Carruth   return false;
11357adc3a2bSChandler Carruth }
11367adc3a2bSChandler Carruth 
11377adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
11387adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
11398220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
11407adc3a2bSChandler Carruth   return false;
11417adc3a2bSChandler Carruth }
11427adc3a2bSChandler Carruth 
11437adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
11447adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
11457adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
11467adc3a2bSChandler Carruth   // code size.
11477adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
11487adc3a2bSChandler Carruth }
11497adc3a2bSChandler Carruth 
11507adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
11517adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
11527adc3a2bSChandler Carruth   // handled by SROA, etc.
11537adc3a2bSChandler Carruth   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
11547adc3a2bSChandler Carruth     return true;
11557adc3a2bSChandler Carruth 
11567adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
11577adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
11587adc3a2bSChandler Carruth   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
11597adc3a2bSChandler Carruth     disableSROA(*OI);
11607adc3a2bSChandler Carruth 
11617adc3a2bSChandler Carruth   return false;
11627adc3a2bSChandler Carruth }
11637adc3a2bSChandler Carruth 
11647adc3a2bSChandler Carruth /// \brief Analyze a basic block for its contribution to the inline cost.
11657adc3a2bSChandler Carruth ///
11667adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
11677adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
11687adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
11697adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
11707adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
11717adc3a2bSChandler Carruth bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
11727adc3a2bSChandler Carruth                                 SmallPtrSetImpl<const Value *> &EphValues) {
11737adc3a2bSChandler Carruth   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
11747adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
11757adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
11767adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
11777adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
11787adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
11797adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
11807adc3a2bSChandler Carruth     // hack around it here.
11817adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
11827adc3a2bSChandler Carruth       continue;
11837adc3a2bSChandler Carruth 
11847adc3a2bSChandler Carruth     // Skip ephemeral values.
11855a82c916SDuncan P. N. Exon Smith     if (EphValues.count(&*I))
11867adc3a2bSChandler Carruth       continue;
11877adc3a2bSChandler Carruth 
11887adc3a2bSChandler Carruth     ++NumInstructions;
11897adc3a2bSChandler Carruth     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
11907adc3a2bSChandler Carruth       ++NumVectorInstructions;
11917adc3a2bSChandler Carruth 
1192e9434e80SSanjay Patel     // If the instruction is floating point, and the target says this operation
1193e9434e80SSanjay Patel     // is expensive or the function has the "use-soft-float" attribute, this may
11947adc3a2bSChandler Carruth     // eventually become a library call. Treat the cost as such.
11957adc3a2bSChandler Carruth     if (I->getType()->isFloatingPointTy()) {
1196e9434e80SSanjay Patel       // If the function has the "use-soft-float" attribute, mark it as
1197e9434e80SSanjay Patel       // expensive.
11987adc3a2bSChandler Carruth       if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
1199908ed7f2SEric Christopher           (F.getFnAttribute("use-soft-float").getValueAsString() == "true"))
12007adc3a2bSChandler Carruth         Cost += InlineConstants::CallPenalty;
12017adc3a2bSChandler Carruth     }
12027adc3a2bSChandler Carruth 
12037adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
12047adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
12057adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
12067adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
12077adc3a2bSChandler Carruth     // cost should count against inlining.
12085a82c916SDuncan P. N. Exon Smith     if (Base::visit(&*I))
12097adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
12107adc3a2bSChandler Carruth     else
12117adc3a2bSChandler Carruth       Cost += InlineConstants::InstrCost;
12127adc3a2bSChandler Carruth 
12137adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
12147adc3a2bSChandler Carruth     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
12157adc3a2bSChandler Carruth         HasIndirectBr || HasFrameEscape)
12167adc3a2bSChandler Carruth       return false;
12177adc3a2bSChandler Carruth 
12187adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
12197adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
12207adc3a2bSChandler Carruth     // the caller stack usage dramatically.
12217adc3a2bSChandler Carruth     if (IsCallerRecursive &&
12227adc3a2bSChandler Carruth         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
12237adc3a2bSChandler Carruth       return false;
12247adc3a2bSChandler Carruth 
12257adc3a2bSChandler Carruth     // Check if we've past the maximum possible threshold so we don't spin in
12267adc3a2bSChandler Carruth     // huge basic blocks that will never inline.
12277adc3a2bSChandler Carruth     if (Cost > Threshold)
12287adc3a2bSChandler Carruth       return false;
12297adc3a2bSChandler Carruth   }
12307adc3a2bSChandler Carruth 
12317adc3a2bSChandler Carruth   return true;
12327adc3a2bSChandler Carruth }
12337adc3a2bSChandler Carruth 
12347adc3a2bSChandler Carruth /// \brief Compute the base pointer and cumulative constant offsets for V.
12357adc3a2bSChandler Carruth ///
12367adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
12377adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
12387adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
12397adc3a2bSChandler Carruth /// no constant offsets applied.
12407adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
12417adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
12427adc3a2bSChandler Carruth     return nullptr;
12437adc3a2bSChandler Carruth 
12447adc3a2bSChandler Carruth   unsigned IntPtrWidth = DL.getPointerSizeInBits();
12457adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
12467adc3a2bSChandler Carruth 
12477adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
12487adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
12497adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
12507adc3a2bSChandler Carruth   Visited.insert(V);
12517adc3a2bSChandler Carruth   do {
12527adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
12537adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
12547adc3a2bSChandler Carruth         return nullptr;
12557adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
12567adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
12577adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
12587adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
12595ce32728SSanjoy Das       if (GA->isInterposable())
12607adc3a2bSChandler Carruth         break;
12617adc3a2bSChandler Carruth       V = GA->getAliasee();
12627adc3a2bSChandler Carruth     } else {
12637adc3a2bSChandler Carruth       break;
12647adc3a2bSChandler Carruth     }
12657adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
12667adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
12677adc3a2bSChandler Carruth 
12687adc3a2bSChandler Carruth   Type *IntPtrTy = DL.getIntPtrType(V->getContext());
12697adc3a2bSChandler Carruth   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
12707adc3a2bSChandler Carruth }
12717adc3a2bSChandler Carruth 
12727adc3a2bSChandler Carruth /// \brief Analyze a call site for potential inlining.
12737adc3a2bSChandler Carruth ///
12747adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
12757adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
12767adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
12777adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
12787adc3a2bSChandler Carruth /// some artifact of the routine.
12797adc3a2bSChandler Carruth bool CallAnalyzer::analyzeCall(CallSite CS) {
12807adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
12817adc3a2bSChandler Carruth 
12827adc3a2bSChandler Carruth   // Perform some tweaks to the cost and threshold based on the direct
12837adc3a2bSChandler Carruth   // callsite information.
12847adc3a2bSChandler Carruth 
12857adc3a2bSChandler Carruth   // We want to more aggressively inline vector-dense kernels, so up the
12867adc3a2bSChandler Carruth   // threshold, and we'll lower it if the % of vector instructions gets too
12877adc3a2bSChandler Carruth   // low. Note that these bonuses are some what arbitrary and evolved over time
12887adc3a2bSChandler Carruth   // by accident as much as because they are principled bonuses.
12897adc3a2bSChandler Carruth   //
12907adc3a2bSChandler Carruth   // FIXME: It would be nice to remove all such bonuses. At least it would be
12917adc3a2bSChandler Carruth   // nice to base the bonus values on something more scientific.
12927adc3a2bSChandler Carruth   assert(NumInstructions == 0);
12937adc3a2bSChandler Carruth   assert(NumVectorInstructions == 0);
1294f4bb2f0dSEaswaran Raman 
1295f4bb2f0dSEaswaran Raman   // Update the threshold based on callsite properties
1296f4bb2f0dSEaswaran Raman   updateThreshold(CS, F);
1297f4bb2f0dSEaswaran Raman 
12987adc3a2bSChandler Carruth   FiftyPercentVectorBonus = 3 * Threshold / 2;
12997adc3a2bSChandler Carruth   TenPercentVectorBonus = 3 * Threshold / 4;
13007adc3a2bSChandler Carruth 
13017adc3a2bSChandler Carruth   // Track whether the post-inlining function would have more than one basic
13027adc3a2bSChandler Carruth   // block. A single basic block is often intended for inlining. Balloon the
13037adc3a2bSChandler Carruth   // threshold by 50% until we pass the single-BB phase.
13047adc3a2bSChandler Carruth   bool SingleBB = true;
13057adc3a2bSChandler Carruth   int SingleBBBonus = Threshold / 2;
13067adc3a2bSChandler Carruth 
13077adc3a2bSChandler Carruth   // Speculatively apply all possible bonuses to Threshold. If cost exceeds
13087adc3a2bSChandler Carruth   // this Threshold any time, and cost cannot decrease, we can stop processing
13097adc3a2bSChandler Carruth   // the rest of the function body.
13107adc3a2bSChandler Carruth   Threshold += (SingleBBBonus + FiftyPercentVectorBonus);
13117adc3a2bSChandler Carruth 
1312351d9b01SXinliang David Li   // Give out bonuses for the callsite, as the instructions setting them up
1313351d9b01SXinliang David Li   // will be gone after inlining.
1314351d9b01SXinliang David Li   Cost -= getCallsiteCost(CS, DL);
13157adc3a2bSChandler Carruth 
13167adc3a2bSChandler Carruth   // If there is only one call of the function, and it has internal linkage,
13177adc3a2bSChandler Carruth   // the cost of inlining it drops dramatically.
1318567556aaSChad Rosier   bool OnlyOneCallAndLocalLinkage =
1319567556aaSChad Rosier       F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction();
13207adc3a2bSChandler Carruth   if (OnlyOneCallAndLocalLinkage)
1321d89875caSPiotr Padlewski     Cost -= InlineConstants::LastCallToStaticBonus;
13227adc3a2bSChandler Carruth 
13237adc3a2bSChandler Carruth   // If this function uses the coldcc calling convention, prefer not to inline
13247adc3a2bSChandler Carruth   // it.
13257adc3a2bSChandler Carruth   if (F.getCallingConv() == CallingConv::Cold)
13267adc3a2bSChandler Carruth     Cost += InlineConstants::ColdccPenalty;
13277adc3a2bSChandler Carruth 
13287adc3a2bSChandler Carruth   // Check if we're done. This can happen due to bonuses and penalties.
13297adc3a2bSChandler Carruth   if (Cost > Threshold)
13307adc3a2bSChandler Carruth     return false;
13317adc3a2bSChandler Carruth 
13327adc3a2bSChandler Carruth   if (F.empty())
13337adc3a2bSChandler Carruth     return true;
13347adc3a2bSChandler Carruth 
13357adc3a2bSChandler Carruth   Function *Caller = CS.getInstruction()->getParent()->getParent();
13367adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
13377adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
13387adc3a2bSChandler Carruth     CallSite Site(U);
13397adc3a2bSChandler Carruth     if (!Site)
13407adc3a2bSChandler Carruth       continue;
13417adc3a2bSChandler Carruth     Instruction *I = Site.getInstruction();
13427adc3a2bSChandler Carruth     if (I->getParent()->getParent() == Caller) {
13437adc3a2bSChandler Carruth       IsCallerRecursive = true;
13447adc3a2bSChandler Carruth       break;
13457adc3a2bSChandler Carruth     }
13467adc3a2bSChandler Carruth   }
13477adc3a2bSChandler Carruth 
13487adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
13497adc3a2bSChandler Carruth   // arguments with known important simplifications.
13507adc3a2bSChandler Carruth   CallSite::arg_iterator CAI = CS.arg_begin();
13517adc3a2bSChandler Carruth   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
13527adc3a2bSChandler Carruth        FAI != FAE; ++FAI, ++CAI) {
13537adc3a2bSChandler Carruth     assert(CAI != CS.arg_end());
13547adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
13555a82c916SDuncan P. N. Exon Smith       SimplifiedValues[&*FAI] = C;
13567adc3a2bSChandler Carruth 
13577adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
13587adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
13595a82c916SDuncan P. N. Exon Smith       ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
13607adc3a2bSChandler Carruth 
13617adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
13627adc3a2bSChandler Carruth       if (isa<AllocaInst>(PtrArg)) {
13635a82c916SDuncan P. N. Exon Smith         SROAArgValues[&*FAI] = PtrArg;
13647adc3a2bSChandler Carruth         SROAArgCosts[PtrArg] = 0;
13657adc3a2bSChandler Carruth       }
13667adc3a2bSChandler Carruth     }
13677adc3a2bSChandler Carruth   }
13687adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
13697adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
13707adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
13717adc3a2bSChandler Carruth 
13727adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
13737adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
13747adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
13757adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
1376aec2fa35SDaniel Jasper   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
13777adc3a2bSChandler Carruth 
13787adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
13797adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
13807adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
13817adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
13827adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
13837adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
13847adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
13857adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1386567556aaSChad Rosier                     SmallPtrSet<BasicBlock *, 16>>
1387567556aaSChad Rosier       BBSetVector;
13887adc3a2bSChandler Carruth   BBSetVector BBWorklist;
13897adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
13907adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
13917adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
13927adc3a2bSChandler Carruth     // Bail out the moment we cross the threshold. This means we'll under-count
13937adc3a2bSChandler Carruth     // the cost, but only when undercounting doesn't matter.
13947adc3a2bSChandler Carruth     if (Cost > Threshold)
13957adc3a2bSChandler Carruth       break;
13967adc3a2bSChandler Carruth 
13977adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
13987adc3a2bSChandler Carruth     if (BB->empty())
13997adc3a2bSChandler Carruth       continue;
14007adc3a2bSChandler Carruth 
14017adc3a2bSChandler Carruth     // Disallow inlining a blockaddress. A blockaddress only has defined
14027adc3a2bSChandler Carruth     // behavior for an indirect branch in the same function, and we do not
14037adc3a2bSChandler Carruth     // currently support inlining indirect branches. But, the inliner may not
14047adc3a2bSChandler Carruth     // see an indirect branch that ends up being dead code at a particular call
14057adc3a2bSChandler Carruth     // site. If the blockaddress escapes the function, e.g., via a global
14067adc3a2bSChandler Carruth     // variable, inlining may lead to an invalid cross-function reference.
14077adc3a2bSChandler Carruth     if (BB->hasAddressTaken())
14087adc3a2bSChandler Carruth       return false;
14097adc3a2bSChandler Carruth 
14107adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
14117adc3a2bSChandler Carruth     // returns false, and we can bail on out.
1412d295b00aSEaswaran Raman     if (!analyzeBlock(BB, EphValues))
14137adc3a2bSChandler Carruth       return false;
14147adc3a2bSChandler Carruth 
14157adc3a2bSChandler Carruth     TerminatorInst *TI = BB->getTerminator();
14167adc3a2bSChandler Carruth 
14177adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
14187adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
14197adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
14207adc3a2bSChandler Carruth       if (BI->isConditional()) {
14217adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
1422567556aaSChad Rosier         if (ConstantInt *SimpleCond =
1423567556aaSChad Rosier                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
14247adc3a2bSChandler Carruth           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
14257adc3a2bSChandler Carruth           continue;
14267adc3a2bSChandler Carruth         }
14277adc3a2bSChandler Carruth       }
14287adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
14297adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
1430567556aaSChad Rosier       if (ConstantInt *SimpleCond =
1431567556aaSChad Rosier               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1432927d8e61SChandler Carruth         BBWorklist.insert(SI->findCaseValue(SimpleCond)->getCaseSuccessor());
14337adc3a2bSChandler Carruth         continue;
14347adc3a2bSChandler Carruth       }
14357adc3a2bSChandler Carruth     }
14367adc3a2bSChandler Carruth 
14377adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
14387adc3a2bSChandler Carruth     // them.
14397adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
14407adc3a2bSChandler Carruth          ++TIdx)
14417adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
14427adc3a2bSChandler Carruth 
14437adc3a2bSChandler Carruth     // If we had any successors at this point, than post-inlining is likely to
14447adc3a2bSChandler Carruth     // have them as well. Note that we assume any basic blocks which existed
14457adc3a2bSChandler Carruth     // due to branches or switches which folded above will also fold after
14467adc3a2bSChandler Carruth     // inlining.
14477adc3a2bSChandler Carruth     if (SingleBB && TI->getNumSuccessors() > 1) {
14487adc3a2bSChandler Carruth       // Take off the bonus we applied to the threshold.
14497adc3a2bSChandler Carruth       Threshold -= SingleBBBonus;
14507adc3a2bSChandler Carruth       SingleBB = false;
14517adc3a2bSChandler Carruth     }
14527adc3a2bSChandler Carruth   }
14537adc3a2bSChandler Carruth 
14547adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
14557adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
14567adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
14577adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
14587adc3a2bSChandler Carruth     return false;
14597adc3a2bSChandler Carruth 
14607adc3a2bSChandler Carruth   // We applied the maximum possible vector bonus at the beginning. Now,
14617adc3a2bSChandler Carruth   // subtract the excess bonus, if any, from the Threshold before
14627adc3a2bSChandler Carruth   // comparing against Cost.
14637adc3a2bSChandler Carruth   if (NumVectorInstructions <= NumInstructions / 10)
14647adc3a2bSChandler Carruth     Threshold -= FiftyPercentVectorBonus;
14657adc3a2bSChandler Carruth   else if (NumVectorInstructions <= NumInstructions / 2)
14667adc3a2bSChandler Carruth     Threshold -= (FiftyPercentVectorBonus - TenPercentVectorBonus);
14677adc3a2bSChandler Carruth 
146800ab73dcSHans Wennborg   return Cost < std::max(1, Threshold);
14697adc3a2bSChandler Carruth }
14707adc3a2bSChandler Carruth 
14717adc3a2bSChandler Carruth #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
14727adc3a2bSChandler Carruth /// \brief Dump stats about this call's analysis.
1473eb2a2546SYaron Keren LLVM_DUMP_METHOD void CallAnalyzer::dump() {
14747adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
14757adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
14767adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
14777adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
14787adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
14797adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
14807adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
14817adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
14827adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
14837adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
14847adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
14857adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
14867adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
14877adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
14887adc3a2bSChandler Carruth }
14897adc3a2bSChandler Carruth #endif
14907adc3a2bSChandler Carruth 
14917adc3a2bSChandler Carruth /// \brief Test that there are no attribute conflicts between Caller and Callee
14927adc3a2bSChandler Carruth ///        that prevent inlining.
14937adc3a2bSChandler Carruth static bool functionsHaveCompatibleAttributes(Function *Caller,
14947adc3a2bSChandler Carruth                                               Function *Callee,
14957adc3a2bSChandler Carruth                                               TargetTransformInfo &TTI) {
14967adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
14971cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
14987adc3a2bSChandler Carruth }
14997adc3a2bSChandler Carruth 
1500351d9b01SXinliang David Li int llvm::getCallsiteCost(CallSite CS, const DataLayout &DL) {
1501351d9b01SXinliang David Li   int Cost = 0;
1502351d9b01SXinliang David Li   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
1503351d9b01SXinliang David Li     if (CS.isByValArgument(I)) {
1504351d9b01SXinliang David Li       // We approximate the number of loads and stores needed by dividing the
1505351d9b01SXinliang David Li       // size of the byval type by the target's pointer size.
1506351d9b01SXinliang David Li       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
1507351d9b01SXinliang David Li       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
1508351d9b01SXinliang David Li       unsigned PointerSize = DL.getPointerSizeInBits();
1509351d9b01SXinliang David Li       // Ceiling division.
1510351d9b01SXinliang David Li       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
1511351d9b01SXinliang David Li 
1512351d9b01SXinliang David Li       // If it generates more than 8 stores it is likely to be expanded as an
1513351d9b01SXinliang David Li       // inline memcpy so we take that as an upper bound. Otherwise we assume
1514351d9b01SXinliang David Li       // one load and one store per word copied.
1515351d9b01SXinliang David Li       // FIXME: The maxStoresPerMemcpy setting from the target should be used
1516351d9b01SXinliang David Li       // here instead of a magic number of 8, but it's not available via
1517351d9b01SXinliang David Li       // DataLayout.
1518351d9b01SXinliang David Li       NumStores = std::min(NumStores, 8U);
1519351d9b01SXinliang David Li 
1520351d9b01SXinliang David Li       Cost += 2 * NumStores * InlineConstants::InstrCost;
1521351d9b01SXinliang David Li     } else {
1522351d9b01SXinliang David Li       // For non-byval arguments subtract off one instruction per call
1523351d9b01SXinliang David Li       // argument.
1524351d9b01SXinliang David Li       Cost += InlineConstants::InstrCost;
1525351d9b01SXinliang David Li     }
1526351d9b01SXinliang David Li   }
1527351d9b01SXinliang David Li   // The call instruction also disappears after inlining.
1528351d9b01SXinliang David Li   Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty;
1529351d9b01SXinliang David Li   return Cost;
1530351d9b01SXinliang David Li }
1531351d9b01SXinliang David Li 
1532ab6a6837SSean Silva InlineCost llvm::getInlineCost(
15331c57cc2bSEaswaran Raman     CallSite CS, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
1534aec2fa35SDaniel Jasper     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
153512585b01SEaswaran Raman     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
153671069cf6SEaswaran Raman     ProfileSummaryInfo *PSI) {
1537aec2fa35SDaniel Jasper   return getInlineCost(CS, CS.getCalledFunction(), Params, CalleeTTI,
153812585b01SEaswaran Raman                        GetAssumptionCache, GetBFI, PSI);
1539b9f7120eSEaswaran Raman }
1540b9f7120eSEaswaran Raman 
1541ab6a6837SSean Silva InlineCost llvm::getInlineCost(
15421c57cc2bSEaswaran Raman     CallSite CS, Function *Callee, const InlineParams &Params,
1543aec2fa35SDaniel Jasper     TargetTransformInfo &CalleeTTI,
1544aec2fa35SDaniel Jasper     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
154512585b01SEaswaran Raman     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
1546aec2fa35SDaniel Jasper     ProfileSummaryInfo *PSI) {
1547f4bb2f0dSEaswaran Raman 
15487adc3a2bSChandler Carruth   // Cannot inline indirect calls.
15497adc3a2bSChandler Carruth   if (!Callee)
15507adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
15517adc3a2bSChandler Carruth 
15527adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
15537adc3a2bSChandler Carruth   // whenever possible.
15547adc3a2bSChandler Carruth   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
15557adc3a2bSChandler Carruth     if (isInlineViable(*Callee))
15567adc3a2bSChandler Carruth       return llvm::InlineCost::getAlways();
15577adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
15587adc3a2bSChandler Carruth   }
15597adc3a2bSChandler Carruth 
15607adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
15617adc3a2bSChandler Carruth   // always-inline attribute).
1562b9f7120eSEaswaran Raman   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee, CalleeTTI))
15637adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
15647adc3a2bSChandler Carruth 
15657adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
15667adc3a2bSChandler Carruth   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
15677adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
15687adc3a2bSChandler Carruth 
15695ce32728SSanjoy Das   // Don't inline functions which can be interposed at link-time.  Don't inline
15705ce32728SSanjoy Das   // functions marked noinline or call sites marked noinline.
1571107b187dSCraig Topper   // Note: inlining non-exact non-interposable functions is fine, since we know
15725ce32728SSanjoy Das   // we have *a* correct implementation of the source level function.
1573567556aaSChad Rosier   if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
1574567556aaSChad Rosier       CS.isNoInline())
15757adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
15767adc3a2bSChandler Carruth 
15777adc3a2bSChandler Carruth   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
15787adc3a2bSChandler Carruth                      << "...\n");
15797adc3a2bSChandler Carruth 
158012585b01SEaswaran Raman   CallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, *Callee, CS,
158112585b01SEaswaran Raman                   Params);
15827adc3a2bSChandler Carruth   bool ShouldInline = CA.analyzeCall(CS);
15837adc3a2bSChandler Carruth 
15847adc3a2bSChandler Carruth   DEBUG(CA.dump());
15857adc3a2bSChandler Carruth 
15867adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
15877adc3a2bSChandler Carruth   if (!ShouldInline && CA.getCost() < CA.getThreshold())
15887adc3a2bSChandler Carruth     return InlineCost::getNever();
15897adc3a2bSChandler Carruth   if (ShouldInline && CA.getCost() >= CA.getThreshold())
15907adc3a2bSChandler Carruth     return InlineCost::getAlways();
15917adc3a2bSChandler Carruth 
15927adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
15937adc3a2bSChandler Carruth }
15947adc3a2bSChandler Carruth 
1595b9f7120eSEaswaran Raman bool llvm::isInlineViable(Function &F) {
15967adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
15977adc3a2bSChandler Carruth   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
15987adc3a2bSChandler Carruth     // Disallow inlining of functions which contain indirect branches or
15997adc3a2bSChandler Carruth     // blockaddresses.
16007adc3a2bSChandler Carruth     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
16017adc3a2bSChandler Carruth       return false;
16027adc3a2bSChandler Carruth 
16035a82c916SDuncan P. N. Exon Smith     for (auto &II : *BI) {
16045a82c916SDuncan P. N. Exon Smith       CallSite CS(&II);
16057adc3a2bSChandler Carruth       if (!CS)
16067adc3a2bSChandler Carruth         continue;
16077adc3a2bSChandler Carruth 
16087adc3a2bSChandler Carruth       // Disallow recursive calls.
16097adc3a2bSChandler Carruth       if (&F == CS.getCalledFunction())
16107adc3a2bSChandler Carruth         return false;
16117adc3a2bSChandler Carruth 
16127adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
16137adc3a2bSChandler Carruth       // attributed as such.
16147adc3a2bSChandler Carruth       if (!ReturnsTwice && CS.isCall() &&
16157adc3a2bSChandler Carruth           cast<CallInst>(CS.getInstruction())->canReturnTwice())
16167adc3a2bSChandler Carruth         return false;
16177adc3a2bSChandler Carruth 
16187adc3a2bSChandler Carruth       // Disallow inlining functions that call @llvm.localescape. Doing this
16197adc3a2bSChandler Carruth       // correctly would require major changes to the inliner.
16207adc3a2bSChandler Carruth       if (CS.getCalledFunction() &&
16217adc3a2bSChandler Carruth           CS.getCalledFunction()->getIntrinsicID() ==
16227adc3a2bSChandler Carruth               llvm::Intrinsic::localescape)
16237adc3a2bSChandler Carruth         return false;
16247adc3a2bSChandler Carruth     }
16257adc3a2bSChandler Carruth   }
16267adc3a2bSChandler Carruth 
16277adc3a2bSChandler Carruth   return true;
16287adc3a2bSChandler Carruth }
16291c57cc2bSEaswaran Raman 
16301c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other
16311c57cc2bSEaswaran Raman // parameters.
16321c57cc2bSEaswaran Raman 
16331c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) {
16341c57cc2bSEaswaran Raman   InlineParams Params;
16351c57cc2bSEaswaran Raman 
16361c57cc2bSEaswaran Raman   // This field is the threshold to use for a callee by default. This is
16371c57cc2bSEaswaran Raman   // derived from one or more of:
16381c57cc2bSEaswaran Raman   //  * optimization or size-optimization levels,
16391c57cc2bSEaswaran Raman   //  * a value passed to createFunctionInliningPass function, or
16401c57cc2bSEaswaran Raman   //  * the -inline-threshold flag.
16411c57cc2bSEaswaran Raman   //  If the -inline-threshold flag is explicitly specified, that is used
16421c57cc2bSEaswaran Raman   //  irrespective of anything else.
16431c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() > 0)
16441c57cc2bSEaswaran Raman     Params.DefaultThreshold = InlineThreshold;
16451c57cc2bSEaswaran Raman   else
16461c57cc2bSEaswaran Raman     Params.DefaultThreshold = Threshold;
16471c57cc2bSEaswaran Raman 
16481c57cc2bSEaswaran Raman   // Set the HintThreshold knob from the -inlinehint-threshold.
16491c57cc2bSEaswaran Raman   Params.HintThreshold = HintThreshold;
16501c57cc2bSEaswaran Raman 
16511c57cc2bSEaswaran Raman   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
16521c57cc2bSEaswaran Raman   Params.HotCallSiteThreshold = HotCallSiteThreshold;
16531c57cc2bSEaswaran Raman 
165412585b01SEaswaran Raman   // Set the ColdCallSiteThreshold knob from the -inline-cold-callsite-threshold.
165512585b01SEaswaran Raman   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
165612585b01SEaswaran Raman 
16571c57cc2bSEaswaran Raman   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
16581c57cc2bSEaswaran Raman   // -inlinehint-threshold commandline option is not explicitly given. If that
16591c57cc2bSEaswaran Raman   // option is present, then its value applies even for callees with size and
16601c57cc2bSEaswaran Raman   // minsize attributes.
16611c57cc2bSEaswaran Raman   // If the -inline-threshold is not specified, set the ColdThreshold from the
16621c57cc2bSEaswaran Raman   // -inlinecold-threshold even if it is not explicitly passed. If
16631c57cc2bSEaswaran Raman   // -inline-threshold is specified, then -inlinecold-threshold needs to be
16641c57cc2bSEaswaran Raman   // explicitly specified to set the ColdThreshold knob
16651c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() == 0) {
16661c57cc2bSEaswaran Raman     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
16671c57cc2bSEaswaran Raman     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
16681c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
16691c57cc2bSEaswaran Raman   } else if (ColdThreshold.getNumOccurrences() > 0) {
16701c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
16711c57cc2bSEaswaran Raman   }
16721c57cc2bSEaswaran Raman   return Params;
16731c57cc2bSEaswaran Raman }
16741c57cc2bSEaswaran Raman 
16751c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() {
16761c57cc2bSEaswaran Raman   return getInlineParams(InlineThreshold);
16771c57cc2bSEaswaran Raman }
16781c57cc2bSEaswaran Raman 
16791c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the
16801c57cc2bSEaswaran Raman // size opt level.
16811c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel,
16821c57cc2bSEaswaran Raman                                          unsigned SizeOptLevel) {
16831c57cc2bSEaswaran Raman   if (OptLevel > 2)
16841c57cc2bSEaswaran Raman     return InlineConstants::OptAggressiveThreshold;
16851c57cc2bSEaswaran Raman   if (SizeOptLevel == 1) // -Os
16861c57cc2bSEaswaran Raman     return InlineConstants::OptSizeThreshold;
16871c57cc2bSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
16881c57cc2bSEaswaran Raman     return InlineConstants::OptMinSizeThreshold;
16891c57cc2bSEaswaran Raman   return InlineThreshold;
16901c57cc2bSEaswaran Raman }
16911c57cc2bSEaswaran Raman 
16921c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
16931c57cc2bSEaswaran Raman   return getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
16941c57cc2bSEaswaran Raman }
1695