* Standardize how analysis results/passes as printed with the print() virtual
[oota-llvm.git] / lib / Analysis / DataStructure / DataStructure.cpp
1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
2 //
3 // This file implements the core data structure functionality.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Module.h"
8 #include "llvm/DerivedTypes.h"
9 #include "Support/STLExtras.h"
10 #include "Support/StatisticReporter.h"
11 #include "Support/STLExtras.h"
12 #include <algorithm>
13 #include <set>
14 #include "llvm/Analysis/DataStructure.h"
15
16 using std::vector;
17
18 //===----------------------------------------------------------------------===//
19 // DSNode Implementation
20 //===----------------------------------------------------------------------===//
21
22 DSNode::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
34 // DSNode copy constructor... do not copy over the referrers list!
35 DSNode::DSNode(const DSNode &N)
36   : Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
37 }
38
39 void DSNode::removeReferrer(DSNodeHandle *H) {
40   // Search backwards, because we depopulate the list from the back for
41   // efficiency (because it's a vector).
42   vector<DSNodeHandle*>::reverse_iterator I =
43     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
48 // 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 //
51 void DSNode::addGlobal(GlobalValue *GV) {
52   // Keep the list sorted.
53   vector<GlobalValue*>::iterator I =
54     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   }
61 }
62
63
64 // addEdgeTo - Add an edge from the current node to the specified node.  This
65 // can cause merging of nodes in the graph.
66 //
67 void 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 //
84 void 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
101   // Merge the node types
102   NodeType |= N->NodeType;
103   N->NodeType = 0;   // N is now a dead node.
104
105   // Merge the globals list...
106   if (!N->Globals.empty()) {
107     // Save the current globals off to the side...
108     vector<GlobalValue*> OldGlobals(Globals);
109
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   }
123 }
124
125 //===----------------------------------------------------------------------===//
126 // DSGraph Implementation
127 //===----------------------------------------------------------------------===//
128
129 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
130   std::map<const DSNode*, DSNode*> NodeMap; // ignored
131   RetNode = cloneInto(G, ValueMap, NodeMap, false);
132 }
133
134 DSGraph::~DSGraph() {
135   FunctionCalls.clear();
136   OrigFunctionCalls.clear();
137   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
150 // dump - Allow inspection of graph in a debugger.
151 void DSGraph::dump() const { print(std::cerr); }
152
153
154 // 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 //
160 DSNode *DSGraph::cloneInto(const DSGraph &G, 
161                            std::map<Value*, DSNodeHandle> &OldValMap,
162                            std::map<const DSNode*, DSNode*> &OldNodeMap,
163                            bool StripLocals) {
164
165   assert(OldNodeMap.size()==0 && "Return argument OldNodeMap should be empty");
166
167   OldNodeMap[0] = 0;  // Null pointer maps to null
168
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);
176     OldNodeMap[Old] = New;
177   }
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)
182       Nodes[i]->setLink(j, OldNodeMap[Nodes[i]->getLink(j)]);
183
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)
193     OldValMap[I->first] = OldNodeMap[I->second];
194
195   // 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   }
204
205   // Copy the list of unresolved callers
206   PendingCallers.insert(PendingCallers.end(),
207                         G.PendingCallers.begin(), G.PendingCallers.end());
208
209   // Return the returned node pointer...
210   return OldNodeMap[G.RetNode];
211 }
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 //
220 static 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 //
243 void 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) {
251     vector<DSNodeHandle> &Args = FunctionCalls[i];
252     // Then the return value is certainly incomplete!
253     markIncompleteNode(Args[0]);
254
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
262   // Mark all of the nodes pointed to by global or cast nodes as incomplete...
263   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
264     if (Nodes[i]->NodeType & (DSNode::GlobalNode | DSNode::CastNode)) {
265       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 //
275 bool 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
300 // 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.
304 //
305 void DSGraph::removeTriviallyDeadNodes() {
306   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
312   // Remove trivially identical function calls
313   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
324 // markAlive - Simple graph traverser that recursively walks the graph marking
325 // stuff to be alive.
326 //
327 static 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 //
342 void 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
386 // 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 //
389 void DSGraph::maskNodeTypes(unsigned char Mask) {
390   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
391     Nodes[i]->NodeType &= Mask;
392 }
393
394
395 //===----------------------------------------------------------------------===//
396 // LocalDataStructures Implementation
397 //===----------------------------------------------------------------------===//
398
399 // releaseMemory - If the pass pipeline is done with this pass, we can release
400 // our memory... here...
401 //
402 void LocalDataStructures::releaseMemory() {
403   for (std::map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
404          E = DSInfo.end(); I != E; ++I)
405     delete I->second;
406
407   // Empty map so next time memory is released, data structures are not
408   // re-deleted.
409   DSInfo.clear();
410 }
411
412 bool LocalDataStructures::run(Module &M) {
413   // Calculate all of the graphs...
414   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
415     if (!I->isExternal())
416       DSInfo.insert(std::make_pair(&*I, new DSGraph(*I)));
417
418   return false;
419 }