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