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 "DSCallSiteIterator.h"
11 #include "llvm/Analysis/DataStructure.h"
12 #include "llvm/Module.h"
13 #include "Support/Statistic.h"
16 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
18 RegisterAnalysis<BUDataStructures>
19 X("budatastructure", "Bottom-up Data Structure Analysis");
24 // run - Calculate the bottom up data structure graphs for each function in the
27 bool BUDataStructures::run(Module &M) {
28 LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
29 GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph());
30 GlobalsGraph->setPrintAuxCalls();
32 Function *MainFunc = M.getMainFunction();
34 calculateReachableGraphs(MainFunc);
36 // Calculate the graphs for any functions that are unreachable from main...
37 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
38 if (!I->isExternal() && DSInfo.find(I) == DSInfo.end()) {
41 std::cerr << "*** Function unreachable from main: "
42 << I->getName() << "\n";
44 calculateReachableGraphs(I); // Calculate all graphs...
49 void BUDataStructures::calculateReachableGraphs(Function *F) {
50 std::vector<Function*> Stack;
51 hash_map<Function*, unsigned> ValMap;
53 calculateGraphs(F, Stack, NextID, ValMap);
56 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
57 // Has the graph already been created?
58 DSGraph *&Graph = DSInfo[F];
59 if (Graph) return *Graph;
61 // Copy the local version into DSInfo...
62 Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F));
64 Graph->setGlobalsGraph(GlobalsGraph);
65 Graph->setPrintAuxCalls();
67 // Start with a copy of the original call sites...
68 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
72 unsigned BUDataStructures::calculateGraphs(Function *F,
73 std::vector<Function*> &Stack,
75 hash_map<Function*, unsigned> &ValMap) {
76 assert(ValMap.find(F) == ValMap.end() && "Shouldn't revisit functions!");
77 unsigned Min = NextID++, MyID = Min;
81 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
88 DSGraph &Graph = getOrCreateGraph(F);
90 // The edges out of the current node are the call site targets...
91 for (DSCallSiteIterator I = DSCallSiteIterator::begin_aux(Graph),
92 E = DSCallSiteIterator::end_aux(Graph); I != E; ++I) {
93 Function *Callee = *I;
95 // Have we visited the destination function yet?
96 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
97 if (It == ValMap.end()) // No, visit it now.
98 M = calculateGraphs(Callee, Stack, NextID, ValMap);
99 else // Yes, get it's number.
101 if (M < Min) Min = M;
104 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
106 return Min; // This is part of a larger SCC!
108 // If this is a new SCC, process it now.
109 if (Stack.back() == F) { // Special case the single "SCC" case here.
110 DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
111 << F->getName() << "\n");
113 DSGraph &G = getDSGraph(*F);
114 DEBUG(std::cerr << " [BU] Calculating graph for: " << F->getName()<< "\n");
116 DEBUG(std::cerr << " [BU] Done inlining: " << F->getName() << " ["
117 << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
120 if (MaxSCC < 1) MaxSCC = 1;
122 // Should we revisit the graph?
123 if (DSCallSiteIterator::begin_aux(G) != DSCallSiteIterator::end_aux(G)) {
125 return calculateGraphs(F, Stack, NextID, ValMap);
132 // SCCFunctions - Keep track of the functions in the current SCC
134 hash_set<Function*> SCCFunctions;
137 std::vector<Function*>::iterator FirstInSCC = Stack.end();
138 DSGraph *SCCGraph = 0;
142 SCCFunctions.insert(NF);
144 // Figure out which graph is the largest one, in order to speed things up
145 // a bit in situations where functions in the SCC have widely different
147 DSGraph &NFGraph = getDSGraph(*NF);
148 if (!SCCGraph || SCCGraph->getGraphSize() < NFGraph.getGraphSize())
152 std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
153 << SCCFunctions.size() << "\n";
155 // Compute the Max SCC Size...
156 if (MaxSCC < SCCFunctions.size())
157 MaxSCC = SCCFunctions.size();
159 // First thing first, collapse all of the DSGraphs into a single graph for
160 // the entire SCC. We computed the largest graph, so clone all of the other
161 // (smaller) graphs into it. Discard all of the old graphs.
163 for (hash_set<Function*>::iterator I = SCCFunctions.begin(),
164 E = SCCFunctions.end(); I != E; ++I) {
165 DSGraph &G = getDSGraph(**I);
166 if (&G != SCCGraph) {
167 DSGraph::NodeMapTy NodeMap;
168 SCCGraph->cloneInto(G, SCCGraph->getScalarMap(),
169 SCCGraph->getReturnNodes(), NodeMap, 0);
170 // Update the DSInfo map and delete the old graph...
171 DSInfo[*I] = SCCGraph;
176 // Now that we have one big happy family, resolve all of the call sites in
178 calculateGraph(*SCCGraph);
179 DEBUG(std::cerr << " [BU] Done inlining SCC [" << SCCGraph->getGraphSize()
180 << "+" << SCCGraph->getAuxFunctionCalls().size() << "]\n");
182 std::cerr << "DONE with SCC #: " << MyID << "\n";
184 // We never have to revisit "SCC" processed functions...
186 // Drop the stuff we don't need from the end of the stack
187 Stack.erase(FirstInSCC, Stack.end());
191 return MyID; // == Min
195 // releaseMemory - If the pass pipeline is done with this pass, we can release
196 // our memory... here...
198 void BUDataStructures::releaseMemory() {
199 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
200 E = DSInfo.end(); I != E; ++I) {
201 I->second->getReturnNodes().erase(I->first);
202 if (I->second->getReturnNodes().empty())
206 // Empty map so next time memory is released, data structures are not
213 void BUDataStructures::calculateGraph(DSGraph &Graph) {
214 // Move our call site list into TempFCs so that inline call sites go into the
215 // new call site list and doesn't invalidate our iterators!
216 std::vector<DSCallSite> TempFCs;
217 std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
218 TempFCs.swap(AuxCallsList);
220 DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
222 // Loop over all of the resolvable call sites
223 unsigned LastCallSiteIdx = ~0U;
224 for (DSCallSiteIterator I = DSCallSiteIterator::begin(TempFCs),
225 E = DSCallSiteIterator::end(TempFCs); I != E; ++I) {
226 // If we skipped over any call sites, they must be unresolvable, copy them
227 // to the real call site list.
229 for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
230 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
231 LastCallSiteIdx = I.getCallSiteIdx();
233 // Resolve the current call...
234 Function *Callee = *I;
235 const DSCallSite &CS = I.getCallSite();
237 if (Callee->isExternal()) {
238 // Ignore this case, simple varargs functions we cannot stub out!
239 } else if (ReturnNodes.find(Callee) != ReturnNodes.end()) {
240 // Self recursion... simply link up the formal arguments with the
241 // actual arguments...
242 DEBUG(std::cerr << " Self Inlining: " << Callee->getName() << "\n");
244 // Handle self recursion by resolving the arguments and return value
245 Graph.mergeInGraph(CS, *Callee, Graph, 0);
248 // Get the data structure graph for the called function.
250 DSGraph &GI = getDSGraph(*Callee); // Graph to inline
252 DEBUG(std::cerr << " Inlining graph for " << Callee->getName()
253 << "[" << GI.getGraphSize() << "+"
254 << GI.getAuxFunctionCalls().size() << "] into ["
255 << Graph.getGraphSize() << "+"
256 << Graph.getAuxFunctionCalls().size() << "]\n");
258 // Handle self recursion by resolving the arguments and return value
259 Graph.mergeInGraph(CS, *Callee, GI,
260 DSGraph::KeepModRefBits |
261 DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes);
264 Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_after_" +
270 // Make sure to catch any leftover unresolvable calls...
271 for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
272 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
276 // Recompute the Incomplete markers. If there are any function calls left
277 // now that are complete, we must loop!
278 Graph.maskIncompleteMarkers();
279 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
280 // FIXME: materialize nodes from the globals graph as neccesary...
281 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
283 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());