blob: 1eeb6907894e7bb6182f2e70b272e7502e7a0bcd [file] [log] [blame]
Vikram S. Adveaaeee752002-07-30 22:06:40 +00001//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
2//
3// This file implements the TDDataStructures class, which represents the
4// Top-down Interprocedural closure of the data structure graph over the
5// program. This is useful (but not strictly necessary?) for applications
6// like pointer analysis.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Analysis/DataStructure.h"
11#include "llvm/Module.h"
12#include "llvm/DerivedTypes.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000013#include "Support/Statistic.h"
Chris Lattner18f07a12003-07-01 16:28:11 +000014#include "DSCallSiteIterator.h"
Vikram S. Adveaaeee752002-07-30 22:06:40 +000015
Chris Lattner4923d1b2003-02-03 22:51:28 +000016namespace {
17 RegisterAnalysis<TDDataStructures> // Register the pass
Chris Lattner312edd32003-06-28 22:14:55 +000018 Y("tddatastructure", "Top-down Data Structure Analysis");
Chris Lattnera8da51b2003-07-02 04:39:44 +000019
20 Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
21}
22
23/// FunctionHasCompleteArguments - This function returns true if it is safe not
24/// to mark arguments to the function complete.
25///
26/// FIXME: Need to check if all callers have been found, or rather if a
27/// funcpointer escapes!
28///
29static bool FunctionHasCompleteArguments(Function &F) {
30 return F.hasInternalLinkage();
Chris Lattner4923d1b2003-02-03 22:51:28 +000031}
Vikram S. Adveaaeee752002-07-30 22:06:40 +000032
Chris Lattneraa0b4682002-11-09 21:12:07 +000033// run - Calculate the top down data structure graphs for each function in the
34// program.
35//
36bool TDDataStructures::run(Module &M) {
37 BUDataStructures &BU = getAnalysis<BUDataStructures>();
Chris Lattner312edd32003-06-28 22:14:55 +000038 GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
Chris Lattneraa0b4682002-11-09 21:12:07 +000039
Chris Lattnera8da51b2003-07-02 04:39:44 +000040 // Figure out which functions must not mark their arguments complete because
41 // they are accessible outside this compilation unit.
42 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
43 if (!FunctionHasCompleteArguments(*I))
44 ArgsRemainIncomplete.insert(I);
45
Chris Lattner6c874612003-07-02 23:42:48 +000046 // We want to traverse the call graph in reverse post-order. To do this, we
47 // calculate a post-order traversal, then reverse it.
48 hash_set<DSGraph*> VisitedGraph;
49 std::vector<DSGraph*> PostOrder;
50 const BUDataStructures::ActualCalleesTy &ActualCallees =
51 getAnalysis<BUDataStructures>().getActualCallees();
52
Chris Lattneraa0b4682002-11-09 21:12:07 +000053 // Calculate top-down from main...
54 if (Function *F = M.getMainFunction())
Chris Lattner61691c52003-07-02 23:44:15 +000055 ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
Chris Lattneraa0b4682002-11-09 21:12:07 +000056
Vikram S. Adve03e19dd2003-07-16 21:40:28 +000057 // Next calculate the graphs for each unreachable function...
Chris Lattnera8da51b2003-07-02 04:39:44 +000058 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner6c874612003-07-02 23:42:48 +000059 ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
60
61 VisitedGraph.clear(); // Release memory!
62
63 // Visit each of the graphs in reverse post-order now!
64 while (!PostOrder.empty()) {
65 inlineGraphIntoCallees(*PostOrder.back());
66 PostOrder.pop_back();
67 }
Chris Lattneraa0b4682002-11-09 21:12:07 +000068
Chris Lattnera8da51b2003-07-02 04:39:44 +000069 ArgsRemainIncomplete.clear();
Chris Lattneraa0b4682002-11-09 21:12:07 +000070 return false;
71}
72
Vikram S. Adveaaeee752002-07-30 22:06:40 +000073
Chris Lattner7a211632002-11-08 21:28:37 +000074DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
75 DSGraph *&G = DSInfo[&F];
76 if (G == 0) { // Not created yet? Clone BU graph...
77 G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F));
78 G->getAuxFunctionCalls().clear();
Chris Lattner24d80072003-02-04 00:59:32 +000079 G->setPrintAuxCalls();
Chris Lattneraa0b4682002-11-09 21:12:07 +000080 G->setGlobalsGraph(GlobalsGraph);
Chris Lattner7a211632002-11-08 21:28:37 +000081 }
82 return *G;
83}
Vikram S. Adve26b98262002-10-20 21:41:02 +000084
Chris Lattnerdea81462003-06-29 22:37:07 +000085
Chris Lattner18f07a12003-07-01 16:28:11 +000086void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
87 std::vector<DSGraph*> &PostOrder,
88 const BUDataStructures::ActualCalleesTy &ActualCallees) {
89 if (F.isExternal()) return;
90 DSGraph &G = getOrCreateDSGraph(F);
91 if (Visited.count(&G)) return;
92 Visited.insert(&G);
93
94 // Recursively traverse all of the callee graphs.
95 const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();
Chris Lattnerdea81462003-06-29 22:37:07 +000096
Chris Lattner18f07a12003-07-01 16:28:11 +000097 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
98 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
99 BUDataStructures::ActualCalleesTy::const_iterator>
Chris Lattnera8da51b2003-07-02 04:39:44 +0000100 IP = ActualCallees.equal_range(&FunctionCalls[i].getCallInst());
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000101
Chris Lattner18f07a12003-07-01 16:28:11 +0000102 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
103 I != IP.second; ++I)
104 ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
105 }
Chris Lattner198be222002-10-21 19:47:18 +0000106
Chris Lattner18f07a12003-07-01 16:28:11 +0000107 PostOrder.push_back(&G);
108}
109
110
111
Chris Lattner18f07a12003-07-01 16:28:11 +0000112
Chris Lattner6c874612003-07-02 23:42:48 +0000113
114// releaseMemory - If the pass pipeline is done with this pass, we can release
115// our memory... here...
116//
117// FIXME: This should be releaseMemory and will work fine, except that LoadVN
118// has no way to extend the lifetime of the pass, which screws up ds-aa.
119//
120void TDDataStructures::releaseMyMemory() {
121 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
122 E = DSInfo.end(); I != E; ++I) {
123 I->second->getReturnNodes().erase(I->first);
124 if (I->second->getReturnNodes().empty())
125 delete I->second;
Chris Lattner18f07a12003-07-01 16:28:11 +0000126 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000127
Chris Lattner6c874612003-07-02 23:42:48 +0000128 // Empty map so next time memory is released, data structures are not
129 // re-deleted.
130 DSInfo.clear();
131 delete GlobalsGraph;
132 GlobalsGraph = 0;
133}
Chris Lattner18f07a12003-07-01 16:28:11 +0000134
135void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000136 // Recompute the Incomplete markers and eliminate unreachable nodes.
Chris Lattner47030f82003-07-02 19:49:11 +0000137 Graph.removeTriviallyDeadNodes();
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000138 Graph.maskIncompleteMarkers();
Chris Lattnera8da51b2003-07-02 04:39:44 +0000139
140 // If any of the functions has incomplete incoming arguments, don't mark any
141 // of them as complete.
142 bool HasIncompleteArgs = false;
143 const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();
144 for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),
145 E = GraphReturnNodes.end(); I != E; ++I)
146 if (ArgsRemainIncomplete.count(I->first)) {
147 HasIncompleteArgs = true;
148 break;
149 }
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000150
151 // Now fold in the necessary globals from the GlobalsGraph. A global G
152 // must be folded in if it exists in the current graph (i.e., is not dead)
153 // and it was not inlined from any of my callers. If it was inlined from
154 // a caller, it would have been fully consistent with the GlobalsGraph
155 // in the caller so folding in is not necessary. Otherwise, this node came
156 // solely from this function's BU graph and so has to be made consistent.
157 //
158 Graph.updateFromGlobalGraph();
159
160 // Recompute the Incomplete markers. Depends on whether args are complete
Chris Lattnera8da51b2003-07-02 04:39:44 +0000161 unsigned Flags
162 = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000163 Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000164
165 // Delete dead nodes. Treat globals that are unreachable as dead also.
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000166 Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
167
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000168 // We are done with computing the current TD Graph! Now move on to
169 // inlining the current graph into the graphs for its callees, if any.
170 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000171 const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
172 if (FunctionCalls.empty()) {
Chris Lattner18f07a12003-07-01 16:28:11 +0000173 DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
174 << "\n");
175 return;
176 }
177
Chris Lattner18f07a12003-07-01 16:28:11 +0000178 // Now that we have information about all of the callees, propagate the
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000179 // current graph into the callees. Clone only the reachable subgraph at
180 // each call-site, not the entire graph (even though the entire graph
181 // would be cloned only once, this should still be better on average).
Chris Lattner18f07a12003-07-01 16:28:11 +0000182 //
183 DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
Chris Lattnera8da51b2003-07-02 04:39:44 +0000184 << FunctionCalls.size() << " call nodes.\n");
Chris Lattner18f07a12003-07-01 16:28:11 +0000185
Chris Lattnera8da51b2003-07-02 04:39:44 +0000186 const BUDataStructures::ActualCalleesTy &ActualCallees =
187 getAnalysis<BUDataStructures>().getActualCallees();
Chris Lattner18f07a12003-07-01 16:28:11 +0000188
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000189 // Loop over all the call sites and all the callees at each call site.
190 // Clone and merge the reachable subgraph from the call into callee's graph.
191 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000192 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000193 // For each function in the invoked function list at this call site...
Chris Lattnera8da51b2003-07-02 04:39:44 +0000194 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
195 BUDataStructures::ActualCalleesTy::const_iterator>
196 IP = ActualCallees.equal_range(&FunctionCalls[i].getCallInst());
197
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000198 // Multiple callees may have the same graph, so try to inline and merge
199 // only once for each <callSite,calleeGraph> pair, not once for each
200 // <callSite,calleeFunction> pair; the latter will be correct but slower.
201 hash_set<DSGraph*> GraphsSeen;
202
203 // Loop over each actual callee at this call site
204 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
205 I != IP.second; ++I) {
206 DSGraph& CalleeGraph = getDSGraph(*I->second);
207 assert(&CalleeGraph != &Graph && "TD need not inline graph into self!");
208
209 // if this callee graph is already done at this site, skip this callee
210 if (GraphsSeen.find(&CalleeGraph) != GraphsSeen.end())
211 continue;
212 GraphsSeen.insert(&CalleeGraph);
213
214 // Get the root nodes for cloning the reachable subgraph into each callee:
215 // -- all global nodes that appear in both the caller and the callee
216 // -- return value at this call site, if any
217 // -- actual arguments passed at this call site
218 // -- callee node at this call site, if this is an indirect call (this may
219 // not be needed for merging, but allows us to create CS and therefore
220 // simplify the merging below).
221 hash_set<const DSNode*> RootNodeSet;
222 for (DSGraph::ScalarMapTy::const_iterator
223 SI = CalleeGraph.getScalarMap().begin(),
224 SE = CalleeGraph.getScalarMap().end(); SI != SE; ++SI)
225 if (GlobalValue* GV = dyn_cast<GlobalValue>(SI->first)) {
226 DSGraph::ScalarMapTy::const_iterator GI=Graph.getScalarMap().find(GV);
227 if (GI != Graph.getScalarMap().end())
228 RootNodeSet.insert(GI->second.getNode());
Chris Lattnera8da51b2003-07-02 04:39:44 +0000229 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000230
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000231 if (const DSNode* RetNode = FunctionCalls[i].getRetVal().getNode())
232 RootNodeSet.insert(RetNode);
Chris Lattner0e744122002-10-17 04:26:54 +0000233
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000234 for (unsigned j=0, N=FunctionCalls[i].getNumPtrArgs(); j < N; ++j)
235 if (const DSNode* ArgTarget = FunctionCalls[i].getPtrArg(j).getNode())
236 RootNodeSet.insert(ArgTarget);
237
238 if (FunctionCalls[i].isIndirectCall())
239 RootNodeSet.insert(FunctionCalls[i].getCalleeNode());
240
Chris Lattnera8da51b2003-07-02 04:39:44 +0000241 DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000242 << CalleeGraph.getFunctionNames()
243 << "': " << I->second->getFunctionType()->getNumParams()
244 << " args\n at call site (DSCallSite*) 0x"
245 << &FunctionCalls[i] << "\n");
246
247 DSGraph::NodeMapTy NodeMapInCallee; // map from nodes to clones in callee
248 DSGraph::NodeMapTy CompletedMap; // unused map for nodes not to do
249 CalleeGraph.cloneReachableSubgraph(Graph, RootNodeSet,
250 NodeMapInCallee, CompletedMap,
251 DSGraph::StripModRefBits |
252 DSGraph::KeepAllocaBit);
Chris Lattner7a211632002-11-08 21:28:37 +0000253
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000254 // Transform our call site info into the cloned version for CalleeGraph
255 DSCallSite CS(FunctionCalls[i], NodeMapInCallee);
Chris Lattnera8da51b2003-07-02 04:39:44 +0000256
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000257 // Get the formal argument and return nodes for the called function
258 // and merge them with the cloned subgraph. Global nodes were merged
259 // already by cloneReachableSubgraph() above.
260 CalleeGraph.getCallSiteForArguments(*I->second).mergeWith(CS);
261
262 ++NumTDInlines;
Chris Lattnera8da51b2003-07-02 04:39:44 +0000263 }
Chris Lattnere0fbd482003-02-09 18:42:43 +0000264 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000265
266 DEBUG(std::cerr << " [TD] Done inlining into callees for: "
267 << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
268 << Graph.getFunctionCalls().size() << "]\n");
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000269}
Chris Lattner4923d1b2003-02-03 22:51:28 +0000270