17adc3a2bSChandler Carruth //===- InlineCost.cpp - Cost analysis for inliner -------------------------===// 27adc3a2bSChandler Carruth // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 67adc3a2bSChandler Carruth // 77adc3a2bSChandler Carruth //===----------------------------------------------------------------------===// 87adc3a2bSChandler Carruth // 97adc3a2bSChandler Carruth // This file implements inline cost analysis. 107adc3a2bSChandler Carruth // 117adc3a2bSChandler Carruth //===----------------------------------------------------------------------===// 127adc3a2bSChandler Carruth 137adc3a2bSChandler Carruth #include "llvm/Analysis/InlineCost.h" 147adc3a2bSChandler Carruth #include "llvm/ADT/STLExtras.h" 157adc3a2bSChandler Carruth #include "llvm/ADT/SetVector.h" 167adc3a2bSChandler Carruth #include "llvm/ADT/SmallPtrSet.h" 177adc3a2bSChandler Carruth #include "llvm/ADT/SmallVector.h" 187adc3a2bSChandler Carruth #include "llvm/ADT/Statistic.h" 19aec2fa35SDaniel Jasper #include "llvm/Analysis/AssumptionCache.h" 2012585b01SEaswaran Raman #include "llvm/Analysis/BlockFrequencyInfo.h" 214c1a1d3cSReid Kleckner #include "llvm/Analysis/CFG.h" 227adc3a2bSChandler Carruth #include "llvm/Analysis/CodeMetrics.h" 237adc3a2bSChandler Carruth #include "llvm/Analysis/ConstantFolding.h" 247adc3a2bSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h" 25ba9f245bSDavid Green #include "llvm/Analysis/LoopInfo.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/CallingConv.h" 317adc3a2bSChandler Carruth #include "llvm/IR/DataLayout.h" 32ba9f245bSDavid Green #include "llvm/IR/Dominators.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" 387cebf0afSCraig Topper #include "llvm/IR/PatternMatch.h" 394c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h" 407adc3a2bSChandler Carruth #include "llvm/Support/Debug.h" 417adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h" 427adc3a2bSChandler Carruth 437adc3a2bSChandler Carruth using namespace llvm; 447adc3a2bSChandler Carruth 457adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost" 467adc3a2bSChandler Carruth 477adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed"); 487adc3a2bSChandler Carruth 491c57cc2bSEaswaran Raman static cl::opt<int> InlineThreshold( 50f4bb2f0dSEaswaran Raman "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore, 51f4bb2f0dSEaswaran Raman cl::desc("Control the amount of inlining to perform (default = 225)")); 52f4bb2f0dSEaswaran Raman 53f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold( 54fd3e7a93SDavid Callahan "inlinehint-threshold", cl::Hidden, cl::init(325), cl::ZeroOrMore, 55f4bb2f0dSEaswaran Raman cl::desc("Threshold for inlining functions with inline hint")); 56f4bb2f0dSEaswaran Raman 5712585b01SEaswaran Raman static cl::opt<int> 5812585b01SEaswaran Raman ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden, 59fd3e7a93SDavid Callahan cl::init(45), cl::ZeroOrMore, 6012585b01SEaswaran Raman cl::desc("Threshold for inlining cold callsites")); 6112585b01SEaswaran Raman 62f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based 63f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and 64f4bb2f0dSEaswaran Raman // BFI. 65f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold( 66fd3e7a93SDavid Callahan "inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore, 67f4bb2f0dSEaswaran Raman cl::desc("Threshold for inlining functions with cold attribute")); 68f4bb2f0dSEaswaran Raman 69de39cb93SDehao Chen static cl::opt<int> 70de39cb93SDehao Chen HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000), 71de39cb93SDehao Chen cl::ZeroOrMore, 72de39cb93SDehao Chen cl::desc("Threshold for hot callsites ")); 73de39cb93SDehao Chen 74974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold( 75974d4eeaSEaswaran Raman "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore, 76974d4eeaSEaswaran Raman cl::desc("Threshold for locally hot callsites ")); 77974d4eeaSEaswaran Raman 78c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq( 79c5fa6358SEaswaran Raman "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, 8002a2bb2fSHiroshi Inoue cl::desc("Maximum block frequency, expressed as a percentage of caller's " 81c5fa6358SEaswaran Raman "entry frequency, for a callsite to be cold in the absence of " 82c5fa6358SEaswaran Raman "profile information.")); 83c5fa6358SEaswaran Raman 84974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq( 85974d4eeaSEaswaran Raman "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore, 86ff77cc75SEaswaran Raman cl::desc("Minimum block frequency, expressed as a multiple of caller's " 87974d4eeaSEaswaran Raman "entry frequency, for a callsite to be hot in the absence of " 88974d4eeaSEaswaran Raman "profile information.")); 89974d4eeaSEaswaran Raman 904924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost( 91fd3e7a93SDavid Callahan "inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore, 920812c5beSHaicheng Wu cl::desc("Compute the full inline cost of a call site even when the cost " 930812c5beSHaicheng Wu "exceeds the threshold.")); 940812c5beSHaicheng Wu 957adc3a2bSChandler Carruth namespace { 96*76aab66dSMircea Trofin class InlineCostCallAnalyzer; 977adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> { 987adc3a2bSChandler Carruth typedef InstVisitor<CallAnalyzer, bool> Base; 997adc3a2bSChandler Carruth friend class InstVisitor<CallAnalyzer, bool>; 1007adc3a2bSChandler Carruth 101*76aab66dSMircea Trofin protected: 1027adc3a2bSChandler Carruth /// The TargetTransformInfo available for this compilation. 1037adc3a2bSChandler Carruth const TargetTransformInfo &TTI; 1047adc3a2bSChandler Carruth 105aec2fa35SDaniel Jasper /// Getter for the cache of @llvm.assume intrinsics. 106aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache; 107aec2fa35SDaniel Jasper 10812585b01SEaswaran Raman /// Getter for BlockFrequencyInfo 10912585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI; 11012585b01SEaswaran Raman 11171069cf6SEaswaran Raman /// Profile summary information. 11271069cf6SEaswaran Raman ProfileSummaryInfo *PSI; 11371069cf6SEaswaran Raman 114f3d122cdSPiotr Padlewski /// The called function. 1157adc3a2bSChandler Carruth Function &F; 1167adc3a2bSChandler Carruth 11785be8ca8SEric Christopher // Cache the DataLayout since we use it a lot. 11885be8ca8SEric Christopher const DataLayout &DL; 11985be8ca8SEric Christopher 1200812c5beSHaicheng Wu /// The OptimizationRemarkEmitter available for this compilation. 1210812c5beSHaicheng Wu OptimizationRemarkEmitter *ORE; 1220812c5beSHaicheng Wu 123f3d122cdSPiotr Padlewski /// The candidate callsite being analyzed. Please do not use this to do 124f3d122cdSPiotr Padlewski /// analysis in the caller function; we want the inline cost query to be 125f3d122cdSPiotr Padlewski /// easily cacheable. Instead, use the cover function paramHasAttr. 126652168a9SFedor Sergeev CallBase &CandidateCall; 1277adc3a2bSChandler Carruth 128*76aab66dSMircea Trofin /// Extension points for handling callsite features. 129*76aab66dSMircea Trofin /// Called after a basic block was analyzed. 130*76aab66dSMircea Trofin virtual void onBlockAnalyzed(const BasicBlock *BB) {} 1311c57cc2bSEaswaran Raman 132*76aab66dSMircea Trofin /// Called at the end of the analysis of the callsite. Return the outcome of 133*76aab66dSMircea Trofin /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or 134*76aab66dSMircea Trofin /// the reason it can't. 135*76aab66dSMircea Trofin virtual InlineResult finalizeAnalysis() { return true; } 136eeae45dcSFedor Sergeev 137*76aab66dSMircea Trofin /// Called when we're about to start processing a basic block, and every time 138*76aab66dSMircea Trofin /// we are done processing an instruction. Return true if there is no point in 139*76aab66dSMircea Trofin /// continuing the analysis (e.g. we've determined already the call site is 140*76aab66dSMircea Trofin /// too expensive to inline) 141*76aab66dSMircea Trofin virtual bool shouldStop() { return false; } 142eeae45dcSFedor Sergeev 143*76aab66dSMircea Trofin /// Called before the analysis of the callee body starts (with callsite 144*76aab66dSMircea Trofin /// contexts propagated). It checks callsite-specific information. Return a 145*76aab66dSMircea Trofin /// reason analysis can't continue if that's the case, or 'true' if it may 146*76aab66dSMircea Trofin /// continue. 147*76aab66dSMircea Trofin virtual InlineResult onAnalysisStart() { return true; } 148*76aab66dSMircea Trofin 149*76aab66dSMircea Trofin /// Called if the analysis engine decides SROA cannot be done for the given 150*76aab66dSMircea Trofin /// alloca. 151*76aab66dSMircea Trofin virtual void onDisableSROA(AllocaInst *Arg) {} 152*76aab66dSMircea Trofin 153*76aab66dSMircea Trofin /// Called the analysis engine determines load elimination won't happen. 154*76aab66dSMircea Trofin virtual void onDisableLoadElimination() {} 155*76aab66dSMircea Trofin 156*76aab66dSMircea Trofin /// Called to account for a call. 157*76aab66dSMircea Trofin virtual void onCallPenalty() {} 158*76aab66dSMircea Trofin 159*76aab66dSMircea Trofin /// Called to account for the expectation the inlining would result in a load 160*76aab66dSMircea Trofin /// elimination. 161*76aab66dSMircea Trofin virtual void onLoadEliminationOpportunity() {} 162*76aab66dSMircea Trofin 163*76aab66dSMircea Trofin /// Called to account for the cost of argument setup for the Call in the 164*76aab66dSMircea Trofin /// callee's body (not the callsite currently under analysis). 165*76aab66dSMircea Trofin virtual void onCallArgumentSetup(const CallBase &Call) {} 166*76aab66dSMircea Trofin 167*76aab66dSMircea Trofin /// Called to account for a load relative intrinsic. 168*76aab66dSMircea Trofin virtual void onLoadRelativeIntrinsic() {} 169*76aab66dSMircea Trofin 170*76aab66dSMircea Trofin /// Called to account for a lowered call. 171*76aab66dSMircea Trofin virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) { 172*76aab66dSMircea Trofin } 173*76aab66dSMircea Trofin 174*76aab66dSMircea Trofin /// Account for a jump table of given size. Return false to stop further 175*76aab66dSMircea Trofin /// processing the switch instruction 176*76aab66dSMircea Trofin virtual bool onJumpTable(unsigned JumpTableSize) { return true; } 177*76aab66dSMircea Trofin 178*76aab66dSMircea Trofin /// Account for a case cluster of given size. Return false to stop further 179*76aab66dSMircea Trofin /// processing of the instruction. 180*76aab66dSMircea Trofin virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; } 181*76aab66dSMircea Trofin 182*76aab66dSMircea Trofin /// Called at the end of processing a switch instruction, with the given 183*76aab66dSMircea Trofin /// number of case clusters. 184*76aab66dSMircea Trofin virtual void onFinalizeSwitch(unsigned JumpTableSize, 185*76aab66dSMircea Trofin unsigned NumCaseCluster) {} 186*76aab66dSMircea Trofin 187*76aab66dSMircea Trofin /// Called to account for any other instruction not specifically accounted 188*76aab66dSMircea Trofin /// for. 189*76aab66dSMircea Trofin virtual void onCommonInstructionSimplification() {} 190*76aab66dSMircea Trofin 191*76aab66dSMircea Trofin /// Start accounting potential benefits due to SROA for the given alloca. 192*76aab66dSMircea Trofin virtual void onInitializeSROAArg(AllocaInst *Arg) {} 193*76aab66dSMircea Trofin 194*76aab66dSMircea Trofin /// Account SROA savings for the AllocaInst value. 195*76aab66dSMircea Trofin virtual void onAggregateSROAUse(AllocaInst *V) {} 196*76aab66dSMircea Trofin 197*76aab66dSMircea Trofin bool handleSROA(Value *V, bool DoNotDisable) { 198*76aab66dSMircea Trofin // Check for SROA candidates in comparisons. 199*76aab66dSMircea Trofin if (auto *SROAArg = getSROAArgForValueOrNull(V)) { 200*76aab66dSMircea Trofin if (DoNotDisable) { 201*76aab66dSMircea Trofin onAggregateSROAUse(SROAArg); 202*76aab66dSMircea Trofin return true; 203*76aab66dSMircea Trofin } 204*76aab66dSMircea Trofin disableSROA(SROAArg); 205*76aab66dSMircea Trofin } 206*76aab66dSMircea Trofin return false; 207*76aab66dSMircea Trofin } 2087adc3a2bSChandler Carruth 209eeae45dcSFedor Sergeev bool IsCallerRecursive = false; 210eeae45dcSFedor Sergeev bool IsRecursiveCall = false; 211eeae45dcSFedor Sergeev bool ExposesReturnsTwice = false; 212eeae45dcSFedor Sergeev bool HasDynamicAlloca = false; 213eeae45dcSFedor Sergeev bool ContainsNoDuplicateCall = false; 214eeae45dcSFedor Sergeev bool HasReturn = false; 215eeae45dcSFedor Sergeev bool HasIndirectBr = false; 216eeae45dcSFedor Sergeev bool HasUninlineableIntrinsic = false; 217eeae45dcSFedor Sergeev bool InitsVargArgs = false; 2187adc3a2bSChandler Carruth 2197adc3a2bSChandler Carruth /// Number of bytes allocated statically by the callee. 220eeae45dcSFedor Sergeev uint64_t AllocatedSize = 0; 221eeae45dcSFedor Sergeev unsigned NumInstructions = 0; 222eeae45dcSFedor Sergeev unsigned NumVectorInstructions = 0; 223eeae45dcSFedor Sergeev 224f3d122cdSPiotr Padlewski /// While we walk the potentially-inlined instructions, we build up and 225f3d122cdSPiotr Padlewski /// maintain a mapping of simplified values specific to this callsite. The 226f3d122cdSPiotr Padlewski /// idea is to propagate any special information we have about arguments to 227f3d122cdSPiotr Padlewski /// this call through the inlinable section of the function, and account for 228f3d122cdSPiotr Padlewski /// likely simplifications post-inlining. The most important aspect we track 229f3d122cdSPiotr Padlewski /// is CFG altering simplifications -- when we prove a basic block dead, that 230f3d122cdSPiotr Padlewski /// can cause dramatic shifts in the cost of inlining a function. 2317adc3a2bSChandler Carruth DenseMap<Value *, Constant *> SimplifiedValues; 2327adc3a2bSChandler Carruth 233f3d122cdSPiotr Padlewski /// Keep track of the values which map back (through function arguments) to 234f3d122cdSPiotr Padlewski /// allocas on the caller stack which could be simplified through SROA. 235*76aab66dSMircea Trofin /// We can disable an association (because for some reason the SROA oportunity 236*76aab66dSMircea Trofin /// is lost) by setting the value to nullptr. We don't delete because we still 237*76aab66dSMircea Trofin /// want isAllocaDerivedArg to function correctly. 238*76aab66dSMircea Trofin DenseMap<Value *, AllocaInst *> SROAArgValues; 2397adc3a2bSChandler Carruth 240f3d122cdSPiotr Padlewski /// Keep track of values which map to a pointer base and constant offset. 2417adc3a2bSChandler Carruth DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs; 2427adc3a2bSChandler Carruth 2433739e14aSHaicheng Wu /// Keep track of dead blocks due to the constant arguments. 2443739e14aSHaicheng Wu SetVector<BasicBlock *> DeadBlocks; 2453739e14aSHaicheng Wu 2463739e14aSHaicheng Wu /// The mapping of the blocks to their known unique successors due to the 2473739e14aSHaicheng Wu /// constant arguments. 2483739e14aSHaicheng Wu DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors; 2493739e14aSHaicheng Wu 250a4461515SHaicheng Wu /// Model the elimination of repeated loads that is expected to happen 251a4461515SHaicheng Wu /// whenever we simplify away the stores that would otherwise cause them to be 252a4461515SHaicheng Wu /// loads. 253a4461515SHaicheng Wu bool EnableLoadElimination; 254a4461515SHaicheng Wu SmallPtrSet<Value *, 16> LoadAddrSet; 255*76aab66dSMircea Trofin 256*76aab66dSMircea Trofin AllocaInst *getSROAArgForValueOrNull(Value *V) const { 257*76aab66dSMircea Trofin auto It = SROAArgValues.find(V); 258*76aab66dSMircea Trofin if (It == SROAArgValues.end()) 259*76aab66dSMircea Trofin return nullptr; 260*76aab66dSMircea Trofin return It->second; 261*76aab66dSMircea Trofin } 262a4461515SHaicheng Wu 2637adc3a2bSChandler Carruth // Custom simplification helper routines. 2647adc3a2bSChandler Carruth bool isAllocaDerivedArg(Value *V); 2657adc3a2bSChandler Carruth void disableSROA(Value *V); 2663739e14aSHaicheng Wu void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB); 267a4461515SHaicheng Wu void disableLoadElimination(); 268201b191bSHaicheng Wu bool isGEPFree(GetElementPtrInst &GEP); 269d3558b5dSEvgeny Astigeevich bool canFoldInboundsGEP(GetElementPtrInst &I); 2707adc3a2bSChandler Carruth bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset); 271652168a9SFedor Sergeev bool simplifyCallSite(Function *F, CallBase &Call); 272617f6364SEaswaran Raman template <typename Callable> 273617f6364SEaswaran Raman bool simplifyInstruction(Instruction &I, Callable Evaluate); 2747adc3a2bSChandler Carruth ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V); 2757adc3a2bSChandler Carruth 2767adc3a2bSChandler Carruth /// Return true if the given argument to the function being considered for 2777adc3a2bSChandler Carruth /// inlining has the given attribute set either at the call site or the 2787adc3a2bSChandler Carruth /// function declaration. Primarily used to inspect call site specific 2797adc3a2bSChandler Carruth /// attributes since these can be more precise than the ones on the callee 2807adc3a2bSChandler Carruth /// itself. 2817adc3a2bSChandler Carruth bool paramHasAttr(Argument *A, Attribute::AttrKind Attr); 2827adc3a2bSChandler Carruth 2837adc3a2bSChandler Carruth /// Return true if the given value is known non null within the callee if 2847adc3a2bSChandler Carruth /// inlined through this particular callsite. 2857adc3a2bSChandler Carruth bool isKnownNonNullInCallee(Value *V); 2867adc3a2bSChandler Carruth 287652168a9SFedor Sergeev /// Return true if size growth is allowed when inlining the callee at \p Call. 288652168a9SFedor Sergeev bool allowSizeGrowth(CallBase &Call); 2899a3fc17aSEaswaran Raman 2907adc3a2bSChandler Carruth // Custom analysis routines. 291c0aa4b75SDavid Bolvansky InlineResult analyzeBlock(BasicBlock *BB, 292c0aa4b75SDavid Bolvansky SmallPtrSetImpl<const Value *> &EphValues); 2937adc3a2bSChandler Carruth 2947adc3a2bSChandler Carruth // Disable several entry points to the visitor so we don't accidentally use 2957adc3a2bSChandler Carruth // them by declaring but not defining them here. 296567556aaSChad Rosier void visit(Module *); 297567556aaSChad Rosier void visit(Module &); 298567556aaSChad Rosier void visit(Function *); 299567556aaSChad Rosier void visit(Function &); 300567556aaSChad Rosier void visit(BasicBlock *); 301567556aaSChad Rosier void visit(BasicBlock &); 3027adc3a2bSChandler Carruth 3037adc3a2bSChandler Carruth // Provide base case for our instruction visit. 3047adc3a2bSChandler Carruth bool visitInstruction(Instruction &I); 3057adc3a2bSChandler Carruth 3067adc3a2bSChandler Carruth // Our visit overrides. 3077adc3a2bSChandler Carruth bool visitAlloca(AllocaInst &I); 3087adc3a2bSChandler Carruth bool visitPHI(PHINode &I); 3097adc3a2bSChandler Carruth bool visitGetElementPtr(GetElementPtrInst &I); 3107adc3a2bSChandler Carruth bool visitBitCast(BitCastInst &I); 3117adc3a2bSChandler Carruth bool visitPtrToInt(PtrToIntInst &I); 3127adc3a2bSChandler Carruth bool visitIntToPtr(IntToPtrInst &I); 3137adc3a2bSChandler Carruth bool visitCastInst(CastInst &I); 3147adc3a2bSChandler Carruth bool visitUnaryInstruction(UnaryInstruction &I); 3157adc3a2bSChandler Carruth bool visitCmpInst(CmpInst &I); 3167adc3a2bSChandler Carruth bool visitSub(BinaryOperator &I); 3177adc3a2bSChandler Carruth bool visitBinaryOperator(BinaryOperator &I); 3186cda33baSCraig Topper bool visitFNeg(UnaryOperator &I); 3197adc3a2bSChandler Carruth bool visitLoad(LoadInst &I); 3207adc3a2bSChandler Carruth bool visitStore(StoreInst &I); 3217adc3a2bSChandler Carruth bool visitExtractValue(ExtractValueInst &I); 3227adc3a2bSChandler Carruth bool visitInsertValue(InsertValueInst &I); 323652168a9SFedor Sergeev bool visitCallBase(CallBase &Call); 3247adc3a2bSChandler Carruth bool visitReturnInst(ReturnInst &RI); 3257adc3a2bSChandler Carruth bool visitBranchInst(BranchInst &BI); 3263ec848bcSHaicheng Wu bool visitSelectInst(SelectInst &SI); 3277adc3a2bSChandler Carruth bool visitSwitchInst(SwitchInst &SI); 3287adc3a2bSChandler Carruth bool visitIndirectBrInst(IndirectBrInst &IBI); 3297adc3a2bSChandler Carruth bool visitResumeInst(ResumeInst &RI); 3307adc3a2bSChandler Carruth bool visitCleanupReturnInst(CleanupReturnInst &RI); 3317adc3a2bSChandler Carruth bool visitCatchReturnInst(CatchReturnInst &RI); 3327adc3a2bSChandler Carruth bool visitUnreachableInst(UnreachableInst &I); 3337adc3a2bSChandler Carruth 3347adc3a2bSChandler Carruth public: 335ab6a6837SSean Silva CallAnalyzer(const TargetTransformInfo &TTI, 336aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 33712585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI, 3380812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, 339*76aab66dSMircea Trofin Function &Callee, CallBase &Call) 34012585b01SEaswaran Raman : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI), 3410812c5beSHaicheng Wu PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE), 342*76aab66dSMircea Trofin CandidateCall(Call), EnableLoadElimination(true) {} 3437adc3a2bSChandler Carruth 34493ac81ccSMircea Trofin InlineResult analyze(); 3457adc3a2bSChandler Carruth 3467adc3a2bSChandler Carruth // Keep a bunch of stats about the cost savings found so we can print them 3477adc3a2bSChandler Carruth // out when debugging. 348eeae45dcSFedor Sergeev unsigned NumConstantArgs = 0; 349eeae45dcSFedor Sergeev unsigned NumConstantOffsetPtrArgs = 0; 350eeae45dcSFedor Sergeev unsigned NumAllocaArgs = 0; 351eeae45dcSFedor Sergeev unsigned NumConstantPtrCmps = 0; 352eeae45dcSFedor Sergeev unsigned NumConstantPtrDiffs = 0; 353eeae45dcSFedor Sergeev unsigned NumInstructionsSimplified = 0; 3547adc3a2bSChandler Carruth 3557adc3a2bSChandler Carruth void dump(); 3567adc3a2bSChandler Carruth }; 3577adc3a2bSChandler Carruth 358*76aab66dSMircea Trofin /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note 359*76aab66dSMircea Trofin /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer 360*76aab66dSMircea Trofin class InlineCostCallAnalyzer final : public CallAnalyzer { 361*76aab66dSMircea Trofin const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1; 362*76aab66dSMircea Trofin const bool ComputeFullInlineCost; 363*76aab66dSMircea Trofin int LoadEliminationCost = 0; 364*76aab66dSMircea Trofin /// Bonus to be applied when percentage of vector instructions in callee is 365*76aab66dSMircea Trofin /// high (see more details in updateThreshold). 366*76aab66dSMircea Trofin int VectorBonus = 0; 367*76aab66dSMircea Trofin /// Bonus to be applied when the callee has only one reachable basic block. 368*76aab66dSMircea Trofin int SingleBBBonus = 0; 369*76aab66dSMircea Trofin 370*76aab66dSMircea Trofin /// Tunable parameters that control the analysis. 371*76aab66dSMircea Trofin const InlineParams &Params; 372*76aab66dSMircea Trofin 373*76aab66dSMircea Trofin /// Upper bound for the inlining cost. Bonuses are being applied to account 374*76aab66dSMircea Trofin /// for speculative "expected profit" of the inlining decision. 375*76aab66dSMircea Trofin int Threshold = 0; 376*76aab66dSMircea Trofin 377*76aab66dSMircea Trofin /// Attempt to evaluate indirect calls to boost its inline cost. 378*76aab66dSMircea Trofin const bool BoostIndirectCalls; 379*76aab66dSMircea Trofin 380*76aab66dSMircea Trofin /// Inlining cost measured in abstract units, accounts for all the 381*76aab66dSMircea Trofin /// instructions expected to be executed for a given function invocation. 382*76aab66dSMircea Trofin /// Instructions that are statically proven to be dead based on call-site 383*76aab66dSMircea Trofin /// arguments are not counted here. 384*76aab66dSMircea Trofin int Cost = 0; 385*76aab66dSMircea Trofin 386*76aab66dSMircea Trofin bool SingleBB = true; 387*76aab66dSMircea Trofin 388*76aab66dSMircea Trofin unsigned SROACostSavings = 0; 389*76aab66dSMircea Trofin unsigned SROACostSavingsLost = 0; 390*76aab66dSMircea Trofin 391*76aab66dSMircea Trofin /// The mapping of caller Alloca values to their accumulated cost savings. If 392*76aab66dSMircea Trofin /// we have to disable SROA for one of the allocas, this tells us how much 393*76aab66dSMircea Trofin /// cost must be added. 394*76aab66dSMircea Trofin DenseMap<AllocaInst *, int> SROAArgCosts; 395*76aab66dSMircea Trofin 396*76aab66dSMircea Trofin /// Return true if \p Call is a cold callsite. 397*76aab66dSMircea Trofin bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI); 398*76aab66dSMircea Trofin 399*76aab66dSMircea Trofin /// Update Threshold based on callsite properties such as callee 400*76aab66dSMircea Trofin /// attributes and callee hotness for PGO builds. The Callee is explicitly 401*76aab66dSMircea Trofin /// passed to support analyzing indirect calls whose target is inferred by 402*76aab66dSMircea Trofin /// analysis. 403*76aab66dSMircea Trofin void updateThreshold(CallBase &Call, Function &Callee); 404*76aab66dSMircea Trofin /// Return a higher threshold if \p Call is a hot callsite. 405*76aab66dSMircea Trofin Optional<int> getHotCallSiteThreshold(CallBase &Call, 406*76aab66dSMircea Trofin BlockFrequencyInfo *CallerBFI); 407*76aab66dSMircea Trofin 408*76aab66dSMircea Trofin /// Handle a capped 'int' increment for Cost. 409*76aab66dSMircea Trofin void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) { 410*76aab66dSMircea Trofin assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound"); 411*76aab66dSMircea Trofin Cost = (int)std::min(UpperBound, Cost + Inc); 412*76aab66dSMircea Trofin } 413*76aab66dSMircea Trofin 414*76aab66dSMircea Trofin void onDisableSROA(AllocaInst *Arg) override { 415*76aab66dSMircea Trofin auto CostIt = SROAArgCosts.find(Arg); 416*76aab66dSMircea Trofin if (CostIt == SROAArgCosts.end()) 417*76aab66dSMircea Trofin return; 418*76aab66dSMircea Trofin addCost(CostIt->second); 419*76aab66dSMircea Trofin SROACostSavings -= CostIt->second; 420*76aab66dSMircea Trofin SROACostSavingsLost += CostIt->second; 421*76aab66dSMircea Trofin SROAArgCosts.erase(CostIt); 422*76aab66dSMircea Trofin } 423*76aab66dSMircea Trofin 424*76aab66dSMircea Trofin void onDisableLoadElimination() override { 425*76aab66dSMircea Trofin addCost(LoadEliminationCost); 426*76aab66dSMircea Trofin LoadEliminationCost = 0; 427*76aab66dSMircea Trofin } 428*76aab66dSMircea Trofin void onCallPenalty() override { addCost(InlineConstants::CallPenalty); } 429*76aab66dSMircea Trofin void onCallArgumentSetup(const CallBase &Call) override { 430*76aab66dSMircea Trofin // Pay the price of the argument setup. We account for the average 1 431*76aab66dSMircea Trofin // instruction per call argument setup here. 432*76aab66dSMircea Trofin addCost(Call.arg_size() * InlineConstants::InstrCost); 433*76aab66dSMircea Trofin } 434*76aab66dSMircea Trofin void onLoadRelativeIntrinsic() override { 435*76aab66dSMircea Trofin // This is normally lowered to 4 LLVM instructions. 436*76aab66dSMircea Trofin addCost(3 * InlineConstants::InstrCost); 437*76aab66dSMircea Trofin } 438*76aab66dSMircea Trofin void onLoweredCall(Function *F, CallBase &Call, 439*76aab66dSMircea Trofin bool IsIndirectCall) override { 440*76aab66dSMircea Trofin // We account for the average 1 instruction per call argument setup here. 441*76aab66dSMircea Trofin addCost(Call.arg_size() * InlineConstants::InstrCost); 442*76aab66dSMircea Trofin 443*76aab66dSMircea Trofin // If we have a constant that we are calling as a function, we can peer 444*76aab66dSMircea Trofin // through it and see the function target. This happens not infrequently 445*76aab66dSMircea Trofin // during devirtualization and so we want to give it a hefty bonus for 446*76aab66dSMircea Trofin // inlining, but cap that bonus in the event that inlining wouldn't pan out. 447*76aab66dSMircea Trofin // Pretend to inline the function, with a custom threshold. 448*76aab66dSMircea Trofin if (IsIndirectCall && BoostIndirectCalls) { 449*76aab66dSMircea Trofin auto IndirectCallParams = Params; 450*76aab66dSMircea Trofin IndirectCallParams.DefaultThreshold = 451*76aab66dSMircea Trofin InlineConstants::IndirectCallThreshold; 452*76aab66dSMircea Trofin /// FIXME: if InlineCostCallAnalyzer is derived from, this may need 453*76aab66dSMircea Trofin /// to instantiate the derived class. 454*76aab66dSMircea Trofin InlineCostCallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F, 455*76aab66dSMircea Trofin Call, IndirectCallParams, false); 456*76aab66dSMircea Trofin if (CA.analyze()) { 457*76aab66dSMircea Trofin // We were able to inline the indirect call! Subtract the cost from the 458*76aab66dSMircea Trofin // threshold to get the bonus we want to apply, but don't go below zero. 459*76aab66dSMircea Trofin Cost -= std::max(0, CA.getThreshold() - CA.getCost()); 460*76aab66dSMircea Trofin } 461*76aab66dSMircea Trofin } else 462*76aab66dSMircea Trofin // Otherwise simply add the cost for merely making the call. 463*76aab66dSMircea Trofin addCost(InlineConstants::CallPenalty); 464*76aab66dSMircea Trofin } 465*76aab66dSMircea Trofin 466*76aab66dSMircea Trofin void onFinalizeSwitch(unsigned JumpTableSize, 467*76aab66dSMircea Trofin unsigned NumCaseCluster) override { 468*76aab66dSMircea Trofin // If suitable for a jump table, consider the cost for the table size and 469*76aab66dSMircea Trofin // branch to destination. 470*76aab66dSMircea Trofin // Maximum valid cost increased in this function. 471*76aab66dSMircea Trofin if (JumpTableSize) { 472*76aab66dSMircea Trofin int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost + 473*76aab66dSMircea Trofin 4 * InlineConstants::InstrCost; 474*76aab66dSMircea Trofin 475*76aab66dSMircea Trofin addCost(JTCost, (int64_t)CostUpperBound); 476*76aab66dSMircea Trofin return; 477*76aab66dSMircea Trofin } 478*76aab66dSMircea Trofin // Considering forming a binary search, we should find the number of nodes 479*76aab66dSMircea Trofin // which is same as the number of comparisons when lowered. For a given 480*76aab66dSMircea Trofin // number of clusters, n, we can define a recursive function, f(n), to find 481*76aab66dSMircea Trofin // the number of nodes in the tree. The recursion is : 482*76aab66dSMircea Trofin // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3, 483*76aab66dSMircea Trofin // and f(n) = n, when n <= 3. 484*76aab66dSMircea Trofin // This will lead a binary tree where the leaf should be either f(2) or f(3) 485*76aab66dSMircea Trofin // when n > 3. So, the number of comparisons from leaves should be n, while 486*76aab66dSMircea Trofin // the number of non-leaf should be : 487*76aab66dSMircea Trofin // 2^(log2(n) - 1) - 1 488*76aab66dSMircea Trofin // = 2^log2(n) * 2^-1 - 1 489*76aab66dSMircea Trofin // = n / 2 - 1. 490*76aab66dSMircea Trofin // Considering comparisons from leaf and non-leaf nodes, we can estimate the 491*76aab66dSMircea Trofin // number of comparisons in a simple closed form : 492*76aab66dSMircea Trofin // n + n / 2 - 1 = n * 3 / 2 - 1 493*76aab66dSMircea Trofin if (NumCaseCluster <= 3) { 494*76aab66dSMircea Trofin // Suppose a comparison includes one compare and one conditional branch. 495*76aab66dSMircea Trofin addCost(NumCaseCluster * 2 * InlineConstants::InstrCost); 496*76aab66dSMircea Trofin return; 497*76aab66dSMircea Trofin } 498*76aab66dSMircea Trofin 499*76aab66dSMircea Trofin int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1; 500*76aab66dSMircea Trofin int64_t SwitchCost = 501*76aab66dSMircea Trofin ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost; 502*76aab66dSMircea Trofin 503*76aab66dSMircea Trofin addCost(SwitchCost, (int64_t)CostUpperBound); 504*76aab66dSMircea Trofin } 505*76aab66dSMircea Trofin void onCommonInstructionSimplification() override { 506*76aab66dSMircea Trofin addCost(InlineConstants::InstrCost); 507*76aab66dSMircea Trofin } 508*76aab66dSMircea Trofin 509*76aab66dSMircea Trofin void onInitializeSROAArg(AllocaInst *Arg) override { SROAArgCosts[Arg] = 0; } 510*76aab66dSMircea Trofin 511*76aab66dSMircea Trofin void onAggregateSROAUse(AllocaInst *SROAArg) override { 512*76aab66dSMircea Trofin auto CostIt = SROAArgCosts.find(SROAArg); 513*76aab66dSMircea Trofin CostIt->second += InlineConstants::InstrCost; 514*76aab66dSMircea Trofin SROACostSavings += InlineConstants::InstrCost; 515*76aab66dSMircea Trofin } 516*76aab66dSMircea Trofin 517*76aab66dSMircea Trofin virtual void onBlockAnalyzed(const BasicBlock *BB) override { 518*76aab66dSMircea Trofin auto *TI = BB->getTerminator(); 519*76aab66dSMircea Trofin // If we had any successors at this point, than post-inlining is likely to 520*76aab66dSMircea Trofin // have them as well. Note that we assume any basic blocks which existed 521*76aab66dSMircea Trofin // due to branches or switches which folded above will also fold after 522*76aab66dSMircea Trofin // inlining. 523*76aab66dSMircea Trofin if (SingleBB && TI->getNumSuccessors() > 1) { 524*76aab66dSMircea Trofin // Take off the bonus we applied to the threshold. 525*76aab66dSMircea Trofin Threshold -= SingleBBBonus; 526*76aab66dSMircea Trofin SingleBB = false; 527*76aab66dSMircea Trofin } 528*76aab66dSMircea Trofin } 529*76aab66dSMircea Trofin virtual InlineResult finalizeAnalysis() override { 530*76aab66dSMircea Trofin // Loops generally act a lot like calls in that they act like barriers to 531*76aab66dSMircea Trofin // movement, require a certain amount of setup, etc. So when optimising for 532*76aab66dSMircea Trofin // size, we penalise any call sites that perform loops. We do this after all 533*76aab66dSMircea Trofin // other costs here, so will likely only be dealing with relatively small 534*76aab66dSMircea Trofin // functions (and hence DT and LI will hopefully be cheap). 535*76aab66dSMircea Trofin auto *Caller = CandidateCall.getFunction(); 536*76aab66dSMircea Trofin if (Caller->hasMinSize()) { 537*76aab66dSMircea Trofin DominatorTree DT(F); 538*76aab66dSMircea Trofin LoopInfo LI(DT); 539*76aab66dSMircea Trofin int NumLoops = 0; 540*76aab66dSMircea Trofin for (Loop *L : LI) { 541*76aab66dSMircea Trofin // Ignore loops that will not be executed 542*76aab66dSMircea Trofin if (DeadBlocks.count(L->getHeader())) 543*76aab66dSMircea Trofin continue; 544*76aab66dSMircea Trofin NumLoops++; 545*76aab66dSMircea Trofin } 546*76aab66dSMircea Trofin addCost(NumLoops * InlineConstants::CallPenalty); 547*76aab66dSMircea Trofin } 548*76aab66dSMircea Trofin 549*76aab66dSMircea Trofin // We applied the maximum possible vector bonus at the beginning. Now, 550*76aab66dSMircea Trofin // subtract the excess bonus, if any, from the Threshold before 551*76aab66dSMircea Trofin // comparing against Cost. 552*76aab66dSMircea Trofin if (NumVectorInstructions <= NumInstructions / 10) 553*76aab66dSMircea Trofin Threshold -= VectorBonus; 554*76aab66dSMircea Trofin else if (NumVectorInstructions <= NumInstructions / 2) 555*76aab66dSMircea Trofin Threshold -= VectorBonus / 2; 556*76aab66dSMircea Trofin 557*76aab66dSMircea Trofin return Cost < std::max(1, Threshold); 558*76aab66dSMircea Trofin } 559*76aab66dSMircea Trofin virtual bool shouldStop() override { 560*76aab66dSMircea Trofin // Bail out the moment we cross the threshold. This means we'll under-count 561*76aab66dSMircea Trofin // the cost, but only when undercounting doesn't matter. 562*76aab66dSMircea Trofin return Cost >= Threshold && !ComputeFullInlineCost; 563*76aab66dSMircea Trofin } 564*76aab66dSMircea Trofin 565*76aab66dSMircea Trofin virtual void onLoadEliminationOpportunity() { 566*76aab66dSMircea Trofin LoadEliminationCost += InlineConstants::InstrCost; 567*76aab66dSMircea Trofin } 568*76aab66dSMircea Trofin 569*76aab66dSMircea Trofin InlineResult onAnalysisStart() override { 570*76aab66dSMircea Trofin // Perform some tweaks to the cost and threshold based on the direct 571*76aab66dSMircea Trofin // callsite information. 572*76aab66dSMircea Trofin 573*76aab66dSMircea Trofin // We want to more aggressively inline vector-dense kernels, so up the 574*76aab66dSMircea Trofin // threshold, and we'll lower it if the % of vector instructions gets too 575*76aab66dSMircea Trofin // low. Note that these bonuses are some what arbitrary and evolved over 576*76aab66dSMircea Trofin // time by accident as much as because they are principled bonuses. 577*76aab66dSMircea Trofin // 578*76aab66dSMircea Trofin // FIXME: It would be nice to remove all such bonuses. At least it would be 579*76aab66dSMircea Trofin // nice to base the bonus values on something more scientific. 580*76aab66dSMircea Trofin assert(NumInstructions == 0); 581*76aab66dSMircea Trofin assert(NumVectorInstructions == 0); 582*76aab66dSMircea Trofin 583*76aab66dSMircea Trofin // Update the threshold based on callsite properties 584*76aab66dSMircea Trofin updateThreshold(CandidateCall, F); 585*76aab66dSMircea Trofin 586*76aab66dSMircea Trofin // While Threshold depends on commandline options that can take negative 587*76aab66dSMircea Trofin // values, we want to enforce the invariant that the computed threshold and 588*76aab66dSMircea Trofin // bonuses are non-negative. 589*76aab66dSMircea Trofin assert(Threshold >= 0); 590*76aab66dSMircea Trofin assert(SingleBBBonus >= 0); 591*76aab66dSMircea Trofin assert(VectorBonus >= 0); 592*76aab66dSMircea Trofin 593*76aab66dSMircea Trofin // Speculatively apply all possible bonuses to Threshold. If cost exceeds 594*76aab66dSMircea Trofin // this Threshold any time, and cost cannot decrease, we can stop processing 595*76aab66dSMircea Trofin // the rest of the function body. 596*76aab66dSMircea Trofin Threshold += (SingleBBBonus + VectorBonus); 597*76aab66dSMircea Trofin 598*76aab66dSMircea Trofin // Give out bonuses for the callsite, as the instructions setting them up 599*76aab66dSMircea Trofin // will be gone after inlining. 600*76aab66dSMircea Trofin addCost(-getCallsiteCost(this->CandidateCall, DL)); 601*76aab66dSMircea Trofin 602*76aab66dSMircea Trofin // If this function uses the coldcc calling convention, prefer not to inline 603*76aab66dSMircea Trofin // it. 604*76aab66dSMircea Trofin if (F.getCallingConv() == CallingConv::Cold) 605*76aab66dSMircea Trofin Cost += InlineConstants::ColdccPenalty; 606*76aab66dSMircea Trofin 607*76aab66dSMircea Trofin // Check if we're done. This can happen due to bonuses and penalties. 608*76aab66dSMircea Trofin if (Cost >= Threshold && !ComputeFullInlineCost) 609*76aab66dSMircea Trofin return "high cost"; 610*76aab66dSMircea Trofin 611*76aab66dSMircea Trofin return true; 612*76aab66dSMircea Trofin } 613*76aab66dSMircea Trofin 614*76aab66dSMircea Trofin public: 615*76aab66dSMircea Trofin InlineCostCallAnalyzer( 616*76aab66dSMircea Trofin const TargetTransformInfo &TTI, 617*76aab66dSMircea Trofin std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 618*76aab66dSMircea Trofin Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI, 619*76aab66dSMircea Trofin ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee, 620*76aab66dSMircea Trofin CallBase &Call, const InlineParams &Params, bool BoostIndirect = true) 621*76aab66dSMircea Trofin : CallAnalyzer(TTI, GetAssumptionCache, GetBFI, PSI, ORE, Callee, Call), 622*76aab66dSMircea Trofin ComputeFullInlineCost(OptComputeFullInlineCost || 623*76aab66dSMircea Trofin Params.ComputeFullInlineCost || ORE), 624*76aab66dSMircea Trofin Params(Params), Threshold(Params.DefaultThreshold), 625*76aab66dSMircea Trofin BoostIndirectCalls(BoostIndirect) {} 626*76aab66dSMircea Trofin void dump(); 627*76aab66dSMircea Trofin 628*76aab66dSMircea Trofin int getThreshold() { return Threshold; } 629*76aab66dSMircea Trofin int getCost() { return Cost; } 630*76aab66dSMircea Trofin }; 6317adc3a2bSChandler Carruth } // namespace 6327adc3a2bSChandler Carruth 6335f8f34e4SAdrian Prantl /// Test whether the given value is an Alloca-derived function argument. 6347adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) { 6357adc3a2bSChandler Carruth return SROAArgValues.count(V); 6367adc3a2bSChandler Carruth } 6377adc3a2bSChandler Carruth 6385f8f34e4SAdrian Prantl /// If 'V' maps to a SROA candidate, disable SROA for it. 6397adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) { 640*76aab66dSMircea Trofin auto It = SROAArgValues.find(V); 641*76aab66dSMircea Trofin if (It == SROAArgValues.end()) 642*76aab66dSMircea Trofin return; 643*76aab66dSMircea Trofin auto *SROAArg = It->second; 644*76aab66dSMircea Trofin if (!SROAArg) 645*76aab66dSMircea Trofin return; 646*76aab66dSMircea Trofin It->second = nullptr; 647*76aab66dSMircea Trofin onDisableSROA(SROAArg); 648*76aab66dSMircea Trofin disableLoadElimination(); 6497adc3a2bSChandler Carruth } 6507adc3a2bSChandler Carruth 651a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() { 652a4461515SHaicheng Wu if (EnableLoadElimination) { 653*76aab66dSMircea Trofin onDisableLoadElimination(); 654a4461515SHaicheng Wu EnableLoadElimination = false; 655a4461515SHaicheng Wu } 656a4461515SHaicheng Wu } 657a4461515SHaicheng Wu 6585f8f34e4SAdrian Prantl /// Accumulate a constant GEP offset into an APInt if possible. 6597adc3a2bSChandler Carruth /// 6607adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any 6617adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite. 6627adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) { 663945b7e5aSElena Demikhovsky unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType()); 6647adc3a2bSChandler Carruth assert(IntPtrWidth == Offset.getBitWidth()); 6657adc3a2bSChandler Carruth 6667adc3a2bSChandler Carruth for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); 6677adc3a2bSChandler Carruth GTI != GTE; ++GTI) { 6687adc3a2bSChandler Carruth ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 6697adc3a2bSChandler Carruth if (!OpC) 6707adc3a2bSChandler Carruth if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand())) 6717adc3a2bSChandler Carruth OpC = dyn_cast<ConstantInt>(SimpleOp); 6727adc3a2bSChandler Carruth if (!OpC) 6737adc3a2bSChandler Carruth return false; 674567556aaSChad Rosier if (OpC->isZero()) 675567556aaSChad Rosier continue; 6767adc3a2bSChandler Carruth 6777adc3a2bSChandler Carruth // Handle a struct index, which adds its field offset to the pointer. 678ab85225bSPeter Collingbourne if (StructType *STy = GTI.getStructTypeOrNull()) { 6797adc3a2bSChandler Carruth unsigned ElementIdx = OpC->getZExtValue(); 6807adc3a2bSChandler Carruth const StructLayout *SL = DL.getStructLayout(STy); 6817adc3a2bSChandler Carruth Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx)); 6827adc3a2bSChandler Carruth continue; 6837adc3a2bSChandler Carruth } 6847adc3a2bSChandler Carruth 6857adc3a2bSChandler Carruth APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType())); 6867adc3a2bSChandler Carruth Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize; 6877adc3a2bSChandler Carruth } 6887adc3a2bSChandler Carruth return true; 6897adc3a2bSChandler Carruth } 6907adc3a2bSChandler Carruth 6915f8f34e4SAdrian Prantl /// Use TTI to check whether a GEP is free. 692201b191bSHaicheng Wu /// 693201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite. 694201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) { 69561c1bd5aSEvgeny Astigeevich SmallVector<Value *, 4> Operands; 69661c1bd5aSEvgeny Astigeevich Operands.push_back(GEP.getOperand(0)); 697201b191bSHaicheng Wu for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 698201b191bSHaicheng Wu if (Constant *SimpleOp = SimplifiedValues.lookup(*I)) 69961c1bd5aSEvgeny Astigeevich Operands.push_back(SimpleOp); 700201b191bSHaicheng Wu else 70161c1bd5aSEvgeny Astigeevich Operands.push_back(*I); 70261c1bd5aSEvgeny Astigeevich return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands); 703201b191bSHaicheng Wu } 704201b191bSHaicheng Wu 7057adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) { 7067adc3a2bSChandler Carruth // Check whether inlining will turn a dynamic alloca into a static 7070f153424SSanjay Patel // alloca and handle that case. 7087adc3a2bSChandler Carruth if (I.isArrayAllocation()) { 7090f153424SSanjay Patel Constant *Size = SimplifiedValues.lookup(I.getArraySize()); 7100f153424SSanjay Patel if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) { 7117adc3a2bSChandler Carruth Type *Ty = I.getAllocatedType(); 71222eb80a1SEaswaran Raman AllocatedSize = SaturatingMultiplyAdd( 713b302561bSGraham Hunter AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty).getFixedSize(), 714b302561bSGraham Hunter AllocatedSize); 7157adc3a2bSChandler Carruth return Base::visitAlloca(I); 7167adc3a2bSChandler Carruth } 7177adc3a2bSChandler Carruth } 7187adc3a2bSChandler Carruth 7197adc3a2bSChandler Carruth // Accumulate the allocated size. 7207adc3a2bSChandler Carruth if (I.isStaticAlloca()) { 7217adc3a2bSChandler Carruth Type *Ty = I.getAllocatedType(); 7225a956c85SMircea Trofin AllocatedSize = 7235a956c85SMircea Trofin SaturatingAdd(DL.getTypeAllocSize(Ty).getFixedSize(), AllocatedSize); 7247adc3a2bSChandler Carruth } 7257adc3a2bSChandler Carruth 7267adc3a2bSChandler Carruth // We will happily inline static alloca instructions. 7277adc3a2bSChandler Carruth if (I.isStaticAlloca()) 7287adc3a2bSChandler Carruth return Base::visitAlloca(I); 7297adc3a2bSChandler Carruth 7307adc3a2bSChandler Carruth // FIXME: This is overly conservative. Dynamic allocas are inefficient for 7317adc3a2bSChandler Carruth // a variety of reasons, and so we would like to not inline them into 7327adc3a2bSChandler Carruth // functions which don't currently have a dynamic alloca. This simply 7337adc3a2bSChandler Carruth // disables inlining altogether in the presence of a dynamic alloca. 7347adc3a2bSChandler Carruth HasDynamicAlloca = true; 7357adc3a2bSChandler Carruth return false; 7367adc3a2bSChandler Carruth } 7377adc3a2bSChandler Carruth 7387adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) { 7397adc3a2bSChandler Carruth // FIXME: We need to propagate SROA *disabling* through phi nodes, even 7407adc3a2bSChandler Carruth // though we don't want to propagate it's bonuses. The idea is to disable 7417adc3a2bSChandler Carruth // SROA if it *might* be used in an inappropriate manner. 7427adc3a2bSChandler Carruth 7437adc3a2bSChandler Carruth // Phi nodes are always zero-cost. 74477f32994SBjorn Pettersson // FIXME: Pointer sizes may differ between different address spaces, so do we 74577f32994SBjorn Pettersson // need to use correct address space in the call to getPointerSizeInBits here? 74677f32994SBjorn Pettersson // Or could we skip the getPointerSizeInBits call completely? As far as I can 74777f32994SBjorn Pettersson // see the ZeroOffset is used as a dummy value, so we can probably use any 74877f32994SBjorn Pettersson // bit width for the ZeroOffset? 74977f32994SBjorn Pettersson APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0)); 7503739e14aSHaicheng Wu bool CheckSROA = I.getType()->isPointerTy(); 7513739e14aSHaicheng Wu 7523739e14aSHaicheng Wu // Track the constant or pointer with constant offset we've seen so far. 7533739e14aSHaicheng Wu Constant *FirstC = nullptr; 7543739e14aSHaicheng Wu std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset}; 7553739e14aSHaicheng Wu Value *FirstV = nullptr; 7563739e14aSHaicheng Wu 7573739e14aSHaicheng Wu for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) { 7583739e14aSHaicheng Wu BasicBlock *Pred = I.getIncomingBlock(i); 7593739e14aSHaicheng Wu // If the incoming block is dead, skip the incoming block. 7603739e14aSHaicheng Wu if (DeadBlocks.count(Pred)) 7613739e14aSHaicheng Wu continue; 7623739e14aSHaicheng Wu // If the parent block of phi is not the known successor of the incoming 7633739e14aSHaicheng Wu // block, skip the incoming block. 7643739e14aSHaicheng Wu BasicBlock *KnownSuccessor = KnownSuccessors[Pred]; 7653739e14aSHaicheng Wu if (KnownSuccessor && KnownSuccessor != I.getParent()) 7663739e14aSHaicheng Wu continue; 7673739e14aSHaicheng Wu 7683739e14aSHaicheng Wu Value *V = I.getIncomingValue(i); 7693739e14aSHaicheng Wu // If the incoming value is this phi itself, skip the incoming value. 7703739e14aSHaicheng Wu if (&I == V) 7713739e14aSHaicheng Wu continue; 7723739e14aSHaicheng Wu 7733739e14aSHaicheng Wu Constant *C = dyn_cast<Constant>(V); 7743739e14aSHaicheng Wu if (!C) 7753739e14aSHaicheng Wu C = SimplifiedValues.lookup(V); 7763739e14aSHaicheng Wu 7773739e14aSHaicheng Wu std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset}; 7783739e14aSHaicheng Wu if (!C && CheckSROA) 7793739e14aSHaicheng Wu BaseAndOffset = ConstantOffsetPtrs.lookup(V); 7803739e14aSHaicheng Wu 7813739e14aSHaicheng Wu if (!C && !BaseAndOffset.first) 7823739e14aSHaicheng Wu // The incoming value is neither a constant nor a pointer with constant 7833739e14aSHaicheng Wu // offset, exit early. 7843739e14aSHaicheng Wu return true; 7853739e14aSHaicheng Wu 7863739e14aSHaicheng Wu if (FirstC) { 7873739e14aSHaicheng Wu if (FirstC == C) 7883739e14aSHaicheng Wu // If we've seen a constant incoming value before and it is the same 7893739e14aSHaicheng Wu // constant we see this time, continue checking the next incoming value. 7903739e14aSHaicheng Wu continue; 7913739e14aSHaicheng Wu // Otherwise early exit because we either see a different constant or saw 7923739e14aSHaicheng Wu // a constant before but we have a pointer with constant offset this time. 7933739e14aSHaicheng Wu return true; 7943739e14aSHaicheng Wu } 7953739e14aSHaicheng Wu 7963739e14aSHaicheng Wu if (FirstV) { 7973739e14aSHaicheng Wu // The same logic as above, but check pointer with constant offset here. 7983739e14aSHaicheng Wu if (FirstBaseAndOffset == BaseAndOffset) 7993739e14aSHaicheng Wu continue; 8003739e14aSHaicheng Wu return true; 8013739e14aSHaicheng Wu } 8023739e14aSHaicheng Wu 8033739e14aSHaicheng Wu if (C) { 8043739e14aSHaicheng Wu // This is the 1st time we've seen a constant, record it. 8053739e14aSHaicheng Wu FirstC = C; 8063739e14aSHaicheng Wu continue; 8073739e14aSHaicheng Wu } 8083739e14aSHaicheng Wu 8093739e14aSHaicheng Wu // The remaining case is that this is the 1st time we've seen a pointer with 8103739e14aSHaicheng Wu // constant offset, record it. 8113739e14aSHaicheng Wu FirstV = V; 8123739e14aSHaicheng Wu FirstBaseAndOffset = BaseAndOffset; 8133739e14aSHaicheng Wu } 8143739e14aSHaicheng Wu 8153739e14aSHaicheng Wu // Check if we can map phi to a constant. 8163739e14aSHaicheng Wu if (FirstC) { 8173739e14aSHaicheng Wu SimplifiedValues[&I] = FirstC; 8183739e14aSHaicheng Wu return true; 8193739e14aSHaicheng Wu } 8203739e14aSHaicheng Wu 8213739e14aSHaicheng Wu // Check if we can map phi to a pointer with constant offset. 8223739e14aSHaicheng Wu if (FirstBaseAndOffset.first) { 8233739e14aSHaicheng Wu ConstantOffsetPtrs[&I] = FirstBaseAndOffset; 8243739e14aSHaicheng Wu 825*76aab66dSMircea Trofin if (auto *SROAArg = getSROAArgForValueOrNull(FirstV)) 8263739e14aSHaicheng Wu SROAArgValues[&I] = SROAArg; 8273739e14aSHaicheng Wu } 8283739e14aSHaicheng Wu 8297adc3a2bSChandler Carruth return true; 8307adc3a2bSChandler Carruth } 8317adc3a2bSChandler Carruth 8325f8f34e4SAdrian Prantl /// Check we can fold GEPs of constant-offset call site argument pointers. 833d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs. 834d3558b5dSEvgeny Astigeevich /// 835d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded. 836d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) { 837d3558b5dSEvgeny Astigeevich // Check if we have a base + offset for the pointer. 838d3558b5dSEvgeny Astigeevich std::pair<Value *, APInt> BaseAndOffset = 839d3558b5dSEvgeny Astigeevich ConstantOffsetPtrs.lookup(I.getPointerOperand()); 840d3558b5dSEvgeny Astigeevich if (!BaseAndOffset.first) 841d3558b5dSEvgeny Astigeevich return false; 842d3558b5dSEvgeny Astigeevich 843d3558b5dSEvgeny Astigeevich // Check if the offset of this GEP is constant, and if so accumulate it 844d3558b5dSEvgeny Astigeevich // into Offset. 845d3558b5dSEvgeny Astigeevich if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) 846d3558b5dSEvgeny Astigeevich return false; 847d3558b5dSEvgeny Astigeevich 848d3558b5dSEvgeny Astigeevich // Add the result as a new mapping to Base + Offset. 849d3558b5dSEvgeny Astigeevich ConstantOffsetPtrs[&I] = BaseAndOffset; 850d3558b5dSEvgeny Astigeevich 851d3558b5dSEvgeny Astigeevich return true; 852d3558b5dSEvgeny Astigeevich } 853d3558b5dSEvgeny Astigeevich 8547adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) { 8557adc3a2bSChandler Carruth DenseMap<Value *, int>::iterator CostIt; 856*76aab66dSMircea Trofin auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand()); 8577adc3a2bSChandler Carruth 858a8b9cdc9SEaswaran Raman // Lambda to check whether a GEP's indices are all constant. 859a8b9cdc9SEaswaran Raman auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) { 860a8b9cdc9SEaswaran Raman for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 861a8b9cdc9SEaswaran Raman if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I)) 862a8b9cdc9SEaswaran Raman return false; 863a8b9cdc9SEaswaran Raman return true; 864a8b9cdc9SEaswaran Raman }; 865a8b9cdc9SEaswaran Raman 866d3558b5dSEvgeny Astigeevich if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) { 867*76aab66dSMircea Trofin if (SROAArg) 8687adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 8697adc3a2bSChandler Carruth 8707adc3a2bSChandler Carruth // Constant GEPs are modeled as free. 8717adc3a2bSChandler Carruth return true; 8727adc3a2bSChandler Carruth } 8737adc3a2bSChandler Carruth 8747adc3a2bSChandler Carruth // Variable GEPs will require math and will disable SROA. 875*76aab66dSMircea Trofin if (SROAArg) 876*76aab66dSMircea Trofin disableSROA(SROAArg); 877201b191bSHaicheng Wu return isGEPFree(I); 8787adc3a2bSChandler Carruth } 8797adc3a2bSChandler Carruth 880617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues. 881617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the 882617f6364SEaswaran Raman /// instruction when all the operands are constants. 883617f6364SEaswaran Raman template <typename Callable> 884617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) { 885617f6364SEaswaran Raman SmallVector<Constant *, 2> COps; 886617f6364SEaswaran Raman for (Value *Op : I.operands()) { 887617f6364SEaswaran Raman Constant *COp = dyn_cast<Constant>(Op); 8887adc3a2bSChandler Carruth if (!COp) 889617f6364SEaswaran Raman COp = SimplifiedValues.lookup(Op); 890617f6364SEaswaran Raman if (!COp) 891617f6364SEaswaran Raman return false; 892617f6364SEaswaran Raman COps.push_back(COp); 893617f6364SEaswaran Raman } 894617f6364SEaswaran Raman auto *C = Evaluate(COps); 895617f6364SEaswaran Raman if (!C) 896617f6364SEaswaran Raman return false; 8977adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 8987adc3a2bSChandler Carruth return true; 8997adc3a2bSChandler Carruth } 9007adc3a2bSChandler Carruth 901617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) { 902617f6364SEaswaran Raman // Propagate constants through bitcasts. 903617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 904617f6364SEaswaran Raman return ConstantExpr::getBitCast(COps[0], I.getType()); 905617f6364SEaswaran Raman })) 906617f6364SEaswaran Raman return true; 907617f6364SEaswaran Raman 9087adc3a2bSChandler Carruth // Track base/offsets through casts 909567556aaSChad Rosier std::pair<Value *, APInt> BaseAndOffset = 910567556aaSChad Rosier ConstantOffsetPtrs.lookup(I.getOperand(0)); 9117adc3a2bSChandler Carruth // Casts don't change the offset, just wrap it up. 9127adc3a2bSChandler Carruth if (BaseAndOffset.first) 9137adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 9147adc3a2bSChandler Carruth 9157adc3a2bSChandler Carruth // Also look for SROA candidates here. 916*76aab66dSMircea Trofin if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0))) 9177adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 9187adc3a2bSChandler Carruth 9197adc3a2bSChandler Carruth // Bitcasts are always zero cost. 9207adc3a2bSChandler Carruth return true; 9217adc3a2bSChandler Carruth } 9227adc3a2bSChandler Carruth 9237adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) { 9247adc3a2bSChandler Carruth // Propagate constants through ptrtoint. 925617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 926617f6364SEaswaran Raman return ConstantExpr::getPtrToInt(COps[0], I.getType()); 927617f6364SEaswaran Raman })) 9287adc3a2bSChandler Carruth return true; 9297adc3a2bSChandler Carruth 9307adc3a2bSChandler Carruth // Track base/offset pairs when converted to a plain integer provided the 9317adc3a2bSChandler Carruth // integer is large enough to represent the pointer. 9327adc3a2bSChandler Carruth unsigned IntegerSize = I.getType()->getScalarSizeInBits(); 93377f32994SBjorn Pettersson unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace(); 93477f32994SBjorn Pettersson if (IntegerSize >= DL.getPointerSizeInBits(AS)) { 935567556aaSChad Rosier std::pair<Value *, APInt> BaseAndOffset = 936567556aaSChad Rosier ConstantOffsetPtrs.lookup(I.getOperand(0)); 9377adc3a2bSChandler Carruth if (BaseAndOffset.first) 9387adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 9397adc3a2bSChandler Carruth } 9407adc3a2bSChandler Carruth 9417adc3a2bSChandler Carruth // This is really weird. Technically, ptrtoint will disable SROA. However, 9427adc3a2bSChandler Carruth // unless that ptrtoint is *used* somewhere in the live basic blocks after 9437adc3a2bSChandler Carruth // inlining, it will be nuked, and SROA should proceed. All of the uses which 9447adc3a2bSChandler Carruth // would block SROA would also block SROA if applied directly to a pointer, 9457adc3a2bSChandler Carruth // and so we can just add the integer in here. The only places where SROA is 9467adc3a2bSChandler Carruth // preserved either cannot fire on an integer, or won't in-and-of themselves 9477adc3a2bSChandler Carruth // disable SROA (ext) w/o some later use that we would see and disable. 948*76aab66dSMircea Trofin if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0))) 9497adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 9507adc3a2bSChandler Carruth 9517adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 9527adc3a2bSChandler Carruth } 9537adc3a2bSChandler Carruth 9547adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) { 9557adc3a2bSChandler Carruth // Propagate constants through ptrtoint. 956617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 957617f6364SEaswaran Raman return ConstantExpr::getIntToPtr(COps[0], I.getType()); 958617f6364SEaswaran Raman })) 9597adc3a2bSChandler Carruth return true; 9607adc3a2bSChandler Carruth 9617adc3a2bSChandler Carruth // Track base/offset pairs when round-tripped through a pointer without 9627adc3a2bSChandler Carruth // modifications provided the integer is not too large. 9637adc3a2bSChandler Carruth Value *Op = I.getOperand(0); 9647adc3a2bSChandler Carruth unsigned IntegerSize = Op->getType()->getScalarSizeInBits(); 96577f32994SBjorn Pettersson if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) { 9667adc3a2bSChandler Carruth std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op); 9677adc3a2bSChandler Carruth if (BaseAndOffset.first) 9687adc3a2bSChandler Carruth ConstantOffsetPtrs[&I] = BaseAndOffset; 9697adc3a2bSChandler Carruth } 9707adc3a2bSChandler Carruth 9717adc3a2bSChandler Carruth // "Propagate" SROA here in the same manner as we do for ptrtoint above. 972*76aab66dSMircea Trofin if (auto *SROAArg = getSROAArgForValueOrNull(Op)) 9737adc3a2bSChandler Carruth SROAArgValues[&I] = SROAArg; 9747adc3a2bSChandler Carruth 9757adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 9767adc3a2bSChandler Carruth } 9777adc3a2bSChandler Carruth 9787adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) { 979ab53c5e5SCraig Topper // Propagate constants through casts. 980617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 981617f6364SEaswaran Raman return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType()); 982617f6364SEaswaran Raman })) 9837adc3a2bSChandler Carruth return true; 9847adc3a2bSChandler Carruth 9857adc3a2bSChandler Carruth // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere. 9867adc3a2bSChandler Carruth disableSROA(I.getOperand(0)); 9877adc3a2bSChandler Carruth 98839ed9a60SEli Friedman // If this is a floating-point cast, and the target says this operation 98939ed9a60SEli Friedman // is expensive, this may eventually become a library call. Treat the cost 99039ed9a60SEli Friedman // as such. 99139ed9a60SEli Friedman switch (I.getOpcode()) { 99239ed9a60SEli Friedman case Instruction::FPTrunc: 99339ed9a60SEli Friedman case Instruction::FPExt: 99439ed9a60SEli Friedman case Instruction::UIToFP: 99539ed9a60SEli Friedman case Instruction::SIToFP: 99639ed9a60SEli Friedman case Instruction::FPToUI: 99739ed9a60SEli Friedman case Instruction::FPToSI: 99839ed9a60SEli Friedman if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive) 999*76aab66dSMircea Trofin onCallPenalty(); 10004dc0b1acSReid Kleckner break; 100139ed9a60SEli Friedman default: 100239ed9a60SEli Friedman break; 100339ed9a60SEli Friedman } 100439ed9a60SEli Friedman 10057adc3a2bSChandler Carruth return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 10067adc3a2bSChandler Carruth } 10077adc3a2bSChandler Carruth 10087adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) { 10097adc3a2bSChandler Carruth Value *Operand = I.getOperand(0); 1010617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1011617f6364SEaswaran Raman return ConstantFoldInstOperands(&I, COps[0], DL); 1012617f6364SEaswaran Raman })) 10137adc3a2bSChandler Carruth return true; 10147adc3a2bSChandler Carruth 1015ab53c5e5SCraig Topper // Disable any SROA on the argument to arbitrary unary instructions. 10167adc3a2bSChandler Carruth disableSROA(Operand); 10177adc3a2bSChandler Carruth 10187adc3a2bSChandler Carruth return false; 10197adc3a2bSChandler Carruth } 10207adc3a2bSChandler Carruth 10217adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) { 1022652168a9SFedor Sergeev return CandidateCall.paramHasAttr(A->getArgNo(), Attr); 10237adc3a2bSChandler Carruth } 10247adc3a2bSChandler Carruth 10257adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) { 10267adc3a2bSChandler Carruth // Does the *call site* have the NonNull attribute set on an argument? We 10277adc3a2bSChandler Carruth // use the attribute on the call site to memoize any analysis done in the 10287adc3a2bSChandler Carruth // caller. This will also trip if the callee function has a non-null 10297adc3a2bSChandler Carruth // parameter attribute, but that's a less interesting case because hopefully 10307adc3a2bSChandler Carruth // the callee would already have been simplified based on that. 10317adc3a2bSChandler Carruth if (Argument *A = dyn_cast<Argument>(V)) 10327adc3a2bSChandler Carruth if (paramHasAttr(A, Attribute::NonNull)) 10337adc3a2bSChandler Carruth return true; 10347adc3a2bSChandler Carruth 10357adc3a2bSChandler Carruth // Is this an alloca in the caller? This is distinct from the attribute case 10367adc3a2bSChandler Carruth // above because attributes aren't updated within the inliner itself and we 10377adc3a2bSChandler Carruth // always want to catch the alloca derived case. 10387adc3a2bSChandler Carruth if (isAllocaDerivedArg(V)) 10397adc3a2bSChandler Carruth // We can actually predict the result of comparisons between an 10407adc3a2bSChandler Carruth // alloca-derived value and null. Note that this fires regardless of 10417adc3a2bSChandler Carruth // SROA firing. 10427adc3a2bSChandler Carruth return true; 10437adc3a2bSChandler Carruth 10447adc3a2bSChandler Carruth return false; 10457adc3a2bSChandler Carruth } 10467adc3a2bSChandler Carruth 1047652168a9SFedor Sergeev bool CallAnalyzer::allowSizeGrowth(CallBase &Call) { 10489a3fc17aSEaswaran Raman // If the normal destination of the invoke or the parent block of the call 10499a3fc17aSEaswaran Raman // site is unreachable-terminated, there is little point in inlining this 10509a3fc17aSEaswaran Raman // unless there is literally zero cost. 10519a3fc17aSEaswaran Raman // FIXME: Note that it is possible that an unreachable-terminated block has a 10529a3fc17aSEaswaran Raman // hot entry. For example, in below scenario inlining hot_call_X() may be 10539a3fc17aSEaswaran Raman // beneficial : 10549a3fc17aSEaswaran Raman // main() { 10559a3fc17aSEaswaran Raman // hot_call_1(); 10569a3fc17aSEaswaran Raman // ... 10579a3fc17aSEaswaran Raman // hot_call_N() 10589a3fc17aSEaswaran Raman // exit(0); 10599a3fc17aSEaswaran Raman // } 10609a3fc17aSEaswaran Raman // For now, we are not handling this corner case here as it is rare in real 10619a3fc17aSEaswaran Raman // code. In future, we should elaborate this based on BPI and BFI in more 10629a3fc17aSEaswaran Raman // general threshold adjusting heuristics in updateThreshold(). 1063652168a9SFedor Sergeev if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) { 10649a3fc17aSEaswaran Raman if (isa<UnreachableInst>(II->getNormalDest()->getTerminator())) 10659a3fc17aSEaswaran Raman return false; 1066652168a9SFedor Sergeev } else if (isa<UnreachableInst>(Call.getParent()->getTerminator())) 10679a3fc17aSEaswaran Raman return false; 10689a3fc17aSEaswaran Raman 10699a3fc17aSEaswaran Raman return true; 10709a3fc17aSEaswaran Raman } 10719a3fc17aSEaswaran Raman 1072*76aab66dSMircea Trofin bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call, 1073652168a9SFedor Sergeev BlockFrequencyInfo *CallerBFI) { 1074c5fa6358SEaswaran Raman // If global profile summary is available, then callsite's coldness is 1075c5fa6358SEaswaran Raman // determined based on that. 1076bba762a1SChandler Carruth if (PSI && PSI->hasProfileSummary()) 1077652168a9SFedor Sergeev return PSI->isColdCallSite(CallSite(&Call), CallerBFI); 1078bba762a1SChandler Carruth 1079bba762a1SChandler Carruth // Otherwise we need BFI to be available. 1080c5fa6358SEaswaran Raman if (!CallerBFI) 1081c5fa6358SEaswaran Raman return false; 1082c5fa6358SEaswaran Raman 1083bba762a1SChandler Carruth // Determine if the callsite is cold relative to caller's entry. We could 1084bba762a1SChandler Carruth // potentially cache the computation of scaled entry frequency, but the added 1085bba762a1SChandler Carruth // complexity is not worth it unless this scaling shows up high in the 1086bba762a1SChandler Carruth // profiles. 1087c5fa6358SEaswaran Raman const BranchProbability ColdProb(ColdCallSiteRelFreq, 100); 1088652168a9SFedor Sergeev auto CallSiteBB = Call.getParent(); 1089c5fa6358SEaswaran Raman auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB); 1090c5fa6358SEaswaran Raman auto CallerEntryFreq = 1091652168a9SFedor Sergeev CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock())); 1092c5fa6358SEaswaran Raman return CallSiteFreq < CallerEntryFreq * ColdProb; 1093c5fa6358SEaswaran Raman } 1094c5fa6358SEaswaran Raman 1095974d4eeaSEaswaran Raman Optional<int> 1096*76aab66dSMircea Trofin InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call, 1097974d4eeaSEaswaran Raman BlockFrequencyInfo *CallerBFI) { 1098bba762a1SChandler Carruth 1099974d4eeaSEaswaran Raman // If global profile summary is available, then callsite's hotness is 1100974d4eeaSEaswaran Raman // determined based on that. 1101652168a9SFedor Sergeev if (PSI && PSI->hasProfileSummary() && 1102652168a9SFedor Sergeev PSI->isHotCallSite(CallSite(&Call), CallerBFI)) 1103bba762a1SChandler Carruth return Params.HotCallSiteThreshold; 1104974d4eeaSEaswaran Raman 1105bba762a1SChandler Carruth // Otherwise we need BFI to be available and to have a locally hot callsite 1106bba762a1SChandler Carruth // threshold. 1107bba762a1SChandler Carruth if (!CallerBFI || !Params.LocallyHotCallSiteThreshold) 1108974d4eeaSEaswaran Raman return None; 1109974d4eeaSEaswaran Raman 1110bba762a1SChandler Carruth // Determine if the callsite is hot relative to caller's entry. We could 1111bba762a1SChandler Carruth // potentially cache the computation of scaled entry frequency, but the added 1112bba762a1SChandler Carruth // complexity is not worth it unless this scaling shows up high in the 1113bba762a1SChandler Carruth // profiles. 1114652168a9SFedor Sergeev auto CallSiteBB = Call.getParent(); 1115974d4eeaSEaswaran Raman auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency(); 1116974d4eeaSEaswaran Raman auto CallerEntryFreq = CallerBFI->getEntryFreq(); 1117974d4eeaSEaswaran Raman if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq) 1118bba762a1SChandler Carruth return Params.LocallyHotCallSiteThreshold; 1119bba762a1SChandler Carruth 1120bba762a1SChandler Carruth // Otherwise treat it normally. 1121974d4eeaSEaswaran Raman return None; 1122974d4eeaSEaswaran Raman } 1123974d4eeaSEaswaran Raman 1124*76aab66dSMircea Trofin void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) { 11259a3fc17aSEaswaran Raman // If no size growth is allowed for this inlining, set Threshold to 0. 1126652168a9SFedor Sergeev if (!allowSizeGrowth(Call)) { 11279a3fc17aSEaswaran Raman Threshold = 0; 11289a3fc17aSEaswaran Raman return; 11299a3fc17aSEaswaran Raman } 11309a3fc17aSEaswaran Raman 1131652168a9SFedor Sergeev Function *Caller = Call.getCaller(); 11321c57cc2bSEaswaran Raman 11331c57cc2bSEaswaran Raman // return min(A, B) if B is valid. 11341c57cc2bSEaswaran Raman auto MinIfValid = [](int A, Optional<int> B) { 11351c57cc2bSEaswaran Raman return B ? std::min(A, B.getValue()) : A; 11361c57cc2bSEaswaran Raman }; 11371c57cc2bSEaswaran Raman 11380d58fcacSEaswaran Raman // return max(A, B) if B is valid. 11390d58fcacSEaswaran Raman auto MaxIfValid = [](int A, Optional<int> B) { 11400d58fcacSEaswaran Raman return B ? std::max(A, B.getValue()) : A; 11410d58fcacSEaswaran Raman }; 11420d58fcacSEaswaran Raman 114351b809bfSEaswaran Raman // Various bonus percentages. These are multiplied by Threshold to get the 114451b809bfSEaswaran Raman // bonus values. 114551b809bfSEaswaran Raman // SingleBBBonus: This bonus is applied if the callee has a single reachable 114651b809bfSEaswaran Raman // basic block at the given callsite context. This is speculatively applied 114751b809bfSEaswaran Raman // and withdrawn if more than one basic block is seen. 114851b809bfSEaswaran Raman // 114951b809bfSEaswaran Raman // LstCallToStaticBonus: This large bonus is applied to ensure the inlining 115051b809bfSEaswaran Raman // of the last call to a static function as inlining such functions is 115151b809bfSEaswaran Raman // guaranteed to reduce code size. 115251b809bfSEaswaran Raman // 115351b809bfSEaswaran Raman // These bonus percentages may be set to 0 based on properties of the caller 115451b809bfSEaswaran Raman // and the callsite. 115551b809bfSEaswaran Raman int SingleBBBonusPercent = 50; 1156d912a9baSDaniil Fukalov int VectorBonusPercent = TTI.getInlinerVectorBonusPercent(); 115702647f73SJordan Rupprecht int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus; 115851b809bfSEaswaran Raman 115951b809bfSEaswaran Raman // Lambda to set all the above bonus and bonus percentages to 0. 116051b809bfSEaswaran Raman auto DisallowAllBonuses = [&]() { 116151b809bfSEaswaran Raman SingleBBBonusPercent = 0; 116251b809bfSEaswaran Raman VectorBonusPercent = 0; 116351b809bfSEaswaran Raman LastCallToStaticBonus = 0; 116451b809bfSEaswaran Raman }; 116551b809bfSEaswaran Raman 11661c57cc2bSEaswaran Raman // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available 11671c57cc2bSEaswaran Raman // and reduce the threshold if the caller has the necessary attribute. 116885bd3978SEvandro Menezes if (Caller->hasMinSize()) { 11691c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold); 117051b809bfSEaswaran Raman // For minsize, we want to disable the single BB bonus and the vector 117151b809bfSEaswaran Raman // bonuses, but not the last-call-to-static bonus. Inlining the last call to 117251b809bfSEaswaran Raman // a static function will, at the minimum, eliminate the parameter setup and 117351b809bfSEaswaran Raman // call/return instructions. 117451b809bfSEaswaran Raman SingleBBBonusPercent = 0; 117551b809bfSEaswaran Raman VectorBonusPercent = 0; 117685bd3978SEvandro Menezes } else if (Caller->hasOptSize()) 11771c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.OptSizeThreshold); 1178f4bb2f0dSEaswaran Raman 1179e08b139dSEaswaran Raman // Adjust the threshold based on inlinehint attribute and profile based 1180e08b139dSEaswaran Raman // hotness information if the caller does not have MinSize attribute. 118185bd3978SEvandro Menezes if (!Caller->hasMinSize()) { 1182e08b139dSEaswaran Raman if (Callee.hasFnAttribute(Attribute::InlineHint)) 11830d58fcacSEaswaran Raman Threshold = MaxIfValid(Threshold, Params.HintThreshold); 1184bba762a1SChandler Carruth 11853cd1479cSEaswaran Raman // FIXME: After switching to the new passmanager, simplify the logic below 1186bba762a1SChandler Carruth // by checking only the callsite hotness/coldness as we will reliably 1187bba762a1SChandler Carruth // have local profile information. 11883cd1479cSEaswaran Raman // 1189bba762a1SChandler Carruth // Callsite hotness and coldness can be determined if sample profile is 1190bba762a1SChandler Carruth // used (which adds hotness metadata to calls) or if caller's 1191bba762a1SChandler Carruth // BlockFrequencyInfo is available. 1192bba762a1SChandler Carruth BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr; 1193652168a9SFedor Sergeev auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI); 119485bd3978SEvandro Menezes if (!Caller->hasOptSize() && HotCallSiteThreshold) { 1195d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Hot callsite.\n"); 1196974d4eeaSEaswaran Raman // FIXME: This should update the threshold only if it exceeds the 1197974d4eeaSEaswaran Raman // current threshold, but AutoFDO + ThinLTO currently relies on this 1198974d4eeaSEaswaran Raman // behavior to prevent inlining of hot callsites during ThinLTO 1199974d4eeaSEaswaran Raman // compile phase. 1200974d4eeaSEaswaran Raman Threshold = HotCallSiteThreshold.getValue(); 1201652168a9SFedor Sergeev } else if (isColdCallSite(Call, CallerBFI)) { 1202d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Cold callsite.\n"); 120351b809bfSEaswaran Raman // Do not apply bonuses for a cold callsite including the 120451b809bfSEaswaran Raman // LastCallToStatic bonus. While this bonus might result in code size 120551b809bfSEaswaran Raman // reduction, it can cause the size of a non-cold caller to increase 120651b809bfSEaswaran Raman // preventing it from being inlined. 120751b809bfSEaswaran Raman DisallowAllBonuses(); 12083cd1479cSEaswaran Raman Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold); 1209bba762a1SChandler Carruth } else if (PSI) { 1210bba762a1SChandler Carruth // Use callee's global profile information only if we have no way of 1211bba762a1SChandler Carruth // determining this via callsite information. 12123cd1479cSEaswaran Raman if (PSI->isFunctionEntryHot(&Callee)) { 1213d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Hot callee.\n"); 1214e08b139dSEaswaran Raman // If callsite hotness can not be determined, we may still know 1215e08b139dSEaswaran Raman // that the callee is hot and treat it as a weaker hint for threshold 1216e08b139dSEaswaran Raman // increase. 1217e08b139dSEaswaran Raman Threshold = MaxIfValid(Threshold, Params.HintThreshold); 1218e08b139dSEaswaran Raman } else if (PSI->isFunctionEntryCold(&Callee)) { 1219d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Cold callee.\n"); 122051b809bfSEaswaran Raman // Do not apply bonuses for a cold callee including the 122151b809bfSEaswaran Raman // LastCallToStatic bonus. While this bonus might result in code size 122251b809bfSEaswaran Raman // reduction, it can cause the size of a non-cold caller to increase 122351b809bfSEaswaran Raman // preventing it from being inlined. 122451b809bfSEaswaran Raman DisallowAllBonuses(); 12251c57cc2bSEaswaran Raman Threshold = MinIfValid(Threshold, Params.ColdThreshold); 1226e08b139dSEaswaran Raman } 1227e08b139dSEaswaran Raman } 1228e08b139dSEaswaran Raman } 12298650a4daSJustin Lebar 123002647f73SJordan Rupprecht // Finally, take the target-specific inlining threshold multiplier into 123102647f73SJordan Rupprecht // account. 12328650a4daSJustin Lebar Threshold *= TTI.getInliningThresholdMultiplier(); 123351b809bfSEaswaran Raman 123451b809bfSEaswaran Raman SingleBBBonus = Threshold * SingleBBBonusPercent / 100; 123551b809bfSEaswaran Raman VectorBonus = Threshold * VectorBonusPercent / 100; 123651b809bfSEaswaran Raman 123702647f73SJordan Rupprecht bool OnlyOneCallAndLocalLinkage = 123802647f73SJordan Rupprecht F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction(); 123902647f73SJordan Rupprecht // If there is only one call of the function, and it has internal linkage, 124002647f73SJordan Rupprecht // the cost of inlining it drops dramatically. It may seem odd to update 124102647f73SJordan Rupprecht // Cost in updateThreshold, but the bonus depends on the logic in this method. 124202647f73SJordan Rupprecht if (OnlyOneCallAndLocalLinkage) 124302647f73SJordan Rupprecht Cost -= LastCallToStaticBonus; 1244f4bb2f0dSEaswaran Raman } 1245f4bb2f0dSEaswaran Raman 12467adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) { 12477adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 12487adc3a2bSChandler Carruth // First try to handle simplified comparisons. 1249617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1250617f6364SEaswaran Raman return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]); 1251617f6364SEaswaran Raman })) 12527adc3a2bSChandler Carruth return true; 12537adc3a2bSChandler Carruth 12547adc3a2bSChandler Carruth if (I.getOpcode() == Instruction::FCmp) 12557adc3a2bSChandler Carruth return false; 12567adc3a2bSChandler Carruth 12577adc3a2bSChandler Carruth // Otherwise look for a comparison between constant offset pointers with 12587adc3a2bSChandler Carruth // a common base. 12597adc3a2bSChandler Carruth Value *LHSBase, *RHSBase; 12607adc3a2bSChandler Carruth APInt LHSOffset, RHSOffset; 12617adc3a2bSChandler Carruth std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 12627adc3a2bSChandler Carruth if (LHSBase) { 12637adc3a2bSChandler Carruth std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 12647adc3a2bSChandler Carruth if (RHSBase && LHSBase == RHSBase) { 12657adc3a2bSChandler Carruth // We have common bases, fold the icmp to a constant based on the 12667adc3a2bSChandler Carruth // offsets. 12677adc3a2bSChandler Carruth Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 12687adc3a2bSChandler Carruth Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 12697adc3a2bSChandler Carruth if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) { 12707adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 12717adc3a2bSChandler Carruth ++NumConstantPtrCmps; 12727adc3a2bSChandler Carruth return true; 12737adc3a2bSChandler Carruth } 12747adc3a2bSChandler Carruth } 12757adc3a2bSChandler Carruth } 12767adc3a2bSChandler Carruth 12777adc3a2bSChandler Carruth // If the comparison is an equality comparison with null, we can simplify it 12787adc3a2bSChandler Carruth // if we know the value (argument) can't be null 12797adc3a2bSChandler Carruth if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) && 12807adc3a2bSChandler Carruth isKnownNonNullInCallee(I.getOperand(0))) { 12817adc3a2bSChandler Carruth bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE; 12827adc3a2bSChandler Carruth SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType()) 12837adc3a2bSChandler Carruth : ConstantInt::getFalse(I.getType()); 12847adc3a2bSChandler Carruth return true; 12857adc3a2bSChandler Carruth } 1286*76aab66dSMircea Trofin return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1))); 12877adc3a2bSChandler Carruth } 12887adc3a2bSChandler Carruth 12897adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) { 12907adc3a2bSChandler Carruth // Try to handle a special case: we can fold computing the difference of two 12917adc3a2bSChandler Carruth // constant-related pointers. 12927adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 12937adc3a2bSChandler Carruth Value *LHSBase, *RHSBase; 12947adc3a2bSChandler Carruth APInt LHSOffset, RHSOffset; 12957adc3a2bSChandler Carruth std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 12967adc3a2bSChandler Carruth if (LHSBase) { 12977adc3a2bSChandler Carruth std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 12987adc3a2bSChandler Carruth if (RHSBase && LHSBase == RHSBase) { 12997adc3a2bSChandler Carruth // We have common bases, fold the subtract to a constant based on the 13007adc3a2bSChandler Carruth // offsets. 13017adc3a2bSChandler Carruth Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 13027adc3a2bSChandler Carruth Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 13037adc3a2bSChandler Carruth if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) { 13047adc3a2bSChandler Carruth SimplifiedValues[&I] = C; 13057adc3a2bSChandler Carruth ++NumConstantPtrDiffs; 13067adc3a2bSChandler Carruth return true; 13077adc3a2bSChandler Carruth } 13087adc3a2bSChandler Carruth } 13097adc3a2bSChandler Carruth } 13107adc3a2bSChandler Carruth 13117adc3a2bSChandler Carruth // Otherwise, fall back to the generic logic for simplifying and handling 13127adc3a2bSChandler Carruth // instructions. 13137adc3a2bSChandler Carruth return Base::visitSub(I); 13147adc3a2bSChandler Carruth } 13157adc3a2bSChandler Carruth 13167adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) { 13177adc3a2bSChandler Carruth Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 13186d14dfe8SHaicheng Wu Constant *CLHS = dyn_cast<Constant>(LHS); 13196d14dfe8SHaicheng Wu if (!CLHS) 13206d14dfe8SHaicheng Wu CLHS = SimplifiedValues.lookup(LHS); 13216d14dfe8SHaicheng Wu Constant *CRHS = dyn_cast<Constant>(RHS); 13226d14dfe8SHaicheng Wu if (!CRHS) 13236d14dfe8SHaicheng Wu CRHS = SimplifiedValues.lookup(RHS); 13246d14dfe8SHaicheng Wu 13257adc3a2bSChandler Carruth Value *SimpleV = nullptr; 13267adc3a2bSChandler Carruth if (auto FI = dyn_cast<FPMathOperator>(&I)) 13275a956c85SMircea Trofin SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, 13285a956c85SMircea Trofin FI->getFastMathFlags(), DL); 13297adc3a2bSChandler Carruth else 13306d14dfe8SHaicheng Wu SimpleV = 13316d14dfe8SHaicheng Wu SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL); 13327adc3a2bSChandler Carruth 13336d14dfe8SHaicheng Wu if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 13346d14dfe8SHaicheng Wu SimplifiedValues[&I] = C; 13356d14dfe8SHaicheng Wu 13366d14dfe8SHaicheng Wu if (SimpleV) 13377adc3a2bSChandler Carruth return true; 13387adc3a2bSChandler Carruth 13397adc3a2bSChandler Carruth // Disable any SROA on arguments to arbitrary, unsimplified binary operators. 13407adc3a2bSChandler Carruth disableSROA(LHS); 13417adc3a2bSChandler Carruth disableSROA(RHS); 13427adc3a2bSChandler Carruth 134339ed9a60SEli Friedman // If the instruction is floating point, and the target says this operation 134439ed9a60SEli Friedman // is expensive, this may eventually become a library call. Treat the cost 13457cebf0afSCraig Topper // as such. Unless it's fneg which can be implemented with an xor. 13467cebf0afSCraig Topper using namespace llvm::PatternMatch; 134739ed9a60SEli Friedman if (I.getType()->isFloatingPointTy() && 13487cebf0afSCraig Topper TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive && 13497cebf0afSCraig Topper !match(&I, m_FNeg(m_Value()))) 1350*76aab66dSMircea Trofin onCallPenalty(); 135139ed9a60SEli Friedman 13527adc3a2bSChandler Carruth return false; 13537adc3a2bSChandler Carruth } 13547adc3a2bSChandler Carruth 13556cda33baSCraig Topper bool CallAnalyzer::visitFNeg(UnaryOperator &I) { 13566cda33baSCraig Topper Value *Op = I.getOperand(0); 13576cda33baSCraig Topper Constant *COp = dyn_cast<Constant>(Op); 13586cda33baSCraig Topper if (!COp) 13596cda33baSCraig Topper COp = SimplifiedValues.lookup(Op); 13606cda33baSCraig Topper 13615a956c85SMircea Trofin Value *SimpleV = SimplifyFNegInst( 13625a956c85SMircea Trofin COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL); 13636cda33baSCraig Topper 13646cda33baSCraig Topper if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 13656cda33baSCraig Topper SimplifiedValues[&I] = C; 13666cda33baSCraig Topper 13676cda33baSCraig Topper if (SimpleV) 13686cda33baSCraig Topper return true; 13696cda33baSCraig Topper 13706cda33baSCraig Topper // Disable any SROA on arguments to arbitrary, unsimplified fneg. 13716cda33baSCraig Topper disableSROA(Op); 13726cda33baSCraig Topper 13736cda33baSCraig Topper return false; 13746cda33baSCraig Topper } 13756cda33baSCraig Topper 13767adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) { 1377*76aab66dSMircea Trofin if (handleSROA(I.getPointerOperand(), I.isSimple())) 13787adc3a2bSChandler Carruth return true; 13797adc3a2bSChandler Carruth 1380a4461515SHaicheng Wu // If the data is already loaded from this address and hasn't been clobbered 1381a4461515SHaicheng Wu // by any stores or calls, this load is likely to be redundant and can be 1382a4461515SHaicheng Wu // eliminated. 1383a4461515SHaicheng Wu if (EnableLoadElimination && 1384b3689cabSHaicheng Wu !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) { 1385*76aab66dSMircea Trofin onLoadEliminationOpportunity(); 1386a4461515SHaicheng Wu return true; 1387a4461515SHaicheng Wu } 1388a4461515SHaicheng Wu 13897adc3a2bSChandler Carruth return false; 13907adc3a2bSChandler Carruth } 13917adc3a2bSChandler Carruth 13927adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) { 1393*76aab66dSMircea Trofin if (handleSROA(I.getPointerOperand(), I.isSimple())) 13947adc3a2bSChandler Carruth return true; 13957adc3a2bSChandler Carruth 1396a4461515SHaicheng Wu // The store can potentially clobber loads and prevent repeated loads from 1397a4461515SHaicheng Wu // being eliminated. 1398a4461515SHaicheng Wu // FIXME: 1399a4461515SHaicheng Wu // 1. We can probably keep an initial set of eliminatable loads substracted 1400a4461515SHaicheng Wu // from the cost even when we finally see a store. We just need to disable 1401a4461515SHaicheng Wu // *further* accumulation of elimination savings. 1402a4461515SHaicheng Wu // 2. We should probably at some point thread MemorySSA for the callee into 1403a4461515SHaicheng Wu // this and then use that to actually compute *really* precise savings. 1404a4461515SHaicheng Wu disableLoadElimination(); 14057adc3a2bSChandler Carruth return false; 14067adc3a2bSChandler Carruth } 14077adc3a2bSChandler Carruth 14087adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) { 14097adc3a2bSChandler Carruth // Constant folding for extract value is trivial. 1410617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1411617f6364SEaswaran Raman return ConstantExpr::getExtractValue(COps[0], I.getIndices()); 1412617f6364SEaswaran Raman })) 14137adc3a2bSChandler Carruth return true; 14147adc3a2bSChandler Carruth 14157adc3a2bSChandler Carruth // SROA can look through these but give them a cost. 14167adc3a2bSChandler Carruth return false; 14177adc3a2bSChandler Carruth } 14187adc3a2bSChandler Carruth 14197adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) { 14207adc3a2bSChandler Carruth // Constant folding for insert value is trivial. 1421617f6364SEaswaran Raman if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1422617f6364SEaswaran Raman return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0], 1423617f6364SEaswaran Raman /*InsertedValueOperand*/ COps[1], 1424617f6364SEaswaran Raman I.getIndices()); 1425617f6364SEaswaran Raman })) 14267adc3a2bSChandler Carruth return true; 14277adc3a2bSChandler Carruth 14287adc3a2bSChandler Carruth // SROA can look through these but give them a cost. 14297adc3a2bSChandler Carruth return false; 14307adc3a2bSChandler Carruth } 14317adc3a2bSChandler Carruth 14325f8f34e4SAdrian Prantl /// Try to simplify a call site. 14337adc3a2bSChandler Carruth /// 14347adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by 14357adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if 14367adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it 14377adc3a2bSChandler Carruth /// free. 1438652168a9SFedor Sergeev bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) { 14397adc3a2bSChandler Carruth // FIXME: Using the instsimplify logic directly for this is inefficient 14407adc3a2bSChandler Carruth // because we have to continually rebuild the argument list even when no 14417adc3a2bSChandler Carruth // simplifications can be performed. Until that is fixed with remapping 14427adc3a2bSChandler Carruth // inside of instsimplify, directly constant fold calls here. 1443652168a9SFedor Sergeev if (!canConstantFoldCallTo(&Call, F)) 14447adc3a2bSChandler Carruth return false; 14457adc3a2bSChandler Carruth 14467adc3a2bSChandler Carruth // Try to re-map the arguments to constants. 14477adc3a2bSChandler Carruth SmallVector<Constant *, 4> ConstantArgs; 1448652168a9SFedor Sergeev ConstantArgs.reserve(Call.arg_size()); 1449652168a9SFedor Sergeev for (Value *I : Call.args()) { 1450652168a9SFedor Sergeev Constant *C = dyn_cast<Constant>(I); 14517adc3a2bSChandler Carruth if (!C) 1452652168a9SFedor Sergeev C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I)); 14537adc3a2bSChandler Carruth if (!C) 14547adc3a2bSChandler Carruth return false; // This argument doesn't map to a constant. 14557adc3a2bSChandler Carruth 14567adc3a2bSChandler Carruth ConstantArgs.push_back(C); 14577adc3a2bSChandler Carruth } 1458652168a9SFedor Sergeev if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) { 1459652168a9SFedor Sergeev SimplifiedValues[&Call] = C; 14607adc3a2bSChandler Carruth return true; 14617adc3a2bSChandler Carruth } 14627adc3a2bSChandler Carruth 14637adc3a2bSChandler Carruth return false; 14647adc3a2bSChandler Carruth } 14657adc3a2bSChandler Carruth 1466652168a9SFedor Sergeev bool CallAnalyzer::visitCallBase(CallBase &Call) { 1467652168a9SFedor Sergeev if (Call.hasFnAttr(Attribute::ReturnsTwice) && 14687adc3a2bSChandler Carruth !F.hasFnAttribute(Attribute::ReturnsTwice)) { 14697adc3a2bSChandler Carruth // This aborts the entire analysis. 14707adc3a2bSChandler Carruth ExposesReturnsTwice = true; 14717adc3a2bSChandler Carruth return false; 14727adc3a2bSChandler Carruth } 1473652168a9SFedor Sergeev if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate()) 14747adc3a2bSChandler Carruth ContainsNoDuplicateCall = true; 14757adc3a2bSChandler Carruth 1476825debe8SEhud Katz Value *Callee = Call.getCalledOperand(); 1477825debe8SEhud Katz Function *F = dyn_cast_or_null<Function>(Callee); 1478825debe8SEhud Katz bool IsIndirectCall = !F; 1479825debe8SEhud Katz if (IsIndirectCall) { 1480825debe8SEhud Katz // Check if this happens to be an indirect function call to a known function 1481825debe8SEhud Katz // in this inline context. If not, we've done all we can. 1482825debe8SEhud Katz F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee)); 1483825debe8SEhud Katz if (!F) { 1484*76aab66dSMircea Trofin onCallArgumentSetup(Call); 1485825debe8SEhud Katz 1486825debe8SEhud Katz if (!Call.onlyReadsMemory()) 1487825debe8SEhud Katz disableLoadElimination(); 1488825debe8SEhud Katz return Base::visitCallBase(Call); 1489825debe8SEhud Katz } 1490825debe8SEhud Katz } 1491825debe8SEhud Katz 1492825debe8SEhud Katz assert(F && "Expected a call to a known function"); 1493825debe8SEhud Katz 14947adc3a2bSChandler Carruth // When we have a concrete function, first try to simplify it directly. 1495652168a9SFedor Sergeev if (simplifyCallSite(F, Call)) 14967adc3a2bSChandler Carruth return true; 14977adc3a2bSChandler Carruth 14987adc3a2bSChandler Carruth // Next check if it is an intrinsic we know about. 14997adc3a2bSChandler Carruth // FIXME: Lift this into part of the InstVisitor. 1500652168a9SFedor Sergeev if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) { 15017adc3a2bSChandler Carruth switch (II->getIntrinsicID()) { 15027adc3a2bSChandler Carruth default: 1503652168a9SFedor Sergeev if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II)) 1504a4461515SHaicheng Wu disableLoadElimination(); 1505652168a9SFedor Sergeev return Base::visitCallBase(Call); 15067adc3a2bSChandler Carruth 15077dd8dbf4SPeter Collingbourne case Intrinsic::load_relative: 1508*76aab66dSMircea Trofin onLoadRelativeIntrinsic(); 15097dd8dbf4SPeter Collingbourne return false; 15107dd8dbf4SPeter Collingbourne 15117adc3a2bSChandler Carruth case Intrinsic::memset: 15127adc3a2bSChandler Carruth case Intrinsic::memcpy: 15137adc3a2bSChandler Carruth case Intrinsic::memmove: 1514a4461515SHaicheng Wu disableLoadElimination(); 15157adc3a2bSChandler Carruth // SROA can usually chew through these intrinsics, but they aren't free. 15167adc3a2bSChandler Carruth return false; 15174296ea72SVitaly Buka case Intrinsic::icall_branch_funnel: 15187adc3a2bSChandler Carruth case Intrinsic::localescape: 15194296ea72SVitaly Buka HasUninlineableIntrinsic = true; 15207adc3a2bSChandler Carruth return false; 152180788d80SFlorian Hahn case Intrinsic::vastart: 152277beee41SSameer AbuAsal InitsVargArgs = true; 152380788d80SFlorian Hahn return false; 15247adc3a2bSChandler Carruth } 15257adc3a2bSChandler Carruth } 15267adc3a2bSChandler Carruth 1527652168a9SFedor Sergeev if (F == Call.getFunction()) { 15287adc3a2bSChandler Carruth // This flag will fully abort the analysis, so don't bother with anything 15297adc3a2bSChandler Carruth // else. 15307adc3a2bSChandler Carruth IsRecursiveCall = true; 15317adc3a2bSChandler Carruth return false; 15327adc3a2bSChandler Carruth } 15337adc3a2bSChandler Carruth 15347adc3a2bSChandler Carruth if (TTI.isLoweredToCall(F)) { 1535*76aab66dSMircea Trofin onLoweredCall(F, Call, IsIndirectCall); 1536825debe8SEhud Katz } 15377adc3a2bSChandler Carruth 1538825debe8SEhud Katz if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory()))) 1539a4461515SHaicheng Wu disableLoadElimination(); 1540652168a9SFedor Sergeev return Base::visitCallBase(Call); 15417adc3a2bSChandler Carruth } 15427adc3a2bSChandler Carruth 15437adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) { 15447adc3a2bSChandler Carruth // At least one return instruction will be free after inlining. 15457adc3a2bSChandler Carruth bool Free = !HasReturn; 15467adc3a2bSChandler Carruth HasReturn = true; 15477adc3a2bSChandler Carruth return Free; 15487adc3a2bSChandler Carruth } 15497adc3a2bSChandler Carruth 15507adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) { 15517adc3a2bSChandler Carruth // We model unconditional branches as essentially free -- they really 15527adc3a2bSChandler Carruth // shouldn't exist at all, but handling them makes the behavior of the 15537adc3a2bSChandler Carruth // inliner more regular and predictable. Interestingly, conditional branches 15547adc3a2bSChandler Carruth // which will fold away are also free. 15557adc3a2bSChandler Carruth return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) || 15567adc3a2bSChandler Carruth dyn_cast_or_null<ConstantInt>( 15577adc3a2bSChandler Carruth SimplifiedValues.lookup(BI.getCondition())); 15587adc3a2bSChandler Carruth } 15597adc3a2bSChandler Carruth 15603ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) { 15613ec848bcSHaicheng Wu bool CheckSROA = SI.getType()->isPointerTy(); 15623ec848bcSHaicheng Wu Value *TrueVal = SI.getTrueValue(); 15633ec848bcSHaicheng Wu Value *FalseVal = SI.getFalseValue(); 15643ec848bcSHaicheng Wu 15653ec848bcSHaicheng Wu Constant *TrueC = dyn_cast<Constant>(TrueVal); 15663ec848bcSHaicheng Wu if (!TrueC) 15673ec848bcSHaicheng Wu TrueC = SimplifiedValues.lookup(TrueVal); 15683ec848bcSHaicheng Wu Constant *FalseC = dyn_cast<Constant>(FalseVal); 15693ec848bcSHaicheng Wu if (!FalseC) 15703ec848bcSHaicheng Wu FalseC = SimplifiedValues.lookup(FalseVal); 15713ec848bcSHaicheng Wu Constant *CondC = 15723ec848bcSHaicheng Wu dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition())); 15733ec848bcSHaicheng Wu 15743ec848bcSHaicheng Wu if (!CondC) { 15753ec848bcSHaicheng Wu // Select C, X, X => X 15763ec848bcSHaicheng Wu if (TrueC == FalseC && TrueC) { 15773ec848bcSHaicheng Wu SimplifiedValues[&SI] = TrueC; 15783ec848bcSHaicheng Wu return true; 15793ec848bcSHaicheng Wu } 15803ec848bcSHaicheng Wu 15813ec848bcSHaicheng Wu if (!CheckSROA) 15823ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 15833ec848bcSHaicheng Wu 15843ec848bcSHaicheng Wu std::pair<Value *, APInt> TrueBaseAndOffset = 15853ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(TrueVal); 15863ec848bcSHaicheng Wu std::pair<Value *, APInt> FalseBaseAndOffset = 15873ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(FalseVal); 15883ec848bcSHaicheng Wu if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) { 15893ec848bcSHaicheng Wu ConstantOffsetPtrs[&SI] = TrueBaseAndOffset; 15903ec848bcSHaicheng Wu 1591*76aab66dSMircea Trofin if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal)) 15923ec848bcSHaicheng Wu SROAArgValues[&SI] = SROAArg; 15933ec848bcSHaicheng Wu return true; 15943ec848bcSHaicheng Wu } 15953ec848bcSHaicheng Wu 15963ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 15973ec848bcSHaicheng Wu } 15983ec848bcSHaicheng Wu 15993ec848bcSHaicheng Wu // Select condition is a constant. 16003ec848bcSHaicheng Wu Value *SelectedV = CondC->isAllOnesValue() 16013ec848bcSHaicheng Wu ? TrueVal 16023ec848bcSHaicheng Wu : (CondC->isNullValue()) ? FalseVal : nullptr; 16033ec848bcSHaicheng Wu if (!SelectedV) { 16043ec848bcSHaicheng Wu // Condition is a vector constant that is not all 1s or all 0s. If all 16053ec848bcSHaicheng Wu // operands are constants, ConstantExpr::getSelect() can handle the cases 16063ec848bcSHaicheng Wu // such as select vectors. 16073ec848bcSHaicheng Wu if (TrueC && FalseC) { 16083ec848bcSHaicheng Wu if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) { 16093ec848bcSHaicheng Wu SimplifiedValues[&SI] = C; 16103ec848bcSHaicheng Wu return true; 16113ec848bcSHaicheng Wu } 16123ec848bcSHaicheng Wu } 16133ec848bcSHaicheng Wu return Base::visitSelectInst(SI); 16143ec848bcSHaicheng Wu } 16153ec848bcSHaicheng Wu 16163ec848bcSHaicheng Wu // Condition is either all 1s or all 0s. SI can be simplified. 16173ec848bcSHaicheng Wu if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) { 16183ec848bcSHaicheng Wu SimplifiedValues[&SI] = SelectedC; 16193ec848bcSHaicheng Wu return true; 16203ec848bcSHaicheng Wu } 16213ec848bcSHaicheng Wu 16223ec848bcSHaicheng Wu if (!CheckSROA) 16233ec848bcSHaicheng Wu return true; 16243ec848bcSHaicheng Wu 16253ec848bcSHaicheng Wu std::pair<Value *, APInt> BaseAndOffset = 16263ec848bcSHaicheng Wu ConstantOffsetPtrs.lookup(SelectedV); 16273ec848bcSHaicheng Wu if (BaseAndOffset.first) { 16283ec848bcSHaicheng Wu ConstantOffsetPtrs[&SI] = BaseAndOffset; 16293ec848bcSHaicheng Wu 1630*76aab66dSMircea Trofin if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV)) 16313ec848bcSHaicheng Wu SROAArgValues[&SI] = SROAArg; 16323ec848bcSHaicheng Wu } 16333ec848bcSHaicheng Wu 16343ec848bcSHaicheng Wu return true; 16353ec848bcSHaicheng Wu } 16363ec848bcSHaicheng Wu 16377adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) { 16387adc3a2bSChandler Carruth // We model unconditional switches as free, see the comments on handling 16397adc3a2bSChandler Carruth // branches. 16407adc3a2bSChandler Carruth if (isa<ConstantInt>(SI.getCondition())) 16417adc3a2bSChandler Carruth return true; 16427adc3a2bSChandler Carruth if (Value *V = SimplifiedValues.lookup(SI.getCondition())) 16437adc3a2bSChandler Carruth if (isa<ConstantInt>(V)) 16447adc3a2bSChandler Carruth return true; 16457adc3a2bSChandler Carruth 16467ad02eeeSEric Christopher // Assume the most general case where the switch is lowered into 1647919f9e8dSJun Bum Lim // either a jump table, bit test, or a balanced binary tree consisting of 1648919f9e8dSJun Bum Lim // case clusters without merging adjacent clusters with the same 1649919f9e8dSJun Bum Lim // destination. We do not consider the switches that are lowered with a mix 1650919f9e8dSJun Bum Lim // of jump table/bit test/binary search tree. The cost of the switch is 1651919f9e8dSJun Bum Lim // proportional to the size of the tree or the size of jump table range. 16522960d41eSJun Bum Lim // 16532960d41eSJun Bum Lim // NB: We convert large switches which are just used to initialize large phi 16542960d41eSJun Bum Lim // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent 16552960d41eSJun Bum Lim // inlining those. It will prevent inlining in cases where the optimization 16562960d41eSJun Bum Lim // does not (yet) fire. 1657919f9e8dSJun Bum Lim 1658919f9e8dSJun Bum Lim unsigned JumpTableSize = 0; 16590d987e41SHiroshi Yamauchi BlockFrequencyInfo *BFI = GetBFI ? &((*GetBFI)(F)) : nullptr; 1660919f9e8dSJun Bum Lim unsigned NumCaseCluster = 16610d987e41SHiroshi Yamauchi TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI); 1662919f9e8dSJun Bum Lim 1663*76aab66dSMircea Trofin onFinalizeSwitch(JumpTableSize, NumCaseCluster); 1664919f9e8dSJun Bum Lim return false; 1665919f9e8dSJun Bum Lim } 1666919f9e8dSJun Bum Lim 16677adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) { 16687adc3a2bSChandler Carruth // We never want to inline functions that contain an indirectbr. This is 16697adc3a2bSChandler Carruth // incorrect because all the blockaddress's (in static global initializers 16707adc3a2bSChandler Carruth // for example) would be referring to the original function, and this 16717adc3a2bSChandler Carruth // indirect jump would jump from the inlined copy of the function into the 16727adc3a2bSChandler Carruth // original function which is extremely undefined behavior. 16737adc3a2bSChandler Carruth // FIXME: This logic isn't really right; we can safely inline functions with 16747adc3a2bSChandler Carruth // indirectbr's as long as no other function or global references the 16757adc3a2bSChandler Carruth // blockaddress of a block within the current function. 16767adc3a2bSChandler Carruth HasIndirectBr = true; 16777adc3a2bSChandler Carruth return false; 16787adc3a2bSChandler Carruth } 16797adc3a2bSChandler Carruth 16807adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) { 16817adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 16827adc3a2bSChandler Carruth // the inline cost of a resume instruction. 16837adc3a2bSChandler Carruth return false; 16847adc3a2bSChandler Carruth } 16857adc3a2bSChandler Carruth 16867adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) { 16877adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 16887adc3a2bSChandler Carruth // the inline cost of a cleanupret instruction. 16897adc3a2bSChandler Carruth return false; 16907adc3a2bSChandler Carruth } 16917adc3a2bSChandler Carruth 16927adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) { 16937adc3a2bSChandler Carruth // FIXME: It's not clear that a single instruction is an accurate model for 16948220bcc5SJoseph Tremoulet // the inline cost of a catchret instruction. 16957adc3a2bSChandler Carruth return false; 16967adc3a2bSChandler Carruth } 16977adc3a2bSChandler Carruth 16987adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) { 16997adc3a2bSChandler Carruth // FIXME: It might be reasonably to discount the cost of instructions leading 17007adc3a2bSChandler Carruth // to unreachable as they have the lowest possible impact on both runtime and 17017adc3a2bSChandler Carruth // code size. 17027adc3a2bSChandler Carruth return true; // No actual code is needed for unreachable. 17037adc3a2bSChandler Carruth } 17047adc3a2bSChandler Carruth 17057adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) { 17067adc3a2bSChandler Carruth // Some instructions are free. All of the free intrinsics can also be 17077adc3a2bSChandler Carruth // handled by SROA, etc. 17087adc3a2bSChandler Carruth if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I)) 17097adc3a2bSChandler Carruth return true; 17107adc3a2bSChandler Carruth 17117adc3a2bSChandler Carruth // We found something we don't understand or can't handle. Mark any SROA-able 17127adc3a2bSChandler Carruth // values in the operand list as no longer viable. 17137adc3a2bSChandler Carruth for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI) 17147adc3a2bSChandler Carruth disableSROA(*OI); 17157adc3a2bSChandler Carruth 17167adc3a2bSChandler Carruth return false; 17177adc3a2bSChandler Carruth } 17187adc3a2bSChandler Carruth 17195f8f34e4SAdrian Prantl /// Analyze a basic block for its contribution to the inline cost. 17207adc3a2bSChandler Carruth /// 17217adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic 17227adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It 17237adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline 17247adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer 17257adc3a2bSChandler Carruth /// viable, and true if inlining remains viable. 1726c0aa4b75SDavid Bolvansky InlineResult 1727c0aa4b75SDavid Bolvansky CallAnalyzer::analyzeBlock(BasicBlock *BB, 17287adc3a2bSChandler Carruth SmallPtrSetImpl<const Value *> &EphValues) { 17297adc3a2bSChandler Carruth for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 17307adc3a2bSChandler Carruth // FIXME: Currently, the number of instructions in a function regardless of 17317adc3a2bSChandler Carruth // our ability to simplify them during inline to constants or dead code, 17327adc3a2bSChandler Carruth // are actually used by the vector bonus heuristic. As long as that's true, 17337adc3a2bSChandler Carruth // we have to special case debug intrinsics here to prevent differences in 17347adc3a2bSChandler Carruth // inlining due to debug symbols. Eventually, the number of unsimplified 17357adc3a2bSChandler Carruth // instructions shouldn't factor into the cost computation, but until then, 17367adc3a2bSChandler Carruth // hack around it here. 17377adc3a2bSChandler Carruth if (isa<DbgInfoIntrinsic>(I)) 17387adc3a2bSChandler Carruth continue; 17397adc3a2bSChandler Carruth 17407adc3a2bSChandler Carruth // Skip ephemeral values. 17415a82c916SDuncan P. N. Exon Smith if (EphValues.count(&*I)) 17427adc3a2bSChandler Carruth continue; 17437adc3a2bSChandler Carruth 17447adc3a2bSChandler Carruth ++NumInstructions; 17457adc3a2bSChandler Carruth if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy()) 17467adc3a2bSChandler Carruth ++NumVectorInstructions; 17477adc3a2bSChandler Carruth 17487adc3a2bSChandler Carruth // If the instruction simplified to a constant, there is no cost to this 17497adc3a2bSChandler Carruth // instruction. Visit the instructions using our InstVisitor to account for 17507adc3a2bSChandler Carruth // all of the per-instruction logic. The visit tree returns true if we 17517adc3a2bSChandler Carruth // consumed the instruction in any way, and false if the instruction's base 17527adc3a2bSChandler Carruth // cost should count against inlining. 17535a82c916SDuncan P. N. Exon Smith if (Base::visit(&*I)) 17547adc3a2bSChandler Carruth ++NumInstructionsSimplified; 17557adc3a2bSChandler Carruth else 1756*76aab66dSMircea Trofin onCommonInstructionSimplification(); 17577adc3a2bSChandler Carruth 17580812c5beSHaicheng Wu using namespace ore; 17597adc3a2bSChandler Carruth // If the visit this instruction detected an uninlinable pattern, abort. 1760c0aa4b75SDavid Bolvansky InlineResult IR; 1761c0aa4b75SDavid Bolvansky if (IsRecursiveCall) 1762c0aa4b75SDavid Bolvansky IR = "recursive"; 1763c0aa4b75SDavid Bolvansky else if (ExposesReturnsTwice) 1764c0aa4b75SDavid Bolvansky IR = "exposes returns twice"; 1765c0aa4b75SDavid Bolvansky else if (HasDynamicAlloca) 1766c0aa4b75SDavid Bolvansky IR = "dynamic alloca"; 1767c0aa4b75SDavid Bolvansky else if (HasIndirectBr) 1768c0aa4b75SDavid Bolvansky IR = "indirect branch"; 1769c0aa4b75SDavid Bolvansky else if (HasUninlineableIntrinsic) 1770c0aa4b75SDavid Bolvansky IR = "uninlinable intrinsic"; 177177beee41SSameer AbuAsal else if (InitsVargArgs) 1772c0aa4b75SDavid Bolvansky IR = "varargs"; 1773c0aa4b75SDavid Bolvansky if (!IR) { 17740812c5beSHaicheng Wu if (ORE) 17759590658fSVivek Pandya ORE->emit([&]() { 17769590658fSVivek Pandya return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 1777652168a9SFedor Sergeev &CandidateCall) 1778c0aa4b75SDavid Bolvansky << NV("Callee", &F) << " has uninlinable pattern (" 1779c0aa4b75SDavid Bolvansky << NV("InlineResult", IR.message) 1780c0aa4b75SDavid Bolvansky << ") and cost is not fully computed"; 17819590658fSVivek Pandya }); 1782c0aa4b75SDavid Bolvansky return IR; 17830812c5beSHaicheng Wu } 17847adc3a2bSChandler Carruth 17857adc3a2bSChandler Carruth // If the caller is a recursive function then we don't want to inline 17867adc3a2bSChandler Carruth // functions which allocate a lot of stack space because it would increase 17877adc3a2bSChandler Carruth // the caller stack usage dramatically. 17887adc3a2bSChandler Carruth if (IsCallerRecursive && 17890812c5beSHaicheng Wu AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) { 1790c0aa4b75SDavid Bolvansky InlineResult IR = "recursive and allocates too much stack space"; 17910812c5beSHaicheng Wu if (ORE) 17929590658fSVivek Pandya ORE->emit([&]() { 17939590658fSVivek Pandya return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 1794652168a9SFedor Sergeev &CandidateCall) 1795c0aa4b75SDavid Bolvansky << NV("Callee", &F) << " is " << NV("InlineResult", IR.message) 1796c0aa4b75SDavid Bolvansky << ". Cost is not fully computed"; 17979590658fSVivek Pandya }); 1798c0aa4b75SDavid Bolvansky return IR; 17990812c5beSHaicheng Wu } 18007adc3a2bSChandler Carruth 1801*76aab66dSMircea Trofin if (shouldStop()) 18027adc3a2bSChandler Carruth return false; 18037adc3a2bSChandler Carruth } 18047adc3a2bSChandler Carruth 18057adc3a2bSChandler Carruth return true; 18067adc3a2bSChandler Carruth } 18077adc3a2bSChandler Carruth 18085f8f34e4SAdrian Prantl /// Compute the base pointer and cumulative constant offsets for V. 18097adc3a2bSChandler Carruth /// 18107adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and 18117adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It 18127adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are 18137adc3a2bSChandler Carruth /// no constant offsets applied. 18147adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) { 18157adc3a2bSChandler Carruth if (!V->getType()->isPointerTy()) 18167adc3a2bSChandler Carruth return nullptr; 18177adc3a2bSChandler Carruth 181877f32994SBjorn Pettersson unsigned AS = V->getType()->getPointerAddressSpace(); 1819945b7e5aSElena Demikhovsky unsigned IntPtrWidth = DL.getIndexSizeInBits(AS); 18207adc3a2bSChandler Carruth APInt Offset = APInt::getNullValue(IntPtrWidth); 18217adc3a2bSChandler Carruth 18227adc3a2bSChandler Carruth // Even though we don't look through PHI nodes, we could be called on an 18237adc3a2bSChandler Carruth // instruction in an unreachable block, which may be on a cycle. 18247adc3a2bSChandler Carruth SmallPtrSet<Value *, 4> Visited; 18257adc3a2bSChandler Carruth Visited.insert(V); 18267adc3a2bSChandler Carruth do { 18277adc3a2bSChandler Carruth if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 18287adc3a2bSChandler Carruth if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset)) 18297adc3a2bSChandler Carruth return nullptr; 18307adc3a2bSChandler Carruth V = GEP->getPointerOperand(); 18317adc3a2bSChandler Carruth } else if (Operator::getOpcode(V) == Instruction::BitCast) { 18327adc3a2bSChandler Carruth V = cast<Operator>(V)->getOperand(0); 18337adc3a2bSChandler Carruth } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 18345ce32728SSanjoy Das if (GA->isInterposable()) 18357adc3a2bSChandler Carruth break; 18367adc3a2bSChandler Carruth V = GA->getAliasee(); 18377adc3a2bSChandler Carruth } else { 18387adc3a2bSChandler Carruth break; 18397adc3a2bSChandler Carruth } 18407adc3a2bSChandler Carruth assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 18417adc3a2bSChandler Carruth } while (Visited.insert(V).second); 18427adc3a2bSChandler Carruth 184397572775SNicola Zaghen Type *IdxPtrTy = DL.getIndexType(V->getType()); 184497572775SNicola Zaghen return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset)); 18457adc3a2bSChandler Carruth } 18467adc3a2bSChandler Carruth 18475f8f34e4SAdrian Prantl /// Find dead blocks due to deleted CFG edges during inlining. 18483739e14aSHaicheng Wu /// 18493739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p 18503739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have 18513739e14aSHaicheng Wu /// no live incoming CFG edges. If one block is found to be dead, we can 18523739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead 18533739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not. 18543739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) { 18553739e14aSHaicheng Wu auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) { 185602a2bb2fSHiroshi Inoue // A CFG edge is dead if the predecessor is dead or the predecessor has a 18573739e14aSHaicheng Wu // known successor which is not the one under exam. 18583739e14aSHaicheng Wu return (DeadBlocks.count(Pred) || 18593739e14aSHaicheng Wu (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ)); 18603739e14aSHaicheng Wu }; 18613739e14aSHaicheng Wu 18623739e14aSHaicheng Wu auto IsNewlyDead = [&](BasicBlock *BB) { 18633739e14aSHaicheng Wu // If all the edges to a block are dead, the block is also dead. 18643739e14aSHaicheng Wu return (!DeadBlocks.count(BB) && 18653739e14aSHaicheng Wu llvm::all_of(predecessors(BB), 18663739e14aSHaicheng Wu [&](BasicBlock *P) { return IsEdgeDead(P, BB); })); 18673739e14aSHaicheng Wu }; 18683739e14aSHaicheng Wu 18693739e14aSHaicheng Wu for (BasicBlock *Succ : successors(CurrBB)) { 18703739e14aSHaicheng Wu if (Succ == NextBB || !IsNewlyDead(Succ)) 18713739e14aSHaicheng Wu continue; 18723739e14aSHaicheng Wu SmallVector<BasicBlock *, 4> NewDead; 18733739e14aSHaicheng Wu NewDead.push_back(Succ); 18743739e14aSHaicheng Wu while (!NewDead.empty()) { 18753739e14aSHaicheng Wu BasicBlock *Dead = NewDead.pop_back_val(); 18763739e14aSHaicheng Wu if (DeadBlocks.insert(Dead)) 18773739e14aSHaicheng Wu // Continue growing the dead block lists. 18783739e14aSHaicheng Wu for (BasicBlock *S : successors(Dead)) 18793739e14aSHaicheng Wu if (IsNewlyDead(S)) 18803739e14aSHaicheng Wu NewDead.push_back(S); 18813739e14aSHaicheng Wu } 18823739e14aSHaicheng Wu } 18833739e14aSHaicheng Wu } 18843739e14aSHaicheng Wu 18855f8f34e4SAdrian Prantl /// Analyze a call site for potential inlining. 18867adc3a2bSChandler Carruth /// 18877adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not 18887adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous 18897adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost 18907adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by 18917adc3a2bSChandler Carruth /// some artifact of the routine. 189293ac81ccSMircea Trofin InlineResult CallAnalyzer::analyze() { 18937adc3a2bSChandler Carruth ++NumCallsAnalyzed; 18947adc3a2bSChandler Carruth 1895*76aab66dSMircea Trofin auto Result = onAnalysisStart(); 1896*76aab66dSMircea Trofin if (!Result) 1897*76aab66dSMircea Trofin return Result; 18987adc3a2bSChandler Carruth 18997adc3a2bSChandler Carruth if (F.empty()) 19007adc3a2bSChandler Carruth return true; 19017adc3a2bSChandler Carruth 190293ac81ccSMircea Trofin Function *Caller = CandidateCall.getFunction(); 19037adc3a2bSChandler Carruth // Check if the caller function is recursive itself. 19047adc3a2bSChandler Carruth for (User *U : Caller->users()) { 1905652168a9SFedor Sergeev CallBase *Call = dyn_cast<CallBase>(U); 1906652168a9SFedor Sergeev if (Call && Call->getFunction() == Caller) { 19077adc3a2bSChandler Carruth IsCallerRecursive = true; 19087adc3a2bSChandler Carruth break; 19097adc3a2bSChandler Carruth } 19107adc3a2bSChandler Carruth } 19117adc3a2bSChandler Carruth 19127adc3a2bSChandler Carruth // Populate our simplified values by mapping from function arguments to call 19137adc3a2bSChandler Carruth // arguments with known important simplifications. 191493ac81ccSMircea Trofin auto CAI = CandidateCall.arg_begin(); 19157adc3a2bSChandler Carruth for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end(); 19167adc3a2bSChandler Carruth FAI != FAE; ++FAI, ++CAI) { 191793ac81ccSMircea Trofin assert(CAI != CandidateCall.arg_end()); 19187adc3a2bSChandler Carruth if (Constant *C = dyn_cast<Constant>(CAI)) 19195a82c916SDuncan P. N. Exon Smith SimplifiedValues[&*FAI] = C; 19207adc3a2bSChandler Carruth 19217adc3a2bSChandler Carruth Value *PtrArg = *CAI; 19227adc3a2bSChandler Carruth if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) { 19235a82c916SDuncan P. N. Exon Smith ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue()); 19247adc3a2bSChandler Carruth 19257adc3a2bSChandler Carruth // We can SROA any pointer arguments derived from alloca instructions. 1926*76aab66dSMircea Trofin if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) { 1927*76aab66dSMircea Trofin SROAArgValues[&*FAI] = SROAArg; 1928*76aab66dSMircea Trofin onInitializeSROAArg(SROAArg); 19297adc3a2bSChandler Carruth } 19307adc3a2bSChandler Carruth } 19317adc3a2bSChandler Carruth } 19327adc3a2bSChandler Carruth NumConstantArgs = SimplifiedValues.size(); 19337adc3a2bSChandler Carruth NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size(); 19347adc3a2bSChandler Carruth NumAllocaArgs = SROAArgValues.size(); 19357adc3a2bSChandler Carruth 19367adc3a2bSChandler Carruth // FIXME: If a caller has multiple calls to a callee, we end up recomputing 19377adc3a2bSChandler Carruth // the ephemeral values multiple times (and they're completely determined by 19387adc3a2bSChandler Carruth // the callee, so this is purely duplicate work). 19397adc3a2bSChandler Carruth SmallPtrSet<const Value *, 32> EphValues; 1940aec2fa35SDaniel Jasper CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues); 19417adc3a2bSChandler Carruth 19427adc3a2bSChandler Carruth // The worklist of live basic blocks in the callee *after* inlining. We avoid 19437adc3a2bSChandler Carruth // adding basic blocks of the callee which can be proven to be dead for this 19447adc3a2bSChandler Carruth // particular call site in order to get more accurate cost estimates. This 19457adc3a2bSChandler Carruth // requires a somewhat heavyweight iteration pattern: we need to walk the 19467adc3a2bSChandler Carruth // basic blocks in a breadth-first order as we insert live successors. To 19477adc3a2bSChandler Carruth // accomplish this, prioritizing for small iterations because we exit after 19487adc3a2bSChandler Carruth // crossing our threshold, we use a small-size optimized SetVector. 19497adc3a2bSChandler Carruth typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>, 1950567556aaSChad Rosier SmallPtrSet<BasicBlock *, 16>> 1951567556aaSChad Rosier BBSetVector; 19527adc3a2bSChandler Carruth BBSetVector BBWorklist; 19537adc3a2bSChandler Carruth BBWorklist.insert(&F.getEntryBlock()); 1954*76aab66dSMircea Trofin 19557adc3a2bSChandler Carruth // Note that we *must not* cache the size, this loop grows the worklist. 19567adc3a2bSChandler Carruth for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 1957*76aab66dSMircea Trofin if (shouldStop()) 19587adc3a2bSChandler Carruth break; 19597adc3a2bSChandler Carruth 19607adc3a2bSChandler Carruth BasicBlock *BB = BBWorklist[Idx]; 19617adc3a2bSChandler Carruth if (BB->empty()) 19627adc3a2bSChandler Carruth continue; 19637adc3a2bSChandler Carruth 1964639b29b1SNick Desaulniers // Disallow inlining a blockaddress with uses other than strictly callbr. 1965639b29b1SNick Desaulniers // A blockaddress only has defined behavior for an indirect branch in the 1966639b29b1SNick Desaulniers // same function, and we do not currently support inlining indirect 1967639b29b1SNick Desaulniers // branches. But, the inliner may not see an indirect branch that ends up 1968639b29b1SNick Desaulniers // being dead code at a particular call site. If the blockaddress escapes 1969639b29b1SNick Desaulniers // the function, e.g., via a global variable, inlining may lead to an 1970639b29b1SNick Desaulniers // invalid cross-function reference. 1971639b29b1SNick Desaulniers // FIXME: pr/39560: continue relaxing this overt restriction. 19726a84cd3bSNick Desaulniers if (BB->hasAddressTaken()) 1973639b29b1SNick Desaulniers for (User *U : BlockAddress::get(&*BB)->users()) 1974639b29b1SNick Desaulniers if (!isa<CallBrInst>(*U)) 1975639b29b1SNick Desaulniers return "blockaddress used outside of callbr"; 19767adc3a2bSChandler Carruth 19777adc3a2bSChandler Carruth // Analyze the cost of this block. If we blow through the threshold, this 19787adc3a2bSChandler Carruth // returns false, and we can bail on out. 1979c0aa4b75SDavid Bolvansky InlineResult IR = analyzeBlock(BB, EphValues); 1980c0aa4b75SDavid Bolvansky if (!IR) 1981c0aa4b75SDavid Bolvansky return IR; 19827adc3a2bSChandler Carruth 1983edb12a83SChandler Carruth Instruction *TI = BB->getTerminator(); 19847adc3a2bSChandler Carruth 19857adc3a2bSChandler Carruth // Add in the live successors by first checking whether we have terminator 19867adc3a2bSChandler Carruth // that may be simplified based on the values simplified by this call. 19877adc3a2bSChandler Carruth if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 19887adc3a2bSChandler Carruth if (BI->isConditional()) { 19897adc3a2bSChandler Carruth Value *Cond = BI->getCondition(); 1990567556aaSChad Rosier if (ConstantInt *SimpleCond = 1991567556aaSChad Rosier dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 19923739e14aSHaicheng Wu BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0); 19933739e14aSHaicheng Wu BBWorklist.insert(NextBB); 19943739e14aSHaicheng Wu KnownSuccessors[BB] = NextBB; 19953739e14aSHaicheng Wu findDeadBlocks(BB, NextBB); 19967adc3a2bSChandler Carruth continue; 19977adc3a2bSChandler Carruth } 19987adc3a2bSChandler Carruth } 19997adc3a2bSChandler Carruth } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 20007adc3a2bSChandler Carruth Value *Cond = SI->getCondition(); 2001567556aaSChad Rosier if (ConstantInt *SimpleCond = 2002567556aaSChad Rosier dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 20033739e14aSHaicheng Wu BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor(); 20043739e14aSHaicheng Wu BBWorklist.insert(NextBB); 20053739e14aSHaicheng Wu KnownSuccessors[BB] = NextBB; 20063739e14aSHaicheng Wu findDeadBlocks(BB, NextBB); 20077adc3a2bSChandler Carruth continue; 20087adc3a2bSChandler Carruth } 20097adc3a2bSChandler Carruth } 20107adc3a2bSChandler Carruth 20117adc3a2bSChandler Carruth // If we're unable to select a particular successor, just count all of 20127adc3a2bSChandler Carruth // them. 20137adc3a2bSChandler Carruth for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize; 20147adc3a2bSChandler Carruth ++TIdx) 20157adc3a2bSChandler Carruth BBWorklist.insert(TI->getSuccessor(TIdx)); 20167adc3a2bSChandler Carruth 2017*76aab66dSMircea Trofin onBlockAnalyzed(BB); 20187adc3a2bSChandler Carruth } 20197adc3a2bSChandler Carruth 202093ac81ccSMircea Trofin bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() && 202193ac81ccSMircea Trofin &F == CandidateCall.getCalledFunction(); 20227adc3a2bSChandler Carruth // If this is a noduplicate call, we can still inline as long as 20237adc3a2bSChandler Carruth // inlining this would cause the removal of the caller (so the instruction 20247adc3a2bSChandler Carruth // is not actually duplicated, just moved). 20257adc3a2bSChandler Carruth if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall) 2026c0aa4b75SDavid Bolvansky return "noduplicate"; 20277adc3a2bSChandler Carruth 2028*76aab66dSMircea Trofin return finalizeAnalysis(); 20297adc3a2bSChandler Carruth } 20307adc3a2bSChandler Carruth 2031615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 20325f8f34e4SAdrian Prantl /// Dump stats about this call's analysis. 2033*76aab66dSMircea Trofin LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { 20347adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n" 20357adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantArgs); 20367adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs); 20377adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumAllocaArgs); 20387adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantPtrCmps); 20397adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumConstantPtrDiffs); 20407adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumInstructionsSimplified); 20417adc3a2bSChandler Carruth DEBUG_PRINT_STAT(NumInstructions); 20427adc3a2bSChandler Carruth DEBUG_PRINT_STAT(SROACostSavings); 20437adc3a2bSChandler Carruth DEBUG_PRINT_STAT(SROACostSavingsLost); 2044a4461515SHaicheng Wu DEBUG_PRINT_STAT(LoadEliminationCost); 20457adc3a2bSChandler Carruth DEBUG_PRINT_STAT(ContainsNoDuplicateCall); 20467adc3a2bSChandler Carruth DEBUG_PRINT_STAT(Cost); 20477adc3a2bSChandler Carruth DEBUG_PRINT_STAT(Threshold); 20487adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT 20497adc3a2bSChandler Carruth } 20507adc3a2bSChandler Carruth #endif 20517adc3a2bSChandler Carruth 20525f8f34e4SAdrian Prantl /// Test that there are no attribute conflicts between Caller and Callee 20537adc3a2bSChandler Carruth /// that prevent inlining. 20547adc3a2bSChandler Carruth static bool functionsHaveCompatibleAttributes(Function *Caller, 20557adc3a2bSChandler Carruth Function *Callee, 20567adc3a2bSChandler Carruth TargetTransformInfo &TTI) { 20577adc3a2bSChandler Carruth return TTI.areInlineCompatible(Caller, Callee) && 20581cb242ebSAkira Hatanaka AttributeFuncs::areInlineCompatible(*Caller, *Callee); 20597adc3a2bSChandler Carruth } 20607adc3a2bSChandler Carruth 2061652168a9SFedor Sergeev int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) { 2062351d9b01SXinliang David Li int Cost = 0; 2063652168a9SFedor Sergeev for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) { 2064652168a9SFedor Sergeev if (Call.isByValArgument(I)) { 2065351d9b01SXinliang David Li // We approximate the number of loads and stores needed by dividing the 2066351d9b01SXinliang David Li // size of the byval type by the target's pointer size. 2067652168a9SFedor Sergeev PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType()); 2068351d9b01SXinliang David Li unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType()); 206977f32994SBjorn Pettersson unsigned AS = PTy->getAddressSpace(); 207077f32994SBjorn Pettersson unsigned PointerSize = DL.getPointerSizeInBits(AS); 2071351d9b01SXinliang David Li // Ceiling division. 2072351d9b01SXinliang David Li unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize; 2073351d9b01SXinliang David Li 2074351d9b01SXinliang David Li // If it generates more than 8 stores it is likely to be expanded as an 2075351d9b01SXinliang David Li // inline memcpy so we take that as an upper bound. Otherwise we assume 2076351d9b01SXinliang David Li // one load and one store per word copied. 2077351d9b01SXinliang David Li // FIXME: The maxStoresPerMemcpy setting from the target should be used 2078351d9b01SXinliang David Li // here instead of a magic number of 8, but it's not available via 2079351d9b01SXinliang David Li // DataLayout. 2080351d9b01SXinliang David Li NumStores = std::min(NumStores, 8U); 2081351d9b01SXinliang David Li 2082351d9b01SXinliang David Li Cost += 2 * NumStores * InlineConstants::InstrCost; 2083351d9b01SXinliang David Li } else { 2084351d9b01SXinliang David Li // For non-byval arguments subtract off one instruction per call 2085351d9b01SXinliang David Li // argument. 2086351d9b01SXinliang David Li Cost += InlineConstants::InstrCost; 2087351d9b01SXinliang David Li } 2088351d9b01SXinliang David Li } 2089351d9b01SXinliang David Li // The call instruction also disappears after inlining. 2090351d9b01SXinliang David Li Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty; 2091351d9b01SXinliang David Li return Cost; 2092351d9b01SXinliang David Li } 2093351d9b01SXinliang David Li 2094ab6a6837SSean Silva InlineCost llvm::getInlineCost( 2095652168a9SFedor Sergeev CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, 2096aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 209712585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 20980812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 2099652168a9SFedor Sergeev return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI, 21000812c5beSHaicheng Wu GetAssumptionCache, GetBFI, PSI, ORE); 2101b9f7120eSEaswaran Raman } 2102b9f7120eSEaswaran Raman 2103ab6a6837SSean Silva InlineCost llvm::getInlineCost( 2104652168a9SFedor Sergeev CallBase &Call, Function *Callee, const InlineParams &Params, 2105aec2fa35SDaniel Jasper TargetTransformInfo &CalleeTTI, 2106aec2fa35SDaniel Jasper std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 210712585b01SEaswaran Raman Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 21080812c5beSHaicheng Wu ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 2109f4bb2f0dSEaswaran Raman 21107adc3a2bSChandler Carruth // Cannot inline indirect calls. 21117adc3a2bSChandler Carruth if (!Callee) 2112c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("indirect call"); 21137adc3a2bSChandler Carruth 21143851496eSBjorn Pettersson // Never inline calls with byval arguments that does not have the alloca 21153851496eSBjorn Pettersson // address space. Since byval arguments can be replaced with a copy to an 21163851496eSBjorn Pettersson // alloca, the inlined code would need to be adjusted to handle that the 21173851496eSBjorn Pettersson // argument is in the alloca address space (so it is a little bit complicated 21183851496eSBjorn Pettersson // to solve). 21193851496eSBjorn Pettersson unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace(); 2120652168a9SFedor Sergeev for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) 2121652168a9SFedor Sergeev if (Call.isByValArgument(I)) { 2122652168a9SFedor Sergeev PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType()); 21233851496eSBjorn Pettersson if (PTy->getAddressSpace() != AllocaAS) 2124c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("byval arguments without alloca" 2125c0aa4b75SDavid Bolvansky " address space"); 21263851496eSBjorn Pettersson } 21273851496eSBjorn Pettersson 21287adc3a2bSChandler Carruth // Calls to functions with always-inline attributes should be inlined 21297adc3a2bSChandler Carruth // whenever possible. 2130652168a9SFedor Sergeev if (Call.hasFnAttr(Attribute::AlwaysInline)) { 213115b17d0aSYevgeny Rouban auto IsViable = isInlineViable(*Callee); 213215b17d0aSYevgeny Rouban if (IsViable) 2133c0aa4b75SDavid Bolvansky return llvm::InlineCost::getAlways("always inline attribute"); 213415b17d0aSYevgeny Rouban return llvm::InlineCost::getNever(IsViable.message); 21357adc3a2bSChandler Carruth } 21367adc3a2bSChandler Carruth 21377adc3a2bSChandler Carruth // Never inline functions with conflicting attributes (unless callee has 21387adc3a2bSChandler Carruth // always-inline attribute). 2139652168a9SFedor Sergeev Function *Caller = Call.getCaller(); 21405ce28f4fSChad Rosier if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI)) 2141c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("conflicting attributes"); 21427adc3a2bSChandler Carruth 21437adc3a2bSChandler Carruth // Don't inline this call if the caller has the optnone attribute. 214485bd3978SEvandro Menezes if (Caller->hasOptNone()) 2145c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("optnone attribute"); 21467adc3a2bSChandler Carruth 214777eeac3dSManoj Gupta // Don't inline a function that treats null pointer as valid into a caller 214877eeac3dSManoj Gupta // that does not have this attribute. 214977eeac3dSManoj Gupta if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined()) 2150c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("nullptr definitions incompatible"); 215177eeac3dSManoj Gupta 2152c0aa4b75SDavid Bolvansky // Don't inline functions which can be interposed at link-time. 2153c0aa4b75SDavid Bolvansky if (Callee->isInterposable()) 2154c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("interposable"); 2155c0aa4b75SDavid Bolvansky 2156c0aa4b75SDavid Bolvansky // Don't inline functions marked noinline. 2157c0aa4b75SDavid Bolvansky if (Callee->hasFnAttribute(Attribute::NoInline)) 2158c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("noinline function attribute"); 2159c0aa4b75SDavid Bolvansky 2160c0aa4b75SDavid Bolvansky // Don't inline call sites marked noinline. 2161652168a9SFedor Sergeev if (Call.isNoInline()) 2162c0aa4b75SDavid Bolvansky return llvm::InlineCost::getNever("noinline call site attribute"); 21637adc3a2bSChandler Carruth 2164d34e60caSNicola Zaghen LLVM_DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName() 21654eb18742SChad Rosier << "... (caller:" << Caller->getName() << ")\n"); 21667adc3a2bSChandler Carruth 2167*76aab66dSMircea Trofin InlineCostCallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE, 2168*76aab66dSMircea Trofin *Callee, Call, Params); 216993ac81ccSMircea Trofin InlineResult ShouldInline = CA.analyze(); 21707adc3a2bSChandler Carruth 2171d34e60caSNicola Zaghen LLVM_DEBUG(CA.dump()); 21727adc3a2bSChandler Carruth 21737adc3a2bSChandler Carruth // Check if there was a reason to force inlining or no inlining. 21747adc3a2bSChandler Carruth if (!ShouldInline && CA.getCost() < CA.getThreshold()) 2175c0aa4b75SDavid Bolvansky return InlineCost::getNever(ShouldInline.message); 21767adc3a2bSChandler Carruth if (ShouldInline && CA.getCost() >= CA.getThreshold()) 2177c0aa4b75SDavid Bolvansky return InlineCost::getAlways("empty function"); 21787adc3a2bSChandler Carruth 21797adc3a2bSChandler Carruth return llvm::InlineCost::get(CA.getCost(), CA.getThreshold()); 21807adc3a2bSChandler Carruth } 21817adc3a2bSChandler Carruth 218215b17d0aSYevgeny Rouban InlineResult llvm::isInlineViable(Function &F) { 21837adc3a2bSChandler Carruth bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice); 21847adc3a2bSChandler Carruth for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) { 2185639b29b1SNick Desaulniers // Disallow inlining of functions which contain indirect branches. 218615b17d0aSYevgeny Rouban if (isa<IndirectBrInst>(BI->getTerminator())) 218715b17d0aSYevgeny Rouban return "contains indirect branches"; 218815b17d0aSYevgeny Rouban 2189639b29b1SNick Desaulniers // Disallow inlining of blockaddresses which are used by non-callbr 2190639b29b1SNick Desaulniers // instructions. 21916a84cd3bSNick Desaulniers if (BI->hasAddressTaken()) 2192639b29b1SNick Desaulniers for (User *U : BlockAddress::get(&*BI)->users()) 2193639b29b1SNick Desaulniers if (!isa<CallBrInst>(*U)) 2194639b29b1SNick Desaulniers return "blockaddress used outside of callbr"; 21957adc3a2bSChandler Carruth 21965a82c916SDuncan P. N. Exon Smith for (auto &II : *BI) { 2197652168a9SFedor Sergeev CallBase *Call = dyn_cast<CallBase>(&II); 2198652168a9SFedor Sergeev if (!Call) 21997adc3a2bSChandler Carruth continue; 22007adc3a2bSChandler Carruth 22017adc3a2bSChandler Carruth // Disallow recursive calls. 2202652168a9SFedor Sergeev if (&F == Call->getCalledFunction()) 220315b17d0aSYevgeny Rouban return "recursive call"; 22047adc3a2bSChandler Carruth 22057adc3a2bSChandler Carruth // Disallow calls which expose returns-twice to a function not previously 22067adc3a2bSChandler Carruth // attributed as such. 2207652168a9SFedor Sergeev if (!ReturnsTwice && isa<CallInst>(Call) && 2208652168a9SFedor Sergeev cast<CallInst>(Call)->canReturnTwice()) 220915b17d0aSYevgeny Rouban return "exposes returns-twice attribute"; 22107adc3a2bSChandler Carruth 2211652168a9SFedor Sergeev if (Call->getCalledFunction()) 2212652168a9SFedor Sergeev switch (Call->getCalledFunction()->getIntrinsicID()) { 22131636651eSFlorian Hahn default: 22141636651eSFlorian Hahn break; 22154296ea72SVitaly Buka // Disallow inlining of @llvm.icall.branch.funnel because current 22164296ea72SVitaly Buka // backend can't separate call targets from call arguments. 22174296ea72SVitaly Buka case llvm::Intrinsic::icall_branch_funnel: 221815b17d0aSYevgeny Rouban return "disallowed inlining of @llvm.icall.branch.funnel"; 22197adc3a2bSChandler Carruth // Disallow inlining functions that call @llvm.localescape. Doing this 22207adc3a2bSChandler Carruth // correctly would require major changes to the inliner. 22211636651eSFlorian Hahn case llvm::Intrinsic::localescape: 222215b17d0aSYevgeny Rouban return "disallowed inlining of @llvm.localescape"; 2223*76aab66dSMircea Trofin // Disallow inlining of functions that initialize VarArgs with 2224*76aab66dSMircea Trofin // va_start. 22251636651eSFlorian Hahn case llvm::Intrinsic::vastart: 222615b17d0aSYevgeny Rouban return "contains VarArgs initialized with va_start"; 22277adc3a2bSChandler Carruth } 22287adc3a2bSChandler Carruth } 22291636651eSFlorian Hahn } 22307adc3a2bSChandler Carruth 22317adc3a2bSChandler Carruth return true; 22327adc3a2bSChandler Carruth } 22331c57cc2bSEaswaran Raman 22341c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other 22351c57cc2bSEaswaran Raman // parameters. 22361c57cc2bSEaswaran Raman 22371c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) { 22381c57cc2bSEaswaran Raman InlineParams Params; 22391c57cc2bSEaswaran Raman 22401c57cc2bSEaswaran Raman // This field is the threshold to use for a callee by default. This is 22411c57cc2bSEaswaran Raman // derived from one or more of: 22421c57cc2bSEaswaran Raman // * optimization or size-optimization levels, 22431c57cc2bSEaswaran Raman // * a value passed to createFunctionInliningPass function, or 22441c57cc2bSEaswaran Raman // * the -inline-threshold flag. 22451c57cc2bSEaswaran Raman // If the -inline-threshold flag is explicitly specified, that is used 22461c57cc2bSEaswaran Raman // irrespective of anything else. 22471c57cc2bSEaswaran Raman if (InlineThreshold.getNumOccurrences() > 0) 22481c57cc2bSEaswaran Raman Params.DefaultThreshold = InlineThreshold; 22491c57cc2bSEaswaran Raman else 22501c57cc2bSEaswaran Raman Params.DefaultThreshold = Threshold; 22511c57cc2bSEaswaran Raman 22521c57cc2bSEaswaran Raman // Set the HintThreshold knob from the -inlinehint-threshold. 22531c57cc2bSEaswaran Raman Params.HintThreshold = HintThreshold; 22541c57cc2bSEaswaran Raman 22551c57cc2bSEaswaran Raman // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold. 22561c57cc2bSEaswaran Raman Params.HotCallSiteThreshold = HotCallSiteThreshold; 22571c57cc2bSEaswaran Raman 2258974d4eeaSEaswaran Raman // If the -locally-hot-callsite-threshold is explicitly specified, use it to 2259974d4eeaSEaswaran Raman // populate LocallyHotCallSiteThreshold. Later, we populate 2260974d4eeaSEaswaran Raman // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if 2261974d4eeaSEaswaran Raman // we know that optimization level is O3 (in the getInlineParams variant that 2262974d4eeaSEaswaran Raman // takes the opt and size levels). 2263974d4eeaSEaswaran Raman // FIXME: Remove this check (and make the assignment unconditional) after 2264974d4eeaSEaswaran Raman // addressing size regression issues at O2. 2265974d4eeaSEaswaran Raman if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0) 2266974d4eeaSEaswaran Raman Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2267974d4eeaSEaswaran Raman 22685a956c85SMircea Trofin // Set the ColdCallSiteThreshold knob from the 22695a956c85SMircea Trofin // -inline-cold-callsite-threshold. 227012585b01SEaswaran Raman Params.ColdCallSiteThreshold = ColdCallSiteThreshold; 227112585b01SEaswaran Raman 22721c57cc2bSEaswaran Raman // Set the OptMinSizeThreshold and OptSizeThreshold params only if the 22731c57cc2bSEaswaran Raman // -inlinehint-threshold commandline option is not explicitly given. If that 22741c57cc2bSEaswaran Raman // option is present, then its value applies even for callees with size and 22751c57cc2bSEaswaran Raman // minsize attributes. 22761c57cc2bSEaswaran Raman // If the -inline-threshold is not specified, set the ColdThreshold from the 22771c57cc2bSEaswaran Raman // -inlinecold-threshold even if it is not explicitly passed. If 22781c57cc2bSEaswaran Raman // -inline-threshold is specified, then -inlinecold-threshold needs to be 22791c57cc2bSEaswaran Raman // explicitly specified to set the ColdThreshold knob 22801c57cc2bSEaswaran Raman if (InlineThreshold.getNumOccurrences() == 0) { 22811c57cc2bSEaswaran Raman Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold; 22821c57cc2bSEaswaran Raman Params.OptSizeThreshold = InlineConstants::OptSizeThreshold; 22831c57cc2bSEaswaran Raman Params.ColdThreshold = ColdThreshold; 22841c57cc2bSEaswaran Raman } else if (ColdThreshold.getNumOccurrences() > 0) { 22851c57cc2bSEaswaran Raman Params.ColdThreshold = ColdThreshold; 22861c57cc2bSEaswaran Raman } 22871c57cc2bSEaswaran Raman return Params; 22881c57cc2bSEaswaran Raman } 22891c57cc2bSEaswaran Raman 22901c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() { 22911c57cc2bSEaswaran Raman return getInlineParams(InlineThreshold); 22921c57cc2bSEaswaran Raman } 22931c57cc2bSEaswaran Raman 22941c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the 22951c57cc2bSEaswaran Raman // size opt level. 22961c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel, 22971c57cc2bSEaswaran Raman unsigned SizeOptLevel) { 22981c57cc2bSEaswaran Raman if (OptLevel > 2) 22991c57cc2bSEaswaran Raman return InlineConstants::OptAggressiveThreshold; 23001c57cc2bSEaswaran Raman if (SizeOptLevel == 1) // -Os 23011c57cc2bSEaswaran Raman return InlineConstants::OptSizeThreshold; 23021c57cc2bSEaswaran Raman if (SizeOptLevel == 2) // -Oz 23031c57cc2bSEaswaran Raman return InlineConstants::OptMinSizeThreshold; 23041c57cc2bSEaswaran Raman return InlineThreshold; 23051c57cc2bSEaswaran Raman } 23061c57cc2bSEaswaran Raman 23071c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) { 2308974d4eeaSEaswaran Raman auto Params = 2309974d4eeaSEaswaran Raman getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel)); 2310974d4eeaSEaswaran Raman // At O3, use the value of -locally-hot-callsite-threshold option to populate 2311974d4eeaSEaswaran Raman // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only 2312974d4eeaSEaswaran Raman // when it is specified explicitly. 2313974d4eeaSEaswaran Raman if (OptLevel > 2) 2314974d4eeaSEaswaran Raman Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2315974d4eeaSEaswaran Raman return Params; 23161c57cc2bSEaswaran Raman } 2317