1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
3 // This file implements the BUDataStructures class, which represents the
4 // Bottom-Up Interprocedural closure of the data structure graph over the
5 // program. This is useful for applications like pool allocation, but **not**
6 // applications like alias analysis.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Analysis/DataStructure.h"
11 #include "llvm/Analysis/DSGraph.h"
12 #include "llvm/Module.h"
13 #include "Support/Statistic.h"
14 #include "Support/hash_map"
17 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
19 RegisterAnalysis<BUDataStructures>
20 X("budatastructure", "Bottom-up Data Structure Analysis Closure");
25 static bool isVAHackFn(const Function *F) {
26 return F->getName() == "printf" || F->getName() == "sscanf" ||
27 F->getName() == "fprintf" || F->getName() == "open" ||
28 F->getName() == "sprintf" || F->getName() == "fputs" ||
29 F->getName() == "fscanf";
32 // isCompleteNode - Return true if we know all of the targets of this node, and
33 // if the call sites are not external.
35 static inline bool isCompleteNode(DSNode *N) {
36 if (N->NodeType & DSNode::Incomplete) return false;
37 const std::vector<GlobalValue*> &Callees = N->getGlobals();
38 for (unsigned i = 0, e = Callees.size(); i != e; ++i)
39 if (Callees[i]->isExternal())
40 if (!isVAHackFn(cast<Function>(Callees[i])))
41 return false; // External function found...
42 return true; // otherwise ok
45 struct CallSiteIterator {
46 // FCs are the edges out of the current node are the call site targets...
47 std::vector<DSCallSite> *FCs;
49 unsigned CallSiteEntry;
51 CallSiteIterator(std::vector<DSCallSite> &CS) : FCs(&CS) {
52 CallSite = 0; CallSiteEntry = 0;
53 advanceToValidCallee();
56 // End iterator ctor...
57 CallSiteIterator(std::vector<DSCallSite> &CS, bool) : FCs(&CS) {
58 CallSite = FCs->size(); CallSiteEntry = 0;
61 void advanceToValidCallee() {
62 while (CallSite < FCs->size()) {
63 if ((*FCs)[CallSite].isDirectCall()) {
64 if (CallSiteEntry == 0 && // direct call only has one target...
65 (!(*FCs)[CallSite].getCalleeFunc()->isExternal() ||
66 isVAHackFn((*FCs)[CallSite].getCalleeFunc()))) // If not external
69 DSNode *CalleeNode = (*FCs)[CallSite].getCalleeNode();
70 if (CallSiteEntry || isCompleteNode(CalleeNode)) {
71 const std::vector<GlobalValue*> &Callees = CalleeNode->getGlobals();
73 if (CallSiteEntry < Callees.size())
82 static CallSiteIterator begin(DSGraph &G) { return G.getAuxFunctionCalls(); }
83 static CallSiteIterator end(DSGraph &G) {
84 return CallSiteIterator(G.getAuxFunctionCalls(), true);
86 static CallSiteIterator begin(std::vector<DSCallSite> &CSs) { return CSs; }
87 static CallSiteIterator end(std::vector<DSCallSite> &CSs) {
88 return CallSiteIterator(CSs, true);
90 bool operator==(const CallSiteIterator &CSI) const {
91 return CallSite == CSI.CallSite && CallSiteEntry == CSI.CallSiteEntry;
93 bool operator!=(const CallSiteIterator &CSI) const { return !operator==(CSI);}
95 unsigned getCallSiteIdx() const { return CallSite; }
96 DSCallSite &getCallSite() const { return (*FCs)[CallSite]; }
98 Function *operator*() const {
99 if ((*FCs)[CallSite].isDirectCall()) {
100 return (*FCs)[CallSite].getCalleeFunc();
102 DSNode *Node = (*FCs)[CallSite].getCalleeNode();
103 return cast<Function>(Node->getGlobals()[CallSiteEntry]);
107 CallSiteIterator& operator++() { // Preincrement
109 advanceToValidCallee();
112 CallSiteIterator operator++(int) { // Postincrement
113 CallSiteIterator tmp = *this; ++*this; return tmp;
119 // run - Calculate the bottom up data structure graphs for each function in the
122 bool BUDataStructures::run(Module &M) {
123 GlobalsGraph = new DSGraph();
124 GlobalsGraph->setPrintAuxCalls();
126 Function *MainFunc = M.getMainFunction();
128 calculateReachableGraphs(MainFunc);
130 // Calculate the graphs for any functions that are unreachable from main...
131 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
132 if (!I->isExternal() && DSInfo.find(I) == DSInfo.end()) {
135 std::cerr << "*** Function unreachable from main: "
136 << I->getName() << "\n";
138 calculateReachableGraphs(I); // Calculate all graphs...
143 void BUDataStructures::calculateReachableGraphs(Function *F) {
144 std::vector<Function*> Stack;
145 hash_map<Function*, unsigned> ValMap;
147 calculateGraphs(F, Stack, NextID, ValMap);
150 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
151 // Has the graph already been created?
152 DSGraph *&Graph = DSInfo[F];
153 if (Graph) return *Graph;
155 // Copy the local version into DSInfo...
156 Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F));
158 Graph->setGlobalsGraph(GlobalsGraph);
159 Graph->setPrintAuxCalls();
161 // Start with a copy of the original call sites...
162 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
166 unsigned BUDataStructures::calculateGraphs(Function *F,
167 std::vector<Function*> &Stack,
169 hash_map<Function*, unsigned> &ValMap) {
170 assert(ValMap.find(F) == ValMap.end() && "Shouldn't revisit functions!");
171 unsigned Min = NextID++, MyID = Min;
175 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
182 DSGraph &Graph = getOrCreateGraph(F);
184 // The edges out of the current node are the call site targets...
185 for (CallSiteIterator I = CallSiteIterator::begin(Graph),
186 E = CallSiteIterator::end(Graph); I != E; ++I) {
187 Function *Callee = *I;
189 // Have we visited the destination function yet?
190 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
191 if (It == ValMap.end()) // No, visit it now.
192 M = calculateGraphs(Callee, Stack, NextID, ValMap);
193 else // Yes, get it's number.
195 if (M < Min) Min = M;
198 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
200 return Min; // This is part of a larger SCC!
202 // If this is a new SCC, process it now.
203 if (Stack.back() == F) { // Special case the single "SCC" case here.
204 DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
205 << F->getName() << "\n");
207 DSGraph &G = calculateGraph(*F);
209 if (MaxSCC < 1) MaxSCC = 1;
211 // Should we revisit the graph?
212 if (CallSiteIterator::begin(G) != CallSiteIterator::end(G)) {
214 return calculateGraphs(F, Stack, NextID, ValMap);
221 // SCCFunctions - Keep track of the functions in the current SCC
223 hash_set<Function*> SCCFunctions;
226 std::vector<Function*>::iterator FirstInSCC = Stack.end();
230 SCCFunctions.insert(NF);
233 std::cerr << "Identified SCC #: " << MyID << " of size: "
234 << (Stack.end()-FirstInSCC) << "\n";
236 // Compute the Max SCC Size...
237 if (MaxSCC < unsigned(Stack.end()-FirstInSCC))
238 MaxSCC = Stack.end()-FirstInSCC;
240 std::vector<Function*>::iterator I = Stack.end();
244 /*DEBUG*/(std::cerr << " Fn #" << (Stack.end()-I) << "/"
245 << (Stack.end()-FirstInSCC) << " in SCC: "
247 DSGraph &G = getDSGraph(**I);
248 std::cerr << " [" << G.getGraphSize() << "+"
249 << G.getAuxFunctionCalls().size() << "] ";
252 // Eliminate all call sites in the SCC that are not to functions that are
254 inlineNonSCCGraphs(**I, SCCFunctions);
257 std::cerr << "after Non-SCC's [" << G.getGraphSize() << "+"
258 << G.getAuxFunctionCalls().size() << "]\n";
260 } while (I != FirstInSCC);
266 /*DEBUG*/(std::cerr << " Fn #" << (Stack.end()-I) << "/"
267 << (Stack.end()-FirstInSCC) << " in SCC: "
269 DSGraph &G = getDSGraph(**I);
270 std::cerr << " [" << G.getGraphSize() << "+"
271 << G.getAuxFunctionCalls().size() << "] ";
273 // Inline all graphs into the SCC nodes...
274 calculateSCCGraph(**I, SCCFunctions);
277 std::cerr << "after [" << G.getGraphSize() << "+"
278 << G.getAuxFunctionCalls().size() << "]\n";
280 } while (I != FirstInSCC);
283 std::cerr << "DONE with SCC #: " << MyID << "\n";
285 // We never have to revisit "SCC" processed functions...
287 // Drop the stuff we don't need from the end of the stack
288 Stack.erase(FirstInSCC, Stack.end());
292 return MyID; // == Min
296 // releaseMemory - If the pass pipeline is done with this pass, we can release
297 // our memory... here...
299 void BUDataStructures::releaseMemory() {
300 for (hash_map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
301 E = DSInfo.end(); I != E; ++I)
304 // Empty map so next time memory is released, data structures are not
311 DSGraph &BUDataStructures::calculateGraph(Function &F) {
312 DSGraph &Graph = getDSGraph(F);
313 DEBUG(std::cerr << " [BU] Calculating graph for: " << F.getName() << "\n");
315 // Move our call site list into TempFCs so that inline call sites go into the
316 // new call site list and doesn't invalidate our iterators!
317 std::vector<DSCallSite> TempFCs;
318 std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
319 TempFCs.swap(AuxCallsList);
321 // Loop over all of the resolvable call sites
322 unsigned LastCallSiteIdx = ~0U;
323 for (CallSiteIterator I = CallSiteIterator::begin(TempFCs),
324 E = CallSiteIterator::end(TempFCs); I != E; ++I) {
325 // If we skipped over any call sites, they must be unresolvable, copy them
326 // to the real call site list.
328 for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
329 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
330 LastCallSiteIdx = I.getCallSiteIdx();
332 // Resolve the current call...
333 Function *Callee = *I;
334 DSCallSite &CS = I.getCallSite();
336 if (Callee->isExternal()) {
337 // Ignore this case, simple varargs functions we cannot stub out!
338 } else if (Callee == &F) {
339 // Self recursion... simply link up the formal arguments with the
340 // actual arguments...
341 DEBUG(std::cerr << " Self Inlining: " << F.getName() << "\n");
343 // Handle self recursion by resolving the arguments and return value
344 Graph.mergeInGraph(CS, Graph, 0);
347 // Get the data structure graph for the called function.
349 DSGraph &GI = getDSGraph(*Callee); // Graph to inline
351 DEBUG(std::cerr << " Inlining graph for " << Callee->getName()
352 << "[" << GI.getGraphSize() << "+"
353 << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
354 << "[" << Graph.getGraphSize() << "+"
355 << Graph.getAuxFunctionCalls().size() << "]\n");
357 Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_before_" +
361 // Handle self recursion by resolving the arguments and return value
362 Graph.mergeInGraph(CS, GI,
363 DSGraph::KeepModRefBits |
364 DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes);
367 Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_after_" +
373 // Make sure to catch any leftover unresolvable calls...
374 for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
375 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
379 // Recompute the Incomplete markers. If there are any function calls left
380 // now that are complete, we must loop!
381 Graph.maskIncompleteMarkers();
382 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
383 // FIXME: materialize nodes from the globals graph as neccesary...
384 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
386 DEBUG(std::cerr << " [BU] Done inlining: " << F.getName() << " ["
387 << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
390 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
396 // inlineNonSCCGraphs - This method is almost like the other two calculate graph
397 // methods. This one is used to inline function graphs (from functions outside
398 // of the SCC) into functions in the SCC. It is not supposed to touch functions
399 // IN the SCC at all.
401 DSGraph &BUDataStructures::inlineNonSCCGraphs(Function &F,
402 hash_set<Function*> &SCCFunctions){
403 DSGraph &Graph = getDSGraph(F);
404 DEBUG(std::cerr << " [BU] Inlining Non-SCC graphs for: "
405 << F.getName() << "\n");
407 // Move our call site list into TempFCs so that inline call sites go into the
408 // new call site list and doesn't invalidate our iterators!
409 std::vector<DSCallSite> TempFCs;
410 std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
411 TempFCs.swap(AuxCallsList);
413 // Loop over all of the resolvable call sites
414 unsigned LastCallSiteIdx = ~0U;
415 for (CallSiteIterator I = CallSiteIterator::begin(TempFCs),
416 E = CallSiteIterator::end(TempFCs); I != E; ++I) {
417 // If we skipped over any call sites, they must be unresolvable, copy them
418 // to the real call site list.
420 for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
421 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
422 LastCallSiteIdx = I.getCallSiteIdx();
424 // Resolve the current call...
425 Function *Callee = *I;
426 DSCallSite &CS = I.getCallSite();
428 if (Callee->isExternal()) {
429 // Ignore this case, simple varargs functions we cannot stub out!
430 } else if (SCCFunctions.count(Callee)) {
431 // Calling a function in the SCC, ignore it for now!
432 DEBUG(std::cerr << " SCC CallSite for: " << Callee->getName() << "\n");
433 AuxCallsList.push_back(CS);
435 // Get the data structure graph for the called function.
437 DSGraph &GI = getDSGraph(*Callee); // Graph to inline
439 DEBUG(std::cerr << " Inlining graph for " << Callee->getName()
440 << "[" << GI.getGraphSize() << "+"
441 << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
442 << "[" << Graph.getGraphSize() << "+"
443 << Graph.getAuxFunctionCalls().size() << "]\n");
445 // Handle self recursion by resolving the arguments and return value
446 Graph.mergeInGraph(CS, GI,
447 DSGraph::KeepModRefBits | DSGraph::StripAllocaBit |
448 DSGraph::DontCloneCallNodes);
452 // Make sure to catch any leftover unresolvable calls...
453 for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
454 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
458 // Recompute the Incomplete markers. If there are any function calls left
459 // now that are complete, we must loop!
460 Graph.maskIncompleteMarkers();
461 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
462 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
464 DEBUG(std::cerr << " [BU] Done Non-SCC inlining: " << F.getName() << " ["
465 << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
467 //Graph.writeGraphToFile(std::cerr, "nscc_" + F.getName());
472 DSGraph &BUDataStructures::calculateSCCGraph(Function &F,
473 hash_set<Function*> &SCCFunctions){
474 DSGraph &Graph = getDSGraph(F);
475 DEBUG(std::cerr << " [BU] Calculating SCC graph for: " << F.getName()<<"\n");
477 std::vector<DSCallSite> UnresolvableCalls;
478 hash_map<Function*, DSCallSite> SCCCallSiteMap;
479 std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
481 while (1) { // Loop until we run out of resolvable call sites!
482 // Move our call site list into TempFCs so that inline call sites go into
483 // the new call site list and doesn't invalidate our iterators!
484 std::vector<DSCallSite> TempFCs;
485 TempFCs.swap(AuxCallsList);
487 // Loop over all of the resolvable call sites
488 unsigned LastCallSiteIdx = ~0U;
489 CallSiteIterator I = CallSiteIterator::begin(TempFCs),
490 E = CallSiteIterator::end(TempFCs);
492 TempFCs.swap(AuxCallsList);
493 break; // Done when no resolvable call sites exist
496 for (; I != E; ++I) {
497 // If we skipped over any call sites, they must be unresolvable, copy them
498 // to the unresolvable site list.
500 for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
501 UnresolvableCalls.push_back(TempFCs[LastCallSiteIdx]);
502 LastCallSiteIdx = I.getCallSiteIdx();
504 // Resolve the current call...
505 Function *Callee = *I;
506 DSCallSite &CS = I.getCallSite();
508 if (Callee->isExternal()) {
509 // Ignore this case, simple varargs functions we cannot stub out!
510 } else if (Callee == &F) {
511 // Self recursion... simply link up the formal arguments with the
512 // actual arguments...
513 DEBUG(std::cerr << " Self Inlining: " << F.getName() << "\n");
515 // Handle self recursion by resolving the arguments and return value
516 Graph.mergeInGraph(CS, Graph, 0);
517 } else if (SCCCallSiteMap.count(Callee)) {
518 // We have already seen a call site in the SCC for this function, just
519 // merge the two call sites together and we are done.
520 SCCCallSiteMap.find(Callee)->second.mergeWith(CS);
522 // Get the data structure graph for the called function.
524 DSGraph &GI = getDSGraph(*Callee); // Graph to inline
525 DEBUG(std::cerr << " Inlining graph for " << Callee->getName()
526 << "[" << GI.getGraphSize() << "+"
527 << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
528 << "[" << Graph.getGraphSize() << "+"
529 << Graph.getAuxFunctionCalls().size() << "]\n");
531 // Handle self recursion by resolving the arguments and return value
532 Graph.mergeInGraph(CS, GI,
533 DSGraph::KeepModRefBits | DSGraph::StripAllocaBit |
534 DSGraph::DontCloneCallNodes);
536 if (SCCFunctions.count(Callee))
537 SCCCallSiteMap.insert(std::make_pair(Callee, CS));
541 // Make sure to catch any leftover unresolvable calls...
542 for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
543 UnresolvableCalls.push_back(TempFCs[LastCallSiteIdx]);
546 // Reset the SCCCallSiteMap...
547 SCCCallSiteMap.clear();
549 AuxCallsList.insert(AuxCallsList.end(), UnresolvableCalls.begin(),
550 UnresolvableCalls.end());
551 UnresolvableCalls.clear();
554 // Recompute the Incomplete markers. If there are any function calls left
555 // now that are complete, we must loop!
556 Graph.maskIncompleteMarkers();
557 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
559 // FIXME: materialize nodes from the globals graph as neccesary...
561 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
563 DEBUG(std::cerr << " [BU] Done inlining: " << F.getName() << " ["
564 << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
566 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());