blob: c125aa7ef7da1a09cdaabceb4e3a975019e181e3 [file] [log] [blame]
Vikram S. Advec5204fb2004-05-23 07:54:02 +00001//===- EquivClassGraphs.cpp - Merge equiv-class graphs & inline bottom-up -===//
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 pass is the same as the complete bottom-up graphs, but
11// with functions partitioned into equivalence classes and a single merged
12// DS graph for all functions in an equivalence class. After this merging,
13// graphs are inlined bottom-up on the SCCs of the final (CBU) call graph.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "ECGraphs"
18#include "EquivClassGraphs.h"
Vikram S. Advec5204fb2004-05-23 07:54:02 +000019#include "llvm/Module.h"
20#include "llvm/Pass.h"
Chris Lattnereaef5682004-07-07 06:22:54 +000021#include "llvm/Analysis/DataStructure/DSGraph.h"
22#include "llvm/Analysis/DataStructure/DataStructure.h"
Vikram S. Advec5204fb2004-05-23 07:54:02 +000023#include "llvm/Support/CallSite.h"
Chris Lattnerc9b93802004-10-11 20:53:28 +000024#include "llvm/Support/Debug.h"
25#include "llvm/ADT/SCCIterator.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/EquivalenceClasses.h"
28#include "llvm/ADT/STLExtras.h"
Vikram S. Advec5204fb2004-05-23 07:54:02 +000029using namespace llvm;
30
Vikram S. Advec5204fb2004-05-23 07:54:02 +000031namespace {
Chris Lattner15d879e2004-10-12 16:52:09 +000032 RegisterAnalysis<PA::EquivClassGraphs> X("equivdatastructure",
Vikram S. Advec5204fb2004-05-23 07:54:02 +000033 "Equivalence-class Bottom-up Data Structure Analysis");
34 Statistic<> NumEquivBUInlines("equivdatastructures", "Number of graphs inlined");
Chris Lattner15d879e2004-10-12 16:52:09 +000035 Statistic<> NumFoldGraphInlines("Inline equiv-class graphs bottom up",
36 "Number of graphs inlined");
Vikram S. Advec5204fb2004-05-23 07:54:02 +000037}
38
39
40// getDSGraphForCallSite - Return the common data structure graph for
41// callees at the specified call site.
42//
Chris Lattner15d879e2004-10-12 16:52:09 +000043Function *PA::EquivClassGraphs::
44getSomeCalleeForCallSite(const CallSite &CS) const {
Vikram S. Advec5204fb2004-05-23 07:54:02 +000045 Function *thisFunc = CS.getCaller();
46 assert(thisFunc && "getDSGraphForCallSite(): Not a valid call site?");
47 DSNode *calleeNode = CBU->getDSGraph(*thisFunc).
48 getNodeForValue(CS.getCalledValue()).getNode();
49 std::map<DSNode*, Function *>::const_iterator I =
50 OneCalledFunction.find(calleeNode);
51 return (I == OneCalledFunction.end())? NULL : I->second;
52}
53
54// computeFoldedGraphs - Calculate the bottom up data structure
55// graphs for each function in the program.
56//
Chris Lattner15d879e2004-10-12 16:52:09 +000057void PA::EquivClassGraphs::computeFoldedGraphs(Module &M) {
Vikram S. Advec5204fb2004-05-23 07:54:02 +000058 CBU = &getAnalysis<CompleteBUDataStructures>();
59
60 // Find equivalence classes of functions called from common call sites.
61 // Fold the CBU graphs for all functions in an equivalence class.
62 buildIndirectFunctionSets(M);
63
64 // Stack of functions used for Tarjan's SCC-finding algorithm.
65 std::vector<Function*> Stack;
66 hash_map<Function*, unsigned> ValMap;
67 unsigned NextID = 1;
68
69 if (Function *Main = M.getMainFunction()) {
70 if (!Main->isExternal())
71 processSCC(getOrCreateGraph(*Main), *Main, Stack, NextID, ValMap);
72 } else {
73 std::cerr << "Fold Graphs: No 'main' function found!\n";
74 }
75
76 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
77 if (!I->isExternal() && !FoldedGraphsMap.count(I))
78 processSCC(getOrCreateGraph(*I), *I, Stack, NextID, ValMap);
79
80 getGlobalsGraph().removeTriviallyDeadNodes();
81}
82
83
84// buildIndirectFunctionSets - Iterate over the module looking for indirect
85// calls to functions. If a call site can invoke any functions [F1, F2... FN],
86// unify the N functions together in the FuncECs set.
87//
Chris Lattner15d879e2004-10-12 16:52:09 +000088void PA::EquivClassGraphs::buildIndirectFunctionSets(Module &M) {
Vikram S. Advec5204fb2004-05-23 07:54:02 +000089 const ActualCalleesTy& AC = CBU->getActualCallees();
90
91 // Loop over all of the indirect calls in the program. If a call site can
92 // call multiple different functions, we need to unify all of the callees into
93 // the same equivalence class.
94 Instruction *LastInst = 0;
95 Function *FirstFunc = 0;
96 for (ActualCalleesTy::const_iterator I=AC.begin(), E=AC.end(); I != E; ++I) {
97 if (I->second->isExternal())
98 continue; // Ignore functions we cannot modify
99
100 CallSite CS = CallSite::get(I->first);
101
102 if (CS.getCalledFunction()) { // Direct call:
103 FuncECs.addElement(I->second); // -- Make sure function has equiv class
104 FirstFunc = I->second; // -- First callee at this site
105 } else { // Else indirect call
106 // DEBUG(std::cerr << "CALLEE: " << I->second->getName()
107 // << " from : " << I->first);
108 if (I->first != LastInst) {
109 // This is the first callee from this call site.
110 LastInst = I->first;
111 FirstFunc = I->second;
112 // Instead of storing the lastInst For Indirection call Sites we store
113 // the DSNode for the function ptr arguemnt
114 Function *thisFunc = LastInst->getParent()->getParent();
Chris Lattner15d879e2004-10-12 16:52:09 +0000115 DSGraph &TFG = CBU->getDSGraph(*thisFunc);
116 DSNode *calleeNode = TFG.getNodeForValue(CS.getCalledValue()).getNode();
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000117 OneCalledFunction[calleeNode] = FirstFunc;
118 FuncECs.addElement(I->second);
119 } else {
120 // This is not the first possible callee from a particular call site.
121 // Union the callee in with the other functions.
122 FuncECs.unionSetsWith(FirstFunc, I->second);
123#ifndef NDEBUG
124 Function *thisFunc = LastInst->getParent()->getParent();
Chris Lattner15d879e2004-10-12 16:52:09 +0000125 DSGraph &TFG = CBU->getDSGraph(*thisFunc);
126 DSNode *calleeNode = TFG.getNodeForValue(CS.getCalledValue()).getNode();
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000127 assert(OneCalledFunction.count(calleeNode) > 0 && "Missed a call?");
128#endif
129 }
130 }
131
132 // Now include all functions that share a graph with any function in the
133 // equivalence class. More precisely, if F is in the class, and G(F) is
134 // its graph, then we include all other functions that are also in G(F).
135 // Currently, that is just the functions in the same call-graph-SCC as F.
136 //
137 DSGraph& funcDSGraph = CBU->getDSGraph(*I->second);
138 const DSGraph::ReturnNodesTy &RetNodes = funcDSGraph.getReturnNodes();
139 for (DSGraph::ReturnNodesTy::const_iterator RI=RetNodes.begin(),
140 RE=RetNodes.end(); RI != RE; ++RI)
141 FuncECs.unionSetsWith(FirstFunc, RI->first);
142 }
143
144 // Now that all of the equivalences have been built, merge the graphs for
145 // each equivalence class.
146 //
147 std::set<Function*> &leaderSet = FuncECs.getLeaderSet();
148 DEBUG(std::cerr << "\nIndirect Function Equivalence Sets:\n");
149 for (std::set<Function*>::iterator LI = leaderSet.begin(),
150 LE = leaderSet.end(); LI != LE; ++LI) {
151
152 Function* LF = *LI;
153 const std::set<Function*>& EqClass = FuncECs.getEqClass(LF);
154
155#ifndef NDEBUG
156 if (EqClass.size() > 1) {
157 DEBUG(std::cerr <<" Equivalence set for leader " <<LF->getName()<<" = ");
158 for (std::set<Function*>::const_iterator EqI = EqClass.begin(),
159 EqEnd = EqClass.end(); EqI != EqEnd; ++EqI)
160 DEBUG(std::cerr << " " << (*EqI)->getName() << ",");
161 DEBUG(std::cerr << "\n");
162 }
163#endif
164
165 if (EqClass.size() > 1) {
166 // This equiv class has multiple functions: merge their graphs.
167 // First, clone the CBU graph for the leader and make it the
168 // common graph for the equivalence graph.
169 DSGraph* mergedG = cloneGraph(*LF);
170
171 // Record the argument nodes for use in merging later below
172 EquivClassGraphArgsInfo& GraphInfo = getECGraphInfo(mergedG);
173 for (Function::aiterator AI1 = LF->abegin(); AI1 != LF->aend(); ++AI1)
Chris Lattnerf4985682004-10-31 18:13:19 +0000174 if (DS::isPointerType(AI1->getType()))
175 GraphInfo.argNodes.push_back(mergedG->getNodeForValue(AI1));
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000176
177 // Merge in the graphs of all other functions in this equiv. class.
178 // Note that two or more functions may have the same graph, and it
179 // only needs to be merged in once. Use a set to find repetitions.
180 std::set<DSGraph*> GraphsMerged;
181 for (std::set<Function*>::const_iterator EqI = EqClass.begin(),
182 EqEnd = EqClass.end(); EqI != EqEnd; ++EqI) {
183 Function* F = *EqI;
184 DSGraph*& FG = FoldedGraphsMap[F];
Chris Lattner113cde82004-10-31 17:47:48 +0000185
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000186 if (F == LF || FG == mergedG)
187 continue;
188
189 // Record the "folded" graph for the function.
190 FG = mergedG;
191
192 // Clone this member of the equivalence class into mergedG
193 DSGraph* CBUGraph = &CBU->getDSGraph(*F);
194 if (GraphsMerged.count(CBUGraph) > 0)
195 continue;
196
197 GraphsMerged.insert(CBUGraph);
198 DSGraph::NodeMapTy NodeMap;
Chris Lattner113cde82004-10-31 17:47:48 +0000199
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000200 mergedG->cloneInto(*CBUGraph, mergedG->getScalarMap(),
201 mergedG->getReturnNodes(), NodeMap, 0);
202
203 // Merge the return nodes of all functions together.
204 mergedG->getReturnNodes()[LF].mergeWith(mergedG->getReturnNodes()[F]);
205
206 // Merge the function arguments with all argument nodes found so far.
207 // If there are extra function args, add them to the vector of argNodes
208 Function::aiterator AI2 = F->abegin(), AI2end = F->aend();
209 for (unsigned arg=0, numArgs=GraphInfo.argNodes.size();
Chris Lattner113cde82004-10-31 17:47:48 +0000210 arg != numArgs && AI2 != AI2end; ++AI2, ++arg)
211 if (DS::isPointerType(AI2->getType()))
212 GraphInfo.argNodes[arg].mergeWith(mergedG->getNodeForValue(AI2));
213
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000214 for ( ; AI2 != AI2end; ++AI2)
Chris Lattner113cde82004-10-31 17:47:48 +0000215 if (DS::isPointerType(AI2->getType()))
216 GraphInfo.argNodes.push_back(mergedG->getNodeForValue(AI2));
217 DEBUG(mergedG->AssertGraphOK());
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000218 }
219 }
220 }
221 DEBUG(std::cerr << "\n");
222}
223
224
Chris Lattner15d879e2004-10-12 16:52:09 +0000225DSGraph &PA::EquivClassGraphs::getOrCreateGraph(Function &F) {
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000226 // Has the graph already been created?
227 DSGraph *&Graph = FoldedGraphsMap[&F];
228 if (Graph) return *Graph;
229
230 // Use the CBU graph directly without copying it.
231 // This automatically updates the FoldedGraphsMap via the reference.
232 Graph = &CBU->getDSGraph(F);
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000233 return *Graph;
234}
235
Chris Lattner15d879e2004-10-12 16:52:09 +0000236DSGraph *PA::EquivClassGraphs::cloneGraph(Function &F) {
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000237 DSGraph *&Graph = FoldedGraphsMap[&F];
238 DSGraph &CBUGraph = CBU->getDSGraph(F);
239 assert(Graph == NULL || Graph == &CBUGraph && "Cloning a graph twice?");
240
241 // Copy the CBU graph...
242 Graph = new DSGraph(CBUGraph); // updates the map via reference
243 Graph->setGlobalsGraph(&getGlobalsGraph());
244 Graph->setPrintAuxCalls();
245
246 // Make sure to update the FoldedGraphsMap map for all functions in the graph!
247 for (DSGraph::ReturnNodesTy::iterator I = Graph->getReturnNodes().begin();
248 I != Graph->getReturnNodes().end(); ++I)
249 if (I->first != &F) {
250 DSGraph*& FG = FoldedGraphsMap[I->first];
251 assert(FG == NULL || FG == &CBU->getDSGraph(*I->first) &&
252 "Merging function in SCC twice?");
253 FG = Graph;
254 }
255
256 return Graph;
257}
258
259
Chris Lattner15d879e2004-10-12 16:52:09 +0000260unsigned PA::EquivClassGraphs::processSCC(DSGraph &FG, Function& F,
261 std::vector<Function*> &Stack,
262 unsigned &NextID,
263 hash_map<Function*,unsigned> &ValMap){
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000264 DEBUG(std::cerr << " ProcessSCC for function " << F.getName() << "\n");
265
266 assert(!ValMap.count(&F) && "Shouldn't revisit functions!");
267 unsigned Min = NextID++, MyID = Min;
268 ValMap[&F] = Min;
269 Stack.push_back(&F);
270
271 // The edges out of the current node are the call site targets...
272 for (unsigned i = 0, e = FG.getFunctionCalls().size(); i != e; ++i) {
273 Instruction *Call = FG.getFunctionCalls()[i].getCallSite().getInstruction();
274
275 // Loop over all of the actually called functions...
276 ActualCalleesTy::const_iterator I, E;
277 for (tie(I, E) = getActualCallees().equal_range(Call); I != E; ++I)
278 if (!I->second->isExternal()) {
279 DSGraph &CalleeG = getOrCreateGraph(*I->second);
280
281 // Have we visited the destination function yet?
282 hash_map<Function*, unsigned>::iterator It = ValMap.find(I->second);
283 unsigned M = (It == ValMap.end()) // No, visit it now.
284 ? processSCC(CalleeG, *I->second, Stack, NextID, ValMap)
285 : It->second; // Yes, get it's number.
286
287 if (M < Min) Min = M;
288 }
289 }
290
291 assert(ValMap[&F] == MyID && "SCC construction assumption wrong!");
292 if (Min != MyID)
293 return Min; // This is part of a larger SCC!
294
295 // If this is a new SCC, process it now.
296 bool IsMultiNodeSCC = false;
297 while (Stack.back() != &F) {
298 DSGraph *NG = &getOrCreateGraph(* Stack.back());
299 ValMap[Stack.back()] = ~0U;
300
301 // Since all SCCs must be the same as those found in CBU, we do not need to
302 // do any merging. Make sure all functions in the SCC share the same graph.
303 assert(NG == &FG &&
304 "FoldGraphs: Functions in the same SCC have different graphs?");
305
306 Stack.pop_back();
307 IsMultiNodeSCC = true;
308 }
309
310 // Clean up the graph before we start inlining a bunch again...
311 if (IsMultiNodeSCC)
312 FG.removeTriviallyDeadNodes();
313
314 Stack.pop_back();
Chris Lattner113cde82004-10-31 17:47:48 +0000315
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000316 processGraph(FG, F);
317 ValMap[&F] = ~0U;
318 return MyID;
319}
320
321
322/// processGraph - Process the CBU graphs for the program in bottom-up order on
323/// the SCC of the __ACTUAL__ call graph. This builds final folded CBU graphs.
Chris Lattner15d879e2004-10-12 16:52:09 +0000324void PA::EquivClassGraphs::processGraph(DSGraph &G, Function &F) {
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000325 DEBUG(std::cerr << " ProcessGraph for function " << F.getName() << "\n");
326
327 hash_set<Instruction*> calls;
328
Chris Lattner113cde82004-10-31 17:47:48 +0000329 DSGraph* CallerGraph = sameAsCBUGraph(F) ? NULL : &getOrCreateGraph(F);
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000330
331 // If the function has not yet been cloned, let's check if any callees
332 // need to be inlined before cloning it.
333 //
334 for (unsigned i=0, e=G.getFunctionCalls().size(); i!=e && !CallerGraph; ++i) {
335 const DSCallSite &CS = G.getFunctionCalls()[i];
336 Instruction *TheCall = CS.getCallSite().getInstruction();
337
338 // Loop over all potential callees to find the first non-external callee.
339 // Some inlining is needed if there is such a callee and it has changed.
340 ActualCalleesTy::const_iterator I, E;
341 for (tie(I, E) = getActualCallees().equal_range(TheCall); I != E; ++I)
342 if (!I->second->isExternal() && !sameAsCBUGraph(*I->second)) {
343 // Ok, the caller does need to be cloned... go ahead and do it now.
344 // clone the CBU graph for F now because we have not cloned it so far
345 CallerGraph = cloneGraph(F);
346 break;
347 }
348 }
349
350 if (!CallerGraph) { // No inlining is needed.
351 DEBUG(std::cerr << " --DONE ProcessGraph for function " << F.getName()
352 << " (NO INLINING NEEDED)\n");
353 return;
354 }
355
356 // Else we need to inline some callee graph. Visit all call sites.
357 // The edges out of the current node are the call site targets...
358 for (unsigned i=0, e = CallerGraph->getFunctionCalls().size(); i != e; ++i) {
359 const DSCallSite &CS = CallerGraph->getFunctionCalls()[i];
360 Instruction *TheCall = CS.getCallSite().getInstruction();
361
362 assert(calls.insert(TheCall).second &&
363 "Call instruction occurs multiple times in graph??");
364
365 // Inline the common callee graph into the current graph, if the callee
366 // graph has not changed. Note that all callees should have the same
367 // graph so we only need to do this once.
368 //
369 DSGraph* CalleeGraph = NULL;
370 ActualCalleesTy::const_iterator I, E;
371 tie(I, E) = getActualCallees().equal_range(TheCall);
372 unsigned TNum, Num;
373
374 // Loop over all potential callees to find the first non-external callee.
375 for (TNum = 0, Num = std::distance(I, E); I != E; ++I, ++TNum)
376 if (!I->second->isExternal())
377 break;
378
379 // Now check if the graph has changed and if so, clone and inline it.
380 if (I != E && !sameAsCBUGraph(*I->second)) {
381 Function *CalleeFunc = I->second;
382
383 // Merge the callee's graph into this graph, if not already the same.
384 // Callees in the same equivalence class (which subsumes those
385 // in the same SCCs) have the same graph. Note that all recursion
386 // including self-recursion have been folded in the equiv classes.
387 //
388 CalleeGraph = &getOrCreateGraph(*CalleeFunc);
389 if (CalleeGraph != CallerGraph) {
390 ++NumFoldGraphInlines;
391 CallerGraph->mergeInGraph(CS, *CalleeFunc, *CalleeGraph,
392 DSGraph::KeepModRefBits |
393 DSGraph::StripAllocaBit |
394 DSGraph::DontCloneCallNodes |
395 DSGraph::DontCloneAuxCallNodes);
396 DEBUG(std::cerr << " Inlining graph [" << i << "/" << e-1
397 << ":" << TNum << "/" << Num-1 << "] for "
398 << CalleeFunc->getName() << "["
399 << CalleeGraph->getGraphSize() << "+"
400 << CalleeGraph->getAuxFunctionCalls().size()
401 << "] into '" /*<< CallerGraph->getFunctionNames()*/ << "' ["
402 << CallerGraph->getGraphSize() << "+"
403 << CallerGraph->getAuxFunctionCalls().size()
404 << "]\n");
405 }
406 }
407
408#ifndef NDEBUG
409 // Now loop over the rest of the callees and make sure they have the
410 // same graph as the one inlined above.
411 if (CalleeGraph)
412 for (++I, ++TNum; I != E; ++I, ++TNum)
413 if (!I->second->isExternal())
414 assert(CalleeGraph == &getOrCreateGraph(*I->second) &&
415 "Callees at a call site have different graphs?");
416#endif
417 }
418
419 // Recompute the Incomplete markers
420 if (CallerGraph != NULL) {
421 assert(CallerGraph->getInlinedGlobals().empty());
422 CallerGraph->maskIncompleteMarkers();
423 CallerGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
424
425 // Delete dead nodes. Treat globals that are unreachable but that can
426 // reach live nodes as live.
427 CallerGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
428 }
429
Chris Lattner15d879e2004-10-12 16:52:09 +0000430 DEBUG(std::cerr << " --DONE ProcessGraph for function "
431 << F.getName() << "\n");
Vikram S. Advec5204fb2004-05-23 07:54:02 +0000432}