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