17adc3a2bSChandler Carruth //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
27adc3a2bSChandler Carruth //
37adc3a2bSChandler Carruth //                     The LLVM Compiler Infrastructure
47adc3a2bSChandler Carruth //
57adc3a2bSChandler Carruth // This file is distributed under the University of Illinois Open Source
67adc3a2bSChandler Carruth // License. See LICENSE.TXT for details.
77adc3a2bSChandler Carruth //
87adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
97adc3a2bSChandler Carruth //
107adc3a2bSChandler Carruth // This file implements inline cost analysis.
117adc3a2bSChandler Carruth //
127adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
137adc3a2bSChandler Carruth 
147adc3a2bSChandler Carruth #include "llvm/Analysis/InlineCost.h"
157adc3a2bSChandler Carruth #include "llvm/ADT/STLExtras.h"
167adc3a2bSChandler Carruth #include "llvm/ADT/SetVector.h"
177adc3a2bSChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
187adc3a2bSChandler Carruth #include "llvm/ADT/SmallVector.h"
197adc3a2bSChandler Carruth #include "llvm/ADT/Statistic.h"
207adc3a2bSChandler Carruth #include "llvm/Analysis/AssumptionCache.h"
217adc3a2bSChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
227adc3a2bSChandler Carruth #include "llvm/Analysis/ConstantFolding.h"
237adc3a2bSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h"
247adc3a2bSChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
257adc3a2bSChandler Carruth #include "llvm/IR/CallSite.h"
267adc3a2bSChandler Carruth #include "llvm/IR/CallingConv.h"
277adc3a2bSChandler Carruth #include "llvm/IR/DataLayout.h"
287adc3a2bSChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
297adc3a2bSChandler Carruth #include "llvm/IR/GlobalAlias.h"
307adc3a2bSChandler Carruth #include "llvm/IR/InstVisitor.h"
317adc3a2bSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
327adc3a2bSChandler Carruth #include "llvm/IR/Operator.h"
337adc3a2bSChandler Carruth #include "llvm/Support/Debug.h"
347adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h"
357adc3a2bSChandler Carruth 
367adc3a2bSChandler Carruth using namespace llvm;
377adc3a2bSChandler Carruth 
387adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost"
397adc3a2bSChandler Carruth 
407adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
417adc3a2bSChandler Carruth 
42*f4bb2f0dSEaswaran Raman // Threshold to use when optsize is specified (and there is no
43*f4bb2f0dSEaswaran Raman // -inline-threshold).
44*f4bb2f0dSEaswaran Raman const int OptSizeThreshold = 75;
45*f4bb2f0dSEaswaran Raman 
46*f4bb2f0dSEaswaran Raman // Threshold to use when -Oz is specified (and there is no -inline-threshold).
47*f4bb2f0dSEaswaran Raman const int OptMinSizeThreshold = 25;
48*f4bb2f0dSEaswaran Raman 
49*f4bb2f0dSEaswaran Raman // Threshold to use when -O[34] is specified (and there is no
50*f4bb2f0dSEaswaran Raman // -inline-threshold).
51*f4bb2f0dSEaswaran Raman const int OptAggressiveThreshold = 275;
52*f4bb2f0dSEaswaran Raman 
53*f4bb2f0dSEaswaran Raman static cl::opt<int> DefaultInlineThreshold(
54*f4bb2f0dSEaswaran Raman     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
55*f4bb2f0dSEaswaran Raman     cl::desc("Control the amount of inlining to perform (default = 225)"));
56*f4bb2f0dSEaswaran Raman 
57*f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold(
58*f4bb2f0dSEaswaran Raman     "inlinehint-threshold", cl::Hidden, cl::init(325),
59*f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with inline hint"));
60*f4bb2f0dSEaswaran Raman 
61*f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based
62*f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and
63*f4bb2f0dSEaswaran Raman // BFI.
64*f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold(
65*f4bb2f0dSEaswaran Raman     "inlinecold-threshold", cl::Hidden, cl::init(225),
66*f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with cold attribute"));
67*f4bb2f0dSEaswaran Raman 
687adc3a2bSChandler Carruth namespace {
697adc3a2bSChandler Carruth 
707adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
717adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
727adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
737adc3a2bSChandler Carruth 
747adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
757adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
767adc3a2bSChandler Carruth 
777adc3a2bSChandler Carruth   /// The cache of @llvm.assume intrinsics.
787adc3a2bSChandler Carruth   AssumptionCacheTracker *ACT;
797adc3a2bSChandler Carruth 
807adc3a2bSChandler Carruth   // The called function.
817adc3a2bSChandler Carruth   Function &F;
827adc3a2bSChandler Carruth 
837adc3a2bSChandler Carruth   // The candidate callsite being analyzed. Please do not use this to do
847adc3a2bSChandler Carruth   // analysis in the caller function; we want the inline cost query to be
857adc3a2bSChandler Carruth   // easily cacheable. Instead, use the cover function paramHasAttr.
867adc3a2bSChandler Carruth   CallSite CandidateCS;
877adc3a2bSChandler Carruth 
887adc3a2bSChandler Carruth   int Threshold;
897adc3a2bSChandler Carruth   int Cost;
907adc3a2bSChandler Carruth 
917adc3a2bSChandler Carruth   bool IsCallerRecursive;
927adc3a2bSChandler Carruth   bool IsRecursiveCall;
937adc3a2bSChandler Carruth   bool ExposesReturnsTwice;
947adc3a2bSChandler Carruth   bool HasDynamicAlloca;
957adc3a2bSChandler Carruth   bool ContainsNoDuplicateCall;
967adc3a2bSChandler Carruth   bool HasReturn;
977adc3a2bSChandler Carruth   bool HasIndirectBr;
987adc3a2bSChandler Carruth   bool HasFrameEscape;
997adc3a2bSChandler Carruth 
1007adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
1017adc3a2bSChandler Carruth   uint64_t AllocatedSize;
1027adc3a2bSChandler Carruth   unsigned NumInstructions, NumVectorInstructions;
1037adc3a2bSChandler Carruth   int FiftyPercentVectorBonus, TenPercentVectorBonus;
1047adc3a2bSChandler Carruth   int VectorBonus;
1057adc3a2bSChandler Carruth 
1067adc3a2bSChandler Carruth   // While we walk the potentially-inlined instructions, we build up and
1077adc3a2bSChandler Carruth   // maintain a mapping of simplified values specific to this callsite. The
1087adc3a2bSChandler Carruth   // idea is to propagate any special information we have about arguments to
1097adc3a2bSChandler Carruth   // this call through the inlinable section of the function, and account for
1107adc3a2bSChandler Carruth   // likely simplifications post-inlining. The most important aspect we track
1117adc3a2bSChandler Carruth   // is CFG altering simplifications -- when we prove a basic block dead, that
1127adc3a2bSChandler Carruth   // can cause dramatic shifts in the cost of inlining a function.
1137adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
1147adc3a2bSChandler Carruth 
1157adc3a2bSChandler Carruth   // Keep track of the values which map back (through function arguments) to
1167adc3a2bSChandler Carruth   // allocas on the caller stack which could be simplified through SROA.
1177adc3a2bSChandler Carruth   DenseMap<Value *, Value *> SROAArgValues;
1187adc3a2bSChandler Carruth 
1197adc3a2bSChandler Carruth   // The mapping of caller Alloca values to their accumulated cost savings. If
1207adc3a2bSChandler Carruth   // we have to disable SROA for one of the allocas, this tells us how much
1217adc3a2bSChandler Carruth   // cost must be added.
1227adc3a2bSChandler Carruth   DenseMap<Value *, int> SROAArgCosts;
1237adc3a2bSChandler Carruth 
1247adc3a2bSChandler Carruth   // Keep track of values which map to a pointer base and constant offset.
1257adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
1267adc3a2bSChandler Carruth 
1277adc3a2bSChandler Carruth   // Custom simplification helper routines.
1287adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
1297adc3a2bSChandler Carruth   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
1307adc3a2bSChandler Carruth                             DenseMap<Value *, int>::iterator &CostIt);
1317adc3a2bSChandler Carruth   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
1327adc3a2bSChandler Carruth   void disableSROA(Value *V);
1337adc3a2bSChandler Carruth   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
1347adc3a2bSChandler Carruth                           int InstructionCost);
1357adc3a2bSChandler Carruth   bool isGEPOffsetConstant(GetElementPtrInst &GEP);
1367adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
1377adc3a2bSChandler Carruth   bool simplifyCallSite(Function *F, CallSite CS);
1387adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
1397adc3a2bSChandler Carruth 
1407adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
1417adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
1427adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
1437adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
1447adc3a2bSChandler Carruth   /// itself.
1457adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
1467adc3a2bSChandler Carruth 
1477adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
1487adc3a2bSChandler Carruth   /// inlined through this particular callsite.
1497adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
1507adc3a2bSChandler Carruth 
151*f4bb2f0dSEaswaran Raman   /// Update Threshold based on callsite properties such as callee
152*f4bb2f0dSEaswaran Raman   /// attributes and callee hotness for PGO builds. The Callee is explicitly
153*f4bb2f0dSEaswaran Raman   /// passed to support analyzing indirect calls whose target is inferred by
154*f4bb2f0dSEaswaran Raman   /// analysis.
155*f4bb2f0dSEaswaran Raman   void updateThreshold(CallSite CS, Function &Callee);
156*f4bb2f0dSEaswaran Raman 
1577adc3a2bSChandler Carruth   // Custom analysis routines.
1587adc3a2bSChandler Carruth   bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
1597adc3a2bSChandler Carruth 
1607adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
1617adc3a2bSChandler Carruth   // them by declaring but not defining them here.
1627adc3a2bSChandler Carruth   void visit(Module *);     void visit(Module &);
1637adc3a2bSChandler Carruth   void visit(Function *);   void visit(Function &);
1647adc3a2bSChandler Carruth   void visit(BasicBlock *); void visit(BasicBlock &);
1657adc3a2bSChandler Carruth 
1667adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
1677adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
1687adc3a2bSChandler Carruth 
1697adc3a2bSChandler Carruth   // Our visit overrides.
1707adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
1717adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
1727adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
1737adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
1747adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
1757adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
1767adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
1777adc3a2bSChandler Carruth   bool visitUnaryInstruction(UnaryInstruction &I);
1787adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
1797adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
1807adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
1817adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
1827adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
1837adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
1847adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
1857adc3a2bSChandler Carruth   bool visitCallSite(CallSite CS);
1867adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
1877adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
1887adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
1897adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
1907adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
1917adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
1927adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
1937adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
1947adc3a2bSChandler Carruth 
1957adc3a2bSChandler Carruth public:
1967adc3a2bSChandler Carruth   CallAnalyzer(const TargetTransformInfo &TTI, AssumptionCacheTracker *ACT,
1977adc3a2bSChandler Carruth                Function &Callee, int Threshold, CallSite CSArg)
1987adc3a2bSChandler Carruth     : TTI(TTI), ACT(ACT), F(Callee), CandidateCS(CSArg), Threshold(Threshold),
1997adc3a2bSChandler Carruth         Cost(0), IsCallerRecursive(false), IsRecursiveCall(false),
2007adc3a2bSChandler Carruth         ExposesReturnsTwice(false), HasDynamicAlloca(false),
2017adc3a2bSChandler Carruth         ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
2027adc3a2bSChandler Carruth         HasFrameEscape(false), AllocatedSize(0), NumInstructions(0),
2037adc3a2bSChandler Carruth         NumVectorInstructions(0), FiftyPercentVectorBonus(0),
2047adc3a2bSChandler Carruth         TenPercentVectorBonus(0), VectorBonus(0), NumConstantArgs(0),
2057adc3a2bSChandler Carruth         NumConstantOffsetPtrArgs(0), NumAllocaArgs(0), NumConstantPtrCmps(0),
2067adc3a2bSChandler Carruth         NumConstantPtrDiffs(0), NumInstructionsSimplified(0),
2077adc3a2bSChandler Carruth         SROACostSavings(0), SROACostSavingsLost(0) {}
2087adc3a2bSChandler Carruth 
2097adc3a2bSChandler Carruth   bool analyzeCall(CallSite CS);
2107adc3a2bSChandler Carruth 
2117adc3a2bSChandler Carruth   int getThreshold() { return Threshold; }
2127adc3a2bSChandler Carruth   int getCost() { return Cost; }
2137adc3a2bSChandler Carruth 
2147adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
2157adc3a2bSChandler Carruth   // out when debugging.
2167adc3a2bSChandler Carruth   unsigned NumConstantArgs;
2177adc3a2bSChandler Carruth   unsigned NumConstantOffsetPtrArgs;
2187adc3a2bSChandler Carruth   unsigned NumAllocaArgs;
2197adc3a2bSChandler Carruth   unsigned NumConstantPtrCmps;
2207adc3a2bSChandler Carruth   unsigned NumConstantPtrDiffs;
2217adc3a2bSChandler Carruth   unsigned NumInstructionsSimplified;
2227adc3a2bSChandler Carruth   unsigned SROACostSavings;
2237adc3a2bSChandler Carruth   unsigned SROACostSavingsLost;
2247adc3a2bSChandler Carruth 
2257adc3a2bSChandler Carruth   void dump();
2267adc3a2bSChandler Carruth };
2277adc3a2bSChandler Carruth 
2287adc3a2bSChandler Carruth } // namespace
2297adc3a2bSChandler Carruth 
2307adc3a2bSChandler Carruth /// \brief Test whether the given value is an Alloca-derived function argument.
2317adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
2327adc3a2bSChandler Carruth   return SROAArgValues.count(V);
2337adc3a2bSChandler Carruth }
2347adc3a2bSChandler Carruth 
2357adc3a2bSChandler Carruth /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
2367adc3a2bSChandler Carruth /// Returns false if V does not map to a SROA-candidate.
2377adc3a2bSChandler Carruth bool CallAnalyzer::lookupSROAArgAndCost(
2387adc3a2bSChandler Carruth     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
2397adc3a2bSChandler Carruth   if (SROAArgValues.empty() || SROAArgCosts.empty())
2407adc3a2bSChandler Carruth     return false;
2417adc3a2bSChandler Carruth 
2427adc3a2bSChandler Carruth   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
2437adc3a2bSChandler Carruth   if (ArgIt == SROAArgValues.end())
2447adc3a2bSChandler Carruth     return false;
2457adc3a2bSChandler Carruth 
2467adc3a2bSChandler Carruth   Arg = ArgIt->second;
2477adc3a2bSChandler Carruth   CostIt = SROAArgCosts.find(Arg);
2487adc3a2bSChandler Carruth   return CostIt != SROAArgCosts.end();
2497adc3a2bSChandler Carruth }
2507adc3a2bSChandler Carruth 
2517adc3a2bSChandler Carruth /// \brief Disable SROA for the candidate marked by this cost iterator.
2527adc3a2bSChandler Carruth ///
2537adc3a2bSChandler Carruth /// This marks the candidate as no longer viable for SROA, and adds the cost
2547adc3a2bSChandler Carruth /// savings associated with it back into the inline cost measurement.
2557adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
2567adc3a2bSChandler Carruth   // If we're no longer able to perform SROA we need to undo its cost savings
2577adc3a2bSChandler Carruth   // and prevent subsequent analysis.
2587adc3a2bSChandler Carruth   Cost += CostIt->second;
2597adc3a2bSChandler Carruth   SROACostSavings -= CostIt->second;
2607adc3a2bSChandler Carruth   SROACostSavingsLost += CostIt->second;
2617adc3a2bSChandler Carruth   SROAArgCosts.erase(CostIt);
2627adc3a2bSChandler Carruth }
2637adc3a2bSChandler Carruth 
2647adc3a2bSChandler Carruth /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
2657adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
2667adc3a2bSChandler Carruth   Value *SROAArg;
2677adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
2687adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
2697adc3a2bSChandler Carruth     disableSROA(CostIt);
2707adc3a2bSChandler Carruth }
2717adc3a2bSChandler Carruth 
2727adc3a2bSChandler Carruth /// \brief Accumulate the given cost for a particular SROA candidate.
2737adc3a2bSChandler Carruth void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
2747adc3a2bSChandler Carruth                                       int InstructionCost) {
2757adc3a2bSChandler Carruth   CostIt->second += InstructionCost;
2767adc3a2bSChandler Carruth   SROACostSavings += InstructionCost;
2777adc3a2bSChandler Carruth }
2787adc3a2bSChandler Carruth 
2797adc3a2bSChandler Carruth /// \brief Check whether a GEP's indices are all constant.
2807adc3a2bSChandler Carruth ///
2817adc3a2bSChandler Carruth /// Respects any simplified values known during the analysis of this callsite.
2827adc3a2bSChandler Carruth bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
2837adc3a2bSChandler Carruth   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
2847adc3a2bSChandler Carruth     if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
2857adc3a2bSChandler Carruth       return false;
2867adc3a2bSChandler Carruth 
2877adc3a2bSChandler Carruth   return true;
2887adc3a2bSChandler Carruth }
2897adc3a2bSChandler Carruth 
2907adc3a2bSChandler Carruth /// \brief Accumulate a constant GEP offset into an APInt if possible.
2917adc3a2bSChandler Carruth ///
2927adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
2937adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
2947adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
2957adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
2967adc3a2bSChandler Carruth   unsigned IntPtrWidth = DL.getPointerSizeInBits();
2977adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
2987adc3a2bSChandler Carruth 
2997adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
3007adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
3017adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
3027adc3a2bSChandler Carruth     if (!OpC)
3037adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
3047adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
3057adc3a2bSChandler Carruth     if (!OpC)
3067adc3a2bSChandler Carruth       return false;
3077adc3a2bSChandler Carruth     if (OpC->isZero()) continue;
3087adc3a2bSChandler Carruth 
3097adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
3107adc3a2bSChandler Carruth     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
3117adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
3127adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
3137adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
3147adc3a2bSChandler Carruth       continue;
3157adc3a2bSChandler Carruth     }
3167adc3a2bSChandler Carruth 
3177adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
3187adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
3197adc3a2bSChandler Carruth   }
3207adc3a2bSChandler Carruth   return true;
3217adc3a2bSChandler Carruth }
3227adc3a2bSChandler Carruth 
3237adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
3247adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
3257adc3a2bSChandler Carruth   // alloca, and handle that case.
3267adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
3277adc3a2bSChandler Carruth     if (Constant *Size = SimplifiedValues.lookup(I.getArraySize())) {
3287adc3a2bSChandler Carruth       ConstantInt *AllocSize = dyn_cast<ConstantInt>(Size);
3297adc3a2bSChandler Carruth       assert(AllocSize && "Allocation size not a constant int?");
3307adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
3317adc3a2bSChandler Carruth       AllocatedSize += Ty->getPrimitiveSizeInBits() * AllocSize->getZExtValue();
3327adc3a2bSChandler Carruth       return Base::visitAlloca(I);
3337adc3a2bSChandler Carruth     }
3347adc3a2bSChandler Carruth   }
3357adc3a2bSChandler Carruth 
3367adc3a2bSChandler Carruth   // Accumulate the allocated size.
3377adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
3387adc3a2bSChandler Carruth     const DataLayout &DL = F.getParent()->getDataLayout();
3397adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
3407adc3a2bSChandler Carruth     AllocatedSize += DL.getTypeAllocSize(Ty);
3417adc3a2bSChandler Carruth   }
3427adc3a2bSChandler Carruth 
3437adc3a2bSChandler Carruth   // We will happily inline static alloca instructions.
3447adc3a2bSChandler Carruth   if (I.isStaticAlloca())
3457adc3a2bSChandler Carruth     return Base::visitAlloca(I);
3467adc3a2bSChandler Carruth 
3477adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
3487adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
3497adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
3507adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
3517adc3a2bSChandler Carruth   HasDynamicAlloca = true;
3527adc3a2bSChandler Carruth   return false;
3537adc3a2bSChandler Carruth }
3547adc3a2bSChandler Carruth 
3557adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
3567adc3a2bSChandler Carruth   // FIXME: We should potentially be tracking values through phi nodes,
3577adc3a2bSChandler Carruth   // especially when they collapse to a single value due to deleted CFG edges
3587adc3a2bSChandler Carruth   // during inlining.
3597adc3a2bSChandler Carruth 
3607adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
3617adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
3627adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
3637adc3a2bSChandler Carruth 
3647adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
3657adc3a2bSChandler Carruth   return true;
3667adc3a2bSChandler Carruth }
3677adc3a2bSChandler Carruth 
3687adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
3697adc3a2bSChandler Carruth   Value *SROAArg;
3707adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
3717adc3a2bSChandler Carruth   bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
3727adc3a2bSChandler Carruth                                             SROAArg, CostIt);
3737adc3a2bSChandler Carruth 
3747adc3a2bSChandler Carruth   // Try to fold GEPs of constant-offset call site argument pointers. This
3757adc3a2bSChandler Carruth   // requires target data and inbounds GEPs.
3767adc3a2bSChandler Carruth   if (I.isInBounds()) {
3777adc3a2bSChandler Carruth     // Check if we have a base + offset for the pointer.
3787adc3a2bSChandler Carruth     Value *Ptr = I.getPointerOperand();
3797adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
3807adc3a2bSChandler Carruth     if (BaseAndOffset.first) {
3817adc3a2bSChandler Carruth       // Check if the offset of this GEP is constant, and if so accumulate it
3827adc3a2bSChandler Carruth       // into Offset.
3837adc3a2bSChandler Carruth       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
3847adc3a2bSChandler Carruth         // Non-constant GEPs aren't folded, and disable SROA.
3857adc3a2bSChandler Carruth         if (SROACandidate)
3867adc3a2bSChandler Carruth           disableSROA(CostIt);
3877adc3a2bSChandler Carruth         return false;
3887adc3a2bSChandler Carruth       }
3897adc3a2bSChandler Carruth 
3907adc3a2bSChandler Carruth       // Add the result as a new mapping to Base + Offset.
3917adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
3927adc3a2bSChandler Carruth 
3937adc3a2bSChandler Carruth       // Also handle SROA candidates here, we already know that the GEP is
3947adc3a2bSChandler Carruth       // all-constant indexed.
3957adc3a2bSChandler Carruth       if (SROACandidate)
3967adc3a2bSChandler Carruth         SROAArgValues[&I] = SROAArg;
3977adc3a2bSChandler Carruth 
3987adc3a2bSChandler Carruth       return true;
3997adc3a2bSChandler Carruth     }
4007adc3a2bSChandler Carruth   }
4017adc3a2bSChandler Carruth 
4027adc3a2bSChandler Carruth   if (isGEPOffsetConstant(I)) {
4037adc3a2bSChandler Carruth     if (SROACandidate)
4047adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
4057adc3a2bSChandler Carruth 
4067adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
4077adc3a2bSChandler Carruth     return true;
4087adc3a2bSChandler Carruth   }
4097adc3a2bSChandler Carruth 
4107adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
4117adc3a2bSChandler Carruth   if (SROACandidate)
4127adc3a2bSChandler Carruth     disableSROA(CostIt);
4137adc3a2bSChandler Carruth   return false;
4147adc3a2bSChandler Carruth }
4157adc3a2bSChandler Carruth 
4167adc3a2bSChandler Carruth bool CallAnalyzer::visitBitCast(BitCastInst &I) {
4177adc3a2bSChandler Carruth   // Propagate constants through bitcasts.
4187adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
4197adc3a2bSChandler Carruth   if (!COp)
4207adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(I.getOperand(0));
4217adc3a2bSChandler Carruth   if (COp)
4227adc3a2bSChandler Carruth     if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
4237adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
4247adc3a2bSChandler Carruth       return true;
4257adc3a2bSChandler Carruth     }
4267adc3a2bSChandler Carruth 
4277adc3a2bSChandler Carruth   // Track base/offsets through casts
4287adc3a2bSChandler Carruth   std::pair<Value *, APInt> BaseAndOffset
4297adc3a2bSChandler Carruth     = ConstantOffsetPtrs.lookup(I.getOperand(0));
4307adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
4317adc3a2bSChandler Carruth   if (BaseAndOffset.first)
4327adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
4337adc3a2bSChandler Carruth 
4347adc3a2bSChandler Carruth   // Also look for SROA candidates here.
4357adc3a2bSChandler Carruth   Value *SROAArg;
4367adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
4377adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
4387adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
4397adc3a2bSChandler Carruth 
4407adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
4417adc3a2bSChandler Carruth   return true;
4427adc3a2bSChandler Carruth }
4437adc3a2bSChandler Carruth 
4447adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
4457adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
4467adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
4477adc3a2bSChandler Carruth   if (!COp)
4487adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(I.getOperand(0));
4497adc3a2bSChandler Carruth   if (COp)
4507adc3a2bSChandler Carruth     if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
4517adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
4527adc3a2bSChandler Carruth       return true;
4537adc3a2bSChandler Carruth     }
4547adc3a2bSChandler Carruth 
4557adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
4567adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
4577adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
4587adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
4597adc3a2bSChandler Carruth   if (IntegerSize >= DL.getPointerSizeInBits()) {
4607adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset
4617adc3a2bSChandler Carruth       = ConstantOffsetPtrs.lookup(I.getOperand(0));
4627adc3a2bSChandler Carruth     if (BaseAndOffset.first)
4637adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
4647adc3a2bSChandler Carruth   }
4657adc3a2bSChandler Carruth 
4667adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
4677adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
4687adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
4697adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
4707adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
4717adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
4727adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
4737adc3a2bSChandler Carruth   Value *SROAArg;
4747adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
4757adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
4767adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
4777adc3a2bSChandler Carruth 
4787adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
4797adc3a2bSChandler Carruth }
4807adc3a2bSChandler Carruth 
4817adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
4827adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
4837adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
4847adc3a2bSChandler Carruth   if (!COp)
4857adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(I.getOperand(0));
4867adc3a2bSChandler Carruth   if (COp)
4877adc3a2bSChandler Carruth     if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
4887adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
4897adc3a2bSChandler Carruth       return true;
4907adc3a2bSChandler Carruth     }
4917adc3a2bSChandler Carruth 
4927adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
4937adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
4947adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
4957adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
4967adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
4977adc3a2bSChandler Carruth   if (IntegerSize <= DL.getPointerSizeInBits()) {
4987adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
4997adc3a2bSChandler Carruth     if (BaseAndOffset.first)
5007adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
5017adc3a2bSChandler Carruth   }
5027adc3a2bSChandler Carruth 
5037adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
5047adc3a2bSChandler Carruth   Value *SROAArg;
5057adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
5067adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
5077adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
5087adc3a2bSChandler Carruth 
5097adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
5107adc3a2bSChandler Carruth }
5117adc3a2bSChandler Carruth 
5127adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
5137adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
5147adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
5157adc3a2bSChandler Carruth   if (!COp)
5167adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(I.getOperand(0));
5177adc3a2bSChandler Carruth   if (COp)
5187adc3a2bSChandler Carruth     if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
5197adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
5207adc3a2bSChandler Carruth       return true;
5217adc3a2bSChandler Carruth     }
5227adc3a2bSChandler Carruth 
5237adc3a2bSChandler Carruth   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
5247adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
5257adc3a2bSChandler Carruth 
5267adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
5277adc3a2bSChandler Carruth }
5287adc3a2bSChandler Carruth 
5297adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
5307adc3a2bSChandler Carruth   Value *Operand = I.getOperand(0);
5317adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(Operand);
5327adc3a2bSChandler Carruth   if (!COp)
5337adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(Operand);
5347adc3a2bSChandler Carruth   if (COp) {
5357adc3a2bSChandler Carruth     const DataLayout &DL = F.getParent()->getDataLayout();
5367adc3a2bSChandler Carruth     if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
5377adc3a2bSChandler Carruth                                                COp, DL)) {
5387adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
5397adc3a2bSChandler Carruth       return true;
5407adc3a2bSChandler Carruth     }
5417adc3a2bSChandler Carruth   }
5427adc3a2bSChandler Carruth 
5437adc3a2bSChandler Carruth   // Disable any SROA on the argument to arbitrary unary operators.
5447adc3a2bSChandler Carruth   disableSROA(Operand);
5457adc3a2bSChandler Carruth 
5467adc3a2bSChandler Carruth   return false;
5477adc3a2bSChandler Carruth }
5487adc3a2bSChandler Carruth 
5497adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
5507adc3a2bSChandler Carruth   unsigned ArgNo = A->getArgNo();
5517adc3a2bSChandler Carruth   return CandidateCS.paramHasAttr(ArgNo+1, Attr);
5527adc3a2bSChandler Carruth }
5537adc3a2bSChandler Carruth 
5547adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
5557adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
5567adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
5577adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
5587adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
5597adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
5607adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
5617adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
5627adc3a2bSChandler Carruth       return true;
5637adc3a2bSChandler Carruth 
5647adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
5657adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
5667adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
5677adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
5687adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
5697adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
5707adc3a2bSChandler Carruth     // SROA firing.
5717adc3a2bSChandler Carruth     return true;
5727adc3a2bSChandler Carruth 
5737adc3a2bSChandler Carruth   return false;
5747adc3a2bSChandler Carruth }
5757adc3a2bSChandler Carruth 
576*f4bb2f0dSEaswaran Raman void CallAnalyzer::updateThreshold(CallSite CS, Function &Callee) {
577*f4bb2f0dSEaswaran Raman   // If -inline-threshold is not given, listen to the optsize attribute when it
578*f4bb2f0dSEaswaran Raman   // would decrease the threshold.
579*f4bb2f0dSEaswaran Raman   Function *Caller = CS.getCaller();
580*f4bb2f0dSEaswaran Raman 
581*f4bb2f0dSEaswaran Raman   // FIXME: Use Function::optForSize()
582*f4bb2f0dSEaswaran Raman   bool OptSize = Caller->hasFnAttribute(Attribute::OptimizeForSize);
583*f4bb2f0dSEaswaran Raman 
584*f4bb2f0dSEaswaran Raman   if (!(DefaultInlineThreshold.getNumOccurrences() > 0) && OptSize &&
585*f4bb2f0dSEaswaran Raman       OptSizeThreshold < Threshold)
586*f4bb2f0dSEaswaran Raman     Threshold = OptSizeThreshold;
587*f4bb2f0dSEaswaran Raman 
588*f4bb2f0dSEaswaran Raman   // If profile information is available, use that to adjust threshold of hot
589*f4bb2f0dSEaswaran Raman   // and cold functions.
590*f4bb2f0dSEaswaran Raman   // FIXME: The heuristic used below for determining hotness and coldness are
591*f4bb2f0dSEaswaran Raman   // based on preliminary SPEC tuning and may not be optimal. Replace this with
592*f4bb2f0dSEaswaran Raman   // a well-tuned heuristic based on *callsite* hotness and not callee hotness.
593*f4bb2f0dSEaswaran Raman   uint64_t FunctionCount = 0, MaxFunctionCount = 0;
594*f4bb2f0dSEaswaran Raman   bool HasPGOCounts = false;
595*f4bb2f0dSEaswaran Raman   if (Callee.getEntryCount() && Callee.getParent()->getMaximumFunctionCount()) {
596*f4bb2f0dSEaswaran Raman     HasPGOCounts = true;
597*f4bb2f0dSEaswaran Raman     FunctionCount = Callee.getEntryCount().getValue();
598*f4bb2f0dSEaswaran Raman     MaxFunctionCount = Callee.getParent()->getMaximumFunctionCount().getValue();
599*f4bb2f0dSEaswaran Raman   }
600*f4bb2f0dSEaswaran Raman 
601*f4bb2f0dSEaswaran Raman   // Listen to the inlinehint attribute or profile based hotness information
602*f4bb2f0dSEaswaran Raman   // when it would increase the threshold and the caller does not need to
603*f4bb2f0dSEaswaran Raman   // minimize its size.
604*f4bb2f0dSEaswaran Raman   bool InlineHint =
605*f4bb2f0dSEaswaran Raman       Callee.hasFnAttribute(Attribute::InlineHint) ||
606*f4bb2f0dSEaswaran Raman       (HasPGOCounts &&
607*f4bb2f0dSEaswaran Raman        FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount));
608*f4bb2f0dSEaswaran Raman   if (InlineHint && HintThreshold > Threshold && !Caller->optForMinSize())
609*f4bb2f0dSEaswaran Raman     Threshold = HintThreshold;
610*f4bb2f0dSEaswaran Raman 
611*f4bb2f0dSEaswaran Raman   // Listen to the cold attribute or profile based coldness information
612*f4bb2f0dSEaswaran Raman   // when it would decrease the threshold.
613*f4bb2f0dSEaswaran Raman   bool ColdCallee =
614*f4bb2f0dSEaswaran Raman       Callee.hasFnAttribute(Attribute::Cold) ||
615*f4bb2f0dSEaswaran Raman       (HasPGOCounts &&
616*f4bb2f0dSEaswaran Raman        FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount));
617*f4bb2f0dSEaswaran Raman   // Command line argument for DefaultInlineThreshold will override the default
618*f4bb2f0dSEaswaran Raman   // ColdThreshold. If we have -inline-threshold but no -inlinecold-threshold,
619*f4bb2f0dSEaswaran Raman   // do not use the default cold threshold even if it is smaller.
620*f4bb2f0dSEaswaran Raman   if ((DefaultInlineThreshold.getNumOccurrences() == 0 ||
621*f4bb2f0dSEaswaran Raman        ColdThreshold.getNumOccurrences() > 0) &&
622*f4bb2f0dSEaswaran Raman       ColdCallee && ColdThreshold < Threshold)
623*f4bb2f0dSEaswaran Raman     Threshold = ColdThreshold;
624*f4bb2f0dSEaswaran Raman }
625*f4bb2f0dSEaswaran Raman 
6267adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
6277adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
6287adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
6297adc3a2bSChandler Carruth   if (!isa<Constant>(LHS))
6307adc3a2bSChandler Carruth     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
6317adc3a2bSChandler Carruth       LHS = SimpleLHS;
6327adc3a2bSChandler Carruth   if (!isa<Constant>(RHS))
6337adc3a2bSChandler Carruth     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
6347adc3a2bSChandler Carruth       RHS = SimpleRHS;
6357adc3a2bSChandler Carruth   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
6367adc3a2bSChandler Carruth     if (Constant *CRHS = dyn_cast<Constant>(RHS))
6377adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
6387adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
6397adc3a2bSChandler Carruth         return true;
6407adc3a2bSChandler Carruth       }
6417adc3a2bSChandler Carruth   }
6427adc3a2bSChandler Carruth 
6437adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
6447adc3a2bSChandler Carruth     return false;
6457adc3a2bSChandler Carruth 
6467adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
6477adc3a2bSChandler Carruth   // a common base.
6487adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
6497adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
6507adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
6517adc3a2bSChandler Carruth   if (LHSBase) {
6527adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
6537adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
6547adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
6557adc3a2bSChandler Carruth       // offsets.
6567adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
6577adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
6587adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
6597adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
6607adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
6617adc3a2bSChandler Carruth         return true;
6627adc3a2bSChandler Carruth       }
6637adc3a2bSChandler Carruth     }
6647adc3a2bSChandler Carruth   }
6657adc3a2bSChandler Carruth 
6667adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
6677adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
6687adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
6697adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
6707adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
6717adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
6727adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
6737adc3a2bSChandler Carruth     return true;
6747adc3a2bSChandler Carruth   }
6757adc3a2bSChandler Carruth   // Finally check for SROA candidates in comparisons.
6767adc3a2bSChandler Carruth   Value *SROAArg;
6777adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
6787adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
6797adc3a2bSChandler Carruth     if (isa<ConstantPointerNull>(I.getOperand(1))) {
6807adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
6817adc3a2bSChandler Carruth       return true;
6827adc3a2bSChandler Carruth     }
6837adc3a2bSChandler Carruth 
6847adc3a2bSChandler Carruth     disableSROA(CostIt);
6857adc3a2bSChandler Carruth   }
6867adc3a2bSChandler Carruth 
6877adc3a2bSChandler Carruth   return false;
6887adc3a2bSChandler Carruth }
6897adc3a2bSChandler Carruth 
6907adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
6917adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
6927adc3a2bSChandler Carruth   // constant-related pointers.
6937adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
6947adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
6957adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
6967adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
6977adc3a2bSChandler Carruth   if (LHSBase) {
6987adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
6997adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
7007adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
7017adc3a2bSChandler Carruth       // offsets.
7027adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
7037adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
7047adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
7057adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
7067adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
7077adc3a2bSChandler Carruth         return true;
7087adc3a2bSChandler Carruth       }
7097adc3a2bSChandler Carruth     }
7107adc3a2bSChandler Carruth   }
7117adc3a2bSChandler Carruth 
7127adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
7137adc3a2bSChandler Carruth   // instructions.
7147adc3a2bSChandler Carruth   return Base::visitSub(I);
7157adc3a2bSChandler Carruth }
7167adc3a2bSChandler Carruth 
7177adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
7187adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
7197adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
7207adc3a2bSChandler Carruth   if (!isa<Constant>(LHS))
7217adc3a2bSChandler Carruth     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
7227adc3a2bSChandler Carruth       LHS = SimpleLHS;
7237adc3a2bSChandler Carruth   if (!isa<Constant>(RHS))
7247adc3a2bSChandler Carruth     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
7257adc3a2bSChandler Carruth       RHS = SimpleRHS;
7267adc3a2bSChandler Carruth   Value *SimpleV = nullptr;
7277adc3a2bSChandler Carruth   if (auto FI = dyn_cast<FPMathOperator>(&I))
7287adc3a2bSChandler Carruth     SimpleV =
7297adc3a2bSChandler Carruth         SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
7307adc3a2bSChandler Carruth   else
7317adc3a2bSChandler Carruth     SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
7327adc3a2bSChandler Carruth 
7337adc3a2bSChandler Carruth   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
7347adc3a2bSChandler Carruth     SimplifiedValues[&I] = C;
7357adc3a2bSChandler Carruth     return true;
7367adc3a2bSChandler Carruth   }
7377adc3a2bSChandler Carruth 
7387adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
7397adc3a2bSChandler Carruth   disableSROA(LHS);
7407adc3a2bSChandler Carruth   disableSROA(RHS);
7417adc3a2bSChandler Carruth 
7427adc3a2bSChandler Carruth   return false;
7437adc3a2bSChandler Carruth }
7447adc3a2bSChandler Carruth 
7457adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
7467adc3a2bSChandler Carruth   Value *SROAArg;
7477adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
7487adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
7497adc3a2bSChandler Carruth     if (I.isSimple()) {
7507adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
7517adc3a2bSChandler Carruth       return true;
7527adc3a2bSChandler Carruth     }
7537adc3a2bSChandler Carruth 
7547adc3a2bSChandler Carruth     disableSROA(CostIt);
7557adc3a2bSChandler Carruth   }
7567adc3a2bSChandler Carruth 
7577adc3a2bSChandler Carruth   return false;
7587adc3a2bSChandler Carruth }
7597adc3a2bSChandler Carruth 
7607adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
7617adc3a2bSChandler Carruth   Value *SROAArg;
7627adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
7637adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
7647adc3a2bSChandler Carruth     if (I.isSimple()) {
7657adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
7667adc3a2bSChandler Carruth       return true;
7677adc3a2bSChandler Carruth     }
7687adc3a2bSChandler Carruth 
7697adc3a2bSChandler Carruth     disableSROA(CostIt);
7707adc3a2bSChandler Carruth   }
7717adc3a2bSChandler Carruth 
7727adc3a2bSChandler Carruth   return false;
7737adc3a2bSChandler Carruth }
7747adc3a2bSChandler Carruth 
7757adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
7767adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
7777adc3a2bSChandler Carruth   Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
7787adc3a2bSChandler Carruth   if (!C)
7797adc3a2bSChandler Carruth     C = SimplifiedValues.lookup(I.getAggregateOperand());
7807adc3a2bSChandler Carruth   if (C) {
7817adc3a2bSChandler Carruth     SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
7827adc3a2bSChandler Carruth     return true;
7837adc3a2bSChandler Carruth   }
7847adc3a2bSChandler Carruth 
7857adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
7867adc3a2bSChandler Carruth   return false;
7877adc3a2bSChandler Carruth }
7887adc3a2bSChandler Carruth 
7897adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
7907adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
7917adc3a2bSChandler Carruth   Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
7927adc3a2bSChandler Carruth   if (!AggC)
7937adc3a2bSChandler Carruth     AggC = SimplifiedValues.lookup(I.getAggregateOperand());
7947adc3a2bSChandler Carruth   Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
7957adc3a2bSChandler Carruth   if (!InsertedC)
7967adc3a2bSChandler Carruth     InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
7977adc3a2bSChandler Carruth   if (AggC && InsertedC) {
7987adc3a2bSChandler Carruth     SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
7997adc3a2bSChandler Carruth                                                         I.getIndices());
8007adc3a2bSChandler Carruth     return true;
8017adc3a2bSChandler Carruth   }
8027adc3a2bSChandler Carruth 
8037adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
8047adc3a2bSChandler Carruth   return false;
8057adc3a2bSChandler Carruth }
8067adc3a2bSChandler Carruth 
8077adc3a2bSChandler Carruth /// \brief Try to simplify a call site.
8087adc3a2bSChandler Carruth ///
8097adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
8107adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
8117adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
8127adc3a2bSChandler Carruth /// free.
8137adc3a2bSChandler Carruth bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
8147adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
8157adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
8167adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
8177adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
8187adc3a2bSChandler Carruth   if (!canConstantFoldCallTo(F))
8197adc3a2bSChandler Carruth     return false;
8207adc3a2bSChandler Carruth 
8217adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
8227adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
8237adc3a2bSChandler Carruth   ConstantArgs.reserve(CS.arg_size());
8247adc3a2bSChandler Carruth   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8257adc3a2bSChandler Carruth        I != E; ++I) {
8267adc3a2bSChandler Carruth     Constant *C = dyn_cast<Constant>(*I);
8277adc3a2bSChandler Carruth     if (!C)
8287adc3a2bSChandler Carruth       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
8297adc3a2bSChandler Carruth     if (!C)
8307adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
8317adc3a2bSChandler Carruth 
8327adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
8337adc3a2bSChandler Carruth   }
8347adc3a2bSChandler Carruth   if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
8357adc3a2bSChandler Carruth     SimplifiedValues[CS.getInstruction()] = C;
8367adc3a2bSChandler Carruth     return true;
8377adc3a2bSChandler Carruth   }
8387adc3a2bSChandler Carruth 
8397adc3a2bSChandler Carruth   return false;
8407adc3a2bSChandler Carruth }
8417adc3a2bSChandler Carruth 
8427adc3a2bSChandler Carruth bool CallAnalyzer::visitCallSite(CallSite CS) {
8437adc3a2bSChandler Carruth   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
8447adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
8457adc3a2bSChandler Carruth     // This aborts the entire analysis.
8467adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
8477adc3a2bSChandler Carruth     return false;
8487adc3a2bSChandler Carruth   }
8497adc3a2bSChandler Carruth   if (CS.isCall() &&
8507adc3a2bSChandler Carruth       cast<CallInst>(CS.getInstruction())->cannotDuplicate())
8517adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
8527adc3a2bSChandler Carruth 
8537adc3a2bSChandler Carruth   if (Function *F = CS.getCalledFunction()) {
8547adc3a2bSChandler Carruth     // When we have a concrete function, first try to simplify it directly.
8557adc3a2bSChandler Carruth     if (simplifyCallSite(F, CS))
8567adc3a2bSChandler Carruth       return true;
8577adc3a2bSChandler Carruth 
8587adc3a2bSChandler Carruth     // Next check if it is an intrinsic we know about.
8597adc3a2bSChandler Carruth     // FIXME: Lift this into part of the InstVisitor.
8607adc3a2bSChandler Carruth     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
8617adc3a2bSChandler Carruth       switch (II->getIntrinsicID()) {
8627adc3a2bSChandler Carruth       default:
8637adc3a2bSChandler Carruth         return Base::visitCallSite(CS);
8647adc3a2bSChandler Carruth 
8657adc3a2bSChandler Carruth       case Intrinsic::memset:
8667adc3a2bSChandler Carruth       case Intrinsic::memcpy:
8677adc3a2bSChandler Carruth       case Intrinsic::memmove:
8687adc3a2bSChandler Carruth         // SROA can usually chew through these intrinsics, but they aren't free.
8697adc3a2bSChandler Carruth         return false;
8707adc3a2bSChandler Carruth       case Intrinsic::localescape:
8717adc3a2bSChandler Carruth         HasFrameEscape = true;
8727adc3a2bSChandler Carruth         return false;
8737adc3a2bSChandler Carruth       }
8747adc3a2bSChandler Carruth     }
8757adc3a2bSChandler Carruth 
8767adc3a2bSChandler Carruth     if (F == CS.getInstruction()->getParent()->getParent()) {
8777adc3a2bSChandler Carruth       // This flag will fully abort the analysis, so don't bother with anything
8787adc3a2bSChandler Carruth       // else.
8797adc3a2bSChandler Carruth       IsRecursiveCall = true;
8807adc3a2bSChandler Carruth       return false;
8817adc3a2bSChandler Carruth     }
8827adc3a2bSChandler Carruth 
8837adc3a2bSChandler Carruth     if (TTI.isLoweredToCall(F)) {
8847adc3a2bSChandler Carruth       // We account for the average 1 instruction per call argument setup
8857adc3a2bSChandler Carruth       // here.
8867adc3a2bSChandler Carruth       Cost += CS.arg_size() * InlineConstants::InstrCost;
8877adc3a2bSChandler Carruth 
8887adc3a2bSChandler Carruth       // Everything other than inline ASM will also have a significant cost
8897adc3a2bSChandler Carruth       // merely from making the call.
8907adc3a2bSChandler Carruth       if (!isa<InlineAsm>(CS.getCalledValue()))
8917adc3a2bSChandler Carruth         Cost += InlineConstants::CallPenalty;
8927adc3a2bSChandler Carruth     }
8937adc3a2bSChandler Carruth 
8947adc3a2bSChandler Carruth     return Base::visitCallSite(CS);
8957adc3a2bSChandler Carruth   }
8967adc3a2bSChandler Carruth 
8977adc3a2bSChandler Carruth   // Otherwise we're in a very special case -- an indirect function call. See
8987adc3a2bSChandler Carruth   // if we can be particularly clever about this.
8997adc3a2bSChandler Carruth   Value *Callee = CS.getCalledValue();
9007adc3a2bSChandler Carruth 
9017adc3a2bSChandler Carruth   // First, pay the price of the argument setup. We account for the average
9027adc3a2bSChandler Carruth   // 1 instruction per call argument setup here.
9037adc3a2bSChandler Carruth   Cost += CS.arg_size() * InlineConstants::InstrCost;
9047adc3a2bSChandler Carruth 
9057adc3a2bSChandler Carruth   // Next, check if this happens to be an indirect function call to a known
9067adc3a2bSChandler Carruth   // function in this inline context. If not, we've done all we can.
9077adc3a2bSChandler Carruth   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
9087adc3a2bSChandler Carruth   if (!F)
9097adc3a2bSChandler Carruth     return Base::visitCallSite(CS);
9107adc3a2bSChandler Carruth 
9117adc3a2bSChandler Carruth   // If we have a constant that we are calling as a function, we can peer
9127adc3a2bSChandler Carruth   // through it and see the function target. This happens not infrequently
9137adc3a2bSChandler Carruth   // during devirtualization and so we want to give it a hefty bonus for
9147adc3a2bSChandler Carruth   // inlining, but cap that bonus in the event that inlining wouldn't pan
9157adc3a2bSChandler Carruth   // out. Pretend to inline the function, with a custom threshold.
9167adc3a2bSChandler Carruth   CallAnalyzer CA(TTI, ACT, *F, InlineConstants::IndirectCallThreshold, CS);
9177adc3a2bSChandler Carruth   if (CA.analyzeCall(CS)) {
9187adc3a2bSChandler Carruth     // We were able to inline the indirect call! Subtract the cost from the
9196d90d9f1SEaswaran Raman     // threshold to get the bonus we want to apply, but don't go below zero.
9206d90d9f1SEaswaran Raman     Cost -= std::max(0, CA.getThreshold() - CA.getCost());
9217adc3a2bSChandler Carruth   }
9227adc3a2bSChandler Carruth 
9237adc3a2bSChandler Carruth   return Base::visitCallSite(CS);
9247adc3a2bSChandler Carruth }
9257adc3a2bSChandler Carruth 
9267adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
9277adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
9287adc3a2bSChandler Carruth   bool Free = !HasReturn;
9297adc3a2bSChandler Carruth   HasReturn = true;
9307adc3a2bSChandler Carruth   return Free;
9317adc3a2bSChandler Carruth }
9327adc3a2bSChandler Carruth 
9337adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
9347adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
9357adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
9367adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
9377adc3a2bSChandler Carruth   // which will fold away are also free.
9387adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
9397adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
9407adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
9417adc3a2bSChandler Carruth }
9427adc3a2bSChandler Carruth 
9437adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
9447adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
9457adc3a2bSChandler Carruth   // branches.
9467adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
9477adc3a2bSChandler Carruth     return true;
9487adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
9497adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
9507adc3a2bSChandler Carruth       return true;
9517adc3a2bSChandler Carruth 
9527adc3a2bSChandler Carruth   // Otherwise, we need to accumulate a cost proportional to the number of
9537adc3a2bSChandler Carruth   // distinct successor blocks. This fan-out in the CFG cannot be represented
9547adc3a2bSChandler Carruth   // for free even if we can represent the core switch as a jumptable that
9557adc3a2bSChandler Carruth   // takes a single instruction.
9567adc3a2bSChandler Carruth   //
9577adc3a2bSChandler Carruth   // NB: We convert large switches which are just used to initialize large phi
9587adc3a2bSChandler Carruth   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
9597adc3a2bSChandler Carruth   // inlining those. It will prevent inlining in cases where the optimization
9607adc3a2bSChandler Carruth   // does not (yet) fire.
9617adc3a2bSChandler Carruth   SmallPtrSet<BasicBlock *, 8> SuccessorBlocks;
9627adc3a2bSChandler Carruth   SuccessorBlocks.insert(SI.getDefaultDest());
9637adc3a2bSChandler Carruth   for (auto I = SI.case_begin(), E = SI.case_end(); I != E; ++I)
9647adc3a2bSChandler Carruth     SuccessorBlocks.insert(I.getCaseSuccessor());
9657adc3a2bSChandler Carruth   // Add cost corresponding to the number of distinct destinations. The first
9667adc3a2bSChandler Carruth   // we model as free because of fallthrough.
9677adc3a2bSChandler Carruth   Cost += (SuccessorBlocks.size() - 1) * InlineConstants::InstrCost;
9687adc3a2bSChandler Carruth   return false;
9697adc3a2bSChandler Carruth }
9707adc3a2bSChandler Carruth 
9717adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
9727adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
9737adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
9747adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
9757adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
9767adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
9777adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
9787adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
9797adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
9807adc3a2bSChandler Carruth   HasIndirectBr = true;
9817adc3a2bSChandler Carruth   return false;
9827adc3a2bSChandler Carruth }
9837adc3a2bSChandler Carruth 
9847adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
9857adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
9867adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
9877adc3a2bSChandler Carruth   return false;
9887adc3a2bSChandler Carruth }
9897adc3a2bSChandler Carruth 
9907adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
9917adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
9927adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
9937adc3a2bSChandler Carruth   return false;
9947adc3a2bSChandler Carruth }
9957adc3a2bSChandler Carruth 
9967adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
9977adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
9988220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
9997adc3a2bSChandler Carruth   return false;
10007adc3a2bSChandler Carruth }
10017adc3a2bSChandler Carruth 
10027adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
10037adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
10047adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
10057adc3a2bSChandler Carruth   // code size.
10067adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
10077adc3a2bSChandler Carruth }
10087adc3a2bSChandler Carruth 
10097adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
10107adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
10117adc3a2bSChandler Carruth   // handled by SROA, etc.
10127adc3a2bSChandler Carruth   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
10137adc3a2bSChandler Carruth     return true;
10147adc3a2bSChandler Carruth 
10157adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
10167adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
10177adc3a2bSChandler Carruth   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
10187adc3a2bSChandler Carruth     disableSROA(*OI);
10197adc3a2bSChandler Carruth 
10207adc3a2bSChandler Carruth   return false;
10217adc3a2bSChandler Carruth }
10227adc3a2bSChandler Carruth 
10237adc3a2bSChandler Carruth 
10247adc3a2bSChandler Carruth /// \brief Analyze a basic block for its contribution to the inline cost.
10257adc3a2bSChandler Carruth ///
10267adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
10277adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
10287adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
10297adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
10307adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
10317adc3a2bSChandler Carruth bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
10327adc3a2bSChandler Carruth                                 SmallPtrSetImpl<const Value *> &EphValues) {
10337adc3a2bSChandler Carruth   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
10347adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
10357adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
10367adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
10377adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
10387adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
10397adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
10407adc3a2bSChandler Carruth     // hack around it here.
10417adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
10427adc3a2bSChandler Carruth       continue;
10437adc3a2bSChandler Carruth 
10447adc3a2bSChandler Carruth     // Skip ephemeral values.
10455a82c916SDuncan P. N. Exon Smith     if (EphValues.count(&*I))
10467adc3a2bSChandler Carruth       continue;
10477adc3a2bSChandler Carruth 
10487adc3a2bSChandler Carruth     ++NumInstructions;
10497adc3a2bSChandler Carruth     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
10507adc3a2bSChandler Carruth       ++NumVectorInstructions;
10517adc3a2bSChandler Carruth 
1052e9434e80SSanjay Patel     // If the instruction is floating point, and the target says this operation
1053e9434e80SSanjay Patel     // is expensive or the function has the "use-soft-float" attribute, this may
10547adc3a2bSChandler Carruth     // eventually become a library call. Treat the cost as such.
10557adc3a2bSChandler Carruth     if (I->getType()->isFloatingPointTy()) {
10567adc3a2bSChandler Carruth       bool hasSoftFloatAttr = false;
10577adc3a2bSChandler Carruth 
1058e9434e80SSanjay Patel       // If the function has the "use-soft-float" attribute, mark it as
1059e9434e80SSanjay Patel       // expensive.
10607adc3a2bSChandler Carruth       if (F.hasFnAttribute("use-soft-float")) {
10617adc3a2bSChandler Carruth         Attribute Attr = F.getFnAttribute("use-soft-float");
10627adc3a2bSChandler Carruth         StringRef Val = Attr.getValueAsString();
10637adc3a2bSChandler Carruth         if (Val == "true")
10647adc3a2bSChandler Carruth           hasSoftFloatAttr = true;
10657adc3a2bSChandler Carruth       }
10667adc3a2bSChandler Carruth 
10677adc3a2bSChandler Carruth       if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
10687adc3a2bSChandler Carruth           hasSoftFloatAttr)
10697adc3a2bSChandler Carruth         Cost += InlineConstants::CallPenalty;
10707adc3a2bSChandler Carruth     }
10717adc3a2bSChandler Carruth 
10727adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
10737adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
10747adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
10757adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
10767adc3a2bSChandler Carruth     // cost should count against inlining.
10775a82c916SDuncan P. N. Exon Smith     if (Base::visit(&*I))
10787adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
10797adc3a2bSChandler Carruth     else
10807adc3a2bSChandler Carruth       Cost += InlineConstants::InstrCost;
10817adc3a2bSChandler Carruth 
10827adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
10837adc3a2bSChandler Carruth     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
10847adc3a2bSChandler Carruth         HasIndirectBr || HasFrameEscape)
10857adc3a2bSChandler Carruth       return false;
10867adc3a2bSChandler Carruth 
10877adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
10887adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
10897adc3a2bSChandler Carruth     // the caller stack usage dramatically.
10907adc3a2bSChandler Carruth     if (IsCallerRecursive &&
10917adc3a2bSChandler Carruth         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
10927adc3a2bSChandler Carruth       return false;
10937adc3a2bSChandler Carruth 
10947adc3a2bSChandler Carruth     // Check if we've past the maximum possible threshold so we don't spin in
10957adc3a2bSChandler Carruth     // huge basic blocks that will never inline.
10967adc3a2bSChandler Carruth     if (Cost > Threshold)
10977adc3a2bSChandler Carruth       return false;
10987adc3a2bSChandler Carruth   }
10997adc3a2bSChandler Carruth 
11007adc3a2bSChandler Carruth   return true;
11017adc3a2bSChandler Carruth }
11027adc3a2bSChandler Carruth 
11037adc3a2bSChandler Carruth /// \brief Compute the base pointer and cumulative constant offsets for V.
11047adc3a2bSChandler Carruth ///
11057adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
11067adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
11077adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
11087adc3a2bSChandler Carruth /// no constant offsets applied.
11097adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
11107adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
11117adc3a2bSChandler Carruth     return nullptr;
11127adc3a2bSChandler Carruth 
11137adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
11147adc3a2bSChandler Carruth   unsigned IntPtrWidth = DL.getPointerSizeInBits();
11157adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
11167adc3a2bSChandler Carruth 
11177adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
11187adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
11197adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
11207adc3a2bSChandler Carruth   Visited.insert(V);
11217adc3a2bSChandler Carruth   do {
11227adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
11237adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
11247adc3a2bSChandler Carruth         return nullptr;
11257adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
11267adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
11277adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
11287adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
11297adc3a2bSChandler Carruth       if (GA->mayBeOverridden())
11307adc3a2bSChandler Carruth         break;
11317adc3a2bSChandler Carruth       V = GA->getAliasee();
11327adc3a2bSChandler Carruth     } else {
11337adc3a2bSChandler Carruth       break;
11347adc3a2bSChandler Carruth     }
11357adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
11367adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
11377adc3a2bSChandler Carruth 
11387adc3a2bSChandler Carruth   Type *IntPtrTy = DL.getIntPtrType(V->getContext());
11397adc3a2bSChandler Carruth   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
11407adc3a2bSChandler Carruth }
11417adc3a2bSChandler Carruth 
11427adc3a2bSChandler Carruth /// \brief Analyze a call site for potential inlining.
11437adc3a2bSChandler Carruth ///
11447adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
11457adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
11467adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
11477adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
11487adc3a2bSChandler Carruth /// some artifact of the routine.
11497adc3a2bSChandler Carruth bool CallAnalyzer::analyzeCall(CallSite CS) {
11507adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
11517adc3a2bSChandler Carruth 
11527adc3a2bSChandler Carruth   // Perform some tweaks to the cost and threshold based on the direct
11537adc3a2bSChandler Carruth   // callsite information.
11547adc3a2bSChandler Carruth 
11557adc3a2bSChandler Carruth   // We want to more aggressively inline vector-dense kernels, so up the
11567adc3a2bSChandler Carruth   // threshold, and we'll lower it if the % of vector instructions gets too
11577adc3a2bSChandler Carruth   // low. Note that these bonuses are some what arbitrary and evolved over time
11587adc3a2bSChandler Carruth   // by accident as much as because they are principled bonuses.
11597adc3a2bSChandler Carruth   //
11607adc3a2bSChandler Carruth   // FIXME: It would be nice to remove all such bonuses. At least it would be
11617adc3a2bSChandler Carruth   // nice to base the bonus values on something more scientific.
11627adc3a2bSChandler Carruth   assert(NumInstructions == 0);
11637adc3a2bSChandler Carruth   assert(NumVectorInstructions == 0);
1164*f4bb2f0dSEaswaran Raman 
1165*f4bb2f0dSEaswaran Raman   // Update the threshold based on callsite properties
1166*f4bb2f0dSEaswaran Raman   updateThreshold(CS, F);
1167*f4bb2f0dSEaswaran Raman 
11687adc3a2bSChandler Carruth   FiftyPercentVectorBonus = 3 * Threshold / 2;
11697adc3a2bSChandler Carruth   TenPercentVectorBonus = 3 * Threshold / 4;
11707adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
11717adc3a2bSChandler Carruth 
11727adc3a2bSChandler Carruth   // Track whether the post-inlining function would have more than one basic
11737adc3a2bSChandler Carruth   // block. A single basic block is often intended for inlining. Balloon the
11747adc3a2bSChandler Carruth   // threshold by 50% until we pass the single-BB phase.
11757adc3a2bSChandler Carruth   bool SingleBB = true;
11767adc3a2bSChandler Carruth   int SingleBBBonus = Threshold / 2;
11777adc3a2bSChandler Carruth 
11787adc3a2bSChandler Carruth   // Speculatively apply all possible bonuses to Threshold. If cost exceeds
11797adc3a2bSChandler Carruth   // this Threshold any time, and cost cannot decrease, we can stop processing
11807adc3a2bSChandler Carruth   // the rest of the function body.
11817adc3a2bSChandler Carruth   Threshold += (SingleBBBonus + FiftyPercentVectorBonus);
11827adc3a2bSChandler Carruth 
11837adc3a2bSChandler Carruth   // Give out bonuses per argument, as the instructions setting them up will
11847adc3a2bSChandler Carruth   // be gone after inlining.
11857adc3a2bSChandler Carruth   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
11867adc3a2bSChandler Carruth     if (CS.isByValArgument(I)) {
11877adc3a2bSChandler Carruth       // We approximate the number of loads and stores needed by dividing the
11887adc3a2bSChandler Carruth       // size of the byval type by the target's pointer size.
11897adc3a2bSChandler Carruth       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
11907adc3a2bSChandler Carruth       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
11917adc3a2bSChandler Carruth       unsigned PointerSize = DL.getPointerSizeInBits();
11927adc3a2bSChandler Carruth       // Ceiling division.
11937adc3a2bSChandler Carruth       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
11947adc3a2bSChandler Carruth 
11957adc3a2bSChandler Carruth       // If it generates more than 8 stores it is likely to be expanded as an
11967adc3a2bSChandler Carruth       // inline memcpy so we take that as an upper bound. Otherwise we assume
11977adc3a2bSChandler Carruth       // one load and one store per word copied.
11987adc3a2bSChandler Carruth       // FIXME: The maxStoresPerMemcpy setting from the target should be used
11997adc3a2bSChandler Carruth       // here instead of a magic number of 8, but it's not available via
12007adc3a2bSChandler Carruth       // DataLayout.
12017adc3a2bSChandler Carruth       NumStores = std::min(NumStores, 8U);
12027adc3a2bSChandler Carruth 
12037adc3a2bSChandler Carruth       Cost -= 2 * NumStores * InlineConstants::InstrCost;
12047adc3a2bSChandler Carruth     } else {
12057adc3a2bSChandler Carruth       // For non-byval arguments subtract off one instruction per call
12067adc3a2bSChandler Carruth       // argument.
12077adc3a2bSChandler Carruth       Cost -= InlineConstants::InstrCost;
12087adc3a2bSChandler Carruth     }
12097adc3a2bSChandler Carruth   }
12107adc3a2bSChandler Carruth 
12117adc3a2bSChandler Carruth   // If there is only one call of the function, and it has internal linkage,
12127adc3a2bSChandler Carruth   // the cost of inlining it drops dramatically.
12137adc3a2bSChandler Carruth   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
12147adc3a2bSChandler Carruth     &F == CS.getCalledFunction();
12157adc3a2bSChandler Carruth   if (OnlyOneCallAndLocalLinkage)
12167adc3a2bSChandler Carruth     Cost += InlineConstants::LastCallToStaticBonus;
12177adc3a2bSChandler Carruth 
12187adc3a2bSChandler Carruth   // If the instruction after the call, or if the normal destination of the
12197adc3a2bSChandler Carruth   // invoke is an unreachable instruction, the function is noreturn. As such,
12207adc3a2bSChandler Carruth   // there is little point in inlining this unless there is literally zero
12217adc3a2bSChandler Carruth   // cost.
12227adc3a2bSChandler Carruth   Instruction *Instr = CS.getInstruction();
12237adc3a2bSChandler Carruth   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
12247adc3a2bSChandler Carruth     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
12257adc3a2bSChandler Carruth       Threshold = 0;
12267adc3a2bSChandler Carruth   } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
12277adc3a2bSChandler Carruth     Threshold = 0;
12287adc3a2bSChandler Carruth 
12297adc3a2bSChandler Carruth   // If this function uses the coldcc calling convention, prefer not to inline
12307adc3a2bSChandler Carruth   // it.
12317adc3a2bSChandler Carruth   if (F.getCallingConv() == CallingConv::Cold)
12327adc3a2bSChandler Carruth     Cost += InlineConstants::ColdccPenalty;
12337adc3a2bSChandler Carruth 
12347adc3a2bSChandler Carruth   // Check if we're done. This can happen due to bonuses and penalties.
12357adc3a2bSChandler Carruth   if (Cost > Threshold)
12367adc3a2bSChandler Carruth     return false;
12377adc3a2bSChandler Carruth 
12387adc3a2bSChandler Carruth   if (F.empty())
12397adc3a2bSChandler Carruth     return true;
12407adc3a2bSChandler Carruth 
12417adc3a2bSChandler Carruth   Function *Caller = CS.getInstruction()->getParent()->getParent();
12427adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
12437adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
12447adc3a2bSChandler Carruth     CallSite Site(U);
12457adc3a2bSChandler Carruth     if (!Site)
12467adc3a2bSChandler Carruth       continue;
12477adc3a2bSChandler Carruth     Instruction *I = Site.getInstruction();
12487adc3a2bSChandler Carruth     if (I->getParent()->getParent() == Caller) {
12497adc3a2bSChandler Carruth       IsCallerRecursive = true;
12507adc3a2bSChandler Carruth       break;
12517adc3a2bSChandler Carruth     }
12527adc3a2bSChandler Carruth   }
12537adc3a2bSChandler Carruth 
12547adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
12557adc3a2bSChandler Carruth   // arguments with known important simplifications.
12567adc3a2bSChandler Carruth   CallSite::arg_iterator CAI = CS.arg_begin();
12577adc3a2bSChandler Carruth   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
12587adc3a2bSChandler Carruth        FAI != FAE; ++FAI, ++CAI) {
12597adc3a2bSChandler Carruth     assert(CAI != CS.arg_end());
12607adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
12615a82c916SDuncan P. N. Exon Smith       SimplifiedValues[&*FAI] = C;
12627adc3a2bSChandler Carruth 
12637adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
12647adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
12655a82c916SDuncan P. N. Exon Smith       ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
12667adc3a2bSChandler Carruth 
12677adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
12687adc3a2bSChandler Carruth       if (isa<AllocaInst>(PtrArg)) {
12695a82c916SDuncan P. N. Exon Smith         SROAArgValues[&*FAI] = PtrArg;
12707adc3a2bSChandler Carruth         SROAArgCosts[PtrArg] = 0;
12717adc3a2bSChandler Carruth       }
12727adc3a2bSChandler Carruth     }
12737adc3a2bSChandler Carruth   }
12747adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
12757adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
12767adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
12777adc3a2bSChandler Carruth 
12787adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
12797adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
12807adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
12817adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
12827adc3a2bSChandler Carruth   CodeMetrics::collectEphemeralValues(&F, &ACT->getAssumptionCache(F), EphValues);
12837adc3a2bSChandler Carruth 
12847adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
12857adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
12867adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
12877adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
12887adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
12897adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
12907adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
12917adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
12927adc3a2bSChandler Carruth                                   SmallPtrSet<BasicBlock *, 16> > BBSetVector;
12937adc3a2bSChandler Carruth   BBSetVector BBWorklist;
12947adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
12957adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
12967adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
12977adc3a2bSChandler Carruth     // Bail out the moment we cross the threshold. This means we'll under-count
12987adc3a2bSChandler Carruth     // the cost, but only when undercounting doesn't matter.
12997adc3a2bSChandler Carruth     if (Cost > Threshold)
13007adc3a2bSChandler Carruth       break;
13017adc3a2bSChandler Carruth 
13027adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
13037adc3a2bSChandler Carruth     if (BB->empty())
13047adc3a2bSChandler Carruth       continue;
13057adc3a2bSChandler Carruth 
13067adc3a2bSChandler Carruth     // Disallow inlining a blockaddress. A blockaddress only has defined
13077adc3a2bSChandler Carruth     // behavior for an indirect branch in the same function, and we do not
13087adc3a2bSChandler Carruth     // currently support inlining indirect branches. But, the inliner may not
13097adc3a2bSChandler Carruth     // see an indirect branch that ends up being dead code at a particular call
13107adc3a2bSChandler Carruth     // site. If the blockaddress escapes the function, e.g., via a global
13117adc3a2bSChandler Carruth     // variable, inlining may lead to an invalid cross-function reference.
13127adc3a2bSChandler Carruth     if (BB->hasAddressTaken())
13137adc3a2bSChandler Carruth       return false;
13147adc3a2bSChandler Carruth 
13157adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
13167adc3a2bSChandler Carruth     // returns false, and we can bail on out.
13177adc3a2bSChandler Carruth     if (!analyzeBlock(BB, EphValues)) {
13187adc3a2bSChandler Carruth       if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
13197adc3a2bSChandler Carruth           HasIndirectBr || HasFrameEscape)
13207adc3a2bSChandler Carruth         return false;
13217adc3a2bSChandler Carruth 
13227adc3a2bSChandler Carruth       // If the caller is a recursive function then we don't want to inline
13237adc3a2bSChandler Carruth       // functions which allocate a lot of stack space because it would increase
13247adc3a2bSChandler Carruth       // the caller stack usage dramatically.
13257adc3a2bSChandler Carruth       if (IsCallerRecursive &&
13267adc3a2bSChandler Carruth           AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
13277adc3a2bSChandler Carruth         return false;
13287adc3a2bSChandler Carruth 
13297adc3a2bSChandler Carruth       break;
13307adc3a2bSChandler Carruth     }
13317adc3a2bSChandler Carruth 
13327adc3a2bSChandler Carruth     TerminatorInst *TI = BB->getTerminator();
13337adc3a2bSChandler Carruth 
13347adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
13357adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
13367adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13377adc3a2bSChandler Carruth       if (BI->isConditional()) {
13387adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
13397adc3a2bSChandler Carruth         if (ConstantInt *SimpleCond
13407adc3a2bSChandler Carruth               = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
13417adc3a2bSChandler Carruth           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
13427adc3a2bSChandler Carruth           continue;
13437adc3a2bSChandler Carruth         }
13447adc3a2bSChandler Carruth       }
13457adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13467adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
13477adc3a2bSChandler Carruth       if (ConstantInt *SimpleCond
13487adc3a2bSChandler Carruth             = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
13497adc3a2bSChandler Carruth         BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
13507adc3a2bSChandler Carruth         continue;
13517adc3a2bSChandler Carruth       }
13527adc3a2bSChandler Carruth     }
13537adc3a2bSChandler Carruth 
13547adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
13557adc3a2bSChandler Carruth     // them.
13567adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
13577adc3a2bSChandler Carruth          ++TIdx)
13587adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
13597adc3a2bSChandler Carruth 
13607adc3a2bSChandler Carruth     // If we had any successors at this point, than post-inlining is likely to
13617adc3a2bSChandler Carruth     // have them as well. Note that we assume any basic blocks which existed
13627adc3a2bSChandler Carruth     // due to branches or switches which folded above will also fold after
13637adc3a2bSChandler Carruth     // inlining.
13647adc3a2bSChandler Carruth     if (SingleBB && TI->getNumSuccessors() > 1) {
13657adc3a2bSChandler Carruth       // Take off the bonus we applied to the threshold.
13667adc3a2bSChandler Carruth       Threshold -= SingleBBBonus;
13677adc3a2bSChandler Carruth       SingleBB = false;
13687adc3a2bSChandler Carruth     }
13697adc3a2bSChandler Carruth   }
13707adc3a2bSChandler Carruth 
13717adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
13727adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
13737adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
13747adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
13757adc3a2bSChandler Carruth     return false;
13767adc3a2bSChandler Carruth 
13777adc3a2bSChandler Carruth   // We applied the maximum possible vector bonus at the beginning. Now,
13787adc3a2bSChandler Carruth   // subtract the excess bonus, if any, from the Threshold before
13797adc3a2bSChandler Carruth   // comparing against Cost.
13807adc3a2bSChandler Carruth   if (NumVectorInstructions <= NumInstructions / 10)
13817adc3a2bSChandler Carruth     Threshold -= FiftyPercentVectorBonus;
13827adc3a2bSChandler Carruth   else if (NumVectorInstructions <= NumInstructions / 2)
13837adc3a2bSChandler Carruth     Threshold -= (FiftyPercentVectorBonus - TenPercentVectorBonus);
13847adc3a2bSChandler Carruth 
138521ce8ecbSHans Wennborg   return Cost <= std::max(0, Threshold);
13867adc3a2bSChandler Carruth }
13877adc3a2bSChandler Carruth 
13887adc3a2bSChandler Carruth #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
13897adc3a2bSChandler Carruth /// \brief Dump stats about this call's analysis.
13907adc3a2bSChandler Carruth void CallAnalyzer::dump() {
13917adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
13927adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
13937adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
13947adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
13957adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
13967adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
13977adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
13987adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
13997adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
14007adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
14017adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
14027adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
14037adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
14047adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
14057adc3a2bSChandler Carruth }
14067adc3a2bSChandler Carruth #endif
14077adc3a2bSChandler Carruth 
14085af7ace4SAkira Hatanaka /// \brief Test that two functions either have or have not the given attribute
14095af7ace4SAkira Hatanaka ///        at the same time.
14105af7ace4SAkira Hatanaka template<typename AttrKind>
14115af7ace4SAkira Hatanaka static bool attributeMatches(Function *F1, Function *F2, AttrKind Attr) {
14125af7ace4SAkira Hatanaka   return F1->getFnAttribute(Attr) == F2->getFnAttribute(Attr);
14135af7ace4SAkira Hatanaka }
14145af7ace4SAkira Hatanaka 
14157adc3a2bSChandler Carruth /// \brief Test that there are no attribute conflicts between Caller and Callee
14167adc3a2bSChandler Carruth ///        that prevent inlining.
14177adc3a2bSChandler Carruth static bool functionsHaveCompatibleAttributes(Function *Caller,
14187adc3a2bSChandler Carruth                                               Function *Callee,
14197adc3a2bSChandler Carruth                                               TargetTransformInfo &TTI) {
14207adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
14211cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
14227adc3a2bSChandler Carruth }
14237adc3a2bSChandler Carruth 
1424*f4bb2f0dSEaswaran Raman InlineCost llvm::getInlineCost(CallSite CS, int DefaultThreshold,
1425b9f7120eSEaswaran Raman                                TargetTransformInfo &CalleeTTI,
1426b9f7120eSEaswaran Raman                                AssumptionCacheTracker *ACT) {
1427*f4bb2f0dSEaswaran Raman   return getInlineCost(CS, CS.getCalledFunction(), DefaultThreshold, CalleeTTI,
1428*f4bb2f0dSEaswaran Raman                        ACT);
1429b9f7120eSEaswaran Raman }
1430b9f7120eSEaswaran Raman 
1431*f4bb2f0dSEaswaran Raman int llvm::computeThresholdFromOptLevels(unsigned OptLevel,
1432*f4bb2f0dSEaswaran Raman                                         unsigned SizeOptLevel) {
1433*f4bb2f0dSEaswaran Raman   if (OptLevel > 2)
1434*f4bb2f0dSEaswaran Raman     return OptAggressiveThreshold;
1435*f4bb2f0dSEaswaran Raman   if (SizeOptLevel == 1) // -Os
1436*f4bb2f0dSEaswaran Raman     return OptSizeThreshold;
1437*f4bb2f0dSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
1438*f4bb2f0dSEaswaran Raman     return OptMinSizeThreshold;
1439*f4bb2f0dSEaswaran Raman   return DefaultInlineThreshold;
1440*f4bb2f0dSEaswaran Raman }
1441*f4bb2f0dSEaswaran Raman 
1442*f4bb2f0dSEaswaran Raman int llvm::getDefaultInlineThreshold() { return DefaultInlineThreshold; }
1443*f4bb2f0dSEaswaran Raman 
1444*f4bb2f0dSEaswaran Raman InlineCost llvm::getInlineCost(CallSite CS, Function *Callee,
1445*f4bb2f0dSEaswaran Raman                                int DefaultThreshold,
1446b9f7120eSEaswaran Raman                                TargetTransformInfo &CalleeTTI,
1447b9f7120eSEaswaran Raman                                AssumptionCacheTracker *ACT) {
1448*f4bb2f0dSEaswaran Raman 
14497adc3a2bSChandler Carruth   // Cannot inline indirect calls.
14507adc3a2bSChandler Carruth   if (!Callee)
14517adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
14527adc3a2bSChandler Carruth 
14537adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
14547adc3a2bSChandler Carruth   // whenever possible.
14557adc3a2bSChandler Carruth   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
14567adc3a2bSChandler Carruth     if (isInlineViable(*Callee))
14577adc3a2bSChandler Carruth       return llvm::InlineCost::getAlways();
14587adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
14597adc3a2bSChandler Carruth   }
14607adc3a2bSChandler Carruth 
14617adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
14627adc3a2bSChandler Carruth   // always-inline attribute).
1463b9f7120eSEaswaran Raman   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee, CalleeTTI))
14647adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
14657adc3a2bSChandler Carruth 
14667adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
14677adc3a2bSChandler Carruth   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
14687adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
14697adc3a2bSChandler Carruth 
14707adc3a2bSChandler Carruth   // Don't inline functions which can be redefined at link-time to mean
14717adc3a2bSChandler Carruth   // something else.  Don't inline functions marked noinline or call sites
14727adc3a2bSChandler Carruth   // marked noinline.
14737adc3a2bSChandler Carruth   if (Callee->mayBeOverridden() ||
14747adc3a2bSChandler Carruth       Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
14757adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
14767adc3a2bSChandler Carruth 
14777adc3a2bSChandler Carruth   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
14787adc3a2bSChandler Carruth         << "...\n");
14797adc3a2bSChandler Carruth 
1480*f4bb2f0dSEaswaran Raman   CallAnalyzer CA(CalleeTTI, ACT, *Callee, DefaultThreshold, CS);
14817adc3a2bSChandler Carruth   bool ShouldInline = CA.analyzeCall(CS);
14827adc3a2bSChandler Carruth 
14837adc3a2bSChandler Carruth   DEBUG(CA.dump());
14847adc3a2bSChandler Carruth 
14857adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
14867adc3a2bSChandler Carruth   if (!ShouldInline && CA.getCost() < CA.getThreshold())
14877adc3a2bSChandler Carruth     return InlineCost::getNever();
14887adc3a2bSChandler Carruth   if (ShouldInline && CA.getCost() >= CA.getThreshold())
14897adc3a2bSChandler Carruth     return InlineCost::getAlways();
14907adc3a2bSChandler Carruth 
14917adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
14927adc3a2bSChandler Carruth }
14937adc3a2bSChandler Carruth 
1494b9f7120eSEaswaran Raman bool llvm::isInlineViable(Function &F) {
14957adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
14967adc3a2bSChandler Carruth   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
14977adc3a2bSChandler Carruth     // Disallow inlining of functions which contain indirect branches or
14987adc3a2bSChandler Carruth     // blockaddresses.
14997adc3a2bSChandler Carruth     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
15007adc3a2bSChandler Carruth       return false;
15017adc3a2bSChandler Carruth 
15025a82c916SDuncan P. N. Exon Smith     for (auto &II : *BI) {
15035a82c916SDuncan P. N. Exon Smith       CallSite CS(&II);
15047adc3a2bSChandler Carruth       if (!CS)
15057adc3a2bSChandler Carruth         continue;
15067adc3a2bSChandler Carruth 
15077adc3a2bSChandler Carruth       // Disallow recursive calls.
15087adc3a2bSChandler Carruth       if (&F == CS.getCalledFunction())
15097adc3a2bSChandler Carruth         return false;
15107adc3a2bSChandler Carruth 
15117adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
15127adc3a2bSChandler Carruth       // attributed as such.
15137adc3a2bSChandler Carruth       if (!ReturnsTwice && CS.isCall() &&
15147adc3a2bSChandler Carruth           cast<CallInst>(CS.getInstruction())->canReturnTwice())
15157adc3a2bSChandler Carruth         return false;
15167adc3a2bSChandler Carruth 
15177adc3a2bSChandler Carruth       // Disallow inlining functions that call @llvm.localescape. Doing this
15187adc3a2bSChandler Carruth       // correctly would require major changes to the inliner.
15197adc3a2bSChandler Carruth       if (CS.getCalledFunction() &&
15207adc3a2bSChandler Carruth           CS.getCalledFunction()->getIntrinsicID() ==
15217adc3a2bSChandler Carruth               llvm::Intrinsic::localescape)
15227adc3a2bSChandler Carruth         return false;
15237adc3a2bSChandler Carruth     }
15247adc3a2bSChandler Carruth   }
15257adc3a2bSChandler Carruth 
15267adc3a2bSChandler Carruth   return true;
15277adc3a2bSChandler Carruth }
1528