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"
217adc3a2bSChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
227adc3a2bSChandler Carruth #include "llvm/Analysis/ConstantFolding.h"
233739e14aSHaicheng Wu #include "llvm/Analysis/CFG.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"
397adc3a2bSChandler Carruth #include "llvm/Support/Debug.h"
407adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h"
417adc3a2bSChandler Carruth 
427adc3a2bSChandler Carruth using namespace llvm;
437adc3a2bSChandler Carruth 
447adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost"
457adc3a2bSChandler Carruth 
467adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
477adc3a2bSChandler Carruth 
481c57cc2bSEaswaran Raman static cl::opt<int> InlineThreshold(
49f4bb2f0dSEaswaran Raman     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
50f4bb2f0dSEaswaran Raman     cl::desc("Control the amount of inlining to perform (default = 225)"));
51f4bb2f0dSEaswaran Raman 
52f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold(
53fd3e7a93SDavid Callahan     "inlinehint-threshold", cl::Hidden, cl::init(325), cl::ZeroOrMore,
54f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with inline hint"));
55f4bb2f0dSEaswaran Raman 
5612585b01SEaswaran Raman static cl::opt<int>
5712585b01SEaswaran Raman     ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
58fd3e7a93SDavid Callahan                           cl::init(45), cl::ZeroOrMore,
5912585b01SEaswaran Raman                           cl::desc("Threshold for inlining cold callsites"));
6012585b01SEaswaran Raman 
61f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based
62f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and
63f4bb2f0dSEaswaran Raman // BFI.
64f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold(
65fd3e7a93SDavid Callahan     "inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore,
66f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with cold attribute"));
67f4bb2f0dSEaswaran Raman 
68de39cb93SDehao Chen static cl::opt<int>
69de39cb93SDehao Chen     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
70de39cb93SDehao Chen                          cl::ZeroOrMore,
71de39cb93SDehao Chen                          cl::desc("Threshold for hot callsites "));
72de39cb93SDehao Chen 
73974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold(
74974d4eeaSEaswaran Raman     "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore,
75974d4eeaSEaswaran Raman     cl::desc("Threshold for locally hot callsites "));
76974d4eeaSEaswaran Raman 
77c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq(
78c5fa6358SEaswaran Raman     "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
7902a2bb2fSHiroshi Inoue     cl::desc("Maximum block frequency, expressed as a percentage of caller's "
80c5fa6358SEaswaran Raman              "entry frequency, for a callsite to be cold in the absence of "
81c5fa6358SEaswaran Raman              "profile information."));
82c5fa6358SEaswaran Raman 
83974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq(
84974d4eeaSEaswaran Raman     "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore,
85ff77cc75SEaswaran Raman     cl::desc("Minimum block frequency, expressed as a multiple of caller's "
86974d4eeaSEaswaran Raman              "entry frequency, for a callsite to be hot in the absence of "
87974d4eeaSEaswaran Raman              "profile information."));
88974d4eeaSEaswaran Raman 
894924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost(
90fd3e7a93SDavid Callahan     "inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore,
910812c5beSHaicheng Wu     cl::desc("Compute the full inline cost of a call site even when the cost "
920812c5beSHaicheng Wu              "exceeds the threshold."));
930812c5beSHaicheng Wu 
947adc3a2bSChandler Carruth namespace {
957adc3a2bSChandler Carruth 
967adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
977adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
987adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
997adc3a2bSChandler Carruth 
1007adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
1017adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
1027adc3a2bSChandler Carruth 
103aec2fa35SDaniel Jasper   /// Getter for the cache of @llvm.assume intrinsics.
104aec2fa35SDaniel Jasper   std::function<AssumptionCache &(Function &)> &GetAssumptionCache;
105aec2fa35SDaniel Jasper 
10612585b01SEaswaran Raman   /// Getter for BlockFrequencyInfo
10712585b01SEaswaran Raman   Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI;
10812585b01SEaswaran Raman 
10971069cf6SEaswaran Raman   /// Profile summary information.
11071069cf6SEaswaran Raman   ProfileSummaryInfo *PSI;
11171069cf6SEaswaran Raman 
112f3d122cdSPiotr Padlewski   /// The called function.
1137adc3a2bSChandler Carruth   Function &F;
1147adc3a2bSChandler Carruth 
11585be8ca8SEric Christopher   // Cache the DataLayout since we use it a lot.
11685be8ca8SEric Christopher   const DataLayout &DL;
11785be8ca8SEric Christopher 
1180812c5beSHaicheng Wu   /// The OptimizationRemarkEmitter available for this compilation.
1190812c5beSHaicheng Wu   OptimizationRemarkEmitter *ORE;
1200812c5beSHaicheng Wu 
121f3d122cdSPiotr Padlewski   /// The candidate callsite being analyzed. Please do not use this to do
122f3d122cdSPiotr Padlewski   /// analysis in the caller function; we want the inline cost query to be
123f3d122cdSPiotr Padlewski   /// easily cacheable. Instead, use the cover function paramHasAttr.
124652168a9SFedor Sergeev   CallBase &CandidateCall;
1257adc3a2bSChandler Carruth 
126f3d122cdSPiotr Padlewski   /// Tunable parameters that control the analysis.
1271c57cc2bSEaswaran Raman   const InlineParams &Params;
1281c57cc2bSEaswaran Raman 
129eeae45dcSFedor Sergeev   /// Upper bound for the inlining cost. Bonuses are being applied to account
130eeae45dcSFedor Sergeev   /// for speculative "expected profit" of the inlining decision.
1317adc3a2bSChandler Carruth   int Threshold;
132eeae45dcSFedor Sergeev 
133eeae45dcSFedor Sergeev   /// Inlining cost measured in abstract units, accounts for all the
134eeae45dcSFedor Sergeev   /// instructions expected to be executed for a given function invocation.
135eeae45dcSFedor Sergeev   /// Instructions that are statically proven to be dead based on call-site
136eeae45dcSFedor Sergeev   /// arguments are not counted here.
137eeae45dcSFedor Sergeev   int Cost = 0;
138eeae45dcSFedor Sergeev 
1394924bb00SEaswaran Raman   bool ComputeFullInlineCost;
1407adc3a2bSChandler Carruth 
141eeae45dcSFedor Sergeev   bool IsCallerRecursive = false;
142eeae45dcSFedor Sergeev   bool IsRecursiveCall = false;
143eeae45dcSFedor Sergeev   bool ExposesReturnsTwice = false;
144eeae45dcSFedor Sergeev   bool HasDynamicAlloca = false;
145eeae45dcSFedor Sergeev   bool ContainsNoDuplicateCall = false;
146eeae45dcSFedor Sergeev   bool HasReturn = false;
147eeae45dcSFedor Sergeev   bool HasIndirectBr = false;
148eeae45dcSFedor Sergeev   bool HasUninlineableIntrinsic = false;
149eeae45dcSFedor Sergeev   bool InitsVargArgs = false;
1507adc3a2bSChandler Carruth 
1517adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
152eeae45dcSFedor Sergeev   uint64_t AllocatedSize = 0;
153eeae45dcSFedor Sergeev   unsigned NumInstructions = 0;
154eeae45dcSFedor Sergeev   unsigned NumVectorInstructions = 0;
155eeae45dcSFedor Sergeev 
156eeae45dcSFedor Sergeev   /// Bonus to be applied when percentage of vector instructions in callee is
157eeae45dcSFedor Sergeev   /// high (see more details in updateThreshold).
158eeae45dcSFedor Sergeev   int VectorBonus = 0;
159eeae45dcSFedor Sergeev   /// Bonus to be applied when the callee has only one reachable basic block.
160eeae45dcSFedor Sergeev   int SingleBBBonus = 0;
1617adc3a2bSChandler Carruth 
162f3d122cdSPiotr Padlewski   /// While we walk the potentially-inlined instructions, we build up and
163f3d122cdSPiotr Padlewski   /// maintain a mapping of simplified values specific to this callsite. The
164f3d122cdSPiotr Padlewski   /// idea is to propagate any special information we have about arguments to
165f3d122cdSPiotr Padlewski   /// this call through the inlinable section of the function, and account for
166f3d122cdSPiotr Padlewski   /// likely simplifications post-inlining. The most important aspect we track
167f3d122cdSPiotr Padlewski   /// is CFG altering simplifications -- when we prove a basic block dead, that
168f3d122cdSPiotr Padlewski   /// can cause dramatic shifts in the cost of inlining a function.
1697adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
1707adc3a2bSChandler Carruth 
171f3d122cdSPiotr Padlewski   /// Keep track of the values which map back (through function arguments) to
172f3d122cdSPiotr Padlewski   /// allocas on the caller stack which could be simplified through SROA.
1737adc3a2bSChandler Carruth   DenseMap<Value *, Value *> SROAArgValues;
1747adc3a2bSChandler Carruth 
175f3d122cdSPiotr Padlewski   /// The mapping of caller Alloca values to their accumulated cost savings. If
176f3d122cdSPiotr Padlewski   /// we have to disable SROA for one of the allocas, this tells us how much
177f3d122cdSPiotr Padlewski   /// cost must be added.
1787adc3a2bSChandler Carruth   DenseMap<Value *, int> SROAArgCosts;
1797adc3a2bSChandler Carruth 
180f3d122cdSPiotr Padlewski   /// Keep track of values which map to a pointer base and constant offset.
1817adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
1827adc3a2bSChandler Carruth 
1833739e14aSHaicheng Wu   /// Keep track of dead blocks due to the constant arguments.
1843739e14aSHaicheng Wu   SetVector<BasicBlock *> DeadBlocks;
1853739e14aSHaicheng Wu 
1863739e14aSHaicheng Wu   /// The mapping of the blocks to their known unique successors due to the
1873739e14aSHaicheng Wu   /// constant arguments.
1883739e14aSHaicheng Wu   DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
1893739e14aSHaicheng Wu 
190a4461515SHaicheng Wu   /// Model the elimination of repeated loads that is expected to happen
191a4461515SHaicheng Wu   /// whenever we simplify away the stores that would otherwise cause them to be
192a4461515SHaicheng Wu   /// loads.
193a4461515SHaicheng Wu   bool EnableLoadElimination;
194a4461515SHaicheng Wu   SmallPtrSet<Value *, 16> LoadAddrSet;
195eeae45dcSFedor Sergeev   int LoadEliminationCost = 0;
196a4461515SHaicheng Wu 
1977adc3a2bSChandler Carruth   // Custom simplification helper routines.
1987adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
1997adc3a2bSChandler Carruth   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
2007adc3a2bSChandler Carruth                             DenseMap<Value *, int>::iterator &CostIt);
2017adc3a2bSChandler Carruth   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
2027adc3a2bSChandler Carruth   void disableSROA(Value *V);
2033739e14aSHaicheng Wu   void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
2047adc3a2bSChandler Carruth   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
2057adc3a2bSChandler Carruth                           int InstructionCost);
206a4461515SHaicheng Wu   void disableLoadElimination();
207201b191bSHaicheng Wu   bool isGEPFree(GetElementPtrInst &GEP);
208d3558b5dSEvgeny Astigeevich   bool canFoldInboundsGEP(GetElementPtrInst &I);
2097adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
210652168a9SFedor Sergeev   bool simplifyCallSite(Function *F, CallBase &Call);
211617f6364SEaswaran Raman   template <typename Callable>
212617f6364SEaswaran Raman   bool simplifyInstruction(Instruction &I, Callable Evaluate);
2137adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
2147adc3a2bSChandler Carruth 
2157adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
2167adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
2177adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
2187adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
2197adc3a2bSChandler Carruth   /// itself.
2207adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
2217adc3a2bSChandler Carruth 
2227adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
2237adc3a2bSChandler Carruth   /// inlined through this particular callsite.
2247adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
2257adc3a2bSChandler Carruth 
226f4bb2f0dSEaswaran Raman   /// Update Threshold based on callsite properties such as callee
227f4bb2f0dSEaswaran Raman   /// attributes and callee hotness for PGO builds. The Callee is explicitly
228f4bb2f0dSEaswaran Raman   /// passed to support analyzing indirect calls whose target is inferred by
229f4bb2f0dSEaswaran Raman   /// analysis.
230652168a9SFedor Sergeev   void updateThreshold(CallBase &Call, Function &Callee);
231f4bb2f0dSEaswaran Raman 
232652168a9SFedor Sergeev   /// Return true if size growth is allowed when inlining the callee at \p Call.
233652168a9SFedor Sergeev   bool allowSizeGrowth(CallBase &Call);
2349a3fc17aSEaswaran Raman 
235652168a9SFedor Sergeev   /// Return true if \p Call is a cold callsite.
236652168a9SFedor Sergeev   bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
237c5fa6358SEaswaran Raman 
238652168a9SFedor Sergeev   /// Return a higher threshold if \p Call is a hot callsite.
239652168a9SFedor Sergeev   Optional<int> getHotCallSiteThreshold(CallBase &Call,
240974d4eeaSEaswaran Raman                                         BlockFrequencyInfo *CallerBFI);
241974d4eeaSEaswaran Raman 
2427adc3a2bSChandler Carruth   // Custom analysis routines.
243c0aa4b75SDavid Bolvansky   InlineResult analyzeBlock(BasicBlock *BB,
244c0aa4b75SDavid Bolvansky                             SmallPtrSetImpl<const Value *> &EphValues);
2457adc3a2bSChandler Carruth 
246eeae45dcSFedor Sergeev   /// Handle a capped 'int' increment for Cost.
247eeae45dcSFedor Sergeev   void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
248eeae45dcSFedor Sergeev     assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound");
249eeae45dcSFedor Sergeev     Cost = (int)std::min(UpperBound, Cost + Inc);
250eeae45dcSFedor Sergeev   }
251eeae45dcSFedor Sergeev 
2527adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
2537adc3a2bSChandler Carruth   // them by declaring but not defining them here.
254567556aaSChad Rosier   void visit(Module *);
255567556aaSChad Rosier   void visit(Module &);
256567556aaSChad Rosier   void visit(Function *);
257567556aaSChad Rosier   void visit(Function &);
258567556aaSChad Rosier   void visit(BasicBlock *);
259567556aaSChad Rosier   void visit(BasicBlock &);
2607adc3a2bSChandler Carruth 
2617adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
2627adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
2637adc3a2bSChandler Carruth 
2647adc3a2bSChandler Carruth   // Our visit overrides.
2657adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
2667adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
2677adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
2687adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
2697adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
2707adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
2717adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
2727adc3a2bSChandler Carruth   bool visitUnaryInstruction(UnaryInstruction &I);
2737adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
2747adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
2757adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
2766cda33baSCraig Topper   bool visitFNeg(UnaryOperator &I);
2777adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
2787adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
2797adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
2807adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
281652168a9SFedor Sergeev   bool visitCallBase(CallBase &Call);
2827adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
2837adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
2843ec848bcSHaicheng Wu   bool visitSelectInst(SelectInst &SI);
2857adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
2867adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
2877adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
2887adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
2897adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
2907adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
2917adc3a2bSChandler Carruth 
2927adc3a2bSChandler Carruth public:
293ab6a6837SSean Silva   CallAnalyzer(const TargetTransformInfo &TTI,
294aec2fa35SDaniel Jasper                std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
29512585b01SEaswaran Raman                Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI,
2960812c5beSHaicheng Wu                ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE,
297652168a9SFedor Sergeev                Function &Callee, CallBase &Call, const InlineParams &Params)
29812585b01SEaswaran Raman       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
2990812c5beSHaicheng Wu         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
300652168a9SFedor Sergeev         CandidateCall(Call), Params(Params), Threshold(Params.DefaultThreshold),
301eeae45dcSFedor Sergeev         ComputeFullInlineCost(OptComputeFullInlineCost ||
3024924bb00SEaswaran Raman                               Params.ComputeFullInlineCost || ORE),
303eeae45dcSFedor Sergeev         EnableLoadElimination(true) {}
3047adc3a2bSChandler Carruth 
305652168a9SFedor Sergeev   InlineResult analyzeCall(CallBase &Call);
3067adc3a2bSChandler Carruth 
3077adc3a2bSChandler Carruth   int getThreshold() { return Threshold; }
3087adc3a2bSChandler Carruth   int getCost() { return Cost; }
3097adc3a2bSChandler Carruth 
3107adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
3117adc3a2bSChandler Carruth   // out when debugging.
312eeae45dcSFedor Sergeev   unsigned NumConstantArgs = 0;
313eeae45dcSFedor Sergeev   unsigned NumConstantOffsetPtrArgs = 0;
314eeae45dcSFedor Sergeev   unsigned NumAllocaArgs = 0;
315eeae45dcSFedor Sergeev   unsigned NumConstantPtrCmps = 0;
316eeae45dcSFedor Sergeev   unsigned NumConstantPtrDiffs = 0;
317eeae45dcSFedor Sergeev   unsigned NumInstructionsSimplified = 0;
318eeae45dcSFedor Sergeev   unsigned SROACostSavings = 0;
319eeae45dcSFedor Sergeev   unsigned SROACostSavingsLost = 0;
3207adc3a2bSChandler Carruth 
3217adc3a2bSChandler Carruth   void dump();
3227adc3a2bSChandler Carruth };
3237adc3a2bSChandler Carruth 
3247adc3a2bSChandler Carruth } // namespace
3257adc3a2bSChandler Carruth 
3265f8f34e4SAdrian Prantl /// Test whether the given value is an Alloca-derived function argument.
3277adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
3287adc3a2bSChandler Carruth   return SROAArgValues.count(V);
3297adc3a2bSChandler Carruth }
3307adc3a2bSChandler Carruth 
3315f8f34e4SAdrian Prantl /// Lookup the SROA-candidate argument and cost iterator which V maps to.
3327adc3a2bSChandler Carruth /// Returns false if V does not map to a SROA-candidate.
3337adc3a2bSChandler Carruth bool CallAnalyzer::lookupSROAArgAndCost(
3347adc3a2bSChandler Carruth     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
3357adc3a2bSChandler Carruth   if (SROAArgValues.empty() || SROAArgCosts.empty())
3367adc3a2bSChandler Carruth     return false;
3377adc3a2bSChandler Carruth 
3387adc3a2bSChandler Carruth   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
3397adc3a2bSChandler Carruth   if (ArgIt == SROAArgValues.end())
3407adc3a2bSChandler Carruth     return false;
3417adc3a2bSChandler Carruth 
3427adc3a2bSChandler Carruth   Arg = ArgIt->second;
3437adc3a2bSChandler Carruth   CostIt = SROAArgCosts.find(Arg);
3447adc3a2bSChandler Carruth   return CostIt != SROAArgCosts.end();
3457adc3a2bSChandler Carruth }
3467adc3a2bSChandler Carruth 
3475f8f34e4SAdrian Prantl /// Disable SROA for the candidate marked by this cost iterator.
3487adc3a2bSChandler Carruth ///
3497adc3a2bSChandler Carruth /// This marks the candidate as no longer viable for SROA, and adds the cost
3507adc3a2bSChandler Carruth /// savings associated with it back into the inline cost measurement.
3517adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
3527adc3a2bSChandler Carruth   // If we're no longer able to perform SROA we need to undo its cost savings
3537adc3a2bSChandler Carruth   // and prevent subsequent analysis.
354eeae45dcSFedor Sergeev   addCost(CostIt->second);
3557adc3a2bSChandler Carruth   SROACostSavings -= CostIt->second;
3567adc3a2bSChandler Carruth   SROACostSavingsLost += CostIt->second;
3577adc3a2bSChandler Carruth   SROAArgCosts.erase(CostIt);
358a4461515SHaicheng Wu   disableLoadElimination();
3597adc3a2bSChandler Carruth }
3607adc3a2bSChandler Carruth 
3615f8f34e4SAdrian Prantl /// If 'V' maps to a SROA candidate, disable SROA for it.
3627adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
3637adc3a2bSChandler Carruth   Value *SROAArg;
3647adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
3657adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
3667adc3a2bSChandler Carruth     disableSROA(CostIt);
3677adc3a2bSChandler Carruth }
3687adc3a2bSChandler Carruth 
3695f8f34e4SAdrian Prantl /// Accumulate the given cost for a particular SROA candidate.
3707adc3a2bSChandler Carruth void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
3717adc3a2bSChandler Carruth                                       int InstructionCost) {
3727adc3a2bSChandler Carruth   CostIt->second += InstructionCost;
3737adc3a2bSChandler Carruth   SROACostSavings += InstructionCost;
3747adc3a2bSChandler Carruth }
3757adc3a2bSChandler Carruth 
376a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() {
377a4461515SHaicheng Wu   if (EnableLoadElimination) {
378eeae45dcSFedor Sergeev     addCost(LoadEliminationCost);
379b3689cabSHaicheng Wu     LoadEliminationCost = 0;
380a4461515SHaicheng Wu     EnableLoadElimination = false;
381a4461515SHaicheng Wu   }
382a4461515SHaicheng Wu }
383a4461515SHaicheng Wu 
3845f8f34e4SAdrian Prantl /// Accumulate a constant GEP offset into an APInt if possible.
3857adc3a2bSChandler Carruth ///
3867adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
3877adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
3887adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
389945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
3907adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
3917adc3a2bSChandler Carruth 
3927adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
3937adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
3947adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
3957adc3a2bSChandler Carruth     if (!OpC)
3967adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
3977adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
3987adc3a2bSChandler Carruth     if (!OpC)
3997adc3a2bSChandler Carruth       return false;
400567556aaSChad Rosier     if (OpC->isZero())
401567556aaSChad Rosier       continue;
4027adc3a2bSChandler Carruth 
4037adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
404ab85225bSPeter Collingbourne     if (StructType *STy = GTI.getStructTypeOrNull()) {
4057adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
4067adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
4077adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
4087adc3a2bSChandler Carruth       continue;
4097adc3a2bSChandler Carruth     }
4107adc3a2bSChandler Carruth 
4117adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
4127adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
4137adc3a2bSChandler Carruth   }
4147adc3a2bSChandler Carruth   return true;
4157adc3a2bSChandler Carruth }
4167adc3a2bSChandler Carruth 
4175f8f34e4SAdrian Prantl /// Use TTI to check whether a GEP is free.
418201b191bSHaicheng Wu ///
419201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite.
420201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
42161c1bd5aSEvgeny Astigeevich   SmallVector<Value *, 4> Operands;
42261c1bd5aSEvgeny Astigeevich   Operands.push_back(GEP.getOperand(0));
423201b191bSHaicheng Wu   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
424201b191bSHaicheng Wu     if (Constant *SimpleOp = SimplifiedValues.lookup(*I))
42561c1bd5aSEvgeny Astigeevich        Operands.push_back(SimpleOp);
426201b191bSHaicheng Wu      else
42761c1bd5aSEvgeny Astigeevich        Operands.push_back(*I);
42861c1bd5aSEvgeny Astigeevich   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands);
429201b191bSHaicheng Wu }
430201b191bSHaicheng Wu 
4317adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
4327adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
4330f153424SSanjay Patel   // alloca and handle that case.
4347adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
4350f153424SSanjay Patel     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
4360f153424SSanjay Patel     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
4377adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
43822eb80a1SEaswaran Raman       AllocatedSize = SaturatingMultiplyAdd(
43922eb80a1SEaswaran Raman           AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty), AllocatedSize);
4407adc3a2bSChandler Carruth       return Base::visitAlloca(I);
4417adc3a2bSChandler Carruth     }
4427adc3a2bSChandler Carruth   }
4437adc3a2bSChandler Carruth 
4447adc3a2bSChandler Carruth   // Accumulate the allocated size.
4457adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
4467adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
44722eb80a1SEaswaran Raman     AllocatedSize = SaturatingAdd(DL.getTypeAllocSize(Ty), AllocatedSize);
4487adc3a2bSChandler Carruth   }
4497adc3a2bSChandler Carruth 
4507adc3a2bSChandler Carruth   // We will happily inline static alloca instructions.
4517adc3a2bSChandler Carruth   if (I.isStaticAlloca())
4527adc3a2bSChandler Carruth     return Base::visitAlloca(I);
4537adc3a2bSChandler Carruth 
4547adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
4557adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
4567adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
4577adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
4587adc3a2bSChandler Carruth   HasDynamicAlloca = true;
4597adc3a2bSChandler Carruth   return false;
4607adc3a2bSChandler Carruth }
4617adc3a2bSChandler Carruth 
4627adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
4637adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
4647adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
4657adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
4667adc3a2bSChandler Carruth 
4677adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
46877f32994SBjorn Pettersson   // FIXME: Pointer sizes may differ between different address spaces, so do we
46977f32994SBjorn Pettersson   // need to use correct address space in the call to getPointerSizeInBits here?
47077f32994SBjorn Pettersson   // Or could we skip the getPointerSizeInBits call completely? As far as I can
47177f32994SBjorn Pettersson   // see the ZeroOffset is used as a dummy value, so we can probably use any
47277f32994SBjorn Pettersson   // bit width for the ZeroOffset?
47377f32994SBjorn Pettersson   APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0));
4743739e14aSHaicheng Wu   bool CheckSROA = I.getType()->isPointerTy();
4753739e14aSHaicheng Wu 
4763739e14aSHaicheng Wu   // Track the constant or pointer with constant offset we've seen so far.
4773739e14aSHaicheng Wu   Constant *FirstC = nullptr;
4783739e14aSHaicheng Wu   std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
4793739e14aSHaicheng Wu   Value *FirstV = nullptr;
4803739e14aSHaicheng Wu 
4813739e14aSHaicheng Wu   for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
4823739e14aSHaicheng Wu     BasicBlock *Pred = I.getIncomingBlock(i);
4833739e14aSHaicheng Wu     // If the incoming block is dead, skip the incoming block.
4843739e14aSHaicheng Wu     if (DeadBlocks.count(Pred))
4853739e14aSHaicheng Wu       continue;
4863739e14aSHaicheng Wu     // If the parent block of phi is not the known successor of the incoming
4873739e14aSHaicheng Wu     // block, skip the incoming block.
4883739e14aSHaicheng Wu     BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
4893739e14aSHaicheng Wu     if (KnownSuccessor && KnownSuccessor != I.getParent())
4903739e14aSHaicheng Wu       continue;
4913739e14aSHaicheng Wu 
4923739e14aSHaicheng Wu     Value *V = I.getIncomingValue(i);
4933739e14aSHaicheng Wu     // If the incoming value is this phi itself, skip the incoming value.
4943739e14aSHaicheng Wu     if (&I == V)
4953739e14aSHaicheng Wu       continue;
4963739e14aSHaicheng Wu 
4973739e14aSHaicheng Wu     Constant *C = dyn_cast<Constant>(V);
4983739e14aSHaicheng Wu     if (!C)
4993739e14aSHaicheng Wu       C = SimplifiedValues.lookup(V);
5003739e14aSHaicheng Wu 
5013739e14aSHaicheng Wu     std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
5023739e14aSHaicheng Wu     if (!C && CheckSROA)
5033739e14aSHaicheng Wu       BaseAndOffset = ConstantOffsetPtrs.lookup(V);
5043739e14aSHaicheng Wu 
5053739e14aSHaicheng Wu     if (!C && !BaseAndOffset.first)
5063739e14aSHaicheng Wu       // The incoming value is neither a constant nor a pointer with constant
5073739e14aSHaicheng Wu       // offset, exit early.
5083739e14aSHaicheng Wu       return true;
5093739e14aSHaicheng Wu 
5103739e14aSHaicheng Wu     if (FirstC) {
5113739e14aSHaicheng Wu       if (FirstC == C)
5123739e14aSHaicheng Wu         // If we've seen a constant incoming value before and it is the same
5133739e14aSHaicheng Wu         // constant we see this time, continue checking the next incoming value.
5143739e14aSHaicheng Wu         continue;
5153739e14aSHaicheng Wu       // Otherwise early exit because we either see a different constant or saw
5163739e14aSHaicheng Wu       // a constant before but we have a pointer with constant offset this time.
5173739e14aSHaicheng Wu       return true;
5183739e14aSHaicheng Wu     }
5193739e14aSHaicheng Wu 
5203739e14aSHaicheng Wu     if (FirstV) {
5213739e14aSHaicheng Wu       // The same logic as above, but check pointer with constant offset here.
5223739e14aSHaicheng Wu       if (FirstBaseAndOffset == BaseAndOffset)
5233739e14aSHaicheng Wu         continue;
5243739e14aSHaicheng Wu       return true;
5253739e14aSHaicheng Wu     }
5263739e14aSHaicheng Wu 
5273739e14aSHaicheng Wu     if (C) {
5283739e14aSHaicheng Wu       // This is the 1st time we've seen a constant, record it.
5293739e14aSHaicheng Wu       FirstC = C;
5303739e14aSHaicheng Wu       continue;
5313739e14aSHaicheng Wu     }
5323739e14aSHaicheng Wu 
5333739e14aSHaicheng Wu     // The remaining case is that this is the 1st time we've seen a pointer with
5343739e14aSHaicheng Wu     // constant offset, record it.
5353739e14aSHaicheng Wu     FirstV = V;
5363739e14aSHaicheng Wu     FirstBaseAndOffset = BaseAndOffset;
5373739e14aSHaicheng Wu   }
5383739e14aSHaicheng Wu 
5393739e14aSHaicheng Wu   // Check if we can map phi to a constant.
5403739e14aSHaicheng Wu   if (FirstC) {
5413739e14aSHaicheng Wu     SimplifiedValues[&I] = FirstC;
5423739e14aSHaicheng Wu     return true;
5433739e14aSHaicheng Wu   }
5443739e14aSHaicheng Wu 
5453739e14aSHaicheng Wu   // Check if we can map phi to a pointer with constant offset.
5463739e14aSHaicheng Wu   if (FirstBaseAndOffset.first) {
5473739e14aSHaicheng Wu     ConstantOffsetPtrs[&I] = FirstBaseAndOffset;
5483739e14aSHaicheng Wu 
5493739e14aSHaicheng Wu     Value *SROAArg;
5503739e14aSHaicheng Wu     DenseMap<Value *, int>::iterator CostIt;
5513739e14aSHaicheng Wu     if (lookupSROAArgAndCost(FirstV, SROAArg, CostIt))
5523739e14aSHaicheng Wu       SROAArgValues[&I] = SROAArg;
5533739e14aSHaicheng Wu   }
5543739e14aSHaicheng Wu 
5557adc3a2bSChandler Carruth   return true;
5567adc3a2bSChandler Carruth }
5577adc3a2bSChandler Carruth 
5585f8f34e4SAdrian Prantl /// Check we can fold GEPs of constant-offset call site argument pointers.
559d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs.
560d3558b5dSEvgeny Astigeevich ///
561d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded.
562d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
563d3558b5dSEvgeny Astigeevich   // Check if we have a base + offset for the pointer.
564d3558b5dSEvgeny Astigeevich   std::pair<Value *, APInt> BaseAndOffset =
565d3558b5dSEvgeny Astigeevich       ConstantOffsetPtrs.lookup(I.getPointerOperand());
566d3558b5dSEvgeny Astigeevich   if (!BaseAndOffset.first)
567d3558b5dSEvgeny Astigeevich     return false;
568d3558b5dSEvgeny Astigeevich 
569d3558b5dSEvgeny Astigeevich   // Check if the offset of this GEP is constant, and if so accumulate it
570d3558b5dSEvgeny Astigeevich   // into Offset.
571d3558b5dSEvgeny Astigeevich   if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
572d3558b5dSEvgeny Astigeevich     return false;
573d3558b5dSEvgeny Astigeevich 
574d3558b5dSEvgeny Astigeevich   // Add the result as a new mapping to Base + Offset.
575d3558b5dSEvgeny Astigeevich   ConstantOffsetPtrs[&I] = BaseAndOffset;
576d3558b5dSEvgeny Astigeevich 
577d3558b5dSEvgeny Astigeevich   return true;
578d3558b5dSEvgeny Astigeevich }
579d3558b5dSEvgeny Astigeevich 
5807adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
5817adc3a2bSChandler Carruth   Value *SROAArg;
5827adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
583567556aaSChad Rosier   bool SROACandidate =
584567556aaSChad Rosier       lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt);
5857adc3a2bSChandler Carruth 
586a8b9cdc9SEaswaran Raman   // Lambda to check whether a GEP's indices are all constant.
587a8b9cdc9SEaswaran Raman   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
588a8b9cdc9SEaswaran Raman     for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
589a8b9cdc9SEaswaran Raman       if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
590a8b9cdc9SEaswaran Raman         return false;
591a8b9cdc9SEaswaran Raman     return true;
592a8b9cdc9SEaswaran Raman   };
593a8b9cdc9SEaswaran Raman 
594d3558b5dSEvgeny Astigeevich   if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
5957adc3a2bSChandler Carruth     if (SROACandidate)
5967adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
5977adc3a2bSChandler Carruth 
5987adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
5997adc3a2bSChandler Carruth     return true;
6007adc3a2bSChandler Carruth   }
6017adc3a2bSChandler Carruth 
6027adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
6037adc3a2bSChandler Carruth   if (SROACandidate)
6047adc3a2bSChandler Carruth     disableSROA(CostIt);
605201b191bSHaicheng Wu   return isGEPFree(I);
6067adc3a2bSChandler Carruth }
6077adc3a2bSChandler Carruth 
608617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues.
609617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the
610617f6364SEaswaran Raman /// instruction when all the operands are constants.
611617f6364SEaswaran Raman template <typename Callable>
612617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
613617f6364SEaswaran Raman   SmallVector<Constant *, 2> COps;
614617f6364SEaswaran Raman   for (Value *Op : I.operands()) {
615617f6364SEaswaran Raman     Constant *COp = dyn_cast<Constant>(Op);
6167adc3a2bSChandler Carruth     if (!COp)
617617f6364SEaswaran Raman       COp = SimplifiedValues.lookup(Op);
618617f6364SEaswaran Raman     if (!COp)
619617f6364SEaswaran Raman       return false;
620617f6364SEaswaran Raman     COps.push_back(COp);
621617f6364SEaswaran Raman   }
622617f6364SEaswaran Raman   auto *C = Evaluate(COps);
623617f6364SEaswaran Raman   if (!C)
624617f6364SEaswaran Raman     return false;
6257adc3a2bSChandler Carruth   SimplifiedValues[&I] = C;
6267adc3a2bSChandler Carruth   return true;
6277adc3a2bSChandler Carruth }
6287adc3a2bSChandler Carruth 
629617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) {
630617f6364SEaswaran Raman   // Propagate constants through bitcasts.
631617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
632617f6364SEaswaran Raman         return ConstantExpr::getBitCast(COps[0], I.getType());
633617f6364SEaswaran Raman       }))
634617f6364SEaswaran Raman     return true;
635617f6364SEaswaran Raman 
6367adc3a2bSChandler Carruth   // Track base/offsets through casts
637567556aaSChad Rosier   std::pair<Value *, APInt> BaseAndOffset =
638567556aaSChad Rosier       ConstantOffsetPtrs.lookup(I.getOperand(0));
6397adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
6407adc3a2bSChandler Carruth   if (BaseAndOffset.first)
6417adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
6427adc3a2bSChandler Carruth 
6437adc3a2bSChandler Carruth   // Also look for SROA candidates here.
6447adc3a2bSChandler Carruth   Value *SROAArg;
6457adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
6467adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
6477adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
6487adc3a2bSChandler Carruth 
6497adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
6507adc3a2bSChandler Carruth   return true;
6517adc3a2bSChandler Carruth }
6527adc3a2bSChandler Carruth 
6537adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
6547adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
655617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
656617f6364SEaswaran Raman         return ConstantExpr::getPtrToInt(COps[0], I.getType());
657617f6364SEaswaran Raman       }))
6587adc3a2bSChandler Carruth     return true;
6597adc3a2bSChandler Carruth 
6607adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
6617adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
6627adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
66377f32994SBjorn Pettersson   unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
66477f32994SBjorn Pettersson   if (IntegerSize >= DL.getPointerSizeInBits(AS)) {
665567556aaSChad Rosier     std::pair<Value *, APInt> BaseAndOffset =
666567556aaSChad Rosier         ConstantOffsetPtrs.lookup(I.getOperand(0));
6677adc3a2bSChandler Carruth     if (BaseAndOffset.first)
6687adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
6697adc3a2bSChandler Carruth   }
6707adc3a2bSChandler Carruth 
6717adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
6727adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
6737adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
6747adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
6757adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
6767adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
6777adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
6787adc3a2bSChandler Carruth   Value *SROAArg;
6797adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
6807adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
6817adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
6827adc3a2bSChandler Carruth 
6837adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
6847adc3a2bSChandler Carruth }
6857adc3a2bSChandler Carruth 
6867adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
6877adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
688617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
689617f6364SEaswaran Raman         return ConstantExpr::getIntToPtr(COps[0], I.getType());
690617f6364SEaswaran Raman       }))
6917adc3a2bSChandler Carruth     return true;
6927adc3a2bSChandler Carruth 
6937adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
6947adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
6957adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
6967adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
69777f32994SBjorn Pettersson   if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
6987adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
6997adc3a2bSChandler Carruth     if (BaseAndOffset.first)
7007adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
7017adc3a2bSChandler Carruth   }
7027adc3a2bSChandler Carruth 
7037adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
7047adc3a2bSChandler Carruth   Value *SROAArg;
7057adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
7067adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
7077adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
7087adc3a2bSChandler Carruth 
7097adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
7107adc3a2bSChandler Carruth }
7117adc3a2bSChandler Carruth 
7127adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
713ab53c5e5SCraig Topper   // Propagate constants through casts.
714617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
715617f6364SEaswaran Raman         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
716617f6364SEaswaran Raman       }))
7177adc3a2bSChandler Carruth     return true;
7187adc3a2bSChandler Carruth 
7197adc3a2bSChandler Carruth   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
7207adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
7217adc3a2bSChandler Carruth 
72239ed9a60SEli Friedman   // If this is a floating-point cast, and the target says this operation
72339ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
72439ed9a60SEli Friedman   // as such.
72539ed9a60SEli Friedman   switch (I.getOpcode()) {
72639ed9a60SEli Friedman   case Instruction::FPTrunc:
72739ed9a60SEli Friedman   case Instruction::FPExt:
72839ed9a60SEli Friedman   case Instruction::UIToFP:
72939ed9a60SEli Friedman   case Instruction::SIToFP:
73039ed9a60SEli Friedman   case Instruction::FPToUI:
73139ed9a60SEli Friedman   case Instruction::FPToSI:
73239ed9a60SEli Friedman     if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive)
733eeae45dcSFedor Sergeev       addCost(InlineConstants::CallPenalty);
7344dc0b1acSReid Kleckner     break;
73539ed9a60SEli Friedman   default:
73639ed9a60SEli Friedman     break;
73739ed9a60SEli Friedman   }
73839ed9a60SEli Friedman 
7397adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
7407adc3a2bSChandler Carruth }
7417adc3a2bSChandler Carruth 
7427adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
7437adc3a2bSChandler Carruth   Value *Operand = I.getOperand(0);
744617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
745617f6364SEaswaran Raman         return ConstantFoldInstOperands(&I, COps[0], DL);
746617f6364SEaswaran Raman       }))
7477adc3a2bSChandler Carruth     return true;
7487adc3a2bSChandler Carruth 
749ab53c5e5SCraig Topper   // Disable any SROA on the argument to arbitrary unary instructions.
7507adc3a2bSChandler Carruth   disableSROA(Operand);
7517adc3a2bSChandler Carruth 
7527adc3a2bSChandler Carruth   return false;
7537adc3a2bSChandler Carruth }
7547adc3a2bSChandler Carruth 
7557adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
756652168a9SFedor Sergeev   return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
7577adc3a2bSChandler Carruth }
7587adc3a2bSChandler Carruth 
7597adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
7607adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
7617adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
7627adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
7637adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
7647adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
7657adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
7667adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
7677adc3a2bSChandler Carruth       return true;
7687adc3a2bSChandler Carruth 
7697adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
7707adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
7717adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
7727adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
7737adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
7747adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
7757adc3a2bSChandler Carruth     // SROA firing.
7767adc3a2bSChandler Carruth     return true;
7777adc3a2bSChandler Carruth 
7787adc3a2bSChandler Carruth   return false;
7797adc3a2bSChandler Carruth }
7807adc3a2bSChandler Carruth 
781652168a9SFedor Sergeev bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
7829a3fc17aSEaswaran Raman   // If the normal destination of the invoke or the parent block of the call
7839a3fc17aSEaswaran Raman   // site is unreachable-terminated, there is little point in inlining this
7849a3fc17aSEaswaran Raman   // unless there is literally zero cost.
7859a3fc17aSEaswaran Raman   // FIXME: Note that it is possible that an unreachable-terminated block has a
7869a3fc17aSEaswaran Raman   // hot entry. For example, in below scenario inlining hot_call_X() may be
7879a3fc17aSEaswaran Raman   // beneficial :
7889a3fc17aSEaswaran Raman   // main() {
7899a3fc17aSEaswaran Raman   //   hot_call_1();
7909a3fc17aSEaswaran Raman   //   ...
7919a3fc17aSEaswaran Raman   //   hot_call_N()
7929a3fc17aSEaswaran Raman   //   exit(0);
7939a3fc17aSEaswaran Raman   // }
7949a3fc17aSEaswaran Raman   // For now, we are not handling this corner case here as it is rare in real
7959a3fc17aSEaswaran Raman   // code. In future, we should elaborate this based on BPI and BFI in more
7969a3fc17aSEaswaran Raman   // general threshold adjusting heuristics in updateThreshold().
797652168a9SFedor Sergeev   if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
7989a3fc17aSEaswaran Raman     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
7999a3fc17aSEaswaran Raman       return false;
800652168a9SFedor Sergeev   } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
8019a3fc17aSEaswaran Raman     return false;
8029a3fc17aSEaswaran Raman 
8039a3fc17aSEaswaran Raman   return true;
8049a3fc17aSEaswaran Raman }
8059a3fc17aSEaswaran Raman 
806652168a9SFedor Sergeev bool CallAnalyzer::isColdCallSite(CallBase &Call,
807652168a9SFedor Sergeev                                   BlockFrequencyInfo *CallerBFI) {
808c5fa6358SEaswaran Raman   // If global profile summary is available, then callsite's coldness is
809c5fa6358SEaswaran Raman   // determined based on that.
810bba762a1SChandler Carruth   if (PSI && PSI->hasProfileSummary())
811652168a9SFedor Sergeev     return PSI->isColdCallSite(CallSite(&Call), CallerBFI);
812bba762a1SChandler Carruth 
813bba762a1SChandler Carruth   // Otherwise we need BFI to be available.
814c5fa6358SEaswaran Raman   if (!CallerBFI)
815c5fa6358SEaswaran Raman     return false;
816c5fa6358SEaswaran Raman 
817bba762a1SChandler Carruth   // Determine if the callsite is cold relative to caller's entry. We could
818bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
819bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
820bba762a1SChandler Carruth   // profiles.
821c5fa6358SEaswaran Raman   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
822652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
823c5fa6358SEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
824c5fa6358SEaswaran Raman   auto CallerEntryFreq =
825652168a9SFedor Sergeev       CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
826c5fa6358SEaswaran Raman   return CallSiteFreq < CallerEntryFreq * ColdProb;
827c5fa6358SEaswaran Raman }
828c5fa6358SEaswaran Raman 
829974d4eeaSEaswaran Raman Optional<int>
830652168a9SFedor Sergeev CallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
831974d4eeaSEaswaran Raman                                       BlockFrequencyInfo *CallerBFI) {
832bba762a1SChandler Carruth 
833974d4eeaSEaswaran Raman   // If global profile summary is available, then callsite's hotness is
834974d4eeaSEaswaran Raman   // determined based on that.
835652168a9SFedor Sergeev   if (PSI && PSI->hasProfileSummary() &&
836652168a9SFedor Sergeev       PSI->isHotCallSite(CallSite(&Call), CallerBFI))
837bba762a1SChandler Carruth     return Params.HotCallSiteThreshold;
838974d4eeaSEaswaran Raman 
839bba762a1SChandler Carruth   // Otherwise we need BFI to be available and to have a locally hot callsite
840bba762a1SChandler Carruth   // threshold.
841bba762a1SChandler Carruth   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
842974d4eeaSEaswaran Raman     return None;
843974d4eeaSEaswaran Raman 
844bba762a1SChandler Carruth   // Determine if the callsite is hot relative to caller's entry. We could
845bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
846bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
847bba762a1SChandler Carruth   // profiles.
848652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
849974d4eeaSEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
850974d4eeaSEaswaran Raman   auto CallerEntryFreq = CallerBFI->getEntryFreq();
851974d4eeaSEaswaran Raman   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
852bba762a1SChandler Carruth     return Params.LocallyHotCallSiteThreshold;
853bba762a1SChandler Carruth 
854bba762a1SChandler Carruth   // Otherwise treat it normally.
855974d4eeaSEaswaran Raman   return None;
856974d4eeaSEaswaran Raman }
857974d4eeaSEaswaran Raman 
858652168a9SFedor Sergeev void CallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
8599a3fc17aSEaswaran Raman   // If no size growth is allowed for this inlining, set Threshold to 0.
860652168a9SFedor Sergeev   if (!allowSizeGrowth(Call)) {
8619a3fc17aSEaswaran Raman     Threshold = 0;
8629a3fc17aSEaswaran Raman     return;
8639a3fc17aSEaswaran Raman   }
8649a3fc17aSEaswaran Raman 
865652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
8661c57cc2bSEaswaran Raman 
8671c57cc2bSEaswaran Raman   // return min(A, B) if B is valid.
8681c57cc2bSEaswaran Raman   auto MinIfValid = [](int A, Optional<int> B) {
8691c57cc2bSEaswaran Raman     return B ? std::min(A, B.getValue()) : A;
8701c57cc2bSEaswaran Raman   };
8711c57cc2bSEaswaran Raman 
8720d58fcacSEaswaran Raman   // return max(A, B) if B is valid.
8730d58fcacSEaswaran Raman   auto MaxIfValid = [](int A, Optional<int> B) {
8740d58fcacSEaswaran Raman     return B ? std::max(A, B.getValue()) : A;
8750d58fcacSEaswaran Raman   };
8760d58fcacSEaswaran Raman 
87751b809bfSEaswaran Raman   // Various bonus percentages. These are multiplied by Threshold to get the
87851b809bfSEaswaran Raman   // bonus values.
87951b809bfSEaswaran Raman   // SingleBBBonus: This bonus is applied if the callee has a single reachable
88051b809bfSEaswaran Raman   // basic block at the given callsite context. This is speculatively applied
88151b809bfSEaswaran Raman   // and withdrawn if more than one basic block is seen.
88251b809bfSEaswaran Raman   //
88351b809bfSEaswaran Raman   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
88451b809bfSEaswaran Raman   // of the last call to a static function as inlining such functions is
88551b809bfSEaswaran Raman   // guaranteed to reduce code size.
88651b809bfSEaswaran Raman   //
88751b809bfSEaswaran Raman   // These bonus percentages may be set to 0 based on properties of the caller
88851b809bfSEaswaran Raman   // and the callsite.
88951b809bfSEaswaran Raman   int SingleBBBonusPercent = 50;
890d912a9baSDaniil Fukalov   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
89102647f73SJordan Rupprecht   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
89251b809bfSEaswaran Raman 
89351b809bfSEaswaran Raman   // Lambda to set all the above bonus and bonus percentages to 0.
89451b809bfSEaswaran Raman   auto DisallowAllBonuses = [&]() {
89551b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
89651b809bfSEaswaran Raman     VectorBonusPercent = 0;
89751b809bfSEaswaran Raman     LastCallToStaticBonus = 0;
89851b809bfSEaswaran Raman   };
89951b809bfSEaswaran Raman 
9001c57cc2bSEaswaran Raman   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
9011c57cc2bSEaswaran Raman   // and reduce the threshold if the caller has the necessary attribute.
90285bd3978SEvandro Menezes   if (Caller->hasMinSize()) {
9031c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
90451b809bfSEaswaran Raman     // For minsize, we want to disable the single BB bonus and the vector
90551b809bfSEaswaran Raman     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
90651b809bfSEaswaran Raman     // a static function will, at the minimum, eliminate the parameter setup and
90751b809bfSEaswaran Raman     // call/return instructions.
90851b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
90951b809bfSEaswaran Raman     VectorBonusPercent = 0;
91085bd3978SEvandro Menezes   } else if (Caller->hasOptSize())
9111c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
912f4bb2f0dSEaswaran Raman 
913e08b139dSEaswaran Raman   // Adjust the threshold based on inlinehint attribute and profile based
914e08b139dSEaswaran Raman   // hotness information if the caller does not have MinSize attribute.
91585bd3978SEvandro Menezes   if (!Caller->hasMinSize()) {
916e08b139dSEaswaran Raman     if (Callee.hasFnAttribute(Attribute::InlineHint))
9170d58fcacSEaswaran Raman       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
918bba762a1SChandler Carruth 
9193cd1479cSEaswaran Raman     // FIXME: After switching to the new passmanager, simplify the logic below
920bba762a1SChandler Carruth     // by checking only the callsite hotness/coldness as we will reliably
921bba762a1SChandler Carruth     // have local profile information.
9223cd1479cSEaswaran Raman     //
923bba762a1SChandler Carruth     // Callsite hotness and coldness can be determined if sample profile is
924bba762a1SChandler Carruth     // used (which adds hotness metadata to calls) or if caller's
925bba762a1SChandler Carruth     // BlockFrequencyInfo is available.
926bba762a1SChandler Carruth     BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr;
927652168a9SFedor Sergeev     auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
92885bd3978SEvandro Menezes     if (!Caller->hasOptSize() && HotCallSiteThreshold) {
929d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Hot callsite.\n");
930974d4eeaSEaswaran Raman       // FIXME: This should update the threshold only if it exceeds the
931974d4eeaSEaswaran Raman       // current threshold, but AutoFDO + ThinLTO currently relies on this
932974d4eeaSEaswaran Raman       // behavior to prevent inlining of hot callsites during ThinLTO
933974d4eeaSEaswaran Raman       // compile phase.
934974d4eeaSEaswaran Raman       Threshold = HotCallSiteThreshold.getValue();
935652168a9SFedor Sergeev     } else if (isColdCallSite(Call, CallerBFI)) {
936d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Cold callsite.\n");
93751b809bfSEaswaran Raman       // Do not apply bonuses for a cold callsite including the
93851b809bfSEaswaran Raman       // LastCallToStatic bonus. While this bonus might result in code size
93951b809bfSEaswaran Raman       // reduction, it can cause the size of a non-cold caller to increase
94051b809bfSEaswaran Raman       // preventing it from being inlined.
94151b809bfSEaswaran Raman       DisallowAllBonuses();
9423cd1479cSEaswaran Raman       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
943bba762a1SChandler Carruth     } else if (PSI) {
944bba762a1SChandler Carruth       // Use callee's global profile information only if we have no way of
945bba762a1SChandler Carruth       // determining this via callsite information.
9463cd1479cSEaswaran Raman       if (PSI->isFunctionEntryHot(&Callee)) {
947d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Hot callee.\n");
948e08b139dSEaswaran Raman         // If callsite hotness can not be determined, we may still know
949e08b139dSEaswaran Raman         // that the callee is hot and treat it as a weaker hint for threshold
950e08b139dSEaswaran Raman         // increase.
951e08b139dSEaswaran Raman         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
952e08b139dSEaswaran Raman       } else if (PSI->isFunctionEntryCold(&Callee)) {
953d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Cold callee.\n");
95451b809bfSEaswaran Raman         // Do not apply bonuses for a cold callee including the
95551b809bfSEaswaran Raman         // LastCallToStatic bonus. While this bonus might result in code size
95651b809bfSEaswaran Raman         // reduction, it can cause the size of a non-cold caller to increase
95751b809bfSEaswaran Raman         // preventing it from being inlined.
95851b809bfSEaswaran Raman         DisallowAllBonuses();
9591c57cc2bSEaswaran Raman         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
960e08b139dSEaswaran Raman       }
961e08b139dSEaswaran Raman     }
962e08b139dSEaswaran Raman   }
9638650a4daSJustin Lebar 
96402647f73SJordan Rupprecht   // Finally, take the target-specific inlining threshold multiplier into
96502647f73SJordan Rupprecht   // account.
9668650a4daSJustin Lebar   Threshold *= TTI.getInliningThresholdMultiplier();
96751b809bfSEaswaran Raman 
96851b809bfSEaswaran Raman   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
96951b809bfSEaswaran Raman   VectorBonus = Threshold * VectorBonusPercent / 100;
97051b809bfSEaswaran Raman 
97102647f73SJordan Rupprecht   bool OnlyOneCallAndLocalLinkage =
97202647f73SJordan Rupprecht       F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction();
97302647f73SJordan Rupprecht   // If there is only one call of the function, and it has internal linkage,
97402647f73SJordan Rupprecht   // the cost of inlining it drops dramatically. It may seem odd to update
97502647f73SJordan Rupprecht   // Cost in updateThreshold, but the bonus depends on the logic in this method.
97602647f73SJordan Rupprecht   if (OnlyOneCallAndLocalLinkage)
97702647f73SJordan Rupprecht     Cost -= LastCallToStaticBonus;
978f4bb2f0dSEaswaran Raman }
979f4bb2f0dSEaswaran Raman 
9807adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
9817adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
9827adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
983617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
984617f6364SEaswaran Raman         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
985617f6364SEaswaran Raman       }))
9867adc3a2bSChandler Carruth     return true;
9877adc3a2bSChandler Carruth 
9887adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
9897adc3a2bSChandler Carruth     return false;
9907adc3a2bSChandler Carruth 
9917adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
9927adc3a2bSChandler Carruth   // a common base.
9937adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
9947adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
9957adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
9967adc3a2bSChandler Carruth   if (LHSBase) {
9977adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
9987adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
9997adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
10007adc3a2bSChandler Carruth       // offsets.
10017adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
10027adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
10037adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
10047adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
10057adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
10067adc3a2bSChandler Carruth         return true;
10077adc3a2bSChandler Carruth       }
10087adc3a2bSChandler Carruth     }
10097adc3a2bSChandler Carruth   }
10107adc3a2bSChandler Carruth 
10117adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
10127adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
10137adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
10147adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
10157adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
10167adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
10177adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
10187adc3a2bSChandler Carruth     return true;
10197adc3a2bSChandler Carruth   }
10207adc3a2bSChandler Carruth   // Finally check for SROA candidates in comparisons.
10217adc3a2bSChandler Carruth   Value *SROAArg;
10227adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
10237adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
10247adc3a2bSChandler Carruth     if (isa<ConstantPointerNull>(I.getOperand(1))) {
10257adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
10267adc3a2bSChandler Carruth       return true;
10277adc3a2bSChandler Carruth     }
10287adc3a2bSChandler Carruth 
10297adc3a2bSChandler Carruth     disableSROA(CostIt);
10307adc3a2bSChandler Carruth   }
10317adc3a2bSChandler Carruth 
10327adc3a2bSChandler Carruth   return false;
10337adc3a2bSChandler Carruth }
10347adc3a2bSChandler Carruth 
10357adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
10367adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
10377adc3a2bSChandler Carruth   // constant-related pointers.
10387adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
10397adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
10407adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
10417adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
10427adc3a2bSChandler Carruth   if (LHSBase) {
10437adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
10447adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
10457adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
10467adc3a2bSChandler Carruth       // offsets.
10477adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
10487adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
10497adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
10507adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
10517adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
10527adc3a2bSChandler Carruth         return true;
10537adc3a2bSChandler Carruth       }
10547adc3a2bSChandler Carruth     }
10557adc3a2bSChandler Carruth   }
10567adc3a2bSChandler Carruth 
10577adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
10587adc3a2bSChandler Carruth   // instructions.
10597adc3a2bSChandler Carruth   return Base::visitSub(I);
10607adc3a2bSChandler Carruth }
10617adc3a2bSChandler Carruth 
10627adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
10637adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
10646d14dfe8SHaicheng Wu   Constant *CLHS = dyn_cast<Constant>(LHS);
10656d14dfe8SHaicheng Wu   if (!CLHS)
10666d14dfe8SHaicheng Wu     CLHS = SimplifiedValues.lookup(LHS);
10676d14dfe8SHaicheng Wu   Constant *CRHS = dyn_cast<Constant>(RHS);
10686d14dfe8SHaicheng Wu   if (!CRHS)
10696d14dfe8SHaicheng Wu     CRHS = SimplifiedValues.lookup(RHS);
10706d14dfe8SHaicheng Wu 
10717adc3a2bSChandler Carruth   Value *SimpleV = nullptr;
10727adc3a2bSChandler Carruth   if (auto FI = dyn_cast<FPMathOperator>(&I))
1073*565c5432SJay Foad     SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS,
10746d14dfe8SHaicheng Wu                             CRHS ? CRHS : RHS, FI->getFastMathFlags(), DL);
10757adc3a2bSChandler Carruth   else
10766d14dfe8SHaicheng Wu     SimpleV =
10776d14dfe8SHaicheng Wu         SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
10787adc3a2bSChandler Carruth 
10796d14dfe8SHaicheng Wu   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
10806d14dfe8SHaicheng Wu     SimplifiedValues[&I] = C;
10816d14dfe8SHaicheng Wu 
10826d14dfe8SHaicheng Wu   if (SimpleV)
10837adc3a2bSChandler Carruth     return true;
10847adc3a2bSChandler Carruth 
10857adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
10867adc3a2bSChandler Carruth   disableSROA(LHS);
10877adc3a2bSChandler Carruth   disableSROA(RHS);
10887adc3a2bSChandler Carruth 
108939ed9a60SEli Friedman   // If the instruction is floating point, and the target says this operation
109039ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
10917cebf0afSCraig Topper   // as such. Unless it's fneg which can be implemented with an xor.
10927cebf0afSCraig Topper   using namespace llvm::PatternMatch;
109339ed9a60SEli Friedman   if (I.getType()->isFloatingPointTy() &&
10947cebf0afSCraig Topper       TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive &&
10957cebf0afSCraig Topper       !match(&I, m_FNeg(m_Value())))
1096eeae45dcSFedor Sergeev     addCost(InlineConstants::CallPenalty);
109739ed9a60SEli Friedman 
10987adc3a2bSChandler Carruth   return false;
10997adc3a2bSChandler Carruth }
11007adc3a2bSChandler Carruth 
11016cda33baSCraig Topper bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
11026cda33baSCraig Topper   Value *Op = I.getOperand(0);
11036cda33baSCraig Topper   Constant *COp = dyn_cast<Constant>(Op);
11046cda33baSCraig Topper   if (!COp)
11056cda33baSCraig Topper     COp = SimplifiedValues.lookup(Op);
11066cda33baSCraig Topper 
11076cda33baSCraig Topper   Value *SimpleV = SimplifyFNegInst(COp ? COp : Op,
11086cda33baSCraig Topper                                     cast<FPMathOperator>(I).getFastMathFlags(),
11096cda33baSCraig Topper                                     DL);
11106cda33baSCraig Topper 
11116cda33baSCraig Topper   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
11126cda33baSCraig Topper     SimplifiedValues[&I] = C;
11136cda33baSCraig Topper 
11146cda33baSCraig Topper   if (SimpleV)
11156cda33baSCraig Topper     return true;
11166cda33baSCraig Topper 
11176cda33baSCraig Topper   // Disable any SROA on arguments to arbitrary, unsimplified fneg.
11186cda33baSCraig Topper   disableSROA(Op);
11196cda33baSCraig Topper 
11206cda33baSCraig Topper   return false;
11216cda33baSCraig Topper }
11226cda33baSCraig Topper 
11237adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
11247adc3a2bSChandler Carruth   Value *SROAArg;
11257adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
11267adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
11277adc3a2bSChandler Carruth     if (I.isSimple()) {
11287adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
11297adc3a2bSChandler Carruth       return true;
11307adc3a2bSChandler Carruth     }
11317adc3a2bSChandler Carruth 
11327adc3a2bSChandler Carruth     disableSROA(CostIt);
11337adc3a2bSChandler Carruth   }
11347adc3a2bSChandler Carruth 
1135a4461515SHaicheng Wu   // If the data is already loaded from this address and hasn't been clobbered
1136a4461515SHaicheng Wu   // by any stores or calls, this load is likely to be redundant and can be
1137a4461515SHaicheng Wu   // eliminated.
1138a4461515SHaicheng Wu   if (EnableLoadElimination &&
1139b3689cabSHaicheng Wu       !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
1140a4461515SHaicheng Wu     LoadEliminationCost += InlineConstants::InstrCost;
1141a4461515SHaicheng Wu     return true;
1142a4461515SHaicheng Wu   }
1143a4461515SHaicheng Wu 
11447adc3a2bSChandler Carruth   return false;
11457adc3a2bSChandler Carruth }
11467adc3a2bSChandler Carruth 
11477adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
11487adc3a2bSChandler Carruth   Value *SROAArg;
11497adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
11507adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
11517adc3a2bSChandler Carruth     if (I.isSimple()) {
11527adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
11537adc3a2bSChandler Carruth       return true;
11547adc3a2bSChandler Carruth     }
11557adc3a2bSChandler Carruth 
11567adc3a2bSChandler Carruth     disableSROA(CostIt);
11577adc3a2bSChandler Carruth   }
11587adc3a2bSChandler Carruth 
1159a4461515SHaicheng Wu   // The store can potentially clobber loads and prevent repeated loads from
1160a4461515SHaicheng Wu   // being eliminated.
1161a4461515SHaicheng Wu   // FIXME:
1162a4461515SHaicheng Wu   // 1. We can probably keep an initial set of eliminatable loads substracted
1163a4461515SHaicheng Wu   // from the cost even when we finally see a store. We just need to disable
1164a4461515SHaicheng Wu   // *further* accumulation of elimination savings.
1165a4461515SHaicheng Wu   // 2. We should probably at some point thread MemorySSA for the callee into
1166a4461515SHaicheng Wu   // this and then use that to actually compute *really* precise savings.
1167a4461515SHaicheng Wu   disableLoadElimination();
11687adc3a2bSChandler Carruth   return false;
11697adc3a2bSChandler Carruth }
11707adc3a2bSChandler Carruth 
11717adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
11727adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
1173617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1174617f6364SEaswaran Raman         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
1175617f6364SEaswaran Raman       }))
11767adc3a2bSChandler Carruth     return true;
11777adc3a2bSChandler Carruth 
11787adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
11797adc3a2bSChandler Carruth   return false;
11807adc3a2bSChandler Carruth }
11817adc3a2bSChandler Carruth 
11827adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
11837adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
1184617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1185617f6364SEaswaran Raman         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
1186617f6364SEaswaran Raman                                             /*InsertedValueOperand*/ COps[1],
1187617f6364SEaswaran Raman                                             I.getIndices());
1188617f6364SEaswaran Raman       }))
11897adc3a2bSChandler Carruth     return true;
11907adc3a2bSChandler Carruth 
11917adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
11927adc3a2bSChandler Carruth   return false;
11937adc3a2bSChandler Carruth }
11947adc3a2bSChandler Carruth 
11955f8f34e4SAdrian Prantl /// Try to simplify a call site.
11967adc3a2bSChandler Carruth ///
11977adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
11987adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
11997adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
12007adc3a2bSChandler Carruth /// free.
1201652168a9SFedor Sergeev bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
12027adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
12037adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
12047adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
12057adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
1206652168a9SFedor Sergeev   if (!canConstantFoldCallTo(&Call, F))
12077adc3a2bSChandler Carruth     return false;
12087adc3a2bSChandler Carruth 
12097adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
12107adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
1211652168a9SFedor Sergeev   ConstantArgs.reserve(Call.arg_size());
1212652168a9SFedor Sergeev   for (Value *I : Call.args()) {
1213652168a9SFedor Sergeev     Constant *C = dyn_cast<Constant>(I);
12147adc3a2bSChandler Carruth     if (!C)
1215652168a9SFedor Sergeev       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
12167adc3a2bSChandler Carruth     if (!C)
12177adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
12187adc3a2bSChandler Carruth 
12197adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
12207adc3a2bSChandler Carruth   }
1221652168a9SFedor Sergeev   if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
1222652168a9SFedor Sergeev     SimplifiedValues[&Call] = C;
12237adc3a2bSChandler Carruth     return true;
12247adc3a2bSChandler Carruth   }
12257adc3a2bSChandler Carruth 
12267adc3a2bSChandler Carruth   return false;
12277adc3a2bSChandler Carruth }
12287adc3a2bSChandler Carruth 
1229652168a9SFedor Sergeev bool CallAnalyzer::visitCallBase(CallBase &Call) {
1230652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
12317adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
12327adc3a2bSChandler Carruth     // This aborts the entire analysis.
12337adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
12347adc3a2bSChandler Carruth     return false;
12357adc3a2bSChandler Carruth   }
1236652168a9SFedor Sergeev   if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
12377adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
12387adc3a2bSChandler Carruth 
1239652168a9SFedor Sergeev   if (Function *F = Call.getCalledFunction()) {
12407adc3a2bSChandler Carruth     // When we have a concrete function, first try to simplify it directly.
1241652168a9SFedor Sergeev     if (simplifyCallSite(F, Call))
12427adc3a2bSChandler Carruth       return true;
12437adc3a2bSChandler Carruth 
12447adc3a2bSChandler Carruth     // Next check if it is an intrinsic we know about.
12457adc3a2bSChandler Carruth     // FIXME: Lift this into part of the InstVisitor.
1246652168a9SFedor Sergeev     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
12477adc3a2bSChandler Carruth       switch (II->getIntrinsicID()) {
12487adc3a2bSChandler Carruth       default:
1249652168a9SFedor Sergeev         if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II))
1250a4461515SHaicheng Wu           disableLoadElimination();
1251652168a9SFedor Sergeev         return Base::visitCallBase(Call);
12527adc3a2bSChandler Carruth 
12537dd8dbf4SPeter Collingbourne       case Intrinsic::load_relative:
12547dd8dbf4SPeter Collingbourne         // This is normally lowered to 4 LLVM instructions.
1255eeae45dcSFedor Sergeev         addCost(3 * InlineConstants::InstrCost);
12567dd8dbf4SPeter Collingbourne         return false;
12577dd8dbf4SPeter Collingbourne 
12587adc3a2bSChandler Carruth       case Intrinsic::memset:
12597adc3a2bSChandler Carruth       case Intrinsic::memcpy:
12607adc3a2bSChandler Carruth       case Intrinsic::memmove:
1261a4461515SHaicheng Wu         disableLoadElimination();
12627adc3a2bSChandler Carruth         // SROA can usually chew through these intrinsics, but they aren't free.
12637adc3a2bSChandler Carruth         return false;
12644296ea72SVitaly Buka       case Intrinsic::icall_branch_funnel:
12657adc3a2bSChandler Carruth       case Intrinsic::localescape:
12664296ea72SVitaly Buka         HasUninlineableIntrinsic = true;
12677adc3a2bSChandler Carruth         return false;
126880788d80SFlorian Hahn       case Intrinsic::vastart:
126977beee41SSameer AbuAsal         InitsVargArgs = true;
127080788d80SFlorian Hahn         return false;
12717adc3a2bSChandler Carruth       }
12727adc3a2bSChandler Carruth     }
12737adc3a2bSChandler Carruth 
1274652168a9SFedor Sergeev     if (F == Call.getFunction()) {
12757adc3a2bSChandler Carruth       // This flag will fully abort the analysis, so don't bother with anything
12767adc3a2bSChandler Carruth       // else.
12777adc3a2bSChandler Carruth       IsRecursiveCall = true;
12787adc3a2bSChandler Carruth       return false;
12797adc3a2bSChandler Carruth     }
12807adc3a2bSChandler Carruth 
12817adc3a2bSChandler Carruth     if (TTI.isLoweredToCall(F)) {
12827adc3a2bSChandler Carruth       // We account for the average 1 instruction per call argument setup
12837adc3a2bSChandler Carruth       // here.
1284eeae45dcSFedor Sergeev       addCost(Call.arg_size() * InlineConstants::InstrCost);
12857adc3a2bSChandler Carruth 
12867adc3a2bSChandler Carruth       // Everything other than inline ASM will also have a significant cost
12877adc3a2bSChandler Carruth       // merely from making the call.
1288652168a9SFedor Sergeev       if (!isa<InlineAsm>(Call.getCalledValue()))
1289eeae45dcSFedor Sergeev         addCost(InlineConstants::CallPenalty);
12907adc3a2bSChandler Carruth     }
12917adc3a2bSChandler Carruth 
1292652168a9SFedor Sergeev     if (!Call.onlyReadsMemory())
1293a4461515SHaicheng Wu       disableLoadElimination();
1294652168a9SFedor Sergeev     return Base::visitCallBase(Call);
12957adc3a2bSChandler Carruth   }
12967adc3a2bSChandler Carruth 
12977adc3a2bSChandler Carruth   // Otherwise we're in a very special case -- an indirect function call. See
12987adc3a2bSChandler Carruth   // if we can be particularly clever about this.
1299652168a9SFedor Sergeev   Value *Callee = Call.getCalledValue();
13007adc3a2bSChandler Carruth 
13017adc3a2bSChandler Carruth   // First, pay the price of the argument setup. We account for the average
13027adc3a2bSChandler Carruth   // 1 instruction per call argument setup here.
1303eeae45dcSFedor Sergeev   addCost(Call.arg_size() * InlineConstants::InstrCost);
13047adc3a2bSChandler Carruth 
13057adc3a2bSChandler Carruth   // Next, check if this happens to be an indirect function call to a known
13067adc3a2bSChandler Carruth   // function in this inline context. If not, we've done all we can.
13077adc3a2bSChandler Carruth   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
1308a4461515SHaicheng Wu   if (!F) {
1309652168a9SFedor Sergeev     if (!Call.onlyReadsMemory())
1310a4461515SHaicheng Wu       disableLoadElimination();
1311652168a9SFedor Sergeev     return Base::visitCallBase(Call);
1312a4461515SHaicheng Wu   }
13137adc3a2bSChandler Carruth 
13147adc3a2bSChandler Carruth   // If we have a constant that we are calling as a function, we can peer
13157adc3a2bSChandler Carruth   // through it and see the function target. This happens not infrequently
13167adc3a2bSChandler Carruth   // during devirtualization and so we want to give it a hefty bonus for
13177adc3a2bSChandler Carruth   // inlining, but cap that bonus in the event that inlining wouldn't pan
13187adc3a2bSChandler Carruth   // out. Pretend to inline the function, with a custom threshold.
13191c57cc2bSEaswaran Raman   auto IndirectCallParams = Params;
13201c57cc2bSEaswaran Raman   IndirectCallParams.DefaultThreshold = InlineConstants::IndirectCallThreshold;
1321652168a9SFedor Sergeev   CallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F, Call,
132212585b01SEaswaran Raman                   IndirectCallParams);
1323652168a9SFedor Sergeev   if (CA.analyzeCall(Call)) {
132402647f73SJordan Rupprecht     // We were able to inline the indirect call! Subtract the cost from the
132502647f73SJordan Rupprecht     // threshold to get the bonus we want to apply, but don't go below zero.
132602647f73SJordan Rupprecht     Cost -= std::max(0, CA.getThreshold() - CA.getCost());
13277adc3a2bSChandler Carruth   }
13287adc3a2bSChandler Carruth 
1329a4461515SHaicheng Wu   if (!F->onlyReadsMemory())
1330a4461515SHaicheng Wu     disableLoadElimination();
1331652168a9SFedor Sergeev   return Base::visitCallBase(Call);
13327adc3a2bSChandler Carruth }
13337adc3a2bSChandler Carruth 
13347adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
13357adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
13367adc3a2bSChandler Carruth   bool Free = !HasReturn;
13377adc3a2bSChandler Carruth   HasReturn = true;
13387adc3a2bSChandler Carruth   return Free;
13397adc3a2bSChandler Carruth }
13407adc3a2bSChandler Carruth 
13417adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
13427adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
13437adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
13447adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
13457adc3a2bSChandler Carruth   // which will fold away are also free.
13467adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
13477adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
13487adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
13497adc3a2bSChandler Carruth }
13507adc3a2bSChandler Carruth 
13513ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
13523ec848bcSHaicheng Wu   bool CheckSROA = SI.getType()->isPointerTy();
13533ec848bcSHaicheng Wu   Value *TrueVal = SI.getTrueValue();
13543ec848bcSHaicheng Wu   Value *FalseVal = SI.getFalseValue();
13553ec848bcSHaicheng Wu 
13563ec848bcSHaicheng Wu   Constant *TrueC = dyn_cast<Constant>(TrueVal);
13573ec848bcSHaicheng Wu   if (!TrueC)
13583ec848bcSHaicheng Wu     TrueC = SimplifiedValues.lookup(TrueVal);
13593ec848bcSHaicheng Wu   Constant *FalseC = dyn_cast<Constant>(FalseVal);
13603ec848bcSHaicheng Wu   if (!FalseC)
13613ec848bcSHaicheng Wu     FalseC = SimplifiedValues.lookup(FalseVal);
13623ec848bcSHaicheng Wu   Constant *CondC =
13633ec848bcSHaicheng Wu       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
13643ec848bcSHaicheng Wu 
13653ec848bcSHaicheng Wu   if (!CondC) {
13663ec848bcSHaicheng Wu     // Select C, X, X => X
13673ec848bcSHaicheng Wu     if (TrueC == FalseC && TrueC) {
13683ec848bcSHaicheng Wu       SimplifiedValues[&SI] = TrueC;
13693ec848bcSHaicheng Wu       return true;
13703ec848bcSHaicheng Wu     }
13713ec848bcSHaicheng Wu 
13723ec848bcSHaicheng Wu     if (!CheckSROA)
13733ec848bcSHaicheng Wu       return Base::visitSelectInst(SI);
13743ec848bcSHaicheng Wu 
13753ec848bcSHaicheng Wu     std::pair<Value *, APInt> TrueBaseAndOffset =
13763ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(TrueVal);
13773ec848bcSHaicheng Wu     std::pair<Value *, APInt> FalseBaseAndOffset =
13783ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(FalseVal);
13793ec848bcSHaicheng Wu     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
13803ec848bcSHaicheng Wu       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
13813ec848bcSHaicheng Wu 
13823ec848bcSHaicheng Wu       Value *SROAArg;
13833ec848bcSHaicheng Wu       DenseMap<Value *, int>::iterator CostIt;
13843ec848bcSHaicheng Wu       if (lookupSROAArgAndCost(TrueVal, SROAArg, CostIt))
13853ec848bcSHaicheng Wu         SROAArgValues[&SI] = SROAArg;
13863ec848bcSHaicheng Wu       return true;
13873ec848bcSHaicheng Wu     }
13883ec848bcSHaicheng Wu 
13893ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
13903ec848bcSHaicheng Wu   }
13913ec848bcSHaicheng Wu 
13923ec848bcSHaicheng Wu   // Select condition is a constant.
13933ec848bcSHaicheng Wu   Value *SelectedV = CondC->isAllOnesValue()
13943ec848bcSHaicheng Wu                          ? TrueVal
13953ec848bcSHaicheng Wu                          : (CondC->isNullValue()) ? FalseVal : nullptr;
13963ec848bcSHaicheng Wu   if (!SelectedV) {
13973ec848bcSHaicheng Wu     // Condition is a vector constant that is not all 1s or all 0s.  If all
13983ec848bcSHaicheng Wu     // operands are constants, ConstantExpr::getSelect() can handle the cases
13993ec848bcSHaicheng Wu     // such as select vectors.
14003ec848bcSHaicheng Wu     if (TrueC && FalseC) {
14013ec848bcSHaicheng Wu       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
14023ec848bcSHaicheng Wu         SimplifiedValues[&SI] = C;
14033ec848bcSHaicheng Wu         return true;
14043ec848bcSHaicheng Wu       }
14053ec848bcSHaicheng Wu     }
14063ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
14073ec848bcSHaicheng Wu   }
14083ec848bcSHaicheng Wu 
14093ec848bcSHaicheng Wu   // Condition is either all 1s or all 0s. SI can be simplified.
14103ec848bcSHaicheng Wu   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
14113ec848bcSHaicheng Wu     SimplifiedValues[&SI] = SelectedC;
14123ec848bcSHaicheng Wu     return true;
14133ec848bcSHaicheng Wu   }
14143ec848bcSHaicheng Wu 
14153ec848bcSHaicheng Wu   if (!CheckSROA)
14163ec848bcSHaicheng Wu     return true;
14173ec848bcSHaicheng Wu 
14183ec848bcSHaicheng Wu   std::pair<Value *, APInt> BaseAndOffset =
14193ec848bcSHaicheng Wu       ConstantOffsetPtrs.lookup(SelectedV);
14203ec848bcSHaicheng Wu   if (BaseAndOffset.first) {
14213ec848bcSHaicheng Wu     ConstantOffsetPtrs[&SI] = BaseAndOffset;
14223ec848bcSHaicheng Wu 
14233ec848bcSHaicheng Wu     Value *SROAArg;
14243ec848bcSHaicheng Wu     DenseMap<Value *, int>::iterator CostIt;
14253ec848bcSHaicheng Wu     if (lookupSROAArgAndCost(SelectedV, SROAArg, CostIt))
14263ec848bcSHaicheng Wu       SROAArgValues[&SI] = SROAArg;
14273ec848bcSHaicheng Wu   }
14283ec848bcSHaicheng Wu 
14293ec848bcSHaicheng Wu   return true;
14303ec848bcSHaicheng Wu }
14313ec848bcSHaicheng Wu 
14327adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
14337adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
14347adc3a2bSChandler Carruth   // branches.
14357adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
14367adc3a2bSChandler Carruth     return true;
14377adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
14387adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
14397adc3a2bSChandler Carruth       return true;
14407adc3a2bSChandler Carruth 
14417ad02eeeSEric Christopher   // Assume the most general case where the switch is lowered into
1442919f9e8dSJun Bum Lim   // either a jump table, bit test, or a balanced binary tree consisting of
1443919f9e8dSJun Bum Lim   // case clusters without merging adjacent clusters with the same
1444919f9e8dSJun Bum Lim   // destination. We do not consider the switches that are lowered with a mix
1445919f9e8dSJun Bum Lim   // of jump table/bit test/binary search tree. The cost of the switch is
1446919f9e8dSJun Bum Lim   // proportional to the size of the tree or the size of jump table range.
14472960d41eSJun Bum Lim   //
14482960d41eSJun Bum Lim   // NB: We convert large switches which are just used to initialize large phi
14492960d41eSJun Bum Lim   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
14502960d41eSJun Bum Lim   // inlining those. It will prevent inlining in cases where the optimization
14512960d41eSJun Bum Lim   // does not (yet) fire.
1452919f9e8dSJun Bum Lim 
1453506cfb7aSJun Bum Lim   // Maximum valid cost increased in this function.
1454506cfb7aSJun Bum Lim   int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
1455506cfb7aSJun Bum Lim 
1456919f9e8dSJun Bum Lim   // Exit early for a large switch, assuming one case needs at least one
1457919f9e8dSJun Bum Lim   // instruction.
1458919f9e8dSJun Bum Lim   // FIXME: This is not true for a bit test, but ignore such case for now to
1459919f9e8dSJun Bum Lim   // save compile-time.
1460919f9e8dSJun Bum Lim   int64_t CostLowerBound =
1461506cfb7aSJun Bum Lim       std::min((int64_t)CostUpperBound,
1462919f9e8dSJun Bum Lim                (int64_t)SI.getNumCases() * InlineConstants::InstrCost + Cost);
1463919f9e8dSJun Bum Lim 
14640812c5beSHaicheng Wu   if (CostLowerBound > Threshold && !ComputeFullInlineCost) {
1465eeae45dcSFedor Sergeev     addCost((int64_t)SI.getNumCases() * InlineConstants::InstrCost);
1466919f9e8dSJun Bum Lim     return false;
1467919f9e8dSJun Bum Lim   }
1468919f9e8dSJun Bum Lim 
1469919f9e8dSJun Bum Lim   unsigned JumpTableSize = 0;
1470919f9e8dSJun Bum Lim   unsigned NumCaseCluster =
1471919f9e8dSJun Bum Lim       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize);
1472919f9e8dSJun Bum Lim 
1473919f9e8dSJun Bum Lim   // If suitable for a jump table, consider the cost for the table size and
1474919f9e8dSJun Bum Lim   // branch to destination.
1475919f9e8dSJun Bum Lim   if (JumpTableSize) {
1476919f9e8dSJun Bum Lim     int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
1477919f9e8dSJun Bum Lim                      4 * InlineConstants::InstrCost;
1478506cfb7aSJun Bum Lim 
1479eeae45dcSFedor Sergeev     addCost(JTCost, (int64_t)CostUpperBound);
1480919f9e8dSJun Bum Lim     return false;
1481919f9e8dSJun Bum Lim   }
1482919f9e8dSJun Bum Lim 
1483919f9e8dSJun Bum Lim   // Considering forming a binary search, we should find the number of nodes
1484919f9e8dSJun Bum Lim   // which is same as the number of comparisons when lowered. For a given
1485919f9e8dSJun Bum Lim   // number of clusters, n, we can define a recursive function, f(n), to find
1486919f9e8dSJun Bum Lim   // the number of nodes in the tree. The recursion is :
1487919f9e8dSJun Bum Lim   // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
1488919f9e8dSJun Bum Lim   // and f(n) = n, when n <= 3.
1489919f9e8dSJun Bum Lim   // This will lead a binary tree where the leaf should be either f(2) or f(3)
1490919f9e8dSJun Bum Lim   // when n > 3.  So, the number of comparisons from leaves should be n, while
1491919f9e8dSJun Bum Lim   // the number of non-leaf should be :
1492919f9e8dSJun Bum Lim   //   2^(log2(n) - 1) - 1
1493919f9e8dSJun Bum Lim   //   = 2^log2(n) * 2^-1 - 1
1494919f9e8dSJun Bum Lim   //   = n / 2 - 1.
1495919f9e8dSJun Bum Lim   // Considering comparisons from leaf and non-leaf nodes, we can estimate the
1496919f9e8dSJun Bum Lim   // number of comparisons in a simple closed form :
1497919f9e8dSJun Bum Lim   //   n + n / 2 - 1 = n * 3 / 2 - 1
1498919f9e8dSJun Bum Lim   if (NumCaseCluster <= 3) {
1499919f9e8dSJun Bum Lim     // Suppose a comparison includes one compare and one conditional branch.
1500eeae45dcSFedor Sergeev     addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
1501919f9e8dSJun Bum Lim     return false;
1502919f9e8dSJun Bum Lim   }
1503506cfb7aSJun Bum Lim 
1504506cfb7aSJun Bum Lim   int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1;
1505506cfb7aSJun Bum Lim   int64_t SwitchCost =
1506919f9e8dSJun Bum Lim       ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
1507506cfb7aSJun Bum Lim 
1508eeae45dcSFedor Sergeev   addCost(SwitchCost, (int64_t)CostUpperBound);
1509919f9e8dSJun Bum Lim   return false;
1510919f9e8dSJun Bum Lim }
1511919f9e8dSJun Bum Lim 
15127adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
15137adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
15147adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
15157adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
15167adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
15177adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
15187adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
15197adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
15207adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
15217adc3a2bSChandler Carruth   HasIndirectBr = true;
15227adc3a2bSChandler Carruth   return false;
15237adc3a2bSChandler Carruth }
15247adc3a2bSChandler Carruth 
15257adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
15267adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
15277adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
15287adc3a2bSChandler Carruth   return false;
15297adc3a2bSChandler Carruth }
15307adc3a2bSChandler Carruth 
15317adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
15327adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
15337adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
15347adc3a2bSChandler Carruth   return false;
15357adc3a2bSChandler Carruth }
15367adc3a2bSChandler Carruth 
15377adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
15387adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
15398220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
15407adc3a2bSChandler Carruth   return false;
15417adc3a2bSChandler Carruth }
15427adc3a2bSChandler Carruth 
15437adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
15447adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
15457adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
15467adc3a2bSChandler Carruth   // code size.
15477adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
15487adc3a2bSChandler Carruth }
15497adc3a2bSChandler Carruth 
15507adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
15517adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
15527adc3a2bSChandler Carruth   // handled by SROA, etc.
15537adc3a2bSChandler Carruth   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
15547adc3a2bSChandler Carruth     return true;
15557adc3a2bSChandler Carruth 
15567adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
15577adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
15587adc3a2bSChandler Carruth   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
15597adc3a2bSChandler Carruth     disableSROA(*OI);
15607adc3a2bSChandler Carruth 
15617adc3a2bSChandler Carruth   return false;
15627adc3a2bSChandler Carruth }
15637adc3a2bSChandler Carruth 
15645f8f34e4SAdrian Prantl /// Analyze a basic block for its contribution to the inline cost.
15657adc3a2bSChandler Carruth ///
15667adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
15677adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
15687adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
15697adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
15707adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
1571c0aa4b75SDavid Bolvansky InlineResult
1572c0aa4b75SDavid Bolvansky CallAnalyzer::analyzeBlock(BasicBlock *BB,
15737adc3a2bSChandler Carruth                            SmallPtrSetImpl<const Value *> &EphValues) {
15747adc3a2bSChandler Carruth   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
15757adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
15767adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
15777adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
15787adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
15797adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
15807adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
15817adc3a2bSChandler Carruth     // hack around it here.
15827adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
15837adc3a2bSChandler Carruth       continue;
15847adc3a2bSChandler Carruth 
15857adc3a2bSChandler Carruth     // Skip ephemeral values.
15865a82c916SDuncan P. N. Exon Smith     if (EphValues.count(&*I))
15877adc3a2bSChandler Carruth       continue;
15887adc3a2bSChandler Carruth 
15897adc3a2bSChandler Carruth     ++NumInstructions;
15907adc3a2bSChandler Carruth     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
15917adc3a2bSChandler Carruth       ++NumVectorInstructions;
15927adc3a2bSChandler Carruth 
15937adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
15947adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
15957adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
15967adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
15977adc3a2bSChandler Carruth     // cost should count against inlining.
15985a82c916SDuncan P. N. Exon Smith     if (Base::visit(&*I))
15997adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
16007adc3a2bSChandler Carruth     else
1601eeae45dcSFedor Sergeev       addCost(InlineConstants::InstrCost);
16027adc3a2bSChandler Carruth 
16030812c5beSHaicheng Wu     using namespace ore;
16047adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
1605c0aa4b75SDavid Bolvansky     InlineResult IR;
1606c0aa4b75SDavid Bolvansky     if (IsRecursiveCall)
1607c0aa4b75SDavid Bolvansky       IR = "recursive";
1608c0aa4b75SDavid Bolvansky     else if (ExposesReturnsTwice)
1609c0aa4b75SDavid Bolvansky       IR = "exposes returns twice";
1610c0aa4b75SDavid Bolvansky     else if (HasDynamicAlloca)
1611c0aa4b75SDavid Bolvansky       IR = "dynamic alloca";
1612c0aa4b75SDavid Bolvansky     else if (HasIndirectBr)
1613c0aa4b75SDavid Bolvansky       IR = "indirect branch";
1614c0aa4b75SDavid Bolvansky     else if (HasUninlineableIntrinsic)
1615c0aa4b75SDavid Bolvansky       IR = "uninlinable intrinsic";
161677beee41SSameer AbuAsal     else if (InitsVargArgs)
1617c0aa4b75SDavid Bolvansky       IR = "varargs";
1618c0aa4b75SDavid Bolvansky     if (!IR) {
16190812c5beSHaicheng Wu       if (ORE)
16209590658fSVivek Pandya         ORE->emit([&]() {
16219590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
1622652168a9SFedor Sergeev                                           &CandidateCall)
1623c0aa4b75SDavid Bolvansky                  << NV("Callee", &F) << " has uninlinable pattern ("
1624c0aa4b75SDavid Bolvansky                  << NV("InlineResult", IR.message)
1625c0aa4b75SDavid Bolvansky                  << ") and cost is not fully computed";
16269590658fSVivek Pandya         });
1627c0aa4b75SDavid Bolvansky       return IR;
16280812c5beSHaicheng Wu     }
16297adc3a2bSChandler Carruth 
16307adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
16317adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
16327adc3a2bSChandler Carruth     // the caller stack usage dramatically.
16337adc3a2bSChandler Carruth     if (IsCallerRecursive &&
16340812c5beSHaicheng Wu         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) {
1635c0aa4b75SDavid Bolvansky       InlineResult IR = "recursive and allocates too much stack space";
16360812c5beSHaicheng Wu       if (ORE)
16379590658fSVivek Pandya         ORE->emit([&]() {
16389590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
1639652168a9SFedor Sergeev                                           &CandidateCall)
1640c0aa4b75SDavid Bolvansky                  << NV("Callee", &F) << " is " << NV("InlineResult", IR.message)
1641c0aa4b75SDavid Bolvansky                  << ". Cost is not fully computed";
16429590658fSVivek Pandya         });
1643c0aa4b75SDavid Bolvansky       return IR;
16440812c5beSHaicheng Wu     }
16457adc3a2bSChandler Carruth 
1646eeae45dcSFedor Sergeev     // Check if we've passed the maximum possible threshold so we don't spin in
16477adc3a2bSChandler Carruth     // huge basic blocks that will never inline.
164861995364SHaicheng Wu     if (Cost >= Threshold && !ComputeFullInlineCost)
16497adc3a2bSChandler Carruth       return false;
16507adc3a2bSChandler Carruth   }
16517adc3a2bSChandler Carruth 
16527adc3a2bSChandler Carruth   return true;
16537adc3a2bSChandler Carruth }
16547adc3a2bSChandler Carruth 
16555f8f34e4SAdrian Prantl /// Compute the base pointer and cumulative constant offsets for V.
16567adc3a2bSChandler Carruth ///
16577adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
16587adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
16597adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
16607adc3a2bSChandler Carruth /// no constant offsets applied.
16617adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
16627adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
16637adc3a2bSChandler Carruth     return nullptr;
16647adc3a2bSChandler Carruth 
166577f32994SBjorn Pettersson   unsigned AS = V->getType()->getPointerAddressSpace();
1666945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
16677adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
16687adc3a2bSChandler Carruth 
16697adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
16707adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
16717adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
16727adc3a2bSChandler Carruth   Visited.insert(V);
16737adc3a2bSChandler Carruth   do {
16747adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
16757adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
16767adc3a2bSChandler Carruth         return nullptr;
16777adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
16787adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
16797adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
16807adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
16815ce32728SSanjoy Das       if (GA->isInterposable())
16827adc3a2bSChandler Carruth         break;
16837adc3a2bSChandler Carruth       V = GA->getAliasee();
16847adc3a2bSChandler Carruth     } else {
16857adc3a2bSChandler Carruth       break;
16867adc3a2bSChandler Carruth     }
16877adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
16887adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
16897adc3a2bSChandler Carruth 
169077f32994SBjorn Pettersson   Type *IntPtrTy = DL.getIntPtrType(V->getContext(), AS);
16917adc3a2bSChandler Carruth   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
16927adc3a2bSChandler Carruth }
16937adc3a2bSChandler Carruth 
16945f8f34e4SAdrian Prantl /// Find dead blocks due to deleted CFG edges during inlining.
16953739e14aSHaicheng Wu ///
16963739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p
16973739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have
16983739e14aSHaicheng Wu /// no live incoming CFG edges.  If one block is found to be dead, we can
16993739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead
17003739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not.
17013739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
17023739e14aSHaicheng Wu   auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
170302a2bb2fSHiroshi Inoue     // A CFG edge is dead if the predecessor is dead or the predecessor has a
17043739e14aSHaicheng Wu     // known successor which is not the one under exam.
17053739e14aSHaicheng Wu     return (DeadBlocks.count(Pred) ||
17063739e14aSHaicheng Wu             (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
17073739e14aSHaicheng Wu   };
17083739e14aSHaicheng Wu 
17093739e14aSHaicheng Wu   auto IsNewlyDead = [&](BasicBlock *BB) {
17103739e14aSHaicheng Wu     // If all the edges to a block are dead, the block is also dead.
17113739e14aSHaicheng Wu     return (!DeadBlocks.count(BB) &&
17123739e14aSHaicheng Wu             llvm::all_of(predecessors(BB),
17133739e14aSHaicheng Wu                          [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
17143739e14aSHaicheng Wu   };
17153739e14aSHaicheng Wu 
17163739e14aSHaicheng Wu   for (BasicBlock *Succ : successors(CurrBB)) {
17173739e14aSHaicheng Wu     if (Succ == NextBB || !IsNewlyDead(Succ))
17183739e14aSHaicheng Wu       continue;
17193739e14aSHaicheng Wu     SmallVector<BasicBlock *, 4> NewDead;
17203739e14aSHaicheng Wu     NewDead.push_back(Succ);
17213739e14aSHaicheng Wu     while (!NewDead.empty()) {
17223739e14aSHaicheng Wu       BasicBlock *Dead = NewDead.pop_back_val();
17233739e14aSHaicheng Wu       if (DeadBlocks.insert(Dead))
17243739e14aSHaicheng Wu         // Continue growing the dead block lists.
17253739e14aSHaicheng Wu         for (BasicBlock *S : successors(Dead))
17263739e14aSHaicheng Wu           if (IsNewlyDead(S))
17273739e14aSHaicheng Wu             NewDead.push_back(S);
17283739e14aSHaicheng Wu     }
17293739e14aSHaicheng Wu   }
17303739e14aSHaicheng Wu }
17313739e14aSHaicheng Wu 
17325f8f34e4SAdrian Prantl /// Analyze a call site for potential inlining.
17337adc3a2bSChandler Carruth ///
17347adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
17357adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
17367adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
17377adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
17387adc3a2bSChandler Carruth /// some artifact of the routine.
1739652168a9SFedor Sergeev InlineResult CallAnalyzer::analyzeCall(CallBase &Call) {
17407adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
17417adc3a2bSChandler Carruth 
17427adc3a2bSChandler Carruth   // Perform some tweaks to the cost and threshold based on the direct
17437adc3a2bSChandler Carruth   // callsite information.
17447adc3a2bSChandler Carruth 
17457adc3a2bSChandler Carruth   // We want to more aggressively inline vector-dense kernels, so up the
17467adc3a2bSChandler Carruth   // threshold, and we'll lower it if the % of vector instructions gets too
17477adc3a2bSChandler Carruth   // low. Note that these bonuses are some what arbitrary and evolved over time
17487adc3a2bSChandler Carruth   // by accident as much as because they are principled bonuses.
17497adc3a2bSChandler Carruth   //
17507adc3a2bSChandler Carruth   // FIXME: It would be nice to remove all such bonuses. At least it would be
17517adc3a2bSChandler Carruth   // nice to base the bonus values on something more scientific.
17527adc3a2bSChandler Carruth   assert(NumInstructions == 0);
17537adc3a2bSChandler Carruth   assert(NumVectorInstructions == 0);
1754f4bb2f0dSEaswaran Raman 
1755f4bb2f0dSEaswaran Raman   // Update the threshold based on callsite properties
1756652168a9SFedor Sergeev   updateThreshold(Call, F);
1757f4bb2f0dSEaswaran Raman 
1758ed279752SEaswaran Raman   // While Threshold depends on commandline options that can take negative
1759ed279752SEaswaran Raman   // values, we want to enforce the invariant that the computed threshold and
1760ed279752SEaswaran Raman   // bonuses are non-negative.
1761ed279752SEaswaran Raman   assert(Threshold >= 0);
1762ed279752SEaswaran Raman   assert(SingleBBBonus >= 0);
1763ed279752SEaswaran Raman   assert(VectorBonus >= 0);
1764ed279752SEaswaran Raman 
17657adc3a2bSChandler Carruth   // Speculatively apply all possible bonuses to Threshold. If cost exceeds
17667adc3a2bSChandler Carruth   // this Threshold any time, and cost cannot decrease, we can stop processing
17677adc3a2bSChandler Carruth   // the rest of the function body.
176851b809bfSEaswaran Raman   Threshold += (SingleBBBonus + VectorBonus);
17697adc3a2bSChandler Carruth 
1770351d9b01SXinliang David Li   // Give out bonuses for the callsite, as the instructions setting them up
1771351d9b01SXinliang David Li   // will be gone after inlining.
1772eeae45dcSFedor Sergeev   addCost(-getCallsiteCost(Call, DL));
17737adc3a2bSChandler Carruth 
17747adc3a2bSChandler Carruth   // If this function uses the coldcc calling convention, prefer not to inline
17757adc3a2bSChandler Carruth   // it.
17767adc3a2bSChandler Carruth   if (F.getCallingConv() == CallingConv::Cold)
17777adc3a2bSChandler Carruth     Cost += InlineConstants::ColdccPenalty;
17787adc3a2bSChandler Carruth 
17797adc3a2bSChandler Carruth   // Check if we're done. This can happen due to bonuses and penalties.
178061995364SHaicheng Wu   if (Cost >= Threshold && !ComputeFullInlineCost)
1781c0aa4b75SDavid Bolvansky     return "high cost";
17827adc3a2bSChandler Carruth 
17837adc3a2bSChandler Carruth   if (F.empty())
17847adc3a2bSChandler Carruth     return true;
17857adc3a2bSChandler Carruth 
1786652168a9SFedor Sergeev   Function *Caller = Call.getFunction();
17877adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
17887adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
1789652168a9SFedor Sergeev     CallBase *Call = dyn_cast<CallBase>(U);
1790652168a9SFedor Sergeev     if (Call && Call->getFunction() == Caller) {
17917adc3a2bSChandler Carruth       IsCallerRecursive = true;
17927adc3a2bSChandler Carruth       break;
17937adc3a2bSChandler Carruth     }
17947adc3a2bSChandler Carruth   }
17957adc3a2bSChandler Carruth 
17967adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
17977adc3a2bSChandler Carruth   // arguments with known important simplifications.
1798652168a9SFedor Sergeev   auto CAI = Call.arg_begin();
17997adc3a2bSChandler Carruth   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
18007adc3a2bSChandler Carruth        FAI != FAE; ++FAI, ++CAI) {
1801652168a9SFedor Sergeev     assert(CAI != Call.arg_end());
18027adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
18035a82c916SDuncan P. N. Exon Smith       SimplifiedValues[&*FAI] = C;
18047adc3a2bSChandler Carruth 
18057adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
18067adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
18075a82c916SDuncan P. N. Exon Smith       ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
18087adc3a2bSChandler Carruth 
18097adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
18107adc3a2bSChandler Carruth       if (isa<AllocaInst>(PtrArg)) {
18115a82c916SDuncan P. N. Exon Smith         SROAArgValues[&*FAI] = PtrArg;
18127adc3a2bSChandler Carruth         SROAArgCosts[PtrArg] = 0;
18137adc3a2bSChandler Carruth       }
18147adc3a2bSChandler Carruth     }
18157adc3a2bSChandler Carruth   }
18167adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
18177adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
18187adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
18197adc3a2bSChandler Carruth 
18207adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
18217adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
18227adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
18237adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
1824aec2fa35SDaniel Jasper   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
18257adc3a2bSChandler Carruth 
18267adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
18277adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
18287adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
18297adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
18307adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
18317adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
18327adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
18337adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1834567556aaSChad Rosier                     SmallPtrSet<BasicBlock *, 16>>
1835567556aaSChad Rosier       BBSetVector;
18367adc3a2bSChandler Carruth   BBSetVector BBWorklist;
18377adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
183851b809bfSEaswaran Raman   bool SingleBB = true;
18397adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
18407adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
18417adc3a2bSChandler Carruth     // Bail out the moment we cross the threshold. This means we'll under-count
18427adc3a2bSChandler Carruth     // the cost, but only when undercounting doesn't matter.
184361995364SHaicheng Wu     if (Cost >= Threshold && !ComputeFullInlineCost)
18447adc3a2bSChandler Carruth       break;
18457adc3a2bSChandler Carruth 
18467adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
18477adc3a2bSChandler Carruth     if (BB->empty())
18487adc3a2bSChandler Carruth       continue;
18497adc3a2bSChandler Carruth 
1850639b29b1SNick Desaulniers     // Disallow inlining a blockaddress with uses other than strictly callbr.
1851639b29b1SNick Desaulniers     // A blockaddress only has defined behavior for an indirect branch in the
1852639b29b1SNick Desaulniers     // same function, and we do not currently support inlining indirect
1853639b29b1SNick Desaulniers     // branches.  But, the inliner may not see an indirect branch that ends up
1854639b29b1SNick Desaulniers     // being dead code at a particular call site. If the blockaddress escapes
1855639b29b1SNick Desaulniers     // the function, e.g., via a global variable, inlining may lead to an
1856639b29b1SNick Desaulniers     // invalid cross-function reference.
1857639b29b1SNick Desaulniers     // FIXME: pr/39560: continue relaxing this overt restriction.
18586a84cd3bSNick Desaulniers     if (BB->hasAddressTaken())
1859639b29b1SNick Desaulniers       for (User *U : BlockAddress::get(&*BB)->users())
1860639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
1861639b29b1SNick Desaulniers           return "blockaddress used outside of callbr";
18627adc3a2bSChandler Carruth 
18637adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
18647adc3a2bSChandler Carruth     // returns false, and we can bail on out.
1865c0aa4b75SDavid Bolvansky     InlineResult IR = analyzeBlock(BB, EphValues);
1866c0aa4b75SDavid Bolvansky     if (!IR)
1867c0aa4b75SDavid Bolvansky       return IR;
18687adc3a2bSChandler Carruth 
1869edb12a83SChandler Carruth     Instruction *TI = BB->getTerminator();
18707adc3a2bSChandler Carruth 
18717adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
18727adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
18737adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
18747adc3a2bSChandler Carruth       if (BI->isConditional()) {
18757adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
1876567556aaSChad Rosier         if (ConstantInt *SimpleCond =
1877567556aaSChad Rosier                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
18783739e14aSHaicheng Wu           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
18793739e14aSHaicheng Wu           BBWorklist.insert(NextBB);
18803739e14aSHaicheng Wu           KnownSuccessors[BB] = NextBB;
18813739e14aSHaicheng Wu           findDeadBlocks(BB, NextBB);
18827adc3a2bSChandler Carruth           continue;
18837adc3a2bSChandler Carruth         }
18847adc3a2bSChandler Carruth       }
18857adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
18867adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
1887567556aaSChad Rosier       if (ConstantInt *SimpleCond =
1888567556aaSChad Rosier               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
18893739e14aSHaicheng Wu         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
18903739e14aSHaicheng Wu         BBWorklist.insert(NextBB);
18913739e14aSHaicheng Wu         KnownSuccessors[BB] = NextBB;
18923739e14aSHaicheng Wu         findDeadBlocks(BB, NextBB);
18937adc3a2bSChandler Carruth         continue;
18947adc3a2bSChandler Carruth       }
18957adc3a2bSChandler Carruth     }
18967adc3a2bSChandler Carruth 
18977adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
18987adc3a2bSChandler Carruth     // them.
18997adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
19007adc3a2bSChandler Carruth          ++TIdx)
19017adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
19027adc3a2bSChandler Carruth 
19037adc3a2bSChandler Carruth     // If we had any successors at this point, than post-inlining is likely to
19047adc3a2bSChandler Carruth     // have them as well. Note that we assume any basic blocks which existed
19057adc3a2bSChandler Carruth     // due to branches or switches which folded above will also fold after
19067adc3a2bSChandler Carruth     // inlining.
19077adc3a2bSChandler Carruth     if (SingleBB && TI->getNumSuccessors() > 1) {
19087adc3a2bSChandler Carruth       // Take off the bonus we applied to the threshold.
19097adc3a2bSChandler Carruth       Threshold -= SingleBBBonus;
19107adc3a2bSChandler Carruth       SingleBB = false;
19117adc3a2bSChandler Carruth     }
19127adc3a2bSChandler Carruth   }
19137adc3a2bSChandler Carruth 
191451b809bfSEaswaran Raman   bool OnlyOneCallAndLocalLinkage =
1915652168a9SFedor Sergeev       F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction();
19167adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
19177adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
19187adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
19197adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1920c0aa4b75SDavid Bolvansky     return "noduplicate";
19217adc3a2bSChandler Carruth 
1922ba9f245bSDavid Green   // Loops generally act a lot like calls in that they act like barriers to
1923ba9f245bSDavid Green   // movement, require a certain amount of setup, etc. So when optimising for
1924ba9f245bSDavid Green   // size, we penalise any call sites that perform loops. We do this after all
1925ba9f245bSDavid Green   // other costs here, so will likely only be dealing with relatively small
1926ba9f245bSDavid Green   // functions (and hence DT and LI will hopefully be cheap).
192785bd3978SEvandro Menezes   if (Caller->hasMinSize()) {
1928ba9f245bSDavid Green     DominatorTree DT(F);
1929ba9f245bSDavid Green     LoopInfo LI(DT);
1930ba9f245bSDavid Green     int NumLoops = 0;
1931ba9f245bSDavid Green     for (Loop *L : LI) {
1932ba9f245bSDavid Green       // Ignore loops that will not be executed
1933ba9f245bSDavid Green       if (DeadBlocks.count(L->getHeader()))
1934ba9f245bSDavid Green         continue;
1935ba9f245bSDavid Green       NumLoops++;
1936ba9f245bSDavid Green     }
1937eeae45dcSFedor Sergeev     addCost(NumLoops * InlineConstants::CallPenalty);
1938ba9f245bSDavid Green   }
1939ba9f245bSDavid Green 
19407adc3a2bSChandler Carruth   // We applied the maximum possible vector bonus at the beginning. Now,
19417adc3a2bSChandler Carruth   // subtract the excess bonus, if any, from the Threshold before
19427adc3a2bSChandler Carruth   // comparing against Cost.
19437adc3a2bSChandler Carruth   if (NumVectorInstructions <= NumInstructions / 10)
194451b809bfSEaswaran Raman     Threshold -= VectorBonus;
19457adc3a2bSChandler Carruth   else if (NumVectorInstructions <= NumInstructions / 2)
194651b809bfSEaswaran Raman     Threshold -= VectorBonus/2;
19477adc3a2bSChandler Carruth 
194800ab73dcSHans Wennborg   return Cost < std::max(1, Threshold);
19497adc3a2bSChandler Carruth }
19507adc3a2bSChandler Carruth 
1951615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
19525f8f34e4SAdrian Prantl /// Dump stats about this call's analysis.
1953eb2a2546SYaron Keren LLVM_DUMP_METHOD void CallAnalyzer::dump() {
19547adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
19557adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
19567adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
19577adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
19587adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
19597adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
19607adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
19617adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
19627adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
19637adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
1964a4461515SHaicheng Wu   DEBUG_PRINT_STAT(LoadEliminationCost);
19657adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
19667adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
19677adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
19687adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
19697adc3a2bSChandler Carruth }
19707adc3a2bSChandler Carruth #endif
19717adc3a2bSChandler Carruth 
19725f8f34e4SAdrian Prantl /// Test that there are no attribute conflicts between Caller and Callee
19737adc3a2bSChandler Carruth ///        that prevent inlining.
19747adc3a2bSChandler Carruth static bool functionsHaveCompatibleAttributes(Function *Caller,
19757adc3a2bSChandler Carruth                                               Function *Callee,
19767adc3a2bSChandler Carruth                                               TargetTransformInfo &TTI) {
19777adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
19781cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
19797adc3a2bSChandler Carruth }
19807adc3a2bSChandler Carruth 
1981652168a9SFedor Sergeev int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) {
1982351d9b01SXinliang David Li   int Cost = 0;
1983652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
1984652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
1985351d9b01SXinliang David Li       // We approximate the number of loads and stores needed by dividing the
1986351d9b01SXinliang David Li       // size of the byval type by the target's pointer size.
1987652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
1988351d9b01SXinliang David Li       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
198977f32994SBjorn Pettersson       unsigned AS = PTy->getAddressSpace();
199077f32994SBjorn Pettersson       unsigned PointerSize = DL.getPointerSizeInBits(AS);
1991351d9b01SXinliang David Li       // Ceiling division.
1992351d9b01SXinliang David Li       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
1993351d9b01SXinliang David Li 
1994351d9b01SXinliang David Li       // If it generates more than 8 stores it is likely to be expanded as an
1995351d9b01SXinliang David Li       // inline memcpy so we take that as an upper bound. Otherwise we assume
1996351d9b01SXinliang David Li       // one load and one store per word copied.
1997351d9b01SXinliang David Li       // FIXME: The maxStoresPerMemcpy setting from the target should be used
1998351d9b01SXinliang David Li       // here instead of a magic number of 8, but it's not available via
1999351d9b01SXinliang David Li       // DataLayout.
2000351d9b01SXinliang David Li       NumStores = std::min(NumStores, 8U);
2001351d9b01SXinliang David Li 
2002351d9b01SXinliang David Li       Cost += 2 * NumStores * InlineConstants::InstrCost;
2003351d9b01SXinliang David Li     } else {
2004351d9b01SXinliang David Li       // For non-byval arguments subtract off one instruction per call
2005351d9b01SXinliang David Li       // argument.
2006351d9b01SXinliang David Li       Cost += InlineConstants::InstrCost;
2007351d9b01SXinliang David Li     }
2008351d9b01SXinliang David Li   }
2009351d9b01SXinliang David Li   // The call instruction also disappears after inlining.
2010351d9b01SXinliang David Li   Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty;
2011351d9b01SXinliang David Li   return Cost;
2012351d9b01SXinliang David Li }
2013351d9b01SXinliang David Li 
2014ab6a6837SSean Silva InlineCost llvm::getInlineCost(
2015652168a9SFedor Sergeev     CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
2016aec2fa35SDaniel Jasper     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
201712585b01SEaswaran Raman     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
20180812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2019652168a9SFedor Sergeev   return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
20200812c5beSHaicheng Wu                        GetAssumptionCache, GetBFI, PSI, ORE);
2021b9f7120eSEaswaran Raman }
2022b9f7120eSEaswaran Raman 
2023ab6a6837SSean Silva InlineCost llvm::getInlineCost(
2024652168a9SFedor Sergeev     CallBase &Call, Function *Callee, const InlineParams &Params,
2025aec2fa35SDaniel Jasper     TargetTransformInfo &CalleeTTI,
2026aec2fa35SDaniel Jasper     std::function<AssumptionCache &(Function &)> &GetAssumptionCache,
202712585b01SEaswaran Raman     Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI,
20280812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2029f4bb2f0dSEaswaran Raman 
20307adc3a2bSChandler Carruth   // Cannot inline indirect calls.
20317adc3a2bSChandler Carruth   if (!Callee)
2032c0aa4b75SDavid Bolvansky     return llvm::InlineCost::getNever("indirect call");
20337adc3a2bSChandler Carruth 
20343851496eSBjorn Pettersson   // Never inline calls with byval arguments that does not have the alloca
20353851496eSBjorn Pettersson   // address space. Since byval arguments can be replaced with a copy to an
20363851496eSBjorn Pettersson   // alloca, the inlined code would need to be adjusted to handle that the
20373851496eSBjorn Pettersson   // argument is in the alloca address space (so it is a little bit complicated
20383851496eSBjorn Pettersson   // to solve).
20393851496eSBjorn Pettersson   unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace();
2040652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I)
2041652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2042652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
20433851496eSBjorn Pettersson       if (PTy->getAddressSpace() != AllocaAS)
2044c0aa4b75SDavid Bolvansky         return llvm::InlineCost::getNever("byval arguments without alloca"
2045c0aa4b75SDavid Bolvansky                                           " address space");
20463851496eSBjorn Pettersson     }
20473851496eSBjorn Pettersson 
20487adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
20497adc3a2bSChandler Carruth   // whenever possible.
2050652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::AlwaysInline)) {
205115b17d0aSYevgeny Rouban     auto IsViable = isInlineViable(*Callee);
205215b17d0aSYevgeny Rouban     if (IsViable)
2053c0aa4b75SDavid Bolvansky       return llvm::InlineCost::getAlways("always inline attribute");
205415b17d0aSYevgeny Rouban     return llvm::InlineCost::getNever(IsViable.message);
20557adc3a2bSChandler Carruth   }
20567adc3a2bSChandler Carruth 
20577adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
20587adc3a2bSChandler Carruth   // always-inline attribute).
2059652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
20605ce28f4fSChad Rosier   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI))
2061c0aa4b75SDavid Bolvansky     return llvm::InlineCost::getNever("conflicting attributes");
20627adc3a2bSChandler Carruth 
20637adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
206485bd3978SEvandro Menezes   if (Caller->hasOptNone())
2065c0aa4b75SDavid Bolvansky     return llvm::InlineCost::getNever("optnone attribute");
20667adc3a2bSChandler Carruth 
206777eeac3dSManoj Gupta   // Don't inline a function that treats null pointer as valid into a caller
206877eeac3dSManoj Gupta   // that does not have this attribute.
206977eeac3dSManoj Gupta   if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined())
2070c0aa4b75SDavid Bolvansky     return llvm::InlineCost::getNever("nullptr definitions incompatible");
207177eeac3dSManoj Gupta 
2072c0aa4b75SDavid Bolvansky   // Don't inline functions which can be interposed at link-time.
2073c0aa4b75SDavid Bolvansky   if (Callee->isInterposable())
2074c0aa4b75SDavid Bolvansky     return llvm::InlineCost::getNever("interposable");
2075c0aa4b75SDavid Bolvansky 
2076c0aa4b75SDavid Bolvansky   // Don't inline functions marked noinline.
2077c0aa4b75SDavid Bolvansky   if (Callee->hasFnAttribute(Attribute::NoInline))
2078c0aa4b75SDavid Bolvansky     return llvm::InlineCost::getNever("noinline function attribute");
2079c0aa4b75SDavid Bolvansky 
2080c0aa4b75SDavid Bolvansky   // Don't inline call sites marked noinline.
2081652168a9SFedor Sergeev   if (Call.isNoInline())
2082c0aa4b75SDavid Bolvansky     return llvm::InlineCost::getNever("noinline call site attribute");
20837adc3a2bSChandler Carruth 
2084d34e60caSNicola Zaghen   LLVM_DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
20854eb18742SChad Rosier                           << "... (caller:" << Caller->getName() << ")\n");
20867adc3a2bSChandler Carruth 
2087652168a9SFedor Sergeev   CallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE, *Callee,
2088652168a9SFedor Sergeev                   Call, Params);
2089652168a9SFedor Sergeev   InlineResult ShouldInline = CA.analyzeCall(Call);
20907adc3a2bSChandler Carruth 
2091d34e60caSNicola Zaghen   LLVM_DEBUG(CA.dump());
20927adc3a2bSChandler Carruth 
20937adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
20947adc3a2bSChandler Carruth   if (!ShouldInline && CA.getCost() < CA.getThreshold())
2095c0aa4b75SDavid Bolvansky     return InlineCost::getNever(ShouldInline.message);
20967adc3a2bSChandler Carruth   if (ShouldInline && CA.getCost() >= CA.getThreshold())
2097c0aa4b75SDavid Bolvansky     return InlineCost::getAlways("empty function");
20987adc3a2bSChandler Carruth 
20997adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
21007adc3a2bSChandler Carruth }
21017adc3a2bSChandler Carruth 
210215b17d0aSYevgeny Rouban InlineResult llvm::isInlineViable(Function &F) {
21037adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
21047adc3a2bSChandler Carruth   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
2105639b29b1SNick Desaulniers     // Disallow inlining of functions which contain indirect branches.
210615b17d0aSYevgeny Rouban     if (isa<IndirectBrInst>(BI->getTerminator()))
210715b17d0aSYevgeny Rouban       return "contains indirect branches";
210815b17d0aSYevgeny Rouban 
2109639b29b1SNick Desaulniers     // Disallow inlining of blockaddresses which are used by non-callbr
2110639b29b1SNick Desaulniers     // instructions.
21116a84cd3bSNick Desaulniers     if (BI->hasAddressTaken())
2112639b29b1SNick Desaulniers       for (User *U : BlockAddress::get(&*BI)->users())
2113639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
2114639b29b1SNick Desaulniers           return "blockaddress used outside of callbr";
21157adc3a2bSChandler Carruth 
21165a82c916SDuncan P. N. Exon Smith     for (auto &II : *BI) {
2117652168a9SFedor Sergeev       CallBase *Call = dyn_cast<CallBase>(&II);
2118652168a9SFedor Sergeev       if (!Call)
21197adc3a2bSChandler Carruth         continue;
21207adc3a2bSChandler Carruth 
21217adc3a2bSChandler Carruth       // Disallow recursive calls.
2122652168a9SFedor Sergeev       if (&F == Call->getCalledFunction())
212315b17d0aSYevgeny Rouban         return "recursive call";
21247adc3a2bSChandler Carruth 
21257adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
21267adc3a2bSChandler Carruth       // attributed as such.
2127652168a9SFedor Sergeev       if (!ReturnsTwice && isa<CallInst>(Call) &&
2128652168a9SFedor Sergeev           cast<CallInst>(Call)->canReturnTwice())
212915b17d0aSYevgeny Rouban         return "exposes returns-twice attribute";
21307adc3a2bSChandler Carruth 
2131652168a9SFedor Sergeev       if (Call->getCalledFunction())
2132652168a9SFedor Sergeev         switch (Call->getCalledFunction()->getIntrinsicID()) {
21331636651eSFlorian Hahn         default:
21341636651eSFlorian Hahn           break;
21354296ea72SVitaly Buka         // Disallow inlining of @llvm.icall.branch.funnel because current
21364296ea72SVitaly Buka         // backend can't separate call targets from call arguments.
21374296ea72SVitaly Buka         case llvm::Intrinsic::icall_branch_funnel:
213815b17d0aSYevgeny Rouban           return "disallowed inlining of @llvm.icall.branch.funnel";
21397adc3a2bSChandler Carruth         // Disallow inlining functions that call @llvm.localescape. Doing this
21407adc3a2bSChandler Carruth         // correctly would require major changes to the inliner.
21411636651eSFlorian Hahn         case llvm::Intrinsic::localescape:
214215b17d0aSYevgeny Rouban           return "disallowed inlining of @llvm.localescape";
214377beee41SSameer AbuAsal         // Disallow inlining of functions that initialize VarArgs with va_start.
21441636651eSFlorian Hahn         case llvm::Intrinsic::vastart:
214515b17d0aSYevgeny Rouban           return "contains VarArgs initialized with va_start";
21467adc3a2bSChandler Carruth         }
21477adc3a2bSChandler Carruth     }
21481636651eSFlorian Hahn   }
21497adc3a2bSChandler Carruth 
21507adc3a2bSChandler Carruth   return true;
21517adc3a2bSChandler Carruth }
21521c57cc2bSEaswaran Raman 
21531c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other
21541c57cc2bSEaswaran Raman // parameters.
21551c57cc2bSEaswaran Raman 
21561c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) {
21571c57cc2bSEaswaran Raman   InlineParams Params;
21581c57cc2bSEaswaran Raman 
21591c57cc2bSEaswaran Raman   // This field is the threshold to use for a callee by default. This is
21601c57cc2bSEaswaran Raman   // derived from one or more of:
21611c57cc2bSEaswaran Raman   //  * optimization or size-optimization levels,
21621c57cc2bSEaswaran Raman   //  * a value passed to createFunctionInliningPass function, or
21631c57cc2bSEaswaran Raman   //  * the -inline-threshold flag.
21641c57cc2bSEaswaran Raman   //  If the -inline-threshold flag is explicitly specified, that is used
21651c57cc2bSEaswaran Raman   //  irrespective of anything else.
21661c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() > 0)
21671c57cc2bSEaswaran Raman     Params.DefaultThreshold = InlineThreshold;
21681c57cc2bSEaswaran Raman   else
21691c57cc2bSEaswaran Raman     Params.DefaultThreshold = Threshold;
21701c57cc2bSEaswaran Raman 
21711c57cc2bSEaswaran Raman   // Set the HintThreshold knob from the -inlinehint-threshold.
21721c57cc2bSEaswaran Raman   Params.HintThreshold = HintThreshold;
21731c57cc2bSEaswaran Raman 
21741c57cc2bSEaswaran Raman   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
21751c57cc2bSEaswaran Raman   Params.HotCallSiteThreshold = HotCallSiteThreshold;
21761c57cc2bSEaswaran Raman 
2177974d4eeaSEaswaran Raman   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
2178974d4eeaSEaswaran Raman   // populate LocallyHotCallSiteThreshold. Later, we populate
2179974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
2180974d4eeaSEaswaran Raman   // we know that optimization level is O3 (in the getInlineParams variant that
2181974d4eeaSEaswaran Raman   // takes the opt and size levels).
2182974d4eeaSEaswaran Raman   // FIXME: Remove this check (and make the assignment unconditional) after
2183974d4eeaSEaswaran Raman   // addressing size regression issues at O2.
2184974d4eeaSEaswaran Raman   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
2185974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2186974d4eeaSEaswaran Raman 
218712585b01SEaswaran Raman   // Set the ColdCallSiteThreshold knob from the -inline-cold-callsite-threshold.
218812585b01SEaswaran Raman   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
218912585b01SEaswaran Raman 
21901c57cc2bSEaswaran Raman   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
21911c57cc2bSEaswaran Raman   // -inlinehint-threshold commandline option is not explicitly given. If that
21921c57cc2bSEaswaran Raman   // option is present, then its value applies even for callees with size and
21931c57cc2bSEaswaran Raman   // minsize attributes.
21941c57cc2bSEaswaran Raman   // If the -inline-threshold is not specified, set the ColdThreshold from the
21951c57cc2bSEaswaran Raman   // -inlinecold-threshold even if it is not explicitly passed. If
21961c57cc2bSEaswaran Raman   // -inline-threshold is specified, then -inlinecold-threshold needs to be
21971c57cc2bSEaswaran Raman   // explicitly specified to set the ColdThreshold knob
21981c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() == 0) {
21991c57cc2bSEaswaran Raman     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
22001c57cc2bSEaswaran Raman     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
22011c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
22021c57cc2bSEaswaran Raman   } else if (ColdThreshold.getNumOccurrences() > 0) {
22031c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
22041c57cc2bSEaswaran Raman   }
22051c57cc2bSEaswaran Raman   return Params;
22061c57cc2bSEaswaran Raman }
22071c57cc2bSEaswaran Raman 
22081c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() {
22091c57cc2bSEaswaran Raman   return getInlineParams(InlineThreshold);
22101c57cc2bSEaswaran Raman }
22111c57cc2bSEaswaran Raman 
22121c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the
22131c57cc2bSEaswaran Raman // size opt level.
22141c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel,
22151c57cc2bSEaswaran Raman                                          unsigned SizeOptLevel) {
22161c57cc2bSEaswaran Raman   if (OptLevel > 2)
22171c57cc2bSEaswaran Raman     return InlineConstants::OptAggressiveThreshold;
22181c57cc2bSEaswaran Raman   if (SizeOptLevel == 1) // -Os
22191c57cc2bSEaswaran Raman     return InlineConstants::OptSizeThreshold;
22201c57cc2bSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
22211c57cc2bSEaswaran Raman     return InlineConstants::OptMinSizeThreshold;
22221c57cc2bSEaswaran Raman   return InlineThreshold;
22231c57cc2bSEaswaran Raman }
22241c57cc2bSEaswaran Raman 
22251c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
2226974d4eeaSEaswaran Raman   auto Params =
2227974d4eeaSEaswaran Raman       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
2228974d4eeaSEaswaran Raman   // At O3, use the value of -locally-hot-callsite-threshold option to populate
2229974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
2230974d4eeaSEaswaran Raman   // when it is specified explicitly.
2231974d4eeaSEaswaran Raman   if (OptLevel > 2)
2232974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2233974d4eeaSEaswaran Raman   return Params;
22341c57cc2bSEaswaran Raman }
2235