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