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() || Caller->hasLinkOnceODRLinkage()) {
00361     int TotalSecondaryCost = 0;
00362     // The candidate cost to be imposed upon the current function.
00363     int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
00364     // This bool tracks what happens if we do NOT inline C into B.
00365     bool callerWillBeRemoved = Caller->hasLocalLinkage();
00366     // This bool tracks what happens if we DO inline C into B.
00367     bool inliningPreventsSomeOuterInline = false;
00368     for (User *U : Caller->users()) {
00369       CallSite CS2(U);
00370 
00371       // If this isn't a call to Caller (it could be some other sort
00372       // of reference) skip it.  Such references will prevent the caller
00373       // from being removed.
00374       if (!CS2 || CS2.getCalledFunction() != Caller) {
00375         callerWillBeRemoved = false;
00376         continue;
00377       }
00378 
00379       InlineCost IC2 = getInlineCost(CS2);
00380       ++NumCallerCallersAnalyzed;
00381       if (!IC2) {
00382         callerWillBeRemoved = false;
00383         continue;
00384       }
00385       if (IC2.isAlways())
00386         continue;
00387 
00388       // See if inlining or original callsite would erase the cost delta of
00389       // this callsite. We subtract off the penalty for the call instruction,
00390       // which we would be deleting.
00391       if (IC2.getCostDelta() <= CandidateCost) {
00392         inliningPreventsSomeOuterInline = true;
00393         TotalSecondaryCost += IC2.getCost();
00394       }
00395     }
00396     // If all outer calls to Caller would get inlined, the cost for the last
00397     // one is set very low by getInlineCost, in anticipation that Caller will
00398     // be removed entirely.  We did not account for this above unless there
00399     // is only one caller of Caller.
00400     if (callerWillBeRemoved && !Caller->use_empty())
00401       TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
00402 
00403     if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
00404       DEBUG(dbgs() << "    NOT Inlining: " << *CS.getInstruction() <<
00405            " Cost = " << IC.getCost() <<
00406            ", outer Cost = " << TotalSecondaryCost << '\n');
00407       emitAnalysis(
00408           CS, Twine("Not inlining. Cost of inlining " +
00409                     CS.getCalledFunction()->getName() +
00410                     " increases the cost of inlining " +
00411                     CS.getCaller()->getName() + " in other contexts"));
00412       return false;
00413     }
00414   }
00415 
00416   DEBUG(dbgs() << "    Inlining: cost=" << IC.getCost()
00417         << ", thres=" << (IC.getCostDelta() + IC.getCost())
00418         << ", Call: " << *CS.getInstruction() << '\n');
00419   emitAnalysis(
00420       CS, CS.getCalledFunction()->getName() + Twine(" can be inlined into ") +
00421               CS.getCaller()->getName() + " with cost=" + Twine(IC.getCost()) +
00422               " (threshold=" + Twine(IC.getCostDelta() + IC.getCost()) + ")");
00423   return true;
00424 }
00425 
00426 /// InlineHistoryIncludes - Return true if the specified inline history ID
00427 /// indicates an inline history that includes the specified function.
00428 static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
00429             const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
00430   while (InlineHistoryID != -1) {
00431     assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
00432            "Invalid inline history ID");
00433     if (InlineHistory[InlineHistoryID].first == F)
00434       return true;
00435     InlineHistoryID = InlineHistory[InlineHistoryID].second;
00436   }
00437   return false;
00438 }
00439 
00440 bool Inliner::runOnSCC(CallGraphSCC &SCC) {
00441   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
00442   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00443   const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
00444   const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
00445 
00446   SmallPtrSet<Function*, 8> SCCFunctions;
00447   DEBUG(dbgs() << "Inliner visiting SCC:");
00448   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00449     Function *F = (*I)->getFunction();
00450     if (F) SCCFunctions.insert(F);
00451     DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
00452   }
00453 
00454   // Scan through and identify all call sites ahead of time so that we only
00455   // inline call sites in the original functions, not call sites that result
00456   // from inlining other functions.
00457   SmallVector<std::pair<CallSite, int>, 16> CallSites;
00458   
00459   // When inlining a callee produces new call sites, we want to keep track of
00460   // the fact that they were inlined from the callee.  This allows us to avoid
00461   // infinite inlining in some obscure cases.  To represent this, we use an
00462   // index into the InlineHistory vector.
00463   SmallVector<std::pair<Function*, int>, 8> InlineHistory;
00464 
00465   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00466     Function *F = (*I)->getFunction();
00467     if (!F) continue;
00468     
00469     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00470       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00471         CallSite CS(cast<Value>(I));
00472         // If this isn't a call, or it is a call to an intrinsic, it can
00473         // never be inlined.
00474         if (!CS || isa<IntrinsicInst>(I))
00475           continue;
00476         
00477         // If this is a direct call to an external function, we can never inline
00478         // it.  If it is an indirect call, inlining may resolve it to be a
00479         // direct call, so we keep it.
00480         if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
00481           continue;
00482         
00483         CallSites.push_back(std::make_pair(CS, -1));
00484       }
00485   }
00486 
00487   DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
00488 
00489   // If there are no calls in this function, exit early.
00490   if (CallSites.empty())
00491     return false;
00492   
00493   // Now that we have all of the call sites, move the ones to functions in the
00494   // current SCC to the end of the list.
00495   unsigned FirstCallInSCC = CallSites.size();
00496   for (unsigned i = 0; i < FirstCallInSCC; ++i)
00497     if (Function *F = CallSites[i].first.getCalledFunction())
00498       if (SCCFunctions.count(F))
00499         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
00500 
00501   
00502   InlinedArrayAllocasTy InlinedArrayAllocas;
00503   InlineFunctionInfo InlineInfo(&CG, DL);
00504   
00505   // Now that we have all of the call sites, loop over them and inline them if
00506   // it looks profitable to do so.
00507   bool Changed = false;
00508   bool LocalChange;
00509   do {
00510     LocalChange = false;
00511     // Iterate over the outer loop because inlining functions can cause indirect
00512     // calls to become direct calls.
00513     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
00514       CallSite CS = CallSites[CSi].first;
00515       
00516       Function *Caller = CS.getCaller();
00517       Function *Callee = CS.getCalledFunction();
00518 
00519       // If this call site is dead and it is to a readonly function, we should
00520       // just delete the call instead of trying to inline it, regardless of
00521       // size.  This happens because IPSCCP propagates the result out of the
00522       // call and then we're left with the dead call.
00523       if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
00524         DEBUG(dbgs() << "    -> Deleting dead call: "
00525                      << *CS.getInstruction() << "\n");
00526         // Update the call graph by deleting the edge from Callee to Caller.
00527         CG[Caller]->removeCallEdgeFor(CS);
00528         CS.getInstruction()->eraseFromParent();
00529         ++NumCallsDeleted;
00530       } else {
00531         // We can only inline direct calls to non-declarations.
00532         if (!Callee || Callee->isDeclaration()) continue;
00533       
00534         // If this call site was obtained by inlining another function, verify
00535         // that the include path for the function did not include the callee
00536         // itself.  If so, we'd be recursively inlining the same function,
00537         // which would provide the same callsites, which would cause us to
00538         // infinitely inline.
00539         int InlineHistoryID = CallSites[CSi].second;
00540         if (InlineHistoryID != -1 &&
00541             InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
00542           continue;
00543         
00544         LLVMContext &CallerCtx = Caller->getContext();
00545 
00546         // Get DebugLoc to report. CS will be invalid after Inliner.
00547         DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
00548 
00549         // If the policy determines that we should inline this function,
00550         // try to do so.
00551         if (!shouldInline(CS)) {
00552           emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00553                                        Twine(Callee->getName() +
00554                                              " will not be inlined into " +
00555                                              Caller->getName()));
00556           continue;
00557         }
00558 
00559         // Attempt to inline the function.
00560         if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
00561                                   InlineHistoryID, InsertLifetime, DL)) {
00562           emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00563                                        Twine(Callee->getName() +
00564                                              " will not be inlined into " +
00565                                              Caller->getName()));
00566           continue;
00567         }
00568         ++NumInlined;
00569 
00570         // Report the inline decision.
00571         emitOptimizationRemark(
00572             CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00573             Twine(Callee->getName() + " inlined into " + Caller->getName()));
00574 
00575         // If inlining this function gave us any new call sites, throw them
00576         // onto our worklist to process.  They are useful inline candidates.
00577         if (!InlineInfo.InlinedCalls.empty()) {
00578           // Create a new inline history entry for this, so that we remember
00579           // that these new callsites came about due to inlining Callee.
00580           int NewHistoryID = InlineHistory.size();
00581           InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
00582 
00583           for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
00584                i != e; ++i) {
00585             Value *Ptr = InlineInfo.InlinedCalls[i];
00586             CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
00587           }
00588         }
00589       }
00590       
00591       // If we inlined or deleted the last possible call site to the function,
00592       // delete the function body now.
00593       if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
00594           // TODO: Can remove if in SCC now.
00595           !SCCFunctions.count(Callee) &&
00596           
00597           // The function may be apparently dead, but if there are indirect
00598           // callgraph references to the node, we cannot delete it yet, this
00599           // could invalidate the CGSCC iterator.
00600           CG[Callee]->getNumReferences() == 0) {
00601         DEBUG(dbgs() << "    -> Deleting dead function: "
00602               << Callee->getName() << "\n");
00603         CallGraphNode *CalleeNode = CG[Callee];
00604         
00605         // Remove any call graph edges from the callee to its callees.
00606         CalleeNode->removeAllCalledFunctions();
00607         
00608         // Removing the node for callee from the call graph and delete it.
00609         delete CG.removeFunctionFromModule(CalleeNode);
00610         ++NumDeleted;
00611       }
00612 
00613       // Remove this call site from the list.  If possible, use 
00614       // swap/pop_back for efficiency, but do not use it if doing so would
00615       // move a call site to a function in this SCC before the
00616       // 'FirstCallInSCC' barrier.
00617       if (SCC.isSingular()) {
00618         CallSites[CSi] = CallSites.back();
00619         CallSites.pop_back();
00620       } else {
00621         CallSites.erase(CallSites.begin()+CSi);
00622       }
00623       --CSi;
00624 
00625       Changed = true;
00626       LocalChange = true;
00627     }
00628   } while (LocalChange);
00629 
00630   return Changed;
00631 }
00632 
00633 // doFinalization - Remove now-dead linkonce functions at the end of
00634 // processing to avoid breaking the SCC traversal.
00635 bool Inliner::doFinalization(CallGraph &CG) {
00636   return removeDeadFunctions(CG);
00637 }
00638 
00639 /// removeDeadFunctions - Remove dead functions that are not included in
00640 /// DNR (Do Not Remove) list.
00641 bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
00642   SmallVector<CallGraphNode*, 16> FunctionsToRemove;
00643 
00644   // Scan for all of the functions, looking for ones that should now be removed
00645   // from the program.  Insert the dead ones in the FunctionsToRemove set.
00646   for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
00647     CallGraphNode *CGN = I->second;
00648     Function *F = CGN->getFunction();
00649     if (!F || F->isDeclaration())
00650       continue;
00651 
00652     // Handle the case when this function is called and we only want to care
00653     // about always-inline functions. This is a bit of a hack to share code
00654     // between here and the InlineAlways pass.
00655     if (AlwaysInlineOnly &&
00656         !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00657                                          Attribute::AlwaysInline))
00658       continue;
00659 
00660     // If the only remaining users of the function are dead constants, remove
00661     // them.
00662     F->removeDeadConstantUsers();
00663 
00664     if (!F->isDefTriviallyDead())
00665       continue;
00666     
00667     // Remove any call graph edges from the function to its callees.
00668     CGN->removeAllCalledFunctions();
00669 
00670     // Remove any edges from the external node to the function's call graph
00671     // node.  These edges might have been made irrelegant due to
00672     // optimization of the program.
00673     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
00674 
00675     // Removing the node for callee from the call graph and delete it.
00676     FunctionsToRemove.push_back(CGN);
00677   }
00678   if (FunctionsToRemove.empty())
00679     return false;
00680 
00681   // Now that we know which functions to delete, do so.  We didn't want to do
00682   // this inline, because that would invalidate our CallGraph::iterator
00683   // objects. :(
00684   //
00685   // Note that it doesn't matter that we are iterating over a non-stable order
00686   // here to do this, it doesn't matter which order the functions are deleted
00687   // in.
00688   array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
00689   FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
00690                                       FunctionsToRemove.end()),
00691                           FunctionsToRemove.end());
00692   for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
00693                                                   E = FunctionsToRemove.end();
00694        I != E; ++I) {
00695     delete CG.removeFunctionFromModule(*I);
00696     ++NumDeleted;
00697   }
00698   return true;
00699 }