LLVM  mainline
InlineCost.cpp
Go to the documentation of this file.
00001 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements inline cost analysis.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Analysis/InlineCost.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/ADT/SetVector.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/AssumptionCache.h"
00021 #include "llvm/Analysis/CodeMetrics.h"
00022 #include "llvm/Analysis/ConstantFolding.h"
00023 #include "llvm/Analysis/InstructionSimplify.h"
00024 #include "llvm/Analysis/TargetTransformInfo.h"
00025 #include "llvm/IR/CallSite.h"
00026 #include "llvm/IR/CallingConv.h"
00027 #include "llvm/IR/DataLayout.h"
00028 #include "llvm/IR/GetElementPtrTypeIterator.h"
00029 #include "llvm/IR/GlobalAlias.h"
00030 #include "llvm/IR/InstVisitor.h"
00031 #include "llvm/IR/IntrinsicInst.h"
00032 #include "llvm/IR/Operator.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 
00036 using namespace llvm;
00037 
00038 #define DEBUG_TYPE "inline-cost"
00039 
00040 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
00041 
00042 namespace {
00043 
00044 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
00045   typedef InstVisitor<CallAnalyzer, bool> Base;
00046   friend class InstVisitor<CallAnalyzer, bool>;
00047 
00048   /// The TargetTransformInfo available for this compilation.
00049   const TargetTransformInfo &TTI;
00050 
00051   /// The cache of @llvm.assume intrinsics.
00052   AssumptionCacheTracker *ACT;
00053 
00054   // The called function.
00055   Function &F;
00056 
00057   int Threshold;
00058   int Cost;
00059 
00060   bool IsCallerRecursive;
00061   bool IsRecursiveCall;
00062   bool ExposesReturnsTwice;
00063   bool HasDynamicAlloca;
00064   bool ContainsNoDuplicateCall;
00065   bool HasReturn;
00066   bool HasIndirectBr;
00067 
00068   /// Number of bytes allocated statically by the callee.
00069   uint64_t AllocatedSize;
00070   unsigned NumInstructions, NumVectorInstructions;
00071   int FiftyPercentVectorBonus, TenPercentVectorBonus;
00072   int VectorBonus;
00073 
00074   // While we walk the potentially-inlined instructions, we build up and
00075   // maintain a mapping of simplified values specific to this callsite. The
00076   // idea is to propagate any special information we have about arguments to
00077   // this call through the inlinable section of the function, and account for
00078   // likely simplifications post-inlining. The most important aspect we track
00079   // is CFG altering simplifications -- when we prove a basic block dead, that
00080   // can cause dramatic shifts in the cost of inlining a function.
00081   DenseMap<Value *, Constant *> SimplifiedValues;
00082 
00083   // Keep track of the values which map back (through function arguments) to
00084   // allocas on the caller stack which could be simplified through SROA.
00085   DenseMap<Value *, Value *> SROAArgValues;
00086 
00087   // The mapping of caller Alloca values to their accumulated cost savings. If
00088   // we have to disable SROA for one of the allocas, this tells us how much
00089   // cost must be added.
00090   DenseMap<Value *, int> SROAArgCosts;
00091 
00092   // Keep track of values which map to a pointer base and constant offset.
00093   DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
00094 
00095   // Custom simplification helper routines.
00096   bool isAllocaDerivedArg(Value *V);
00097   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
00098                             DenseMap<Value *, int>::iterator &CostIt);
00099   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
00100   void disableSROA(Value *V);
00101   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
00102                           int InstructionCost);
00103   bool isGEPOffsetConstant(GetElementPtrInst &GEP);
00104   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
00105   bool simplifyCallSite(Function *F, CallSite CS);
00106   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
00107 
00108   // Custom analysis routines.
00109   bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
00110 
00111   // Disable several entry points to the visitor so we don't accidentally use
00112   // them by declaring but not defining them here.
00113   void visit(Module *);     void visit(Module &);
00114   void visit(Function *);   void visit(Function &);
00115   void visit(BasicBlock *); void visit(BasicBlock &);
00116 
00117   // Provide base case for our instruction visit.
00118   bool visitInstruction(Instruction &I);
00119 
00120   // Our visit overrides.
00121   bool visitAlloca(AllocaInst &I);
00122   bool visitPHI(PHINode &I);
00123   bool visitGetElementPtr(GetElementPtrInst &I);
00124   bool visitBitCast(BitCastInst &I);
00125   bool visitPtrToInt(PtrToIntInst &I);
00126   bool visitIntToPtr(IntToPtrInst &I);
00127   bool visitCastInst(CastInst &I);
00128   bool visitUnaryInstruction(UnaryInstruction &I);
00129   bool visitCmpInst(CmpInst &I);
00130   bool visitSub(BinaryOperator &I);
00131   bool visitBinaryOperator(BinaryOperator &I);
00132   bool visitLoad(LoadInst &I);
00133   bool visitStore(StoreInst &I);
00134   bool visitExtractValue(ExtractValueInst &I);
00135   bool visitInsertValue(InsertValueInst &I);
00136   bool visitCallSite(CallSite CS);
00137   bool visitReturnInst(ReturnInst &RI);
00138   bool visitBranchInst(BranchInst &BI);
00139   bool visitSwitchInst(SwitchInst &SI);
00140   bool visitIndirectBrInst(IndirectBrInst &IBI);
00141   bool visitResumeInst(ResumeInst &RI);
00142   bool visitUnreachableInst(UnreachableInst &I);
00143 
00144 public:
00145   CallAnalyzer(const TargetTransformInfo &TTI, AssumptionCacheTracker *ACT,
00146                Function &Callee, int Threshold)
00147       : TTI(TTI), ACT(ACT), F(Callee), Threshold(Threshold), Cost(0),
00148         IsCallerRecursive(false), IsRecursiveCall(false),
00149         ExposesReturnsTwice(false), HasDynamicAlloca(false),
00150         ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
00151         AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0),
00152         FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
00153         NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
00154         NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
00155         NumInstructionsSimplified(0), SROACostSavings(0),
00156         SROACostSavingsLost(0) {}
00157 
00158   bool analyzeCall(CallSite CS);
00159 
00160   int getThreshold() { return Threshold; }
00161   int getCost() { return Cost; }
00162 
00163   // Keep a bunch of stats about the cost savings found so we can print them
00164   // out when debugging.
00165   unsigned NumConstantArgs;
00166   unsigned NumConstantOffsetPtrArgs;
00167   unsigned NumAllocaArgs;
00168   unsigned NumConstantPtrCmps;
00169   unsigned NumConstantPtrDiffs;
00170   unsigned NumInstructionsSimplified;
00171   unsigned SROACostSavings;
00172   unsigned SROACostSavingsLost;
00173 
00174   void dump();
00175 };
00176 
00177 } // namespace
00178 
00179 /// \brief Test whether the given value is an Alloca-derived function argument.
00180 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
00181   return SROAArgValues.count(V);
00182 }
00183 
00184 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
00185 /// Returns false if V does not map to a SROA-candidate.
00186 bool CallAnalyzer::lookupSROAArgAndCost(
00187     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
00188   if (SROAArgValues.empty() || SROAArgCosts.empty())
00189     return false;
00190 
00191   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
00192   if (ArgIt == SROAArgValues.end())
00193     return false;
00194 
00195   Arg = ArgIt->second;
00196   CostIt = SROAArgCosts.find(Arg);
00197   return CostIt != SROAArgCosts.end();
00198 }
00199 
00200 /// \brief Disable SROA for the candidate marked by this cost iterator.
00201 ///
00202 /// This marks the candidate as no longer viable for SROA, and adds the cost
00203 /// savings associated with it back into the inline cost measurement.
00204 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
00205   // If we're no longer able to perform SROA we need to undo its cost savings
00206   // and prevent subsequent analysis.
00207   Cost += CostIt->second;
00208   SROACostSavings -= CostIt->second;
00209   SROACostSavingsLost += CostIt->second;
00210   SROAArgCosts.erase(CostIt);
00211 }
00212 
00213 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
00214 void CallAnalyzer::disableSROA(Value *V) {
00215   Value *SROAArg;
00216   DenseMap<Value *, int>::iterator CostIt;
00217   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
00218     disableSROA(CostIt);
00219 }
00220 
00221 /// \brief Accumulate the given cost for a particular SROA candidate.
00222 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
00223                                       int InstructionCost) {
00224   CostIt->second += InstructionCost;
00225   SROACostSavings += InstructionCost;
00226 }
00227 
00228 /// \brief Check whether a GEP's indices are all constant.
00229 ///
00230 /// Respects any simplified values known during the analysis of this callsite.
00231 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
00232   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
00233     if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
00234       return false;
00235 
00236   return true;
00237 }
00238 
00239 /// \brief Accumulate a constant GEP offset into an APInt if possible.
00240 ///
00241 /// Returns false if unable to compute the offset for any reason. Respects any
00242 /// simplified values known during the analysis of this callsite.
00243 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
00244   const DataLayout &DL = F.getParent()->getDataLayout();
00245   unsigned IntPtrWidth = DL.getPointerSizeInBits();
00246   assert(IntPtrWidth == Offset.getBitWidth());
00247 
00248   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
00249        GTI != GTE; ++GTI) {
00250     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
00251     if (!OpC)
00252       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
00253         OpC = dyn_cast<ConstantInt>(SimpleOp);
00254     if (!OpC)
00255       return false;
00256     if (OpC->isZero()) continue;
00257 
00258     // Handle a struct index, which adds its field offset to the pointer.
00259     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00260       unsigned ElementIdx = OpC->getZExtValue();
00261       const StructLayout *SL = DL.getStructLayout(STy);
00262       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
00263       continue;
00264     }
00265 
00266     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
00267     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
00268   }
00269   return true;
00270 }
00271 
00272 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
00273   // Check whether inlining will turn a dynamic alloca into a static
00274   // alloca, and handle that case.
00275   if (I.isArrayAllocation()) {
00276     if (Constant *Size = SimplifiedValues.lookup(I.getArraySize())) {
00277       ConstantInt *AllocSize = dyn_cast<ConstantInt>(Size);
00278       assert(AllocSize && "Allocation size not a constant int?");
00279       Type *Ty = I.getAllocatedType();
00280       AllocatedSize += Ty->getPrimitiveSizeInBits() * AllocSize->getZExtValue();
00281       return Base::visitAlloca(I);
00282     }
00283   }
00284 
00285   // Accumulate the allocated size.
00286   if (I.isStaticAlloca()) {
00287     const DataLayout &DL = F.getParent()->getDataLayout();
00288     Type *Ty = I.getAllocatedType();
00289     AllocatedSize += DL.getTypeAllocSize(Ty);
00290   }
00291 
00292   // We will happily inline static alloca instructions.
00293   if (I.isStaticAlloca())
00294     return Base::visitAlloca(I);
00295 
00296   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
00297   // a variety of reasons, and so we would like to not inline them into
00298   // functions which don't currently have a dynamic alloca. This simply
00299   // disables inlining altogether in the presence of a dynamic alloca.
00300   HasDynamicAlloca = true;
00301   return false;
00302 }
00303 
00304 bool CallAnalyzer::visitPHI(PHINode &I) {
00305   // FIXME: We should potentially be tracking values through phi nodes,
00306   // especially when they collapse to a single value due to deleted CFG edges
00307   // during inlining.
00308 
00309   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
00310   // though we don't want to propagate it's bonuses. The idea is to disable
00311   // SROA if it *might* be used in an inappropriate manner.
00312 
00313   // Phi nodes are always zero-cost.
00314   return true;
00315 }
00316 
00317 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
00318   Value *SROAArg;
00319   DenseMap<Value *, int>::iterator CostIt;
00320   bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
00321                                             SROAArg, CostIt);
00322 
00323   // Try to fold GEPs of constant-offset call site argument pointers. This
00324   // requires target data and inbounds GEPs.
00325   if (I.isInBounds()) {
00326     // Check if we have a base + offset for the pointer.
00327     Value *Ptr = I.getPointerOperand();
00328     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
00329     if (BaseAndOffset.first) {
00330       // Check if the offset of this GEP is constant, and if so accumulate it
00331       // into Offset.
00332       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
00333         // Non-constant GEPs aren't folded, and disable SROA.
00334         if (SROACandidate)
00335           disableSROA(CostIt);
00336         return false;
00337       }
00338 
00339       // Add the result as a new mapping to Base + Offset.
00340       ConstantOffsetPtrs[&I] = BaseAndOffset;
00341 
00342       // Also handle SROA candidates here, we already know that the GEP is
00343       // all-constant indexed.
00344       if (SROACandidate)
00345         SROAArgValues[&I] = SROAArg;
00346 
00347       return true;
00348     }
00349   }
00350 
00351   if (isGEPOffsetConstant(I)) {
00352     if (SROACandidate)
00353       SROAArgValues[&I] = SROAArg;
00354 
00355     // Constant GEPs are modeled as free.
00356     return true;
00357   }
00358 
00359   // Variable GEPs will require math and will disable SROA.
00360   if (SROACandidate)
00361     disableSROA(CostIt);
00362   return false;
00363 }
00364 
00365 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
00366   // Propagate constants through bitcasts.
00367   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
00368   if (!COp)
00369     COp = SimplifiedValues.lookup(I.getOperand(0));
00370   if (COp)
00371     if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
00372       SimplifiedValues[&I] = C;
00373       return true;
00374     }
00375 
00376   // Track base/offsets through casts
00377   std::pair<Value *, APInt> BaseAndOffset
00378     = ConstantOffsetPtrs.lookup(I.getOperand(0));
00379   // Casts don't change the offset, just wrap it up.
00380   if (BaseAndOffset.first)
00381     ConstantOffsetPtrs[&I] = BaseAndOffset;
00382 
00383   // Also look for SROA candidates here.
00384   Value *SROAArg;
00385   DenseMap<Value *, int>::iterator CostIt;
00386   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
00387     SROAArgValues[&I] = SROAArg;
00388 
00389   // Bitcasts are always zero cost.
00390   return true;
00391 }
00392 
00393 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
00394   // Propagate constants through ptrtoint.
00395   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
00396   if (!COp)
00397     COp = SimplifiedValues.lookup(I.getOperand(0));
00398   if (COp)
00399     if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
00400       SimplifiedValues[&I] = C;
00401       return true;
00402     }
00403 
00404   // Track base/offset pairs when converted to a plain integer provided the
00405   // integer is large enough to represent the pointer.
00406   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
00407   const DataLayout &DL = F.getParent()->getDataLayout();
00408   if (IntegerSize >= DL.getPointerSizeInBits()) {
00409     std::pair<Value *, APInt> BaseAndOffset
00410       = ConstantOffsetPtrs.lookup(I.getOperand(0));
00411     if (BaseAndOffset.first)
00412       ConstantOffsetPtrs[&I] = BaseAndOffset;
00413   }
00414 
00415   // This is really weird. Technically, ptrtoint will disable SROA. However,
00416   // unless that ptrtoint is *used* somewhere in the live basic blocks after
00417   // inlining, it will be nuked, and SROA should proceed. All of the uses which
00418   // would block SROA would also block SROA if applied directly to a pointer,
00419   // and so we can just add the integer in here. The only places where SROA is
00420   // preserved either cannot fire on an integer, or won't in-and-of themselves
00421   // disable SROA (ext) w/o some later use that we would see and disable.
00422   Value *SROAArg;
00423   DenseMap<Value *, int>::iterator CostIt;
00424   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
00425     SROAArgValues[&I] = SROAArg;
00426 
00427   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
00428 }
00429 
00430 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
00431   // Propagate constants through ptrtoint.
00432   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
00433   if (!COp)
00434     COp = SimplifiedValues.lookup(I.getOperand(0));
00435   if (COp)
00436     if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
00437       SimplifiedValues[&I] = C;
00438       return true;
00439     }
00440 
00441   // Track base/offset pairs when round-tripped through a pointer without
00442   // modifications provided the integer is not too large.
00443   Value *Op = I.getOperand(0);
00444   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
00445   const DataLayout &DL = F.getParent()->getDataLayout();
00446   if (IntegerSize <= DL.getPointerSizeInBits()) {
00447     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
00448     if (BaseAndOffset.first)
00449       ConstantOffsetPtrs[&I] = BaseAndOffset;
00450   }
00451 
00452   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
00453   Value *SROAArg;
00454   DenseMap<Value *, int>::iterator CostIt;
00455   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
00456     SROAArgValues[&I] = SROAArg;
00457 
00458   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
00459 }
00460 
00461 bool CallAnalyzer::visitCastInst(CastInst &I) {
00462   // Propagate constants through ptrtoint.
00463   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
00464   if (!COp)
00465     COp = SimplifiedValues.lookup(I.getOperand(0));
00466   if (COp)
00467     if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
00468       SimplifiedValues[&I] = C;
00469       return true;
00470     }
00471 
00472   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
00473   disableSROA(I.getOperand(0));
00474 
00475   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
00476 }
00477 
00478 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
00479   Value *Operand = I.getOperand(0);
00480   Constant *COp = dyn_cast<Constant>(Operand);
00481   if (!COp)
00482     COp = SimplifiedValues.lookup(Operand);
00483   if (COp) {
00484     const DataLayout &DL = F.getParent()->getDataLayout();
00485     if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
00486                                                COp, DL)) {
00487       SimplifiedValues[&I] = C;
00488       return true;
00489     }
00490   }
00491 
00492   // Disable any SROA on the argument to arbitrary unary operators.
00493   disableSROA(Operand);
00494 
00495   return false;
00496 }
00497 
00498 bool CallAnalyzer::visitCmpInst(CmpInst &I) {
00499   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00500   // First try to handle simplified comparisons.
00501   if (!isa<Constant>(LHS))
00502     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
00503       LHS = SimpleLHS;
00504   if (!isa<Constant>(RHS))
00505     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
00506       RHS = SimpleRHS;
00507   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
00508     if (Constant *CRHS = dyn_cast<Constant>(RHS))
00509       if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
00510         SimplifiedValues[&I] = C;
00511         return true;
00512       }
00513   }
00514 
00515   if (I.getOpcode() == Instruction::FCmp)
00516     return false;
00517 
00518   // Otherwise look for a comparison between constant offset pointers with
00519   // a common base.
00520   Value *LHSBase, *RHSBase;
00521   APInt LHSOffset, RHSOffset;
00522   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
00523   if (LHSBase) {
00524     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
00525     if (RHSBase && LHSBase == RHSBase) {
00526       // We have common bases, fold the icmp to a constant based on the
00527       // offsets.
00528       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
00529       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
00530       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
00531         SimplifiedValues[&I] = C;
00532         ++NumConstantPtrCmps;
00533         return true;
00534       }
00535     }
00536   }
00537 
00538   // If the comparison is an equality comparison with null, we can simplify it
00539   // for any alloca-derived argument.
00540   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
00541     if (isAllocaDerivedArg(I.getOperand(0))) {
00542       // We can actually predict the result of comparisons between an
00543       // alloca-derived value and null. Note that this fires regardless of
00544       // SROA firing.
00545       bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
00546       SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
00547                                         : ConstantInt::getFalse(I.getType());
00548       return true;
00549     }
00550 
00551   // Finally check for SROA candidates in comparisons.
00552   Value *SROAArg;
00553   DenseMap<Value *, int>::iterator CostIt;
00554   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
00555     if (isa<ConstantPointerNull>(I.getOperand(1))) {
00556       accumulateSROACost(CostIt, InlineConstants::InstrCost);
00557       return true;
00558     }
00559 
00560     disableSROA(CostIt);
00561   }
00562 
00563   return false;
00564 }
00565 
00566 bool CallAnalyzer::visitSub(BinaryOperator &I) {
00567   // Try to handle a special case: we can fold computing the difference of two
00568   // constant-related pointers.
00569   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00570   Value *LHSBase, *RHSBase;
00571   APInt LHSOffset, RHSOffset;
00572   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
00573   if (LHSBase) {
00574     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
00575     if (RHSBase && LHSBase == RHSBase) {
00576       // We have common bases, fold the subtract to a constant based on the
00577       // offsets.
00578       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
00579       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
00580       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
00581         SimplifiedValues[&I] = C;
00582         ++NumConstantPtrDiffs;
00583         return true;
00584       }
00585     }
00586   }
00587 
00588   // Otherwise, fall back to the generic logic for simplifying and handling
00589   // instructions.
00590   return Base::visitSub(I);
00591 }
00592 
00593 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
00594   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00595   const DataLayout &DL = F.getParent()->getDataLayout();
00596   if (!isa<Constant>(LHS))
00597     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
00598       LHS = SimpleLHS;
00599   if (!isa<Constant>(RHS))
00600     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
00601       RHS = SimpleRHS;
00602   Value *SimpleV = nullptr;
00603   if (auto FI = dyn_cast<FPMathOperator>(&I))
00604     SimpleV =
00605         SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
00606   else
00607     SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
00608 
00609   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
00610     SimplifiedValues[&I] = C;
00611     return true;
00612   }
00613 
00614   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
00615   disableSROA(LHS);
00616   disableSROA(RHS);
00617 
00618   return false;
00619 }
00620 
00621 bool CallAnalyzer::visitLoad(LoadInst &I) {
00622   Value *SROAArg;
00623   DenseMap<Value *, int>::iterator CostIt;
00624   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
00625     if (I.isSimple()) {
00626       accumulateSROACost(CostIt, InlineConstants::InstrCost);
00627       return true;
00628     }
00629 
00630     disableSROA(CostIt);
00631   }
00632 
00633   return false;
00634 }
00635 
00636 bool CallAnalyzer::visitStore(StoreInst &I) {
00637   Value *SROAArg;
00638   DenseMap<Value *, int>::iterator CostIt;
00639   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
00640     if (I.isSimple()) {
00641       accumulateSROACost(CostIt, InlineConstants::InstrCost);
00642       return true;
00643     }
00644 
00645     disableSROA(CostIt);
00646   }
00647 
00648   return false;
00649 }
00650 
00651 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
00652   // Constant folding for extract value is trivial.
00653   Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
00654   if (!C)
00655     C = SimplifiedValues.lookup(I.getAggregateOperand());
00656   if (C) {
00657     SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
00658     return true;
00659   }
00660 
00661   // SROA can look through these but give them a cost.
00662   return false;
00663 }
00664 
00665 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
00666   // Constant folding for insert value is trivial.
00667   Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
00668   if (!AggC)
00669     AggC = SimplifiedValues.lookup(I.getAggregateOperand());
00670   Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
00671   if (!InsertedC)
00672     InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
00673   if (AggC && InsertedC) {
00674     SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
00675                                                         I.getIndices());
00676     return true;
00677   }
00678 
00679   // SROA can look through these but give them a cost.
00680   return false;
00681 }
00682 
00683 /// \brief Try to simplify a call site.
00684 ///
00685 /// Takes a concrete function and callsite and tries to actually simplify it by
00686 /// analyzing the arguments and call itself with instsimplify. Returns true if
00687 /// it has simplified the callsite to some other entity (a constant), making it
00688 /// free.
00689 bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
00690   // FIXME: Using the instsimplify logic directly for this is inefficient
00691   // because we have to continually rebuild the argument list even when no
00692   // simplifications can be performed. Until that is fixed with remapping
00693   // inside of instsimplify, directly constant fold calls here.
00694   if (!canConstantFoldCallTo(F))
00695     return false;
00696 
00697   // Try to re-map the arguments to constants.
00698   SmallVector<Constant *, 4> ConstantArgs;
00699   ConstantArgs.reserve(CS.arg_size());
00700   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
00701        I != E; ++I) {
00702     Constant *C = dyn_cast<Constant>(*I);
00703     if (!C)
00704       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
00705     if (!C)
00706       return false; // This argument doesn't map to a constant.
00707 
00708     ConstantArgs.push_back(C);
00709   }
00710   if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
00711     SimplifiedValues[CS.getInstruction()] = C;
00712     return true;
00713   }
00714 
00715   return false;
00716 }
00717 
00718 bool CallAnalyzer::visitCallSite(CallSite CS) {
00719   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
00720       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
00721     // This aborts the entire analysis.
00722     ExposesReturnsTwice = true;
00723     return false;
00724   }
00725   if (CS.isCall() &&
00726       cast<CallInst>(CS.getInstruction())->cannotDuplicate())
00727     ContainsNoDuplicateCall = true;
00728 
00729   if (Function *F = CS.getCalledFunction()) {
00730     // When we have a concrete function, first try to simplify it directly.
00731     if (simplifyCallSite(F, CS))
00732       return true;
00733 
00734     // Next check if it is an intrinsic we know about.
00735     // FIXME: Lift this into part of the InstVisitor.
00736     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
00737       switch (II->getIntrinsicID()) {
00738       default:
00739         return Base::visitCallSite(CS);
00740 
00741       case Intrinsic::memset:
00742       case Intrinsic::memcpy:
00743       case Intrinsic::memmove:
00744         // SROA can usually chew through these intrinsics, but they aren't free.
00745         return false;
00746       }
00747     }
00748 
00749     if (F == CS.getInstruction()->getParent()->getParent()) {
00750       // This flag will fully abort the analysis, so don't bother with anything
00751       // else.
00752       IsRecursiveCall = true;
00753       return false;
00754     }
00755 
00756     if (TTI.isLoweredToCall(F)) {
00757       // We account for the average 1 instruction per call argument setup
00758       // here.
00759       Cost += CS.arg_size() * InlineConstants::InstrCost;
00760 
00761       // Everything other than inline ASM will also have a significant cost
00762       // merely from making the call.
00763       if (!isa<InlineAsm>(CS.getCalledValue()))
00764         Cost += InlineConstants::CallPenalty;
00765     }
00766 
00767     return Base::visitCallSite(CS);
00768   }
00769 
00770   // Otherwise we're in a very special case -- an indirect function call. See
00771   // if we can be particularly clever about this.
00772   Value *Callee = CS.getCalledValue();
00773 
00774   // First, pay the price of the argument setup. We account for the average
00775   // 1 instruction per call argument setup here.
00776   Cost += CS.arg_size() * InlineConstants::InstrCost;
00777 
00778   // Next, check if this happens to be an indirect function call to a known
00779   // function in this inline context. If not, we've done all we can.
00780   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
00781   if (!F)
00782     return Base::visitCallSite(CS);
00783 
00784   // If we have a constant that we are calling as a function, we can peer
00785   // through it and see the function target. This happens not infrequently
00786   // during devirtualization and so we want to give it a hefty bonus for
00787   // inlining, but cap that bonus in the event that inlining wouldn't pan
00788   // out. Pretend to inline the function, with a custom threshold.
00789   CallAnalyzer CA(TTI, ACT, *F, InlineConstants::IndirectCallThreshold);
00790   if (CA.analyzeCall(CS)) {
00791     // We were able to inline the indirect call! Subtract the cost from the
00792     // bonus we want to apply, but don't go below zero.
00793     Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
00794   }
00795 
00796   return Base::visitCallSite(CS);
00797 }
00798 
00799 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
00800   // At least one return instruction will be free after inlining.
00801   bool Free = !HasReturn;
00802   HasReturn = true;
00803   return Free;
00804 }
00805 
00806 bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
00807   // We model unconditional branches as essentially free -- they really
00808   // shouldn't exist at all, but handling them makes the behavior of the
00809   // inliner more regular and predictable. Interestingly, conditional branches
00810   // which will fold away are also free.
00811   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
00812          dyn_cast_or_null<ConstantInt>(
00813              SimplifiedValues.lookup(BI.getCondition()));
00814 }
00815 
00816 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
00817   // We model unconditional switches as free, see the comments on handling
00818   // branches.
00819   if (isa<ConstantInt>(SI.getCondition()))
00820     return true;
00821   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
00822     if (isa<ConstantInt>(V))
00823       return true;
00824 
00825   // Otherwise, we need to accumulate a cost proportional to the number of
00826   // distinct successor blocks. This fan-out in the CFG cannot be represented
00827   // for free even if we can represent the core switch as a jumptable that
00828   // takes a single instruction.
00829   //
00830   // NB: We convert large switches which are just used to initialize large phi
00831   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
00832   // inlining those. It will prevent inlining in cases where the optimization
00833   // does not (yet) fire.
00834   SmallPtrSet<BasicBlock *, 8> SuccessorBlocks;
00835   SuccessorBlocks.insert(SI.getDefaultDest());
00836   for (auto I = SI.case_begin(), E = SI.case_end(); I != E; ++I)
00837     SuccessorBlocks.insert(I.getCaseSuccessor());
00838   // Add cost corresponding to the number of distinct destinations. The first
00839   // we model as free because of fallthrough.
00840   Cost += (SuccessorBlocks.size() - 1) * InlineConstants::InstrCost;
00841   return false;
00842 }
00843 
00844 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
00845   // We never want to inline functions that contain an indirectbr.  This is
00846   // incorrect because all the blockaddress's (in static global initializers
00847   // for example) would be referring to the original function, and this
00848   // indirect jump would jump from the inlined copy of the function into the
00849   // original function which is extremely undefined behavior.
00850   // FIXME: This logic isn't really right; we can safely inline functions with
00851   // indirectbr's as long as no other function or global references the
00852   // blockaddress of a block within the current function.
00853   HasIndirectBr = true;
00854   return false;
00855 }
00856 
00857 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
00858   // FIXME: It's not clear that a single instruction is an accurate model for
00859   // the inline cost of a resume instruction.
00860   return false;
00861 }
00862 
00863 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
00864   // FIXME: It might be reasonably to discount the cost of instructions leading
00865   // to unreachable as they have the lowest possible impact on both runtime and
00866   // code size.
00867   return true; // No actual code is needed for unreachable.
00868 }
00869 
00870 bool CallAnalyzer::visitInstruction(Instruction &I) {
00871   // Some instructions are free. All of the free intrinsics can also be
00872   // handled by SROA, etc.
00873   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
00874     return true;
00875 
00876   // We found something we don't understand or can't handle. Mark any SROA-able
00877   // values in the operand list as no longer viable.
00878   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
00879     disableSROA(*OI);
00880 
00881   return false;
00882 }
00883 
00884 
00885 /// \brief Analyze a basic block for its contribution to the inline cost.
00886 ///
00887 /// This method walks the analyzer over every instruction in the given basic
00888 /// block and accounts for their cost during inlining at this callsite. It
00889 /// aborts early if the threshold has been exceeded or an impossible to inline
00890 /// construct has been detected. It returns false if inlining is no longer
00891 /// viable, and true if inlining remains viable.
00892 bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
00893                                 SmallPtrSetImpl<const Value *> &EphValues) {
00894   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00895     // FIXME: Currently, the number of instructions in a function regardless of
00896     // our ability to simplify them during inline to constants or dead code,
00897     // are actually used by the vector bonus heuristic. As long as that's true,
00898     // we have to special case debug intrinsics here to prevent differences in
00899     // inlining due to debug symbols. Eventually, the number of unsimplified
00900     // instructions shouldn't factor into the cost computation, but until then,
00901     // hack around it here.
00902     if (isa<DbgInfoIntrinsic>(I))
00903       continue;
00904 
00905     // Skip ephemeral values.
00906     if (EphValues.count(I))
00907       continue;
00908 
00909     ++NumInstructions;
00910     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
00911       ++NumVectorInstructions;
00912 
00913     // If the instruction is floating point, and the target says this operation is
00914     // expensive or the function has the "use-soft-float" attribute, this may
00915     // eventually become a library call.  Treat the cost as such.
00916     if (I->getType()->isFloatingPointTy()) {
00917       bool hasSoftFloatAttr = false;
00918 
00919       // If the function has the "use-soft-float" attribute, mark it as expensive.
00920       if (F.hasFnAttribute("use-soft-float")) {
00921         Attribute Attr = F.getFnAttribute("use-soft-float");
00922         StringRef Val = Attr.getValueAsString();
00923         if (Val == "true")
00924           hasSoftFloatAttr = true;
00925       }
00926 
00927       if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
00928           hasSoftFloatAttr)
00929         Cost += InlineConstants::CallPenalty;
00930     }
00931 
00932     // If the instruction simplified to a constant, there is no cost to this
00933     // instruction. Visit the instructions using our InstVisitor to account for
00934     // all of the per-instruction logic. The visit tree returns true if we
00935     // consumed the instruction in any way, and false if the instruction's base
00936     // cost should count against inlining.
00937     if (Base::visit(I))
00938       ++NumInstructionsSimplified;
00939     else
00940       Cost += InlineConstants::InstrCost;
00941 
00942     // If the visit this instruction detected an uninlinable pattern, abort.
00943     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
00944         HasIndirectBr)
00945       return false;
00946 
00947     // If the caller is a recursive function then we don't want to inline
00948     // functions which allocate a lot of stack space because it would increase
00949     // the caller stack usage dramatically.
00950     if (IsCallerRecursive &&
00951         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
00952       return false;
00953 
00954     if (NumVectorInstructions > NumInstructions/2)
00955       VectorBonus = FiftyPercentVectorBonus;
00956     else if (NumVectorInstructions > NumInstructions/10)
00957       VectorBonus = TenPercentVectorBonus;
00958     else
00959       VectorBonus = 0;
00960 
00961     // Check if we've past the threshold so we don't spin in huge basic
00962     // blocks that will never inline.
00963     if (Cost > (Threshold + VectorBonus))
00964       return false;
00965   }
00966 
00967   return true;
00968 }
00969 
00970 /// \brief Compute the base pointer and cumulative constant offsets for V.
00971 ///
00972 /// This strips all constant offsets off of V, leaving it the base pointer, and
00973 /// accumulates the total constant offset applied in the returned constant. It
00974 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
00975 /// no constant offsets applied.
00976 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
00977   if (!V->getType()->isPointerTy())
00978     return nullptr;
00979 
00980   const DataLayout &DL = F.getParent()->getDataLayout();
00981   unsigned IntPtrWidth = DL.getPointerSizeInBits();
00982   APInt Offset = APInt::getNullValue(IntPtrWidth);
00983 
00984   // Even though we don't look through PHI nodes, we could be called on an
00985   // instruction in an unreachable block, which may be on a cycle.
00986   SmallPtrSet<Value *, 4> Visited;
00987   Visited.insert(V);
00988   do {
00989     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00990       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
00991         return nullptr;
00992       V = GEP->getPointerOperand();
00993     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
00994       V = cast<Operator>(V)->getOperand(0);
00995     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00996       if (GA->mayBeOverridden())
00997         break;
00998       V = GA->getAliasee();
00999     } else {
01000       break;
01001     }
01002     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
01003   } while (Visited.insert(V).second);
01004 
01005   Type *IntPtrTy = DL.getIntPtrType(V->getContext());
01006   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
01007 }
01008 
01009 /// \brief Analyze a call site for potential inlining.
01010 ///
01011 /// Returns true if inlining this call is viable, and false if it is not
01012 /// viable. It computes the cost and adjusts the threshold based on numerous
01013 /// factors and heuristics. If this method returns false but the computed cost
01014 /// is below the computed threshold, then inlining was forcibly disabled by
01015 /// some artifact of the routine.
01016 bool CallAnalyzer::analyzeCall(CallSite CS) {
01017   ++NumCallsAnalyzed;
01018 
01019   // Track whether the post-inlining function would have more than one basic
01020   // block. A single basic block is often intended for inlining. Balloon the
01021   // threshold by 50% until we pass the single-BB phase.
01022   bool SingleBB = true;
01023   int SingleBBBonus = Threshold / 2;
01024   Threshold += SingleBBBonus;
01025 
01026   // Perform some tweaks to the cost and threshold based on the direct
01027   // callsite information.
01028 
01029   // We want to more aggressively inline vector-dense kernels, so up the
01030   // threshold, and we'll lower it if the % of vector instructions gets too
01031   // low.
01032   assert(NumInstructions == 0);
01033   assert(NumVectorInstructions == 0);
01034   FiftyPercentVectorBonus = Threshold;
01035   TenPercentVectorBonus = Threshold / 2;
01036   const DataLayout &DL = F.getParent()->getDataLayout();
01037 
01038   // Give out bonuses per argument, as the instructions setting them up will
01039   // be gone after inlining.
01040   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
01041     if (CS.isByValArgument(I)) {
01042       // We approximate the number of loads and stores needed by dividing the
01043       // size of the byval type by the target's pointer size.
01044       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
01045       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
01046       unsigned PointerSize = DL.getPointerSizeInBits();
01047       // Ceiling division.
01048       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
01049 
01050       // If it generates more than 8 stores it is likely to be expanded as an
01051       // inline memcpy so we take that as an upper bound. Otherwise we assume
01052       // one load and one store per word copied.
01053       // FIXME: The maxStoresPerMemcpy setting from the target should be used
01054       // here instead of a magic number of 8, but it's not available via
01055       // DataLayout.
01056       NumStores = std::min(NumStores, 8U);
01057 
01058       Cost -= 2 * NumStores * InlineConstants::InstrCost;
01059     } else {
01060       // For non-byval arguments subtract off one instruction per call
01061       // argument.
01062       Cost -= InlineConstants::InstrCost;
01063     }
01064   }
01065 
01066   // If there is only one call of the function, and it has internal linkage,
01067   // the cost of inlining it drops dramatically.
01068   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
01069     &F == CS.getCalledFunction();
01070   if (OnlyOneCallAndLocalLinkage)
01071     Cost += InlineConstants::LastCallToStaticBonus;
01072 
01073   // If the instruction after the call, or if the normal destination of the
01074   // invoke is an unreachable instruction, the function is noreturn. As such,
01075   // there is little point in inlining this unless there is literally zero
01076   // cost.
01077   Instruction *Instr = CS.getInstruction();
01078   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
01079     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
01080       Threshold = 1;
01081   } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
01082     Threshold = 1;
01083 
01084   // If this function uses the coldcc calling convention, prefer not to inline
01085   // it.
01086   if (F.getCallingConv() == CallingConv::Cold)
01087     Cost += InlineConstants::ColdccPenalty;
01088 
01089   // Check if we're done. This can happen due to bonuses and penalties.
01090   if (Cost > Threshold)
01091     return false;
01092 
01093   if (F.empty())
01094     return true;
01095 
01096   Function *Caller = CS.getInstruction()->getParent()->getParent();
01097   // Check if the caller function is recursive itself.
01098   for (User *U : Caller->users()) {
01099     CallSite Site(U);
01100     if (!Site)
01101       continue;
01102     Instruction *I = Site.getInstruction();
01103     if (I->getParent()->getParent() == Caller) {
01104       IsCallerRecursive = true;
01105       break;
01106     }
01107   }
01108 
01109   // Populate our simplified values by mapping from function arguments to call
01110   // arguments with known important simplifications.
01111   CallSite::arg_iterator CAI = CS.arg_begin();
01112   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
01113        FAI != FAE; ++FAI, ++CAI) {
01114     assert(CAI != CS.arg_end());
01115     if (Constant *C = dyn_cast<Constant>(CAI))
01116       SimplifiedValues[FAI] = C;
01117 
01118     Value *PtrArg = *CAI;
01119     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
01120       ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
01121 
01122       // We can SROA any pointer arguments derived from alloca instructions.
01123       if (isa<AllocaInst>(PtrArg)) {
01124         SROAArgValues[FAI] = PtrArg;
01125         SROAArgCosts[PtrArg] = 0;
01126       }
01127     }
01128   }
01129   NumConstantArgs = SimplifiedValues.size();
01130   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
01131   NumAllocaArgs = SROAArgValues.size();
01132 
01133   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
01134   // the ephemeral values multiple times (and they're completely determined by
01135   // the callee, so this is purely duplicate work).
01136   SmallPtrSet<const Value *, 32> EphValues;
01137   CodeMetrics::collectEphemeralValues(&F, &ACT->getAssumptionCache(F), EphValues);
01138 
01139   // The worklist of live basic blocks in the callee *after* inlining. We avoid
01140   // adding basic blocks of the callee which can be proven to be dead for this
01141   // particular call site in order to get more accurate cost estimates. This
01142   // requires a somewhat heavyweight iteration pattern: we need to walk the
01143   // basic blocks in a breadth-first order as we insert live successors. To
01144   // accomplish this, prioritizing for small iterations because we exit after
01145   // crossing our threshold, we use a small-size optimized SetVector.
01146   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
01147                                   SmallPtrSet<BasicBlock *, 16> > BBSetVector;
01148   BBSetVector BBWorklist;
01149   BBWorklist.insert(&F.getEntryBlock());
01150   // Note that we *must not* cache the size, this loop grows the worklist.
01151   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
01152     // Bail out the moment we cross the threshold. This means we'll under-count
01153     // the cost, but only when undercounting doesn't matter.
01154     if (Cost > (Threshold + VectorBonus))
01155       break;
01156 
01157     BasicBlock *BB = BBWorklist[Idx];
01158     if (BB->empty())
01159       continue;
01160 
01161     // Disallow inlining a blockaddress. A blockaddress only has defined
01162     // behavior for an indirect branch in the same function, and we do not
01163     // currently support inlining indirect branches. But, the inliner may not
01164     // see an indirect branch that ends up being dead code at a particular call
01165     // site. If the blockaddress escapes the function, e.g., via a global
01166     // variable, inlining may lead to an invalid cross-function reference.
01167     if (BB->hasAddressTaken())
01168       return false;
01169 
01170     // Analyze the cost of this block. If we blow through the threshold, this
01171     // returns false, and we can bail on out.
01172     if (!analyzeBlock(BB, EphValues)) {
01173       if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
01174           HasIndirectBr)
01175         return false;
01176 
01177       // If the caller is a recursive function then we don't want to inline
01178       // functions which allocate a lot of stack space because it would increase
01179       // the caller stack usage dramatically.
01180       if (IsCallerRecursive &&
01181           AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
01182         return false;
01183 
01184       break;
01185     }
01186 
01187     TerminatorInst *TI = BB->getTerminator();
01188 
01189     // Add in the live successors by first checking whether we have terminator
01190     // that may be simplified based on the values simplified by this call.
01191     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
01192       if (BI->isConditional()) {
01193         Value *Cond = BI->getCondition();
01194         if (ConstantInt *SimpleCond
01195               = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
01196           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
01197           continue;
01198         }
01199       }
01200     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
01201       Value *Cond = SI->getCondition();
01202       if (ConstantInt *SimpleCond
01203             = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
01204         BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
01205         continue;
01206       }
01207     }
01208 
01209     // If we're unable to select a particular successor, just count all of
01210     // them.
01211     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
01212          ++TIdx)
01213       BBWorklist.insert(TI->getSuccessor(TIdx));
01214 
01215     // If we had any successors at this point, than post-inlining is likely to
01216     // have them as well. Note that we assume any basic blocks which existed
01217     // due to branches or switches which folded above will also fold after
01218     // inlining.
01219     if (SingleBB && TI->getNumSuccessors() > 1) {
01220       // Take off the bonus we applied to the threshold.
01221       Threshold -= SingleBBBonus;
01222       SingleBB = false;
01223     }
01224   }
01225 
01226   // If this is a noduplicate call, we can still inline as long as
01227   // inlining this would cause the removal of the caller (so the instruction
01228   // is not actually duplicated, just moved).
01229   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
01230     return false;
01231 
01232   Threshold += VectorBonus;
01233 
01234   return Cost < Threshold;
01235 }
01236 
01237 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01238 /// \brief Dump stats about this call's analysis.
01239 void CallAnalyzer::dump() {
01240 #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
01241   DEBUG_PRINT_STAT(NumConstantArgs);
01242   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
01243   DEBUG_PRINT_STAT(NumAllocaArgs);
01244   DEBUG_PRINT_STAT(NumConstantPtrCmps);
01245   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
01246   DEBUG_PRINT_STAT(NumInstructionsSimplified);
01247   DEBUG_PRINT_STAT(SROACostSavings);
01248   DEBUG_PRINT_STAT(SROACostSavingsLost);
01249   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
01250   DEBUG_PRINT_STAT(Cost);
01251   DEBUG_PRINT_STAT(Threshold);
01252   DEBUG_PRINT_STAT(VectorBonus);
01253 #undef DEBUG_PRINT_STAT
01254 }
01255 #endif
01256 
01257 INITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
01258                       true, true)
01259 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
01260 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
01261 INITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
01262                     true, true)
01263 
01264 char InlineCostAnalysis::ID = 0;
01265 
01266 InlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID) {}
01267 
01268 InlineCostAnalysis::~InlineCostAnalysis() {}
01269 
01270 void InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
01271   AU.setPreservesAll();
01272   AU.addRequired<AssumptionCacheTracker>();
01273   AU.addRequired<TargetTransformInfoWrapperPass>();
01274   CallGraphSCCPass::getAnalysisUsage(AU);
01275 }
01276 
01277 bool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) {
01278   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
01279   ACT = &getAnalysis<AssumptionCacheTracker>();
01280   return false;
01281 }
01282 
01283 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) {
01284   return getInlineCost(CS, CS.getCalledFunction(), Threshold);
01285 }
01286 
01287 /// \brief Test that two functions either have or have not the given attribute
01288 ///        at the same time.
01289 static bool attributeMatches(Function *F1, Function *F2,
01290                              Attribute::AttrKind Attr) {
01291   return F1->hasFnAttribute(Attr) == F2->hasFnAttribute(Attr);
01292 }
01293 
01294 /// \brief Test that there are no attribute conflicts between Caller and Callee
01295 ///        that prevent inlining.
01296 static bool functionsHaveCompatibleAttributes(Function *Caller,
01297                                               Function *Callee) {
01298   return attributeMatches(Caller, Callee, Attribute::SanitizeAddress) &&
01299          attributeMatches(Caller, Callee, Attribute::SanitizeMemory) &&
01300          attributeMatches(Caller, Callee, Attribute::SanitizeThread);
01301 }
01302 
01303 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
01304                                              int Threshold) {
01305   // Cannot inline indirect calls.
01306   if (!Callee)
01307     return llvm::InlineCost::getNever();
01308 
01309   // Calls to functions with always-inline attributes should be inlined
01310   // whenever possible.
01311   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
01312     if (isInlineViable(*Callee))
01313       return llvm::InlineCost::getAlways();
01314     return llvm::InlineCost::getNever();
01315   }
01316 
01317   // Never inline functions with conflicting attributes (unless callee has
01318   // always-inline attribute).
01319   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee))
01320     return llvm::InlineCost::getNever();
01321 
01322   // Don't inline this call if the caller has the optnone attribute.
01323   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
01324     return llvm::InlineCost::getNever();
01325 
01326   // Don't inline functions which can be redefined at link-time to mean
01327   // something else.  Don't inline functions marked noinline or call sites
01328   // marked noinline.
01329   if (Callee->mayBeOverridden() ||
01330       Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
01331     return llvm::InlineCost::getNever();
01332 
01333   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
01334         << "...\n");
01335 
01336   CallAnalyzer CA(TTIWP->getTTI(*Callee), ACT, *Callee, Threshold);
01337   bool ShouldInline = CA.analyzeCall(CS);
01338 
01339   DEBUG(CA.dump());
01340 
01341   // Check if there was a reason to force inlining or no inlining.
01342   if (!ShouldInline && CA.getCost() < CA.getThreshold())
01343     return InlineCost::getNever();
01344   if (ShouldInline && CA.getCost() >= CA.getThreshold())
01345     return InlineCost::getAlways();
01346 
01347   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
01348 }
01349 
01350 bool InlineCostAnalysis::isInlineViable(Function &F) {
01351   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
01352   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
01353     // Disallow inlining of functions which contain indirect branches or
01354     // blockaddresses.
01355     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
01356       return false;
01357 
01358     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
01359          ++II) {
01360       CallSite CS(II);
01361       if (!CS)
01362         continue;
01363 
01364       // Disallow recursive calls.
01365       if (&F == CS.getCalledFunction())
01366         return false;
01367 
01368       // Disallow calls which expose returns-twice to a function not previously
01369       // attributed as such.
01370       if (!ReturnsTwice && CS.isCall() &&
01371           cast<CallInst>(CS.getInstruction())->canReturnTwice())
01372         return false;
01373     }
01374   }
01375 
01376   return true;
01377 }