blob: 5d62f0907300cbefdf7709f739f898769598b673 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00002//
Chris Lattnerc68c31b2002-07-10 22:38:08 +00003// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00004//
5//===----------------------------------------------------------------------===//
6
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00007#include "llvm/Module.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +00008#include "llvm/DerivedTypes.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +00009#include "Support/STLExtras.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000010#include "Support/StatisticReporter.h"
Chris Lattnere2219762002-07-18 18:22:40 +000011#include "Support/STLExtras.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000012#include <algorithm>
Chris Lattnere2219762002-07-18 18:22:40 +000013#include <set>
Chris Lattner0d9bab82002-07-18 00:12:30 +000014#include "llvm/Analysis/DataStructure.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000015
Chris Lattnere2219762002-07-18 18:22:40 +000016using std::vector;
17
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000018//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000019// DSNode Implementation
20//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000021
Chris Lattnerc68c31b2002-07-10 22:38:08 +000022DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
23 // If this node has any fields, allocate them now, but leave them null.
24 switch (T->getPrimitiveID()) {
25 case Type::PointerTyID: Links.resize(1); break;
26 case Type::ArrayTyID: Links.resize(1); break;
27 case Type::StructTyID:
28 Links.resize(cast<StructType>(T)->getNumContainedTypes());
29 break;
30 default: break;
31 }
32}
33
Chris Lattner0d9bab82002-07-18 00:12:30 +000034// DSNode copy constructor... do not copy over the referrers list!
35DSNode::DSNode(const DSNode &N)
36 : Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
37}
38
Chris Lattnerc68c31b2002-07-10 22:38:08 +000039void DSNode::removeReferrer(DSNodeHandle *H) {
40 // Search backwards, because we depopulate the list from the back for
41 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000042 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000043 std::find(Referrers.rbegin(), Referrers.rend(), H);
44 assert(I != Referrers.rend() && "Referrer not pointing to node!");
45 Referrers.erase(I.base()-1);
46}
47
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000048// addGlobal - Add an entry for a global value to the Globals list. This also
49// marks the node with the 'G' flag if it does not already have it.
50//
51void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000052 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000053 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000054 std::lower_bound(Globals.begin(), Globals.end(), GV);
55
56 if (I == Globals.end() || *I != GV) {
57 assert(GV->getType()->getElementType() == Ty);
58 Globals.insert(I, GV);
59 NodeType |= GlobalNode;
60 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000061}
62
63
Chris Lattnerc68c31b2002-07-10 22:38:08 +000064// addEdgeTo - Add an edge from the current node to the specified node. This
65// can cause merging of nodes in the graph.
66//
67void DSNode::addEdgeTo(unsigned LinkNo, DSNode *N) {
68 assert(LinkNo < Links.size() && "LinkNo out of range!");
69 if (N == 0 || Links[LinkNo] == N) return; // Nothing to do
70 if (Links[LinkNo] == 0) { // No merging to perform
71 Links[LinkNo] = N;
72 return;
73 }
74
75 // Merge the two nodes...
76 Links[LinkNo]->mergeWith(N);
77}
78
79
80// mergeWith - Merge this node into the specified node, moving all links to and
81// from the argument node into the current node. The specified node may be a
82// null pointer (in which case, nothing happens).
83//
84void DSNode::mergeWith(DSNode *N) {
85 if (N == 0 || N == this) return; // Noop
86 assert(N->Ty == Ty && N->Links.size() == Links.size() &&
87 "Cannot merge nodes of two different types!");
88
89 // Remove all edges pointing at N, causing them to point to 'this' instead.
90 while (!N->Referrers.empty())
91 *N->Referrers.back() = this;
92
93 // Make all of the outgoing links of N now be outgoing links of this. This
94 // can cause recursive merging!
95 //
96 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
97 addEdgeTo(i, N->Links[i]);
98 N->Links[i] = 0; // Reduce unneccesary edges in graph. N is dead
99 }
100
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000101 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000102 NodeType |= N->NodeType;
103 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000104
105 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000106 if (!N->Globals.empty()) {
107 // Save the current globals off to the side...
Chris Lattnere2219762002-07-18 18:22:40 +0000108 vector<GlobalValue*> OldGlobals(Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000109
110 // Resize the globals vector to be big enough to hold both of them...
111 Globals.resize(Globals.size()+N->Globals.size());
112
113 // Merge the two sorted globals lists together...
114 std::merge(OldGlobals.begin(), OldGlobals.end(),
115 N->Globals.begin(), N->Globals.end(), Globals.begin());
116
117 // Erase duplicate entries from the globals list...
118 Globals.erase(std::unique(Globals.begin(), Globals.end()), Globals.end());
119
120 // Delete the globals from the old node...
121 N->Globals.clear();
122 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000123}
124
125//===----------------------------------------------------------------------===//
126// DSGraph Implementation
127//===----------------------------------------------------------------------===//
128
Chris Lattner0d9bab82002-07-18 00:12:30 +0000129DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000130 std::map<const DSNode*, DSNode*> NodeMap; // ignored
131 RetNode = cloneInto(G, ValueMap, NodeMap, false);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000132}
133
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000134DSGraph::~DSGraph() {
135 FunctionCalls.clear();
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000136 OrigFunctionCalls.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000137 ValueMap.clear();
138 RetNode = 0;
139
140#ifndef NDEBUG
141 // Drop all intra-node references, so that assertions don't fail...
142 std::for_each(Nodes.begin(), Nodes.end(),
143 std::mem_fun(&DSNode::dropAllReferences));
144#endif
145
146 // Delete all of the nodes themselves...
147 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
148}
149
Chris Lattner0d9bab82002-07-18 00:12:30 +0000150// dump - Allow inspection of graph in a debugger.
151void DSGraph::dump() const { print(std::cerr); }
152
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000153
Chris Lattner0d9bab82002-07-18 00:12:30 +0000154// cloneInto - Clone the specified DSGraph into the current graph, returning the
155// Return node of the graph. The translated ValueMap for the old function is
156// filled into the OldValMap member. If StripLocals is set to true, Scalar and
157// Alloca markers are removed from the graph, as the graph is being cloned into
158// a calling function's graph.
159//
160DSNode *DSGraph::cloneInto(const DSGraph &G,
161 std::map<Value*, DSNodeHandle> &OldValMap,
Chris Lattnere2219762002-07-18 18:22:40 +0000162 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner0d9bab82002-07-18 00:12:30 +0000163 bool StripLocals) {
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000164
165 assert(OldNodeMap.size()==0 && "Return argument OldNodeMap should be empty");
166
167 OldNodeMap[0] = 0; // Null pointer maps to null
Chris Lattner0d9bab82002-07-18 00:12:30 +0000168
169 unsigned FN = Nodes.size(); // FirstNode...
170
171 // Duplicate all of the nodes, populating the node map...
172 Nodes.reserve(FN+G.Nodes.size());
173 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
174 DSNode *Old = G.Nodes[i], *New = new DSNode(*Old);
175 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000176 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000177 }
178
179 // Rewrite the links in the nodes to point into the current graph now.
180 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
181 for (unsigned j = 0, e = Nodes[i]->getNumLinks(); j != e; ++j)
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000182 Nodes[i]->setLink(j, OldNodeMap[Nodes[i]->getLink(j)]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000183
184 // If we are inlining this graph into the called function graph, remove local
185 // markers.
186 if (StripLocals)
187 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
188 Nodes[i]->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
189
190 // Copy the value map...
191 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
192 E = G.ValueMap.end(); I != E; ++I)
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000193 OldValMap[I->first] = OldNodeMap[I->second];
Chris Lattner0d9bab82002-07-18 00:12:30 +0000194
Chris Lattnere2219762002-07-18 18:22:40 +0000195 // Copy the function calls list...
196 unsigned FC = FunctionCalls.size(); // FirstCall
197 FunctionCalls.reserve(FC+G.FunctionCalls.size());
198 for (unsigned i = 0, e = G.FunctionCalls.size(); i != e; ++i) {
199 FunctionCalls.push_back(std::vector<DSNodeHandle>());
200 FunctionCalls[FC+i].reserve(G.FunctionCalls[i].size());
201 for (unsigned j = 0, e = G.FunctionCalls[i].size(); j != e; ++j)
202 FunctionCalls[FC+i].push_back(OldNodeMap[G.FunctionCalls[i][j]]);
203 }
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000204
205 // Copy the list of unresolved callers
206 PendingCallers.insert(PendingCallers.end(),
207 G.PendingCallers.begin(), G.PendingCallers.end());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000208
209 // Return the returned node pointer...
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000210 return OldNodeMap[G.RetNode];
Chris Lattner0d9bab82002-07-18 00:12:30 +0000211}
212
213
214// markIncompleteNodes - Mark the specified node as having contents that are not
215// known with the current analysis we have performed. Because a node makes all
216// of the nodes it can reach imcomplete if the node itself is incomplete, we
217// must recursively traverse the data structure graph, marking all reachable
218// nodes as incomplete.
219//
220static void markIncompleteNode(DSNode *N) {
221 // Stop recursion if no node, or if node already marked...
222 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
223
224 // Actually mark the node
225 N->NodeType |= DSNode::Incomplete;
226
227 // Recusively process children...
228 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
229 markIncompleteNode(N->getLink(i));
230}
231
232
233// markIncompleteNodes - Traverse the graph, identifying nodes that may be
234// modified by other functions that have not been resolved yet. This marks
235// nodes that are reachable through three sources of "unknownness":
236//
237// Global Variables, Function Calls, and Incoming Arguments
238//
239// For any node that may have unknown components (because something outside the
240// scope of current analysis may have modified it), the 'Incomplete' flag is
241// added to the NodeType.
242//
243void DSGraph::markIncompleteNodes() {
244 // Mark any incoming arguments as incomplete...
245 for (Function::aiterator I = Func.abegin(), E = Func.aend(); I != E; ++I)
246 if (isa<PointerType>(I->getType()))
247 markIncompleteNode(ValueMap[I]->getLink(0));
248
249 // Mark stuff passed into functions calls as being incomplete...
250 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattnere2219762002-07-18 18:22:40 +0000251 vector<DSNodeHandle> &Args = FunctionCalls[i];
252 // Then the return value is certainly incomplete!
253 markIncompleteNode(Args[0]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000254
255 // The call does not make the function argument incomplete...
256
257 // All arguments to the function call are incomplete though!
258 for (unsigned i = 2, e = Args.size(); i != e; ++i)
259 markIncompleteNode(Args[i]);
260 }
261
Chris Lattner055dc2c2002-07-18 15:54:42 +0000262 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000263 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner055dc2c2002-07-18 15:54:42 +0000264 if (Nodes[i]->NodeType & (DSNode::GlobalNode | DSNode::CastNode)) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000265 DSNode *N = Nodes[i];
266 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
267 markIncompleteNode(N->getLink(i));
268 }
269}
270
271// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
272// checks to see if there are simple transformations that it can do to make it
273// dead.
274//
275bool DSGraph::isNodeDead(DSNode *N) {
276 // Is it a trivially dead shadow node...
277 if (N->getReferrers().empty() && N->NodeType == 0)
278 return true;
279
280 // Is it a function node or some other trivially unused global?
281 if ((N->NodeType & ~DSNode::GlobalNode) == 0 &&
282 N->getNumLinks() == 0 &&
283 N->getReferrers().size() == N->getGlobals().size()) {
284
285 // Remove the globals from the valuemap, so that the referrer count will go
286 // down to zero.
287 while (!N->getGlobals().empty()) {
288 GlobalValue *GV = N->getGlobals().back();
289 N->getGlobals().pop_back();
290 ValueMap.erase(GV);
291 }
292 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
293 return true;
294 }
295
296 return false;
297}
298
299
Chris Lattnere2219762002-07-18 18:22:40 +0000300// removeTriviallyDeadNodes - After the graph has been constructed, this method
301// removes all unreachable nodes that are created because they got merged with
302// other nodes in the graph. These nodes will all be trivially unreachable, so
303// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000304//
Chris Lattnere2219762002-07-18 18:22:40 +0000305void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000306 for (unsigned i = 0; i != Nodes.size(); ++i)
307 if (isNodeDead(Nodes[i])) { // This node is dead!
308 delete Nodes[i]; // Free memory...
309 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
310 }
311
Chris Lattnere2219762002-07-18 18:22:40 +0000312 // Remove trivially identical function calls
Chris Lattner0d9bab82002-07-18 00:12:30 +0000313 unsigned NumFns = FunctionCalls.size();
314 std::sort(FunctionCalls.begin(), FunctionCalls.end());
315 FunctionCalls.erase(std::unique(FunctionCalls.begin(), FunctionCalls.end()),
316 FunctionCalls.end());
317
318 DEBUG(if (NumFns != FunctionCalls.size())
319 std::cerr << "Merged " << (NumFns-FunctionCalls.size())
320 << " call nodes in " << Func.getName() << "\n";);
321}
322
323
Chris Lattnere2219762002-07-18 18:22:40 +0000324// markAlive - Simple graph traverser that recursively walks the graph marking
325// stuff to be alive.
326//
327static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
328 if (N == 0 || Alive.count(N)) return;
329
330 Alive.insert(N);
331 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
332 markAlive(N->getLink(i), Alive);
333}
334
335
336// removeDeadNodes - Use a more powerful reachability analysis to eliminate
337// subgraphs that are unreachable. This often occurs because the data
338// structure doesn't "escape" into it's caller, and thus should be eliminated
339// from the caller's graph entirely. This is only appropriate to use when
340// inlining graphs.
341//
342void DSGraph::removeDeadNodes() {
343 // Reduce the amount of work we have to do...
344 removeTriviallyDeadNodes();
345
346 // FIXME: Merge nontrivially identical call nodes...
347
348 // Alive - a set that holds all nodes found to be reachable/alive.
349 std::set<DSNode*> Alive;
350
351 // Mark all nodes reachable by call nodes as alive...
352 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
353 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
354 markAlive(FunctionCalls[i][j], Alive);
355
356 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
357 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
358 markAlive(OrigFunctionCalls[i][j], Alive);
359
360 // Mark all nodes reachable by scalar, global, or incomplete nodes as
361 // reachable...
362 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
363 if (Nodes[i]->NodeType & (DSNode::ScalarNode | DSNode::GlobalNode))
364 markAlive(Nodes[i], Alive);
365
366 // Loop over all unreachable nodes, dropping their references...
367 std::vector<DSNode*> DeadNodes;
368 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
369 for (unsigned i = 0; i != Nodes.size(); ++i)
370 if (!Alive.count(Nodes[i])) {
371 DSNode *N = Nodes[i];
372 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
373 DeadNodes.push_back(N); // Add node to our list of dead nodes
374 N->dropAllReferences(); // Drop all outgoing edges
375 }
376
377 // The return value is alive as well...
378 markAlive(RetNode, Alive);
379
380 // Delete all dead nodes...
381 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
382}
383
384
385
Chris Lattner0d9bab82002-07-18 00:12:30 +0000386// maskNodeTypes - Apply a mask to all of the node types in the graph. This
387// is useful for clearing out markers like Scalar or Incomplete.
388//
389void DSGraph::maskNodeTypes(unsigned char Mask) {
390 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
391 Nodes[i]->NodeType &= Mask;
392}
393
394
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000395//===----------------------------------------------------------------------===//
396// LocalDataStructures Implementation
397//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000398
399// releaseMemory - If the pass pipeline is done with this pass, we can release
400// our memory... here...
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000401//
402void LocalDataStructures::releaseMemory() {
403 for (std::map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
404 E = DSInfo.end(); I != E; ++I)
405 delete I->second;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000406
407 // Empty map so next time memory is released, data structures are not
408 // re-deleted.
409 DSInfo.clear();
410}
411
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000412bool LocalDataStructures::run(Module &M) {
413 // Calculate all of the graphs...
414 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000415 if (!I->isExternal())
416 DSInfo.insert(std::make_pair(&*I, new DSGraph(*I)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000417
418 return false;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000419}