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