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