Improve some _slow_ behavior introduced in my patches the last few days.
[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 #define DEBUG_TYPE "inline"
17 #include "Inliner.h"
18 #include "llvm/Module.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/Utils/Cloning.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include <set>
28 using namespace llvm;
29
30 STATISTIC(NumInlined, "Number of functions inlined");
31 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
32
33 namespace {
34   cl::opt<unsigned>             // FIXME: 200 is VERY conservative
35   InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
36         cl::desc("Control the amount of inlining to perform (default = 200)"));
37 }
38
39 Inliner::Inliner() : InlineThreshold(InlineLimit) {}
40
41 /// getAnalysisUsage - For this class, we declare that we require and preserve
42 /// the call graph.  If the derived class implements this method, it should
43 /// always explicitly call the implementation here.
44 void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
45   Info.addRequired<TargetData>();
46   CallGraphSCCPass::getAnalysisUsage(Info);
47 }
48
49 // InlineCallIfPossible - If it is possible to inline the specified call site,
50 // do so and update the CallGraph for this operation.
51 static bool InlineCallIfPossible(CallSite CS, CallGraph &CG,
52                                  const std::set<Function*> &SCCFunctions,
53                                  const TargetData &TD) {
54   Function *Callee = CS.getCalledFunction();
55   if (!InlineFunction(CS, &CG, &TD)) return false;
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     DOUT << "    -> Deleting dead function: " << Callee->getName() << "\n";
62
63     // Remove any call graph edges from the callee to its callees.
64     CallGraphNode *CalleeNode = CG[Callee];
65     while (CalleeNode->begin() != CalleeNode->end())
66       CalleeNode->removeCallEdgeTo((CalleeNode->end()-1)->second);
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   DOUT << "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     DOUT << " " << (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()->isDeclaration()))
98             CallSites.push_back(CS);
99         }
100
101   DOUT << ": " << 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->isDeclaration() ||
123             CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){
124           if (SCC.size() == 1) {
125             std::swap(CallSites[CSi], CallSites.back());
126             CallSites.pop_back();
127           } else {
128             // Keep the 'in SCC / not in SCC' boundary correct.
129             CallSites.erase(CallSites.begin()+CSi);
130           }
131           --CSi;
132           continue;
133         }
134
135         // If the policy determines that we should inline this function,
136         // try to do so.
137         CallSite CS = CallSites[CSi];
138         int InlineCost = getInlineCost(CS);
139         if (InlineCost >= (int)InlineThreshold) {
140           DOUT << "    NOT Inlining: cost=" << InlineCost
141                << ", Call: " << *CS.getInstruction();
142         } else {
143           DOUT << "    Inlining: cost=" << InlineCost
144                << ", Call: " << *CS.getInstruction();
145
146           // Attempt to inline the function...
147           if (InlineCallIfPossible(CS, CG, SCCFunctions, 
148                                    getAnalysis<TargetData>())) {
149             // Remove this call site from the list.  If possible, use 
150             // swap/pop_back for efficiency, but do not use it if doing so would
151             // move a call site to a function in this SCC before the
152             // 'FirstCallInSCC' barrier.
153             if (SCC.size() == 1) {
154               std::swap(CallSites[CSi], CallSites.back());
155               CallSites.pop_back();
156             } else {
157               CallSites.erase(CallSites.begin()+CSi);
158             }
159             --CSi;
160
161             ++NumInlined;
162             Changed = true;
163             LocalChange = true;
164           }
165         }
166       }
167   } while (LocalChange);
168
169   return Changed;
170 }
171
172 // doFinalization - Remove now-dead linkonce functions at the end of
173 // processing to avoid breaking the SCC traversal.
174 bool Inliner::doFinalization(CallGraph &CG) {
175   std::set<CallGraphNode*> FunctionsToRemove;
176
177   // Scan for all of the functions, looking for ones that should now be removed
178   // from the program.  Insert the dead ones in the FunctionsToRemove set.
179   for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
180     CallGraphNode *CGN = I->second;
181     if (Function *F = CGN ? CGN->getFunction() : 0) {
182       // If the only remaining users of the function are dead constants, remove
183       // them.
184       F->removeDeadConstantUsers();
185
186       if ((F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&
187           F->use_empty()) {
188
189         // Remove any call graph edges from the function to its callees.
190         while (CGN->begin() != CGN->end())
191           CGN->removeCallEdgeTo((CGN->end()-1)->second);
192
193         // Remove any edges from the external node to the function's call graph
194         // node.  These edges might have been made irrelegant due to
195         // optimization of the program.
196         CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
197
198         // Removing the node for callee from the call graph and delete it.
199         FunctionsToRemove.insert(CGN);
200       }
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 }