Changes For Bug 352
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "Inliner.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Support/CallSite.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 #include <set>
26 using namespace llvm;
27
28 namespace {
29   Statistic<> NumInlined("inline", "Number of functions inlined");
30   Statistic<> NumDeleted("inline", "Number of functions deleted because all callers found");
31   cl::opt<unsigned>             // FIXME: 200 is VERY conservative
32   InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
33               cl::desc("Control the amount of inlining to perform (default = 200)"));
34 }
35
36 Inliner::Inliner() : InlineThreshold(InlineLimit) {}
37
38 // InlineCallIfPossible - If it is possible to inline the specified call site,
39 // do so and update the CallGraph for this operation.
40 static bool InlineCallIfPossible(CallSite CS, CallGraph &CG,
41                                  const std::set<Function*> &SCCFunctions) {
42   Function *Caller = CS.getInstruction()->getParent()->getParent();
43   Function *Callee = CS.getCalledFunction();
44   if (!InlineFunction(CS)) return false;
45
46   // Update the call graph by deleting the edge from Callee to Caller
47   CallGraphNode *CalleeNode = CG[Callee];
48   CallGraphNode *CallerNode = CG[Caller];
49   CallerNode->removeCallEdgeTo(CalleeNode);
50
51   // Since we inlined all uninlined call sites in the callee into the caller,
52   // add edges from the caller to all of the callees of the callee.
53   for (CallGraphNode::iterator I = CalleeNode->begin(),
54          E = CalleeNode->end(); I != E; ++I)
55     CallerNode->addCalledFunction(*I);
56   
57   // If we inlined the last possible call site to the function, delete the
58   // function body now.
59   if (Callee->use_empty() && Callee->hasInternalLinkage() &&
60       !SCCFunctions.count(Callee)) {
61     DEBUG(std::cerr << "    -> Deleting dead function: "
62                     << Callee->getName() << "\n");
63     
64     // Remove any call graph edges from the callee to its callees.
65     while (CalleeNode->begin() != CalleeNode->end())
66       CalleeNode->removeCallEdgeTo(*(CalleeNode->end()-1));
67      
68     // Removing the node for callee from the call graph and delete it.
69     delete CG.removeFunctionFromModule(CalleeNode);
70     ++NumDeleted;
71   }
72   return true;
73 }
74
75 bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
76   CallGraph &CG = getAnalysis<CallGraph>();
77
78   std::set<Function*> SCCFunctions;
79   DEBUG(std::cerr << "Inliner visiting SCC:");
80   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
81     Function *F = SCC[i]->getFunction();
82     if (F) SCCFunctions.insert(F);
83     DEBUG(std::cerr << " " << (F ? F->getName() : "INDIRECTNODE"));
84   }
85
86   // Scan through and identify all call sites ahead of time so that we only
87   // inline call sites in the original functions, not call sites that result
88   // from inlining other functions.
89   std::vector<CallSite> CallSites;
90
91   for (unsigned i = 0, e = SCC.size(); i != e; ++i)
92     if (Function *F = SCC[i]->getFunction())
93       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
94         for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
95           CallSite CS = CallSite::get(I);
96           if (CS.getInstruction() && (!CS.getCalledFunction() ||
97                                       !CS.getCalledFunction()->isExternal()))
98             CallSites.push_back(CS);
99         }
100
101   DEBUG(std::cerr << ": " << CallSites.size() << " call sites.\n");
102   
103   // Now that we have all of the call sites, move the ones to functions in the
104   // current SCC to the end of the list.
105   unsigned FirstCallInSCC = CallSites.size();
106   for (unsigned i = 0; i < FirstCallInSCC; ++i)
107     if (Function *F = CallSites[i].getCalledFunction())
108       if (SCCFunctions.count(F))
109         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
110   
111   // Now that we have all of the call sites, loop over them and inline them if
112   // it looks profitable to do so.
113   bool Changed = false;
114   bool LocalChange;
115   do {
116     LocalChange = false;
117     // Iterate over the outer loop because inlining functions can cause indirect
118     // calls to become direct calls.
119     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
120       if (Function *Callee = CallSites[CSi].getCalledFunction()) {
121         // Calls to external functions are never inlinable.
122         if (Callee->isExternal() ||
123             CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){
124           std::swap(CallSites[CSi], CallSites.back());
125           CallSites.pop_back();
126           --CSi;
127           continue;
128         }
129
130         // If the policy determines that we should inline this function,
131         // try to do so.
132         CallSite CS = CallSites[CSi];
133         int InlineCost = getInlineCost(CS);
134         if (InlineCost >= (int)InlineThreshold) {
135           DEBUG(std::cerr << "    NOT Inlining: cost=" << InlineCost
136                 << ", Call: " << *CS.getInstruction());
137         } else {
138           DEBUG(std::cerr << "    Inlining: cost=" << InlineCost
139                 << ", Call: " << *CS.getInstruction());
140           
141           Function *Caller = CS.getInstruction()->getParent()->getParent();
142
143           // Attempt to inline the function...
144           if (InlineCallIfPossible(CS, CG, SCCFunctions)) {
145             // Remove this call site from the list.
146             std::swap(CallSites[CSi], CallSites.back());
147             CallSites.pop_back();
148             --CSi;
149
150             ++NumInlined;
151             Changed = true;
152             LocalChange = true;
153           }
154         }
155       }
156   } while (LocalChange);
157
158   return Changed;
159 }
160
161 // doFinalization - Remove now-dead linkonce functions at the end of
162 // processing to avoid breaking the SCC traversal.
163 bool Inliner::doFinalization(CallGraph &CG) {
164   std::set<CallGraphNode*> FunctionsToRemove;
165
166   // Scan for all of the functions, looking for ones that should now be removed
167   // from the program.  Insert the dead ones in the FunctionsToRemove set.
168   for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
169     CallGraphNode *CGN = I->second;
170     if (Function *F = CGN ? CGN->getFunction() : 0) {
171       // If the only remaining users of the function are dead constants,
172       // remove them.
173       bool HadDeadConstantUsers = !F->use_empty();
174       F->removeDeadConstantUsers();
175
176       if ((F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&
177           F->use_empty()) {
178         // Remove any call graph edges from the function to its callees.
179         while (CGN->begin() != CGN->end())
180           CGN->removeCallEdgeTo(*(CGN->end()-1));
181         
182         // If the function has external linkage (basically if it's a linkonce
183         // function) remove the edge from the external node to the callee
184         // node.
185         if (!F->hasInternalLinkage() || HadDeadConstantUsers)
186           CG.getExternalCallingNode()->removeCallEdgeTo(CGN);
187         
188         // Removing the node for callee from the call graph and delete it.
189         FunctionsToRemove.insert(CGN);
190       }
191     }
192   }
193
194   // Now that we know which functions to delete, do so.  We didn't want to do
195   // this inline, because that would invalidate our CallGraph::iterator
196   // objects. :(
197   bool Changed = false;
198   for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
199          E = FunctionsToRemove.end(); I != E; ++I) {
200     delete CG.removeFunctionFromModule(*I);
201     ++NumDeleted;
202     Changed = true;
203   }
204
205   return Changed;
206 }