1249259Sdim//===- InlineCost.cpp - Cost analysis for inliner -------------------------===// 2249259Sdim// 3249259Sdim// The LLVM Compiler Infrastructure 4249259Sdim// 5249259Sdim// This file is distributed under the University of Illinois Open Source 6249259Sdim// License. See LICENSE.TXT for details. 7249259Sdim// 8249259Sdim//===----------------------------------------------------------------------===// 9249259Sdim// 10249259Sdim// This file implements inline cost analysis. 11249259Sdim// 12249259Sdim//===----------------------------------------------------------------------===// 13249259Sdim 14249259Sdim#define DEBUG_TYPE "inline-cost" 15249259Sdim#include "llvm/Analysis/InlineCost.h" 16249259Sdim#include "llvm/ADT/STLExtras.h" 17249259Sdim#include "llvm/ADT/SetVector.h" 18249259Sdim#include "llvm/ADT/SmallPtrSet.h" 19249259Sdim#include "llvm/ADT/SmallVector.h" 20249259Sdim#include "llvm/ADT/Statistic.h" 21249259Sdim#include "llvm/Analysis/ConstantFolding.h" 22249259Sdim#include "llvm/Analysis/InstructionSimplify.h" 23249259Sdim#include "llvm/Analysis/TargetTransformInfo.h" 24249259Sdim#include "llvm/IR/CallingConv.h" 25249259Sdim#include "llvm/IR/DataLayout.h" 26249259Sdim#include "llvm/IR/GlobalAlias.h" 27249259Sdim#include "llvm/IR/IntrinsicInst.h" 28249259Sdim#include "llvm/IR/Operator.h" 29249259Sdim#include "llvm/InstVisitor.h" 30249259Sdim#include "llvm/Support/CallSite.h" 31249259Sdim#include "llvm/Support/Debug.h" 32249259Sdim#include "llvm/Support/GetElementPtrTypeIterator.h" 33249259Sdim#include "llvm/Support/raw_ostream.h" 34249259Sdim 35249259Sdimusing namespace llvm; 36249259Sdim 37249259SdimSTATISTIC(NumCallsAnalyzed, "Number of call sites analyzed"); 38249259Sdim 39249259Sdimnamespace { 40249259Sdim 41249259Sdimclass CallAnalyzer : public InstVisitor<CallAnalyzer, bool> { 42249259Sdim typedef InstVisitor<CallAnalyzer, bool> Base; 43249259Sdim friend class InstVisitor<CallAnalyzer, bool>; 44249259Sdim 45249259Sdim // DataLayout if available, or null. 46249259Sdim const DataLayout *const TD; 47249259Sdim 48249259Sdim /// The TargetTransformInfo available for this compilation. 49249259Sdim const TargetTransformInfo &TTI; 50249259Sdim 51249259Sdim // The called function. 52249259Sdim Function &F; 53249259Sdim 54249259Sdim int Threshold; 55249259Sdim int Cost; 56249259Sdim 57249259Sdim bool IsCallerRecursive; 58249259Sdim bool IsRecursiveCall; 59249259Sdim bool ExposesReturnsTwice; 60249259Sdim bool HasDynamicAlloca; 61249259Sdim bool ContainsNoDuplicateCall; 62263508Sdim bool HasReturn; 63263508Sdim bool HasIndirectBr; 64249259Sdim 65249259Sdim /// Number of bytes allocated statically by the callee. 66249259Sdim uint64_t AllocatedSize; 67249259Sdim unsigned NumInstructions, NumVectorInstructions; 68249259Sdim int FiftyPercentVectorBonus, TenPercentVectorBonus; 69249259Sdim int VectorBonus; 70249259Sdim 71249259Sdim // While we walk the potentially-inlined instructions, we build up and 72249259Sdim // maintain a mapping of simplified values specific to this callsite. The 73249259Sdim // idea is to propagate any special information we have about arguments to 74249259Sdim // this call through the inlinable section of the function, and account for 75249259Sdim // likely simplifications post-inlining. The most important aspect we track 76249259Sdim // is CFG altering simplifications -- when we prove a basic block dead, that 77249259Sdim // can cause dramatic shifts in the cost of inlining a function. 78249259Sdim DenseMap<Value *, Constant *> SimplifiedValues; 79249259Sdim 80249259Sdim // Keep track of the values which map back (through function arguments) to 81249259Sdim // allocas on the caller stack which could be simplified through SROA. 82249259Sdim DenseMap<Value *, Value *> SROAArgValues; 83249259Sdim 84249259Sdim // The mapping of caller Alloca values to their accumulated cost savings. If 85249259Sdim // we have to disable SROA for one of the allocas, this tells us how much 86249259Sdim // cost must be added. 87249259Sdim DenseMap<Value *, int> SROAArgCosts; 88249259Sdim 89249259Sdim // Keep track of values which map to a pointer base and constant offset. 90249259Sdim DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs; 91249259Sdim 92249259Sdim // Custom simplification helper routines. 93249259Sdim bool isAllocaDerivedArg(Value *V); 94249259Sdim bool lookupSROAArgAndCost(Value *V, Value *&Arg, 95249259Sdim DenseMap<Value *, int>::iterator &CostIt); 96249259Sdim void disableSROA(DenseMap<Value *, int>::iterator CostIt); 97249259Sdim void disableSROA(Value *V); 98249259Sdim void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt, 99249259Sdim int InstructionCost); 100249259Sdim bool handleSROACandidate(bool IsSROAValid, 101249259Sdim DenseMap<Value *, int>::iterator CostIt, 102249259Sdim int InstructionCost); 103249259Sdim bool isGEPOffsetConstant(GetElementPtrInst &GEP); 104249259Sdim bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset); 105249259Sdim bool simplifyCallSite(Function *F, CallSite CS); 106249259Sdim ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V); 107249259Sdim 108249259Sdim // Custom analysis routines. 109249259Sdim bool analyzeBlock(BasicBlock *BB); 110249259Sdim 111249259Sdim // Disable several entry points to the visitor so we don't accidentally use 112249259Sdim // them by declaring but not defining them here. 113249259Sdim void visit(Module *); void visit(Module &); 114249259Sdim void visit(Function *); void visit(Function &); 115249259Sdim void visit(BasicBlock *); void visit(BasicBlock &); 116249259Sdim 117249259Sdim // Provide base case for our instruction visit. 118249259Sdim bool visitInstruction(Instruction &I); 119249259Sdim 120249259Sdim // Our visit overrides. 121249259Sdim bool visitAlloca(AllocaInst &I); 122249259Sdim bool visitPHI(PHINode &I); 123249259Sdim bool visitGetElementPtr(GetElementPtrInst &I); 124249259Sdim bool visitBitCast(BitCastInst &I); 125249259Sdim bool visitPtrToInt(PtrToIntInst &I); 126249259Sdim bool visitIntToPtr(IntToPtrInst &I); 127249259Sdim bool visitCastInst(CastInst &I); 128249259Sdim bool visitUnaryInstruction(UnaryInstruction &I); 129263508Sdim bool visitCmpInst(CmpInst &I); 130249259Sdim bool visitSub(BinaryOperator &I); 131249259Sdim bool visitBinaryOperator(BinaryOperator &I); 132249259Sdim bool visitLoad(LoadInst &I); 133249259Sdim bool visitStore(StoreInst &I); 134249259Sdim bool visitExtractValue(ExtractValueInst &I); 135249259Sdim bool visitInsertValue(InsertValueInst &I); 136249259Sdim bool visitCallSite(CallSite CS); 137263508Sdim bool visitReturnInst(ReturnInst &RI); 138263508Sdim bool visitBranchInst(BranchInst &BI); 139263508Sdim bool visitSwitchInst(SwitchInst &SI); 140263508Sdim bool visitIndirectBrInst(IndirectBrInst &IBI); 141263508Sdim bool visitResumeInst(ResumeInst &RI); 142263508Sdim bool visitUnreachableInst(UnreachableInst &I); 143249259Sdim 144249259Sdimpublic: 145249259Sdim CallAnalyzer(const DataLayout *TD, const TargetTransformInfo &TTI, 146249259Sdim Function &Callee, int Threshold) 147249259Sdim : TD(TD), TTI(TTI), F(Callee), Threshold(Threshold), Cost(0), 148249259Sdim IsCallerRecursive(false), IsRecursiveCall(false), 149249259Sdim ExposesReturnsTwice(false), HasDynamicAlloca(false), 150263508Sdim ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false), 151263508Sdim AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0), 152263508Sdim FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0), 153263508Sdim NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0), 154263508Sdim NumConstantPtrCmps(0), NumConstantPtrDiffs(0), 155263508Sdim NumInstructionsSimplified(0), SROACostSavings(0), 156263508Sdim SROACostSavingsLost(0) {} 157249259Sdim 158249259Sdim bool analyzeCall(CallSite CS); 159249259Sdim 160249259Sdim int getThreshold() { return Threshold; } 161249259Sdim int getCost() { return Cost; } 162249259Sdim 163249259Sdim // Keep a bunch of stats about the cost savings found so we can print them 164249259Sdim // out when debugging. 165249259Sdim unsigned NumConstantArgs; 166249259Sdim unsigned NumConstantOffsetPtrArgs; 167249259Sdim unsigned NumAllocaArgs; 168249259Sdim unsigned NumConstantPtrCmps; 169249259Sdim unsigned NumConstantPtrDiffs; 170249259Sdim unsigned NumInstructionsSimplified; 171249259Sdim unsigned SROACostSavings; 172249259Sdim unsigned SROACostSavingsLost; 173249259Sdim 174249259Sdim void dump(); 175249259Sdim}; 176249259Sdim 177249259Sdim} // namespace 178249259Sdim 179249259Sdim/// \brief Test whether the given value is an Alloca-derived function argument. 180249259Sdimbool CallAnalyzer::isAllocaDerivedArg(Value *V) { 181249259Sdim return SROAArgValues.count(V); 182249259Sdim} 183249259Sdim 184249259Sdim/// \brief Lookup the SROA-candidate argument and cost iterator which V maps to. 185249259Sdim/// Returns false if V does not map to a SROA-candidate. 186249259Sdimbool CallAnalyzer::lookupSROAArgAndCost( 187249259Sdim Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) { 188249259Sdim if (SROAArgValues.empty() || SROAArgCosts.empty()) 189249259Sdim return false; 190249259Sdim 191249259Sdim DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V); 192249259Sdim if (ArgIt == SROAArgValues.end()) 193249259Sdim return false; 194249259Sdim 195249259Sdim Arg = ArgIt->second; 196249259Sdim CostIt = SROAArgCosts.find(Arg); 197249259Sdim return CostIt != SROAArgCosts.end(); 198249259Sdim} 199249259Sdim 200249259Sdim/// \brief Disable SROA for the candidate marked by this cost iterator. 201249259Sdim/// 202249259Sdim/// This marks the candidate as no longer viable for SROA, and adds the cost 203249259Sdim/// savings associated with it back into the inline cost measurement. 204249259Sdimvoid CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) { 205249259Sdim // If we're no longer able to perform SROA we need to undo its cost savings 206249259Sdim // and prevent subsequent analysis. 207249259Sdim Cost += CostIt->second; 208249259Sdim SROACostSavings -= CostIt->second; 209249259Sdim SROACostSavingsLost += CostIt->second; 210249259Sdim SROAArgCosts.erase(CostIt); 211249259Sdim} 212249259Sdim 213249259Sdim/// \brief If 'V' maps to a SROA candidate, disable SROA for it. 214249259Sdimvoid CallAnalyzer::disableSROA(Value *V) { 215249259Sdim Value *SROAArg; 216249259Sdim DenseMap<Value *, int>::iterator CostIt; 217249259Sdim if (lookupSROAArgAndCost(V, SROAArg, CostIt)) 218249259Sdim disableSROA(CostIt); 219249259Sdim} 220249259Sdim 221249259Sdim/// \brief Accumulate the given cost for a particular SROA candidate. 222249259Sdimvoid CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt, 223249259Sdim int InstructionCost) { 224249259Sdim CostIt->second += InstructionCost; 225249259Sdim SROACostSavings += InstructionCost; 226249259Sdim} 227249259Sdim 228249259Sdim/// \brief Helper for the common pattern of handling a SROA candidate. 229249259Sdim/// Either accumulates the cost savings if the SROA remains valid, or disables 230249259Sdim/// SROA for the candidate. 231249259Sdimbool CallAnalyzer::handleSROACandidate(bool IsSROAValid, 232249259Sdim DenseMap<Value *, int>::iterator CostIt, 233249259Sdim int InstructionCost) { 234249259Sdim if (IsSROAValid) { 235249259Sdim accumulateSROACost(CostIt, InstructionCost); 236249259Sdim return true; 237249259Sdim } 238249259Sdim 239249259Sdim disableSROA(CostIt); 240249259Sdim return false; 241249259Sdim} 242249259Sdim 243249259Sdim/// \brief Check whether a GEP's indices are all constant. 244249259Sdim/// 245249259Sdim/// Respects any simplified values known during the analysis of this callsite. 246249259Sdimbool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) { 247249259Sdim for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 248249259Sdim if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I)) 249249259Sdim return false; 250249259Sdim 251249259Sdim return true; 252249259Sdim} 253249259Sdim 254249259Sdim/// \brief Accumulate a constant GEP offset into an APInt if possible. 255249259Sdim/// 256249259Sdim/// Returns false if unable to compute the offset for any reason. Respects any 257249259Sdim/// simplified values known during the analysis of this callsite. 258249259Sdimbool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) { 259249259Sdim if (!TD) 260249259Sdim return false; 261249259Sdim 262249259Sdim unsigned IntPtrWidth = TD->getPointerSizeInBits(); 263249259Sdim assert(IntPtrWidth == Offset.getBitWidth()); 264249259Sdim 265249259Sdim for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); 266249259Sdim GTI != GTE; ++GTI) { 267249259Sdim ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 268249259Sdim if (!OpC) 269249259Sdim if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand())) 270249259Sdim OpC = dyn_cast<ConstantInt>(SimpleOp); 271249259Sdim if (!OpC) 272249259Sdim return false; 273249259Sdim if (OpC->isZero()) continue; 274249259Sdim 275249259Sdim // Handle a struct index, which adds its field offset to the pointer. 276249259Sdim if (StructType *STy = dyn_cast<StructType>(*GTI)) { 277249259Sdim unsigned ElementIdx = OpC->getZExtValue(); 278249259Sdim const StructLayout *SL = TD->getStructLayout(STy); 279249259Sdim Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx)); 280249259Sdim continue; 281249259Sdim } 282249259Sdim 283249259Sdim APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType())); 284249259Sdim Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize; 285249259Sdim } 286249259Sdim return true; 287249259Sdim} 288249259Sdim 289249259Sdimbool CallAnalyzer::visitAlloca(AllocaInst &I) { 290249259Sdim // FIXME: Check whether inlining will turn a dynamic alloca into a static 291249259Sdim // alloca, and handle that case. 292249259Sdim 293249259Sdim // Accumulate the allocated size. 294249259Sdim if (I.isStaticAlloca()) { 295249259Sdim Type *Ty = I.getAllocatedType(); 296249259Sdim AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) : 297249259Sdim Ty->getPrimitiveSizeInBits()); 298249259Sdim } 299249259Sdim 300249259Sdim // We will happily inline static alloca instructions. 301249259Sdim if (I.isStaticAlloca()) 302249259Sdim return Base::visitAlloca(I); 303249259Sdim 304249259Sdim // FIXME: This is overly conservative. Dynamic allocas are inefficient for 305249259Sdim // a variety of reasons, and so we would like to not inline them into 306249259Sdim // functions which don't currently have a dynamic alloca. This simply 307249259Sdim // disables inlining altogether in the presence of a dynamic alloca. 308249259Sdim HasDynamicAlloca = true; 309249259Sdim return false; 310249259Sdim} 311249259Sdim 312249259Sdimbool CallAnalyzer::visitPHI(PHINode &I) { 313249259Sdim // FIXME: We should potentially be tracking values through phi nodes, 314249259Sdim // especially when they collapse to a single value due to deleted CFG edges 315249259Sdim // during inlining. 316249259Sdim 317249259Sdim // FIXME: We need to propagate SROA *disabling* through phi nodes, even 318249259Sdim // though we don't want to propagate it's bonuses. The idea is to disable 319249259Sdim // SROA if it *might* be used in an inappropriate manner. 320249259Sdim 321249259Sdim // Phi nodes are always zero-cost. 322249259Sdim return true; 323249259Sdim} 324249259Sdim 325249259Sdimbool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) { 326249259Sdim Value *SROAArg; 327249259Sdim DenseMap<Value *, int>::iterator CostIt; 328249259Sdim bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(), 329249259Sdim SROAArg, CostIt); 330249259Sdim 331249259Sdim // Try to fold GEPs of constant-offset call site argument pointers. This 332249259Sdim // requires target data and inbounds GEPs. 333249259Sdim if (TD && I.isInBounds()) { 334249259Sdim // Check if we have a base + offset for the pointer. 335249259Sdim Value *Ptr = I.getPointerOperand(); 336249259Sdim std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr); 337249259Sdim if (BaseAndOffset.first) { 338249259Sdim // Check if the offset of this GEP is constant, and if so accumulate it 339249259Sdim // into Offset. 340249259Sdim if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) { 341249259Sdim // Non-constant GEPs aren't folded, and disable SROA. 342249259Sdim if (SROACandidate) 343249259Sdim disableSROA(CostIt); 344249259Sdim return false; 345249259Sdim } 346249259Sdim 347249259Sdim // Add the result as a new mapping to Base + Offset. 348249259Sdim ConstantOffsetPtrs[&I] = BaseAndOffset; 349249259Sdim 350249259Sdim // Also handle SROA candidates here, we already know that the GEP is 351249259Sdim // all-constant indexed. 352249259Sdim if (SROACandidate) 353249259Sdim SROAArgValues[&I] = SROAArg; 354249259Sdim 355249259Sdim return true; 356249259Sdim } 357249259Sdim } 358249259Sdim 359249259Sdim if (isGEPOffsetConstant(I)) { 360249259Sdim if (SROACandidate) 361249259Sdim SROAArgValues[&I] = SROAArg; 362249259Sdim 363249259Sdim // Constant GEPs are modeled as free. 364249259Sdim return true; 365249259Sdim } 366249259Sdim 367249259Sdim // Variable GEPs will require math and will disable SROA. 368249259Sdim if (SROACandidate) 369249259Sdim disableSROA(CostIt); 370249259Sdim return false; 371249259Sdim} 372249259Sdim 373249259Sdimbool CallAnalyzer::visitBitCast(BitCastInst &I) { 374249259Sdim // Propagate constants through bitcasts. 375249259Sdim Constant *COp = dyn_cast<Constant>(I.getOperand(0)); 376249259Sdim if (!COp) 377249259Sdim COp = SimplifiedValues.lookup(I.getOperand(0)); 378249259Sdim if (COp) 379249259Sdim if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) { 380249259Sdim SimplifiedValues[&I] = C; 381249259Sdim return true; 382249259Sdim } 383249259Sdim 384249259Sdim // Track base/offsets through casts 385249259Sdim std::pair<Value *, APInt> BaseAndOffset 386249259Sdim = ConstantOffsetPtrs.lookup(I.getOperand(0)); 387249259Sdim // Casts don't change the offset, just wrap it up. 388249259Sdim if (BaseAndOffset.first) 389249259Sdim ConstantOffsetPtrs[&I] = BaseAndOffset; 390249259Sdim 391249259Sdim // Also look for SROA candidates here. 392249259Sdim Value *SROAArg; 393249259Sdim DenseMap<Value *, int>::iterator CostIt; 394249259Sdim if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) 395249259Sdim SROAArgValues[&I] = SROAArg; 396249259Sdim 397249259Sdim // Bitcasts are always zero cost. 398249259Sdim return true; 399249259Sdim} 400249259Sdim 401249259Sdimbool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) { 402249259Sdim // Propagate constants through ptrtoint. 403249259Sdim Constant *COp = dyn_cast<Constant>(I.getOperand(0)); 404249259Sdim if (!COp) 405249259Sdim COp = SimplifiedValues.lookup(I.getOperand(0)); 406249259Sdim if (COp) 407249259Sdim if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) { 408249259Sdim SimplifiedValues[&I] = C; 409249259Sdim return true; 410249259Sdim } 411249259Sdim 412249259Sdim // Track base/offset pairs when converted to a plain integer provided the 413249259Sdim // integer is large enough to represent the pointer. 414249259Sdim unsigned IntegerSize = I.getType()->getScalarSizeInBits(); 415249259Sdim if (TD && IntegerSize >= TD->getPointerSizeInBits()) { 416249259Sdim std::pair<Value *, APInt> BaseAndOffset 417249259Sdim = ConstantOffsetPtrs.lookup(I.getOperand(0)); 418249259Sdim if (BaseAndOffset.first) 419249259Sdim ConstantOffsetPtrs[&I] = BaseAndOffset; 420249259Sdim } 421249259Sdim 422249259Sdim // This is really weird. Technically, ptrtoint will disable SROA. However, 423249259Sdim // unless that ptrtoint is *used* somewhere in the live basic blocks after 424249259Sdim // inlining, it will be nuked, and SROA should proceed. All of the uses which 425249259Sdim // would block SROA would also block SROA if applied directly to a pointer, 426249259Sdim // and so we can just add the integer in here. The only places where SROA is 427249259Sdim // preserved either cannot fire on an integer, or won't in-and-of themselves 428249259Sdim // disable SROA (ext) w/o some later use that we would see and disable. 429249259Sdim Value *SROAArg; 430249259Sdim DenseMap<Value *, int>::iterator CostIt; 431249259Sdim if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) 432249259Sdim SROAArgValues[&I] = SROAArg; 433249259Sdim 434249259Sdim return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 435249259Sdim} 436249259Sdim 437249259Sdimbool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) { 438249259Sdim // Propagate constants through ptrtoint. 439249259Sdim Constant *COp = dyn_cast<Constant>(I.getOperand(0)); 440249259Sdim if (!COp) 441249259Sdim COp = SimplifiedValues.lookup(I.getOperand(0)); 442249259Sdim if (COp) 443249259Sdim if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) { 444249259Sdim SimplifiedValues[&I] = C; 445249259Sdim return true; 446249259Sdim } 447249259Sdim 448249259Sdim // Track base/offset pairs when round-tripped through a pointer without 449249259Sdim // modifications provided the integer is not too large. 450249259Sdim Value *Op = I.getOperand(0); 451249259Sdim unsigned IntegerSize = Op->getType()->getScalarSizeInBits(); 452249259Sdim if (TD && IntegerSize <= TD->getPointerSizeInBits()) { 453249259Sdim std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op); 454249259Sdim if (BaseAndOffset.first) 455249259Sdim ConstantOffsetPtrs[&I] = BaseAndOffset; 456249259Sdim } 457249259Sdim 458249259Sdim // "Propagate" SROA here in the same manner as we do for ptrtoint above. 459249259Sdim Value *SROAArg; 460249259Sdim DenseMap<Value *, int>::iterator CostIt; 461249259Sdim if (lookupSROAArgAndCost(Op, SROAArg, CostIt)) 462249259Sdim SROAArgValues[&I] = SROAArg; 463249259Sdim 464249259Sdim return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 465249259Sdim} 466249259Sdim 467249259Sdimbool CallAnalyzer::visitCastInst(CastInst &I) { 468249259Sdim // Propagate constants through ptrtoint. 469249259Sdim Constant *COp = dyn_cast<Constant>(I.getOperand(0)); 470249259Sdim if (!COp) 471249259Sdim COp = SimplifiedValues.lookup(I.getOperand(0)); 472249259Sdim if (COp) 473249259Sdim if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) { 474249259Sdim SimplifiedValues[&I] = C; 475249259Sdim return true; 476249259Sdim } 477249259Sdim 478249259Sdim // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere. 479249259Sdim disableSROA(I.getOperand(0)); 480249259Sdim 481249259Sdim return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 482249259Sdim} 483249259Sdim 484249259Sdimbool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) { 485249259Sdim Value *Operand = I.getOperand(0); 486249259Sdim Constant *COp = dyn_cast<Constant>(Operand); 487249259Sdim if (!COp) 488249259Sdim COp = SimplifiedValues.lookup(Operand); 489249259Sdim if (COp) 490249259Sdim if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(), 491249259Sdim COp, TD)) { 492249259Sdim SimplifiedValues[&I] = C; 493249259Sdim return true; 494249259Sdim } 495249259Sdim 496249259Sdim // Disable any SROA on the argument to arbitrary unary operators. 497249259Sdim disableSROA(Operand); 498249259Sdim 499249259Sdim return false; 500249259Sdim} 501249259Sdim 502263508Sdimbool CallAnalyzer::visitCmpInst(CmpInst &I) { 503249259Sdim Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 504249259Sdim // First try to handle simplified comparisons. 505249259Sdim if (!isa<Constant>(LHS)) 506249259Sdim if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 507249259Sdim LHS = SimpleLHS; 508249259Sdim if (!isa<Constant>(RHS)) 509249259Sdim if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 510249259Sdim RHS = SimpleRHS; 511263508Sdim if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 512249259Sdim if (Constant *CRHS = dyn_cast<Constant>(RHS)) 513263508Sdim if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) { 514249259Sdim SimplifiedValues[&I] = C; 515249259Sdim return true; 516249259Sdim } 517263508Sdim } 518249259Sdim 519263508Sdim if (I.getOpcode() == Instruction::FCmp) 520263508Sdim return false; 521263508Sdim 522249259Sdim // Otherwise look for a comparison between constant offset pointers with 523249259Sdim // a common base. 524249259Sdim Value *LHSBase, *RHSBase; 525249259Sdim APInt LHSOffset, RHSOffset; 526249259Sdim llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 527249259Sdim if (LHSBase) { 528249259Sdim llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 529249259Sdim if (RHSBase && LHSBase == RHSBase) { 530249259Sdim // We have common bases, fold the icmp to a constant based on the 531249259Sdim // offsets. 532249259Sdim Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 533249259Sdim Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 534249259Sdim if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) { 535249259Sdim SimplifiedValues[&I] = C; 536249259Sdim ++NumConstantPtrCmps; 537249259Sdim return true; 538249259Sdim } 539249259Sdim } 540249259Sdim } 541249259Sdim 542249259Sdim // If the comparison is an equality comparison with null, we can simplify it 543249259Sdim // for any alloca-derived argument. 544249259Sdim if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1))) 545249259Sdim if (isAllocaDerivedArg(I.getOperand(0))) { 546249259Sdim // We can actually predict the result of comparisons between an 547249259Sdim // alloca-derived value and null. Note that this fires regardless of 548249259Sdim // SROA firing. 549249259Sdim bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE; 550249259Sdim SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType()) 551249259Sdim : ConstantInt::getFalse(I.getType()); 552249259Sdim return true; 553249259Sdim } 554249259Sdim 555249259Sdim // Finally check for SROA candidates in comparisons. 556249259Sdim Value *SROAArg; 557249259Sdim DenseMap<Value *, int>::iterator CostIt; 558249259Sdim if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) { 559249259Sdim if (isa<ConstantPointerNull>(I.getOperand(1))) { 560249259Sdim accumulateSROACost(CostIt, InlineConstants::InstrCost); 561249259Sdim return true; 562249259Sdim } 563249259Sdim 564249259Sdim disableSROA(CostIt); 565249259Sdim } 566249259Sdim 567249259Sdim return false; 568249259Sdim} 569249259Sdim 570249259Sdimbool CallAnalyzer::visitSub(BinaryOperator &I) { 571249259Sdim // Try to handle a special case: we can fold computing the difference of two 572249259Sdim // constant-related pointers. 573249259Sdim Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 574249259Sdim Value *LHSBase, *RHSBase; 575249259Sdim APInt LHSOffset, RHSOffset; 576249259Sdim llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 577249259Sdim if (LHSBase) { 578249259Sdim llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 579249259Sdim if (RHSBase && LHSBase == RHSBase) { 580249259Sdim // We have common bases, fold the subtract to a constant based on the 581249259Sdim // offsets. 582249259Sdim Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 583249259Sdim Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 584249259Sdim if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) { 585249259Sdim SimplifiedValues[&I] = C; 586249259Sdim ++NumConstantPtrDiffs; 587249259Sdim return true; 588249259Sdim } 589249259Sdim } 590249259Sdim } 591249259Sdim 592249259Sdim // Otherwise, fall back to the generic logic for simplifying and handling 593249259Sdim // instructions. 594249259Sdim return Base::visitSub(I); 595249259Sdim} 596249259Sdim 597249259Sdimbool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) { 598249259Sdim Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 599249259Sdim if (!isa<Constant>(LHS)) 600249259Sdim if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 601249259Sdim LHS = SimpleLHS; 602249259Sdim if (!isa<Constant>(RHS)) 603249259Sdim if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 604249259Sdim RHS = SimpleRHS; 605249259Sdim Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD); 606249259Sdim if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) { 607249259Sdim SimplifiedValues[&I] = C; 608249259Sdim return true; 609249259Sdim } 610249259Sdim 611249259Sdim // Disable any SROA on arguments to arbitrary, unsimplified binary operators. 612249259Sdim disableSROA(LHS); 613249259Sdim disableSROA(RHS); 614249259Sdim 615249259Sdim return false; 616249259Sdim} 617249259Sdim 618249259Sdimbool CallAnalyzer::visitLoad(LoadInst &I) { 619249259Sdim Value *SROAArg; 620249259Sdim DenseMap<Value *, int>::iterator CostIt; 621249259Sdim if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) { 622249259Sdim if (I.isSimple()) { 623249259Sdim accumulateSROACost(CostIt, InlineConstants::InstrCost); 624249259Sdim return true; 625249259Sdim } 626249259Sdim 627249259Sdim disableSROA(CostIt); 628249259Sdim } 629249259Sdim 630249259Sdim return false; 631249259Sdim} 632249259Sdim 633249259Sdimbool CallAnalyzer::visitStore(StoreInst &I) { 634249259Sdim Value *SROAArg; 635249259Sdim DenseMap<Value *, int>::iterator CostIt; 636249259Sdim if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) { 637249259Sdim if (I.isSimple()) { 638249259Sdim accumulateSROACost(CostIt, InlineConstants::InstrCost); 639249259Sdim return true; 640249259Sdim } 641249259Sdim 642249259Sdim disableSROA(CostIt); 643249259Sdim } 644249259Sdim 645249259Sdim return false; 646249259Sdim} 647249259Sdim 648249259Sdimbool CallAnalyzer::visitExtractValue(ExtractValueInst &I) { 649249259Sdim // Constant folding for extract value is trivial. 650249259Sdim Constant *C = dyn_cast<Constant>(I.getAggregateOperand()); 651249259Sdim if (!C) 652249259Sdim C = SimplifiedValues.lookup(I.getAggregateOperand()); 653249259Sdim if (C) { 654249259Sdim SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices()); 655249259Sdim return true; 656249259Sdim } 657249259Sdim 658249259Sdim // SROA can look through these but give them a cost. 659249259Sdim return false; 660249259Sdim} 661249259Sdim 662249259Sdimbool CallAnalyzer::visitInsertValue(InsertValueInst &I) { 663249259Sdim // Constant folding for insert value is trivial. 664249259Sdim Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand()); 665249259Sdim if (!AggC) 666249259Sdim AggC = SimplifiedValues.lookup(I.getAggregateOperand()); 667249259Sdim Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand()); 668249259Sdim if (!InsertedC) 669249259Sdim InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand()); 670249259Sdim if (AggC && InsertedC) { 671249259Sdim SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC, 672249259Sdim I.getIndices()); 673249259Sdim return true; 674249259Sdim } 675249259Sdim 676249259Sdim // SROA can look through these but give them a cost. 677249259Sdim return false; 678249259Sdim} 679249259Sdim 680249259Sdim/// \brief Try to simplify a call site. 681249259Sdim/// 682249259Sdim/// Takes a concrete function and callsite and tries to actually simplify it by 683249259Sdim/// analyzing the arguments and call itself with instsimplify. Returns true if 684249259Sdim/// it has simplified the callsite to some other entity (a constant), making it 685249259Sdim/// free. 686249259Sdimbool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) { 687249259Sdim // FIXME: Using the instsimplify logic directly for this is inefficient 688249259Sdim // because we have to continually rebuild the argument list even when no 689249259Sdim // simplifications can be performed. Until that is fixed with remapping 690249259Sdim // inside of instsimplify, directly constant fold calls here. 691249259Sdim if (!canConstantFoldCallTo(F)) 692249259Sdim return false; 693249259Sdim 694249259Sdim // Try to re-map the arguments to constants. 695249259Sdim SmallVector<Constant *, 4> ConstantArgs; 696249259Sdim ConstantArgs.reserve(CS.arg_size()); 697249259Sdim for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 698249259Sdim I != E; ++I) { 699249259Sdim Constant *C = dyn_cast<Constant>(*I); 700249259Sdim if (!C) 701249259Sdim C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I)); 702249259Sdim if (!C) 703249259Sdim return false; // This argument doesn't map to a constant. 704249259Sdim 705249259Sdim ConstantArgs.push_back(C); 706249259Sdim } 707249259Sdim if (Constant *C = ConstantFoldCall(F, ConstantArgs)) { 708249259Sdim SimplifiedValues[CS.getInstruction()] = C; 709249259Sdim return true; 710249259Sdim } 711249259Sdim 712249259Sdim return false; 713249259Sdim} 714249259Sdim 715249259Sdimbool CallAnalyzer::visitCallSite(CallSite CS) { 716263508Sdim if (CS.hasFnAttr(Attribute::ReturnsTwice) && 717249259Sdim !F.getAttributes().hasAttribute(AttributeSet::FunctionIndex, 718249259Sdim Attribute::ReturnsTwice)) { 719249259Sdim // This aborts the entire analysis. 720249259Sdim ExposesReturnsTwice = true; 721249259Sdim return false; 722249259Sdim } 723249259Sdim if (CS.isCall() && 724249259Sdim cast<CallInst>(CS.getInstruction())->hasFnAttr(Attribute::NoDuplicate)) 725249259Sdim ContainsNoDuplicateCall = true; 726249259Sdim 727249259Sdim if (Function *F = CS.getCalledFunction()) { 728249259Sdim // When we have a concrete function, first try to simplify it directly. 729249259Sdim if (simplifyCallSite(F, CS)) 730249259Sdim return true; 731249259Sdim 732249259Sdim // Next check if it is an intrinsic we know about. 733249259Sdim // FIXME: Lift this into part of the InstVisitor. 734249259Sdim if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) { 735249259Sdim switch (II->getIntrinsicID()) { 736249259Sdim default: 737249259Sdim return Base::visitCallSite(CS); 738249259Sdim 739249259Sdim case Intrinsic::memset: 740249259Sdim case Intrinsic::memcpy: 741249259Sdim case Intrinsic::memmove: 742249259Sdim // SROA can usually chew through these intrinsics, but they aren't free. 743249259Sdim return false; 744249259Sdim } 745249259Sdim } 746249259Sdim 747249259Sdim if (F == CS.getInstruction()->getParent()->getParent()) { 748249259Sdim // This flag will fully abort the analysis, so don't bother with anything 749249259Sdim // else. 750249259Sdim IsRecursiveCall = true; 751249259Sdim return false; 752249259Sdim } 753249259Sdim 754249259Sdim if (TTI.isLoweredToCall(F)) { 755249259Sdim // We account for the average 1 instruction per call argument setup 756249259Sdim // here. 757249259Sdim Cost += CS.arg_size() * InlineConstants::InstrCost; 758249259Sdim 759249259Sdim // Everything other than inline ASM will also have a significant cost 760249259Sdim // merely from making the call. 761249259Sdim if (!isa<InlineAsm>(CS.getCalledValue())) 762249259Sdim Cost += InlineConstants::CallPenalty; 763249259Sdim } 764249259Sdim 765249259Sdim return Base::visitCallSite(CS); 766249259Sdim } 767249259Sdim 768249259Sdim // Otherwise we're in a very special case -- an indirect function call. See 769249259Sdim // if we can be particularly clever about this. 770249259Sdim Value *Callee = CS.getCalledValue(); 771249259Sdim 772249259Sdim // First, pay the price of the argument setup. We account for the average 773249259Sdim // 1 instruction per call argument setup here. 774249259Sdim Cost += CS.arg_size() * InlineConstants::InstrCost; 775249259Sdim 776249259Sdim // Next, check if this happens to be an indirect function call to a known 777249259Sdim // function in this inline context. If not, we've done all we can. 778249259Sdim Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee)); 779249259Sdim if (!F) 780249259Sdim return Base::visitCallSite(CS); 781249259Sdim 782249259Sdim // If we have a constant that we are calling as a function, we can peer 783249259Sdim // through it and see the function target. This happens not infrequently 784249259Sdim // during devirtualization and so we want to give it a hefty bonus for 785249259Sdim // inlining, but cap that bonus in the event that inlining wouldn't pan 786249259Sdim // out. Pretend to inline the function, with a custom threshold. 787249259Sdim CallAnalyzer CA(TD, TTI, *F, InlineConstants::IndirectCallThreshold); 788249259Sdim if (CA.analyzeCall(CS)) { 789249259Sdim // We were able to inline the indirect call! Subtract the cost from the 790249259Sdim // bonus we want to apply, but don't go below zero. 791249259Sdim Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost()); 792249259Sdim } 793249259Sdim 794249259Sdim return Base::visitCallSite(CS); 795249259Sdim} 796249259Sdim 797263508Sdimbool CallAnalyzer::visitReturnInst(ReturnInst &RI) { 798263508Sdim // At least one return instruction will be free after inlining. 799263508Sdim bool Free = !HasReturn; 800263508Sdim HasReturn = true; 801263508Sdim return Free; 802263508Sdim} 803263508Sdim 804263508Sdimbool CallAnalyzer::visitBranchInst(BranchInst &BI) { 805263508Sdim // We model unconditional branches as essentially free -- they really 806263508Sdim // shouldn't exist at all, but handling them makes the behavior of the 807263508Sdim // inliner more regular and predictable. Interestingly, conditional branches 808263508Sdim // which will fold away are also free. 809263508Sdim return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) || 810263508Sdim dyn_cast_or_null<ConstantInt>( 811263508Sdim SimplifiedValues.lookup(BI.getCondition())); 812263508Sdim} 813263508Sdim 814263508Sdimbool CallAnalyzer::visitSwitchInst(SwitchInst &SI) { 815263508Sdim // We model unconditional switches as free, see the comments on handling 816263508Sdim // branches. 817263508Sdim return isa<ConstantInt>(SI.getCondition()) || 818263508Sdim dyn_cast_or_null<ConstantInt>( 819263508Sdim SimplifiedValues.lookup(SI.getCondition())); 820263508Sdim} 821263508Sdim 822263508Sdimbool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) { 823263508Sdim // We never want to inline functions that contain an indirectbr. This is 824263508Sdim // incorrect because all the blockaddress's (in static global initializers 825263508Sdim // for example) would be referring to the original function, and this 826263508Sdim // indirect jump would jump from the inlined copy of the function into the 827263508Sdim // original function which is extremely undefined behavior. 828263508Sdim // FIXME: This logic isn't really right; we can safely inline functions with 829263508Sdim // indirectbr's as long as no other function or global references the 830263508Sdim // blockaddress of a block within the current function. And as a QOI issue, 831263508Sdim // if someone is using a blockaddress without an indirectbr, and that 832263508Sdim // reference somehow ends up in another function or global, we probably don't 833263508Sdim // want to inline this function. 834263508Sdim HasIndirectBr = true; 835263508Sdim return false; 836263508Sdim} 837263508Sdim 838263508Sdimbool CallAnalyzer::visitResumeInst(ResumeInst &RI) { 839263508Sdim // FIXME: It's not clear that a single instruction is an accurate model for 840263508Sdim // the inline cost of a resume instruction. 841263508Sdim return false; 842263508Sdim} 843263508Sdim 844263508Sdimbool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) { 845263508Sdim // FIXME: It might be reasonably to discount the cost of instructions leading 846263508Sdim // to unreachable as they have the lowest possible impact on both runtime and 847263508Sdim // code size. 848263508Sdim return true; // No actual code is needed for unreachable. 849263508Sdim} 850263508Sdim 851249259Sdimbool CallAnalyzer::visitInstruction(Instruction &I) { 852249259Sdim // Some instructions are free. All of the free intrinsics can also be 853249259Sdim // handled by SROA, etc. 854249259Sdim if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I)) 855249259Sdim return true; 856249259Sdim 857249259Sdim // We found something we don't understand or can't handle. Mark any SROA-able 858249259Sdim // values in the operand list as no longer viable. 859249259Sdim for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI) 860249259Sdim disableSROA(*OI); 861249259Sdim 862249259Sdim return false; 863249259Sdim} 864249259Sdim 865249259Sdim 866249259Sdim/// \brief Analyze a basic block for its contribution to the inline cost. 867249259Sdim/// 868249259Sdim/// This method walks the analyzer over every instruction in the given basic 869249259Sdim/// block and accounts for their cost during inlining at this callsite. It 870249259Sdim/// aborts early if the threshold has been exceeded or an impossible to inline 871249259Sdim/// construct has been detected. It returns false if inlining is no longer 872249259Sdim/// viable, and true if inlining remains viable. 873249259Sdimbool CallAnalyzer::analyzeBlock(BasicBlock *BB) { 874263508Sdim for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 875249259Sdim ++NumInstructions; 876249259Sdim if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy()) 877249259Sdim ++NumVectorInstructions; 878249259Sdim 879249259Sdim // If the instruction simplified to a constant, there is no cost to this 880249259Sdim // instruction. Visit the instructions using our InstVisitor to account for 881249259Sdim // all of the per-instruction logic. The visit tree returns true if we 882249259Sdim // consumed the instruction in any way, and false if the instruction's base 883249259Sdim // cost should count against inlining. 884249259Sdim if (Base::visit(I)) 885249259Sdim ++NumInstructionsSimplified; 886249259Sdim else 887249259Sdim Cost += InlineConstants::InstrCost; 888249259Sdim 889249259Sdim // If the visit this instruction detected an uninlinable pattern, abort. 890263508Sdim if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca || 891263508Sdim HasIndirectBr) 892249259Sdim return false; 893249259Sdim 894249259Sdim // If the caller is a recursive function then we don't want to inline 895249259Sdim // functions which allocate a lot of stack space because it would increase 896249259Sdim // the caller stack usage dramatically. 897249259Sdim if (IsCallerRecursive && 898249259Sdim AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) 899249259Sdim return false; 900249259Sdim 901249259Sdim if (NumVectorInstructions > NumInstructions/2) 902249259Sdim VectorBonus = FiftyPercentVectorBonus; 903249259Sdim else if (NumVectorInstructions > NumInstructions/10) 904249259Sdim VectorBonus = TenPercentVectorBonus; 905249259Sdim else 906249259Sdim VectorBonus = 0; 907249259Sdim 908249259Sdim // Check if we've past the threshold so we don't spin in huge basic 909249259Sdim // blocks that will never inline. 910249259Sdim if (Cost > (Threshold + VectorBonus)) 911249259Sdim return false; 912249259Sdim } 913249259Sdim 914249259Sdim return true; 915249259Sdim} 916249259Sdim 917249259Sdim/// \brief Compute the base pointer and cumulative constant offsets for V. 918249259Sdim/// 919249259Sdim/// This strips all constant offsets off of V, leaving it the base pointer, and 920249259Sdim/// accumulates the total constant offset applied in the returned constant. It 921249259Sdim/// returns 0 if V is not a pointer, and returns the constant '0' if there are 922249259Sdim/// no constant offsets applied. 923249259SdimConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) { 924249259Sdim if (!TD || !V->getType()->isPointerTy()) 925249259Sdim return 0; 926249259Sdim 927249259Sdim unsigned IntPtrWidth = TD->getPointerSizeInBits(); 928249259Sdim APInt Offset = APInt::getNullValue(IntPtrWidth); 929249259Sdim 930249259Sdim // Even though we don't look through PHI nodes, we could be called on an 931249259Sdim // instruction in an unreachable block, which may be on a cycle. 932249259Sdim SmallPtrSet<Value *, 4> Visited; 933249259Sdim Visited.insert(V); 934249259Sdim do { 935249259Sdim if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 936249259Sdim if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset)) 937249259Sdim return 0; 938249259Sdim V = GEP->getPointerOperand(); 939249259Sdim } else if (Operator::getOpcode(V) == Instruction::BitCast) { 940249259Sdim V = cast<Operator>(V)->getOperand(0); 941249259Sdim } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 942249259Sdim if (GA->mayBeOverridden()) 943249259Sdim break; 944249259Sdim V = GA->getAliasee(); 945249259Sdim } else { 946249259Sdim break; 947249259Sdim } 948249259Sdim assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 949249259Sdim } while (Visited.insert(V)); 950249259Sdim 951249259Sdim Type *IntPtrTy = TD->getIntPtrType(V->getContext()); 952249259Sdim return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset)); 953249259Sdim} 954249259Sdim 955249259Sdim/// \brief Analyze a call site for potential inlining. 956249259Sdim/// 957249259Sdim/// Returns true if inlining this call is viable, and false if it is not 958249259Sdim/// viable. It computes the cost and adjusts the threshold based on numerous 959249259Sdim/// factors and heuristics. If this method returns false but the computed cost 960249259Sdim/// is below the computed threshold, then inlining was forcibly disabled by 961249259Sdim/// some artifact of the routine. 962249259Sdimbool CallAnalyzer::analyzeCall(CallSite CS) { 963249259Sdim ++NumCallsAnalyzed; 964249259Sdim 965249259Sdim // Track whether the post-inlining function would have more than one basic 966249259Sdim // block. A single basic block is often intended for inlining. Balloon the 967249259Sdim // threshold by 50% until we pass the single-BB phase. 968249259Sdim bool SingleBB = true; 969249259Sdim int SingleBBBonus = Threshold / 2; 970249259Sdim Threshold += SingleBBBonus; 971249259Sdim 972249259Sdim // Perform some tweaks to the cost and threshold based on the direct 973249259Sdim // callsite information. 974249259Sdim 975249259Sdim // We want to more aggressively inline vector-dense kernels, so up the 976249259Sdim // threshold, and we'll lower it if the % of vector instructions gets too 977249259Sdim // low. 978249259Sdim assert(NumInstructions == 0); 979249259Sdim assert(NumVectorInstructions == 0); 980249259Sdim FiftyPercentVectorBonus = Threshold; 981249259Sdim TenPercentVectorBonus = Threshold / 2; 982249259Sdim 983249259Sdim // Give out bonuses per argument, as the instructions setting them up will 984249259Sdim // be gone after inlining. 985249259Sdim for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) { 986249259Sdim if (TD && CS.isByValArgument(I)) { 987249259Sdim // We approximate the number of loads and stores needed by dividing the 988249259Sdim // size of the byval type by the target's pointer size. 989249259Sdim PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType()); 990249259Sdim unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType()); 991249259Sdim unsigned PointerSize = TD->getPointerSizeInBits(); 992249259Sdim // Ceiling division. 993249259Sdim unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize; 994249259Sdim 995249259Sdim // If it generates more than 8 stores it is likely to be expanded as an 996249259Sdim // inline memcpy so we take that as an upper bound. Otherwise we assume 997249259Sdim // one load and one store per word copied. 998249259Sdim // FIXME: The maxStoresPerMemcpy setting from the target should be used 999249259Sdim // here instead of a magic number of 8, but it's not available via 1000249259Sdim // DataLayout. 1001249259Sdim NumStores = std::min(NumStores, 8U); 1002249259Sdim 1003249259Sdim Cost -= 2 * NumStores * InlineConstants::InstrCost; 1004249259Sdim } else { 1005249259Sdim // For non-byval arguments subtract off one instruction per call 1006249259Sdim // argument. 1007249259Sdim Cost -= InlineConstants::InstrCost; 1008249259Sdim } 1009249259Sdim } 1010249259Sdim 1011249259Sdim // If there is only one call of the function, and it has internal linkage, 1012249259Sdim // the cost of inlining it drops dramatically. 1013249259Sdim bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() && 1014249259Sdim &F == CS.getCalledFunction(); 1015249259Sdim if (OnlyOneCallAndLocalLinkage) 1016249259Sdim Cost += InlineConstants::LastCallToStaticBonus; 1017249259Sdim 1018249259Sdim // If the instruction after the call, or if the normal destination of the 1019249259Sdim // invoke is an unreachable instruction, the function is noreturn. As such, 1020249259Sdim // there is little point in inlining this unless there is literally zero 1021249259Sdim // cost. 1022249259Sdim Instruction *Instr = CS.getInstruction(); 1023249259Sdim if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) { 1024249259Sdim if (isa<UnreachableInst>(II->getNormalDest()->begin())) 1025249259Sdim Threshold = 1; 1026249259Sdim } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr))) 1027249259Sdim Threshold = 1; 1028249259Sdim 1029249259Sdim // If this function uses the coldcc calling convention, prefer not to inline 1030249259Sdim // it. 1031249259Sdim if (F.getCallingConv() == CallingConv::Cold) 1032249259Sdim Cost += InlineConstants::ColdccPenalty; 1033249259Sdim 1034249259Sdim // Check if we're done. This can happen due to bonuses and penalties. 1035249259Sdim if (Cost > Threshold) 1036249259Sdim return false; 1037249259Sdim 1038249259Sdim if (F.empty()) 1039249259Sdim return true; 1040249259Sdim 1041249259Sdim Function *Caller = CS.getInstruction()->getParent()->getParent(); 1042249259Sdim // Check if the caller function is recursive itself. 1043249259Sdim for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end(); 1044249259Sdim U != E; ++U) { 1045249259Sdim CallSite Site(cast<Value>(*U)); 1046249259Sdim if (!Site) 1047249259Sdim continue; 1048249259Sdim Instruction *I = Site.getInstruction(); 1049249259Sdim if (I->getParent()->getParent() == Caller) { 1050249259Sdim IsCallerRecursive = true; 1051249259Sdim break; 1052249259Sdim } 1053249259Sdim } 1054249259Sdim 1055249259Sdim // Populate our simplified values by mapping from function arguments to call 1056249259Sdim // arguments with known important simplifications. 1057249259Sdim CallSite::arg_iterator CAI = CS.arg_begin(); 1058249259Sdim for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end(); 1059249259Sdim FAI != FAE; ++FAI, ++CAI) { 1060249259Sdim assert(CAI != CS.arg_end()); 1061249259Sdim if (Constant *C = dyn_cast<Constant>(CAI)) 1062249259Sdim SimplifiedValues[FAI] = C; 1063249259Sdim 1064249259Sdim Value *PtrArg = *CAI; 1065249259Sdim if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) { 1066249259Sdim ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue()); 1067249259Sdim 1068249259Sdim // We can SROA any pointer arguments derived from alloca instructions. 1069249259Sdim if (isa<AllocaInst>(PtrArg)) { 1070249259Sdim SROAArgValues[FAI] = PtrArg; 1071249259Sdim SROAArgCosts[PtrArg] = 0; 1072249259Sdim } 1073249259Sdim } 1074249259Sdim } 1075249259Sdim NumConstantArgs = SimplifiedValues.size(); 1076249259Sdim NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size(); 1077249259Sdim NumAllocaArgs = SROAArgValues.size(); 1078249259Sdim 1079249259Sdim // The worklist of live basic blocks in the callee *after* inlining. We avoid 1080249259Sdim // adding basic blocks of the callee which can be proven to be dead for this 1081249259Sdim // particular call site in order to get more accurate cost estimates. This 1082249259Sdim // requires a somewhat heavyweight iteration pattern: we need to walk the 1083249259Sdim // basic blocks in a breadth-first order as we insert live successors. To 1084249259Sdim // accomplish this, prioritizing for small iterations because we exit after 1085249259Sdim // crossing our threshold, we use a small-size optimized SetVector. 1086249259Sdim typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>, 1087249259Sdim SmallPtrSet<BasicBlock *, 16> > BBSetVector; 1088249259Sdim BBSetVector BBWorklist; 1089249259Sdim BBWorklist.insert(&F.getEntryBlock()); 1090249259Sdim // Note that we *must not* cache the size, this loop grows the worklist. 1091249259Sdim for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 1092249259Sdim // Bail out the moment we cross the threshold. This means we'll under-count 1093249259Sdim // the cost, but only when undercounting doesn't matter. 1094249259Sdim if (Cost > (Threshold + VectorBonus)) 1095249259Sdim break; 1096249259Sdim 1097249259Sdim BasicBlock *BB = BBWorklist[Idx]; 1098249259Sdim if (BB->empty()) 1099249259Sdim continue; 1100249259Sdim 1101249259Sdim // Analyze the cost of this block. If we blow through the threshold, this 1102249259Sdim // returns false, and we can bail on out. 1103249259Sdim if (!analyzeBlock(BB)) { 1104263508Sdim if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca || 1105263508Sdim HasIndirectBr) 1106249259Sdim return false; 1107249259Sdim 1108249259Sdim // If the caller is a recursive function then we don't want to inline 1109249259Sdim // functions which allocate a lot of stack space because it would increase 1110249259Sdim // the caller stack usage dramatically. 1111249259Sdim if (IsCallerRecursive && 1112249259Sdim AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) 1113249259Sdim return false; 1114249259Sdim 1115249259Sdim break; 1116249259Sdim } 1117249259Sdim 1118263508Sdim TerminatorInst *TI = BB->getTerminator(); 1119263508Sdim 1120249259Sdim // Add in the live successors by first checking whether we have terminator 1121249259Sdim // that may be simplified based on the values simplified by this call. 1122249259Sdim if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 1123249259Sdim if (BI->isConditional()) { 1124249259Sdim Value *Cond = BI->getCondition(); 1125249259Sdim if (ConstantInt *SimpleCond 1126249259Sdim = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 1127249259Sdim BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0)); 1128249259Sdim continue; 1129249259Sdim } 1130249259Sdim } 1131249259Sdim } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 1132249259Sdim Value *Cond = SI->getCondition(); 1133249259Sdim if (ConstantInt *SimpleCond 1134249259Sdim = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 1135249259Sdim BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor()); 1136249259Sdim continue; 1137249259Sdim } 1138249259Sdim } 1139249259Sdim 1140249259Sdim // If we're unable to select a particular successor, just count all of 1141249259Sdim // them. 1142249259Sdim for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize; 1143249259Sdim ++TIdx) 1144249259Sdim BBWorklist.insert(TI->getSuccessor(TIdx)); 1145249259Sdim 1146249259Sdim // If we had any successors at this point, than post-inlining is likely to 1147249259Sdim // have them as well. Note that we assume any basic blocks which existed 1148249259Sdim // due to branches or switches which folded above will also fold after 1149249259Sdim // inlining. 1150249259Sdim if (SingleBB && TI->getNumSuccessors() > 1) { 1151249259Sdim // Take off the bonus we applied to the threshold. 1152249259Sdim Threshold -= SingleBBBonus; 1153249259Sdim SingleBB = false; 1154249259Sdim } 1155249259Sdim } 1156249259Sdim 1157249259Sdim // If this is a noduplicate call, we can still inline as long as 1158249259Sdim // inlining this would cause the removal of the caller (so the instruction 1159249259Sdim // is not actually duplicated, just moved). 1160249259Sdim if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall) 1161249259Sdim return false; 1162249259Sdim 1163249259Sdim Threshold += VectorBonus; 1164249259Sdim 1165249259Sdim return Cost < Threshold; 1166249259Sdim} 1167249259Sdim 1168249259Sdim#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1169249259Sdim/// \brief Dump stats about this call's analysis. 1170249259Sdimvoid CallAnalyzer::dump() { 1171249259Sdim#define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n" 1172249259Sdim DEBUG_PRINT_STAT(NumConstantArgs); 1173249259Sdim DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs); 1174249259Sdim DEBUG_PRINT_STAT(NumAllocaArgs); 1175249259Sdim DEBUG_PRINT_STAT(NumConstantPtrCmps); 1176249259Sdim DEBUG_PRINT_STAT(NumConstantPtrDiffs); 1177249259Sdim DEBUG_PRINT_STAT(NumInstructionsSimplified); 1178249259Sdim DEBUG_PRINT_STAT(SROACostSavings); 1179249259Sdim DEBUG_PRINT_STAT(SROACostSavingsLost); 1180249259Sdim DEBUG_PRINT_STAT(ContainsNoDuplicateCall); 1181249259Sdim#undef DEBUG_PRINT_STAT 1182249259Sdim} 1183249259Sdim#endif 1184249259Sdim 1185249259SdimINITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis", 1186249259Sdim true, true) 1187249259SdimINITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 1188249259SdimINITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis", 1189249259Sdim true, true) 1190249259Sdim 1191249259Sdimchar InlineCostAnalysis::ID = 0; 1192249259Sdim 1193249259SdimInlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID), TD(0) {} 1194249259Sdim 1195249259SdimInlineCostAnalysis::~InlineCostAnalysis() {} 1196249259Sdim 1197249259Sdimvoid InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { 1198249259Sdim AU.setPreservesAll(); 1199249259Sdim AU.addRequired<TargetTransformInfo>(); 1200249259Sdim CallGraphSCCPass::getAnalysisUsage(AU); 1201249259Sdim} 1202249259Sdim 1203249259Sdimbool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) { 1204249259Sdim TD = getAnalysisIfAvailable<DataLayout>(); 1205249259Sdim TTI = &getAnalysis<TargetTransformInfo>(); 1206249259Sdim return false; 1207249259Sdim} 1208249259Sdim 1209249259SdimInlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) { 1210249259Sdim return getInlineCost(CS, CS.getCalledFunction(), Threshold); 1211249259Sdim} 1212249259Sdim 1213263508Sdim/// \brief Test that two functions either have or have not the given attribute 1214263508Sdim/// at the same time. 1215263508Sdimstatic bool attributeMatches(Function *F1, Function *F2, 1216263508Sdim Attribute::AttrKind Attr) { 1217263508Sdim return F1->hasFnAttribute(Attr) == F2->hasFnAttribute(Attr); 1218263508Sdim} 1219263508Sdim 1220263508Sdim/// \brief Test that there are no attribute conflicts between Caller and Callee 1221263508Sdim/// that prevent inlining. 1222263508Sdimstatic bool functionsHaveCompatibleAttributes(Function *Caller, 1223263508Sdim Function *Callee) { 1224263508Sdim return attributeMatches(Caller, Callee, Attribute::SanitizeAddress) && 1225263508Sdim attributeMatches(Caller, Callee, Attribute::SanitizeMemory) && 1226263508Sdim attributeMatches(Caller, Callee, Attribute::SanitizeThread); 1227263508Sdim} 1228263508Sdim 1229249259SdimInlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee, 1230249259Sdim int Threshold) { 1231249259Sdim // Cannot inline indirect calls. 1232249259Sdim if (!Callee) 1233249259Sdim return llvm::InlineCost::getNever(); 1234249259Sdim 1235249259Sdim // Calls to functions with always-inline attributes should be inlined 1236249259Sdim // whenever possible. 1237263508Sdim if (Callee->hasFnAttribute(Attribute::AlwaysInline)) { 1238249259Sdim if (isInlineViable(*Callee)) 1239249259Sdim return llvm::InlineCost::getAlways(); 1240249259Sdim return llvm::InlineCost::getNever(); 1241249259Sdim } 1242249259Sdim 1243263508Sdim // Never inline functions with conflicting attributes (unless callee has 1244263508Sdim // always-inline attribute). 1245263508Sdim if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee)) 1246263508Sdim return llvm::InlineCost::getNever(); 1247263508Sdim 1248263508Sdim // Don't inline this call if the caller has the optnone attribute. 1249263508Sdim if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone)) 1250263508Sdim return llvm::InlineCost::getNever(); 1251263508Sdim 1252249259Sdim // Don't inline functions which can be redefined at link-time to mean 1253249259Sdim // something else. Don't inline functions marked noinline or call sites 1254249259Sdim // marked noinline. 1255249259Sdim if (Callee->mayBeOverridden() || 1256263508Sdim Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline()) 1257249259Sdim return llvm::InlineCost::getNever(); 1258249259Sdim 1259249259Sdim DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName() 1260249259Sdim << "...\n"); 1261249259Sdim 1262249259Sdim CallAnalyzer CA(TD, *TTI, *Callee, Threshold); 1263249259Sdim bool ShouldInline = CA.analyzeCall(CS); 1264249259Sdim 1265249259Sdim DEBUG(CA.dump()); 1266249259Sdim 1267249259Sdim // Check if there was a reason to force inlining or no inlining. 1268249259Sdim if (!ShouldInline && CA.getCost() < CA.getThreshold()) 1269249259Sdim return InlineCost::getNever(); 1270249259Sdim if (ShouldInline && CA.getCost() >= CA.getThreshold()) 1271249259Sdim return InlineCost::getAlways(); 1272249259Sdim 1273249259Sdim return llvm::InlineCost::get(CA.getCost(), CA.getThreshold()); 1274249259Sdim} 1275249259Sdim 1276249259Sdimbool InlineCostAnalysis::isInlineViable(Function &F) { 1277249259Sdim bool ReturnsTwice = 1278249259Sdim F.getAttributes().hasAttribute(AttributeSet::FunctionIndex, 1279249259Sdim Attribute::ReturnsTwice); 1280249259Sdim for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) { 1281249259Sdim // Disallow inlining of functions which contain an indirect branch. 1282249259Sdim if (isa<IndirectBrInst>(BI->getTerminator())) 1283249259Sdim return false; 1284249259Sdim 1285249259Sdim for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; 1286249259Sdim ++II) { 1287249259Sdim CallSite CS(II); 1288249259Sdim if (!CS) 1289249259Sdim continue; 1290249259Sdim 1291249259Sdim // Disallow recursive calls. 1292249259Sdim if (&F == CS.getCalledFunction()) 1293249259Sdim return false; 1294249259Sdim 1295249259Sdim // Disallow calls which expose returns-twice to a function not previously 1296249259Sdim // attributed as such. 1297249259Sdim if (!ReturnsTwice && CS.isCall() && 1298249259Sdim cast<CallInst>(CS.getInstruction())->canReturnTwice()) 1299249259Sdim return false; 1300249259Sdim } 1301249259Sdim } 1302249259Sdim 1303249259Sdim return true; 1304249259Sdim} 1305