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" 243739e14aSHaicheng Wu #include "llvm/Analysis/CFG.h" 257adc3a2bSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h" 2671069cf6SEaswaran Raman #include "llvm/Analysis/ProfileSummaryInfo.h" 277adc3a2bSChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h" 28*a4461515SHaicheng Wu #include "llvm/Analysis/ValueTracking.h" 297adc3a2bSChandler Carruth #include "llvm/IR/CallSite.h" 307adc3a2bSChandler Carruth #include "llvm/IR/CallingConv.h" 317adc3a2bSChandler Carruth #include "llvm/IR/DataLayout.h" 327adc3a2bSChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h" 337adc3a2bSChandler Carruth #include "llvm/IR/GlobalAlias.h" 347adc3a2bSChandler Carruth #include "llvm/IR/InstVisitor.h" 357adc3a2bSChandler Carruth #include "llvm/IR/IntrinsicInst.h" 367adc3a2bSChandler Carruth #include "llvm/IR/Operator.h" 377adc3a2bSChandler Carruth #include "llvm/Support/Debug.h" 387adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h" 397adc3a2bSChandler Carruth 407adc3a2bSChandler Carruth using namespace llvm; 417adc3a2bSChandler Carruth 427adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost" 437adc3a2bSChandler Carruth 447adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed"); 457adc3a2bSChandler Carruth 461c57cc2bSEaswaran Raman static cl::opt<int> InlineThreshold( 47f4bb2f0dSEaswaran Raman "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore, 48f4bb2f0dSEaswaran Raman cl::desc("Control the amount of inlining to perform (default = 225)")); 49f4bb2f0dSEaswaran Raman 50f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold( 51f4bb2f0dSEaswaran Raman "inlinehint-threshold", cl::Hidden, cl::init(325), 52f4bb2f0dSEaswaran Raman cl::desc("Threshold for inlining functions with inline hint")); 53f4bb2f0dSEaswaran Raman 5412585b01SEaswaran Raman static cl::opt<int> 5512585b01SEaswaran Raman ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden, 5612585b01SEaswaran Raman cl::init(45), 5712585b01SEaswaran Raman cl::desc("Threshold for inlining cold callsites")); 5812585b01SEaswaran Raman 59f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based 60f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and 61f4bb2f0dSEaswaran Raman // BFI. 62f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold( 63c103ef89SEaswaran Raman "inlinecold-threshold", cl::Hidden, cl::init(45), 64f4bb2f0dSEaswaran Raman cl::desc("Threshold for inlining functions with cold attribute")); 65f4bb2f0dSEaswaran Raman 66de39cb93SDehao Chen static cl::opt<int> 67de39cb93SDehao Chen HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000), 68de39cb93SDehao Chen cl::ZeroOrMore, 69de39cb93SDehao Chen cl::desc("Threshold for hot callsites ")); 70de39cb93SDehao Chen 71974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold( 72974d4eeaSEaswaran Raman "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore, 73974d4eeaSEaswaran Raman cl::desc("Threshold for locally hot callsites ")); 74974d4eeaSEaswaran Raman 75c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq( 76c5fa6358SEaswaran Raman "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, 77c5fa6358SEaswaran Raman cl::desc("Maxmimum block frequency, expressed as a percentage of caller's " 78c5fa6358SEaswaran Raman "entry frequency, for a callsite to be cold in the absence of " 79c5fa6358SEaswaran Raman "profile information.")); 80c5fa6358SEaswaran Raman 81974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq( 82974d4eeaSEaswaran Raman "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore, 83ff77cc75SEaswaran Raman cl::desc("Minimum block frequency, expressed as a multiple of caller's " 84974d4eeaSEaswaran Raman "entry frequency, for a callsite to be hot in the absence of " 85974d4eeaSEaswaran Raman "profile information.")); 86974d4eeaSEaswaran Raman 874924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost( 880812c5beSHaicheng Wu "inline-cost-full", cl::Hidden, cl::init(false), 890812c5beSHaicheng Wu cl::desc("Compute the full inline cost of a call site even when the cost " 900812c5beSHaicheng Wu "exceeds the threshold.")); 910812c5beSHaicheng Wu 927adc3a2bSChandler Carruth namespace { 937adc3a2bSChandler Carruth 947adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> { 957adc3a2bSChandler Carruth typedef InstVisitor<CallAnalyzer, bool> Base; 967adc3a2bSChandler Carruth friend class InstVisitor<CallAnalyzer, bool>; 977adc3a2bSChandler Carruth 987adc3a2bSChandler Carruth /// The TargetTransformInfo available for this compilation. 997adc3a2bSChandler Carruth const TargetTransformInfo &TTI; 1007adc3a2bSChandler Carruth 101aec2fa35SDaniel Jasper /// Getter for the cache of @llvm.assume intrinsics. 102aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache; 103aec2fa35SDaniel Jasper 10412585b01SEaswaran Raman /// Getter for BlockFrequencyInfo 10512585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI; 10612585b01SEaswaran Raman 10771069cf6SEaswaran Raman /// Profile summary information. 10871069cf6SEaswaran Raman ProfileSummaryInfo *PSI; 10971069cf6SEaswaran Raman 110f3d122cdSPiotr Padlewski /// The called function. 1117adc3a2bSChandler Carruth Function &F; 1127adc3a2bSChandler Carruth 11385be8ca8SEric Christopher // Cache the DataLayout since we use it a lot. 11485be8ca8SEric Christopher const DataLayout &DL; 11585be8ca8SEric Christopher 1160812c5beSHaicheng Wu /// The OptimizationRemarkEmitter available for this compilation. 1170812c5beSHaicheng Wu OptimizationRemarkEmitter *ORE; 1180812c5beSHaicheng Wu 119f3d122cdSPiotr Padlewski /// The candidate callsite being analyzed. Please do not use this to do 120f3d122cdSPiotr Padlewski /// analysis in the caller function; we want the inline cost query to be 121f3d122cdSPiotr Padlewski /// easily cacheable. Instead, use the cover function paramHasAttr. 1227adc3a2bSChandler Carruth CallSite CandidateCS; 1237adc3a2bSChandler Carruth 124f3d122cdSPiotr Padlewski /// Tunable parameters that control the analysis. 1251c57cc2bSEaswaran Raman const InlineParams &Params; 1261c57cc2bSEaswaran Raman 1277adc3a2bSChandler Carruth int Threshold; 1287adc3a2bSChandler Carruth int Cost; 1294924bb00SEaswaran Raman bool ComputeFullInlineCost; 1307adc3a2bSChandler Carruth 1317adc3a2bSChandler Carruth bool IsCallerRecursive; 1327adc3a2bSChandler Carruth bool IsRecursiveCall; 1337adc3a2bSChandler Carruth bool ExposesReturnsTwice; 1347adc3a2bSChandler Carruth bool HasDynamicAlloca; 1357adc3a2bSChandler Carruth bool ContainsNoDuplicateCall; 1367adc3a2bSChandler Carruth bool HasReturn; 1377adc3a2bSChandler Carruth bool HasIndirectBr; 1387adc3a2bSChandler Carruth bool HasFrameEscape; 1397adc3a2bSChandler Carruth 1407adc3a2bSChandler Carruth /// Number of bytes allocated statically by the callee. 1417adc3a2bSChandler Carruth uint64_t AllocatedSize; 1427adc3a2bSChandler Carruth unsigned NumInstructions, NumVectorInstructions; 14351b809bfSEaswaran Raman int VectorBonus, TenPercentVectorBonus; 14451b809bfSEaswaran Raman // Bonus to be applied when the callee has only one reachable basic block. 14551b809bfSEaswaran Raman int SingleBBBonus; 1467adc3a2bSChandler Carruth 147f3d122cdSPiotr Padlewski /// While we walk the potentially-inlined instructions, we build up and 148f3d122cdSPiotr Padlewski /// maintain a mapping of simplified values specific to this callsite. The 149f3d122cdSPiotr Padlewski /// idea is to propagate any special information we have about arguments to 150f3d122cdSPiotr Padlewski /// this call through the inlinable section of the function, and account for 151f3d122cdSPiotr Padlewski /// likely simplifications post-inlining. The most important aspect we track 152f3d122cdSPiotr Padlewski /// is CFG altering simplifications -- when we prove a basic block dead, that 153f3d122cdSPiotr Padlewski /// can cause dramatic shifts in the cost of inlining a function. 1547adc3a2bSChandler Carruth DenseMap<Value *, Constant *> SimplifiedValues; 1557adc3a2bSChandler Carruth 156f3d122cdSPiotr Padlewski /// Keep track of the values which map back (through function arguments) to 157f3d122cdSPiotr Padlewski /// allocas on the caller stack which could be simplified through SROA. 1587adc3a2bSChandler Carruth DenseMap<Value *, Value *> SROAArgValues; 1597adc3a2bSChandler Carruth 160f3d122cdSPiotr Padlewski /// The mapping of caller Alloca values to their accumulated cost savings. If 161f3d122cdSPiotr Padlewski /// we have to disable SROA for one of the allocas, this tells us how much 162f3d122cdSPiotr Padlewski /// cost must be added. 1637adc3a2bSChandler Carruth DenseMap<Value *, int> SROAArgCosts; 1647adc3a2bSChandler Carruth 165f3d122cdSPiotr Padlewski /// Keep track of values which map to a pointer base and constant offset. 1667adc3a2bSChandler Carruth DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs; 1677adc3a2bSChandler Carruth 1683739e14aSHaicheng Wu /// Keep track of dead blocks due to the constant arguments. 1693739e14aSHaicheng Wu SetVector<BasicBlock *> DeadBlocks; 1703739e14aSHaicheng Wu 1713739e14aSHaicheng Wu /// The mapping of the blocks to their known unique successors due to the 1723739e14aSHaicheng Wu /// constant arguments. 1733739e14aSHaicheng Wu DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors; 1743739e14aSHaicheng Wu 175*a4461515SHaicheng Wu /// Model the elimination of repeated loads that is expected to happen 176*a4461515SHaicheng Wu /// whenever we simplify away the stores that would otherwise cause them to be 177*a4461515SHaicheng Wu /// loads. 178*a4461515SHaicheng Wu bool EnableLoadElimination; 179*a4461515SHaicheng Wu SmallPtrSet<Value *, 16> LoadAddrSet; 180*a4461515SHaicheng Wu int LoadEliminationCost; 181*a4461515SHaicheng Wu 1827adc3a2bSChandler Carruth // Custom simplification helper routines. 1837adc3a2bSChandler Carruth bool isAllocaDerivedArg(Value *V); 1847adc3a2bSChandler Carruth bool lookupSROAArgAndCost(Value *V, Value *&Arg, 1857adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator &CostIt); 1867adc3a2bSChandler Carruth void disableSROA(DenseMap<Value *, int>::iterator CostIt); 1877adc3a2bSChandler Carruth void disableSROA(Value *V); 1883739e14aSHaicheng Wu void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB); 1897adc3a2bSChandler Carruth void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt, 1907adc3a2bSChandler Carruth int InstructionCost); 191*a4461515SHaicheng Wu void disableLoadElimination(); 192201b191bSHaicheng Wu bool isGEPFree(GetElementPtrInst &GEP); 193d3558b5dSEvgeny Astigeevich bool canFoldInboundsGEP(GetElementPtrInst &I); 1947adc3a2bSChandler Carruth bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset); 1957adc3a2bSChandler Carruth bool simplifyCallSite(Function *F, CallSite CS); 196617f6364SEaswaran Raman template <typename Callable> 197617f6364SEaswaran Raman bool simplifyInstruction(Instruction &I, Callable Evaluate); 1987adc3a2bSChandler Carruth ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V); 1997adc3a2bSChandler Carruth 2007adc3a2bSChandler Carruth /// Return true if the given argument to the function being considered for 2017adc3a2bSChandler Carruth /// inlining has the given attribute set either at the call site or the 2027adc3a2bSChandler Carruth /// function declaration. Primarily used to inspect call site specific 2037adc3a2bSChandler Carruth /// attributes since these can be more precise than the ones on the callee 2047adc3a2bSChandler Carruth /// itself. 2057adc3a2bSChandler Carruth bool paramHasAttr(Argument *A, Attribute::AttrKind Attr); 2067adc3a2bSChandler Carruth 2077adc3a2bSChandler Carruth /// Return true if the given value is known non null within the callee if 2087adc3a2bSChandler Carruth /// inlined through this particular callsite. 2097adc3a2bSChandler Carruth bool isKnownNonNullInCallee(Value *V); 2107adc3a2bSChandler Carruth 211f4bb2f0dSEaswaran Raman /// Update Threshold based on callsite properties such as callee 212f4bb2f0dSEaswaran Raman /// attributes and callee hotness for PGO builds. The Callee is explicitly 213f4bb2f0dSEaswaran Raman /// passed to support analyzing indirect calls whose target is inferred by 214f4bb2f0dSEaswaran Raman /// analysis. 215f4bb2f0dSEaswaran Raman void updateThreshold(CallSite CS, Function &Callee); 216f4bb2f0dSEaswaran Raman 2179a3fc17aSEaswaran Raman /// Return true if size growth is allowed when inlining the callee at CS. 2189a3fc17aSEaswaran Raman bool allowSizeGrowth(CallSite CS); 2199a3fc17aSEaswaran Raman 220c5fa6358SEaswaran Raman /// Return true if \p CS is a cold callsite. 221c5fa6358SEaswaran Raman bool isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI); 222c5fa6358SEaswaran Raman 223974d4eeaSEaswaran Raman /// Return a higher threshold if \p CS is a hot callsite. 224974d4eeaSEaswaran Raman Optional<int> getHotCallSiteThreshold(CallSite CS, 225974d4eeaSEaswaran Raman BlockFrequencyInfo *CallerBFI); 226974d4eeaSEaswaran Raman 2277adc3a2bSChandler Carruth // Custom analysis routines. 2287adc3a2bSChandler Carruth bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues); 2297adc3a2bSChandler Carruth 2307adc3a2bSChandler Carruth // Disable several entry points to the visitor so we don't accidentally use 2317adc3a2bSChandler Carruth // them by declaring but not defining them here. 232567556aaSChad Rosier void visit(Module *); 233567556aaSChad Rosier void visit(Module &); 234567556aaSChad Rosier void visit(Function *); 235567556aaSChad Rosier void visit(Function &); 236567556aaSChad Rosier void visit(BasicBlock *); 237567556aaSChad Rosier void visit(BasicBlock &); 2387adc3a2bSChandler Carruth 2397adc3a2bSChandler Carruth // Provide base case for our instruction visit. 2407adc3a2bSChandler Carruth bool visitInstruction(Instruction &I); 2417adc3a2bSChandler Carruth 2427adc3a2bSChandler Carruth // Our visit overrides. 2437adc3a2bSChandler Carruth bool visitAlloca(AllocaInst &I); 2447adc3a2bSChandler Carruth bool visitPHI(PHINode &I); 2457adc3a2bSChandler Carruth bool visitGetElementPtr(GetElementPtrInst &I); 2467adc3a2bSChandler Carruth bool visitBitCast(BitCastInst &I); 2477adc3a2bSChandler Carruth bool visitPtrToInt(PtrToIntInst &I); 2487adc3a2bSChandler Carruth bool visitIntToPtr(IntToPtrInst &I); 2497adc3a2bSChandler Carruth bool visitCastInst(CastInst &I); 2507adc3a2bSChandler Carruth bool visitUnaryInstruction(UnaryInstruction &I); 2517adc3a2bSChandler Carruth bool visitCmpInst(CmpInst &I); 2522e1c050eSChad Rosier bool visitAnd(BinaryOperator &I); 2532e1c050eSChad Rosier bool visitOr(BinaryOperator &I); 2547adc3a2bSChandler Carruth bool visitSub(BinaryOperator &I); 2557adc3a2bSChandler Carruth bool visitBinaryOperator(BinaryOperator &I); 2567adc3a2bSChandler Carruth bool visitLoad(LoadInst &I); 2577adc3a2bSChandler Carruth bool visitStore(StoreInst &I); 2587adc3a2bSChandler Carruth bool visitExtractValue(ExtractValueInst &I); 2597adc3a2bSChandler Carruth bool visitInsertValue(InsertValueInst &I); 2607adc3a2bSChandler Carruth bool visitCallSite(CallSite CS); 2617adc3a2bSChandler Carruth bool visitReturnInst(ReturnInst &RI); 2627adc3a2bSChandler Carruth bool visitBranchInst(BranchInst &BI); 2633ec848bcSHaicheng Wu bool visitSelectInst(SelectInst &SI); 2647adc3a2bSChandler Carruth bool visitSwitchInst(SwitchInst &SI); 2657adc3a2bSChandler Carruth bool visitIndirectBrInst(IndirectBrInst &IBI); 2667adc3a2bSChandler Carruth bool visitResumeInst(ResumeInst &RI); 2677adc3a2bSChandler Carruth bool visitCleanupReturnInst(CleanupReturnInst &RI); 2687adc3a2bSChandler Carruth bool visitCatchReturnInst(CatchReturnInst &RI); 2697adc3a2bSChandler Carruth bool visitUnreachableInst(UnreachableInst &I); 2707adc3a2bSChandler Carruth 2717adc3a2bSChandler Carruth public: 272ab6a6837SSean Silva CallAnalyzer(const TargetTransformInfo &TTI, 273aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 27412585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI, 2750812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, 2760812c5beSHaicheng Wu Function &Callee, CallSite CSArg, const InlineParams &Params) 27712585b01SEaswaran Raman : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI), 2780812c5beSHaicheng Wu PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE), 27985be8ca8SEric Christopher CandidateCS(CSArg), Params(Params), Threshold(Params.DefaultThreshold), 2804924bb00SEaswaran Raman Cost(0), ComputeFullInlineCost(OptComputeFullInlineCost || 2814924bb00SEaswaran Raman Params.ComputeFullInlineCost || ORE), 2824924bb00SEaswaran Raman IsCallerRecursive(false), IsRecursiveCall(false), 28385be8ca8SEric Christopher ExposesReturnsTwice(false), HasDynamicAlloca(false), 28485be8ca8SEric Christopher ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false), 28585be8ca8SEric Christopher HasFrameEscape(false), AllocatedSize(0), NumInstructions(0), 28651b809bfSEaswaran Raman NumVectorInstructions(0), VectorBonus(0), SingleBBBonus(0), 287*a4461515SHaicheng Wu EnableLoadElimination(true), LoadEliminationCost(0), NumConstantArgs(0), 288*a4461515SHaicheng Wu NumConstantOffsetPtrArgs(0), NumAllocaArgs(0), NumConstantPtrCmps(0), 289*a4461515SHaicheng Wu NumConstantPtrDiffs(0), NumInstructionsSimplified(0), 290*a4461515SHaicheng Wu SROACostSavings(0), SROACostSavingsLost(0) {} 2917adc3a2bSChandler Carruth 2927adc3a2bSChandler Carruth bool analyzeCall(CallSite CS); 2937adc3a2bSChandler Carruth 2947adc3a2bSChandler Carruth int getThreshold() { return Threshold; } 2957adc3a2bSChandler Carruth int getCost() { return Cost; } 2967adc3a2bSChandler Carruth 2977adc3a2bSChandler Carruth // Keep a bunch of stats about the cost savings found so we can print them 2987adc3a2bSChandler Carruth // out when debugging. 2997adc3a2bSChandler Carruth unsigned NumConstantArgs; 3007adc3a2bSChandler Carruth unsigned NumConstantOffsetPtrArgs; 3017adc3a2bSChandler Carruth unsigned NumAllocaArgs; 3027adc3a2bSChandler Carruth unsigned NumConstantPtrCmps; 3037adc3a2bSChandler Carruth unsigned NumConstantPtrDiffs; 3047adc3a2bSChandler Carruth unsigned NumInstructionsSimplified; 3057adc3a2bSChandler Carruth unsigned SROACostSavings; 3067adc3a2bSChandler Carruth unsigned SROACostSavingsLost; 3077adc3a2bSChandler Carruth 3087adc3a2bSChandler Carruth void dump(); 3097adc3a2bSChandler Carruth }; 3107adc3a2bSChandler Carruth 3117adc3a2bSChandler Carruth } // namespace 3127adc3a2bSChandler Carruth 3137adc3a2bSChandler Carruth /// \brief Test whether the given value is an Alloca-derived function argument. 3147adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) { 3157adc3a2bSChandler Carruth return SROAArgValues.count(V); 3167adc3a2bSChandler Carruth } 3177adc3a2bSChandler Carruth 3187adc3a2bSChandler Carruth /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to. 3197adc3a2bSChandler Carruth /// Returns false if V does not map to a SROA-candidate. 3207adc3a2bSChandler Carruth bool CallAnalyzer::lookupSROAArgAndCost( 3217adc3a2bSChandler Carruth Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) { 3227adc3a2bSChandler Carruth if (SROAArgValues.empty() || SROAArgCosts.empty()) 3237adc3a2bSChandler Carruth return false; 3247adc3a2bSChandler Carruth 3257adc3a2bSChandler Carruth DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V); 3267adc3a2bSChandler Carruth if (ArgIt == SROAArgValues.end()) 3277adc3a2bSChandler Carruth return false; 3287adc3a2bSChandler Carruth 3297adc3a2bSChandler Carruth Arg = ArgIt->second; 3307adc3a2bSChandler Carruth CostIt = SROAArgCosts.find(Arg); 3317adc3a2bSChandler Carruth return CostIt != SROAArgCosts.end(); 3327adc3a2bSChandler Carruth } 3337adc3a2bSChandler Carruth 3347adc3a2bSChandler Carruth /// \brief Disable SROA for the candidate marked by this cost iterator. 3357adc3a2bSChandler Carruth /// 3367adc3a2bSChandler Carruth /// This marks the candidate as no longer viable for SROA, and adds the cost 3377adc3a2bSChandler Carruth /// savings associated with it back into the inline cost measurement. 3387adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) { 3397adc3a2bSChandler Carruth // If we're no longer able to perform SROA we need to undo its cost savings 3407adc3a2bSChandler Carruth // and prevent subsequent analysis. 3417adc3a2bSChandler Carruth Cost += CostIt->second; 3427adc3a2bSChandler Carruth SROACostSavings -= CostIt->second; 3437adc3a2bSChandler Carruth SROACostSavingsLost += CostIt->second; 3447adc3a2bSChandler Carruth SROAArgCosts.erase(CostIt); 345*a4461515SHaicheng Wu disableLoadElimination(); 3467adc3a2bSChandler Carruth } 3477adc3a2bSChandler Carruth 3487adc3a2bSChandler Carruth /// \brief If 'V' maps to a SROA candidate, disable SROA for it. 3497adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) { 3507adc3a2bSChandler Carruth Value *SROAArg; 3517adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 3527adc3a2bSChandler Carruth if (lookupSROAArgAndCost(V, SROAArg, CostIt)) 3537adc3a2bSChandler Carruth disableSROA(CostIt); 3547adc3a2bSChandler Carruth } 3557adc3a2bSChandler Carruth 3567adc3a2bSChandler Carruth /// \brief Accumulate the given cost for a particular SROA candidate. 3577adc3a2bSChandler Carruth void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt, 3587adc3a2bSChandler Carruth int InstructionCost) { 3597adc3a2bSChandler Carruth CostIt->second += InstructionCost; 3607adc3a2bSChandler Carruth SROACostSavings += InstructionCost; 3617adc3a2bSChandler Carruth } 3627adc3a2bSChandler Carruth 363*a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() { 364*a4461515SHaicheng Wu if (EnableLoadElimination) { 365*a4461515SHaicheng Wu Cost += LoadEliminationCost; 366*a4461515SHaicheng Wu EnableLoadElimination = false; 367*a4461515SHaicheng Wu } 368*a4461515SHaicheng Wu } 369*a4461515SHaicheng Wu 3707adc3a2bSChandler Carruth /// \brief Accumulate a constant GEP offset into an APInt if possible. 3717adc3a2bSChandler Carruth /// 3727adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any 3737adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite. 3747adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) { 3757adc3a2bSChandler Carruth unsigned IntPtrWidth = DL.getPointerSizeInBits(); 3767adc3a2bSChandler Carruth assert(IntPtrWidth == Offset.getBitWidth()); 3777adc3a2bSChandler Carruth 3787adc3a2bSChandler Carruth for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); 3797adc3a2bSChandler Carruth GTI != GTE; ++GTI) { 3807adc3a2bSChandler Carruth ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 3817adc3a2bSChandler Carruth if (!OpC) 3827adc3a2bSChandler Carruth if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand())) 3837adc3a2bSChandler Carruth OpC = dyn_cast<ConstantInt>(SimpleOp); 3847adc3a2bSChandler Carruth if (!OpC) 3857adc3a2bSChandler Carruth return false; 386567556aaSChad Rosier if (OpC->isZero()) 387567556aaSChad Rosier continue; 3887adc3a2bSChandler Carruth 3897adc3a2bSChandler Carruth // Handle a struct index, which adds its field offset to the pointer. 390ab85225bSPeter Collingbourne if (StructType *STy = GTI.getStructTypeOrNull()) { 3917adc3a2bSChandler Carruth unsigned ElementIdx = OpC->getZExtValue(); 3927adc3a2bSChandler Carruth const StructLayout *SL = DL.getStructLayout(STy); 3937adc3a2bSChandler Carruth Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx)); 3947adc3a2bSChandler Carruth continue; 3957adc3a2bSChandler Carruth } 3967adc3a2bSChandler Carruth 3977adc3a2bSChandler Carruth APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType())); 3987adc3a2bSChandler Carruth Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize; 3997adc3a2bSChandler Carruth } 4007adc3a2bSChandler Carruth return true; 4017adc3a2bSChandler Carruth } 4027adc3a2bSChandler Carruth 403201b191bSHaicheng Wu /// \brief Use TTI to check whether a GEP is free. 404201b191bSHaicheng Wu /// 405201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite. 406201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) { 40761c1bd5aSEvgeny Astigeevich SmallVector<Value *, 4> Operands; 40861c1bd5aSEvgeny Astigeevich Operands.push_back(GEP.getOperand(0)); 409201b191bSHaicheng Wu for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 410201b191bSHaicheng Wu if (Constant *SimpleOp = SimplifiedValues.lookup(*I)) 41161c1bd5aSEvgeny Astigeevich Operands.push_back(SimpleOp); 412201b191bSHaicheng Wu else 41361c1bd5aSEvgeny Astigeevich Operands.push_back(*I); 41461c1bd5aSEvgeny Astigeevich return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands); 415201b191bSHaicheng Wu } 416201b191bSHaicheng Wu 4177adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) { 4187adc3a2bSChandler Carruth // Check whether inlining will turn a dynamic alloca into a static 4190f153424SSanjay Patel // alloca and handle that case. 4207adc3a2bSChandler Carruth if (I.isArrayAllocation()) { 4210f153424SSanjay Patel Constant *Size = SimplifiedValues.lookup(I.getArraySize()); 4220f153424SSanjay Patel if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) { 4237adc3a2bSChandler Carruth Type *Ty = I.getAllocatedType(); 42422eb80a1SEaswaran Raman AllocatedSize = SaturatingMultiplyAdd( 42522eb80a1SEaswaran Raman AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty), AllocatedSize); 4267adc3a2bSChandler Carruth return Base::visitAlloca(I); 4277adc3a2bSChandler Carruth } 4287adc3a2bSChandler Carruth } 4297adc3a2bSChandler Carruth 4307adc3a2bSChandler Carruth // Accumulate the allocated size. 4317adc3a2bSChandler Carruth if (I.isStaticAlloca()) { 4327adc3a2bSChandler Carruth Type *Ty = I.getAllocatedType(); 43322eb80a1SEaswaran Raman AllocatedSize = SaturatingAdd(DL.getTypeAllocSize(Ty), AllocatedSize); 4347adc3a2bSChandler Carruth } 4357adc3a2bSChandler Carruth 4367adc3a2bSChandler Carruth // We will happily inline static alloca instructions. 4377adc3a2bSChandler Carruth if (I.isStaticAlloca()) 4387adc3a2bSChandler Carruth return Base::visitAlloca(I); 4397adc3a2bSChandler Carruth 4407adc3a2bSChandler Carruth // FIXME: This is overly conservative. Dynamic allocas are inefficient for 4417adc3a2bSChandler Carruth // a variety of reasons, and so we would like to not inline them into 4427adc3a2bSChandler Carruth // functions which don't currently have a dynamic alloca. This simply 4437adc3a2bSChandler Carruth // disables inlining altogether in the presence of a dynamic alloca. 4447adc3a2bSChandler Carruth HasDynamicAlloca = true; 4457adc3a2bSChandler Carruth return false; 4467adc3a2bSChandler Carruth } 4477adc3a2bSChandler Carruth 4487adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) { 4497adc3a2bSChandler Carruth // FIXME: We need to propagate SROA *disabling* through phi nodes, even 4507adc3a2bSChandler Carruth // though we don't want to propagate it's bonuses. The idea is to disable 4517adc3a2bSChandler Carruth // SROA if it *might* be used in an inappropriate manner. 4527adc3a2bSChandler Carruth 4537adc3a2bSChandler Carruth // Phi nodes are always zero-cost. 4543739e14aSHaicheng Wu 4553739e14aSHaicheng Wu APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits()); 4563739e14aSHaicheng Wu bool CheckSROA = I.getType()->isPointerTy(); 4573739e14aSHaicheng Wu 4583739e14aSHaicheng Wu // Track the constant or pointer with constant offset we've seen so far. 4593739e14aSHaicheng Wu Constant *FirstC = nullptr; 4603739e14aSHaicheng Wu std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset}; 4613739e14aSHaicheng Wu Value *FirstV = nullptr; 4623739e14aSHaicheng Wu 4633739e14aSHaicheng Wu for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) { 4643739e14aSHaicheng Wu BasicBlock *Pred = I.getIncomingBlock(i); 4653739e14aSHaicheng Wu // If the incoming block is dead, skip the incoming block. 4663739e14aSHaicheng Wu if (DeadBlocks.count(Pred)) 4673739e14aSHaicheng Wu continue; 4683739e14aSHaicheng Wu // If the parent block of phi is not the known successor of the incoming 4693739e14aSHaicheng Wu // block, skip the incoming block. 4703739e14aSHaicheng Wu BasicBlock *KnownSuccessor = KnownSuccessors[Pred]; 4713739e14aSHaicheng Wu if (KnownSuccessor && KnownSuccessor != I.getParent()) 4723739e14aSHaicheng Wu continue; 4733739e14aSHaicheng Wu 4743739e14aSHaicheng Wu Value *V = I.getIncomingValue(i); 4753739e14aSHaicheng Wu // If the incoming value is this phi itself, skip the incoming value. 4763739e14aSHaicheng Wu if (&I == V) 4773739e14aSHaicheng Wu continue; 4783739e14aSHaicheng Wu 4793739e14aSHaicheng Wu Constant *C = dyn_cast<Constant>(V); 4803739e14aSHaicheng Wu if (!C) 4813739e14aSHaicheng Wu C = SimplifiedValues.lookup(V); 4823739e14aSHaicheng Wu 4833739e14aSHaicheng Wu std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset}; 4843739e14aSHaicheng Wu if (!C && CheckSROA) 4853739e14aSHaicheng Wu BaseAndOffset = ConstantOffsetPtrs.lookup(V); 4863739e14aSHaicheng Wu 4873739e14aSHaicheng Wu if (!C && !BaseAndOffset.first) 4883739e14aSHaicheng Wu // The incoming value is neither a constant nor a pointer with constant 4893739e14aSHaicheng Wu // offset, exit early. 4903739e14aSHaicheng Wu return true; 4913739e14aSHaicheng Wu 4923739e14aSHaicheng Wu if (FirstC) { 4933739e14aSHaicheng Wu if (FirstC == C) 4943739e14aSHaicheng Wu // If we've seen a constant incoming value before and it is the same 4953739e14aSHaicheng Wu // constant we see this time, continue checking the next incoming value. 4963739e14aSHaicheng Wu continue; 4973739e14aSHaicheng Wu // Otherwise early exit because we either see a different constant or saw 4983739e14aSHaicheng Wu // a constant before but we have a pointer with constant offset this time. 4993739e14aSHaicheng Wu return true; 5003739e14aSHaicheng Wu } 5013739e14aSHaicheng Wu 5023739e14aSHaicheng Wu if (FirstV) { 5033739e14aSHaicheng Wu // The same logic as above, but check pointer with constant offset here. 5043739e14aSHaicheng Wu if (FirstBaseAndOffset == BaseAndOffset) 5053739e14aSHaicheng Wu continue; 5063739e14aSHaicheng Wu return true; 5073739e14aSHaicheng Wu } 5083739e14aSHaicheng Wu 5093739e14aSHaicheng Wu if (C) { 5103739e14aSHaicheng Wu // This is the 1st time we've seen a constant, record it. 5113739e14aSHaicheng Wu FirstC = C; 5123739e14aSHaicheng Wu continue; 5133739e14aSHaicheng Wu } 5143739e14aSHaicheng Wu 5153739e14aSHaicheng Wu // The remaining case is that this is the 1st time we've seen a pointer with 5163739e14aSHaicheng Wu // constant offset, record it. 5173739e14aSHaicheng Wu FirstV = V; 5183739e14aSHaicheng Wu FirstBaseAndOffset = BaseAndOffset; 5193739e14aSHaicheng Wu } 5203739e14aSHaicheng Wu 5213739e14aSHaicheng Wu // Check if we can map phi to a constant. 5223739e14aSHaicheng Wu if (FirstC) { 5233739e14aSHaicheng Wu SimplifiedValues[&I] = FirstC; 5243739e14aSHaicheng Wu return true; 5253739e14aSHaicheng Wu } 5263739e14aSHaicheng Wu 5273739e14aSHaicheng Wu // Check if we can map phi to a pointer with constant offset. 5283739e14aSHaicheng Wu if (FirstBaseAndOffset.first) { 5293739e14aSHaicheng Wu ConstantOffsetPtrs[&I] = FirstBaseAndOffset; 5303739e14aSHaicheng Wu 5313739e14aSHaicheng Wu Value *SROAArg; 5323739e14aSHaicheng Wu DenseMap<Value *, int>::iterator CostIt; 5333739e14aSHaicheng Wu if (lookupSROAArgAndCost(FirstV, SROAArg, CostIt)) 5343739e14aSHaicheng Wu SROAArgValues[&I] = SROAArg; 5353739e14aSHaicheng Wu } 5363739e14aSHaicheng Wu 5377adc3a2bSChandler Carruth return true; 5387adc3a2bSChandler Carruth } 5397adc3a2bSChandler Carruth 540d3558b5dSEvgeny Astigeevich /// \brief Check we can fold GEPs of constant-offset call site argument pointers. 541d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs. 542d3558b5dSEvgeny Astigeevich /// 543d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded. 544d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) { 545d3558b5dSEvgeny Astigeevich // Check if we have a base + offset for the pointer. 546d3558b5dSEvgeny Astigeevich std::pair<Value *, APInt> BaseAndOffset = 547d3558b5dSEvgeny Astigeevich ConstantOffsetPtrs.lookup(I.getPointerOperand()); 548d3558b5dSEvgeny Astigeevich if (!BaseAndOffset.first) 549d3558b5dSEvgeny Astigeevich return false; 550d3558b5dSEvgeny Astigeevich 551d3558b5dSEvgeny Astigeevich // Check if the offset of this GEP is constant, and if so accumulate it 552d3558b5dSEvgeny Astigeevich // into Offset. 553d3558b5dSEvgeny Astigeevich if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) 554d3558b5dSEvgeny Astigeevich return false; 555d3558b5dSEvgeny Astigeevich 556d3558b5dSEvgeny Astigeevich // Add the result as a new mapping to Base + Offset. 557d3558b5dSEvgeny Astigeevich ConstantOffsetPtrs[&I] = BaseAndOffset; 558d3558b5dSEvgeny Astigeevich 559d3558b5dSEvgeny Astigeevich return true; 560d3558b5dSEvgeny Astigeevich } 561d3558b5dSEvgeny Astigeevich 5627adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) { 5637adc3a2bSChandler Carruth Value *SROAArg; 5647adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 565567556aaSChad Rosier bool SROACandidate = 566567556aaSChad Rosier lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt); 5677adc3a2bSChandler Carruth 568a8b9cdc9SEaswaran Raman // Lambda to check whether a GEP's indices are all constant. 569a8b9cdc9SEaswaran Raman auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) { 570a8b9cdc9SEaswaran Raman for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 571a8b9cdc9SEaswaran Raman if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I)) 572a8b9cdc9SEaswaran Raman return false; 573a8b9cdc9SEaswaran Raman return true; 574a8b9cdc9SEaswaran Raman }; 575a8b9cdc9SEaswaran Raman 576d3558b5dSEvgeny Astigeevich if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) { 5777adc3a2bSChandler Carruth if (SROACandidate) 5787adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 5797adc3a2bSChandler Carruth 5807adc3a2bSChandler Carruth // Constant GEPs are modeled as free. 5817adc3a2bSChandler Carruth return true; 5827adc3a2bSChandler Carruth } 5837adc3a2bSChandler Carruth 5847adc3a2bSChandler Carruth // Variable GEPs will require math and will disable SROA. 5857adc3a2bSChandler Carruth if (SROACandidate) 5867adc3a2bSChandler Carruth disableSROA(CostIt); 587201b191bSHaicheng Wu return isGEPFree(I); 5887adc3a2bSChandler Carruth } 5897adc3a2bSChandler Carruth 590617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues. 591617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the 592617f6364SEaswaran Raman /// instruction when all the operands are constants. 593617f6364SEaswaran Raman template <typename Callable> 594617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) { 595617f6364SEaswaran Raman SmallVector<Constant *, 2> COps; 596617f6364SEaswaran Raman for (Value *Op : I.operands()) { 597617f6364SEaswaran Raman Constant *COp = dyn_cast<Constant>(Op); 5987adc3a2bSChandler Carruth if (!COp) 599617f6364SEaswaran Raman COp = SimplifiedValues.lookup(Op); 600617f6364SEaswaran Raman if (!COp) 601617f6364SEaswaran Raman return false; 602617f6364SEaswaran Raman COps.push_back(COp); 603617f6364SEaswaran Raman } 604617f6364SEaswaran Raman auto *C = Evaluate(COps); 605617f6364SEaswaran Raman if (!C) 606617f6364SEaswaran Raman return false; 6077adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 6087adc3a2bSChandler Carruth return true; 6097adc3a2bSChandler Carruth } 6107adc3a2bSChandler Carruth 611617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) { 612617f6364SEaswaran Raman // Propagate constants through bitcasts. 613617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 614617f6364SEaswaran Raman return ConstantExpr::getBitCast(COps[0], I.getType()); 615617f6364SEaswaran Raman })) 616617f6364SEaswaran Raman return true; 617617f6364SEaswaran Raman 6187adc3a2bSChandler Carruth // Track base/offsets through casts 619567556aaSChad Rosier std::pair<Value *, APInt> BaseAndOffset = 620567556aaSChad Rosier ConstantOffsetPtrs.lookup(I.getOperand(0)); 6217adc3a2bSChandler Carruth // Casts don't change the offset, just wrap it up. 6227adc3a2bSChandler Carruth if (BaseAndOffset.first) 6237adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 6247adc3a2bSChandler Carruth 6257adc3a2bSChandler Carruth // Also look for SROA candidates here. 6267adc3a2bSChandler Carruth Value *SROAArg; 6277adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 6287adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) 6297adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 6307adc3a2bSChandler Carruth 6317adc3a2bSChandler Carruth // Bitcasts are always zero cost. 6327adc3a2bSChandler Carruth return true; 6337adc3a2bSChandler Carruth } 6347adc3a2bSChandler Carruth 6357adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) { 6367adc3a2bSChandler Carruth // Propagate constants through ptrtoint. 637617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 638617f6364SEaswaran Raman return ConstantExpr::getPtrToInt(COps[0], I.getType()); 639617f6364SEaswaran Raman })) 6407adc3a2bSChandler Carruth return true; 6417adc3a2bSChandler Carruth 6427adc3a2bSChandler Carruth // Track base/offset pairs when converted to a plain integer provided the 6437adc3a2bSChandler Carruth // integer is large enough to represent the pointer. 6447adc3a2bSChandler Carruth unsigned IntegerSize = I.getType()->getScalarSizeInBits(); 6457adc3a2bSChandler Carruth if (IntegerSize >= DL.getPointerSizeInBits()) { 646567556aaSChad Rosier std::pair<Value *, APInt> BaseAndOffset = 647567556aaSChad Rosier ConstantOffsetPtrs.lookup(I.getOperand(0)); 6487adc3a2bSChandler Carruth if (BaseAndOffset.first) 6497adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 6507adc3a2bSChandler Carruth } 6517adc3a2bSChandler Carruth 6527adc3a2bSChandler Carruth // This is really weird. Technically, ptrtoint will disable SROA. However, 6537adc3a2bSChandler Carruth // unless that ptrtoint is *used* somewhere in the live basic blocks after 6547adc3a2bSChandler Carruth // inlining, it will be nuked, and SROA should proceed. All of the uses which 6557adc3a2bSChandler Carruth // would block SROA would also block SROA if applied directly to a pointer, 6567adc3a2bSChandler Carruth // and so we can just add the integer in here. The only places where SROA is 6577adc3a2bSChandler Carruth // preserved either cannot fire on an integer, or won't in-and-of themselves 6587adc3a2bSChandler Carruth // disable SROA (ext) w/o some later use that we would see and disable. 6597adc3a2bSChandler Carruth Value *SROAArg; 6607adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 6617adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) 6627adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 6637adc3a2bSChandler Carruth 6647adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 6657adc3a2bSChandler Carruth } 6667adc3a2bSChandler Carruth 6677adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) { 6687adc3a2bSChandler Carruth // Propagate constants through ptrtoint. 669617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 670617f6364SEaswaran Raman return ConstantExpr::getIntToPtr(COps[0], I.getType()); 671617f6364SEaswaran Raman })) 6727adc3a2bSChandler Carruth return true; 6737adc3a2bSChandler Carruth 6747adc3a2bSChandler Carruth // Track base/offset pairs when round-tripped through a pointer without 6757adc3a2bSChandler Carruth // modifications provided the integer is not too large. 6767adc3a2bSChandler Carruth Value *Op = I.getOperand(0); 6777adc3a2bSChandler Carruth unsigned IntegerSize = Op->getType()->getScalarSizeInBits(); 6787adc3a2bSChandler Carruth if (IntegerSize <= DL.getPointerSizeInBits()) { 6797adc3a2bSChandler Carruth std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op); 6807adc3a2bSChandler Carruth if (BaseAndOffset.first) 6817adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 6827adc3a2bSChandler Carruth } 6837adc3a2bSChandler Carruth 6847adc3a2bSChandler Carruth // "Propagate" SROA here in the same manner as we do for ptrtoint above. 6857adc3a2bSChandler Carruth Value *SROAArg; 6867adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 6877adc3a2bSChandler Carruth if (lookupSROAArgAndCost(Op, SROAArg, CostIt)) 6887adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 6897adc3a2bSChandler Carruth 6907adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 6917adc3a2bSChandler Carruth } 6927adc3a2bSChandler Carruth 6937adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) { 6947adc3a2bSChandler Carruth // Propagate constants through ptrtoint. 695617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 696617f6364SEaswaran Raman return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType()); 697617f6364SEaswaran Raman })) 6987adc3a2bSChandler Carruth return true; 6997adc3a2bSChandler Carruth 7007adc3a2bSChandler Carruth // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere. 7017adc3a2bSChandler Carruth disableSROA(I.getOperand(0)); 7027adc3a2bSChandler Carruth 7037adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 7047adc3a2bSChandler Carruth } 7057adc3a2bSChandler Carruth 7067adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) { 7077adc3a2bSChandler Carruth Value *Operand = I.getOperand(0); 708617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 709617f6364SEaswaran Raman return ConstantFoldInstOperands(&I, COps[0], DL); 710617f6364SEaswaran Raman })) 7117adc3a2bSChandler Carruth return true; 7127adc3a2bSChandler Carruth 7137adc3a2bSChandler Carruth // Disable any SROA on the argument to arbitrary unary operators. 7147adc3a2bSChandler Carruth disableSROA(Operand); 7157adc3a2bSChandler Carruth 7167adc3a2bSChandler Carruth return false; 7177adc3a2bSChandler Carruth } 7187adc3a2bSChandler Carruth 7197adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) { 720fb502d2fSReid Kleckner return CandidateCS.paramHasAttr(A->getArgNo(), Attr); 7217adc3a2bSChandler Carruth } 7227adc3a2bSChandler Carruth 7237adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) { 7247adc3a2bSChandler Carruth // Does the *call site* have the NonNull attribute set on an argument? We 7257adc3a2bSChandler Carruth // use the attribute on the call site to memoize any analysis done in the 7267adc3a2bSChandler Carruth // caller. This will also trip if the callee function has a non-null 7277adc3a2bSChandler Carruth // parameter attribute, but that's a less interesting case because hopefully 7287adc3a2bSChandler Carruth // the callee would already have been simplified based on that. 7297adc3a2bSChandler Carruth if (Argument *A = dyn_cast<Argument>(V)) 7307adc3a2bSChandler Carruth if (paramHasAttr(A, Attribute::NonNull)) 7317adc3a2bSChandler Carruth return true; 7327adc3a2bSChandler Carruth 7337adc3a2bSChandler Carruth // Is this an alloca in the caller? This is distinct from the attribute case 7347adc3a2bSChandler Carruth // above because attributes aren't updated within the inliner itself and we 7357adc3a2bSChandler Carruth // always want to catch the alloca derived case. 7367adc3a2bSChandler Carruth if (isAllocaDerivedArg(V)) 7377adc3a2bSChandler Carruth // We can actually predict the result of comparisons between an 7387adc3a2bSChandler Carruth // alloca-derived value and null. Note that this fires regardless of 7397adc3a2bSChandler Carruth // SROA firing. 7407adc3a2bSChandler Carruth return true; 7417adc3a2bSChandler Carruth 7427adc3a2bSChandler Carruth return false; 7437adc3a2bSChandler Carruth } 7447adc3a2bSChandler Carruth 7459a3fc17aSEaswaran Raman bool CallAnalyzer::allowSizeGrowth(CallSite CS) { 7469a3fc17aSEaswaran Raman // If the normal destination of the invoke or the parent block of the call 7479a3fc17aSEaswaran Raman // site is unreachable-terminated, there is little point in inlining this 7489a3fc17aSEaswaran Raman // unless there is literally zero cost. 7499a3fc17aSEaswaran Raman // FIXME: Note that it is possible that an unreachable-terminated block has a 7509a3fc17aSEaswaran Raman // hot entry. For example, in below scenario inlining hot_call_X() may be 7519a3fc17aSEaswaran Raman // beneficial : 7529a3fc17aSEaswaran Raman // main() { 7539a3fc17aSEaswaran Raman // hot_call_1(); 7549a3fc17aSEaswaran Raman // ... 7559a3fc17aSEaswaran Raman // hot_call_N() 7569a3fc17aSEaswaran Raman // exit(0); 7579a3fc17aSEaswaran Raman // } 7589a3fc17aSEaswaran Raman // For now, we are not handling this corner case here as it is rare in real 7599a3fc17aSEaswaran Raman // code. In future, we should elaborate this based on BPI and BFI in more 7609a3fc17aSEaswaran Raman // general threshold adjusting heuristics in updateThreshold(). 7619a3fc17aSEaswaran Raman Instruction *Instr = CS.getInstruction(); 7629a3fc17aSEaswaran Raman if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) { 7639a3fc17aSEaswaran Raman if (isa<UnreachableInst>(II->getNormalDest()->getTerminator())) 7649a3fc17aSEaswaran Raman return false; 7659a3fc17aSEaswaran Raman } else if (isa<UnreachableInst>(Instr->getParent()->getTerminator())) 7669a3fc17aSEaswaran Raman return false; 7679a3fc17aSEaswaran Raman 7689a3fc17aSEaswaran Raman return true; 7699a3fc17aSEaswaran Raman } 7709a3fc17aSEaswaran Raman 771c5fa6358SEaswaran Raman bool CallAnalyzer::isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI) { 772c5fa6358SEaswaran Raman // If global profile summary is available, then callsite's coldness is 773c5fa6358SEaswaran Raman // determined based on that. 774bba762a1SChandler Carruth if (PSI && PSI->hasProfileSummary()) 775c5fa6358SEaswaran Raman return PSI->isColdCallSite(CS, CallerBFI); 776bba762a1SChandler Carruth 777bba762a1SChandler Carruth // Otherwise we need BFI to be available. 778c5fa6358SEaswaran Raman if (!CallerBFI) 779c5fa6358SEaswaran Raman return false; 780c5fa6358SEaswaran Raman 781bba762a1SChandler Carruth // Determine if the callsite is cold relative to caller's entry. We could 782bba762a1SChandler Carruth // potentially cache the computation of scaled entry frequency, but the added 783bba762a1SChandler Carruth // complexity is not worth it unless this scaling shows up high in the 784bba762a1SChandler Carruth // profiles. 785c5fa6358SEaswaran Raman const BranchProbability ColdProb(ColdCallSiteRelFreq, 100); 786c5fa6358SEaswaran Raman auto CallSiteBB = CS.getInstruction()->getParent(); 787c5fa6358SEaswaran Raman auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB); 788c5fa6358SEaswaran Raman auto CallerEntryFreq = 789c5fa6358SEaswaran Raman CallerBFI->getBlockFreq(&(CS.getCaller()->getEntryBlock())); 790c5fa6358SEaswaran Raman return CallSiteFreq < CallerEntryFreq * ColdProb; 791c5fa6358SEaswaran Raman } 792c5fa6358SEaswaran Raman 793974d4eeaSEaswaran Raman Optional<int> 794974d4eeaSEaswaran Raman CallAnalyzer::getHotCallSiteThreshold(CallSite CS, 795974d4eeaSEaswaran Raman BlockFrequencyInfo *CallerBFI) { 796bba762a1SChandler Carruth 797974d4eeaSEaswaran Raman // If global profile summary is available, then callsite's hotness is 798974d4eeaSEaswaran Raman // determined based on that. 799bba762a1SChandler Carruth if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(CS, CallerBFI)) 800bba762a1SChandler Carruth return Params.HotCallSiteThreshold; 801974d4eeaSEaswaran Raman 802bba762a1SChandler Carruth // Otherwise we need BFI to be available and to have a locally hot callsite 803bba762a1SChandler Carruth // threshold. 804bba762a1SChandler Carruth if (!CallerBFI || !Params.LocallyHotCallSiteThreshold) 805974d4eeaSEaswaran Raman return None; 806974d4eeaSEaswaran Raman 807bba762a1SChandler Carruth // Determine if the callsite is hot relative to caller's entry. We could 808bba762a1SChandler Carruth // potentially cache the computation of scaled entry frequency, but the added 809bba762a1SChandler Carruth // complexity is not worth it unless this scaling shows up high in the 810bba762a1SChandler Carruth // profiles. 811974d4eeaSEaswaran Raman auto CallSiteBB = CS.getInstruction()->getParent(); 812974d4eeaSEaswaran Raman auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency(); 813974d4eeaSEaswaran Raman auto CallerEntryFreq = CallerBFI->getEntryFreq(); 814974d4eeaSEaswaran Raman if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq) 815bba762a1SChandler Carruth return Params.LocallyHotCallSiteThreshold; 816bba762a1SChandler Carruth 817bba762a1SChandler Carruth // Otherwise treat it normally. 818974d4eeaSEaswaran Raman return None; 819974d4eeaSEaswaran Raman } 820974d4eeaSEaswaran Raman 821f4bb2f0dSEaswaran Raman void CallAnalyzer::updateThreshold(CallSite CS, Function &Callee) { 8229a3fc17aSEaswaran Raman // If no size growth is allowed for this inlining, set Threshold to 0. 8239a3fc17aSEaswaran Raman if (!allowSizeGrowth(CS)) { 8249a3fc17aSEaswaran Raman Threshold = 0; 8259a3fc17aSEaswaran Raman return; 8269a3fc17aSEaswaran Raman } 8279a3fc17aSEaswaran Raman 828bb578ef0SEaswaran Raman Function *Caller = CS.getCaller(); 8291c57cc2bSEaswaran Raman 8301c57cc2bSEaswaran Raman // return min(A, B) if B is valid. 8311c57cc2bSEaswaran Raman auto MinIfValid = [](int A, Optional<int> B) { 8321c57cc2bSEaswaran Raman return B ? std::min(A, B.getValue()) : A; 8331c57cc2bSEaswaran Raman }; 8341c57cc2bSEaswaran Raman 8350d58fcacSEaswaran Raman // return max(A, B) if B is valid. 8360d58fcacSEaswaran Raman auto MaxIfValid = [](int A, Optional<int> B) { 8370d58fcacSEaswaran Raman return B ? std::max(A, B.getValue()) : A; 8380d58fcacSEaswaran Raman }; 8390d58fcacSEaswaran Raman 84051b809bfSEaswaran Raman // Various bonus percentages. These are multiplied by Threshold to get the 84151b809bfSEaswaran Raman // bonus values. 84251b809bfSEaswaran Raman // SingleBBBonus: This bonus is applied if the callee has a single reachable 84351b809bfSEaswaran Raman // basic block at the given callsite context. This is speculatively applied 84451b809bfSEaswaran Raman // and withdrawn if more than one basic block is seen. 84551b809bfSEaswaran Raman // 84651b809bfSEaswaran Raman // Vector bonuses: We want to more aggressively inline vector-dense kernels 84751b809bfSEaswaran Raman // and apply this bonus based on the percentage of vector instructions. A 84851b809bfSEaswaran Raman // bonus is applied if the vector instructions exceed 50% and half that amount 84951b809bfSEaswaran Raman // is applied if it exceeds 10%. Note that these bonuses are some what 85051b809bfSEaswaran Raman // arbitrary and evolved over time by accident as much as because they are 85151b809bfSEaswaran Raman // principled bonuses. 85251b809bfSEaswaran Raman // FIXME: It would be nice to base the bonus values on something more 85351b809bfSEaswaran Raman // scientific. 85451b809bfSEaswaran Raman // 85551b809bfSEaswaran Raman // LstCallToStaticBonus: This large bonus is applied to ensure the inlining 85651b809bfSEaswaran Raman // of the last call to a static function as inlining such functions is 85751b809bfSEaswaran Raman // guaranteed to reduce code size. 85851b809bfSEaswaran Raman // 85951b809bfSEaswaran Raman // These bonus percentages may be set to 0 based on properties of the caller 86051b809bfSEaswaran Raman // and the callsite. 86151b809bfSEaswaran Raman int SingleBBBonusPercent = 50; 86251b809bfSEaswaran Raman int VectorBonusPercent = 150; 86351b809bfSEaswaran Raman int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus; 86451b809bfSEaswaran Raman 86551b809bfSEaswaran Raman // Lambda to set all the above bonus and bonus percentages to 0. 86651b809bfSEaswaran Raman auto DisallowAllBonuses = [&]() { 86751b809bfSEaswaran Raman SingleBBBonusPercent = 0; 86851b809bfSEaswaran Raman VectorBonusPercent = 0; 86951b809bfSEaswaran Raman LastCallToStaticBonus = 0; 87051b809bfSEaswaran Raman }; 87151b809bfSEaswaran Raman 8721c57cc2bSEaswaran Raman // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available 8731c57cc2bSEaswaran Raman // and reduce the threshold if the caller has the necessary attribute. 87451b809bfSEaswaran Raman if (Caller->optForMinSize()) { 8751c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold); 87651b809bfSEaswaran Raman // For minsize, we want to disable the single BB bonus and the vector 87751b809bfSEaswaran Raman // bonuses, but not the last-call-to-static bonus. Inlining the last call to 87851b809bfSEaswaran Raman // a static function will, at the minimum, eliminate the parameter setup and 87951b809bfSEaswaran Raman // call/return instructions. 88051b809bfSEaswaran Raman SingleBBBonusPercent = 0; 88151b809bfSEaswaran Raman VectorBonusPercent = 0; 88251b809bfSEaswaran Raman } else if (Caller->optForSize()) 8831c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.OptSizeThreshold); 884f4bb2f0dSEaswaran Raman 885e08b139dSEaswaran Raman // Adjust the threshold based on inlinehint attribute and profile based 886e08b139dSEaswaran Raman // hotness information if the caller does not have MinSize attribute. 887e08b139dSEaswaran Raman if (!Caller->optForMinSize()) { 888e08b139dSEaswaran Raman if (Callee.hasFnAttribute(Attribute::InlineHint)) 8890d58fcacSEaswaran Raman Threshold = MaxIfValid(Threshold, Params.HintThreshold); 890bba762a1SChandler Carruth 8913cd1479cSEaswaran Raman // FIXME: After switching to the new passmanager, simplify the logic below 892bba762a1SChandler Carruth // by checking only the callsite hotness/coldness as we will reliably 893bba762a1SChandler Carruth // have local profile information. 8943cd1479cSEaswaran Raman // 895bba762a1SChandler Carruth // Callsite hotness and coldness can be determined if sample profile is 896bba762a1SChandler Carruth // used (which adds hotness metadata to calls) or if caller's 897bba762a1SChandler Carruth // BlockFrequencyInfo is available. 898bba762a1SChandler Carruth BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr; 899974d4eeaSEaswaran Raman auto HotCallSiteThreshold = getHotCallSiteThreshold(CS, CallerBFI); 900974d4eeaSEaswaran Raman if (!Caller->optForSize() && HotCallSiteThreshold) { 90112585b01SEaswaran Raman DEBUG(dbgs() << "Hot callsite.\n"); 902974d4eeaSEaswaran Raman // FIXME: This should update the threshold only if it exceeds the 903974d4eeaSEaswaran Raman // current threshold, but AutoFDO + ThinLTO currently relies on this 904974d4eeaSEaswaran Raman // behavior to prevent inlining of hot callsites during ThinLTO 905974d4eeaSEaswaran Raman // compile phase. 906974d4eeaSEaswaran Raman Threshold = HotCallSiteThreshold.getValue(); 907c5fa6358SEaswaran Raman } else if (isColdCallSite(CS, CallerBFI)) { 9083cd1479cSEaswaran Raman DEBUG(dbgs() << "Cold callsite.\n"); 90951b809bfSEaswaran Raman // Do not apply bonuses for a cold callsite including the 91051b809bfSEaswaran Raman // LastCallToStatic bonus. While this bonus might result in code size 91151b809bfSEaswaran Raman // reduction, it can cause the size of a non-cold caller to increase 91251b809bfSEaswaran Raman // preventing it from being inlined. 91351b809bfSEaswaran Raman DisallowAllBonuses(); 9143cd1479cSEaswaran Raman Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold); 915bba762a1SChandler Carruth } else if (PSI) { 916bba762a1SChandler Carruth // Use callee's global profile information only if we have no way of 917bba762a1SChandler Carruth // determining this via callsite information. 9183cd1479cSEaswaran Raman if (PSI->isFunctionEntryHot(&Callee)) { 91912585b01SEaswaran Raman DEBUG(dbgs() << "Hot callee.\n"); 920e08b139dSEaswaran Raman // If callsite hotness can not be determined, we may still know 921e08b139dSEaswaran Raman // that the callee is hot and treat it as a weaker hint for threshold 922e08b139dSEaswaran Raman // increase. 923e08b139dSEaswaran Raman Threshold = MaxIfValid(Threshold, Params.HintThreshold); 924e08b139dSEaswaran Raman } else if (PSI->isFunctionEntryCold(&Callee)) { 92512585b01SEaswaran Raman DEBUG(dbgs() << "Cold callee.\n"); 92651b809bfSEaswaran Raman // Do not apply bonuses for a cold callee including the 92751b809bfSEaswaran Raman // LastCallToStatic bonus. While this bonus might result in code size 92851b809bfSEaswaran Raman // reduction, it can cause the size of a non-cold caller to increase 92951b809bfSEaswaran Raman // preventing it from being inlined. 93051b809bfSEaswaran Raman DisallowAllBonuses(); 9311c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.ColdThreshold); 932e08b139dSEaswaran Raman } 933e08b139dSEaswaran Raman } 934e08b139dSEaswaran Raman } 9358650a4daSJustin Lebar 9368650a4daSJustin Lebar // Finally, take the target-specific inlining threshold multiplier into 9378650a4daSJustin Lebar // account. 9388650a4daSJustin Lebar Threshold *= TTI.getInliningThresholdMultiplier(); 93951b809bfSEaswaran Raman 94051b809bfSEaswaran Raman SingleBBBonus = Threshold * SingleBBBonusPercent / 100; 94151b809bfSEaswaran Raman VectorBonus = Threshold * VectorBonusPercent / 100; 94251b809bfSEaswaran Raman 94351b809bfSEaswaran Raman bool OnlyOneCallAndLocalLinkage = 94451b809bfSEaswaran Raman F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction(); 94551b809bfSEaswaran Raman // If there is only one call of the function, and it has internal linkage, 94651b809bfSEaswaran Raman // the cost of inlining it drops dramatically. It may seem odd to update 94751b809bfSEaswaran Raman // Cost in updateThreshold, but the bonus depends on the logic in this method. 94851b809bfSEaswaran Raman if (OnlyOneCallAndLocalLinkage) 94951b809bfSEaswaran Raman Cost -= LastCallToStaticBonus; 950f4bb2f0dSEaswaran Raman } 951f4bb2f0dSEaswaran Raman 9527adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) { 9537adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 9547adc3a2bSChandler Carruth // First try to handle simplified comparisons. 955617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 956617f6364SEaswaran Raman return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]); 957617f6364SEaswaran Raman })) 9587adc3a2bSChandler Carruth return true; 9597adc3a2bSChandler Carruth 9607adc3a2bSChandler Carruth if (I.getOpcode() == Instruction::FCmp) 9617adc3a2bSChandler Carruth return false; 9627adc3a2bSChandler Carruth 9637adc3a2bSChandler Carruth // Otherwise look for a comparison between constant offset pointers with 9647adc3a2bSChandler Carruth // a common base. 9657adc3a2bSChandler Carruth Value *LHSBase, *RHSBase; 9667adc3a2bSChandler Carruth APInt LHSOffset, RHSOffset; 9677adc3a2bSChandler Carruth std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 9687adc3a2bSChandler Carruth if (LHSBase) { 9697adc3a2bSChandler Carruth std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 9707adc3a2bSChandler Carruth if (RHSBase && LHSBase == RHSBase) { 9717adc3a2bSChandler Carruth // We have common bases, fold the icmp to a constant based on the 9727adc3a2bSChandler Carruth // offsets. 9737adc3a2bSChandler Carruth Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 9747adc3a2bSChandler Carruth Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 9757adc3a2bSChandler Carruth if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) { 9767adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 9777adc3a2bSChandler Carruth ++NumConstantPtrCmps; 9787adc3a2bSChandler Carruth return true; 9797adc3a2bSChandler Carruth } 9807adc3a2bSChandler Carruth } 9817adc3a2bSChandler Carruth } 9827adc3a2bSChandler Carruth 9837adc3a2bSChandler Carruth // If the comparison is an equality comparison with null, we can simplify it 9847adc3a2bSChandler Carruth // if we know the value (argument) can't be null 9857adc3a2bSChandler Carruth if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) && 9867adc3a2bSChandler Carruth isKnownNonNullInCallee(I.getOperand(0))) { 9877adc3a2bSChandler Carruth bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE; 9887adc3a2bSChandler Carruth SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType()) 9897adc3a2bSChandler Carruth : ConstantInt::getFalse(I.getType()); 9907adc3a2bSChandler Carruth return true; 9917adc3a2bSChandler Carruth } 9927adc3a2bSChandler Carruth // Finally check for SROA candidates in comparisons. 9937adc3a2bSChandler Carruth Value *SROAArg; 9947adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 9957adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) { 9967adc3a2bSChandler Carruth if (isa<ConstantPointerNull>(I.getOperand(1))) { 9977adc3a2bSChandler Carruth accumulateSROACost(CostIt, InlineConstants::InstrCost); 9987adc3a2bSChandler Carruth return true; 9997adc3a2bSChandler Carruth } 10007adc3a2bSChandler Carruth 10017adc3a2bSChandler Carruth disableSROA(CostIt); 10027adc3a2bSChandler Carruth } 10037adc3a2bSChandler Carruth 10047adc3a2bSChandler Carruth return false; 10057adc3a2bSChandler Carruth } 10067adc3a2bSChandler Carruth 10072e1c050eSChad Rosier bool CallAnalyzer::visitOr(BinaryOperator &I) { 10082e1c050eSChad Rosier // This is necessary because the generic simplify instruction only works if 10092e1c050eSChad Rosier // both operands are constants. 10102e1c050eSChad Rosier for (unsigned i = 0; i < 2; ++i) { 10112e1c050eSChad Rosier if (ConstantInt *C = dyn_cast_or_null<ConstantInt>( 10122e1c050eSChad Rosier SimplifiedValues.lookup(I.getOperand(i)))) 10132e1c050eSChad Rosier if (C->isAllOnesValue()) { 10142e1c050eSChad Rosier SimplifiedValues[&I] = C; 10152e1c050eSChad Rosier return true; 10162e1c050eSChad Rosier } 10172e1c050eSChad Rosier } 10182e1c050eSChad Rosier return Base::visitOr(I); 10192e1c050eSChad Rosier } 10202e1c050eSChad Rosier 10212e1c050eSChad Rosier bool CallAnalyzer::visitAnd(BinaryOperator &I) { 10222e1c050eSChad Rosier // This is necessary because the generic simplify instruction only works if 10232e1c050eSChad Rosier // both operands are constants. 10242e1c050eSChad Rosier for (unsigned i = 0; i < 2; ++i) { 10252e1c050eSChad Rosier if (ConstantInt *C = dyn_cast_or_null<ConstantInt>( 10262e1c050eSChad Rosier SimplifiedValues.lookup(I.getOperand(i)))) 10272e1c050eSChad Rosier if (C->isZero()) { 10282e1c050eSChad Rosier SimplifiedValues[&I] = C; 10292e1c050eSChad Rosier return true; 10302e1c050eSChad Rosier } 10312e1c050eSChad Rosier } 10322e1c050eSChad Rosier return Base::visitAnd(I); 10332e1c050eSChad Rosier } 10342e1c050eSChad Rosier 10357adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) { 10367adc3a2bSChandler Carruth // Try to handle a special case: we can fold computing the difference of two 10377adc3a2bSChandler Carruth // constant-related pointers. 10387adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 10397adc3a2bSChandler Carruth Value *LHSBase, *RHSBase; 10407adc3a2bSChandler Carruth APInt LHSOffset, RHSOffset; 10417adc3a2bSChandler Carruth std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 10427adc3a2bSChandler Carruth if (LHSBase) { 10437adc3a2bSChandler Carruth std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 10447adc3a2bSChandler Carruth if (RHSBase && LHSBase == RHSBase) { 10457adc3a2bSChandler Carruth // We have common bases, fold the subtract to a constant based on the 10467adc3a2bSChandler Carruth // offsets. 10477adc3a2bSChandler Carruth Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 10487adc3a2bSChandler Carruth Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 10497adc3a2bSChandler Carruth if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) { 10507adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 10517adc3a2bSChandler Carruth ++NumConstantPtrDiffs; 10527adc3a2bSChandler Carruth return true; 10537adc3a2bSChandler Carruth } 10547adc3a2bSChandler Carruth } 10557adc3a2bSChandler Carruth } 10567adc3a2bSChandler Carruth 10577adc3a2bSChandler Carruth // Otherwise, fall back to the generic logic for simplifying and handling 10587adc3a2bSChandler Carruth // instructions. 10597adc3a2bSChandler Carruth return Base::visitSub(I); 10607adc3a2bSChandler Carruth } 10617adc3a2bSChandler Carruth 10627adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) { 10637adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1064617f6364SEaswaran Raman auto Evaluate = [&](SmallVectorImpl<Constant *> &COps) { 10657adc3a2bSChandler Carruth Value *SimpleV = nullptr; 10667adc3a2bSChandler Carruth if (auto FI = dyn_cast<FPMathOperator>(&I)) 1067617f6364SEaswaran Raman SimpleV = SimplifyFPBinOp(I.getOpcode(), COps[0], COps[1], 1068617f6364SEaswaran Raman FI->getFastMathFlags(), DL); 10697adc3a2bSChandler Carruth else 1070617f6364SEaswaran Raman SimpleV = SimplifyBinOp(I.getOpcode(), COps[0], COps[1], DL); 1071617f6364SEaswaran Raman return dyn_cast_or_null<Constant>(SimpleV); 1072617f6364SEaswaran Raman }; 10737adc3a2bSChandler Carruth 1074617f6364SEaswaran Raman if (simplifyInstruction(I, Evaluate)) 10757adc3a2bSChandler Carruth return true; 10767adc3a2bSChandler Carruth 10777adc3a2bSChandler Carruth // Disable any SROA on arguments to arbitrary, unsimplified binary operators. 10787adc3a2bSChandler Carruth disableSROA(LHS); 10797adc3a2bSChandler Carruth disableSROA(RHS); 10807adc3a2bSChandler Carruth 10817adc3a2bSChandler Carruth return false; 10827adc3a2bSChandler Carruth } 10837adc3a2bSChandler Carruth 10847adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) { 10857adc3a2bSChandler Carruth Value *SROAArg; 10867adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 10877adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) { 10887adc3a2bSChandler Carruth if (I.isSimple()) { 10897adc3a2bSChandler Carruth accumulateSROACost(CostIt, InlineConstants::InstrCost); 10907adc3a2bSChandler Carruth return true; 10917adc3a2bSChandler Carruth } 10927adc3a2bSChandler Carruth 10937adc3a2bSChandler Carruth disableSROA(CostIt); 10947adc3a2bSChandler Carruth } 10957adc3a2bSChandler Carruth 1096*a4461515SHaicheng Wu // If the data is already loaded from this address and hasn't been clobbered 1097*a4461515SHaicheng Wu // by any stores or calls, this load is likely to be redundant and can be 1098*a4461515SHaicheng Wu // eliminated. 1099*a4461515SHaicheng Wu if (EnableLoadElimination && 1100*a4461515SHaicheng Wu !LoadAddrSet.insert(I.getPointerOperand()).second) { 1101*a4461515SHaicheng Wu LoadEliminationCost += InlineConstants::InstrCost; 1102*a4461515SHaicheng Wu return true; 1103*a4461515SHaicheng Wu } 1104*a4461515SHaicheng Wu 11057adc3a2bSChandler Carruth return false; 11067adc3a2bSChandler Carruth } 11077adc3a2bSChandler Carruth 11087adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) { 11097adc3a2bSChandler Carruth Value *SROAArg; 11107adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 11117adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) { 11127adc3a2bSChandler Carruth if (I.isSimple()) { 11137adc3a2bSChandler Carruth accumulateSROACost(CostIt, InlineConstants::InstrCost); 11147adc3a2bSChandler Carruth return true; 11157adc3a2bSChandler Carruth } 11167adc3a2bSChandler Carruth 11177adc3a2bSChandler Carruth disableSROA(CostIt); 11187adc3a2bSChandler Carruth } 11197adc3a2bSChandler Carruth 1120*a4461515SHaicheng Wu // The store can potentially clobber loads and prevent repeated loads from 1121*a4461515SHaicheng Wu // being eliminated. 1122*a4461515SHaicheng Wu // FIXME: 1123*a4461515SHaicheng Wu // 1. We can probably keep an initial set of eliminatable loads substracted 1124*a4461515SHaicheng Wu // from the cost even when we finally see a store. We just need to disable 1125*a4461515SHaicheng Wu // *further* accumulation of elimination savings. 1126*a4461515SHaicheng Wu // 2. We should probably at some point thread MemorySSA for the callee into 1127*a4461515SHaicheng Wu // this and then use that to actually compute *really* precise savings. 1128*a4461515SHaicheng Wu disableLoadElimination(); 11297adc3a2bSChandler Carruth return false; 11307adc3a2bSChandler Carruth } 11317adc3a2bSChandler Carruth 11327adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) { 11337adc3a2bSChandler Carruth // Constant folding for extract value is trivial. 1134617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1135617f6364SEaswaran Raman return ConstantExpr::getExtractValue(COps[0], I.getIndices()); 1136617f6364SEaswaran Raman })) 11377adc3a2bSChandler Carruth return true; 11387adc3a2bSChandler Carruth 11397adc3a2bSChandler Carruth // SROA can look through these but give them a cost. 11407adc3a2bSChandler Carruth return false; 11417adc3a2bSChandler Carruth } 11427adc3a2bSChandler Carruth 11437adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) { 11447adc3a2bSChandler Carruth // Constant folding for insert value is trivial. 1145617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1146617f6364SEaswaran Raman return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0], 1147617f6364SEaswaran Raman /*InsertedValueOperand*/ COps[1], 1148617f6364SEaswaran Raman I.getIndices()); 1149617f6364SEaswaran Raman })) 11507adc3a2bSChandler Carruth return true; 11517adc3a2bSChandler Carruth 11527adc3a2bSChandler Carruth // SROA can look through these but give them a cost. 11537adc3a2bSChandler Carruth return false; 11547adc3a2bSChandler Carruth } 11557adc3a2bSChandler Carruth 11567adc3a2bSChandler Carruth /// \brief Try to simplify a call site. 11577adc3a2bSChandler Carruth /// 11587adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by 11597adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if 11607adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it 11617adc3a2bSChandler Carruth /// free. 11627adc3a2bSChandler Carruth bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) { 11637adc3a2bSChandler Carruth // FIXME: Using the instsimplify logic directly for this is inefficient 11647adc3a2bSChandler Carruth // because we have to continually rebuild the argument list even when no 11657adc3a2bSChandler Carruth // simplifications can be performed. Until that is fixed with remapping 11667adc3a2bSChandler Carruth // inside of instsimplify, directly constant fold calls here. 1167647025f9SAndrew Kaylor if (!canConstantFoldCallTo(CS, F)) 11687adc3a2bSChandler Carruth return false; 11697adc3a2bSChandler Carruth 11707adc3a2bSChandler Carruth // Try to re-map the arguments to constants. 11717adc3a2bSChandler Carruth SmallVector<Constant *, 4> ConstantArgs; 11727adc3a2bSChandler Carruth ConstantArgs.reserve(CS.arg_size()); 1173567556aaSChad Rosier for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; 1174567556aaSChad Rosier ++I) { 11757adc3a2bSChandler Carruth Constant *C = dyn_cast<Constant>(*I); 11767adc3a2bSChandler Carruth if (!C) 11777adc3a2bSChandler Carruth C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I)); 11787adc3a2bSChandler Carruth if (!C) 11797adc3a2bSChandler Carruth return false; // This argument doesn't map to a constant. 11807adc3a2bSChandler Carruth 11817adc3a2bSChandler Carruth ConstantArgs.push_back(C); 11827adc3a2bSChandler Carruth } 1183647025f9SAndrew Kaylor if (Constant *C = ConstantFoldCall(CS, F, ConstantArgs)) { 11847adc3a2bSChandler Carruth SimplifiedValues[CS.getInstruction()] = C; 11857adc3a2bSChandler Carruth return true; 11867adc3a2bSChandler Carruth } 11877adc3a2bSChandler Carruth 11887adc3a2bSChandler Carruth return false; 11897adc3a2bSChandler Carruth } 11907adc3a2bSChandler Carruth 11917adc3a2bSChandler Carruth bool CallAnalyzer::visitCallSite(CallSite CS) { 11927adc3a2bSChandler Carruth if (CS.hasFnAttr(Attribute::ReturnsTwice) && 11937adc3a2bSChandler Carruth !F.hasFnAttribute(Attribute::ReturnsTwice)) { 11947adc3a2bSChandler Carruth // This aborts the entire analysis. 11957adc3a2bSChandler Carruth ExposesReturnsTwice = true; 11967adc3a2bSChandler Carruth return false; 11977adc3a2bSChandler Carruth } 1198567556aaSChad Rosier if (CS.isCall() && cast<CallInst>(CS.getInstruction())->cannotDuplicate()) 11997adc3a2bSChandler Carruth ContainsNoDuplicateCall = true; 12007adc3a2bSChandler Carruth 12017adc3a2bSChandler Carruth if (Function *F = CS.getCalledFunction()) { 12027adc3a2bSChandler Carruth // When we have a concrete function, first try to simplify it directly. 12037adc3a2bSChandler Carruth if (simplifyCallSite(F, CS)) 12047adc3a2bSChandler Carruth return true; 12057adc3a2bSChandler Carruth 12067adc3a2bSChandler Carruth // Next check if it is an intrinsic we know about. 12077adc3a2bSChandler Carruth // FIXME: Lift this into part of the InstVisitor. 12087adc3a2bSChandler Carruth if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) { 12097adc3a2bSChandler Carruth switch (II->getIntrinsicID()) { 12107adc3a2bSChandler Carruth default: 1211*a4461515SHaicheng Wu if (!CS.onlyReadsMemory() && !isAssumeLikeIntrinsic(II)) 1212*a4461515SHaicheng Wu disableLoadElimination(); 12137adc3a2bSChandler Carruth return Base::visitCallSite(CS); 12147adc3a2bSChandler Carruth 12157dd8dbf4SPeter Collingbourne case Intrinsic::load_relative: 12167dd8dbf4SPeter Collingbourne // This is normally lowered to 4 LLVM instructions. 12177dd8dbf4SPeter Collingbourne Cost += 3 * InlineConstants::InstrCost; 12187dd8dbf4SPeter Collingbourne return false; 12197dd8dbf4SPeter Collingbourne 12207adc3a2bSChandler Carruth case Intrinsic::memset: 12217adc3a2bSChandler Carruth case Intrinsic::memcpy: 12227adc3a2bSChandler Carruth case Intrinsic::memmove: 1223*a4461515SHaicheng Wu disableLoadElimination(); 12247adc3a2bSChandler Carruth // SROA can usually chew through these intrinsics, but they aren't free. 12257adc3a2bSChandler Carruth return false; 12267adc3a2bSChandler Carruth case Intrinsic::localescape: 12277adc3a2bSChandler Carruth HasFrameEscape = true; 12287adc3a2bSChandler Carruth return false; 12297adc3a2bSChandler Carruth } 12307adc3a2bSChandler Carruth } 12317adc3a2bSChandler Carruth 12329d939c8fSDavide Italiano if (F == CS.getInstruction()->getFunction()) { 12337adc3a2bSChandler Carruth // This flag will fully abort the analysis, so don't bother with anything 12347adc3a2bSChandler Carruth // else. 12357adc3a2bSChandler Carruth IsRecursiveCall = true; 12367adc3a2bSChandler Carruth return false; 12377adc3a2bSChandler Carruth } 12387adc3a2bSChandler Carruth 12397adc3a2bSChandler Carruth if (TTI.isLoweredToCall(F)) { 12407adc3a2bSChandler Carruth // We account for the average 1 instruction per call argument setup 12417adc3a2bSChandler Carruth // here. 12427adc3a2bSChandler Carruth Cost += CS.arg_size() * InlineConstants::InstrCost; 12437adc3a2bSChandler Carruth 12447adc3a2bSChandler Carruth // Everything other than inline ASM will also have a significant cost 12457adc3a2bSChandler Carruth // merely from making the call. 12467adc3a2bSChandler Carruth if (!isa<InlineAsm>(CS.getCalledValue())) 12477adc3a2bSChandler Carruth Cost += InlineConstants::CallPenalty; 12487adc3a2bSChandler Carruth } 12497adc3a2bSChandler Carruth 1250*a4461515SHaicheng Wu if (!CS.onlyReadsMemory()) 1251*a4461515SHaicheng Wu disableLoadElimination(); 12527adc3a2bSChandler Carruth return Base::visitCallSite(CS); 12537adc3a2bSChandler Carruth } 12547adc3a2bSChandler Carruth 12557adc3a2bSChandler Carruth // Otherwise we're in a very special case -- an indirect function call. See 12567adc3a2bSChandler Carruth // if we can be particularly clever about this. 12577adc3a2bSChandler Carruth Value *Callee = CS.getCalledValue(); 12587adc3a2bSChandler Carruth 12597adc3a2bSChandler Carruth // First, pay the price of the argument setup. We account for the average 12607adc3a2bSChandler Carruth // 1 instruction per call argument setup here. 12617adc3a2bSChandler Carruth Cost += CS.arg_size() * InlineConstants::InstrCost; 12627adc3a2bSChandler Carruth 12637adc3a2bSChandler Carruth // Next, check if this happens to be an indirect function call to a known 12647adc3a2bSChandler Carruth // function in this inline context. If not, we've done all we can. 12657adc3a2bSChandler Carruth Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee)); 1266*a4461515SHaicheng Wu if (!F) { 1267*a4461515SHaicheng Wu if (!CS.onlyReadsMemory()) 1268*a4461515SHaicheng Wu disableLoadElimination(); 12697adc3a2bSChandler Carruth return Base::visitCallSite(CS); 1270*a4461515SHaicheng Wu } 12717adc3a2bSChandler Carruth 12727adc3a2bSChandler Carruth // If we have a constant that we are calling as a function, we can peer 12737adc3a2bSChandler Carruth // through it and see the function target. This happens not infrequently 12747adc3a2bSChandler Carruth // during devirtualization and so we want to give it a hefty bonus for 12757adc3a2bSChandler Carruth // inlining, but cap that bonus in the event that inlining wouldn't pan 12767adc3a2bSChandler Carruth // out. Pretend to inline the function, with a custom threshold. 12771c57cc2bSEaswaran Raman auto IndirectCallParams = Params; 12781c57cc2bSEaswaran Raman IndirectCallParams.DefaultThreshold = InlineConstants::IndirectCallThreshold; 12790812c5beSHaicheng Wu CallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F, CS, 128012585b01SEaswaran Raman IndirectCallParams); 12817adc3a2bSChandler Carruth if (CA.analyzeCall(CS)) { 12827adc3a2bSChandler Carruth // We were able to inline the indirect call! Subtract the cost from the 12836d90d9f1SEaswaran Raman // threshold to get the bonus we want to apply, but don't go below zero. 12846d90d9f1SEaswaran Raman Cost -= std::max(0, CA.getThreshold() - CA.getCost()); 12857adc3a2bSChandler Carruth } 12867adc3a2bSChandler Carruth 1287*a4461515SHaicheng Wu if (!F->onlyReadsMemory()) 1288*a4461515SHaicheng Wu disableLoadElimination(); 12897adc3a2bSChandler Carruth return Base::visitCallSite(CS); 12907adc3a2bSChandler Carruth } 12917adc3a2bSChandler Carruth 12927adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) { 12937adc3a2bSChandler Carruth // At least one return instruction will be free after inlining. 12947adc3a2bSChandler Carruth bool Free = !HasReturn; 12957adc3a2bSChandler Carruth HasReturn = true; 12967adc3a2bSChandler Carruth return Free; 12977adc3a2bSChandler Carruth } 12987adc3a2bSChandler Carruth 12997adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) { 13007adc3a2bSChandler Carruth // We model unconditional branches as essentially free -- they really 13017adc3a2bSChandler Carruth // shouldn't exist at all, but handling them makes the behavior of the 13027adc3a2bSChandler Carruth // inliner more regular and predictable. Interestingly, conditional branches 13037adc3a2bSChandler Carruth // which will fold away are also free. 13047adc3a2bSChandler Carruth return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) || 13057adc3a2bSChandler Carruth dyn_cast_or_null<ConstantInt>( 13067adc3a2bSChandler Carruth SimplifiedValues.lookup(BI.getCondition())); 13077adc3a2bSChandler Carruth } 13087adc3a2bSChandler Carruth 13093ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) { 13103ec848bcSHaicheng Wu bool CheckSROA = SI.getType()->isPointerTy(); 13113ec848bcSHaicheng Wu Value *TrueVal = SI.getTrueValue(); 13123ec848bcSHaicheng Wu Value *FalseVal = SI.getFalseValue(); 13133ec848bcSHaicheng Wu 13143ec848bcSHaicheng Wu Constant *TrueC = dyn_cast<Constant>(TrueVal); 13153ec848bcSHaicheng Wu if (!TrueC) 13163ec848bcSHaicheng Wu TrueC = SimplifiedValues.lookup(TrueVal); 13173ec848bcSHaicheng Wu Constant *FalseC = dyn_cast<Constant>(FalseVal); 13183ec848bcSHaicheng Wu if (!FalseC) 13193ec848bcSHaicheng Wu FalseC = SimplifiedValues.lookup(FalseVal); 13203ec848bcSHaicheng Wu Constant *CondC = 13213ec848bcSHaicheng Wu dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition())); 13223ec848bcSHaicheng Wu 13233ec848bcSHaicheng Wu if (!CondC) { 13243ec848bcSHaicheng Wu // Select C, X, X => X 13253ec848bcSHaicheng Wu if (TrueC == FalseC && TrueC) { 13263ec848bcSHaicheng Wu SimplifiedValues[&SI] = TrueC; 13273ec848bcSHaicheng Wu return true; 13283ec848bcSHaicheng Wu } 13293ec848bcSHaicheng Wu 13303ec848bcSHaicheng Wu if (!CheckSROA) 13313ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 13323ec848bcSHaicheng Wu 13333ec848bcSHaicheng Wu std::pair<Value *, APInt> TrueBaseAndOffset = 13343ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(TrueVal); 13353ec848bcSHaicheng Wu std::pair<Value *, APInt> FalseBaseAndOffset = 13363ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(FalseVal); 13373ec848bcSHaicheng Wu if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) { 13383ec848bcSHaicheng Wu ConstantOffsetPtrs[&SI] = TrueBaseAndOffset; 13393ec848bcSHaicheng Wu 13403ec848bcSHaicheng Wu Value *SROAArg; 13413ec848bcSHaicheng Wu DenseMap<Value *, int>::iterator CostIt; 13423ec848bcSHaicheng Wu if (lookupSROAArgAndCost(TrueVal, SROAArg, CostIt)) 13433ec848bcSHaicheng Wu SROAArgValues[&SI] = SROAArg; 13443ec848bcSHaicheng Wu return true; 13453ec848bcSHaicheng Wu } 13463ec848bcSHaicheng Wu 13473ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 13483ec848bcSHaicheng Wu } 13493ec848bcSHaicheng Wu 13503ec848bcSHaicheng Wu // Select condition is a constant. 13513ec848bcSHaicheng Wu Value *SelectedV = CondC->isAllOnesValue() 13523ec848bcSHaicheng Wu ? TrueVal 13533ec848bcSHaicheng Wu : (CondC->isNullValue()) ? FalseVal : nullptr; 13543ec848bcSHaicheng Wu if (!SelectedV) { 13553ec848bcSHaicheng Wu // Condition is a vector constant that is not all 1s or all 0s. If all 13563ec848bcSHaicheng Wu // operands are constants, ConstantExpr::getSelect() can handle the cases 13573ec848bcSHaicheng Wu // such as select vectors. 13583ec848bcSHaicheng Wu if (TrueC && FalseC) { 13593ec848bcSHaicheng Wu if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) { 13603ec848bcSHaicheng Wu SimplifiedValues[&SI] = C; 13613ec848bcSHaicheng Wu return true; 13623ec848bcSHaicheng Wu } 13633ec848bcSHaicheng Wu } 13643ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 13653ec848bcSHaicheng Wu } 13663ec848bcSHaicheng Wu 13673ec848bcSHaicheng Wu // Condition is either all 1s or all 0s. SI can be simplified. 13683ec848bcSHaicheng Wu if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) { 13693ec848bcSHaicheng Wu SimplifiedValues[&SI] = SelectedC; 13703ec848bcSHaicheng Wu return true; 13713ec848bcSHaicheng Wu } 13723ec848bcSHaicheng Wu 13733ec848bcSHaicheng Wu if (!CheckSROA) 13743ec848bcSHaicheng Wu return true; 13753ec848bcSHaicheng Wu 13763ec848bcSHaicheng Wu std::pair<Value *, APInt> BaseAndOffset = 13773ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(SelectedV); 13783ec848bcSHaicheng Wu if (BaseAndOffset.first) { 13793ec848bcSHaicheng Wu ConstantOffsetPtrs[&SI] = BaseAndOffset; 13803ec848bcSHaicheng Wu 13813ec848bcSHaicheng Wu Value *SROAArg; 13823ec848bcSHaicheng Wu DenseMap<Value *, int>::iterator CostIt; 13833ec848bcSHaicheng Wu if (lookupSROAArgAndCost(SelectedV, SROAArg, CostIt)) 13843ec848bcSHaicheng Wu SROAArgValues[&SI] = SROAArg; 13853ec848bcSHaicheng Wu } 13863ec848bcSHaicheng Wu 13873ec848bcSHaicheng Wu return true; 13883ec848bcSHaicheng Wu } 13893ec848bcSHaicheng Wu 13907adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) { 13917adc3a2bSChandler Carruth // We model unconditional switches as free, see the comments on handling 13927adc3a2bSChandler Carruth // branches. 13937adc3a2bSChandler Carruth if (isa<ConstantInt>(SI.getCondition())) 13947adc3a2bSChandler Carruth return true; 13957adc3a2bSChandler Carruth if (Value *V = SimplifiedValues.lookup(SI.getCondition())) 13967adc3a2bSChandler Carruth if (isa<ConstantInt>(V)) 13977adc3a2bSChandler Carruth return true; 13987adc3a2bSChandler Carruth 13997ad02eeeSEric Christopher // Assume the most general case where the switch is lowered into 1400919f9e8dSJun Bum Lim // either a jump table, bit test, or a balanced binary tree consisting of 1401919f9e8dSJun Bum Lim // case clusters without merging adjacent clusters with the same 1402919f9e8dSJun Bum Lim // destination. We do not consider the switches that are lowered with a mix 1403919f9e8dSJun Bum Lim // of jump table/bit test/binary search tree. The cost of the switch is 1404919f9e8dSJun Bum Lim // proportional to the size of the tree or the size of jump table range. 14052960d41eSJun Bum Lim // 14062960d41eSJun Bum Lim // NB: We convert large switches which are just used to initialize large phi 14072960d41eSJun Bum Lim // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent 14082960d41eSJun Bum Lim // inlining those. It will prevent inlining in cases where the optimization 14092960d41eSJun Bum Lim // does not (yet) fire. 1410919f9e8dSJun Bum Lim 1411506cfb7aSJun Bum Lim // Maximum valid cost increased in this function. 1412506cfb7aSJun Bum Lim int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1; 1413506cfb7aSJun Bum Lim 1414919f9e8dSJun Bum Lim // Exit early for a large switch, assuming one case needs at least one 1415919f9e8dSJun Bum Lim // instruction. 1416919f9e8dSJun Bum Lim // FIXME: This is not true for a bit test, but ignore such case for now to 1417919f9e8dSJun Bum Lim // save compile-time. 1418919f9e8dSJun Bum Lim int64_t CostLowerBound = 1419506cfb7aSJun Bum Lim std::min((int64_t)CostUpperBound, 1420919f9e8dSJun Bum Lim (int64_t)SI.getNumCases() * InlineConstants::InstrCost + Cost); 1421919f9e8dSJun Bum Lim 14220812c5beSHaicheng Wu if (CostLowerBound > Threshold && !ComputeFullInlineCost) { 1423919f9e8dSJun Bum Lim Cost = CostLowerBound; 1424919f9e8dSJun Bum Lim return false; 1425919f9e8dSJun Bum Lim } 1426919f9e8dSJun Bum Lim 1427919f9e8dSJun Bum Lim unsigned JumpTableSize = 0; 1428919f9e8dSJun Bum Lim unsigned NumCaseCluster = 1429919f9e8dSJun Bum Lim TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize); 1430919f9e8dSJun Bum Lim 1431919f9e8dSJun Bum Lim // If suitable for a jump table, consider the cost for the table size and 1432919f9e8dSJun Bum Lim // branch to destination. 1433919f9e8dSJun Bum Lim if (JumpTableSize) { 1434919f9e8dSJun Bum Lim int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost + 1435919f9e8dSJun Bum Lim 4 * InlineConstants::InstrCost; 1436506cfb7aSJun Bum Lim 1437506cfb7aSJun Bum Lim Cost = std::min((int64_t)CostUpperBound, JTCost + Cost); 1438919f9e8dSJun Bum Lim return false; 1439919f9e8dSJun Bum Lim } 1440919f9e8dSJun Bum Lim 1441919f9e8dSJun Bum Lim // Considering forming a binary search, we should find the number of nodes 1442919f9e8dSJun Bum Lim // which is same as the number of comparisons when lowered. For a given 1443919f9e8dSJun Bum Lim // number of clusters, n, we can define a recursive function, f(n), to find 1444919f9e8dSJun Bum Lim // the number of nodes in the tree. The recursion is : 1445919f9e8dSJun Bum Lim // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3, 1446919f9e8dSJun Bum Lim // and f(n) = n, when n <= 3. 1447919f9e8dSJun Bum Lim // This will lead a binary tree where the leaf should be either f(2) or f(3) 1448919f9e8dSJun Bum Lim // when n > 3. So, the number of comparisons from leaves should be n, while 1449919f9e8dSJun Bum Lim // the number of non-leaf should be : 1450919f9e8dSJun Bum Lim // 2^(log2(n) - 1) - 1 1451919f9e8dSJun Bum Lim // = 2^log2(n) * 2^-1 - 1 1452919f9e8dSJun Bum Lim // = n / 2 - 1. 1453919f9e8dSJun Bum Lim // Considering comparisons from leaf and non-leaf nodes, we can estimate the 1454919f9e8dSJun Bum Lim // number of comparisons in a simple closed form : 1455919f9e8dSJun Bum Lim // n + n / 2 - 1 = n * 3 / 2 - 1 1456919f9e8dSJun Bum Lim if (NumCaseCluster <= 3) { 1457919f9e8dSJun Bum Lim // Suppose a comparison includes one compare and one conditional branch. 1458919f9e8dSJun Bum Lim Cost += NumCaseCluster * 2 * InlineConstants::InstrCost; 1459919f9e8dSJun Bum Lim return false; 1460919f9e8dSJun Bum Lim } 1461506cfb7aSJun Bum Lim 1462506cfb7aSJun Bum Lim int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1; 1463506cfb7aSJun Bum Lim int64_t SwitchCost = 1464919f9e8dSJun Bum Lim ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost; 1465506cfb7aSJun Bum Lim 1466506cfb7aSJun Bum Lim Cost = std::min((int64_t)CostUpperBound, SwitchCost + Cost); 1467919f9e8dSJun Bum Lim return false; 1468919f9e8dSJun Bum Lim } 1469919f9e8dSJun Bum Lim 14707adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) { 14717adc3a2bSChandler Carruth // We never want to inline functions that contain an indirectbr. This is 14727adc3a2bSChandler Carruth // incorrect because all the blockaddress's (in static global initializers 14737adc3a2bSChandler Carruth // for example) would be referring to the original function, and this 14747adc3a2bSChandler Carruth // indirect jump would jump from the inlined copy of the function into the 14757adc3a2bSChandler Carruth // original function which is extremely undefined behavior. 14767adc3a2bSChandler Carruth // FIXME: This logic isn't really right; we can safely inline functions with 14777adc3a2bSChandler Carruth // indirectbr's as long as no other function or global references the 14787adc3a2bSChandler Carruth // blockaddress of a block within the current function. 14797adc3a2bSChandler Carruth HasIndirectBr = true; 14807adc3a2bSChandler Carruth return false; 14817adc3a2bSChandler Carruth } 14827adc3a2bSChandler Carruth 14837adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) { 14847adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 14857adc3a2bSChandler Carruth // the inline cost of a resume instruction. 14867adc3a2bSChandler Carruth return false; 14877adc3a2bSChandler Carruth } 14887adc3a2bSChandler Carruth 14897adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) { 14907adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 14917adc3a2bSChandler Carruth // the inline cost of a cleanupret instruction. 14927adc3a2bSChandler Carruth return false; 14937adc3a2bSChandler Carruth } 14947adc3a2bSChandler Carruth 14957adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) { 14967adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 14978220bcc5SJoseph Tremoulet // the inline cost of a catchret instruction. 14987adc3a2bSChandler Carruth return false; 14997adc3a2bSChandler Carruth } 15007adc3a2bSChandler Carruth 15017adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) { 15027adc3a2bSChandler Carruth // FIXME: It might be reasonably to discount the cost of instructions leading 15037adc3a2bSChandler Carruth // to unreachable as they have the lowest possible impact on both runtime and 15047adc3a2bSChandler Carruth // code size. 15057adc3a2bSChandler Carruth return true; // No actual code is needed for unreachable. 15067adc3a2bSChandler Carruth } 15077adc3a2bSChandler Carruth 15087adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) { 15097adc3a2bSChandler Carruth // Some instructions are free. All of the free intrinsics can also be 15107adc3a2bSChandler Carruth // handled by SROA, etc. 15117adc3a2bSChandler Carruth if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I)) 15127adc3a2bSChandler Carruth return true; 15137adc3a2bSChandler Carruth 15147adc3a2bSChandler Carruth // We found something we don't understand or can't handle. Mark any SROA-able 15157adc3a2bSChandler Carruth // values in the operand list as no longer viable. 15167adc3a2bSChandler Carruth for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI) 15177adc3a2bSChandler Carruth disableSROA(*OI); 15187adc3a2bSChandler Carruth 15197adc3a2bSChandler Carruth return false; 15207adc3a2bSChandler Carruth } 15217adc3a2bSChandler Carruth 15227adc3a2bSChandler Carruth /// \brief Analyze a basic block for its contribution to the inline cost. 15237adc3a2bSChandler Carruth /// 15247adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic 15257adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It 15267adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline 15277adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer 15287adc3a2bSChandler Carruth /// viable, and true if inlining remains viable. 15297adc3a2bSChandler Carruth bool CallAnalyzer::analyzeBlock(BasicBlock *BB, 15307adc3a2bSChandler Carruth SmallPtrSetImpl<const Value *> &EphValues) { 15317adc3a2bSChandler Carruth for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 15327adc3a2bSChandler Carruth // FIXME: Currently, the number of instructions in a function regardless of 15337adc3a2bSChandler Carruth // our ability to simplify them during inline to constants or dead code, 15347adc3a2bSChandler Carruth // are actually used by the vector bonus heuristic. As long as that's true, 15357adc3a2bSChandler Carruth // we have to special case debug intrinsics here to prevent differences in 15367adc3a2bSChandler Carruth // inlining due to debug symbols. Eventually, the number of unsimplified 15377adc3a2bSChandler Carruth // instructions shouldn't factor into the cost computation, but until then, 15387adc3a2bSChandler Carruth // hack around it here. 15397adc3a2bSChandler Carruth if (isa<DbgInfoIntrinsic>(I)) 15407adc3a2bSChandler Carruth continue; 15417adc3a2bSChandler Carruth 15427adc3a2bSChandler Carruth // Skip ephemeral values. 15435a82c916SDuncan P. N. Exon Smith if (EphValues.count(&*I)) 15447adc3a2bSChandler Carruth continue; 15457adc3a2bSChandler Carruth 15467adc3a2bSChandler Carruth ++NumInstructions; 15477adc3a2bSChandler Carruth if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy()) 15487adc3a2bSChandler Carruth ++NumVectorInstructions; 15497adc3a2bSChandler Carruth 1550e9434e80SSanjay Patel // If the instruction is floating point, and the target says this operation 1551e9434e80SSanjay Patel // is expensive or the function has the "use-soft-float" attribute, this may 15527adc3a2bSChandler Carruth // eventually become a library call. Treat the cost as such. 15537adc3a2bSChandler Carruth if (I->getType()->isFloatingPointTy()) { 1554e9434e80SSanjay Patel // If the function has the "use-soft-float" attribute, mark it as 1555e9434e80SSanjay Patel // expensive. 15567adc3a2bSChandler Carruth if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive || 1557908ed7f2SEric Christopher (F.getFnAttribute("use-soft-float").getValueAsString() == "true")) 15587adc3a2bSChandler Carruth Cost += InlineConstants::CallPenalty; 15597adc3a2bSChandler Carruth } 15607adc3a2bSChandler Carruth 15617adc3a2bSChandler Carruth // If the instruction simplified to a constant, there is no cost to this 15627adc3a2bSChandler Carruth // instruction. Visit the instructions using our InstVisitor to account for 15637adc3a2bSChandler Carruth // all of the per-instruction logic. The visit tree returns true if we 15647adc3a2bSChandler Carruth // consumed the instruction in any way, and false if the instruction's base 15657adc3a2bSChandler Carruth // cost should count against inlining. 15665a82c916SDuncan P. N. Exon Smith if (Base::visit(&*I)) 15677adc3a2bSChandler Carruth ++NumInstructionsSimplified; 15687adc3a2bSChandler Carruth else 15697adc3a2bSChandler Carruth Cost += InlineConstants::InstrCost; 15707adc3a2bSChandler Carruth 15710812c5beSHaicheng Wu using namespace ore; 15727adc3a2bSChandler Carruth // If the visit this instruction detected an uninlinable pattern, abort. 15737adc3a2bSChandler Carruth if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca || 15740812c5beSHaicheng Wu HasIndirectBr || HasFrameEscape) { 15750812c5beSHaicheng Wu if (ORE) 15769590658fSVivek Pandya ORE->emit([&]() { 15779590658fSVivek Pandya return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 15780812c5beSHaicheng Wu CandidateCS.getInstruction()) 15790812c5beSHaicheng Wu << NV("Callee", &F) 15809590658fSVivek Pandya << " has uninlinable pattern and cost is not fully computed"; 15819590658fSVivek Pandya }); 15827adc3a2bSChandler Carruth return false; 15830812c5beSHaicheng Wu } 15847adc3a2bSChandler Carruth 15857adc3a2bSChandler Carruth // If the caller is a recursive function then we don't want to inline 15867adc3a2bSChandler Carruth // functions which allocate a lot of stack space because it would increase 15877adc3a2bSChandler Carruth // the caller stack usage dramatically. 15887adc3a2bSChandler Carruth if (IsCallerRecursive && 15890812c5beSHaicheng Wu AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) { 15900812c5beSHaicheng Wu if (ORE) 15919590658fSVivek Pandya ORE->emit([&]() { 15929590658fSVivek Pandya return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 15930812c5beSHaicheng Wu CandidateCS.getInstruction()) 15940812c5beSHaicheng Wu << NV("Callee", &F) 15950812c5beSHaicheng Wu << " is recursive and allocates too much stack space. Cost is " 15969590658fSVivek Pandya "not fully computed"; 15979590658fSVivek Pandya }); 15987adc3a2bSChandler Carruth return false; 15990812c5beSHaicheng Wu } 16007adc3a2bSChandler Carruth 16017adc3a2bSChandler Carruth // Check if we've past the maximum possible threshold so we don't spin in 16027adc3a2bSChandler Carruth // huge basic blocks that will never inline. 160361995364SHaicheng Wu if (Cost >= Threshold && !ComputeFullInlineCost) 16047adc3a2bSChandler Carruth return false; 16057adc3a2bSChandler Carruth } 16067adc3a2bSChandler Carruth 16077adc3a2bSChandler Carruth return true; 16087adc3a2bSChandler Carruth } 16097adc3a2bSChandler Carruth 16107adc3a2bSChandler Carruth /// \brief Compute the base pointer and cumulative constant offsets for V. 16117adc3a2bSChandler Carruth /// 16127adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and 16137adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It 16147adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are 16157adc3a2bSChandler Carruth /// no constant offsets applied. 16167adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) { 16177adc3a2bSChandler Carruth if (!V->getType()->isPointerTy()) 16187adc3a2bSChandler Carruth return nullptr; 16197adc3a2bSChandler Carruth 16207adc3a2bSChandler Carruth unsigned IntPtrWidth = DL.getPointerSizeInBits(); 16217adc3a2bSChandler Carruth APInt Offset = APInt::getNullValue(IntPtrWidth); 16227adc3a2bSChandler Carruth 16237adc3a2bSChandler Carruth // Even though we don't look through PHI nodes, we could be called on an 16247adc3a2bSChandler Carruth // instruction in an unreachable block, which may be on a cycle. 16257adc3a2bSChandler Carruth SmallPtrSet<Value *, 4> Visited; 16267adc3a2bSChandler Carruth Visited.insert(V); 16277adc3a2bSChandler Carruth do { 16287adc3a2bSChandler Carruth if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 16297adc3a2bSChandler Carruth if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset)) 16307adc3a2bSChandler Carruth return nullptr; 16317adc3a2bSChandler Carruth V = GEP->getPointerOperand(); 16327adc3a2bSChandler Carruth } else if (Operator::getOpcode(V) == Instruction::BitCast) { 16337adc3a2bSChandler Carruth V = cast<Operator>(V)->getOperand(0); 16347adc3a2bSChandler Carruth } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 16355ce32728SSanjoy Das if (GA->isInterposable()) 16367adc3a2bSChandler Carruth break; 16377adc3a2bSChandler Carruth V = GA->getAliasee(); 16387adc3a2bSChandler Carruth } else { 16397adc3a2bSChandler Carruth break; 16407adc3a2bSChandler Carruth } 16417adc3a2bSChandler Carruth assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 16427adc3a2bSChandler Carruth } while (Visited.insert(V).second); 16437adc3a2bSChandler Carruth 16447adc3a2bSChandler Carruth Type *IntPtrTy = DL.getIntPtrType(V->getContext()); 16457adc3a2bSChandler Carruth return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset)); 16467adc3a2bSChandler Carruth } 16477adc3a2bSChandler Carruth 16483739e14aSHaicheng Wu /// \brief Find dead blocks due to deleted CFG edges during inlining. 16493739e14aSHaicheng Wu /// 16503739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p 16513739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have 16523739e14aSHaicheng Wu /// no live incoming CFG edges. If one block is found to be dead, we can 16533739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead 16543739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not. 16553739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) { 16563739e14aSHaicheng Wu auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) { 16573739e14aSHaicheng Wu // A CFG edge is dead if the predecessor is dead or the predessor has a 16583739e14aSHaicheng Wu // known successor which is not the one under exam. 16593739e14aSHaicheng Wu return (DeadBlocks.count(Pred) || 16603739e14aSHaicheng Wu (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ)); 16613739e14aSHaicheng Wu }; 16623739e14aSHaicheng Wu 16633739e14aSHaicheng Wu auto IsNewlyDead = [&](BasicBlock *BB) { 16643739e14aSHaicheng Wu // If all the edges to a block are dead, the block is also dead. 16653739e14aSHaicheng Wu return (!DeadBlocks.count(BB) && 16663739e14aSHaicheng Wu llvm::all_of(predecessors(BB), 16673739e14aSHaicheng Wu [&](BasicBlock *P) { return IsEdgeDead(P, BB); })); 16683739e14aSHaicheng Wu }; 16693739e14aSHaicheng Wu 16703739e14aSHaicheng Wu for (BasicBlock *Succ : successors(CurrBB)) { 16713739e14aSHaicheng Wu if (Succ == NextBB || !IsNewlyDead(Succ)) 16723739e14aSHaicheng Wu continue; 16733739e14aSHaicheng Wu SmallVector<BasicBlock *, 4> NewDead; 16743739e14aSHaicheng Wu NewDead.push_back(Succ); 16753739e14aSHaicheng Wu while (!NewDead.empty()) { 16763739e14aSHaicheng Wu BasicBlock *Dead = NewDead.pop_back_val(); 16773739e14aSHaicheng Wu if (DeadBlocks.insert(Dead)) 16783739e14aSHaicheng Wu // Continue growing the dead block lists. 16793739e14aSHaicheng Wu for (BasicBlock *S : successors(Dead)) 16803739e14aSHaicheng Wu if (IsNewlyDead(S)) 16813739e14aSHaicheng Wu NewDead.push_back(S); 16823739e14aSHaicheng Wu } 16833739e14aSHaicheng Wu } 16843739e14aSHaicheng Wu } 16853739e14aSHaicheng Wu 16867adc3a2bSChandler Carruth /// \brief Analyze a call site for potential inlining. 16877adc3a2bSChandler Carruth /// 16887adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not 16897adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous 16907adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost 16917adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by 16927adc3a2bSChandler Carruth /// some artifact of the routine. 16937adc3a2bSChandler Carruth bool CallAnalyzer::analyzeCall(CallSite CS) { 16947adc3a2bSChandler Carruth ++NumCallsAnalyzed; 16957adc3a2bSChandler Carruth 16967adc3a2bSChandler Carruth // Perform some tweaks to the cost and threshold based on the direct 16977adc3a2bSChandler Carruth // callsite information. 16987adc3a2bSChandler Carruth 16997adc3a2bSChandler Carruth // We want to more aggressively inline vector-dense kernels, so up the 17007adc3a2bSChandler Carruth // threshold, and we'll lower it if the % of vector instructions gets too 17017adc3a2bSChandler Carruth // low. Note that these bonuses are some what arbitrary and evolved over time 17027adc3a2bSChandler Carruth // by accident as much as because they are principled bonuses. 17037adc3a2bSChandler Carruth // 17047adc3a2bSChandler Carruth // FIXME: It would be nice to remove all such bonuses. At least it would be 17057adc3a2bSChandler Carruth // nice to base the bonus values on something more scientific. 17067adc3a2bSChandler Carruth assert(NumInstructions == 0); 17077adc3a2bSChandler Carruth assert(NumVectorInstructions == 0); 1708f4bb2f0dSEaswaran Raman 1709f4bb2f0dSEaswaran Raman // Update the threshold based on callsite properties 1710f4bb2f0dSEaswaran Raman updateThreshold(CS, F); 1711f4bb2f0dSEaswaran Raman 17127adc3a2bSChandler Carruth // Speculatively apply all possible bonuses to Threshold. If cost exceeds 17137adc3a2bSChandler Carruth // this Threshold any time, and cost cannot decrease, we can stop processing 17147adc3a2bSChandler Carruth // the rest of the function body. 171551b809bfSEaswaran Raman Threshold += (SingleBBBonus + VectorBonus); 17167adc3a2bSChandler Carruth 1717351d9b01SXinliang David Li // Give out bonuses for the callsite, as the instructions setting them up 1718351d9b01SXinliang David Li // will be gone after inlining. 1719351d9b01SXinliang David Li Cost -= getCallsiteCost(CS, DL); 17207adc3a2bSChandler Carruth 17217adc3a2bSChandler Carruth // If this function uses the coldcc calling convention, prefer not to inline 17227adc3a2bSChandler Carruth // it. 17237adc3a2bSChandler Carruth if (F.getCallingConv() == CallingConv::Cold) 17247adc3a2bSChandler Carruth Cost += InlineConstants::ColdccPenalty; 17257adc3a2bSChandler Carruth 17267adc3a2bSChandler Carruth // Check if we're done. This can happen due to bonuses and penalties. 172761995364SHaicheng Wu if (Cost >= Threshold && !ComputeFullInlineCost) 17287adc3a2bSChandler Carruth return false; 17297adc3a2bSChandler Carruth 17307adc3a2bSChandler Carruth if (F.empty()) 17317adc3a2bSChandler Carruth return true; 17327adc3a2bSChandler Carruth 17339d939c8fSDavide Italiano Function *Caller = CS.getInstruction()->getFunction(); 17347adc3a2bSChandler Carruth // Check if the caller function is recursive itself. 17357adc3a2bSChandler Carruth for (User *U : Caller->users()) { 17367adc3a2bSChandler Carruth CallSite Site(U); 17377adc3a2bSChandler Carruth if (!Site) 17387adc3a2bSChandler Carruth continue; 17397adc3a2bSChandler Carruth Instruction *I = Site.getInstruction(); 17409d939c8fSDavide Italiano if (I->getFunction() == Caller) { 17417adc3a2bSChandler Carruth IsCallerRecursive = true; 17427adc3a2bSChandler Carruth break; 17437adc3a2bSChandler Carruth } 17447adc3a2bSChandler Carruth } 17457adc3a2bSChandler Carruth 17467adc3a2bSChandler Carruth // Populate our simplified values by mapping from function arguments to call 17477adc3a2bSChandler Carruth // arguments with known important simplifications. 17487adc3a2bSChandler Carruth CallSite::arg_iterator CAI = CS.arg_begin(); 17497adc3a2bSChandler Carruth for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end(); 17507adc3a2bSChandler Carruth FAI != FAE; ++FAI, ++CAI) { 17517adc3a2bSChandler Carruth assert(CAI != CS.arg_end()); 17527adc3a2bSChandler Carruth if (Constant *C = dyn_cast<Constant>(CAI)) 17535a82c916SDuncan P. N. Exon Smith SimplifiedValues[&*FAI] = C; 17547adc3a2bSChandler Carruth 17557adc3a2bSChandler Carruth Value *PtrArg = *CAI; 17567adc3a2bSChandler Carruth if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) { 17575a82c916SDuncan P. N. Exon Smith ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue()); 17587adc3a2bSChandler Carruth 17597adc3a2bSChandler Carruth // We can SROA any pointer arguments derived from alloca instructions. 17607adc3a2bSChandler Carruth if (isa<AllocaInst>(PtrArg)) { 17615a82c916SDuncan P. N. Exon Smith SROAArgValues[&*FAI] = PtrArg; 17627adc3a2bSChandler Carruth SROAArgCosts[PtrArg] = 0; 17637adc3a2bSChandler Carruth } 17647adc3a2bSChandler Carruth } 17657adc3a2bSChandler Carruth } 17667adc3a2bSChandler Carruth NumConstantArgs = SimplifiedValues.size(); 17677adc3a2bSChandler Carruth NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size(); 17687adc3a2bSChandler Carruth NumAllocaArgs = SROAArgValues.size(); 17697adc3a2bSChandler Carruth 17707adc3a2bSChandler Carruth // FIXME: If a caller has multiple calls to a callee, we end up recomputing 17717adc3a2bSChandler Carruth // the ephemeral values multiple times (and they're completely determined by 17727adc3a2bSChandler Carruth // the callee, so this is purely duplicate work). 17737adc3a2bSChandler Carruth SmallPtrSet<const Value *, 32> EphValues; 1774aec2fa35SDaniel Jasper CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues); 17757adc3a2bSChandler Carruth 17767adc3a2bSChandler Carruth // The worklist of live basic blocks in the callee *after* inlining. We avoid 17777adc3a2bSChandler Carruth // adding basic blocks of the callee which can be proven to be dead for this 17787adc3a2bSChandler Carruth // particular call site in order to get more accurate cost estimates. This 17797adc3a2bSChandler Carruth // requires a somewhat heavyweight iteration pattern: we need to walk the 17807adc3a2bSChandler Carruth // basic blocks in a breadth-first order as we insert live successors. To 17817adc3a2bSChandler Carruth // accomplish this, prioritizing for small iterations because we exit after 17827adc3a2bSChandler Carruth // crossing our threshold, we use a small-size optimized SetVector. 17837adc3a2bSChandler Carruth typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>, 1784567556aaSChad Rosier SmallPtrSet<BasicBlock *, 16>> 1785567556aaSChad Rosier BBSetVector; 17867adc3a2bSChandler Carruth BBSetVector BBWorklist; 17877adc3a2bSChandler Carruth BBWorklist.insert(&F.getEntryBlock()); 178851b809bfSEaswaran Raman bool SingleBB = true; 17897adc3a2bSChandler Carruth // Note that we *must not* cache the size, this loop grows the worklist. 17907adc3a2bSChandler Carruth for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 17917adc3a2bSChandler Carruth // Bail out the moment we cross the threshold. This means we'll under-count 17927adc3a2bSChandler Carruth // the cost, but only when undercounting doesn't matter. 179361995364SHaicheng Wu if (Cost >= Threshold && !ComputeFullInlineCost) 17947adc3a2bSChandler Carruth break; 17957adc3a2bSChandler Carruth 17967adc3a2bSChandler Carruth BasicBlock *BB = BBWorklist[Idx]; 17977adc3a2bSChandler Carruth if (BB->empty()) 17987adc3a2bSChandler Carruth continue; 17997adc3a2bSChandler Carruth 18007adc3a2bSChandler Carruth // Disallow inlining a blockaddress. A blockaddress only has defined 18017adc3a2bSChandler Carruth // behavior for an indirect branch in the same function, and we do not 18027adc3a2bSChandler Carruth // currently support inlining indirect branches. But, the inliner may not 18037adc3a2bSChandler Carruth // see an indirect branch that ends up being dead code at a particular call 18047adc3a2bSChandler Carruth // site. If the blockaddress escapes the function, e.g., via a global 18057adc3a2bSChandler Carruth // variable, inlining may lead to an invalid cross-function reference. 18067adc3a2bSChandler Carruth if (BB->hasAddressTaken()) 18077adc3a2bSChandler Carruth return false; 18087adc3a2bSChandler Carruth 18097adc3a2bSChandler Carruth // Analyze the cost of this block. If we blow through the threshold, this 18107adc3a2bSChandler Carruth // returns false, and we can bail on out. 1811d295b00aSEaswaran Raman if (!analyzeBlock(BB, EphValues)) 18127adc3a2bSChandler Carruth return false; 18137adc3a2bSChandler Carruth 18147adc3a2bSChandler Carruth TerminatorInst *TI = BB->getTerminator(); 18157adc3a2bSChandler Carruth 18167adc3a2bSChandler Carruth // Add in the live successors by first checking whether we have terminator 18177adc3a2bSChandler Carruth // that may be simplified based on the values simplified by this call. 18187adc3a2bSChandler Carruth if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 18197adc3a2bSChandler Carruth if (BI->isConditional()) { 18207adc3a2bSChandler Carruth Value *Cond = BI->getCondition(); 1821567556aaSChad Rosier if (ConstantInt *SimpleCond = 1822567556aaSChad Rosier dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 18233739e14aSHaicheng Wu BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0); 18243739e14aSHaicheng Wu BBWorklist.insert(NextBB); 18253739e14aSHaicheng Wu KnownSuccessors[BB] = NextBB; 18263739e14aSHaicheng Wu findDeadBlocks(BB, NextBB); 18277adc3a2bSChandler Carruth continue; 18287adc3a2bSChandler Carruth } 18297adc3a2bSChandler Carruth } 18307adc3a2bSChandler Carruth } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 18317adc3a2bSChandler Carruth Value *Cond = SI->getCondition(); 1832567556aaSChad Rosier if (ConstantInt *SimpleCond = 1833567556aaSChad Rosier dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 18343739e14aSHaicheng Wu BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor(); 18353739e14aSHaicheng Wu BBWorklist.insert(NextBB); 18363739e14aSHaicheng Wu KnownSuccessors[BB] = NextBB; 18373739e14aSHaicheng Wu findDeadBlocks(BB, NextBB); 18387adc3a2bSChandler Carruth continue; 18397adc3a2bSChandler Carruth } 18407adc3a2bSChandler Carruth } 18417adc3a2bSChandler Carruth 18427adc3a2bSChandler Carruth // If we're unable to select a particular successor, just count all of 18437adc3a2bSChandler Carruth // them. 18447adc3a2bSChandler Carruth for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize; 18457adc3a2bSChandler Carruth ++TIdx) 18467adc3a2bSChandler Carruth BBWorklist.insert(TI->getSuccessor(TIdx)); 18477adc3a2bSChandler Carruth 18487adc3a2bSChandler Carruth // If we had any successors at this point, than post-inlining is likely to 18497adc3a2bSChandler Carruth // have them as well. Note that we assume any basic blocks which existed 18507adc3a2bSChandler Carruth // due to branches or switches which folded above will also fold after 18517adc3a2bSChandler Carruth // inlining. 18527adc3a2bSChandler Carruth if (SingleBB && TI->getNumSuccessors() > 1) { 18537adc3a2bSChandler Carruth // Take off the bonus we applied to the threshold. 18547adc3a2bSChandler Carruth Threshold -= SingleBBBonus; 18557adc3a2bSChandler Carruth SingleBB = false; 18567adc3a2bSChandler Carruth } 18577adc3a2bSChandler Carruth } 18587adc3a2bSChandler Carruth 185951b809bfSEaswaran Raman bool OnlyOneCallAndLocalLinkage = 186051b809bfSEaswaran Raman F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction(); 18617adc3a2bSChandler Carruth // If this is a noduplicate call, we can still inline as long as 18627adc3a2bSChandler Carruth // inlining this would cause the removal of the caller (so the instruction 18637adc3a2bSChandler Carruth // is not actually duplicated, just moved). 18647adc3a2bSChandler Carruth if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall) 18657adc3a2bSChandler Carruth return false; 18667adc3a2bSChandler Carruth 18677adc3a2bSChandler Carruth // We applied the maximum possible vector bonus at the beginning. Now, 18687adc3a2bSChandler Carruth // subtract the excess bonus, if any, from the Threshold before 18697adc3a2bSChandler Carruth // comparing against Cost. 18707adc3a2bSChandler Carruth if (NumVectorInstructions <= NumInstructions / 10) 187151b809bfSEaswaran Raman Threshold -= VectorBonus; 18727adc3a2bSChandler Carruth else if (NumVectorInstructions <= NumInstructions / 2) 187351b809bfSEaswaran Raman Threshold -= VectorBonus/2; 18747adc3a2bSChandler Carruth 187500ab73dcSHans Wennborg return Cost < std::max(1, Threshold); 18767adc3a2bSChandler Carruth } 18777adc3a2bSChandler Carruth 1878615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 18797adc3a2bSChandler Carruth /// \brief Dump stats about this call's analysis. 1880eb2a2546SYaron Keren LLVM_DUMP_METHOD void CallAnalyzer::dump() { 18817adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n" 18827adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantArgs); 18837adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs); 18847adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumAllocaArgs); 18857adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantPtrCmps); 18867adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantPtrDiffs); 18877adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumInstructionsSimplified); 18887adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumInstructions); 18897adc3a2bSChandler Carruth DEBUG_PRINT_STAT(SROACostSavings); 18907adc3a2bSChandler Carruth DEBUG_PRINT_STAT(SROACostSavingsLost); 1891*a4461515SHaicheng Wu DEBUG_PRINT_STAT(LoadEliminationCost); 18927adc3a2bSChandler Carruth DEBUG_PRINT_STAT(ContainsNoDuplicateCall); 18937adc3a2bSChandler Carruth DEBUG_PRINT_STAT(Cost); 18947adc3a2bSChandler Carruth DEBUG_PRINT_STAT(Threshold); 18957adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT 18967adc3a2bSChandler Carruth } 18977adc3a2bSChandler Carruth #endif 18987adc3a2bSChandler Carruth 18997adc3a2bSChandler Carruth /// \brief Test that there are no attribute conflicts between Caller and Callee 19007adc3a2bSChandler Carruth /// that prevent inlining. 19017adc3a2bSChandler Carruth static bool functionsHaveCompatibleAttributes(Function *Caller, 19027adc3a2bSChandler Carruth Function *Callee, 19037adc3a2bSChandler Carruth TargetTransformInfo &TTI) { 19047adc3a2bSChandler Carruth return TTI.areInlineCompatible(Caller, Callee) && 19051cb242ebSAkira Hatanaka AttributeFuncs::areInlineCompatible(*Caller, *Callee); 19067adc3a2bSChandler Carruth } 19077adc3a2bSChandler Carruth 1908351d9b01SXinliang David Li int llvm::getCallsiteCost(CallSite CS, const DataLayout &DL) { 1909351d9b01SXinliang David Li int Cost = 0; 1910351d9b01SXinliang David Li for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) { 1911351d9b01SXinliang David Li if (CS.isByValArgument(I)) { 1912351d9b01SXinliang David Li // We approximate the number of loads and stores needed by dividing the 1913351d9b01SXinliang David Li // size of the byval type by the target's pointer size. 1914351d9b01SXinliang David Li PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType()); 1915351d9b01SXinliang David Li unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType()); 1916351d9b01SXinliang David Li unsigned PointerSize = DL.getPointerSizeInBits(); 1917351d9b01SXinliang David Li // Ceiling division. 1918351d9b01SXinliang David Li unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize; 1919351d9b01SXinliang David Li 1920351d9b01SXinliang David Li // If it generates more than 8 stores it is likely to be expanded as an 1921351d9b01SXinliang David Li // inline memcpy so we take that as an upper bound. Otherwise we assume 1922351d9b01SXinliang David Li // one load and one store per word copied. 1923351d9b01SXinliang David Li // FIXME: The maxStoresPerMemcpy setting from the target should be used 1924351d9b01SXinliang David Li // here instead of a magic number of 8, but it's not available via 1925351d9b01SXinliang David Li // DataLayout. 1926351d9b01SXinliang David Li NumStores = std::min(NumStores, 8U); 1927351d9b01SXinliang David Li 1928351d9b01SXinliang David Li Cost += 2 * NumStores * InlineConstants::InstrCost; 1929351d9b01SXinliang David Li } else { 1930351d9b01SXinliang David Li // For non-byval arguments subtract off one instruction per call 1931351d9b01SXinliang David Li // argument. 1932351d9b01SXinliang David Li Cost += InlineConstants::InstrCost; 1933351d9b01SXinliang David Li } 1934351d9b01SXinliang David Li } 1935351d9b01SXinliang David Li // The call instruction also disappears after inlining. 1936351d9b01SXinliang David Li Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty; 1937351d9b01SXinliang David Li return Cost; 1938351d9b01SXinliang David Li } 1939351d9b01SXinliang David Li 1940ab6a6837SSean Silva InlineCost llvm::getInlineCost( 19411c57cc2bSEaswaran Raman CallSite CS, const InlineParams &Params, TargetTransformInfo &CalleeTTI, 1942aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 194312585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 19440812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 1945aec2fa35SDaniel Jasper return getInlineCost(CS, CS.getCalledFunction(), Params, CalleeTTI, 19460812c5beSHaicheng Wu GetAssumptionCache, GetBFI, PSI, ORE); 1947b9f7120eSEaswaran Raman } 1948b9f7120eSEaswaran Raman 1949ab6a6837SSean Silva InlineCost llvm::getInlineCost( 19501c57cc2bSEaswaran Raman CallSite CS, Function *Callee, const InlineParams &Params, 1951aec2fa35SDaniel Jasper TargetTransformInfo &CalleeTTI, 1952aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 195312585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 19540812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 1955f4bb2f0dSEaswaran Raman 19567adc3a2bSChandler Carruth // Cannot inline indirect calls. 19577adc3a2bSChandler Carruth if (!Callee) 19587adc3a2bSChandler Carruth return llvm::InlineCost::getNever(); 19597adc3a2bSChandler Carruth 19607adc3a2bSChandler Carruth // Calls to functions with always-inline attributes should be inlined 19617adc3a2bSChandler Carruth // whenever possible. 19627adc3a2bSChandler Carruth if (CS.hasFnAttr(Attribute::AlwaysInline)) { 19637adc3a2bSChandler Carruth if (isInlineViable(*Callee)) 19647adc3a2bSChandler Carruth return llvm::InlineCost::getAlways(); 19657adc3a2bSChandler Carruth return llvm::InlineCost::getNever(); 19667adc3a2bSChandler Carruth } 19677adc3a2bSChandler Carruth 19687adc3a2bSChandler Carruth // Never inline functions with conflicting attributes (unless callee has 19697adc3a2bSChandler Carruth // always-inline attribute). 19705ce28f4fSChad Rosier Function *Caller = CS.getCaller(); 19715ce28f4fSChad Rosier if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI)) 19727adc3a2bSChandler Carruth return llvm::InlineCost::getNever(); 19737adc3a2bSChandler Carruth 19747adc3a2bSChandler Carruth // Don't inline this call if the caller has the optnone attribute. 19755ce28f4fSChad Rosier if (Caller->hasFnAttribute(Attribute::OptimizeNone)) 19767adc3a2bSChandler Carruth return llvm::InlineCost::getNever(); 19777adc3a2bSChandler Carruth 19785ce32728SSanjoy Das // Don't inline functions which can be interposed at link-time. Don't inline 19795ce32728SSanjoy Das // functions marked noinline or call sites marked noinline. 1980107b187dSCraig Topper // Note: inlining non-exact non-interposable functions is fine, since we know 19815ce32728SSanjoy Das // we have *a* correct implementation of the source level function. 1982567556aaSChad Rosier if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) || 1983567556aaSChad Rosier CS.isNoInline()) 19847adc3a2bSChandler Carruth return llvm::InlineCost::getNever(); 19857adc3a2bSChandler Carruth 19867adc3a2bSChandler Carruth DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName() 19874eb18742SChad Rosier << "... (caller:" << Caller->getName() << ")\n"); 19887adc3a2bSChandler Carruth 19890812c5beSHaicheng Wu CallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE, *Callee, CS, 199012585b01SEaswaran Raman Params); 19917adc3a2bSChandler Carruth bool ShouldInline = CA.analyzeCall(CS); 19927adc3a2bSChandler Carruth 19937adc3a2bSChandler Carruth DEBUG(CA.dump()); 19947adc3a2bSChandler Carruth 19957adc3a2bSChandler Carruth // Check if there was a reason to force inlining or no inlining. 19967adc3a2bSChandler Carruth if (!ShouldInline && CA.getCost() < CA.getThreshold()) 19977adc3a2bSChandler Carruth return InlineCost::getNever(); 19987adc3a2bSChandler Carruth if (ShouldInline && CA.getCost() >= CA.getThreshold()) 19997adc3a2bSChandler Carruth return InlineCost::getAlways(); 20007adc3a2bSChandler Carruth 20017adc3a2bSChandler Carruth return llvm::InlineCost::get(CA.getCost(), CA.getThreshold()); 20027adc3a2bSChandler Carruth } 20037adc3a2bSChandler Carruth 2004b9f7120eSEaswaran Raman bool llvm::isInlineViable(Function &F) { 20057adc3a2bSChandler Carruth bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice); 20067adc3a2bSChandler Carruth for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) { 20077adc3a2bSChandler Carruth // Disallow inlining of functions which contain indirect branches or 20087adc3a2bSChandler Carruth // blockaddresses. 20097adc3a2bSChandler Carruth if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken()) 20107adc3a2bSChandler Carruth return false; 20117adc3a2bSChandler Carruth 20125a82c916SDuncan P. N. Exon Smith for (auto &II : *BI) { 20135a82c916SDuncan P. N. Exon Smith CallSite CS(&II); 20147adc3a2bSChandler Carruth if (!CS) 20157adc3a2bSChandler Carruth continue; 20167adc3a2bSChandler Carruth 20177adc3a2bSChandler Carruth // Disallow recursive calls. 20187adc3a2bSChandler Carruth if (&F == CS.getCalledFunction()) 20197adc3a2bSChandler Carruth return false; 20207adc3a2bSChandler Carruth 20217adc3a2bSChandler Carruth // Disallow calls which expose returns-twice to a function not previously 20227adc3a2bSChandler Carruth // attributed as such. 20237adc3a2bSChandler Carruth if (!ReturnsTwice && CS.isCall() && 20247adc3a2bSChandler Carruth cast<CallInst>(CS.getInstruction())->canReturnTwice()) 20257adc3a2bSChandler Carruth return false; 20267adc3a2bSChandler Carruth 20277adc3a2bSChandler Carruth // Disallow inlining functions that call @llvm.localescape. Doing this 20287adc3a2bSChandler Carruth // correctly would require major changes to the inliner. 20297adc3a2bSChandler Carruth if (CS.getCalledFunction() && 20307adc3a2bSChandler Carruth CS.getCalledFunction()->getIntrinsicID() == 20317adc3a2bSChandler Carruth llvm::Intrinsic::localescape) 20327adc3a2bSChandler Carruth return false; 20337adc3a2bSChandler Carruth } 20347adc3a2bSChandler Carruth } 20357adc3a2bSChandler Carruth 20367adc3a2bSChandler Carruth return true; 20377adc3a2bSChandler Carruth } 20381c57cc2bSEaswaran Raman 20391c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other 20401c57cc2bSEaswaran Raman // parameters. 20411c57cc2bSEaswaran Raman 20421c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) { 20431c57cc2bSEaswaran Raman InlineParams Params; 20441c57cc2bSEaswaran Raman 20451c57cc2bSEaswaran Raman // This field is the threshold to use for a callee by default. This is 20461c57cc2bSEaswaran Raman // derived from one or more of: 20471c57cc2bSEaswaran Raman // * optimization or size-optimization levels, 20481c57cc2bSEaswaran Raman // * a value passed to createFunctionInliningPass function, or 20491c57cc2bSEaswaran Raman // * the -inline-threshold flag. 20501c57cc2bSEaswaran Raman // If the -inline-threshold flag is explicitly specified, that is used 20511c57cc2bSEaswaran Raman // irrespective of anything else. 20521c57cc2bSEaswaran Raman if (InlineThreshold.getNumOccurrences() > 0) 20531c57cc2bSEaswaran Raman Params.DefaultThreshold = InlineThreshold; 20541c57cc2bSEaswaran Raman else 20551c57cc2bSEaswaran Raman Params.DefaultThreshold = Threshold; 20561c57cc2bSEaswaran Raman 20571c57cc2bSEaswaran Raman // Set the HintThreshold knob from the -inlinehint-threshold. 20581c57cc2bSEaswaran Raman Params.HintThreshold = HintThreshold; 20591c57cc2bSEaswaran Raman 20601c57cc2bSEaswaran Raman // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold. 20611c57cc2bSEaswaran Raman Params.HotCallSiteThreshold = HotCallSiteThreshold; 20621c57cc2bSEaswaran Raman 2063974d4eeaSEaswaran Raman // If the -locally-hot-callsite-threshold is explicitly specified, use it to 2064974d4eeaSEaswaran Raman // populate LocallyHotCallSiteThreshold. Later, we populate 2065974d4eeaSEaswaran Raman // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if 2066974d4eeaSEaswaran Raman // we know that optimization level is O3 (in the getInlineParams variant that 2067974d4eeaSEaswaran Raman // takes the opt and size levels). 2068974d4eeaSEaswaran Raman // FIXME: Remove this check (and make the assignment unconditional) after 2069974d4eeaSEaswaran Raman // addressing size regression issues at O2. 2070974d4eeaSEaswaran Raman if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0) 2071974d4eeaSEaswaran Raman Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2072974d4eeaSEaswaran Raman 207312585b01SEaswaran Raman // Set the ColdCallSiteThreshold knob from the -inline-cold-callsite-threshold. 207412585b01SEaswaran Raman Params.ColdCallSiteThreshold = ColdCallSiteThreshold; 207512585b01SEaswaran Raman 20761c57cc2bSEaswaran Raman // Set the OptMinSizeThreshold and OptSizeThreshold params only if the 20771c57cc2bSEaswaran Raman // -inlinehint-threshold commandline option is not explicitly given. If that 20781c57cc2bSEaswaran Raman // option is present, then its value applies even for callees with size and 20791c57cc2bSEaswaran Raman // minsize attributes. 20801c57cc2bSEaswaran Raman // If the -inline-threshold is not specified, set the ColdThreshold from the 20811c57cc2bSEaswaran Raman // -inlinecold-threshold even if it is not explicitly passed. If 20821c57cc2bSEaswaran Raman // -inline-threshold is specified, then -inlinecold-threshold needs to be 20831c57cc2bSEaswaran Raman // explicitly specified to set the ColdThreshold knob 20841c57cc2bSEaswaran Raman if (InlineThreshold.getNumOccurrences() == 0) { 20851c57cc2bSEaswaran Raman Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold; 20861c57cc2bSEaswaran Raman Params.OptSizeThreshold = InlineConstants::OptSizeThreshold; 20871c57cc2bSEaswaran Raman Params.ColdThreshold = ColdThreshold; 20881c57cc2bSEaswaran Raman } else if (ColdThreshold.getNumOccurrences() > 0) { 20891c57cc2bSEaswaran Raman Params.ColdThreshold = ColdThreshold; 20901c57cc2bSEaswaran Raman } 20911c57cc2bSEaswaran Raman return Params; 20921c57cc2bSEaswaran Raman } 20931c57cc2bSEaswaran Raman 20941c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() { 20951c57cc2bSEaswaran Raman return getInlineParams(InlineThreshold); 20961c57cc2bSEaswaran Raman } 20971c57cc2bSEaswaran Raman 20981c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the 20991c57cc2bSEaswaran Raman // size opt level. 21001c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel, 21011c57cc2bSEaswaran Raman unsigned SizeOptLevel) { 21021c57cc2bSEaswaran Raman if (OptLevel > 2) 21031c57cc2bSEaswaran Raman return InlineConstants::OptAggressiveThreshold; 21041c57cc2bSEaswaran Raman if (SizeOptLevel == 1) // -Os 21051c57cc2bSEaswaran Raman return InlineConstants::OptSizeThreshold; 21061c57cc2bSEaswaran Raman if (SizeOptLevel == 2) // -Oz 21071c57cc2bSEaswaran Raman return InlineConstants::OptMinSizeThreshold; 21081c57cc2bSEaswaran Raman return InlineThreshold; 21091c57cc2bSEaswaran Raman } 21101c57cc2bSEaswaran Raman 21111c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) { 2112974d4eeaSEaswaran Raman auto Params = 2113974d4eeaSEaswaran Raman getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel)); 2114974d4eeaSEaswaran Raman // At O3, use the value of -locally-hot-callsite-threshold option to populate 2115974d4eeaSEaswaran Raman // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only 2116974d4eeaSEaswaran Raman // when it is specified explicitly. 2117974d4eeaSEaswaran Raman if (OptLevel > 2) 2118974d4eeaSEaswaran Raman Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2119974d4eeaSEaswaran Raman return Params; 21201c57cc2bSEaswaran Raman } 2121