LLVM API Documentation

Inliner.cpp
Go to the documentation of this file.
00001 //===- Inliner.cpp - Code common to all inliners --------------------------===//
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 the mechanics required to implement inlining without
00011 // missing any calls and updating the call graph.  The decisions of which calls
00012 // are profitable to inline are implemented elsewhere.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Transforms/IPO/InlinerPass.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/ADT/Statistic.h"
00019 #include "llvm/Analysis/CallGraph.h"
00020 #include "llvm/Analysis/InlineCost.h"
00021 #include "llvm/IR/CallSite.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/DiagnosticInfo.h"
00024 #include "llvm/IR/Instructions.h"
00025 #include "llvm/IR/IntrinsicInst.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Target/TargetLibraryInfo.h"
00031 #include "llvm/Transforms/Utils/Cloning.h"
00032 #include "llvm/Transforms/Utils/Local.h"
00033 using namespace llvm;
00034 
00035 #define DEBUG_TYPE "inline"
00036 
00037 STATISTIC(NumInlined, "Number of functions inlined");
00038 STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
00039 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
00040 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
00041 
00042 // This weirdly named statistic tracks the number of times that, when attempting
00043 // to inline a function A into B, we analyze the callers of B in order to see
00044 // if those would be more profitable and blocked inline steps.
00045 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
00046 
00047 static cl::opt<int>
00048 InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
00049         cl::desc("Control the amount of inlining to perform (default = 225)"));
00050 
00051 static cl::opt<int>
00052 HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
00053               cl::desc("Threshold for inlining functions with inline hint"));
00054 
00055 // We instroduce this threshold to help performance of instrumentation based
00056 // PGO before we actually hook up inliner with analysis passes such as BPI and
00057 // BFI.
00058 static cl::opt<int>
00059 ColdThreshold("inlinecold-threshold", cl::Hidden, cl::init(225),
00060               cl::desc("Threshold for inlining functions with cold attribute"));
00061 
00062 // Threshold to use when optsize is specified (and there is no -inline-limit).
00063 const int OptSizeThreshold = 75;
00064 
00065 Inliner::Inliner(char &ID) 
00066   : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
00067 
00068 Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
00069   : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
00070                                           InlineLimit : Threshold),
00071     InsertLifetime(InsertLifetime) {}
00072 
00073 /// getAnalysisUsage - For this class, we declare that we require and preserve
00074 /// the call graph.  If the derived class implements this method, it should
00075 /// always explicitly call the implementation here.
00076 void Inliner::getAnalysisUsage(AnalysisUsage &AU) const {
00077   CallGraphSCCPass::getAnalysisUsage(AU);
00078 }
00079 
00080 
00081 typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
00082 InlinedArrayAllocasTy;
00083 
00084 /// \brief If the inlined function had a higher stack protection level than the
00085 /// calling function, then bump up the caller's stack protection level.
00086 static void AdjustCallerSSPLevel(Function *Caller, Function *Callee) {
00087   // If upgrading the SSP attribute, clear out the old SSP Attributes first.
00088   // Having multiple SSP attributes doesn't actually hurt, but it adds useless
00089   // clutter to the IR.
00090   AttrBuilder B;
00091   B.addAttribute(Attribute::StackProtect)
00092     .addAttribute(Attribute::StackProtectStrong);
00093   AttributeSet OldSSPAttr = AttributeSet::get(Caller->getContext(),
00094                                               AttributeSet::FunctionIndex,
00095                                               B);
00096   AttributeSet CallerAttr = Caller->getAttributes(),
00097                CalleeAttr = Callee->getAttributes();
00098 
00099   if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
00100                               Attribute::StackProtectReq)) {
00101     Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
00102     Caller->addFnAttr(Attribute::StackProtectReq);
00103   } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
00104                                      Attribute::StackProtectStrong) &&
00105              !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
00106                                       Attribute::StackProtectReq)) {
00107     Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
00108     Caller->addFnAttr(Attribute::StackProtectStrong);
00109   } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
00110                                      Attribute::StackProtect) &&
00111            !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
00112                                     Attribute::StackProtectReq) &&
00113            !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
00114                                     Attribute::StackProtectStrong))
00115     Caller->addFnAttr(Attribute::StackProtect);
00116 }
00117 
00118 /// InlineCallIfPossible - If it is possible to inline the specified call site,
00119 /// do so and update the CallGraph for this operation.
00120 ///
00121 /// This function also does some basic book-keeping to update the IR.  The
00122 /// InlinedArrayAllocas map keeps track of any allocas that are already
00123 /// available from other  functions inlined into the caller.  If we are able to
00124 /// inline this call site we attempt to reuse already available allocas or add
00125 /// any new allocas to the set if not possible.
00126 static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
00127                                  InlinedArrayAllocasTy &InlinedArrayAllocas,
00128                                  int InlineHistory, bool InsertLifetime,
00129                                  const DataLayout *DL) {
00130   Function *Callee = CS.getCalledFunction();
00131   Function *Caller = CS.getCaller();
00132 
00133   // Try to inline the function.  Get the list of static allocas that were
00134   // inlined.
00135   if (!InlineFunction(CS, IFI, InsertLifetime))
00136     return false;
00137 
00138   AdjustCallerSSPLevel(Caller, Callee);
00139 
00140   // Look at all of the allocas that we inlined through this call site.  If we
00141   // have already inlined other allocas through other calls into this function,
00142   // then we know that they have disjoint lifetimes and that we can merge them.
00143   //
00144   // There are many heuristics possible for merging these allocas, and the
00145   // different options have different tradeoffs.  One thing that we *really*
00146   // don't want to hurt is SRoA: once inlining happens, often allocas are no
00147   // longer address taken and so they can be promoted.
00148   //
00149   // Our "solution" for that is to only merge allocas whose outermost type is an
00150   // array type.  These are usually not promoted because someone is using a
00151   // variable index into them.  These are also often the most important ones to
00152   // merge.
00153   //
00154   // A better solution would be to have real memory lifetime markers in the IR
00155   // and not have the inliner do any merging of allocas at all.  This would
00156   // allow the backend to do proper stack slot coloring of all allocas that
00157   // *actually make it to the backend*, which is really what we want.
00158   //
00159   // Because we don't have this information, we do this simple and useful hack.
00160   //
00161   SmallPtrSet<AllocaInst*, 16> UsedAllocas;
00162   
00163   // When processing our SCC, check to see if CS was inlined from some other
00164   // call site.  For example, if we're processing "A" in this code:
00165   //   A() { B() }
00166   //   B() { x = alloca ... C() }
00167   //   C() { y = alloca ... }
00168   // Assume that C was not inlined into B initially, and so we're processing A
00169   // and decide to inline B into A.  Doing this makes an alloca available for
00170   // reuse and makes a callsite (C) available for inlining.  When we process
00171   // the C call site we don't want to do any alloca merging between X and Y
00172   // because their scopes are not disjoint.  We could make this smarter by
00173   // keeping track of the inline history for each alloca in the
00174   // InlinedArrayAllocas but this isn't likely to be a significant win.
00175   if (InlineHistory != -1)  // Only do merging for top-level call sites in SCC.
00176     return true;
00177   
00178   // Loop over all the allocas we have so far and see if they can be merged with
00179   // a previously inlined alloca.  If not, remember that we had it.
00180   for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
00181        AllocaNo != e; ++AllocaNo) {
00182     AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
00183     
00184     // Don't bother trying to merge array allocations (they will usually be
00185     // canonicalized to be an allocation *of* an array), or allocations whose
00186     // type is not itself an array (because we're afraid of pessimizing SRoA).
00187     ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
00188     if (!ATy || AI->isArrayAllocation())
00189       continue;
00190     
00191     // Get the list of all available allocas for this array type.
00192     std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
00193     
00194     // Loop over the allocas in AllocasForType to see if we can reuse one.  Note
00195     // that we have to be careful not to reuse the same "available" alloca for
00196     // multiple different allocas that we just inlined, we use the 'UsedAllocas'
00197     // set to keep track of which "available" allocas are being used by this
00198     // function.  Also, AllocasForType can be empty of course!
00199     bool MergedAwayAlloca = false;
00200     for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
00201       AllocaInst *AvailableAlloca = AllocasForType[i];
00202 
00203       unsigned Align1 = AI->getAlignment(),
00204                Align2 = AvailableAlloca->getAlignment();
00205       // If we don't have data layout information, and only one alloca is using
00206       // the target default, then we can't safely merge them because we can't
00207       // pick the greater alignment.
00208       if (!DL && (!Align1 || !Align2) && Align1 != Align2)
00209         continue;
00210       
00211       // The available alloca has to be in the right function, not in some other
00212       // function in this SCC.
00213       if (AvailableAlloca->getParent() != AI->getParent())
00214         continue;
00215       
00216       // If the inlined function already uses this alloca then we can't reuse
00217       // it.
00218       if (!UsedAllocas.insert(AvailableAlloca))
00219         continue;
00220       
00221       // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
00222       // success!
00223       DEBUG(dbgs() << "    ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
00224                    << *AvailableAlloca << '\n');
00225       
00226       AI->replaceAllUsesWith(AvailableAlloca);
00227 
00228       if (Align1 != Align2) {
00229         if (!Align1 || !Align2) {
00230           assert(DL && "DataLayout required to compare default alignments");
00231           unsigned TypeAlign = DL->getABITypeAlignment(AI->getAllocatedType());
00232 
00233           Align1 = Align1 ? Align1 : TypeAlign;
00234           Align2 = Align2 ? Align2 : TypeAlign;
00235         }
00236 
00237         if (Align1 > Align2)
00238           AvailableAlloca->setAlignment(AI->getAlignment());
00239       }
00240 
00241       AI->eraseFromParent();
00242       MergedAwayAlloca = true;
00243       ++NumMergedAllocas;
00244       IFI.StaticAllocas[AllocaNo] = nullptr;
00245       break;
00246     }
00247 
00248     // If we already nuked the alloca, we're done with it.
00249     if (MergedAwayAlloca)
00250       continue;
00251     
00252     // If we were unable to merge away the alloca either because there are no
00253     // allocas of the right type available or because we reused them all
00254     // already, remember that this alloca came from an inlined function and mark
00255     // it used so we don't reuse it for other allocas from this inline
00256     // operation.
00257     AllocasForType.push_back(AI);
00258     UsedAllocas.insert(AI);
00259   }
00260   
00261   return true;
00262 }
00263 
00264 unsigned Inliner::getInlineThreshold(CallSite CS) const {
00265   int thres = InlineThreshold; // -inline-threshold or else selected by
00266                                // overall opt level
00267 
00268   // If -inline-threshold is not given, listen to the optsize attribute when it
00269   // would decrease the threshold.
00270   Function *Caller = CS.getCaller();
00271   bool OptSize = Caller && !Caller->isDeclaration() &&
00272     Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00273                                          Attribute::OptimizeForSize);
00274   if (!(InlineLimit.getNumOccurrences() > 0) && OptSize &&
00275       OptSizeThreshold < thres)
00276     thres = OptSizeThreshold;
00277 
00278   // Listen to the inlinehint attribute when it would increase the threshold
00279   // and the caller does not need to minimize its size.
00280   Function *Callee = CS.getCalledFunction();
00281   bool InlineHint = Callee && !Callee->isDeclaration() &&
00282     Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00283                                          Attribute::InlineHint);
00284   if (InlineHint && HintThreshold > thres
00285       && !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00286                                                Attribute::MinSize))
00287     thres = HintThreshold;
00288 
00289   // Listen to the cold attribute when it would decrease the threshold.
00290   bool ColdCallee = Callee && !Callee->isDeclaration() &&
00291     Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00292                                          Attribute::Cold);
00293   // Command line argument for InlineLimit will override the default
00294   // ColdThreshold. If we have -inline-threshold but no -inlinecold-threshold,
00295   // do not use the default cold threshold even if it is smaller.
00296   if ((InlineLimit.getNumOccurrences() == 0 ||
00297        ColdThreshold.getNumOccurrences() > 0) && ColdCallee &&
00298       ColdThreshold < thres)
00299     thres = ColdThreshold;
00300 
00301   return thres;
00302 }
00303 
00304 static void emitAnalysis(CallSite CS, const Twine &Msg) {
00305   Function *Caller = CS.getCaller();
00306   LLVMContext &Ctx = Caller->getContext();
00307   DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
00308   emitOptimizationRemarkAnalysis(Ctx, DEBUG_TYPE, *Caller, DLoc, Msg);
00309 }
00310 
00311 /// shouldInline - Return true if the inliner should attempt to inline
00312 /// at the given CallSite.
00313 bool Inliner::shouldInline(CallSite CS) {
00314   InlineCost IC = getInlineCost(CS);
00315   
00316   if (IC.isAlways()) {
00317     DEBUG(dbgs() << "    Inlining: cost=always"
00318           << ", Call: " << *CS.getInstruction() << "\n");
00319     emitAnalysis(CS, Twine(CS.getCalledFunction()->getName()) +
00320                          " should always be inlined (cost=always)");
00321     return true;
00322   }
00323   
00324   if (IC.isNever()) {
00325     DEBUG(dbgs() << "    NOT Inlining: cost=never"
00326           << ", Call: " << *CS.getInstruction() << "\n");
00327     emitAnalysis(CS, Twine(CS.getCalledFunction()->getName() +
00328                            " should never be inlined (cost=never)"));
00329     return false;
00330   }
00331   
00332   Function *Caller = CS.getCaller();
00333   if (!IC) {
00334     DEBUG(dbgs() << "    NOT Inlining: cost=" << IC.getCost()
00335           << ", thres=" << (IC.getCostDelta() + IC.getCost())
00336           << ", Call: " << *CS.getInstruction() << "\n");
00337     emitAnalysis(CS, Twine(CS.getCalledFunction()->getName() +
00338                            " too costly to inline (cost=") +
00339                          Twine(IC.getCost()) + ", threshold=" +
00340                          Twine(IC.getCostDelta() + IC.getCost()) + ")");
00341     return false;
00342   }
00343   
00344   // Try to detect the case where the current inlining candidate caller (call
00345   // it B) is a static or linkonce-ODR function and is an inlining candidate
00346   // elsewhere, and the current candidate callee (call it C) is large enough
00347   // that inlining it into B would make B too big to inline later. In these
00348   // circumstances it may be best not to inline C into B, but to inline B into
00349   // its callers.
00350   //
00351   // This only applies to static and linkonce-ODR functions because those are
00352   // expected to be available for inlining in the translation units where they
00353   // are used. Thus we will always have the opportunity to make local inlining
00354   // decisions. Importantly the linkonce-ODR linkage covers inline functions
00355   // and templates in C++.
00356   //
00357   // FIXME: All of this logic should be sunk into getInlineCost. It relies on
00358   // the internal implementation of the inline cost metrics rather than
00359   // treating them as truly abstract units etc.
00360   if (Caller->hasLocalLinkage() ||
00361       Caller->getLinkage() == GlobalValue::LinkOnceODRLinkage) {
00362     int TotalSecondaryCost = 0;
00363     // The candidate cost to be imposed upon the current function.
00364     int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
00365     // This bool tracks what happens if we do NOT inline C into B.
00366     bool callerWillBeRemoved = Caller->hasLocalLinkage();
00367     // This bool tracks what happens if we DO inline C into B.
00368     bool inliningPreventsSomeOuterInline = false;
00369     for (User *U : Caller->users()) {
00370       CallSite CS2(U);
00371 
00372       // If this isn't a call to Caller (it could be some other sort
00373       // of reference) skip it.  Such references will prevent the caller
00374       // from being removed.
00375       if (!CS2 || CS2.getCalledFunction() != Caller) {
00376         callerWillBeRemoved = false;
00377         continue;
00378       }
00379 
00380       InlineCost IC2 = getInlineCost(CS2);
00381       ++NumCallerCallersAnalyzed;
00382       if (!IC2) {
00383         callerWillBeRemoved = false;
00384         continue;
00385       }
00386       if (IC2.isAlways())
00387         continue;
00388 
00389       // See if inlining or original callsite would erase the cost delta of
00390       // this callsite. We subtract off the penalty for the call instruction,
00391       // which we would be deleting.
00392       if (IC2.getCostDelta() <= CandidateCost) {
00393         inliningPreventsSomeOuterInline = true;
00394         TotalSecondaryCost += IC2.getCost();
00395       }
00396     }
00397     // If all outer calls to Caller would get inlined, the cost for the last
00398     // one is set very low by getInlineCost, in anticipation that Caller will
00399     // be removed entirely.  We did not account for this above unless there
00400     // is only one caller of Caller.
00401     if (callerWillBeRemoved && !Caller->use_empty())
00402       TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
00403 
00404     if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
00405       DEBUG(dbgs() << "    NOT Inlining: " << *CS.getInstruction() <<
00406            " Cost = " << IC.getCost() <<
00407            ", outer Cost = " << TotalSecondaryCost << '\n');
00408       emitAnalysis(
00409           CS, Twine("Not inlining. Cost of inlining " +
00410                     CS.getCalledFunction()->getName() +
00411                     " increases the cost of inlining " +
00412                     CS.getCaller()->getName() + " in other contexts"));
00413       return false;
00414     }
00415   }
00416 
00417   DEBUG(dbgs() << "    Inlining: cost=" << IC.getCost()
00418         << ", thres=" << (IC.getCostDelta() + IC.getCost())
00419         << ", Call: " << *CS.getInstruction() << '\n');
00420   emitAnalysis(
00421       CS, CS.getCalledFunction()->getName() + Twine(" can be inlined into ") +
00422               CS.getCaller()->getName() + " with cost=" + Twine(IC.getCost()) +
00423               " (threshold=" + Twine(IC.getCostDelta() + IC.getCost()) + ")");
00424   return true;
00425 }
00426 
00427 /// InlineHistoryIncludes - Return true if the specified inline history ID
00428 /// indicates an inline history that includes the specified function.
00429 static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
00430             const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
00431   while (InlineHistoryID != -1) {
00432     assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
00433            "Invalid inline history ID");
00434     if (InlineHistory[InlineHistoryID].first == F)
00435       return true;
00436     InlineHistoryID = InlineHistory[InlineHistoryID].second;
00437   }
00438   return false;
00439 }
00440 
00441 bool Inliner::runOnSCC(CallGraphSCC &SCC) {
00442   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
00443   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00444   const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
00445   const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
00446 
00447   SmallPtrSet<Function*, 8> SCCFunctions;
00448   DEBUG(dbgs() << "Inliner visiting SCC:");
00449   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00450     Function *F = (*I)->getFunction();
00451     if (F) SCCFunctions.insert(F);
00452     DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
00453   }
00454 
00455   // Scan through and identify all call sites ahead of time so that we only
00456   // inline call sites in the original functions, not call sites that result
00457   // from inlining other functions.
00458   SmallVector<std::pair<CallSite, int>, 16> CallSites;
00459   
00460   // When inlining a callee produces new call sites, we want to keep track of
00461   // the fact that they were inlined from the callee.  This allows us to avoid
00462   // infinite inlining in some obscure cases.  To represent this, we use an
00463   // index into the InlineHistory vector.
00464   SmallVector<std::pair<Function*, int>, 8> InlineHistory;
00465 
00466   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00467     Function *F = (*I)->getFunction();
00468     if (!F) continue;
00469     
00470     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00471       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00472         CallSite CS(cast<Value>(I));
00473         // If this isn't a call, or it is a call to an intrinsic, it can
00474         // never be inlined.
00475         if (!CS || isa<IntrinsicInst>(I))
00476           continue;
00477         
00478         // If this is a direct call to an external function, we can never inline
00479         // it.  If it is an indirect call, inlining may resolve it to be a
00480         // direct call, so we keep it.
00481         if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
00482           continue;
00483         
00484         CallSites.push_back(std::make_pair(CS, -1));
00485       }
00486   }
00487 
00488   DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
00489 
00490   // If there are no calls in this function, exit early.
00491   if (CallSites.empty())
00492     return false;
00493   
00494   // Now that we have all of the call sites, move the ones to functions in the
00495   // current SCC to the end of the list.
00496   unsigned FirstCallInSCC = CallSites.size();
00497   for (unsigned i = 0; i < FirstCallInSCC; ++i)
00498     if (Function *F = CallSites[i].first.getCalledFunction())
00499       if (SCCFunctions.count(F))
00500         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
00501 
00502   
00503   InlinedArrayAllocasTy InlinedArrayAllocas;
00504   InlineFunctionInfo InlineInfo(&CG, DL);
00505   
00506   // Now that we have all of the call sites, loop over them and inline them if
00507   // it looks profitable to do so.
00508   bool Changed = false;
00509   bool LocalChange;
00510   do {
00511     LocalChange = false;
00512     // Iterate over the outer loop because inlining functions can cause indirect
00513     // calls to become direct calls.
00514     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
00515       CallSite CS = CallSites[CSi].first;
00516       
00517       Function *Caller = CS.getCaller();
00518       Function *Callee = CS.getCalledFunction();
00519 
00520       // If this call site is dead and it is to a readonly function, we should
00521       // just delete the call instead of trying to inline it, regardless of
00522       // size.  This happens because IPSCCP propagates the result out of the
00523       // call and then we're left with the dead call.
00524       if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
00525         DEBUG(dbgs() << "    -> Deleting dead call: "
00526                      << *CS.getInstruction() << "\n");
00527         // Update the call graph by deleting the edge from Callee to Caller.
00528         CG[Caller]->removeCallEdgeFor(CS);
00529         CS.getInstruction()->eraseFromParent();
00530         ++NumCallsDeleted;
00531       } else {
00532         // We can only inline direct calls to non-declarations.
00533         if (!Callee || Callee->isDeclaration()) continue;
00534       
00535         // If this call site was obtained by inlining another function, verify
00536         // that the include path for the function did not include the callee
00537         // itself.  If so, we'd be recursively inlining the same function,
00538         // which would provide the same callsites, which would cause us to
00539         // infinitely inline.
00540         int InlineHistoryID = CallSites[CSi].second;
00541         if (InlineHistoryID != -1 &&
00542             InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
00543           continue;
00544         
00545         LLVMContext &CallerCtx = Caller->getContext();
00546 
00547         // Get DebugLoc to report. CS will be invalid after Inliner.
00548         DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
00549 
00550         // If the policy determines that we should inline this function,
00551         // try to do so.
00552         if (!shouldInline(CS)) {
00553           emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00554                                        Twine(Callee->getName() +
00555                                              " will not be inlined into " +
00556                                              Caller->getName()));
00557           continue;
00558         }
00559 
00560         // Attempt to inline the function.
00561         if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
00562                                   InlineHistoryID, InsertLifetime, DL)) {
00563           emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00564                                        Twine(Callee->getName() +
00565                                              " will not be inlined into " +
00566                                              Caller->getName()));
00567           continue;
00568         }
00569         ++NumInlined;
00570 
00571         // Report the inline decision.
00572         emitOptimizationRemark(
00573             CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00574             Twine(Callee->getName() + " inlined into " + Caller->getName()));
00575 
00576         // If inlining this function gave us any new call sites, throw them
00577         // onto our worklist to process.  They are useful inline candidates.
00578         if (!InlineInfo.InlinedCalls.empty()) {
00579           // Create a new inline history entry for this, so that we remember
00580           // that these new callsites came about due to inlining Callee.
00581           int NewHistoryID = InlineHistory.size();
00582           InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
00583 
00584           for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
00585                i != e; ++i) {
00586             Value *Ptr = InlineInfo.InlinedCalls[i];
00587             CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
00588           }
00589         }
00590       }
00591       
00592       // If we inlined or deleted the last possible call site to the function,
00593       // delete the function body now.
00594       if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
00595           // TODO: Can remove if in SCC now.
00596           !SCCFunctions.count(Callee) &&
00597           
00598           // The function may be apparently dead, but if there are indirect
00599           // callgraph references to the node, we cannot delete it yet, this
00600           // could invalidate the CGSCC iterator.
00601           CG[Callee]->getNumReferences() == 0) {
00602         DEBUG(dbgs() << "    -> Deleting dead function: "
00603               << Callee->getName() << "\n");
00604         CallGraphNode *CalleeNode = CG[Callee];
00605         
00606         // Remove any call graph edges from the callee to its callees.
00607         CalleeNode->removeAllCalledFunctions();
00608         
00609         // Removing the node for callee from the call graph and delete it.
00610         delete CG.removeFunctionFromModule(CalleeNode);
00611         ++NumDeleted;
00612       }
00613 
00614       // Remove this call site from the list.  If possible, use 
00615       // swap/pop_back for efficiency, but do not use it if doing so would
00616       // move a call site to a function in this SCC before the
00617       // 'FirstCallInSCC' barrier.
00618       if (SCC.isSingular()) {
00619         CallSites[CSi] = CallSites.back();
00620         CallSites.pop_back();
00621       } else {
00622         CallSites.erase(CallSites.begin()+CSi);
00623       }
00624       --CSi;
00625 
00626       Changed = true;
00627       LocalChange = true;
00628     }
00629   } while (LocalChange);
00630 
00631   return Changed;
00632 }
00633 
00634 // doFinalization - Remove now-dead linkonce functions at the end of
00635 // processing to avoid breaking the SCC traversal.
00636 bool Inliner::doFinalization(CallGraph &CG) {
00637   return removeDeadFunctions(CG);
00638 }
00639 
00640 /// removeDeadFunctions - Remove dead functions that are not included in
00641 /// DNR (Do Not Remove) list.
00642 bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
00643   SmallVector<CallGraphNode*, 16> FunctionsToRemove;
00644 
00645   // Scan for all of the functions, looking for ones that should now be removed
00646   // from the program.  Insert the dead ones in the FunctionsToRemove set.
00647   for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
00648     CallGraphNode *CGN = I->second;
00649     Function *F = CGN->getFunction();
00650     if (!F || F->isDeclaration())
00651       continue;
00652 
00653     // Handle the case when this function is called and we only want to care
00654     // about always-inline functions. This is a bit of a hack to share code
00655     // between here and the InlineAlways pass.
00656     if (AlwaysInlineOnly &&
00657         !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00658                                          Attribute::AlwaysInline))
00659       continue;
00660 
00661     // If the only remaining users of the function are dead constants, remove
00662     // them.
00663     F->removeDeadConstantUsers();
00664 
00665     if (!F->isDefTriviallyDead())
00666       continue;
00667     
00668     // Remove any call graph edges from the function to its callees.
00669     CGN->removeAllCalledFunctions();
00670 
00671     // Remove any edges from the external node to the function's call graph
00672     // node.  These edges might have been made irrelegant due to
00673     // optimization of the program.
00674     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
00675 
00676     // Removing the node for callee from the call graph and delete it.
00677     FunctionsToRemove.push_back(CGN);
00678   }
00679   if (FunctionsToRemove.empty())
00680     return false;
00681 
00682   // Now that we know which functions to delete, do so.  We didn't want to do
00683   // this inline, because that would invalidate our CallGraph::iterator
00684   // objects. :(
00685   //
00686   // Note that it doesn't matter that we are iterating over a non-stable order
00687   // here to do this, it doesn't matter which order the functions are deleted
00688   // in.
00689   array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
00690   FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
00691                                       FunctionsToRemove.end()),
00692                           FunctionsToRemove.end());
00693   for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
00694                                                   E = FunctionsToRemove.end();
00695        I != E; ++I) {
00696     delete CG.removeFunctionFromModule(*I);
00697     ++NumDeleted;
00698   }
00699   return true;
00700 }