d75d6ca92b3c35fb7793ed5d5ca2488b69ff4b89
[oota-llvm.git] / lib / Transforms / IPO / Inliner.cpp
1 //===- Inliner.cpp - Code common to all inliners --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the mechanics required to implement inlining without
11 // missing any calls and updating the call graph.  The decisions of which calls
12 // are profitable to inline are implemented elsewhere.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "inline"
17 #include "llvm/Transforms/IPO/InlinerPass.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Analysis/InlineCost.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/CallSite.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetLibraryInfo.h"
31 #include "llvm/Transforms/Utils/Cloning.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 using namespace llvm;
34
35 STATISTIC(NumInlined, "Number of functions inlined");
36 STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
37 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
38 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
39
40 // This weirdly named statistic tracks the number of times that, when attempting
41 // to inline a function A into B, we analyze the callers of B in order to see
42 // if those would be more profitable and blocked inline steps.
43 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
44
45 static cl::opt<int>
46 InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
47         cl::desc("Control the amount of inlining to perform (default = 225)"));
48
49 static cl::opt<int>
50 HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
51               cl::desc("Threshold for inlining functions with inline hint"));
52
53 // Threshold to use when optsize is specified (and there is no -inline-limit).
54 const int OptSizeThreshold = 75;
55
56 Inliner::Inliner(char &ID) 
57   : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
58
59 Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
60   : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
61                                           InlineLimit : Threshold),
62     InsertLifetime(InsertLifetime) {}
63
64 /// getAnalysisUsage - For this class, we declare that we require and preserve
65 /// the call graph.  If the derived class implements this method, it should
66 /// always explicitly call the implementation here.
67 void Inliner::getAnalysisUsage(AnalysisUsage &AU) const {
68   CallGraphSCCPass::getAnalysisUsage(AU);
69 }
70
71
72 typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
73 InlinedArrayAllocasTy;
74
75 /// \brief If the inlined function had a higher stack protection level than the
76 /// calling function, then bump up the caller's stack protection level.
77 static void AdjustCallerSSPLevel(Function *Caller, Function *Callee) {
78   // If upgrading the SSP attribute, clear out the old SSP Attributes first.
79   // Having multiple SSP attributes doesn't actually hurt, but it adds useless
80   // clutter to the IR.
81   AttrBuilder B;
82   B.addAttribute(Attribute::StackProtect)
83     .addAttribute(Attribute::StackProtectStrong);
84   AttributeSet OldSSPAttr = AttributeSet::get(Caller->getContext(),
85                                               AttributeSet::FunctionIndex,
86                                               B);
87   AttributeSet CallerAttr = Caller->getAttributes(),
88                CalleeAttr = Callee->getAttributes();
89
90   if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
91                               Attribute::StackProtectReq)) {
92     Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
93     Caller->addFnAttr(Attribute::StackProtectReq);
94   } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
95                                      Attribute::StackProtectStrong) &&
96              !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
97                                       Attribute::StackProtectReq)) {
98     Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
99     Caller->addFnAttr(Attribute::StackProtectStrong);
100   } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
101                                      Attribute::StackProtect) &&
102            !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
103                                     Attribute::StackProtectReq) &&
104            !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
105                                     Attribute::StackProtectStrong))
106     Caller->addFnAttr(Attribute::StackProtect);
107 }
108
109 /// InlineCallIfPossible - If it is possible to inline the specified call site,
110 /// do so and update the CallGraph for this operation.
111 ///
112 /// This function also does some basic book-keeping to update the IR.  The
113 /// InlinedArrayAllocas map keeps track of any allocas that are already
114 /// available from other  functions inlined into the caller.  If we are able to
115 /// inline this call site we attempt to reuse already available allocas or add
116 /// any new allocas to the set if not possible.
117 static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
118                                  InlinedArrayAllocasTy &InlinedArrayAllocas,
119                                  int InlineHistory, bool InsertLifetime,
120                                  const DataLayout *TD) {
121   Function *Callee = CS.getCalledFunction();
122   Function *Caller = CS.getCaller();
123
124   // Try to inline the function.  Get the list of static allocas that were
125   // inlined.
126   if (!InlineFunction(CS, IFI, InsertLifetime))
127     return false;
128
129   AdjustCallerSSPLevel(Caller, Callee);
130
131   // Look at all of the allocas that we inlined through this call site.  If we
132   // have already inlined other allocas through other calls into this function,
133   // then we know that they have disjoint lifetimes and that we can merge them.
134   //
135   // There are many heuristics possible for merging these allocas, and the
136   // different options have different tradeoffs.  One thing that we *really*
137   // don't want to hurt is SRoA: once inlining happens, often allocas are no
138   // longer address taken and so they can be promoted.
139   //
140   // Our "solution" for that is to only merge allocas whose outermost type is an
141   // array type.  These are usually not promoted because someone is using a
142   // variable index into them.  These are also often the most important ones to
143   // merge.
144   //
145   // A better solution would be to have real memory lifetime markers in the IR
146   // and not have the inliner do any merging of allocas at all.  This would
147   // allow the backend to do proper stack slot coloring of all allocas that
148   // *actually make it to the backend*, which is really what we want.
149   //
150   // Because we don't have this information, we do this simple and useful hack.
151   //
152   SmallPtrSet<AllocaInst*, 16> UsedAllocas;
153   
154   // When processing our SCC, check to see if CS was inlined from some other
155   // call site.  For example, if we're processing "A" in this code:
156   //   A() { B() }
157   //   B() { x = alloca ... C() }
158   //   C() { y = alloca ... }
159   // Assume that C was not inlined into B initially, and so we're processing A
160   // and decide to inline B into A.  Doing this makes an alloca available for
161   // reuse and makes a callsite (C) available for inlining.  When we process
162   // the C call site we don't want to do any alloca merging between X and Y
163   // because their scopes are not disjoint.  We could make this smarter by
164   // keeping track of the inline history for each alloca in the
165   // InlinedArrayAllocas but this isn't likely to be a significant win.
166   if (InlineHistory != -1)  // Only do merging for top-level call sites in SCC.
167     return true;
168   
169   // Loop over all the allocas we have so far and see if they can be merged with
170   // a previously inlined alloca.  If not, remember that we had it.
171   for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
172        AllocaNo != e; ++AllocaNo) {
173     AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
174     
175     // Don't bother trying to merge array allocations (they will usually be
176     // canonicalized to be an allocation *of* an array), or allocations whose
177     // type is not itself an array (because we're afraid of pessimizing SRoA).
178     ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
179     if (ATy == 0 || AI->isArrayAllocation())
180       continue;
181     
182     // Get the list of all available allocas for this array type.
183     std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
184     
185     // Loop over the allocas in AllocasForType to see if we can reuse one.  Note
186     // that we have to be careful not to reuse the same "available" alloca for
187     // multiple different allocas that we just inlined, we use the 'UsedAllocas'
188     // set to keep track of which "available" allocas are being used by this
189     // function.  Also, AllocasForType can be empty of course!
190     bool MergedAwayAlloca = false;
191     for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
192       AllocaInst *AvailableAlloca = AllocasForType[i];
193
194       unsigned Align1 = AI->getAlignment(),
195                Align2 = AvailableAlloca->getAlignment();
196       // If we don't have data layout information, and only one alloca is using
197       // the target default, then we can't safely merge them because we can't
198       // pick the greater alignment.
199       if (!TD && (!Align1 || !Align2) && Align1 != Align2)
200         continue;
201       
202       // The available alloca has to be in the right function, not in some other
203       // function in this SCC.
204       if (AvailableAlloca->getParent() != AI->getParent())
205         continue;
206       
207       // If the inlined function already uses this alloca then we can't reuse
208       // it.
209       if (!UsedAllocas.insert(AvailableAlloca))
210         continue;
211       
212       // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
213       // success!
214       DEBUG(dbgs() << "    ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
215                    << *AvailableAlloca << '\n');
216       
217       AI->replaceAllUsesWith(AvailableAlloca);
218
219       if (Align1 != Align2) {
220         if (!Align1 || !Align2) {
221           assert(TD && "DataLayout required to compare default alignments");
222           unsigned TypeAlign = TD->getABITypeAlignment(AI->getAllocatedType());
223
224           Align1 = Align1 ? Align1 : TypeAlign;
225           Align2 = Align2 ? Align2 : TypeAlign;
226         }
227
228         if (Align1 > Align2)
229           AvailableAlloca->setAlignment(AI->getAlignment());
230       }
231
232       AI->eraseFromParent();
233       MergedAwayAlloca = true;
234       ++NumMergedAllocas;
235       IFI.StaticAllocas[AllocaNo] = 0;
236       break;
237     }
238
239     // If we already nuked the alloca, we're done with it.
240     if (MergedAwayAlloca)
241       continue;
242     
243     // If we were unable to merge away the alloca either because there are no
244     // allocas of the right type available or because we reused them all
245     // already, remember that this alloca came from an inlined function and mark
246     // it used so we don't reuse it for other allocas from this inline
247     // operation.
248     AllocasForType.push_back(AI);
249     UsedAllocas.insert(AI);
250   }
251   
252   return true;
253 }
254
255 unsigned Inliner::getInlineThreshold(CallSite CS) const {
256   int thres = InlineThreshold; // -inline-threshold or else selected by
257                                // overall opt level
258
259   // If -inline-threshold is not given, listen to the optsize attribute when it
260   // would decrease the threshold.
261   Function *Caller = CS.getCaller();
262   bool OptSize = Caller && !Caller->isDeclaration() &&
263     Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
264                                          Attribute::OptimizeForSize);
265   if (!(InlineLimit.getNumOccurrences() > 0) && OptSize &&
266       OptSizeThreshold < thres)
267     thres = OptSizeThreshold;
268
269   // Listen to the inlinehint attribute when it would increase the threshold
270   // and the caller does not need to minimize its size.
271   Function *Callee = CS.getCalledFunction();
272   bool InlineHint = Callee && !Callee->isDeclaration() &&
273     Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
274                                          Attribute::InlineHint);
275   if (InlineHint && HintThreshold > thres
276       && !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
277                                                Attribute::MinSize))
278     thres = HintThreshold;
279
280   return thres;
281 }
282
283 /// shouldInline - Return true if the inliner should attempt to inline
284 /// at the given CallSite.
285 bool Inliner::shouldInline(CallSite CS) {
286   InlineCost IC = getInlineCost(CS);
287   
288   if (IC.isAlways()) {
289     DEBUG(dbgs() << "    Inlining: cost=always"
290           << ", Call: " << *CS.getInstruction() << "\n");
291     return true;
292   }
293   
294   if (IC.isNever()) {
295     DEBUG(dbgs() << "    NOT Inlining: cost=never"
296           << ", Call: " << *CS.getInstruction() << "\n");
297     return false;
298   }
299   
300   Function *Caller = CS.getCaller();
301   if (!IC) {
302     DEBUG(dbgs() << "    NOT Inlining: cost=" << IC.getCost()
303           << ", thres=" << (IC.getCostDelta() + IC.getCost())
304           << ", Call: " << *CS.getInstruction() << "\n");
305     return false;
306   }
307   
308   // Try to detect the case where the current inlining candidate caller (call
309   // it B) is a static or linkonce-ODR function and is an inlining candidate
310   // elsewhere, and the current candidate callee (call it C) is large enough
311   // that inlining it into B would make B too big to inline later. In these
312   // circumstances it may be best not to inline C into B, but to inline B into
313   // its callers.
314   //
315   // This only applies to static and linkonce-ODR functions because those are
316   // expected to be available for inlining in the translation units where they
317   // are used. Thus we will always have the opportunity to make local inlining
318   // decisions. Importantly the linkonce-ODR linkage covers inline functions
319   // and templates in C++.
320   //
321   // FIXME: All of this logic should be sunk into getInlineCost. It relies on
322   // the internal implementation of the inline cost metrics rather than
323   // treating them as truly abstract units etc.
324   if (Caller->hasLocalLinkage() ||
325       Caller->getLinkage() == GlobalValue::LinkOnceODRLinkage) {
326     int TotalSecondaryCost = 0;
327     // The candidate cost to be imposed upon the current function.
328     int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
329     // This bool tracks what happens if we do NOT inline C into B.
330     bool callerWillBeRemoved = Caller->hasLocalLinkage();
331     // This bool tracks what happens if we DO inline C into B.
332     bool inliningPreventsSomeOuterInline = false;
333     for (Value::use_iterator I = Caller->use_begin(), E =Caller->use_end(); 
334          I != E; ++I) {
335       CallSite CS2(*I);
336
337       // If this isn't a call to Caller (it could be some other sort
338       // of reference) skip it.  Such references will prevent the caller
339       // from being removed.
340       if (!CS2 || CS2.getCalledFunction() != Caller) {
341         callerWillBeRemoved = false;
342         continue;
343       }
344
345       InlineCost IC2 = getInlineCost(CS2);
346       ++NumCallerCallersAnalyzed;
347       if (!IC2) {
348         callerWillBeRemoved = false;
349         continue;
350       }
351       if (IC2.isAlways())
352         continue;
353
354       // See if inlining or original callsite would erase the cost delta of
355       // this callsite. We subtract off the penalty for the call instruction,
356       // which we would be deleting.
357       if (IC2.getCostDelta() <= CandidateCost) {
358         inliningPreventsSomeOuterInline = true;
359         TotalSecondaryCost += IC2.getCost();
360       }
361     }
362     // If all outer calls to Caller would get inlined, the cost for the last
363     // one is set very low by getInlineCost, in anticipation that Caller will
364     // be removed entirely.  We did not account for this above unless there
365     // is only one caller of Caller.
366     if (callerWillBeRemoved && Caller->use_begin() != Caller->use_end())
367       TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
368
369     if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
370       DEBUG(dbgs() << "    NOT Inlining: " << *CS.getInstruction() <<
371            " Cost = " << IC.getCost() <<
372            ", outer Cost = " << TotalSecondaryCost << '\n');
373       return false;
374     }
375   }
376
377   DEBUG(dbgs() << "    Inlining: cost=" << IC.getCost()
378         << ", thres=" << (IC.getCostDelta() + IC.getCost())
379         << ", Call: " << *CS.getInstruction() << '\n');
380   return true;
381 }
382
383 /// InlineHistoryIncludes - Return true if the specified inline history ID
384 /// indicates an inline history that includes the specified function.
385 static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
386             const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
387   while (InlineHistoryID != -1) {
388     assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
389            "Invalid inline history ID");
390     if (InlineHistory[InlineHistoryID].first == F)
391       return true;
392     InlineHistoryID = InlineHistory[InlineHistoryID].second;
393   }
394   return false;
395 }
396
397 bool Inliner::runOnSCC(CallGraphSCC &SCC) {
398   CallGraph &CG = getAnalysis<CallGraph>();
399   const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
400   const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
401
402   SmallPtrSet<Function*, 8> SCCFunctions;
403   DEBUG(dbgs() << "Inliner visiting SCC:");
404   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
405     Function *F = (*I)->getFunction();
406     if (F) SCCFunctions.insert(F);
407     DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
408   }
409
410   // Scan through and identify all call sites ahead of time so that we only
411   // inline call sites in the original functions, not call sites that result
412   // from inlining other functions.
413   SmallVector<std::pair<CallSite, int>, 16> CallSites;
414   
415   // When inlining a callee produces new call sites, we want to keep track of
416   // the fact that they were inlined from the callee.  This allows us to avoid
417   // infinite inlining in some obscure cases.  To represent this, we use an
418   // index into the InlineHistory vector.
419   SmallVector<std::pair<Function*, int>, 8> InlineHistory;
420
421   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
422     Function *F = (*I)->getFunction();
423     if (!F) continue;
424     
425     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
426       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
427         CallSite CS(cast<Value>(I));
428         // If this isn't a call, or it is a call to an intrinsic, it can
429         // never be inlined.
430         if (!CS || isa<IntrinsicInst>(I))
431           continue;
432         
433         // If this is a direct call to an external function, we can never inline
434         // it.  If it is an indirect call, inlining may resolve it to be a
435         // direct call, so we keep it.
436         if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
437           continue;
438         
439         CallSites.push_back(std::make_pair(CS, -1));
440       }
441   }
442
443   DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
444
445   // If there are no calls in this function, exit early.
446   if (CallSites.empty())
447     return false;
448   
449   // Now that we have all of the call sites, move the ones to functions in the
450   // current SCC to the end of the list.
451   unsigned FirstCallInSCC = CallSites.size();
452   for (unsigned i = 0; i < FirstCallInSCC; ++i)
453     if (Function *F = CallSites[i].first.getCalledFunction())
454       if (SCCFunctions.count(F))
455         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
456
457   
458   InlinedArrayAllocasTy InlinedArrayAllocas;
459   InlineFunctionInfo InlineInfo(&CG, TD);
460   
461   // Now that we have all of the call sites, loop over them and inline them if
462   // it looks profitable to do so.
463   bool Changed = false;
464   bool LocalChange;
465   do {
466     LocalChange = false;
467     // Iterate over the outer loop because inlining functions can cause indirect
468     // calls to become direct calls.
469     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
470       CallSite CS = CallSites[CSi].first;
471       
472       Function *Caller = CS.getCaller();
473       Function *Callee = CS.getCalledFunction();
474
475       // If this call site is dead and it is to a readonly function, we should
476       // just delete the call instead of trying to inline it, regardless of
477       // size.  This happens because IPSCCP propagates the result out of the
478       // call and then we're left with the dead call.
479       if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
480         DEBUG(dbgs() << "    -> Deleting dead call: "
481                      << *CS.getInstruction() << "\n");
482         // Update the call graph by deleting the edge from Callee to Caller.
483         CG[Caller]->removeCallEdgeFor(CS);
484         CS.getInstruction()->eraseFromParent();
485         ++NumCallsDeleted;
486       } else {
487         // We can only inline direct calls to non-declarations.
488         if (Callee == 0 || Callee->isDeclaration()) continue;
489       
490         // If this call site was obtained by inlining another function, verify
491         // that the include path for the function did not include the callee
492         // itself.  If so, we'd be recursively inlining the same function,
493         // which would provide the same callsites, which would cause us to
494         // infinitely inline.
495         int InlineHistoryID = CallSites[CSi].second;
496         if (InlineHistoryID != -1 &&
497             InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
498           continue;
499         
500         
501         // If the policy determines that we should inline this function,
502         // try to do so.
503         if (!shouldInline(CS))
504           continue;
505
506         // Attempt to inline the function.
507         if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
508                                   InlineHistoryID, InsertLifetime, TD))
509           continue;
510         ++NumInlined;
511         
512         // If inlining this function gave us any new call sites, throw them
513         // onto our worklist to process.  They are useful inline candidates.
514         if (!InlineInfo.InlinedCalls.empty()) {
515           // Create a new inline history entry for this, so that we remember
516           // that these new callsites came about due to inlining Callee.
517           int NewHistoryID = InlineHistory.size();
518           InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
519
520           for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
521                i != e; ++i) {
522             Value *Ptr = InlineInfo.InlinedCalls[i];
523             CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
524           }
525         }
526       }
527       
528       // If we inlined or deleted the last possible call site to the function,
529       // delete the function body now.
530       if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
531           // TODO: Can remove if in SCC now.
532           !SCCFunctions.count(Callee) &&
533           
534           // The function may be apparently dead, but if there are indirect
535           // callgraph references to the node, we cannot delete it yet, this
536           // could invalidate the CGSCC iterator.
537           CG[Callee]->getNumReferences() == 0) {
538         DEBUG(dbgs() << "    -> Deleting dead function: "
539               << Callee->getName() << "\n");
540         CallGraphNode *CalleeNode = CG[Callee];
541         
542         // Remove any call graph edges from the callee to its callees.
543         CalleeNode->removeAllCalledFunctions();
544         
545         // Removing the node for callee from the call graph and delete it.
546         delete CG.removeFunctionFromModule(CalleeNode);
547         ++NumDeleted;
548       }
549
550       // Remove this call site from the list.  If possible, use 
551       // swap/pop_back for efficiency, but do not use it if doing so would
552       // move a call site to a function in this SCC before the
553       // 'FirstCallInSCC' barrier.
554       if (SCC.isSingular()) {
555         CallSites[CSi] = CallSites.back();
556         CallSites.pop_back();
557       } else {
558         CallSites.erase(CallSites.begin()+CSi);
559       }
560       --CSi;
561
562       Changed = true;
563       LocalChange = true;
564     }
565   } while (LocalChange);
566
567   return Changed;
568 }
569
570 // doFinalization - Remove now-dead linkonce functions at the end of
571 // processing to avoid breaking the SCC traversal.
572 bool Inliner::doFinalization(CallGraph &CG) {
573   return removeDeadFunctions(CG);
574 }
575
576 /// removeDeadFunctions - Remove dead functions that are not included in
577 /// DNR (Do Not Remove) list.
578 bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
579   SmallVector<CallGraphNode*, 16> FunctionsToRemove;
580
581   // Scan for all of the functions, looking for ones that should now be removed
582   // from the program.  Insert the dead ones in the FunctionsToRemove set.
583   for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
584     CallGraphNode *CGN = I->second;
585     Function *F = CGN->getFunction();
586     if (!F || F->isDeclaration())
587       continue;
588
589     // Handle the case when this function is called and we only want to care
590     // about always-inline functions. This is a bit of a hack to share code
591     // between here and the InlineAlways pass.
592     if (AlwaysInlineOnly &&
593         !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
594                                          Attribute::AlwaysInline))
595       continue;
596
597     // If the only remaining users of the function are dead constants, remove
598     // them.
599     F->removeDeadConstantUsers();
600
601     if (!F->isDefTriviallyDead())
602       continue;
603     
604     // Remove any call graph edges from the function to its callees.
605     CGN->removeAllCalledFunctions();
606
607     // Remove any edges from the external node to the function's call graph
608     // node.  These edges might have been made irrelegant due to
609     // optimization of the program.
610     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
611
612     // Removing the node for callee from the call graph and delete it.
613     FunctionsToRemove.push_back(CGN);
614   }
615   if (FunctionsToRemove.empty())
616     return false;
617
618   // Now that we know which functions to delete, do so.  We didn't want to do
619   // this inline, because that would invalidate our CallGraph::iterator
620   // objects. :(
621   //
622   // Note that it doesn't matter that we are iterating over a non-stable order
623   // here to do this, it doesn't matter which order the functions are deleted
624   // in.
625   array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
626   FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
627                                       FunctionsToRemove.end()),
628                           FunctionsToRemove.end());
629   for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
630                                                   E = FunctionsToRemove.end();
631        I != E; ++I) {
632     delete CG.removeFunctionFromModule(*I);
633     ++NumDeleted;
634   }
635   return true;
636 }