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" 28a4461515SHaicheng Wu #include "llvm/Analysis/ValueTracking.h" 29432a3883SNico Weber #include "llvm/Config/llvm-config.h" 307adc3a2bSChandler Carruth #include "llvm/IR/CallSite.h" 317adc3a2bSChandler Carruth #include "llvm/IR/CallingConv.h" 327adc3a2bSChandler Carruth #include "llvm/IR/DataLayout.h" 337adc3a2bSChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h" 347adc3a2bSChandler Carruth #include "llvm/IR/GlobalAlias.h" 357adc3a2bSChandler Carruth #include "llvm/IR/InstVisitor.h" 367adc3a2bSChandler Carruth #include "llvm/IR/IntrinsicInst.h" 377adc3a2bSChandler Carruth #include "llvm/IR/Operator.h" 387adc3a2bSChandler Carruth #include "llvm/Support/Debug.h" 397adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h" 407adc3a2bSChandler Carruth 417adc3a2bSChandler Carruth using namespace llvm; 427adc3a2bSChandler Carruth 437adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost" 447adc3a2bSChandler Carruth 457adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed"); 467adc3a2bSChandler Carruth 471c57cc2bSEaswaran Raman static cl::opt<int> InlineThreshold( 48f4bb2f0dSEaswaran Raman "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore, 49f4bb2f0dSEaswaran Raman cl::desc("Control the amount of inlining to perform (default = 225)")); 50f4bb2f0dSEaswaran Raman 51f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold( 52f4bb2f0dSEaswaran Raman "inlinehint-threshold", cl::Hidden, cl::init(325), 53f4bb2f0dSEaswaran Raman cl::desc("Threshold for inlining functions with inline hint")); 54f4bb2f0dSEaswaran Raman 5512585b01SEaswaran Raman static cl::opt<int> 5612585b01SEaswaran Raman ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden, 5712585b01SEaswaran Raman cl::init(45), 5812585b01SEaswaran Raman cl::desc("Threshold for inlining cold callsites")); 5912585b01SEaswaran Raman 60f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based 61f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and 62f4bb2f0dSEaswaran Raman // BFI. 63f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold( 64c103ef89SEaswaran Raman "inlinecold-threshold", cl::Hidden, cl::init(45), 65f4bb2f0dSEaswaran Raman cl::desc("Threshold for inlining functions with cold attribute")); 66f4bb2f0dSEaswaran Raman 67de39cb93SDehao Chen static cl::opt<int> 68de39cb93SDehao Chen HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000), 69de39cb93SDehao Chen cl::ZeroOrMore, 70de39cb93SDehao Chen cl::desc("Threshold for hot callsites ")); 71de39cb93SDehao Chen 72974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold( 73974d4eeaSEaswaran Raman "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore, 74974d4eeaSEaswaran Raman cl::desc("Threshold for locally hot callsites ")); 75974d4eeaSEaswaran Raman 76c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq( 77c5fa6358SEaswaran Raman "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, 78c5fa6358SEaswaran Raman cl::desc("Maxmimum block frequency, expressed as a percentage of caller's " 79c5fa6358SEaswaran Raman "entry frequency, for a callsite to be cold in the absence of " 80c5fa6358SEaswaran Raman "profile information.")); 81c5fa6358SEaswaran Raman 82974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq( 83974d4eeaSEaswaran Raman "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore, 84ff77cc75SEaswaran Raman cl::desc("Minimum block frequency, expressed as a multiple of caller's " 85974d4eeaSEaswaran Raman "entry frequency, for a callsite to be hot in the absence of " 86974d4eeaSEaswaran Raman "profile information.")); 87974d4eeaSEaswaran Raman 884924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost( 890812c5beSHaicheng Wu "inline-cost-full", cl::Hidden, cl::init(false), 900812c5beSHaicheng Wu cl::desc("Compute the full inline cost of a call site even when the cost " 910812c5beSHaicheng Wu "exceeds the threshold.")); 920812c5beSHaicheng Wu 937adc3a2bSChandler Carruth namespace { 947adc3a2bSChandler Carruth 957adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> { 967adc3a2bSChandler Carruth typedef InstVisitor<CallAnalyzer, bool> Base; 977adc3a2bSChandler Carruth friend class InstVisitor<CallAnalyzer, bool>; 987adc3a2bSChandler Carruth 997adc3a2bSChandler Carruth /// The TargetTransformInfo available for this compilation. 1007adc3a2bSChandler Carruth const TargetTransformInfo &TTI; 1017adc3a2bSChandler Carruth 102aec2fa35SDaniel Jasper /// Getter for the cache of @llvm.assume intrinsics. 103aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache; 104aec2fa35SDaniel Jasper 10512585b01SEaswaran Raman /// Getter for BlockFrequencyInfo 10612585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI; 10712585b01SEaswaran Raman 10871069cf6SEaswaran Raman /// Profile summary information. 10971069cf6SEaswaran Raman ProfileSummaryInfo *PSI; 11071069cf6SEaswaran Raman 111f3d122cdSPiotr Padlewski /// The called function. 1127adc3a2bSChandler Carruth Function &F; 1137adc3a2bSChandler Carruth 11485be8ca8SEric Christopher // Cache the DataLayout since we use it a lot. 11585be8ca8SEric Christopher const DataLayout &DL; 11685be8ca8SEric Christopher 1170812c5beSHaicheng Wu /// The OptimizationRemarkEmitter available for this compilation. 1180812c5beSHaicheng Wu OptimizationRemarkEmitter *ORE; 1190812c5beSHaicheng Wu 120f3d122cdSPiotr Padlewski /// The candidate callsite being analyzed. Please do not use this to do 121f3d122cdSPiotr Padlewski /// analysis in the caller function; we want the inline cost query to be 122f3d122cdSPiotr Padlewski /// easily cacheable. Instead, use the cover function paramHasAttr. 1237adc3a2bSChandler Carruth CallSite CandidateCS; 1247adc3a2bSChandler Carruth 125f3d122cdSPiotr Padlewski /// Tunable parameters that control the analysis. 1261c57cc2bSEaswaran Raman const InlineParams &Params; 1271c57cc2bSEaswaran Raman 1287adc3a2bSChandler Carruth int Threshold; 1297adc3a2bSChandler Carruth int Cost; 1304924bb00SEaswaran Raman bool ComputeFullInlineCost; 1317adc3a2bSChandler Carruth 1327adc3a2bSChandler Carruth bool IsCallerRecursive; 1337adc3a2bSChandler Carruth bool IsRecursiveCall; 1347adc3a2bSChandler Carruth bool ExposesReturnsTwice; 1357adc3a2bSChandler Carruth bool HasDynamicAlloca; 1367adc3a2bSChandler Carruth bool ContainsNoDuplicateCall; 1377adc3a2bSChandler Carruth bool HasReturn; 1387adc3a2bSChandler Carruth bool HasIndirectBr; 1394296ea72SVitaly Buka bool HasUninlineableIntrinsic; 140*77beee41SSameer AbuAsal bool InitsVargArgs; 1417adc3a2bSChandler Carruth 1427adc3a2bSChandler Carruth /// Number of bytes allocated statically by the callee. 1437adc3a2bSChandler Carruth uint64_t AllocatedSize; 1447adc3a2bSChandler Carruth unsigned NumInstructions, NumVectorInstructions; 14551b809bfSEaswaran Raman int VectorBonus, TenPercentVectorBonus; 14651b809bfSEaswaran Raman // Bonus to be applied when the callee has only one reachable basic block. 14751b809bfSEaswaran Raman int SingleBBBonus; 1487adc3a2bSChandler Carruth 149f3d122cdSPiotr Padlewski /// While we walk the potentially-inlined instructions, we build up and 150f3d122cdSPiotr Padlewski /// maintain a mapping of simplified values specific to this callsite. The 151f3d122cdSPiotr Padlewski /// idea is to propagate any special information we have about arguments to 152f3d122cdSPiotr Padlewski /// this call through the inlinable section of the function, and account for 153f3d122cdSPiotr Padlewski /// likely simplifications post-inlining. The most important aspect we track 154f3d122cdSPiotr Padlewski /// is CFG altering simplifications -- when we prove a basic block dead, that 155f3d122cdSPiotr Padlewski /// can cause dramatic shifts in the cost of inlining a function. 1567adc3a2bSChandler Carruth DenseMap<Value *, Constant *> SimplifiedValues; 1577adc3a2bSChandler Carruth 158f3d122cdSPiotr Padlewski /// Keep track of the values which map back (through function arguments) to 159f3d122cdSPiotr Padlewski /// allocas on the caller stack which could be simplified through SROA. 1607adc3a2bSChandler Carruth DenseMap<Value *, Value *> SROAArgValues; 1617adc3a2bSChandler Carruth 162f3d122cdSPiotr Padlewski /// The mapping of caller Alloca values to their accumulated cost savings. If 163f3d122cdSPiotr Padlewski /// we have to disable SROA for one of the allocas, this tells us how much 164f3d122cdSPiotr Padlewski /// cost must be added. 1657adc3a2bSChandler Carruth DenseMap<Value *, int> SROAArgCosts; 1667adc3a2bSChandler Carruth 167f3d122cdSPiotr Padlewski /// Keep track of values which map to a pointer base and constant offset. 1687adc3a2bSChandler Carruth DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs; 1697adc3a2bSChandler Carruth 1703739e14aSHaicheng Wu /// Keep track of dead blocks due to the constant arguments. 1713739e14aSHaicheng Wu SetVector<BasicBlock *> DeadBlocks; 1723739e14aSHaicheng Wu 1733739e14aSHaicheng Wu /// The mapping of the blocks to their known unique successors due to the 1743739e14aSHaicheng Wu /// constant arguments. 1753739e14aSHaicheng Wu DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors; 1763739e14aSHaicheng Wu 177a4461515SHaicheng Wu /// Model the elimination of repeated loads that is expected to happen 178a4461515SHaicheng Wu /// whenever we simplify away the stores that would otherwise cause them to be 179a4461515SHaicheng Wu /// loads. 180a4461515SHaicheng Wu bool EnableLoadElimination; 181a4461515SHaicheng Wu SmallPtrSet<Value *, 16> LoadAddrSet; 182a4461515SHaicheng Wu int LoadEliminationCost; 183a4461515SHaicheng Wu 1847adc3a2bSChandler Carruth // Custom simplification helper routines. 1857adc3a2bSChandler Carruth bool isAllocaDerivedArg(Value *V); 1867adc3a2bSChandler Carruth bool lookupSROAArgAndCost(Value *V, Value *&Arg, 1877adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator &CostIt); 1887adc3a2bSChandler Carruth void disableSROA(DenseMap<Value *, int>::iterator CostIt); 1897adc3a2bSChandler Carruth void disableSROA(Value *V); 1903739e14aSHaicheng Wu void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB); 1917adc3a2bSChandler Carruth void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt, 1927adc3a2bSChandler Carruth int InstructionCost); 193a4461515SHaicheng Wu void disableLoadElimination(); 194201b191bSHaicheng Wu bool isGEPFree(GetElementPtrInst &GEP); 195d3558b5dSEvgeny Astigeevich bool canFoldInboundsGEP(GetElementPtrInst &I); 1967adc3a2bSChandler Carruth bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset); 1977adc3a2bSChandler Carruth bool simplifyCallSite(Function *F, CallSite CS); 198617f6364SEaswaran Raman template <typename Callable> 199617f6364SEaswaran Raman bool simplifyInstruction(Instruction &I, Callable Evaluate); 2007adc3a2bSChandler Carruth ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V); 2017adc3a2bSChandler Carruth 2027adc3a2bSChandler Carruth /// Return true if the given argument to the function being considered for 2037adc3a2bSChandler Carruth /// inlining has the given attribute set either at the call site or the 2047adc3a2bSChandler Carruth /// function declaration. Primarily used to inspect call site specific 2057adc3a2bSChandler Carruth /// attributes since these can be more precise than the ones on the callee 2067adc3a2bSChandler Carruth /// itself. 2077adc3a2bSChandler Carruth bool paramHasAttr(Argument *A, Attribute::AttrKind Attr); 2087adc3a2bSChandler Carruth 2097adc3a2bSChandler Carruth /// Return true if the given value is known non null within the callee if 2107adc3a2bSChandler Carruth /// inlined through this particular callsite. 2117adc3a2bSChandler Carruth bool isKnownNonNullInCallee(Value *V); 2127adc3a2bSChandler Carruth 213f4bb2f0dSEaswaran Raman /// Update Threshold based on callsite properties such as callee 214f4bb2f0dSEaswaran Raman /// attributes and callee hotness for PGO builds. The Callee is explicitly 215f4bb2f0dSEaswaran Raman /// passed to support analyzing indirect calls whose target is inferred by 216f4bb2f0dSEaswaran Raman /// analysis. 217f4bb2f0dSEaswaran Raman void updateThreshold(CallSite CS, Function &Callee); 218f4bb2f0dSEaswaran Raman 2199a3fc17aSEaswaran Raman /// Return true if size growth is allowed when inlining the callee at CS. 2209a3fc17aSEaswaran Raman bool allowSizeGrowth(CallSite CS); 2219a3fc17aSEaswaran Raman 222c5fa6358SEaswaran Raman /// Return true if \p CS is a cold callsite. 223c5fa6358SEaswaran Raman bool isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI); 224c5fa6358SEaswaran Raman 225974d4eeaSEaswaran Raman /// Return a higher threshold if \p CS is a hot callsite. 226974d4eeaSEaswaran Raman Optional<int> getHotCallSiteThreshold(CallSite CS, 227974d4eeaSEaswaran Raman BlockFrequencyInfo *CallerBFI); 228974d4eeaSEaswaran Raman 2297adc3a2bSChandler Carruth // Custom analysis routines. 230c0aa4b75SDavid Bolvansky InlineResult analyzeBlock(BasicBlock *BB, 231c0aa4b75SDavid Bolvansky SmallPtrSetImpl<const Value *> &EphValues); 2327adc3a2bSChandler Carruth 2337adc3a2bSChandler Carruth // Disable several entry points to the visitor so we don't accidentally use 2347adc3a2bSChandler Carruth // them by declaring but not defining them here. 235567556aaSChad Rosier void visit(Module *); 236567556aaSChad Rosier void visit(Module &); 237567556aaSChad Rosier void visit(Function *); 238567556aaSChad Rosier void visit(Function &); 239567556aaSChad Rosier void visit(BasicBlock *); 240567556aaSChad Rosier void visit(BasicBlock &); 2417adc3a2bSChandler Carruth 2427adc3a2bSChandler Carruth // Provide base case for our instruction visit. 2437adc3a2bSChandler Carruth bool visitInstruction(Instruction &I); 2447adc3a2bSChandler Carruth 2457adc3a2bSChandler Carruth // Our visit overrides. 2467adc3a2bSChandler Carruth bool visitAlloca(AllocaInst &I); 2477adc3a2bSChandler Carruth bool visitPHI(PHINode &I); 2487adc3a2bSChandler Carruth bool visitGetElementPtr(GetElementPtrInst &I); 2497adc3a2bSChandler Carruth bool visitBitCast(BitCastInst &I); 2507adc3a2bSChandler Carruth bool visitPtrToInt(PtrToIntInst &I); 2517adc3a2bSChandler Carruth bool visitIntToPtr(IntToPtrInst &I); 2527adc3a2bSChandler Carruth bool visitCastInst(CastInst &I); 2537adc3a2bSChandler Carruth bool visitUnaryInstruction(UnaryInstruction &I); 2547adc3a2bSChandler Carruth bool visitCmpInst(CmpInst &I); 2557adc3a2bSChandler Carruth bool visitSub(BinaryOperator &I); 2567adc3a2bSChandler Carruth bool visitBinaryOperator(BinaryOperator &I); 2577adc3a2bSChandler Carruth bool visitLoad(LoadInst &I); 2587adc3a2bSChandler Carruth bool visitStore(StoreInst &I); 2597adc3a2bSChandler Carruth bool visitExtractValue(ExtractValueInst &I); 2607adc3a2bSChandler Carruth bool visitInsertValue(InsertValueInst &I); 2617adc3a2bSChandler Carruth bool visitCallSite(CallSite CS); 2627adc3a2bSChandler Carruth bool visitReturnInst(ReturnInst &RI); 2637adc3a2bSChandler Carruth bool visitBranchInst(BranchInst &BI); 2643ec848bcSHaicheng Wu bool visitSelectInst(SelectInst &SI); 2657adc3a2bSChandler Carruth bool visitSwitchInst(SwitchInst &SI); 2667adc3a2bSChandler Carruth bool visitIndirectBrInst(IndirectBrInst &IBI); 2677adc3a2bSChandler Carruth bool visitResumeInst(ResumeInst &RI); 2687adc3a2bSChandler Carruth bool visitCleanupReturnInst(CleanupReturnInst &RI); 2697adc3a2bSChandler Carruth bool visitCatchReturnInst(CatchReturnInst &RI); 2707adc3a2bSChandler Carruth bool visitUnreachableInst(UnreachableInst &I); 2717adc3a2bSChandler Carruth 2727adc3a2bSChandler Carruth public: 273ab6a6837SSean Silva CallAnalyzer(const TargetTransformInfo &TTI, 274aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 27512585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI, 2760812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, 2770812c5beSHaicheng Wu Function &Callee, CallSite CSArg, const InlineParams &Params) 27812585b01SEaswaran Raman : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI), 2790812c5beSHaicheng Wu PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE), 28085be8ca8SEric Christopher CandidateCS(CSArg), Params(Params), Threshold(Params.DefaultThreshold), 2814924bb00SEaswaran Raman Cost(0), ComputeFullInlineCost(OptComputeFullInlineCost || 2824924bb00SEaswaran Raman Params.ComputeFullInlineCost || ORE), 2834924bb00SEaswaran Raman IsCallerRecursive(false), IsRecursiveCall(false), 28485be8ca8SEric Christopher ExposesReturnsTwice(false), HasDynamicAlloca(false), 28585be8ca8SEric Christopher ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false), 286*77beee41SSameer AbuAsal HasUninlineableIntrinsic(false), InitsVargArgs(false), AllocatedSize(0), 2874296ea72SVitaly Buka NumInstructions(0), NumVectorInstructions(0), VectorBonus(0), 2884296ea72SVitaly Buka SingleBBBonus(0), EnableLoadElimination(true), LoadEliminationCost(0), 2894296ea72SVitaly Buka NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0), 2904296ea72SVitaly Buka NumConstantPtrCmps(0), NumConstantPtrDiffs(0), 2914296ea72SVitaly Buka NumInstructionsSimplified(0), SROACostSavings(0), 2924296ea72SVitaly Buka SROACostSavingsLost(0) {} 2937adc3a2bSChandler Carruth 294c0aa4b75SDavid Bolvansky InlineResult analyzeCall(CallSite CS); 2957adc3a2bSChandler Carruth 2967adc3a2bSChandler Carruth int getThreshold() { return Threshold; } 2977adc3a2bSChandler Carruth int getCost() { return Cost; } 2987adc3a2bSChandler Carruth 2997adc3a2bSChandler Carruth // Keep a bunch of stats about the cost savings found so we can print them 3007adc3a2bSChandler Carruth // out when debugging. 3017adc3a2bSChandler Carruth unsigned NumConstantArgs; 3027adc3a2bSChandler Carruth unsigned NumConstantOffsetPtrArgs; 3037adc3a2bSChandler Carruth unsigned NumAllocaArgs; 3047adc3a2bSChandler Carruth unsigned NumConstantPtrCmps; 3057adc3a2bSChandler Carruth unsigned NumConstantPtrDiffs; 3067adc3a2bSChandler Carruth unsigned NumInstructionsSimplified; 3077adc3a2bSChandler Carruth unsigned SROACostSavings; 3087adc3a2bSChandler Carruth unsigned SROACostSavingsLost; 3097adc3a2bSChandler Carruth 3107adc3a2bSChandler Carruth void dump(); 3117adc3a2bSChandler Carruth }; 3127adc3a2bSChandler Carruth 3137adc3a2bSChandler Carruth } // namespace 3147adc3a2bSChandler Carruth 3155f8f34e4SAdrian Prantl /// Test whether the given value is an Alloca-derived function argument. 3167adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) { 3177adc3a2bSChandler Carruth return SROAArgValues.count(V); 3187adc3a2bSChandler Carruth } 3197adc3a2bSChandler Carruth 3205f8f34e4SAdrian Prantl /// Lookup the SROA-candidate argument and cost iterator which V maps to. 3217adc3a2bSChandler Carruth /// Returns false if V does not map to a SROA-candidate. 3227adc3a2bSChandler Carruth bool CallAnalyzer::lookupSROAArgAndCost( 3237adc3a2bSChandler Carruth Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) { 3247adc3a2bSChandler Carruth if (SROAArgValues.empty() || SROAArgCosts.empty()) 3257adc3a2bSChandler Carruth return false; 3267adc3a2bSChandler Carruth 3277adc3a2bSChandler Carruth DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V); 3287adc3a2bSChandler Carruth if (ArgIt == SROAArgValues.end()) 3297adc3a2bSChandler Carruth return false; 3307adc3a2bSChandler Carruth 3317adc3a2bSChandler Carruth Arg = ArgIt->second; 3327adc3a2bSChandler Carruth CostIt = SROAArgCosts.find(Arg); 3337adc3a2bSChandler Carruth return CostIt != SROAArgCosts.end(); 3347adc3a2bSChandler Carruth } 3357adc3a2bSChandler Carruth 3365f8f34e4SAdrian Prantl /// Disable SROA for the candidate marked by this cost iterator. 3377adc3a2bSChandler Carruth /// 3387adc3a2bSChandler Carruth /// This marks the candidate as no longer viable for SROA, and adds the cost 3397adc3a2bSChandler Carruth /// savings associated with it back into the inline cost measurement. 3407adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) { 3417adc3a2bSChandler Carruth // If we're no longer able to perform SROA we need to undo its cost savings 3427adc3a2bSChandler Carruth // and prevent subsequent analysis. 3437adc3a2bSChandler Carruth Cost += CostIt->second; 3447adc3a2bSChandler Carruth SROACostSavings -= CostIt->second; 3457adc3a2bSChandler Carruth SROACostSavingsLost += CostIt->second; 3467adc3a2bSChandler Carruth SROAArgCosts.erase(CostIt); 347a4461515SHaicheng Wu disableLoadElimination(); 3487adc3a2bSChandler Carruth } 3497adc3a2bSChandler Carruth 3505f8f34e4SAdrian Prantl /// If 'V' maps to a SROA candidate, disable SROA for it. 3517adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) { 3527adc3a2bSChandler Carruth Value *SROAArg; 3537adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 3547adc3a2bSChandler Carruth if (lookupSROAArgAndCost(V, SROAArg, CostIt)) 3557adc3a2bSChandler Carruth disableSROA(CostIt); 3567adc3a2bSChandler Carruth } 3577adc3a2bSChandler Carruth 3585f8f34e4SAdrian Prantl /// Accumulate the given cost for a particular SROA candidate. 3597adc3a2bSChandler Carruth void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt, 3607adc3a2bSChandler Carruth int InstructionCost) { 3617adc3a2bSChandler Carruth CostIt->second += InstructionCost; 3627adc3a2bSChandler Carruth SROACostSavings += InstructionCost; 3637adc3a2bSChandler Carruth } 3647adc3a2bSChandler Carruth 365a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() { 366a4461515SHaicheng Wu if (EnableLoadElimination) { 367a4461515SHaicheng Wu Cost += LoadEliminationCost; 368b3689cabSHaicheng Wu LoadEliminationCost = 0; 369a4461515SHaicheng Wu EnableLoadElimination = false; 370a4461515SHaicheng Wu } 371a4461515SHaicheng Wu } 372a4461515SHaicheng Wu 3735f8f34e4SAdrian Prantl /// Accumulate a constant GEP offset into an APInt if possible. 3747adc3a2bSChandler Carruth /// 3757adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any 3767adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite. 3777adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) { 378945b7e5aSElena Demikhovsky unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType()); 3797adc3a2bSChandler Carruth assert(IntPtrWidth == Offset.getBitWidth()); 3807adc3a2bSChandler Carruth 3817adc3a2bSChandler Carruth for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); 3827adc3a2bSChandler Carruth GTI != GTE; ++GTI) { 3837adc3a2bSChandler Carruth ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 3847adc3a2bSChandler Carruth if (!OpC) 3857adc3a2bSChandler Carruth if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand())) 3867adc3a2bSChandler Carruth OpC = dyn_cast<ConstantInt>(SimpleOp); 3877adc3a2bSChandler Carruth if (!OpC) 3887adc3a2bSChandler Carruth return false; 389567556aaSChad Rosier if (OpC->isZero()) 390567556aaSChad Rosier continue; 3917adc3a2bSChandler Carruth 3927adc3a2bSChandler Carruth // Handle a struct index, which adds its field offset to the pointer. 393ab85225bSPeter Collingbourne if (StructType *STy = GTI.getStructTypeOrNull()) { 3947adc3a2bSChandler Carruth unsigned ElementIdx = OpC->getZExtValue(); 3957adc3a2bSChandler Carruth const StructLayout *SL = DL.getStructLayout(STy); 3967adc3a2bSChandler Carruth Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx)); 3977adc3a2bSChandler Carruth continue; 3987adc3a2bSChandler Carruth } 3997adc3a2bSChandler Carruth 4007adc3a2bSChandler Carruth APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType())); 4017adc3a2bSChandler Carruth Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize; 4027adc3a2bSChandler Carruth } 4037adc3a2bSChandler Carruth return true; 4047adc3a2bSChandler Carruth } 4057adc3a2bSChandler Carruth 4065f8f34e4SAdrian Prantl /// Use TTI to check whether a GEP is free. 407201b191bSHaicheng Wu /// 408201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite. 409201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) { 41061c1bd5aSEvgeny Astigeevich SmallVector<Value *, 4> Operands; 41161c1bd5aSEvgeny Astigeevich Operands.push_back(GEP.getOperand(0)); 412201b191bSHaicheng Wu for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 413201b191bSHaicheng Wu if (Constant *SimpleOp = SimplifiedValues.lookup(*I)) 41461c1bd5aSEvgeny Astigeevich Operands.push_back(SimpleOp); 415201b191bSHaicheng Wu else 41661c1bd5aSEvgeny Astigeevich Operands.push_back(*I); 41761c1bd5aSEvgeny Astigeevich return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands); 418201b191bSHaicheng Wu } 419201b191bSHaicheng Wu 4207adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) { 4217adc3a2bSChandler Carruth // Check whether inlining will turn a dynamic alloca into a static 4220f153424SSanjay Patel // alloca and handle that case. 4237adc3a2bSChandler Carruth if (I.isArrayAllocation()) { 4240f153424SSanjay Patel Constant *Size = SimplifiedValues.lookup(I.getArraySize()); 4250f153424SSanjay Patel if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) { 4267adc3a2bSChandler Carruth Type *Ty = I.getAllocatedType(); 42722eb80a1SEaswaran Raman AllocatedSize = SaturatingMultiplyAdd( 42822eb80a1SEaswaran Raman AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty), AllocatedSize); 4297adc3a2bSChandler Carruth return Base::visitAlloca(I); 4307adc3a2bSChandler Carruth } 4317adc3a2bSChandler Carruth } 4327adc3a2bSChandler Carruth 4337adc3a2bSChandler Carruth // Accumulate the allocated size. 4347adc3a2bSChandler Carruth if (I.isStaticAlloca()) { 4357adc3a2bSChandler Carruth Type *Ty = I.getAllocatedType(); 43622eb80a1SEaswaran Raman AllocatedSize = SaturatingAdd(DL.getTypeAllocSize(Ty), AllocatedSize); 4377adc3a2bSChandler Carruth } 4387adc3a2bSChandler Carruth 4397adc3a2bSChandler Carruth // We will happily inline static alloca instructions. 4407adc3a2bSChandler Carruth if (I.isStaticAlloca()) 4417adc3a2bSChandler Carruth return Base::visitAlloca(I); 4427adc3a2bSChandler Carruth 4437adc3a2bSChandler Carruth // FIXME: This is overly conservative. Dynamic allocas are inefficient for 4447adc3a2bSChandler Carruth // a variety of reasons, and so we would like to not inline them into 4457adc3a2bSChandler Carruth // functions which don't currently have a dynamic alloca. This simply 4467adc3a2bSChandler Carruth // disables inlining altogether in the presence of a dynamic alloca. 4477adc3a2bSChandler Carruth HasDynamicAlloca = true; 4487adc3a2bSChandler Carruth return false; 4497adc3a2bSChandler Carruth } 4507adc3a2bSChandler Carruth 4517adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) { 4527adc3a2bSChandler Carruth // FIXME: We need to propagate SROA *disabling* through phi nodes, even 4537adc3a2bSChandler Carruth // though we don't want to propagate it's bonuses. The idea is to disable 4547adc3a2bSChandler Carruth // SROA if it *might* be used in an inappropriate manner. 4557adc3a2bSChandler Carruth 4567adc3a2bSChandler Carruth // Phi nodes are always zero-cost. 45777f32994SBjorn Pettersson // FIXME: Pointer sizes may differ between different address spaces, so do we 45877f32994SBjorn Pettersson // need to use correct address space in the call to getPointerSizeInBits here? 45977f32994SBjorn Pettersson // Or could we skip the getPointerSizeInBits call completely? As far as I can 46077f32994SBjorn Pettersson // see the ZeroOffset is used as a dummy value, so we can probably use any 46177f32994SBjorn Pettersson // bit width for the ZeroOffset? 46277f32994SBjorn Pettersson APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0)); 4633739e14aSHaicheng Wu bool CheckSROA = I.getType()->isPointerTy(); 4643739e14aSHaicheng Wu 4653739e14aSHaicheng Wu // Track the constant or pointer with constant offset we've seen so far. 4663739e14aSHaicheng Wu Constant *FirstC = nullptr; 4673739e14aSHaicheng Wu std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset}; 4683739e14aSHaicheng Wu Value *FirstV = nullptr; 4693739e14aSHaicheng Wu 4703739e14aSHaicheng Wu for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) { 4713739e14aSHaicheng Wu BasicBlock *Pred = I.getIncomingBlock(i); 4723739e14aSHaicheng Wu // If the incoming block is dead, skip the incoming block. 4733739e14aSHaicheng Wu if (DeadBlocks.count(Pred)) 4743739e14aSHaicheng Wu continue; 4753739e14aSHaicheng Wu // If the parent block of phi is not the known successor of the incoming 4763739e14aSHaicheng Wu // block, skip the incoming block. 4773739e14aSHaicheng Wu BasicBlock *KnownSuccessor = KnownSuccessors[Pred]; 4783739e14aSHaicheng Wu if (KnownSuccessor && KnownSuccessor != I.getParent()) 4793739e14aSHaicheng Wu continue; 4803739e14aSHaicheng Wu 4813739e14aSHaicheng Wu Value *V = I.getIncomingValue(i); 4823739e14aSHaicheng Wu // If the incoming value is this phi itself, skip the incoming value. 4833739e14aSHaicheng Wu if (&I == V) 4843739e14aSHaicheng Wu continue; 4853739e14aSHaicheng Wu 4863739e14aSHaicheng Wu Constant *C = dyn_cast<Constant>(V); 4873739e14aSHaicheng Wu if (!C) 4883739e14aSHaicheng Wu C = SimplifiedValues.lookup(V); 4893739e14aSHaicheng Wu 4903739e14aSHaicheng Wu std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset}; 4913739e14aSHaicheng Wu if (!C && CheckSROA) 4923739e14aSHaicheng Wu BaseAndOffset = ConstantOffsetPtrs.lookup(V); 4933739e14aSHaicheng Wu 4943739e14aSHaicheng Wu if (!C && !BaseAndOffset.first) 4953739e14aSHaicheng Wu // The incoming value is neither a constant nor a pointer with constant 4963739e14aSHaicheng Wu // offset, exit early. 4973739e14aSHaicheng Wu return true; 4983739e14aSHaicheng Wu 4993739e14aSHaicheng Wu if (FirstC) { 5003739e14aSHaicheng Wu if (FirstC == C) 5013739e14aSHaicheng Wu // If we've seen a constant incoming value before and it is the same 5023739e14aSHaicheng Wu // constant we see this time, continue checking the next incoming value. 5033739e14aSHaicheng Wu continue; 5043739e14aSHaicheng Wu // Otherwise early exit because we either see a different constant or saw 5053739e14aSHaicheng Wu // a constant before but we have a pointer with constant offset this time. 5063739e14aSHaicheng Wu return true; 5073739e14aSHaicheng Wu } 5083739e14aSHaicheng Wu 5093739e14aSHaicheng Wu if (FirstV) { 5103739e14aSHaicheng Wu // The same logic as above, but check pointer with constant offset here. 5113739e14aSHaicheng Wu if (FirstBaseAndOffset == BaseAndOffset) 5123739e14aSHaicheng Wu continue; 5133739e14aSHaicheng Wu return true; 5143739e14aSHaicheng Wu } 5153739e14aSHaicheng Wu 5163739e14aSHaicheng Wu if (C) { 5173739e14aSHaicheng Wu // This is the 1st time we've seen a constant, record it. 5183739e14aSHaicheng Wu FirstC = C; 5193739e14aSHaicheng Wu continue; 5203739e14aSHaicheng Wu } 5213739e14aSHaicheng Wu 5223739e14aSHaicheng Wu // The remaining case is that this is the 1st time we've seen a pointer with 5233739e14aSHaicheng Wu // constant offset, record it. 5243739e14aSHaicheng Wu FirstV = V; 5253739e14aSHaicheng Wu FirstBaseAndOffset = BaseAndOffset; 5263739e14aSHaicheng Wu } 5273739e14aSHaicheng Wu 5283739e14aSHaicheng Wu // Check if we can map phi to a constant. 5293739e14aSHaicheng Wu if (FirstC) { 5303739e14aSHaicheng Wu SimplifiedValues[&I] = FirstC; 5313739e14aSHaicheng Wu return true; 5323739e14aSHaicheng Wu } 5333739e14aSHaicheng Wu 5343739e14aSHaicheng Wu // Check if we can map phi to a pointer with constant offset. 5353739e14aSHaicheng Wu if (FirstBaseAndOffset.first) { 5363739e14aSHaicheng Wu ConstantOffsetPtrs[&I] = FirstBaseAndOffset; 5373739e14aSHaicheng Wu 5383739e14aSHaicheng Wu Value *SROAArg; 5393739e14aSHaicheng Wu DenseMap<Value *, int>::iterator CostIt; 5403739e14aSHaicheng Wu if (lookupSROAArgAndCost(FirstV, SROAArg, CostIt)) 5413739e14aSHaicheng Wu SROAArgValues[&I] = SROAArg; 5423739e14aSHaicheng Wu } 5433739e14aSHaicheng Wu 5447adc3a2bSChandler Carruth return true; 5457adc3a2bSChandler Carruth } 5467adc3a2bSChandler Carruth 5475f8f34e4SAdrian Prantl /// Check we can fold GEPs of constant-offset call site argument pointers. 548d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs. 549d3558b5dSEvgeny Astigeevich /// 550d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded. 551d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) { 552d3558b5dSEvgeny Astigeevich // Check if we have a base + offset for the pointer. 553d3558b5dSEvgeny Astigeevich std::pair<Value *, APInt> BaseAndOffset = 554d3558b5dSEvgeny Astigeevich ConstantOffsetPtrs.lookup(I.getPointerOperand()); 555d3558b5dSEvgeny Astigeevich if (!BaseAndOffset.first) 556d3558b5dSEvgeny Astigeevich return false; 557d3558b5dSEvgeny Astigeevich 558d3558b5dSEvgeny Astigeevich // Check if the offset of this GEP is constant, and if so accumulate it 559d3558b5dSEvgeny Astigeevich // into Offset. 560d3558b5dSEvgeny Astigeevich if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) 561d3558b5dSEvgeny Astigeevich return false; 562d3558b5dSEvgeny Astigeevich 563d3558b5dSEvgeny Astigeevich // Add the result as a new mapping to Base + Offset. 564d3558b5dSEvgeny Astigeevich ConstantOffsetPtrs[&I] = BaseAndOffset; 565d3558b5dSEvgeny Astigeevich 566d3558b5dSEvgeny Astigeevich return true; 567d3558b5dSEvgeny Astigeevich } 568d3558b5dSEvgeny Astigeevich 5697adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) { 5707adc3a2bSChandler Carruth Value *SROAArg; 5717adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 572567556aaSChad Rosier bool SROACandidate = 573567556aaSChad Rosier lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt); 5747adc3a2bSChandler Carruth 575a8b9cdc9SEaswaran Raman // Lambda to check whether a GEP's indices are all constant. 576a8b9cdc9SEaswaran Raman auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) { 577a8b9cdc9SEaswaran Raman for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 578a8b9cdc9SEaswaran Raman if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I)) 579a8b9cdc9SEaswaran Raman return false; 580a8b9cdc9SEaswaran Raman return true; 581a8b9cdc9SEaswaran Raman }; 582a8b9cdc9SEaswaran Raman 583d3558b5dSEvgeny Astigeevich if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) { 5847adc3a2bSChandler Carruth if (SROACandidate) 5857adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 5867adc3a2bSChandler Carruth 5877adc3a2bSChandler Carruth // Constant GEPs are modeled as free. 5887adc3a2bSChandler Carruth return true; 5897adc3a2bSChandler Carruth } 5907adc3a2bSChandler Carruth 5917adc3a2bSChandler Carruth // Variable GEPs will require math and will disable SROA. 5927adc3a2bSChandler Carruth if (SROACandidate) 5937adc3a2bSChandler Carruth disableSROA(CostIt); 594201b191bSHaicheng Wu return isGEPFree(I); 5957adc3a2bSChandler Carruth } 5967adc3a2bSChandler Carruth 597617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues. 598617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the 599617f6364SEaswaran Raman /// instruction when all the operands are constants. 600617f6364SEaswaran Raman template <typename Callable> 601617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) { 602617f6364SEaswaran Raman SmallVector<Constant *, 2> COps; 603617f6364SEaswaran Raman for (Value *Op : I.operands()) { 604617f6364SEaswaran Raman Constant *COp = dyn_cast<Constant>(Op); 6057adc3a2bSChandler Carruth if (!COp) 606617f6364SEaswaran Raman COp = SimplifiedValues.lookup(Op); 607617f6364SEaswaran Raman if (!COp) 608617f6364SEaswaran Raman return false; 609617f6364SEaswaran Raman COps.push_back(COp); 610617f6364SEaswaran Raman } 611617f6364SEaswaran Raman auto *C = Evaluate(COps); 612617f6364SEaswaran Raman if (!C) 613617f6364SEaswaran Raman return false; 6147adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 6157adc3a2bSChandler Carruth return true; 6167adc3a2bSChandler Carruth } 6177adc3a2bSChandler Carruth 618617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) { 619617f6364SEaswaran Raman // Propagate constants through bitcasts. 620617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 621617f6364SEaswaran Raman return ConstantExpr::getBitCast(COps[0], I.getType()); 622617f6364SEaswaran Raman })) 623617f6364SEaswaran Raman return true; 624617f6364SEaswaran Raman 6257adc3a2bSChandler Carruth // Track base/offsets through casts 626567556aaSChad Rosier std::pair<Value *, APInt> BaseAndOffset = 627567556aaSChad Rosier ConstantOffsetPtrs.lookup(I.getOperand(0)); 6287adc3a2bSChandler Carruth // Casts don't change the offset, just wrap it up. 6297adc3a2bSChandler Carruth if (BaseAndOffset.first) 6307adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 6317adc3a2bSChandler Carruth 6327adc3a2bSChandler Carruth // Also look for SROA candidates here. 6337adc3a2bSChandler Carruth Value *SROAArg; 6347adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 6357adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) 6367adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 6377adc3a2bSChandler Carruth 6387adc3a2bSChandler Carruth // Bitcasts are always zero cost. 6397adc3a2bSChandler Carruth return true; 6407adc3a2bSChandler Carruth } 6417adc3a2bSChandler Carruth 6427adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) { 6437adc3a2bSChandler Carruth // Propagate constants through ptrtoint. 644617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 645617f6364SEaswaran Raman return ConstantExpr::getPtrToInt(COps[0], I.getType()); 646617f6364SEaswaran Raman })) 6477adc3a2bSChandler Carruth return true; 6487adc3a2bSChandler Carruth 6497adc3a2bSChandler Carruth // Track base/offset pairs when converted to a plain integer provided the 6507adc3a2bSChandler Carruth // integer is large enough to represent the pointer. 6517adc3a2bSChandler Carruth unsigned IntegerSize = I.getType()->getScalarSizeInBits(); 65277f32994SBjorn Pettersson unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace(); 65377f32994SBjorn Pettersson if (IntegerSize >= DL.getPointerSizeInBits(AS)) { 654567556aaSChad Rosier std::pair<Value *, APInt> BaseAndOffset = 655567556aaSChad Rosier ConstantOffsetPtrs.lookup(I.getOperand(0)); 6567adc3a2bSChandler Carruth if (BaseAndOffset.first) 6577adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 6587adc3a2bSChandler Carruth } 6597adc3a2bSChandler Carruth 6607adc3a2bSChandler Carruth // This is really weird. Technically, ptrtoint will disable SROA. However, 6617adc3a2bSChandler Carruth // unless that ptrtoint is *used* somewhere in the live basic blocks after 6627adc3a2bSChandler Carruth // inlining, it will be nuked, and SROA should proceed. All of the uses which 6637adc3a2bSChandler Carruth // would block SROA would also block SROA if applied directly to a pointer, 6647adc3a2bSChandler Carruth // and so we can just add the integer in here. The only places where SROA is 6657adc3a2bSChandler Carruth // preserved either cannot fire on an integer, or won't in-and-of themselves 6667adc3a2bSChandler Carruth // disable SROA (ext) w/o some later use that we would see and disable. 6677adc3a2bSChandler Carruth Value *SROAArg; 6687adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 6697adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) 6707adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 6717adc3a2bSChandler Carruth 6727adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 6737adc3a2bSChandler Carruth } 6747adc3a2bSChandler Carruth 6757adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) { 6767adc3a2bSChandler Carruth // Propagate constants through ptrtoint. 677617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 678617f6364SEaswaran Raman return ConstantExpr::getIntToPtr(COps[0], I.getType()); 679617f6364SEaswaran Raman })) 6807adc3a2bSChandler Carruth return true; 6817adc3a2bSChandler Carruth 6827adc3a2bSChandler Carruth // Track base/offset pairs when round-tripped through a pointer without 6837adc3a2bSChandler Carruth // modifications provided the integer is not too large. 6847adc3a2bSChandler Carruth Value *Op = I.getOperand(0); 6857adc3a2bSChandler Carruth unsigned IntegerSize = Op->getType()->getScalarSizeInBits(); 68677f32994SBjorn Pettersson if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) { 6877adc3a2bSChandler Carruth std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op); 6887adc3a2bSChandler Carruth if (BaseAndOffset.first) 6897adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 6907adc3a2bSChandler Carruth } 6917adc3a2bSChandler Carruth 6927adc3a2bSChandler Carruth // "Propagate" SROA here in the same manner as we do for ptrtoint above. 6937adc3a2bSChandler Carruth Value *SROAArg; 6947adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 6957adc3a2bSChandler Carruth if (lookupSROAArgAndCost(Op, SROAArg, CostIt)) 6967adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 6977adc3a2bSChandler Carruth 6987adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 6997adc3a2bSChandler Carruth } 7007adc3a2bSChandler Carruth 7017adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) { 7027adc3a2bSChandler Carruth // Propagate constants through ptrtoint. 703617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 704617f6364SEaswaran Raman return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType()); 705617f6364SEaswaran Raman })) 7067adc3a2bSChandler Carruth return true; 7077adc3a2bSChandler Carruth 7087adc3a2bSChandler Carruth // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere. 7097adc3a2bSChandler Carruth disableSROA(I.getOperand(0)); 7107adc3a2bSChandler Carruth 71139ed9a60SEli Friedman // If this is a floating-point cast, and the target says this operation 71239ed9a60SEli Friedman // is expensive, this may eventually become a library call. Treat the cost 71339ed9a60SEli Friedman // as such. 71439ed9a60SEli Friedman switch (I.getOpcode()) { 71539ed9a60SEli Friedman case Instruction::FPTrunc: 71639ed9a60SEli Friedman case Instruction::FPExt: 71739ed9a60SEli Friedman case Instruction::UIToFP: 71839ed9a60SEli Friedman case Instruction::SIToFP: 71939ed9a60SEli Friedman case Instruction::FPToUI: 72039ed9a60SEli Friedman case Instruction::FPToSI: 72139ed9a60SEli Friedman if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive) 72239ed9a60SEli Friedman Cost += InlineConstants::CallPenalty; 72339ed9a60SEli Friedman default: 72439ed9a60SEli Friedman break; 72539ed9a60SEli Friedman } 72639ed9a60SEli Friedman 7277adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 7287adc3a2bSChandler Carruth } 7297adc3a2bSChandler Carruth 7307adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) { 7317adc3a2bSChandler Carruth Value *Operand = I.getOperand(0); 732617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 733617f6364SEaswaran Raman return ConstantFoldInstOperands(&I, COps[0], DL); 734617f6364SEaswaran Raman })) 7357adc3a2bSChandler Carruth return true; 7367adc3a2bSChandler Carruth 7377adc3a2bSChandler Carruth // Disable any SROA on the argument to arbitrary unary operators. 7387adc3a2bSChandler Carruth disableSROA(Operand); 7397adc3a2bSChandler Carruth 7407adc3a2bSChandler Carruth return false; 7417adc3a2bSChandler Carruth } 7427adc3a2bSChandler Carruth 7437adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) { 744fb502d2fSReid Kleckner return CandidateCS.paramHasAttr(A->getArgNo(), Attr); 7457adc3a2bSChandler Carruth } 7467adc3a2bSChandler Carruth 7477adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) { 7487adc3a2bSChandler Carruth // Does the *call site* have the NonNull attribute set on an argument? We 7497adc3a2bSChandler Carruth // use the attribute on the call site to memoize any analysis done in the 7507adc3a2bSChandler Carruth // caller. This will also trip if the callee function has a non-null 7517adc3a2bSChandler Carruth // parameter attribute, but that's a less interesting case because hopefully 7527adc3a2bSChandler Carruth // the callee would already have been simplified based on that. 7537adc3a2bSChandler Carruth if (Argument *A = dyn_cast<Argument>(V)) 7547adc3a2bSChandler Carruth if (paramHasAttr(A, Attribute::NonNull)) 7557adc3a2bSChandler Carruth return true; 7567adc3a2bSChandler Carruth 7577adc3a2bSChandler Carruth // Is this an alloca in the caller? This is distinct from the attribute case 7587adc3a2bSChandler Carruth // above because attributes aren't updated within the inliner itself and we 7597adc3a2bSChandler Carruth // always want to catch the alloca derived case. 7607adc3a2bSChandler Carruth if (isAllocaDerivedArg(V)) 7617adc3a2bSChandler Carruth // We can actually predict the result of comparisons between an 7627adc3a2bSChandler Carruth // alloca-derived value and null. Note that this fires regardless of 7637adc3a2bSChandler Carruth // SROA firing. 7647adc3a2bSChandler Carruth return true; 7657adc3a2bSChandler Carruth 7667adc3a2bSChandler Carruth return false; 7677adc3a2bSChandler Carruth } 7687adc3a2bSChandler Carruth 7699a3fc17aSEaswaran Raman bool CallAnalyzer::allowSizeGrowth(CallSite CS) { 7709a3fc17aSEaswaran Raman // If the normal destination of the invoke or the parent block of the call 7719a3fc17aSEaswaran Raman // site is unreachable-terminated, there is little point in inlining this 7729a3fc17aSEaswaran Raman // unless there is literally zero cost. 7739a3fc17aSEaswaran Raman // FIXME: Note that it is possible that an unreachable-terminated block has a 7749a3fc17aSEaswaran Raman // hot entry. For example, in below scenario inlining hot_call_X() may be 7759a3fc17aSEaswaran Raman // beneficial : 7769a3fc17aSEaswaran Raman // main() { 7779a3fc17aSEaswaran Raman // hot_call_1(); 7789a3fc17aSEaswaran Raman // ... 7799a3fc17aSEaswaran Raman // hot_call_N() 7809a3fc17aSEaswaran Raman // exit(0); 7819a3fc17aSEaswaran Raman // } 7829a3fc17aSEaswaran Raman // For now, we are not handling this corner case here as it is rare in real 7839a3fc17aSEaswaran Raman // code. In future, we should elaborate this based on BPI and BFI in more 7849a3fc17aSEaswaran Raman // general threshold adjusting heuristics in updateThreshold(). 7859a3fc17aSEaswaran Raman Instruction *Instr = CS.getInstruction(); 7869a3fc17aSEaswaran Raman if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) { 7879a3fc17aSEaswaran Raman if (isa<UnreachableInst>(II->getNormalDest()->getTerminator())) 7889a3fc17aSEaswaran Raman return false; 7899a3fc17aSEaswaran Raman } else if (isa<UnreachableInst>(Instr->getParent()->getTerminator())) 7909a3fc17aSEaswaran Raman return false; 7919a3fc17aSEaswaran Raman 7929a3fc17aSEaswaran Raman return true; 7939a3fc17aSEaswaran Raman } 7949a3fc17aSEaswaran Raman 795c5fa6358SEaswaran Raman bool CallAnalyzer::isColdCallSite(CallSite CS, BlockFrequencyInfo *CallerBFI) { 796c5fa6358SEaswaran Raman // If global profile summary is available, then callsite's coldness is 797c5fa6358SEaswaran Raman // determined based on that. 798bba762a1SChandler Carruth if (PSI && PSI->hasProfileSummary()) 799c5fa6358SEaswaran Raman return PSI->isColdCallSite(CS, CallerBFI); 800bba762a1SChandler Carruth 801bba762a1SChandler Carruth // Otherwise we need BFI to be available. 802c5fa6358SEaswaran Raman if (!CallerBFI) 803c5fa6358SEaswaran Raman return false; 804c5fa6358SEaswaran Raman 805bba762a1SChandler Carruth // Determine if the callsite is cold relative to caller's entry. We could 806bba762a1SChandler Carruth // potentially cache the computation of scaled entry frequency, but the added 807bba762a1SChandler Carruth // complexity is not worth it unless this scaling shows up high in the 808bba762a1SChandler Carruth // profiles. 809c5fa6358SEaswaran Raman const BranchProbability ColdProb(ColdCallSiteRelFreq, 100); 810c5fa6358SEaswaran Raman auto CallSiteBB = CS.getInstruction()->getParent(); 811c5fa6358SEaswaran Raman auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB); 812c5fa6358SEaswaran Raman auto CallerEntryFreq = 813c5fa6358SEaswaran Raman CallerBFI->getBlockFreq(&(CS.getCaller()->getEntryBlock())); 814c5fa6358SEaswaran Raman return CallSiteFreq < CallerEntryFreq * ColdProb; 815c5fa6358SEaswaran Raman } 816c5fa6358SEaswaran Raman 817974d4eeaSEaswaran Raman Optional<int> 818974d4eeaSEaswaran Raman CallAnalyzer::getHotCallSiteThreshold(CallSite CS, 819974d4eeaSEaswaran Raman BlockFrequencyInfo *CallerBFI) { 820bba762a1SChandler Carruth 821974d4eeaSEaswaran Raman // If global profile summary is available, then callsite's hotness is 822974d4eeaSEaswaran Raman // determined based on that. 823bba762a1SChandler Carruth if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(CS, CallerBFI)) 824bba762a1SChandler Carruth return Params.HotCallSiteThreshold; 825974d4eeaSEaswaran Raman 826bba762a1SChandler Carruth // Otherwise we need BFI to be available and to have a locally hot callsite 827bba762a1SChandler Carruth // threshold. 828bba762a1SChandler Carruth if (!CallerBFI || !Params.LocallyHotCallSiteThreshold) 829974d4eeaSEaswaran Raman return None; 830974d4eeaSEaswaran Raman 831bba762a1SChandler Carruth // Determine if the callsite is hot relative to caller's entry. We could 832bba762a1SChandler Carruth // potentially cache the computation of scaled entry frequency, but the added 833bba762a1SChandler Carruth // complexity is not worth it unless this scaling shows up high in the 834bba762a1SChandler Carruth // profiles. 835974d4eeaSEaswaran Raman auto CallSiteBB = CS.getInstruction()->getParent(); 836974d4eeaSEaswaran Raman auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency(); 837974d4eeaSEaswaran Raman auto CallerEntryFreq = CallerBFI->getEntryFreq(); 838974d4eeaSEaswaran Raman if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq) 839bba762a1SChandler Carruth return Params.LocallyHotCallSiteThreshold; 840bba762a1SChandler Carruth 841bba762a1SChandler Carruth // Otherwise treat it normally. 842974d4eeaSEaswaran Raman return None; 843974d4eeaSEaswaran Raman } 844974d4eeaSEaswaran Raman 845f4bb2f0dSEaswaran Raman void CallAnalyzer::updateThreshold(CallSite CS, Function &Callee) { 8469a3fc17aSEaswaran Raman // If no size growth is allowed for this inlining, set Threshold to 0. 8479a3fc17aSEaswaran Raman if (!allowSizeGrowth(CS)) { 8489a3fc17aSEaswaran Raman Threshold = 0; 8499a3fc17aSEaswaran Raman return; 8509a3fc17aSEaswaran Raman } 8519a3fc17aSEaswaran Raman 852bb578ef0SEaswaran Raman Function *Caller = CS.getCaller(); 8531c57cc2bSEaswaran Raman 8541c57cc2bSEaswaran Raman // return min(A, B) if B is valid. 8551c57cc2bSEaswaran Raman auto MinIfValid = [](int A, Optional<int> B) { 8561c57cc2bSEaswaran Raman return B ? std::min(A, B.getValue()) : A; 8571c57cc2bSEaswaran Raman }; 8581c57cc2bSEaswaran Raman 8590d58fcacSEaswaran Raman // return max(A, B) if B is valid. 8600d58fcacSEaswaran Raman auto MaxIfValid = [](int A, Optional<int> B) { 8610d58fcacSEaswaran Raman return B ? std::max(A, B.getValue()) : A; 8620d58fcacSEaswaran Raman }; 8630d58fcacSEaswaran Raman 86451b809bfSEaswaran Raman // Various bonus percentages. These are multiplied by Threshold to get the 86551b809bfSEaswaran Raman // bonus values. 86651b809bfSEaswaran Raman // SingleBBBonus: This bonus is applied if the callee has a single reachable 86751b809bfSEaswaran Raman // basic block at the given callsite context. This is speculatively applied 86851b809bfSEaswaran Raman // and withdrawn if more than one basic block is seen. 86951b809bfSEaswaran Raman // 87051b809bfSEaswaran Raman // Vector bonuses: We want to more aggressively inline vector-dense kernels 87151b809bfSEaswaran Raman // and apply this bonus based on the percentage of vector instructions. A 87251b809bfSEaswaran Raman // bonus is applied if the vector instructions exceed 50% and half that amount 87351b809bfSEaswaran Raman // is applied if it exceeds 10%. Note that these bonuses are some what 87451b809bfSEaswaran Raman // arbitrary and evolved over time by accident as much as because they are 87551b809bfSEaswaran Raman // principled bonuses. 87651b809bfSEaswaran Raman // FIXME: It would be nice to base the bonus values on something more 87751b809bfSEaswaran Raman // scientific. 87851b809bfSEaswaran Raman // 87951b809bfSEaswaran Raman // LstCallToStaticBonus: This large bonus is applied to ensure the inlining 88051b809bfSEaswaran Raman // of the last call to a static function as inlining such functions is 88151b809bfSEaswaran Raman // guaranteed to reduce code size. 88251b809bfSEaswaran Raman // 88351b809bfSEaswaran Raman // These bonus percentages may be set to 0 based on properties of the caller 88451b809bfSEaswaran Raman // and the callsite. 88551b809bfSEaswaran Raman int SingleBBBonusPercent = 50; 88651b809bfSEaswaran Raman int VectorBonusPercent = 150; 88751b809bfSEaswaran Raman int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus; 88851b809bfSEaswaran Raman 88951b809bfSEaswaran Raman // Lambda to set all the above bonus and bonus percentages to 0. 89051b809bfSEaswaran Raman auto DisallowAllBonuses = [&]() { 89151b809bfSEaswaran Raman SingleBBBonusPercent = 0; 89251b809bfSEaswaran Raman VectorBonusPercent = 0; 89351b809bfSEaswaran Raman LastCallToStaticBonus = 0; 89451b809bfSEaswaran Raman }; 89551b809bfSEaswaran Raman 8961c57cc2bSEaswaran Raman // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available 8971c57cc2bSEaswaran Raman // and reduce the threshold if the caller has the necessary attribute. 89851b809bfSEaswaran Raman if (Caller->optForMinSize()) { 8991c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold); 90051b809bfSEaswaran Raman // For minsize, we want to disable the single BB bonus and the vector 90151b809bfSEaswaran Raman // bonuses, but not the last-call-to-static bonus. Inlining the last call to 90251b809bfSEaswaran Raman // a static function will, at the minimum, eliminate the parameter setup and 90351b809bfSEaswaran Raman // call/return instructions. 90451b809bfSEaswaran Raman SingleBBBonusPercent = 0; 90551b809bfSEaswaran Raman VectorBonusPercent = 0; 90651b809bfSEaswaran Raman } else if (Caller->optForSize()) 9071c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.OptSizeThreshold); 908f4bb2f0dSEaswaran Raman 909e08b139dSEaswaran Raman // Adjust the threshold based on inlinehint attribute and profile based 910e08b139dSEaswaran Raman // hotness information if the caller does not have MinSize attribute. 911e08b139dSEaswaran Raman if (!Caller->optForMinSize()) { 912e08b139dSEaswaran Raman if (Callee.hasFnAttribute(Attribute::InlineHint)) 9130d58fcacSEaswaran Raman Threshold = MaxIfValid(Threshold, Params.HintThreshold); 914bba762a1SChandler Carruth 9153cd1479cSEaswaran Raman // FIXME: After switching to the new passmanager, simplify the logic below 916bba762a1SChandler Carruth // by checking only the callsite hotness/coldness as we will reliably 917bba762a1SChandler Carruth // have local profile information. 9183cd1479cSEaswaran Raman // 919bba762a1SChandler Carruth // Callsite hotness and coldness can be determined if sample profile is 920bba762a1SChandler Carruth // used (which adds hotness metadata to calls) or if caller's 921bba762a1SChandler Carruth // BlockFrequencyInfo is available. 922bba762a1SChandler Carruth BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr; 923974d4eeaSEaswaran Raman auto HotCallSiteThreshold = getHotCallSiteThreshold(CS, CallerBFI); 924974d4eeaSEaswaran Raman if (!Caller->optForSize() && HotCallSiteThreshold) { 925d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Hot callsite.\n"); 926974d4eeaSEaswaran Raman // FIXME: This should update the threshold only if it exceeds the 927974d4eeaSEaswaran Raman // current threshold, but AutoFDO + ThinLTO currently relies on this 928974d4eeaSEaswaran Raman // behavior to prevent inlining of hot callsites during ThinLTO 929974d4eeaSEaswaran Raman // compile phase. 930974d4eeaSEaswaran Raman Threshold = HotCallSiteThreshold.getValue(); 931c5fa6358SEaswaran Raman } else if (isColdCallSite(CS, CallerBFI)) { 932d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Cold callsite.\n"); 93351b809bfSEaswaran Raman // Do not apply bonuses for a cold callsite including the 93451b809bfSEaswaran Raman // LastCallToStatic bonus. While this bonus might result in code size 93551b809bfSEaswaran Raman // reduction, it can cause the size of a non-cold caller to increase 93651b809bfSEaswaran Raman // preventing it from being inlined. 93751b809bfSEaswaran Raman DisallowAllBonuses(); 9383cd1479cSEaswaran Raman Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold); 939bba762a1SChandler Carruth } else if (PSI) { 940bba762a1SChandler Carruth // Use callee's global profile information only if we have no way of 941bba762a1SChandler Carruth // determining this via callsite information. 9423cd1479cSEaswaran Raman if (PSI->isFunctionEntryHot(&Callee)) { 943d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Hot callee.\n"); 944e08b139dSEaswaran Raman // If callsite hotness can not be determined, we may still know 945e08b139dSEaswaran Raman // that the callee is hot and treat it as a weaker hint for threshold 946e08b139dSEaswaran Raman // increase. 947e08b139dSEaswaran Raman Threshold = MaxIfValid(Threshold, Params.HintThreshold); 948e08b139dSEaswaran Raman } else if (PSI->isFunctionEntryCold(&Callee)) { 949d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Cold callee.\n"); 95051b809bfSEaswaran Raman // Do not apply bonuses for a cold callee including the 95151b809bfSEaswaran Raman // LastCallToStatic bonus. While this bonus might result in code size 95251b809bfSEaswaran Raman // reduction, it can cause the size of a non-cold caller to increase 95351b809bfSEaswaran Raman // preventing it from being inlined. 95451b809bfSEaswaran Raman DisallowAllBonuses(); 9551c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.ColdThreshold); 956e08b139dSEaswaran Raman } 957e08b139dSEaswaran Raman } 958e08b139dSEaswaran Raman } 9598650a4daSJustin Lebar 9608650a4daSJustin Lebar // Finally, take the target-specific inlining threshold multiplier into 9618650a4daSJustin Lebar // account. 9628650a4daSJustin Lebar Threshold *= TTI.getInliningThresholdMultiplier(); 96351b809bfSEaswaran Raman 96451b809bfSEaswaran Raman SingleBBBonus = Threshold * SingleBBBonusPercent / 100; 96551b809bfSEaswaran Raman VectorBonus = Threshold * VectorBonusPercent / 100; 96651b809bfSEaswaran Raman 96751b809bfSEaswaran Raman bool OnlyOneCallAndLocalLinkage = 96851b809bfSEaswaran Raman F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction(); 96951b809bfSEaswaran Raman // If there is only one call of the function, and it has internal linkage, 97051b809bfSEaswaran Raman // the cost of inlining it drops dramatically. It may seem odd to update 97151b809bfSEaswaran Raman // Cost in updateThreshold, but the bonus depends on the logic in this method. 97251b809bfSEaswaran Raman if (OnlyOneCallAndLocalLinkage) 97351b809bfSEaswaran Raman Cost -= LastCallToStaticBonus; 974f4bb2f0dSEaswaran Raman } 975f4bb2f0dSEaswaran Raman 9767adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) { 9777adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 9787adc3a2bSChandler Carruth // First try to handle simplified comparisons. 979617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 980617f6364SEaswaran Raman return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]); 981617f6364SEaswaran Raman })) 9827adc3a2bSChandler Carruth return true; 9837adc3a2bSChandler Carruth 9847adc3a2bSChandler Carruth if (I.getOpcode() == Instruction::FCmp) 9857adc3a2bSChandler Carruth return false; 9867adc3a2bSChandler Carruth 9877adc3a2bSChandler Carruth // Otherwise look for a comparison between constant offset pointers with 9887adc3a2bSChandler Carruth // a common base. 9897adc3a2bSChandler Carruth Value *LHSBase, *RHSBase; 9907adc3a2bSChandler Carruth APInt LHSOffset, RHSOffset; 9917adc3a2bSChandler Carruth std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 9927adc3a2bSChandler Carruth if (LHSBase) { 9937adc3a2bSChandler Carruth std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 9947adc3a2bSChandler Carruth if (RHSBase && LHSBase == RHSBase) { 9957adc3a2bSChandler Carruth // We have common bases, fold the icmp to a constant based on the 9967adc3a2bSChandler Carruth // offsets. 9977adc3a2bSChandler Carruth Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 9987adc3a2bSChandler Carruth Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 9997adc3a2bSChandler Carruth if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) { 10007adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 10017adc3a2bSChandler Carruth ++NumConstantPtrCmps; 10027adc3a2bSChandler Carruth return true; 10037adc3a2bSChandler Carruth } 10047adc3a2bSChandler Carruth } 10057adc3a2bSChandler Carruth } 10067adc3a2bSChandler Carruth 10077adc3a2bSChandler Carruth // If the comparison is an equality comparison with null, we can simplify it 10087adc3a2bSChandler Carruth // if we know the value (argument) can't be null 10097adc3a2bSChandler Carruth if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) && 10107adc3a2bSChandler Carruth isKnownNonNullInCallee(I.getOperand(0))) { 10117adc3a2bSChandler Carruth bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE; 10127adc3a2bSChandler Carruth SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType()) 10137adc3a2bSChandler Carruth : ConstantInt::getFalse(I.getType()); 10147adc3a2bSChandler Carruth return true; 10157adc3a2bSChandler Carruth } 10167adc3a2bSChandler Carruth // Finally check for SROA candidates in comparisons. 10177adc3a2bSChandler Carruth Value *SROAArg; 10187adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 10197adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) { 10207adc3a2bSChandler Carruth if (isa<ConstantPointerNull>(I.getOperand(1))) { 10217adc3a2bSChandler Carruth accumulateSROACost(CostIt, InlineConstants::InstrCost); 10227adc3a2bSChandler Carruth return true; 10237adc3a2bSChandler Carruth } 10247adc3a2bSChandler Carruth 10257adc3a2bSChandler Carruth disableSROA(CostIt); 10267adc3a2bSChandler Carruth } 10277adc3a2bSChandler Carruth 10287adc3a2bSChandler Carruth return false; 10297adc3a2bSChandler Carruth } 10307adc3a2bSChandler Carruth 10317adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) { 10327adc3a2bSChandler Carruth // Try to handle a special case: we can fold computing the difference of two 10337adc3a2bSChandler Carruth // constant-related pointers. 10347adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 10357adc3a2bSChandler Carruth Value *LHSBase, *RHSBase; 10367adc3a2bSChandler Carruth APInt LHSOffset, RHSOffset; 10377adc3a2bSChandler Carruth std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 10387adc3a2bSChandler Carruth if (LHSBase) { 10397adc3a2bSChandler Carruth std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 10407adc3a2bSChandler Carruth if (RHSBase && LHSBase == RHSBase) { 10417adc3a2bSChandler Carruth // We have common bases, fold the subtract to a constant based on the 10427adc3a2bSChandler Carruth // offsets. 10437adc3a2bSChandler Carruth Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 10447adc3a2bSChandler Carruth Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 10457adc3a2bSChandler Carruth if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) { 10467adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 10477adc3a2bSChandler Carruth ++NumConstantPtrDiffs; 10487adc3a2bSChandler Carruth return true; 10497adc3a2bSChandler Carruth } 10507adc3a2bSChandler Carruth } 10517adc3a2bSChandler Carruth } 10527adc3a2bSChandler Carruth 10537adc3a2bSChandler Carruth // Otherwise, fall back to the generic logic for simplifying and handling 10547adc3a2bSChandler Carruth // instructions. 10557adc3a2bSChandler Carruth return Base::visitSub(I); 10567adc3a2bSChandler Carruth } 10577adc3a2bSChandler Carruth 10587adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) { 10597adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 10606d14dfe8SHaicheng Wu Constant *CLHS = dyn_cast<Constant>(LHS); 10616d14dfe8SHaicheng Wu if (!CLHS) 10626d14dfe8SHaicheng Wu CLHS = SimplifiedValues.lookup(LHS); 10636d14dfe8SHaicheng Wu Constant *CRHS = dyn_cast<Constant>(RHS); 10646d14dfe8SHaicheng Wu if (!CRHS) 10656d14dfe8SHaicheng Wu CRHS = SimplifiedValues.lookup(RHS); 10666d14dfe8SHaicheng Wu 10677adc3a2bSChandler Carruth Value *SimpleV = nullptr; 10687adc3a2bSChandler Carruth if (auto FI = dyn_cast<FPMathOperator>(&I)) 10696d14dfe8SHaicheng Wu SimpleV = SimplifyFPBinOp(I.getOpcode(), CLHS ? CLHS : LHS, 10706d14dfe8SHaicheng Wu CRHS ? CRHS : RHS, FI->getFastMathFlags(), DL); 10717adc3a2bSChandler Carruth else 10726d14dfe8SHaicheng Wu SimpleV = 10736d14dfe8SHaicheng Wu SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL); 10747adc3a2bSChandler Carruth 10756d14dfe8SHaicheng Wu if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 10766d14dfe8SHaicheng Wu SimplifiedValues[&I] = C; 10776d14dfe8SHaicheng Wu 10786d14dfe8SHaicheng Wu if (SimpleV) 10797adc3a2bSChandler Carruth return true; 10807adc3a2bSChandler Carruth 10817adc3a2bSChandler Carruth // Disable any SROA on arguments to arbitrary, unsimplified binary operators. 10827adc3a2bSChandler Carruth disableSROA(LHS); 10837adc3a2bSChandler Carruth disableSROA(RHS); 10847adc3a2bSChandler Carruth 108539ed9a60SEli Friedman // If the instruction is floating point, and the target says this operation 108639ed9a60SEli Friedman // is expensive, this may eventually become a library call. Treat the cost 108739ed9a60SEli Friedman // as such. 108839ed9a60SEli Friedman if (I.getType()->isFloatingPointTy() && 108939ed9a60SEli Friedman TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive) 109039ed9a60SEli Friedman Cost += InlineConstants::CallPenalty; 109139ed9a60SEli Friedman 10927adc3a2bSChandler Carruth return false; 10937adc3a2bSChandler Carruth } 10947adc3a2bSChandler Carruth 10957adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) { 10967adc3a2bSChandler Carruth Value *SROAArg; 10977adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 10987adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) { 10997adc3a2bSChandler Carruth if (I.isSimple()) { 11007adc3a2bSChandler Carruth accumulateSROACost(CostIt, InlineConstants::InstrCost); 11017adc3a2bSChandler Carruth return true; 11027adc3a2bSChandler Carruth } 11037adc3a2bSChandler Carruth 11047adc3a2bSChandler Carruth disableSROA(CostIt); 11057adc3a2bSChandler Carruth } 11067adc3a2bSChandler Carruth 1107a4461515SHaicheng Wu // If the data is already loaded from this address and hasn't been clobbered 1108a4461515SHaicheng Wu // by any stores or calls, this load is likely to be redundant and can be 1109a4461515SHaicheng Wu // eliminated. 1110a4461515SHaicheng Wu if (EnableLoadElimination && 1111b3689cabSHaicheng Wu !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) { 1112a4461515SHaicheng Wu LoadEliminationCost += InlineConstants::InstrCost; 1113a4461515SHaicheng Wu return true; 1114a4461515SHaicheng Wu } 1115a4461515SHaicheng Wu 11167adc3a2bSChandler Carruth return false; 11177adc3a2bSChandler Carruth } 11187adc3a2bSChandler Carruth 11197adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) { 11207adc3a2bSChandler Carruth Value *SROAArg; 11217adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 11227adc3a2bSChandler Carruth if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) { 11237adc3a2bSChandler Carruth if (I.isSimple()) { 11247adc3a2bSChandler Carruth accumulateSROACost(CostIt, InlineConstants::InstrCost); 11257adc3a2bSChandler Carruth return true; 11267adc3a2bSChandler Carruth } 11277adc3a2bSChandler Carruth 11287adc3a2bSChandler Carruth disableSROA(CostIt); 11297adc3a2bSChandler Carruth } 11307adc3a2bSChandler Carruth 1131a4461515SHaicheng Wu // The store can potentially clobber loads and prevent repeated loads from 1132a4461515SHaicheng Wu // being eliminated. 1133a4461515SHaicheng Wu // FIXME: 1134a4461515SHaicheng Wu // 1. We can probably keep an initial set of eliminatable loads substracted 1135a4461515SHaicheng Wu // from the cost even when we finally see a store. We just need to disable 1136a4461515SHaicheng Wu // *further* accumulation of elimination savings. 1137a4461515SHaicheng Wu // 2. We should probably at some point thread MemorySSA for the callee into 1138a4461515SHaicheng Wu // this and then use that to actually compute *really* precise savings. 1139a4461515SHaicheng Wu disableLoadElimination(); 11407adc3a2bSChandler Carruth return false; 11417adc3a2bSChandler Carruth } 11427adc3a2bSChandler Carruth 11437adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) { 11447adc3a2bSChandler Carruth // Constant folding for extract value is trivial. 1145617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1146617f6364SEaswaran Raman return ConstantExpr::getExtractValue(COps[0], I.getIndices()); 1147617f6364SEaswaran Raman })) 11487adc3a2bSChandler Carruth return true; 11497adc3a2bSChandler Carruth 11507adc3a2bSChandler Carruth // SROA can look through these but give them a cost. 11517adc3a2bSChandler Carruth return false; 11527adc3a2bSChandler Carruth } 11537adc3a2bSChandler Carruth 11547adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) { 11557adc3a2bSChandler Carruth // Constant folding for insert value is trivial. 1156617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1157617f6364SEaswaran Raman return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0], 1158617f6364SEaswaran Raman /*InsertedValueOperand*/ COps[1], 1159617f6364SEaswaran Raman I.getIndices()); 1160617f6364SEaswaran Raman })) 11617adc3a2bSChandler Carruth return true; 11627adc3a2bSChandler Carruth 11637adc3a2bSChandler Carruth // SROA can look through these but give them a cost. 11647adc3a2bSChandler Carruth return false; 11657adc3a2bSChandler Carruth } 11667adc3a2bSChandler Carruth 11675f8f34e4SAdrian Prantl /// Try to simplify a call site. 11687adc3a2bSChandler Carruth /// 11697adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by 11707adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if 11717adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it 11727adc3a2bSChandler Carruth /// free. 11737adc3a2bSChandler Carruth bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) { 11747adc3a2bSChandler Carruth // FIXME: Using the instsimplify logic directly for this is inefficient 11757adc3a2bSChandler Carruth // because we have to continually rebuild the argument list even when no 11767adc3a2bSChandler Carruth // simplifications can be performed. Until that is fixed with remapping 11777adc3a2bSChandler Carruth // inside of instsimplify, directly constant fold calls here. 1178647025f9SAndrew Kaylor if (!canConstantFoldCallTo(CS, F)) 11797adc3a2bSChandler Carruth return false; 11807adc3a2bSChandler Carruth 11817adc3a2bSChandler Carruth // Try to re-map the arguments to constants. 11827adc3a2bSChandler Carruth SmallVector<Constant *, 4> ConstantArgs; 11837adc3a2bSChandler Carruth ConstantArgs.reserve(CS.arg_size()); 1184567556aaSChad Rosier for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; 1185567556aaSChad Rosier ++I) { 11867adc3a2bSChandler Carruth Constant *C = dyn_cast<Constant>(*I); 11877adc3a2bSChandler Carruth if (!C) 11887adc3a2bSChandler Carruth C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I)); 11897adc3a2bSChandler Carruth if (!C) 11907adc3a2bSChandler Carruth return false; // This argument doesn't map to a constant. 11917adc3a2bSChandler Carruth 11927adc3a2bSChandler Carruth ConstantArgs.push_back(C); 11937adc3a2bSChandler Carruth } 1194647025f9SAndrew Kaylor if (Constant *C = ConstantFoldCall(CS, F, ConstantArgs)) { 11957adc3a2bSChandler Carruth SimplifiedValues[CS.getInstruction()] = C; 11967adc3a2bSChandler Carruth return true; 11977adc3a2bSChandler Carruth } 11987adc3a2bSChandler Carruth 11997adc3a2bSChandler Carruth return false; 12007adc3a2bSChandler Carruth } 12017adc3a2bSChandler Carruth 12027adc3a2bSChandler Carruth bool CallAnalyzer::visitCallSite(CallSite CS) { 12037adc3a2bSChandler Carruth if (CS.hasFnAttr(Attribute::ReturnsTwice) && 12047adc3a2bSChandler Carruth !F.hasFnAttribute(Attribute::ReturnsTwice)) { 12057adc3a2bSChandler Carruth // This aborts the entire analysis. 12067adc3a2bSChandler Carruth ExposesReturnsTwice = true; 12077adc3a2bSChandler Carruth return false; 12087adc3a2bSChandler Carruth } 1209567556aaSChad Rosier if (CS.isCall() && cast<CallInst>(CS.getInstruction())->cannotDuplicate()) 12107adc3a2bSChandler Carruth ContainsNoDuplicateCall = true; 12117adc3a2bSChandler Carruth 12127adc3a2bSChandler Carruth if (Function *F = CS.getCalledFunction()) { 12137adc3a2bSChandler Carruth // When we have a concrete function, first try to simplify it directly. 12147adc3a2bSChandler Carruth if (simplifyCallSite(F, CS)) 12157adc3a2bSChandler Carruth return true; 12167adc3a2bSChandler Carruth 12177adc3a2bSChandler Carruth // Next check if it is an intrinsic we know about. 12187adc3a2bSChandler Carruth // FIXME: Lift this into part of the InstVisitor. 12197adc3a2bSChandler Carruth if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) { 12207adc3a2bSChandler Carruth switch (II->getIntrinsicID()) { 12217adc3a2bSChandler Carruth default: 1222a4461515SHaicheng Wu if (!CS.onlyReadsMemory() && !isAssumeLikeIntrinsic(II)) 1223a4461515SHaicheng Wu disableLoadElimination(); 12247adc3a2bSChandler Carruth return Base::visitCallSite(CS); 12257adc3a2bSChandler Carruth 12267dd8dbf4SPeter Collingbourne case Intrinsic::load_relative: 12277dd8dbf4SPeter Collingbourne // This is normally lowered to 4 LLVM instructions. 12287dd8dbf4SPeter Collingbourne Cost += 3 * InlineConstants::InstrCost; 12297dd8dbf4SPeter Collingbourne return false; 12307dd8dbf4SPeter Collingbourne 12317adc3a2bSChandler Carruth case Intrinsic::memset: 12327adc3a2bSChandler Carruth case Intrinsic::memcpy: 12337adc3a2bSChandler Carruth case Intrinsic::memmove: 1234a4461515SHaicheng Wu disableLoadElimination(); 12357adc3a2bSChandler Carruth // SROA can usually chew through these intrinsics, but they aren't free. 12367adc3a2bSChandler Carruth return false; 12374296ea72SVitaly Buka case Intrinsic::icall_branch_funnel: 12387adc3a2bSChandler Carruth case Intrinsic::localescape: 12394296ea72SVitaly Buka HasUninlineableIntrinsic = true; 12407adc3a2bSChandler Carruth return false; 124180788d80SFlorian Hahn case Intrinsic::vastart: 1242*77beee41SSameer AbuAsal InitsVargArgs = true; 124380788d80SFlorian Hahn return false; 12447adc3a2bSChandler Carruth } 12457adc3a2bSChandler Carruth } 12467adc3a2bSChandler Carruth 12479d939c8fSDavide Italiano if (F == CS.getInstruction()->getFunction()) { 12487adc3a2bSChandler Carruth // This flag will fully abort the analysis, so don't bother with anything 12497adc3a2bSChandler Carruth // else. 12507adc3a2bSChandler Carruth IsRecursiveCall = true; 12517adc3a2bSChandler Carruth return false; 12527adc3a2bSChandler Carruth } 12537adc3a2bSChandler Carruth 12547adc3a2bSChandler Carruth if (TTI.isLoweredToCall(F)) { 12557adc3a2bSChandler Carruth // We account for the average 1 instruction per call argument setup 12567adc3a2bSChandler Carruth // here. 12577adc3a2bSChandler Carruth Cost += CS.arg_size() * InlineConstants::InstrCost; 12587adc3a2bSChandler Carruth 12597adc3a2bSChandler Carruth // Everything other than inline ASM will also have a significant cost 12607adc3a2bSChandler Carruth // merely from making the call. 12617adc3a2bSChandler Carruth if (!isa<InlineAsm>(CS.getCalledValue())) 12627adc3a2bSChandler Carruth Cost += InlineConstants::CallPenalty; 12637adc3a2bSChandler Carruth } 12647adc3a2bSChandler Carruth 1265a4461515SHaicheng Wu if (!CS.onlyReadsMemory()) 1266a4461515SHaicheng Wu disableLoadElimination(); 12677adc3a2bSChandler Carruth return Base::visitCallSite(CS); 12687adc3a2bSChandler Carruth } 12697adc3a2bSChandler Carruth 12707adc3a2bSChandler Carruth // Otherwise we're in a very special case -- an indirect function call. See 12717adc3a2bSChandler Carruth // if we can be particularly clever about this. 12727adc3a2bSChandler Carruth Value *Callee = CS.getCalledValue(); 12737adc3a2bSChandler Carruth 12747adc3a2bSChandler Carruth // First, pay the price of the argument setup. We account for the average 12757adc3a2bSChandler Carruth // 1 instruction per call argument setup here. 12767adc3a2bSChandler Carruth Cost += CS.arg_size() * InlineConstants::InstrCost; 12777adc3a2bSChandler Carruth 12787adc3a2bSChandler Carruth // Next, check if this happens to be an indirect function call to a known 12797adc3a2bSChandler Carruth // function in this inline context. If not, we've done all we can. 12807adc3a2bSChandler Carruth Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee)); 1281a4461515SHaicheng Wu if (!F) { 1282a4461515SHaicheng Wu if (!CS.onlyReadsMemory()) 1283a4461515SHaicheng Wu disableLoadElimination(); 12847adc3a2bSChandler Carruth return Base::visitCallSite(CS); 1285a4461515SHaicheng Wu } 12867adc3a2bSChandler Carruth 12877adc3a2bSChandler Carruth // If we have a constant that we are calling as a function, we can peer 12887adc3a2bSChandler Carruth // through it and see the function target. This happens not infrequently 12897adc3a2bSChandler Carruth // during devirtualization and so we want to give it a hefty bonus for 12907adc3a2bSChandler Carruth // inlining, but cap that bonus in the event that inlining wouldn't pan 12917adc3a2bSChandler Carruth // out. Pretend to inline the function, with a custom threshold. 12921c57cc2bSEaswaran Raman auto IndirectCallParams = Params; 12931c57cc2bSEaswaran Raman IndirectCallParams.DefaultThreshold = InlineConstants::IndirectCallThreshold; 12940812c5beSHaicheng Wu CallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F, CS, 129512585b01SEaswaran Raman IndirectCallParams); 12967adc3a2bSChandler Carruth if (CA.analyzeCall(CS)) { 12977adc3a2bSChandler Carruth // We were able to inline the indirect call! Subtract the cost from the 12986d90d9f1SEaswaran Raman // threshold to get the bonus we want to apply, but don't go below zero. 12996d90d9f1SEaswaran Raman Cost -= std::max(0, CA.getThreshold() - CA.getCost()); 13007adc3a2bSChandler Carruth } 13017adc3a2bSChandler Carruth 1302a4461515SHaicheng Wu if (!F->onlyReadsMemory()) 1303a4461515SHaicheng Wu disableLoadElimination(); 13047adc3a2bSChandler Carruth return Base::visitCallSite(CS); 13057adc3a2bSChandler Carruth } 13067adc3a2bSChandler Carruth 13077adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) { 13087adc3a2bSChandler Carruth // At least one return instruction will be free after inlining. 13097adc3a2bSChandler Carruth bool Free = !HasReturn; 13107adc3a2bSChandler Carruth HasReturn = true; 13117adc3a2bSChandler Carruth return Free; 13127adc3a2bSChandler Carruth } 13137adc3a2bSChandler Carruth 13147adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) { 13157adc3a2bSChandler Carruth // We model unconditional branches as essentially free -- they really 13167adc3a2bSChandler Carruth // shouldn't exist at all, but handling them makes the behavior of the 13177adc3a2bSChandler Carruth // inliner more regular and predictable. Interestingly, conditional branches 13187adc3a2bSChandler Carruth // which will fold away are also free. 13197adc3a2bSChandler Carruth return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) || 13207adc3a2bSChandler Carruth dyn_cast_or_null<ConstantInt>( 13217adc3a2bSChandler Carruth SimplifiedValues.lookup(BI.getCondition())); 13227adc3a2bSChandler Carruth } 13237adc3a2bSChandler Carruth 13243ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) { 13253ec848bcSHaicheng Wu bool CheckSROA = SI.getType()->isPointerTy(); 13263ec848bcSHaicheng Wu Value *TrueVal = SI.getTrueValue(); 13273ec848bcSHaicheng Wu Value *FalseVal = SI.getFalseValue(); 13283ec848bcSHaicheng Wu 13293ec848bcSHaicheng Wu Constant *TrueC = dyn_cast<Constant>(TrueVal); 13303ec848bcSHaicheng Wu if (!TrueC) 13313ec848bcSHaicheng Wu TrueC = SimplifiedValues.lookup(TrueVal); 13323ec848bcSHaicheng Wu Constant *FalseC = dyn_cast<Constant>(FalseVal); 13333ec848bcSHaicheng Wu if (!FalseC) 13343ec848bcSHaicheng Wu FalseC = SimplifiedValues.lookup(FalseVal); 13353ec848bcSHaicheng Wu Constant *CondC = 13363ec848bcSHaicheng Wu dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition())); 13373ec848bcSHaicheng Wu 13383ec848bcSHaicheng Wu if (!CondC) { 13393ec848bcSHaicheng Wu // Select C, X, X => X 13403ec848bcSHaicheng Wu if (TrueC == FalseC && TrueC) { 13413ec848bcSHaicheng Wu SimplifiedValues[&SI] = TrueC; 13423ec848bcSHaicheng Wu return true; 13433ec848bcSHaicheng Wu } 13443ec848bcSHaicheng Wu 13453ec848bcSHaicheng Wu if (!CheckSROA) 13463ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 13473ec848bcSHaicheng Wu 13483ec848bcSHaicheng Wu std::pair<Value *, APInt> TrueBaseAndOffset = 13493ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(TrueVal); 13503ec848bcSHaicheng Wu std::pair<Value *, APInt> FalseBaseAndOffset = 13513ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(FalseVal); 13523ec848bcSHaicheng Wu if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) { 13533ec848bcSHaicheng Wu ConstantOffsetPtrs[&SI] = TrueBaseAndOffset; 13543ec848bcSHaicheng Wu 13553ec848bcSHaicheng Wu Value *SROAArg; 13563ec848bcSHaicheng Wu DenseMap<Value *, int>::iterator CostIt; 13573ec848bcSHaicheng Wu if (lookupSROAArgAndCost(TrueVal, SROAArg, CostIt)) 13583ec848bcSHaicheng Wu SROAArgValues[&SI] = SROAArg; 13593ec848bcSHaicheng Wu return true; 13603ec848bcSHaicheng Wu } 13613ec848bcSHaicheng Wu 13623ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 13633ec848bcSHaicheng Wu } 13643ec848bcSHaicheng Wu 13653ec848bcSHaicheng Wu // Select condition is a constant. 13663ec848bcSHaicheng Wu Value *SelectedV = CondC->isAllOnesValue() 13673ec848bcSHaicheng Wu ? TrueVal 13683ec848bcSHaicheng Wu : (CondC->isNullValue()) ? FalseVal : nullptr; 13693ec848bcSHaicheng Wu if (!SelectedV) { 13703ec848bcSHaicheng Wu // Condition is a vector constant that is not all 1s or all 0s. If all 13713ec848bcSHaicheng Wu // operands are constants, ConstantExpr::getSelect() can handle the cases 13723ec848bcSHaicheng Wu // such as select vectors. 13733ec848bcSHaicheng Wu if (TrueC && FalseC) { 13743ec848bcSHaicheng Wu if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) { 13753ec848bcSHaicheng Wu SimplifiedValues[&SI] = C; 13763ec848bcSHaicheng Wu return true; 13773ec848bcSHaicheng Wu } 13783ec848bcSHaicheng Wu } 13793ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 13803ec848bcSHaicheng Wu } 13813ec848bcSHaicheng Wu 13823ec848bcSHaicheng Wu // Condition is either all 1s or all 0s. SI can be simplified. 13833ec848bcSHaicheng Wu if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) { 13843ec848bcSHaicheng Wu SimplifiedValues[&SI] = SelectedC; 13853ec848bcSHaicheng Wu return true; 13863ec848bcSHaicheng Wu } 13873ec848bcSHaicheng Wu 13883ec848bcSHaicheng Wu if (!CheckSROA) 13893ec848bcSHaicheng Wu return true; 13903ec848bcSHaicheng Wu 13913ec848bcSHaicheng Wu std::pair<Value *, APInt> BaseAndOffset = 13923ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(SelectedV); 13933ec848bcSHaicheng Wu if (BaseAndOffset.first) { 13943ec848bcSHaicheng Wu ConstantOffsetPtrs[&SI] = BaseAndOffset; 13953ec848bcSHaicheng Wu 13963ec848bcSHaicheng Wu Value *SROAArg; 13973ec848bcSHaicheng Wu DenseMap<Value *, int>::iterator CostIt; 13983ec848bcSHaicheng Wu if (lookupSROAArgAndCost(SelectedV, SROAArg, CostIt)) 13993ec848bcSHaicheng Wu SROAArgValues[&SI] = SROAArg; 14003ec848bcSHaicheng Wu } 14013ec848bcSHaicheng Wu 14023ec848bcSHaicheng Wu return true; 14033ec848bcSHaicheng Wu } 14043ec848bcSHaicheng Wu 14057adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) { 14067adc3a2bSChandler Carruth // We model unconditional switches as free, see the comments on handling 14077adc3a2bSChandler Carruth // branches. 14087adc3a2bSChandler Carruth if (isa<ConstantInt>(SI.getCondition())) 14097adc3a2bSChandler Carruth return true; 14107adc3a2bSChandler Carruth if (Value *V = SimplifiedValues.lookup(SI.getCondition())) 14117adc3a2bSChandler Carruth if (isa<ConstantInt>(V)) 14127adc3a2bSChandler Carruth return true; 14137adc3a2bSChandler Carruth 14147ad02eeeSEric Christopher // Assume the most general case where the switch is lowered into 1415919f9e8dSJun Bum Lim // either a jump table, bit test, or a balanced binary tree consisting of 1416919f9e8dSJun Bum Lim // case clusters without merging adjacent clusters with the same 1417919f9e8dSJun Bum Lim // destination. We do not consider the switches that are lowered with a mix 1418919f9e8dSJun Bum Lim // of jump table/bit test/binary search tree. The cost of the switch is 1419919f9e8dSJun Bum Lim // proportional to the size of the tree or the size of jump table range. 14202960d41eSJun Bum Lim // 14212960d41eSJun Bum Lim // NB: We convert large switches which are just used to initialize large phi 14222960d41eSJun Bum Lim // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent 14232960d41eSJun Bum Lim // inlining those. It will prevent inlining in cases where the optimization 14242960d41eSJun Bum Lim // does not (yet) fire. 1425919f9e8dSJun Bum Lim 1426506cfb7aSJun Bum Lim // Maximum valid cost increased in this function. 1427506cfb7aSJun Bum Lim int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1; 1428506cfb7aSJun Bum Lim 1429919f9e8dSJun Bum Lim // Exit early for a large switch, assuming one case needs at least one 1430919f9e8dSJun Bum Lim // instruction. 1431919f9e8dSJun Bum Lim // FIXME: This is not true for a bit test, but ignore such case for now to 1432919f9e8dSJun Bum Lim // save compile-time. 1433919f9e8dSJun Bum Lim int64_t CostLowerBound = 1434506cfb7aSJun Bum Lim std::min((int64_t)CostUpperBound, 1435919f9e8dSJun Bum Lim (int64_t)SI.getNumCases() * InlineConstants::InstrCost + Cost); 1436919f9e8dSJun Bum Lim 14370812c5beSHaicheng Wu if (CostLowerBound > Threshold && !ComputeFullInlineCost) { 1438919f9e8dSJun Bum Lim Cost = CostLowerBound; 1439919f9e8dSJun Bum Lim return false; 1440919f9e8dSJun Bum Lim } 1441919f9e8dSJun Bum Lim 1442919f9e8dSJun Bum Lim unsigned JumpTableSize = 0; 1443919f9e8dSJun Bum Lim unsigned NumCaseCluster = 1444919f9e8dSJun Bum Lim TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize); 1445919f9e8dSJun Bum Lim 1446919f9e8dSJun Bum Lim // If suitable for a jump table, consider the cost for the table size and 1447919f9e8dSJun Bum Lim // branch to destination. 1448919f9e8dSJun Bum Lim if (JumpTableSize) { 1449919f9e8dSJun Bum Lim int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost + 1450919f9e8dSJun Bum Lim 4 * InlineConstants::InstrCost; 1451506cfb7aSJun Bum Lim 1452506cfb7aSJun Bum Lim Cost = std::min((int64_t)CostUpperBound, JTCost + Cost); 1453919f9e8dSJun Bum Lim return false; 1454919f9e8dSJun Bum Lim } 1455919f9e8dSJun Bum Lim 1456919f9e8dSJun Bum Lim // Considering forming a binary search, we should find the number of nodes 1457919f9e8dSJun Bum Lim // which is same as the number of comparisons when lowered. For a given 1458919f9e8dSJun Bum Lim // number of clusters, n, we can define a recursive function, f(n), to find 1459919f9e8dSJun Bum Lim // the number of nodes in the tree. The recursion is : 1460919f9e8dSJun Bum Lim // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3, 1461919f9e8dSJun Bum Lim // and f(n) = n, when n <= 3. 1462919f9e8dSJun Bum Lim // This will lead a binary tree where the leaf should be either f(2) or f(3) 1463919f9e8dSJun Bum Lim // when n > 3. So, the number of comparisons from leaves should be n, while 1464919f9e8dSJun Bum Lim // the number of non-leaf should be : 1465919f9e8dSJun Bum Lim // 2^(log2(n) - 1) - 1 1466919f9e8dSJun Bum Lim // = 2^log2(n) * 2^-1 - 1 1467919f9e8dSJun Bum Lim // = n / 2 - 1. 1468919f9e8dSJun Bum Lim // Considering comparisons from leaf and non-leaf nodes, we can estimate the 1469919f9e8dSJun Bum Lim // number of comparisons in a simple closed form : 1470919f9e8dSJun Bum Lim // n + n / 2 - 1 = n * 3 / 2 - 1 1471919f9e8dSJun Bum Lim if (NumCaseCluster <= 3) { 1472919f9e8dSJun Bum Lim // Suppose a comparison includes one compare and one conditional branch. 1473919f9e8dSJun Bum Lim Cost += NumCaseCluster * 2 * InlineConstants::InstrCost; 1474919f9e8dSJun Bum Lim return false; 1475919f9e8dSJun Bum Lim } 1476506cfb7aSJun Bum Lim 1477506cfb7aSJun Bum Lim int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1; 1478506cfb7aSJun Bum Lim int64_t SwitchCost = 1479919f9e8dSJun Bum Lim ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost; 1480506cfb7aSJun Bum Lim 1481506cfb7aSJun Bum Lim Cost = std::min((int64_t)CostUpperBound, SwitchCost + Cost); 1482919f9e8dSJun Bum Lim return false; 1483919f9e8dSJun Bum Lim } 1484919f9e8dSJun Bum Lim 14857adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) { 14867adc3a2bSChandler Carruth // We never want to inline functions that contain an indirectbr. This is 14877adc3a2bSChandler Carruth // incorrect because all the blockaddress's (in static global initializers 14887adc3a2bSChandler Carruth // for example) would be referring to the original function, and this 14897adc3a2bSChandler Carruth // indirect jump would jump from the inlined copy of the function into the 14907adc3a2bSChandler Carruth // original function which is extremely undefined behavior. 14917adc3a2bSChandler Carruth // FIXME: This logic isn't really right; we can safely inline functions with 14927adc3a2bSChandler Carruth // indirectbr's as long as no other function or global references the 14937adc3a2bSChandler Carruth // blockaddress of a block within the current function. 14947adc3a2bSChandler Carruth HasIndirectBr = true; 14957adc3a2bSChandler Carruth return false; 14967adc3a2bSChandler Carruth } 14977adc3a2bSChandler Carruth 14987adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) { 14997adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 15007adc3a2bSChandler Carruth // the inline cost of a resume instruction. 15017adc3a2bSChandler Carruth return false; 15027adc3a2bSChandler Carruth } 15037adc3a2bSChandler Carruth 15047adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) { 15057adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 15067adc3a2bSChandler Carruth // the inline cost of a cleanupret instruction. 15077adc3a2bSChandler Carruth return false; 15087adc3a2bSChandler Carruth } 15097adc3a2bSChandler Carruth 15107adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) { 15117adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 15128220bcc5SJoseph Tremoulet // the inline cost of a catchret instruction. 15137adc3a2bSChandler Carruth return false; 15147adc3a2bSChandler Carruth } 15157adc3a2bSChandler Carruth 15167adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) { 15177adc3a2bSChandler Carruth // FIXME: It might be reasonably to discount the cost of instructions leading 15187adc3a2bSChandler Carruth // to unreachable as they have the lowest possible impact on both runtime and 15197adc3a2bSChandler Carruth // code size. 15207adc3a2bSChandler Carruth return true; // No actual code is needed for unreachable. 15217adc3a2bSChandler Carruth } 15227adc3a2bSChandler Carruth 15237adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) { 15247adc3a2bSChandler Carruth // Some instructions are free. All of the free intrinsics can also be 15257adc3a2bSChandler Carruth // handled by SROA, etc. 15267adc3a2bSChandler Carruth if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I)) 15277adc3a2bSChandler Carruth return true; 15287adc3a2bSChandler Carruth 15297adc3a2bSChandler Carruth // We found something we don't understand or can't handle. Mark any SROA-able 15307adc3a2bSChandler Carruth // values in the operand list as no longer viable. 15317adc3a2bSChandler Carruth for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI) 15327adc3a2bSChandler Carruth disableSROA(*OI); 15337adc3a2bSChandler Carruth 15347adc3a2bSChandler Carruth return false; 15357adc3a2bSChandler Carruth } 15367adc3a2bSChandler Carruth 15375f8f34e4SAdrian Prantl /// Analyze a basic block for its contribution to the inline cost. 15387adc3a2bSChandler Carruth /// 15397adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic 15407adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It 15417adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline 15427adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer 15437adc3a2bSChandler Carruth /// viable, and true if inlining remains viable. 1544c0aa4b75SDavid Bolvansky InlineResult 1545c0aa4b75SDavid Bolvansky CallAnalyzer::analyzeBlock(BasicBlock *BB, 15467adc3a2bSChandler Carruth SmallPtrSetImpl<const Value *> &EphValues) { 15477adc3a2bSChandler Carruth for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 15487adc3a2bSChandler Carruth // FIXME: Currently, the number of instructions in a function regardless of 15497adc3a2bSChandler Carruth // our ability to simplify them during inline to constants or dead code, 15507adc3a2bSChandler Carruth // are actually used by the vector bonus heuristic. As long as that's true, 15517adc3a2bSChandler Carruth // we have to special case debug intrinsics here to prevent differences in 15527adc3a2bSChandler Carruth // inlining due to debug symbols. Eventually, the number of unsimplified 15537adc3a2bSChandler Carruth // instructions shouldn't factor into the cost computation, but until then, 15547adc3a2bSChandler Carruth // hack around it here. 15557adc3a2bSChandler Carruth if (isa<DbgInfoIntrinsic>(I)) 15567adc3a2bSChandler Carruth continue; 15577adc3a2bSChandler Carruth 15587adc3a2bSChandler Carruth // Skip ephemeral values. 15595a82c916SDuncan P. N. Exon Smith if (EphValues.count(&*I)) 15607adc3a2bSChandler Carruth continue; 15617adc3a2bSChandler Carruth 15627adc3a2bSChandler Carruth ++NumInstructions; 15637adc3a2bSChandler Carruth if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy()) 15647adc3a2bSChandler Carruth ++NumVectorInstructions; 15657adc3a2bSChandler Carruth 15667adc3a2bSChandler Carruth // If the instruction simplified to a constant, there is no cost to this 15677adc3a2bSChandler Carruth // instruction. Visit the instructions using our InstVisitor to account for 15687adc3a2bSChandler Carruth // all of the per-instruction logic. The visit tree returns true if we 15697adc3a2bSChandler Carruth // consumed the instruction in any way, and false if the instruction's base 15707adc3a2bSChandler Carruth // cost should count against inlining. 15715a82c916SDuncan P. N. Exon Smith if (Base::visit(&*I)) 15727adc3a2bSChandler Carruth ++NumInstructionsSimplified; 15737adc3a2bSChandler Carruth else 15747adc3a2bSChandler Carruth Cost += InlineConstants::InstrCost; 15757adc3a2bSChandler Carruth 15760812c5beSHaicheng Wu using namespace ore; 15777adc3a2bSChandler Carruth // If the visit this instruction detected an uninlinable pattern, abort. 1578c0aa4b75SDavid Bolvansky InlineResult IR; 1579c0aa4b75SDavid Bolvansky if (IsRecursiveCall) 1580c0aa4b75SDavid Bolvansky IR = "recursive"; 1581c0aa4b75SDavid Bolvansky else if (ExposesReturnsTwice) 1582c0aa4b75SDavid Bolvansky IR = "exposes returns twice"; 1583c0aa4b75SDavid Bolvansky else if (HasDynamicAlloca) 1584c0aa4b75SDavid Bolvansky IR = "dynamic alloca"; 1585c0aa4b75SDavid Bolvansky else if (HasIndirectBr) 1586c0aa4b75SDavid Bolvansky IR = "indirect branch"; 1587c0aa4b75SDavid Bolvansky else if (HasUninlineableIntrinsic) 1588c0aa4b75SDavid Bolvansky IR = "uninlinable intrinsic"; 1589*77beee41SSameer AbuAsal else if (InitsVargArgs) 1590c0aa4b75SDavid Bolvansky IR = "varargs"; 1591c0aa4b75SDavid Bolvansky if (!IR) { 15920812c5beSHaicheng Wu if (ORE) 15939590658fSVivek Pandya ORE->emit([&]() { 15949590658fSVivek Pandya return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 15950812c5beSHaicheng Wu CandidateCS.getInstruction()) 1596c0aa4b75SDavid Bolvansky << NV("Callee", &F) << " has uninlinable pattern (" 1597c0aa4b75SDavid Bolvansky << NV("InlineResult", IR.message) 1598c0aa4b75SDavid Bolvansky << ") and cost is not fully computed"; 15999590658fSVivek Pandya }); 1600c0aa4b75SDavid Bolvansky return IR; 16010812c5beSHaicheng Wu } 16027adc3a2bSChandler Carruth 16037adc3a2bSChandler Carruth // If the caller is a recursive function then we don't want to inline 16047adc3a2bSChandler Carruth // functions which allocate a lot of stack space because it would increase 16057adc3a2bSChandler Carruth // the caller stack usage dramatically. 16067adc3a2bSChandler Carruth if (IsCallerRecursive && 16070812c5beSHaicheng Wu AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) { 1608c0aa4b75SDavid Bolvansky InlineResult IR = "recursive and allocates too much stack space"; 16090812c5beSHaicheng Wu if (ORE) 16109590658fSVivek Pandya ORE->emit([&]() { 16119590658fSVivek Pandya return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 16120812c5beSHaicheng Wu CandidateCS.getInstruction()) 1613c0aa4b75SDavid Bolvansky << NV("Callee", &F) << " is " << NV("InlineResult", IR.message) 1614c0aa4b75SDavid Bolvansky << ". Cost is not fully computed"; 16159590658fSVivek Pandya }); 1616c0aa4b75SDavid Bolvansky return IR; 16170812c5beSHaicheng Wu } 16187adc3a2bSChandler Carruth 16197adc3a2bSChandler Carruth // Check if we've past the maximum possible threshold so we don't spin in 16207adc3a2bSChandler Carruth // huge basic blocks that will never inline. 162161995364SHaicheng Wu if (Cost >= Threshold && !ComputeFullInlineCost) 16227adc3a2bSChandler Carruth return false; 16237adc3a2bSChandler Carruth } 16247adc3a2bSChandler Carruth 16257adc3a2bSChandler Carruth return true; 16267adc3a2bSChandler Carruth } 16277adc3a2bSChandler Carruth 16285f8f34e4SAdrian Prantl /// Compute the base pointer and cumulative constant offsets for V. 16297adc3a2bSChandler Carruth /// 16307adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and 16317adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It 16327adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are 16337adc3a2bSChandler Carruth /// no constant offsets applied. 16347adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) { 16357adc3a2bSChandler Carruth if (!V->getType()->isPointerTy()) 16367adc3a2bSChandler Carruth return nullptr; 16377adc3a2bSChandler Carruth 163877f32994SBjorn Pettersson unsigned AS = V->getType()->getPointerAddressSpace(); 1639945b7e5aSElena Demikhovsky unsigned IntPtrWidth = DL.getIndexSizeInBits(AS); 16407adc3a2bSChandler Carruth APInt Offset = APInt::getNullValue(IntPtrWidth); 16417adc3a2bSChandler Carruth 16427adc3a2bSChandler Carruth // Even though we don't look through PHI nodes, we could be called on an 16437adc3a2bSChandler Carruth // instruction in an unreachable block, which may be on a cycle. 16447adc3a2bSChandler Carruth SmallPtrSet<Value *, 4> Visited; 16457adc3a2bSChandler Carruth Visited.insert(V); 16467adc3a2bSChandler Carruth do { 16477adc3a2bSChandler Carruth if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 16487adc3a2bSChandler Carruth if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset)) 16497adc3a2bSChandler Carruth return nullptr; 16507adc3a2bSChandler Carruth V = GEP->getPointerOperand(); 16517adc3a2bSChandler Carruth } else if (Operator::getOpcode(V) == Instruction::BitCast) { 16527adc3a2bSChandler Carruth V = cast<Operator>(V)->getOperand(0); 16537adc3a2bSChandler Carruth } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 16545ce32728SSanjoy Das if (GA->isInterposable()) 16557adc3a2bSChandler Carruth break; 16567adc3a2bSChandler Carruth V = GA->getAliasee(); 16577adc3a2bSChandler Carruth } else { 16587adc3a2bSChandler Carruth break; 16597adc3a2bSChandler Carruth } 16607adc3a2bSChandler Carruth assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 16617adc3a2bSChandler Carruth } while (Visited.insert(V).second); 16627adc3a2bSChandler Carruth 166377f32994SBjorn Pettersson Type *IntPtrTy = DL.getIntPtrType(V->getContext(), AS); 16647adc3a2bSChandler Carruth return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset)); 16657adc3a2bSChandler Carruth } 16667adc3a2bSChandler Carruth 16675f8f34e4SAdrian Prantl /// Find dead blocks due to deleted CFG edges during inlining. 16683739e14aSHaicheng Wu /// 16693739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p 16703739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have 16713739e14aSHaicheng Wu /// no live incoming CFG edges. If one block is found to be dead, we can 16723739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead 16733739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not. 16743739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) { 16753739e14aSHaicheng Wu auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) { 16763739e14aSHaicheng Wu // A CFG edge is dead if the predecessor is dead or the predessor has a 16773739e14aSHaicheng Wu // known successor which is not the one under exam. 16783739e14aSHaicheng Wu return (DeadBlocks.count(Pred) || 16793739e14aSHaicheng Wu (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ)); 16803739e14aSHaicheng Wu }; 16813739e14aSHaicheng Wu 16823739e14aSHaicheng Wu auto IsNewlyDead = [&](BasicBlock *BB) { 16833739e14aSHaicheng Wu // If all the edges to a block are dead, the block is also dead. 16843739e14aSHaicheng Wu return (!DeadBlocks.count(BB) && 16853739e14aSHaicheng Wu llvm::all_of(predecessors(BB), 16863739e14aSHaicheng Wu [&](BasicBlock *P) { return IsEdgeDead(P, BB); })); 16873739e14aSHaicheng Wu }; 16883739e14aSHaicheng Wu 16893739e14aSHaicheng Wu for (BasicBlock *Succ : successors(CurrBB)) { 16903739e14aSHaicheng Wu if (Succ == NextBB || !IsNewlyDead(Succ)) 16913739e14aSHaicheng Wu continue; 16923739e14aSHaicheng Wu SmallVector<BasicBlock *, 4> NewDead; 16933739e14aSHaicheng Wu NewDead.push_back(Succ); 16943739e14aSHaicheng Wu while (!NewDead.empty()) { 16953739e14aSHaicheng Wu BasicBlock *Dead = NewDead.pop_back_val(); 16963739e14aSHaicheng Wu if (DeadBlocks.insert(Dead)) 16973739e14aSHaicheng Wu // Continue growing the dead block lists. 16983739e14aSHaicheng Wu for (BasicBlock *S : successors(Dead)) 16993739e14aSHaicheng Wu if (IsNewlyDead(S)) 17003739e14aSHaicheng Wu NewDead.push_back(S); 17013739e14aSHaicheng Wu } 17023739e14aSHaicheng Wu } 17033739e14aSHaicheng Wu } 17043739e14aSHaicheng Wu 17055f8f34e4SAdrian Prantl /// Analyze a call site for potential inlining. 17067adc3a2bSChandler Carruth /// 17077adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not 17087adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous 17097adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost 17107adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by 17117adc3a2bSChandler Carruth /// some artifact of the routine. 1712c0aa4b75SDavid Bolvansky InlineResult CallAnalyzer::analyzeCall(CallSite CS) { 17137adc3a2bSChandler Carruth ++NumCallsAnalyzed; 17147adc3a2bSChandler Carruth 17157adc3a2bSChandler Carruth // Perform some tweaks to the cost and threshold based on the direct 17167adc3a2bSChandler Carruth // callsite information. 17177adc3a2bSChandler Carruth 17187adc3a2bSChandler Carruth // We want to more aggressively inline vector-dense kernels, so up the 17197adc3a2bSChandler Carruth // threshold, and we'll lower it if the % of vector instructions gets too 17207adc3a2bSChandler Carruth // low. Note that these bonuses are some what arbitrary and evolved over time 17217adc3a2bSChandler Carruth // by accident as much as because they are principled bonuses. 17227adc3a2bSChandler Carruth // 17237adc3a2bSChandler Carruth // FIXME: It would be nice to remove all such bonuses. At least it would be 17247adc3a2bSChandler Carruth // nice to base the bonus values on something more scientific. 17257adc3a2bSChandler Carruth assert(NumInstructions == 0); 17267adc3a2bSChandler Carruth assert(NumVectorInstructions == 0); 1727f4bb2f0dSEaswaran Raman 1728f4bb2f0dSEaswaran Raman // Update the threshold based on callsite properties 1729f4bb2f0dSEaswaran Raman updateThreshold(CS, F); 1730f4bb2f0dSEaswaran Raman 17317adc3a2bSChandler Carruth // Speculatively apply all possible bonuses to Threshold. If cost exceeds 17327adc3a2bSChandler Carruth // this Threshold any time, and cost cannot decrease, we can stop processing 17337adc3a2bSChandler Carruth // the rest of the function body. 173451b809bfSEaswaran Raman Threshold += (SingleBBBonus + VectorBonus); 17357adc3a2bSChandler Carruth 1736351d9b01SXinliang David Li // Give out bonuses for the callsite, as the instructions setting them up 1737351d9b01SXinliang David Li // will be gone after inlining. 1738351d9b01SXinliang David Li Cost -= getCallsiteCost(CS, DL); 17397adc3a2bSChandler Carruth 17407adc3a2bSChandler Carruth // If this function uses the coldcc calling convention, prefer not to inline 17417adc3a2bSChandler Carruth // it. 17427adc3a2bSChandler Carruth if (F.getCallingConv() == CallingConv::Cold) 17437adc3a2bSChandler Carruth Cost += InlineConstants::ColdccPenalty; 17447adc3a2bSChandler Carruth 17457adc3a2bSChandler Carruth // Check if we're done. This can happen due to bonuses and penalties. 174661995364SHaicheng Wu if (Cost >= Threshold && !ComputeFullInlineCost) 1747c0aa4b75SDavid Bolvansky return "high cost"; 17487adc3a2bSChandler Carruth 17497adc3a2bSChandler Carruth if (F.empty()) 17507adc3a2bSChandler Carruth return true; 17517adc3a2bSChandler Carruth 17529d939c8fSDavide Italiano Function *Caller = CS.getInstruction()->getFunction(); 17537adc3a2bSChandler Carruth // Check if the caller function is recursive itself. 17547adc3a2bSChandler Carruth for (User *U : Caller->users()) { 17557adc3a2bSChandler Carruth CallSite Site(U); 17567adc3a2bSChandler Carruth if (!Site) 17577adc3a2bSChandler Carruth continue; 17587adc3a2bSChandler Carruth Instruction *I = Site.getInstruction(); 17599d939c8fSDavide Italiano if (I->getFunction() == Caller) { 17607adc3a2bSChandler Carruth IsCallerRecursive = true; 17617adc3a2bSChandler Carruth break; 17627adc3a2bSChandler Carruth } 17637adc3a2bSChandler Carruth } 17647adc3a2bSChandler Carruth 17657adc3a2bSChandler Carruth // Populate our simplified values by mapping from function arguments to call 17667adc3a2bSChandler Carruth // arguments with known important simplifications. 17677adc3a2bSChandler Carruth CallSite::arg_iterator CAI = CS.arg_begin(); 17687adc3a2bSChandler Carruth for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end(); 17697adc3a2bSChandler Carruth FAI != FAE; ++FAI, ++CAI) { 17707adc3a2bSChandler Carruth assert(CAI != CS.arg_end()); 17717adc3a2bSChandler Carruth if (Constant *C = dyn_cast<Constant>(CAI)) 17725a82c916SDuncan P. N. Exon Smith SimplifiedValues[&*FAI] = C; 17737adc3a2bSChandler Carruth 17747adc3a2bSChandler Carruth Value *PtrArg = *CAI; 17757adc3a2bSChandler Carruth if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) { 17765a82c916SDuncan P. N. Exon Smith ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue()); 17777adc3a2bSChandler Carruth 17787adc3a2bSChandler Carruth // We can SROA any pointer arguments derived from alloca instructions. 17797adc3a2bSChandler Carruth if (isa<AllocaInst>(PtrArg)) { 17805a82c916SDuncan P. N. Exon Smith SROAArgValues[&*FAI] = PtrArg; 17817adc3a2bSChandler Carruth SROAArgCosts[PtrArg] = 0; 17827adc3a2bSChandler Carruth } 17837adc3a2bSChandler Carruth } 17847adc3a2bSChandler Carruth } 17857adc3a2bSChandler Carruth NumConstantArgs = SimplifiedValues.size(); 17867adc3a2bSChandler Carruth NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size(); 17877adc3a2bSChandler Carruth NumAllocaArgs = SROAArgValues.size(); 17887adc3a2bSChandler Carruth 17897adc3a2bSChandler Carruth // FIXME: If a caller has multiple calls to a callee, we end up recomputing 17907adc3a2bSChandler Carruth // the ephemeral values multiple times (and they're completely determined by 17917adc3a2bSChandler Carruth // the callee, so this is purely duplicate work). 17927adc3a2bSChandler Carruth SmallPtrSet<const Value *, 32> EphValues; 1793aec2fa35SDaniel Jasper CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues); 17947adc3a2bSChandler Carruth 17957adc3a2bSChandler Carruth // The worklist of live basic blocks in the callee *after* inlining. We avoid 17967adc3a2bSChandler Carruth // adding basic blocks of the callee which can be proven to be dead for this 17977adc3a2bSChandler Carruth // particular call site in order to get more accurate cost estimates. This 17987adc3a2bSChandler Carruth // requires a somewhat heavyweight iteration pattern: we need to walk the 17997adc3a2bSChandler Carruth // basic blocks in a breadth-first order as we insert live successors. To 18007adc3a2bSChandler Carruth // accomplish this, prioritizing for small iterations because we exit after 18017adc3a2bSChandler Carruth // crossing our threshold, we use a small-size optimized SetVector. 18027adc3a2bSChandler Carruth typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>, 1803567556aaSChad Rosier SmallPtrSet<BasicBlock *, 16>> 1804567556aaSChad Rosier BBSetVector; 18057adc3a2bSChandler Carruth BBSetVector BBWorklist; 18067adc3a2bSChandler Carruth BBWorklist.insert(&F.getEntryBlock()); 180751b809bfSEaswaran Raman bool SingleBB = true; 18087adc3a2bSChandler Carruth // Note that we *must not* cache the size, this loop grows the worklist. 18097adc3a2bSChandler Carruth for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 18107adc3a2bSChandler Carruth // Bail out the moment we cross the threshold. This means we'll under-count 18117adc3a2bSChandler Carruth // the cost, but only when undercounting doesn't matter. 181261995364SHaicheng Wu if (Cost >= Threshold && !ComputeFullInlineCost) 18137adc3a2bSChandler Carruth break; 18147adc3a2bSChandler Carruth 18157adc3a2bSChandler Carruth BasicBlock *BB = BBWorklist[Idx]; 18167adc3a2bSChandler Carruth if (BB->empty()) 18177adc3a2bSChandler Carruth continue; 18187adc3a2bSChandler Carruth 18197adc3a2bSChandler Carruth // Disallow inlining a blockaddress. A blockaddress only has defined 18207adc3a2bSChandler Carruth // behavior for an indirect branch in the same function, and we do not 18217adc3a2bSChandler Carruth // currently support inlining indirect branches. But, the inliner may not 18227adc3a2bSChandler Carruth // see an indirect branch that ends up being dead code at a particular call 18237adc3a2bSChandler Carruth // site. If the blockaddress escapes the function, e.g., via a global 18247adc3a2bSChandler Carruth // variable, inlining may lead to an invalid cross-function reference. 18257adc3a2bSChandler Carruth if (BB->hasAddressTaken()) 1826c0aa4b75SDavid Bolvansky return "blockaddress"; 18277adc3a2bSChandler Carruth 18287adc3a2bSChandler Carruth // Analyze the cost of this block. If we blow through the threshold, this 18297adc3a2bSChandler Carruth // returns false, and we can bail on out. 1830c0aa4b75SDavid Bolvansky InlineResult IR = analyzeBlock(BB, EphValues); 1831c0aa4b75SDavid Bolvansky if (!IR) 1832c0aa4b75SDavid Bolvansky return IR; 18337adc3a2bSChandler Carruth 18347adc3a2bSChandler Carruth TerminatorInst *TI = BB->getTerminator(); 18357adc3a2bSChandler Carruth 18367adc3a2bSChandler Carruth // Add in the live successors by first checking whether we have terminator 18377adc3a2bSChandler Carruth // that may be simplified based on the values simplified by this call. 18387adc3a2bSChandler Carruth if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 18397adc3a2bSChandler Carruth if (BI->isConditional()) { 18407adc3a2bSChandler Carruth Value *Cond = BI->getCondition(); 1841567556aaSChad Rosier if (ConstantInt *SimpleCond = 1842567556aaSChad Rosier dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 18433739e14aSHaicheng Wu BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0); 18443739e14aSHaicheng Wu BBWorklist.insert(NextBB); 18453739e14aSHaicheng Wu KnownSuccessors[BB] = NextBB; 18463739e14aSHaicheng Wu findDeadBlocks(BB, NextBB); 18477adc3a2bSChandler Carruth continue; 18487adc3a2bSChandler Carruth } 18497adc3a2bSChandler Carruth } 18507adc3a2bSChandler Carruth } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 18517adc3a2bSChandler Carruth Value *Cond = SI->getCondition(); 1852567556aaSChad Rosier if (ConstantInt *SimpleCond = 1853567556aaSChad Rosier dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 18543739e14aSHaicheng Wu BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor(); 18553739e14aSHaicheng Wu BBWorklist.insert(NextBB); 18563739e14aSHaicheng Wu KnownSuccessors[BB] = NextBB; 18573739e14aSHaicheng Wu findDeadBlocks(BB, NextBB); 18587adc3a2bSChandler Carruth continue; 18597adc3a2bSChandler Carruth } 18607adc3a2bSChandler Carruth } 18617adc3a2bSChandler Carruth 18627adc3a2bSChandler Carruth // If we're unable to select a particular successor, just count all of 18637adc3a2bSChandler Carruth // them. 18647adc3a2bSChandler Carruth for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize; 18657adc3a2bSChandler Carruth ++TIdx) 18667adc3a2bSChandler Carruth BBWorklist.insert(TI->getSuccessor(TIdx)); 18677adc3a2bSChandler Carruth 18687adc3a2bSChandler Carruth // If we had any successors at this point, than post-inlining is likely to 18697adc3a2bSChandler Carruth // have them as well. Note that we assume any basic blocks which existed 18707adc3a2bSChandler Carruth // due to branches or switches which folded above will also fold after 18717adc3a2bSChandler Carruth // inlining. 18727adc3a2bSChandler Carruth if (SingleBB && TI->getNumSuccessors() > 1) { 18737adc3a2bSChandler Carruth // Take off the bonus we applied to the threshold. 18747adc3a2bSChandler Carruth Threshold -= SingleBBBonus; 18757adc3a2bSChandler Carruth SingleBB = false; 18767adc3a2bSChandler Carruth } 18777adc3a2bSChandler Carruth } 18787adc3a2bSChandler Carruth 187951b809bfSEaswaran Raman bool OnlyOneCallAndLocalLinkage = 188051b809bfSEaswaran Raman F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction(); 18817adc3a2bSChandler Carruth // If this is a noduplicate call, we can still inline as long as 18827adc3a2bSChandler Carruth // inlining this would cause the removal of the caller (so the instruction 18837adc3a2bSChandler Carruth // is not actually duplicated, just moved). 18847adc3a2bSChandler Carruth if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall) 1885c0aa4b75SDavid Bolvansky return "noduplicate"; 18867adc3a2bSChandler Carruth 18877adc3a2bSChandler Carruth // We applied the maximum possible vector bonus at the beginning. Now, 18887adc3a2bSChandler Carruth // subtract the excess bonus, if any, from the Threshold before 18897adc3a2bSChandler Carruth // comparing against Cost. 18907adc3a2bSChandler Carruth if (NumVectorInstructions <= NumInstructions / 10) 189151b809bfSEaswaran Raman Threshold -= VectorBonus; 18927adc3a2bSChandler Carruth else if (NumVectorInstructions <= NumInstructions / 2) 189351b809bfSEaswaran Raman Threshold -= VectorBonus/2; 18947adc3a2bSChandler Carruth 189500ab73dcSHans Wennborg return Cost < std::max(1, Threshold); 18967adc3a2bSChandler Carruth } 18977adc3a2bSChandler Carruth 1898615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 18995f8f34e4SAdrian Prantl /// Dump stats about this call's analysis. 1900eb2a2546SYaron Keren LLVM_DUMP_METHOD void CallAnalyzer::dump() { 19017adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n" 19027adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantArgs); 19037adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs); 19047adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumAllocaArgs); 19057adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantPtrCmps); 19067adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantPtrDiffs); 19077adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumInstructionsSimplified); 19087adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumInstructions); 19097adc3a2bSChandler Carruth DEBUG_PRINT_STAT(SROACostSavings); 19107adc3a2bSChandler Carruth DEBUG_PRINT_STAT(SROACostSavingsLost); 1911a4461515SHaicheng Wu DEBUG_PRINT_STAT(LoadEliminationCost); 19127adc3a2bSChandler Carruth DEBUG_PRINT_STAT(ContainsNoDuplicateCall); 19137adc3a2bSChandler Carruth DEBUG_PRINT_STAT(Cost); 19147adc3a2bSChandler Carruth DEBUG_PRINT_STAT(Threshold); 19157adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT 19167adc3a2bSChandler Carruth } 19177adc3a2bSChandler Carruth #endif 19187adc3a2bSChandler Carruth 19195f8f34e4SAdrian Prantl /// Test that there are no attribute conflicts between Caller and Callee 19207adc3a2bSChandler Carruth /// that prevent inlining. 19217adc3a2bSChandler Carruth static bool functionsHaveCompatibleAttributes(Function *Caller, 19227adc3a2bSChandler Carruth Function *Callee, 19237adc3a2bSChandler Carruth TargetTransformInfo &TTI) { 19247adc3a2bSChandler Carruth return TTI.areInlineCompatible(Caller, Callee) && 19251cb242ebSAkira Hatanaka AttributeFuncs::areInlineCompatible(*Caller, *Callee); 19267adc3a2bSChandler Carruth } 19277adc3a2bSChandler Carruth 1928351d9b01SXinliang David Li int llvm::getCallsiteCost(CallSite CS, const DataLayout &DL) { 1929351d9b01SXinliang David Li int Cost = 0; 1930351d9b01SXinliang David Li for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) { 1931351d9b01SXinliang David Li if (CS.isByValArgument(I)) { 1932351d9b01SXinliang David Li // We approximate the number of loads and stores needed by dividing the 1933351d9b01SXinliang David Li // size of the byval type by the target's pointer size. 1934351d9b01SXinliang David Li PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType()); 1935351d9b01SXinliang David Li unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType()); 193677f32994SBjorn Pettersson unsigned AS = PTy->getAddressSpace(); 193777f32994SBjorn Pettersson unsigned PointerSize = DL.getPointerSizeInBits(AS); 1938351d9b01SXinliang David Li // Ceiling division. 1939351d9b01SXinliang David Li unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize; 1940351d9b01SXinliang David Li 1941351d9b01SXinliang David Li // If it generates more than 8 stores it is likely to be expanded as an 1942351d9b01SXinliang David Li // inline memcpy so we take that as an upper bound. Otherwise we assume 1943351d9b01SXinliang David Li // one load and one store per word copied. 1944351d9b01SXinliang David Li // FIXME: The maxStoresPerMemcpy setting from the target should be used 1945351d9b01SXinliang David Li // here instead of a magic number of 8, but it's not available via 1946351d9b01SXinliang David Li // DataLayout. 1947351d9b01SXinliang David Li NumStores = std::min(NumStores, 8U); 1948351d9b01SXinliang David Li 1949351d9b01SXinliang David Li Cost += 2 * NumStores * InlineConstants::InstrCost; 1950351d9b01SXinliang David Li } else { 1951351d9b01SXinliang David Li // For non-byval arguments subtract off one instruction per call 1952351d9b01SXinliang David Li // argument. 1953351d9b01SXinliang David Li Cost += InlineConstants::InstrCost; 1954351d9b01SXinliang David Li } 1955351d9b01SXinliang David Li } 1956351d9b01SXinliang David Li // The call instruction also disappears after inlining. 1957351d9b01SXinliang David Li Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty; 1958351d9b01SXinliang David Li return Cost; 1959351d9b01SXinliang David Li } 1960351d9b01SXinliang David Li 1961ab6a6837SSean Silva InlineCost llvm::getInlineCost( 19621c57cc2bSEaswaran Raman CallSite CS, const InlineParams &Params, TargetTransformInfo &CalleeTTI, 1963aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 196412585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 19650812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 1966aec2fa35SDaniel Jasper return getInlineCost(CS, CS.getCalledFunction(), Params, CalleeTTI, 19670812c5beSHaicheng Wu GetAssumptionCache, GetBFI, PSI, ORE); 1968b9f7120eSEaswaran Raman } 1969b9f7120eSEaswaran Raman 1970ab6a6837SSean Silva InlineCost llvm::getInlineCost( 19711c57cc2bSEaswaran Raman CallSite CS, Function *Callee, const InlineParams &Params, 1972aec2fa35SDaniel Jasper TargetTransformInfo &CalleeTTI, 1973aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 197412585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 19750812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 1976f4bb2f0dSEaswaran Raman 19777adc3a2bSChandler Carruth // Cannot inline indirect calls. 19787adc3a2bSChandler Carruth if (!Callee) 1979c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("indirect call"); 19807adc3a2bSChandler Carruth 19813851496eSBjorn Pettersson // Never inline calls with byval arguments that does not have the alloca 19823851496eSBjorn Pettersson // address space. Since byval arguments can be replaced with a copy to an 19833851496eSBjorn Pettersson // alloca, the inlined code would need to be adjusted to handle that the 19843851496eSBjorn Pettersson // argument is in the alloca address space (so it is a little bit complicated 19853851496eSBjorn Pettersson // to solve). 19863851496eSBjorn Pettersson unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace(); 19873851496eSBjorn Pettersson for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) 19883851496eSBjorn Pettersson if (CS.isByValArgument(I)) { 19893851496eSBjorn Pettersson PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType()); 19903851496eSBjorn Pettersson if (PTy->getAddressSpace() != AllocaAS) 1991c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("byval arguments without alloca" 1992c0aa4b75SDavid Bolvansky " address space"); 19933851496eSBjorn Pettersson } 19943851496eSBjorn Pettersson 19957adc3a2bSChandler Carruth // Calls to functions with always-inline attributes should be inlined 19967adc3a2bSChandler Carruth // whenever possible. 19977adc3a2bSChandler Carruth if (CS.hasFnAttr(Attribute::AlwaysInline)) { 19987adc3a2bSChandler Carruth if (isInlineViable(*Callee)) 1999c0aa4b75SDavid Bolvansky return llvm::InlineCost::getAlways("always inline attribute"); 2000c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("inapplicable always inline attribute"); 20017adc3a2bSChandler Carruth } 20027adc3a2bSChandler Carruth 20037adc3a2bSChandler Carruth // Never inline functions with conflicting attributes (unless callee has 20047adc3a2bSChandler Carruth // always-inline attribute). 20055ce28f4fSChad Rosier Function *Caller = CS.getCaller(); 20065ce28f4fSChad Rosier if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI)) 2007c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("conflicting attributes"); 20087adc3a2bSChandler Carruth 20097adc3a2bSChandler Carruth // Don't inline this call if the caller has the optnone attribute. 20105ce28f4fSChad Rosier if (Caller->hasFnAttribute(Attribute::OptimizeNone)) 2011c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("optnone attribute"); 20127adc3a2bSChandler Carruth 201377eeac3dSManoj Gupta // Don't inline a function that treats null pointer as valid into a caller 201477eeac3dSManoj Gupta // that does not have this attribute. 201577eeac3dSManoj Gupta if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined()) 2016c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("nullptr definitions incompatible"); 201777eeac3dSManoj Gupta 2018c0aa4b75SDavid Bolvansky // Don't inline functions which can be interposed at link-time. 2019c0aa4b75SDavid Bolvansky if (Callee->isInterposable()) 2020c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("interposable"); 2021c0aa4b75SDavid Bolvansky 2022c0aa4b75SDavid Bolvansky // Don't inline functions marked noinline. 2023c0aa4b75SDavid Bolvansky if (Callee->hasFnAttribute(Attribute::NoInline)) 2024c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("noinline function attribute"); 2025c0aa4b75SDavid Bolvansky 2026c0aa4b75SDavid Bolvansky // Don't inline call sites marked noinline. 2027c0aa4b75SDavid Bolvansky if (CS.isNoInline()) 2028c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("noinline call site attribute"); 20297adc3a2bSChandler Carruth 2030d34e60caSNicola Zaghen LLVM_DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName() 20314eb18742SChad Rosier << "... (caller:" << Caller->getName() << ")\n"); 20327adc3a2bSChandler Carruth 20330812c5beSHaicheng Wu CallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE, *Callee, CS, 203412585b01SEaswaran Raman Params); 2035c0aa4b75SDavid Bolvansky InlineResult ShouldInline = CA.analyzeCall(CS); 20367adc3a2bSChandler Carruth 2037d34e60caSNicola Zaghen LLVM_DEBUG(CA.dump()); 20387adc3a2bSChandler Carruth 20397adc3a2bSChandler Carruth // Check if there was a reason to force inlining or no inlining. 20407adc3a2bSChandler Carruth if (!ShouldInline && CA.getCost() < CA.getThreshold()) 2041c0aa4b75SDavid Bolvansky return InlineCost::getNever(ShouldInline.message); 20427adc3a2bSChandler Carruth if (ShouldInline && CA.getCost() >= CA.getThreshold()) 2043c0aa4b75SDavid Bolvansky return InlineCost::getAlways("empty function"); 20447adc3a2bSChandler Carruth 20457adc3a2bSChandler Carruth return llvm::InlineCost::get(CA.getCost(), CA.getThreshold()); 20467adc3a2bSChandler Carruth } 20477adc3a2bSChandler Carruth 2048b9f7120eSEaswaran Raman bool llvm::isInlineViable(Function &F) { 20497adc3a2bSChandler Carruth bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice); 20507adc3a2bSChandler Carruth for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) { 20517adc3a2bSChandler Carruth // Disallow inlining of functions which contain indirect branches or 20527adc3a2bSChandler Carruth // blockaddresses. 20537adc3a2bSChandler Carruth if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken()) 20547adc3a2bSChandler Carruth return false; 20557adc3a2bSChandler Carruth 20565a82c916SDuncan P. N. Exon Smith for (auto &II : *BI) { 20575a82c916SDuncan P. N. Exon Smith CallSite CS(&II); 20587adc3a2bSChandler Carruth if (!CS) 20597adc3a2bSChandler Carruth continue; 20607adc3a2bSChandler Carruth 20617adc3a2bSChandler Carruth // Disallow recursive calls. 20627adc3a2bSChandler Carruth if (&F == CS.getCalledFunction()) 20637adc3a2bSChandler Carruth return false; 20647adc3a2bSChandler Carruth 20657adc3a2bSChandler Carruth // Disallow calls which expose returns-twice to a function not previously 20667adc3a2bSChandler Carruth // attributed as such. 20677adc3a2bSChandler Carruth if (!ReturnsTwice && CS.isCall() && 20687adc3a2bSChandler Carruth cast<CallInst>(CS.getInstruction())->canReturnTwice()) 20697adc3a2bSChandler Carruth return false; 20707adc3a2bSChandler Carruth 20711636651eSFlorian Hahn if (CS.getCalledFunction()) 20721636651eSFlorian Hahn switch (CS.getCalledFunction()->getIntrinsicID()) { 20731636651eSFlorian Hahn default: 20741636651eSFlorian Hahn break; 20754296ea72SVitaly Buka // Disallow inlining of @llvm.icall.branch.funnel because current 20764296ea72SVitaly Buka // backend can't separate call targets from call arguments. 20774296ea72SVitaly Buka case llvm::Intrinsic::icall_branch_funnel: 20787adc3a2bSChandler Carruth // Disallow inlining functions that call @llvm.localescape. Doing this 20797adc3a2bSChandler Carruth // correctly would require major changes to the inliner. 20801636651eSFlorian Hahn case llvm::Intrinsic::localescape: 2081*77beee41SSameer AbuAsal // Disallow inlining of functions that initialize VarArgs with va_start. 20821636651eSFlorian Hahn case llvm::Intrinsic::vastart: 20837adc3a2bSChandler Carruth return false; 20847adc3a2bSChandler Carruth } 20857adc3a2bSChandler Carruth } 20861636651eSFlorian Hahn } 20877adc3a2bSChandler Carruth 20887adc3a2bSChandler Carruth return true; 20897adc3a2bSChandler Carruth } 20901c57cc2bSEaswaran Raman 20911c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other 20921c57cc2bSEaswaran Raman // parameters. 20931c57cc2bSEaswaran Raman 20941c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) { 20951c57cc2bSEaswaran Raman InlineParams Params; 20961c57cc2bSEaswaran Raman 20971c57cc2bSEaswaran Raman // This field is the threshold to use for a callee by default. This is 20981c57cc2bSEaswaran Raman // derived from one or more of: 20991c57cc2bSEaswaran Raman // * optimization or size-optimization levels, 21001c57cc2bSEaswaran Raman // * a value passed to createFunctionInliningPass function, or 21011c57cc2bSEaswaran Raman // * the -inline-threshold flag. 21021c57cc2bSEaswaran Raman // If the -inline-threshold flag is explicitly specified, that is used 21031c57cc2bSEaswaran Raman // irrespective of anything else. 21041c57cc2bSEaswaran Raman if (InlineThreshold.getNumOccurrences() > 0) 21051c57cc2bSEaswaran Raman Params.DefaultThreshold = InlineThreshold; 21061c57cc2bSEaswaran Raman else 21071c57cc2bSEaswaran Raman Params.DefaultThreshold = Threshold; 21081c57cc2bSEaswaran Raman 21091c57cc2bSEaswaran Raman // Set the HintThreshold knob from the -inlinehint-threshold. 21101c57cc2bSEaswaran Raman Params.HintThreshold = HintThreshold; 21111c57cc2bSEaswaran Raman 21121c57cc2bSEaswaran Raman // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold. 21131c57cc2bSEaswaran Raman Params.HotCallSiteThreshold = HotCallSiteThreshold; 21141c57cc2bSEaswaran Raman 2115974d4eeaSEaswaran Raman // If the -locally-hot-callsite-threshold is explicitly specified, use it to 2116974d4eeaSEaswaran Raman // populate LocallyHotCallSiteThreshold. Later, we populate 2117974d4eeaSEaswaran Raman // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if 2118974d4eeaSEaswaran Raman // we know that optimization level is O3 (in the getInlineParams variant that 2119974d4eeaSEaswaran Raman // takes the opt and size levels). 2120974d4eeaSEaswaran Raman // FIXME: Remove this check (and make the assignment unconditional) after 2121974d4eeaSEaswaran Raman // addressing size regression issues at O2. 2122974d4eeaSEaswaran Raman if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0) 2123974d4eeaSEaswaran Raman Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2124974d4eeaSEaswaran Raman 212512585b01SEaswaran Raman // Set the ColdCallSiteThreshold knob from the -inline-cold-callsite-threshold. 212612585b01SEaswaran Raman Params.ColdCallSiteThreshold = ColdCallSiteThreshold; 212712585b01SEaswaran Raman 21281c57cc2bSEaswaran Raman // Set the OptMinSizeThreshold and OptSizeThreshold params only if the 21291c57cc2bSEaswaran Raman // -inlinehint-threshold commandline option is not explicitly given. If that 21301c57cc2bSEaswaran Raman // option is present, then its value applies even for callees with size and 21311c57cc2bSEaswaran Raman // minsize attributes. 21321c57cc2bSEaswaran Raman // If the -inline-threshold is not specified, set the ColdThreshold from the 21331c57cc2bSEaswaran Raman // -inlinecold-threshold even if it is not explicitly passed. If 21341c57cc2bSEaswaran Raman // -inline-threshold is specified, then -inlinecold-threshold needs to be 21351c57cc2bSEaswaran Raman // explicitly specified to set the ColdThreshold knob 21361c57cc2bSEaswaran Raman if (InlineThreshold.getNumOccurrences() == 0) { 21371c57cc2bSEaswaran Raman Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold; 21381c57cc2bSEaswaran Raman Params.OptSizeThreshold = InlineConstants::OptSizeThreshold; 21391c57cc2bSEaswaran Raman Params.ColdThreshold = ColdThreshold; 21401c57cc2bSEaswaran Raman } else if (ColdThreshold.getNumOccurrences() > 0) { 21411c57cc2bSEaswaran Raman Params.ColdThreshold = ColdThreshold; 21421c57cc2bSEaswaran Raman } 21431c57cc2bSEaswaran Raman return Params; 21441c57cc2bSEaswaran Raman } 21451c57cc2bSEaswaran Raman 21461c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() { 21471c57cc2bSEaswaran Raman return getInlineParams(InlineThreshold); 21481c57cc2bSEaswaran Raman } 21491c57cc2bSEaswaran Raman 21501c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the 21511c57cc2bSEaswaran Raman // size opt level. 21521c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel, 21531c57cc2bSEaswaran Raman unsigned SizeOptLevel) { 21541c57cc2bSEaswaran Raman if (OptLevel > 2) 21551c57cc2bSEaswaran Raman return InlineConstants::OptAggressiveThreshold; 21561c57cc2bSEaswaran Raman if (SizeOptLevel == 1) // -Os 21571c57cc2bSEaswaran Raman return InlineConstants::OptSizeThreshold; 21581c57cc2bSEaswaran Raman if (SizeOptLevel == 2) // -Oz 21591c57cc2bSEaswaran Raman return InlineConstants::OptMinSizeThreshold; 21601c57cc2bSEaswaran Raman return InlineThreshold; 21611c57cc2bSEaswaran Raman } 21621c57cc2bSEaswaran Raman 21631c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) { 2164974d4eeaSEaswaran Raman auto Params = 2165974d4eeaSEaswaran Raman getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel)); 2166974d4eeaSEaswaran Raman // At O3, use the value of -locally-hot-callsite-threshold option to populate 2167974d4eeaSEaswaran Raman // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only 2168974d4eeaSEaswaran Raman // when it is specified explicitly. 2169974d4eeaSEaswaran Raman if (OptLevel > 2) 2170974d4eeaSEaswaran Raman Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2171974d4eeaSEaswaran Raman return Params; 21721c57cc2bSEaswaran Raman } 2173