Rename ValueMap to ScalarMap
[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/Analysis/DSGraph.h"
8 #include "llvm/Function.h"
9 #include "llvm/iOther.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/Target/TargetData.h"
12 #include "Support/STLExtras.h"
13 #include "Support/Statistic.h"
14 #include <algorithm>
15 #include <set>
16
17 using std::vector;
18
19 namespace DataStructureAnalysis {   // TODO: FIXME
20   // isPointerType - Return true if this first class type is big enough to hold
21   // a pointer.
22   //
23   bool isPointerType(const Type *Ty);
24   extern TargetData TD;
25 }
26 using namespace DataStructureAnalysis;
27
28 //===----------------------------------------------------------------------===//
29 // DSNode Implementation
30 //===----------------------------------------------------------------------===//
31
32 DSNode::DSNode(enum NodeTy NT, const Type *T) : NodeType(NT) {
33   // Add the type entry if it is specified...
34   if (T) getTypeRec(T, 0);
35 }
36
37 // DSNode copy constructor... do not copy over the referrers list!
38 DSNode::DSNode(const DSNode &N)
39   : Links(N.Links), MergeMap(N.MergeMap),
40     TypeEntries(N.TypeEntries), Globals(N.Globals), NodeType(N.NodeType) {
41 }
42
43 void DSNode::removeReferrer(DSNodeHandle *H) {
44   // Search backwards, because we depopulate the list from the back for
45   // efficiency (because it's a vector).
46   vector<DSNodeHandle*>::reverse_iterator I =
47     std::find(Referrers.rbegin(), Referrers.rend(), H);
48   assert(I != Referrers.rend() && "Referrer not pointing to node!");
49   Referrers.erase(I.base()-1);
50 }
51
52 // addGlobal - Add an entry for a global value to the Globals list.  This also
53 // marks the node with the 'G' flag if it does not already have it.
54 //
55 void DSNode::addGlobal(GlobalValue *GV) {
56   // Keep the list sorted.
57   vector<GlobalValue*>::iterator I =
58     std::lower_bound(Globals.begin(), Globals.end(), GV);
59
60   if (I == Globals.end() || *I != GV) {
61     //assert(GV->getType()->getElementType() == Ty);
62     Globals.insert(I, GV);
63     NodeType |= GlobalNode;
64   }
65 }
66
67 /// foldNodeCompletely - If we determine that this node has some funny
68 /// behavior happening to it that we cannot represent, we fold it down to a
69 /// single, completely pessimistic, node.  This node is represented as a
70 /// single byte with a single TypeEntry of "void".
71 ///
72 void DSNode::foldNodeCompletely() {
73   // We are no longer typed at all...
74   TypeEntries.clear();
75   TypeEntries.push_back(DSTypeRec(Type::VoidTy, 0));
76
77   // Loop over all of our referrers, making them point to our one byte of space.
78   for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
79        I != E; ++I)
80     (*I)->setOffset(0);
81
82   // Fold the MergeMap down to a single byte of space...
83   MergeMap.resize(1);
84   MergeMap[0] = -1;
85
86   // If we have links, merge all of our outgoing links together...
87   if (!Links.empty()) {
88     MergeMap[0] = 0;      // We now contain an outgoing edge...
89     for (unsigned i = 1, e = Links.size(); i != e; ++i)
90       Links[0].mergeWith(Links[i]);
91     Links.resize(1);
92   }
93 }
94
95 /// isNodeCompletelyFolded - Return true if this node has been completely
96 /// folded down to something that can never be expanded, effectively losing
97 /// all of the field sensitivity that may be present in the node.
98 ///
99 bool DSNode::isNodeCompletelyFolded() const {
100   return getSize() == 1 && TypeEntries.size() == 1 &&
101          TypeEntries[0].Ty == Type::VoidTy;
102 }
103
104
105
106 /// setLink - Set the link at the specified offset to the specified
107 /// NodeHandle, replacing what was there.  It is uncommon to use this method,
108 /// instead one of the higher level methods should be used, below.
109 ///
110 void DSNode::setLink(unsigned i, const DSNodeHandle &NH) {
111   // Create a new entry in the Links vector to hold a new element for offset.
112   if (!hasLink(i)) {
113     signed char NewIdx = Links.size();
114     // Check to see if we allocate more than 128 distinct links for this node.
115     // If so, just merge with the last one.  This really shouldn't ever happen,
116     // but it should work regardless of whether it does or not.
117     //
118     if (NewIdx >= 0) {
119       Links.push_back(NH);             // Allocate space: common case
120     } else {                           // Wrap around?  Too many links?
121       NewIdx--;                        // Merge with whatever happened last
122       assert(NewIdx > 0 && "Should wrap back around");
123       std::cerr << "\n*** DSNode found that requires more than 128 "
124                 << "active links at once!\n\n";
125     } 
126
127     signed char OldIdx = MergeMap[i];
128     assert (OldIdx < 0 && "Shouldn't contain link!");
129
130     // Make sure that anything aliasing this field gets updated to point to the
131     // new link field.
132     rewriteMergeMap(OldIdx, NewIdx);
133     assert(MergeMap[i] == NewIdx && "Field not replaced!");
134   } else {
135     Links[MergeMap[i]] = NH;
136   }
137 }
138
139 // addEdgeTo - Add an edge from the current node to the specified node.  This
140 // can cause merging of nodes in the graph.
141 //
142 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
143   assert(Offset < getSize() && "Offset out of range!");
144   if (NH.getNode() == 0) return;       // Nothing to do
145
146   if (DSNodeHandle *ExistingNH = getLink(Offset)) {
147     // Merge the two nodes...
148     ExistingNH->mergeWith(NH);
149   } else {                             // No merging to perform...
150     setLink(Offset, NH);               // Just force a link in there...
151   }
152 }
153
154 /// getTypeRec - This method returns the specified type record if it exists.
155 /// If it does not yet exist, the method checks to see whether or not the
156 /// request would result in an untrackable state.  If adding it would cause
157 /// untrackable state, we foldNodeCompletely the node and return the void
158 /// record, otherwise we add an new TypeEntry and return it.
159 ///
160 DSTypeRec &DSNode::getTypeRec(const Type *Ty, unsigned Offset) {
161   // If the node is already collapsed, we can't do anything... bail out early
162   if (isNodeCompletelyFolded()) {
163     assert(TypeEntries.size() == 1 && "Node folded and Entries.size() != 1?");
164     return TypeEntries[0];
165   }
166
167   // First search to see if we already have a record for this...
168   DSTypeRec SearchFor(Ty, Offset);
169
170   std::vector<DSTypeRec>::iterator I;
171   if (TypeEntries.size() < 5) {  // Linear search if we have few entries.
172     I = TypeEntries.begin();
173     while (I != TypeEntries.end() && *I < SearchFor)
174       ++I;
175   } else {
176     I = std::lower_bound(TypeEntries.begin(), TypeEntries.end(), SearchFor);
177   }
178   
179   // At this point, I either points to the right entry or it points to the entry
180   // we are to insert the new entry in front of...
181   //
182   if (I != TypeEntries.end() && *I == SearchFor)
183     return *I;
184   
185   // ASSUME that it's okay to add this type entry.
186   // FIXME: This should check to make sure it's ok.
187   
188   // If the data size is different then our current size, try to resize the node
189   unsigned ReqSize = Ty->isSized() ? TD.getTypeSize(Ty) : 0;
190   if (getSize() < ReqSize) {
191     // If we are trying to make it bigger, and we can grow the node, do so.
192     if (growNode(ReqSize)) {
193       assert(isNodeCompletelyFolded() && "Node isn't folded?");
194       return TypeEntries[0];
195     }
196
197   } else if (getSize() > ReqSize) {
198     // If we are trying to make the node smaller, we don't have to do anything.
199
200   }
201
202   return *TypeEntries.insert(I, SearchFor);
203 }
204
205 /// growNode - Attempt to grow the node to the specified size.  This may do one
206 /// of three things:
207 ///   1. Grow the node, return false
208 ///   2. Refuse to grow the node, but maintain a trackable situation, return
209 ///      false.
210 ///   3. Be unable to track if node was that size, so collapse the node and
211 ///      return true.
212 ///
213 bool DSNode::growNode(unsigned ReqSize) {
214   unsigned OldSize = getSize();
215
216   if (0) {
217     // FIXME: DSNode::growNode() doesn't perform correct safety checks yet!
218     
219     foldNodeCompletely();
220     return true;
221   }
222
223   assert(ReqSize > OldSize && "Not growing node!");
224
225   // Resize the merge map to have enough space...
226   MergeMap.resize(ReqSize);
227
228   // Assign unique values to all of the elements of MergeMap
229   if (ReqSize < 128) {
230     // Handle the common case of reasonable size structures...
231     for (unsigned i = OldSize; i != ReqSize; ++i)
232       MergeMap[i] = -1-i;   // Assign -1, -2, -3, ...
233   } else {
234     // It's possible that we have something really big here.  In this case,
235     // divide the object into chunks until it will fit into 128 elements.
236     unsigned Multiple = ReqSize/128;
237     
238     // It's probably an array, and probably some power of two in size.
239     // Because of this, find the biggest power of two that is bigger than
240     // multiple to use as our real Multiple.
241     unsigned RealMultiple = 2;
242     while (RealMultiple <= Multiple) RealMultiple <<= 1;
243     
244     unsigned RealBound = ReqSize/RealMultiple;
245     assert(RealBound <= 128 && "Math didn't work out right");
246     
247     // Now go through and assign indexes that are between -1 and -128
248     // inclusive
249     //
250     for (unsigned i = OldSize; i != ReqSize; ++i)
251       MergeMap[i] = -1-(i % RealBound);   // Assign -1, -2, -3...
252   }
253   return false;
254 }
255
256 /// mergeMappedValues - This is the higher level form of rewriteMergeMap.  It is
257 /// fully capable of merging links together if neccesary as well as simply
258 /// rewriting the map entries.
259 ///
260 void DSNode::mergeMappedValues(signed char V1, signed char V2) {
261   assert(V1 != V2 && "Cannot merge two identical mapped values!");
262   
263   if (V1 < 0) {  // If there is no outgoing link from V1, merge it with V2
264     if (V2 < 0 && V1 > V2)
265        // If both are not linked, merge to the field closer to 0
266       rewriteMergeMap(V2, V1);
267     else
268       rewriteMergeMap(V1, V2);
269   } else if (V2 < 0) {           // Is V2 < 0 && V1 >= 0?
270     rewriteMergeMap(V2, V1);     // Merge into the one with the link...
271   } else {                       // Otherwise, links exist at both locations
272     // Merge Links[V1] with Links[V2] so they point to the same place now...
273     Links[V1].mergeWith(Links[V2]);
274
275     // Merge the V2 link into V1 so that we reduce the overall value of the
276     // links are reduced...
277     //
278     if (V2 < V1) std::swap(V1, V2);     // Ensure V1 < V2
279     rewriteMergeMap(V2, V1);            // After this, V2 is "dead"
280
281     // Change the user of the last link to use V2 instead
282     if ((unsigned)V2 != Links.size()-1) {
283       rewriteMergeMap(Links.size()-1, V2);  // Point to V2 instead of last el...
284       // Make sure V2 points the right DSNode
285       Links[V2] = Links.back();
286     }
287
288     // Reduce the number of distinct outgoing links...
289     Links.pop_back();
290   }
291 }
292
293
294 // MergeSortedVectors - Efficiently merge a vector into another vector where
295 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
296 // efficiently copyable and have sane comparison semantics.
297 //
298 template<typename T>
299 void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
300   // By far, the most common cases will be the simple ones.  In these cases,
301   // avoid having to allocate a temporary vector...
302   //
303   if (Src.empty()) {             // Nothing to merge in...
304     return;
305   } else if (Dest.empty()) {     // Just copy the result in...
306     Dest = Src;
307   } else if (Src.size() == 1) {  // Insert a single element...
308     const T &V = Src[0];
309     typename vector<T>::iterator I =
310       std::lower_bound(Dest.begin(), Dest.end(), V);
311     if (I == Dest.end() || *I != Src[0])  // If not already contained...
312       Dest.insert(I, Src[0]);
313   } else if (Dest.size() == 1) {
314     T Tmp = Dest[0];                      // Save value in temporary...
315     Dest = Src;                           // Copy over list...
316     typename vector<T>::iterator I =
317       std::lower_bound(Dest.begin(), Dest.end(),Tmp);
318     if (I == Dest.end() || *I != Src[0])  // If not already contained...
319       Dest.insert(I, Src[0]);
320
321   } else {
322     // Make a copy to the side of Dest...
323     vector<T> Old(Dest);
324     
325     // Make space for all of the type entries now...
326     Dest.resize(Dest.size()+Src.size());
327     
328     // Merge the two sorted ranges together... into Dest.
329     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
330     
331     // Now erase any duplicate entries that may have accumulated into the 
332     // vectors (because they were in both of the input sets)
333     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
334   }
335 }
336
337
338 // mergeWith - Merge this node and the specified node, moving all links to and
339 // from the argument node into the current node, deleting the node argument.
340 // Offset indicates what offset the specified node is to be merged into the
341 // current node.
342 //
343 // The specified node may be a null pointer (in which case, nothing happens).
344 //
345 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
346   DSNode *N = NH.getNode();
347   if (N == 0 || (N == this && NH.getOffset() == Offset))
348     return;  // Noop
349
350   assert(NH.getNode() != this &&
351          "Cannot merge two portions of the same node yet!");
352
353   // If we are merging a node with a completely folded node, then both nodes are
354   // now completely folded.
355   //
356   if (isNodeCompletelyFolded()) {
357     N->foldNodeCompletely();
358   } else if (NH.getNode()->isNodeCompletelyFolded()) {
359     foldNodeCompletely();
360     Offset = 0;
361   }
362
363   // If both nodes are not at offset 0, make sure that we are merging the node
364   // at an later offset into the node with the zero offset.
365   //
366   if (Offset > NH.getOffset()) {
367     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
368     return;
369   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
370     // If the offsets are the same, merge the smaller node into the bigger node
371     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
372     return;
373   }
374
375 #if 0
376   std::cerr << "\n\nMerging:\n";
377   N->print(std::cerr, 0);
378   std::cerr << " and:\n";
379   print(std::cerr, 0);
380 #endif
381
382   // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
383   // respect to NH.Offset) is now zero.
384   //
385   unsigned NOffset = NH.getOffset()-Offset;
386
387   // If our destination node is too small... try to grow it.
388   if (N->getSize()+NOffset > getSize() &&
389       growNode(N->getSize()+NOffset)) {
390     // Catastrophic failure occured and we had to collapse the node.  In this
391     // case, collapse the other node as well.
392     N->foldNodeCompletely();
393     NOffset = 0;
394   }
395   unsigned NSize = N->getSize();
396
397   // Remove all edges pointing at N, causing them to point to 'this' instead.
398   // Make sure to adjust their offset, not just the node pointer.
399   //
400   while (!N->Referrers.empty()) {
401     DSNodeHandle &Ref = *N->Referrers.back();
402     Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
403   }
404
405   // We must merge fields in this node due to nodes merged in the source node.
406   // In order to handle this we build a map that converts from the source node's
407   // MergeMap values to our MergeMap values.  This map is indexed by the
408   // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
409   // 2*SourceNodeSize elements of space for the mapping.  We can do this because
410   // we know that there are at most SourceNodeSize outgoing links in the node
411   // (thus that many positive values) and at most SourceNodeSize distinct fields
412   // (thus that many negative values).
413   //
414   std::vector<signed char> MergeMapMap(NSize*2, 127);
415
416   // Loop through the structures, merging them together...
417   for (unsigned i = 0, e = NSize; i != e; ++i) {
418     // Get what this byte of N maps to...
419     signed char NElement = N->MergeMap[i];
420
421     // Get what we map this byte to...
422     signed char Element = MergeMap[i+NOffset];
423     // We use 127 as a sentinal and don't check for it's existence yet...
424     assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
425
426     signed char CurMappedVal = MergeMapMap[NElement+NSize];
427     if (CurMappedVal == 127) {               // Haven't seen this NElement yet?
428       MergeMapMap[NElement+NSize] = Element; // Map the two together...
429     } else if (CurMappedVal != Element) {
430       // If we are mapping two different fields together this means that we need
431       // to merge fields in the current node due to merging in the source node.
432       //
433       mergeMappedValues(CurMappedVal, Element);
434       MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
435     }
436   }
437
438   // Make all of the outgoing links of N now be outgoing links of this.  This
439   // can cause recursive merging!
440   //
441   for (unsigned i = 0, e = NSize; i != e; ++i)
442     if (DSNodeHandle *Link = N->getLink(i)) {
443       addEdgeTo(i+NOffset, *Link);
444       N->MergeMap[i] = -1;  // Kill outgoing edge
445     }
446
447   // Now that there are no outgoing edges, all of the Links are dead.
448   N->Links.clear();
449
450   // Merge the node types
451   NodeType |= N->NodeType;
452   N->NodeType = 0;   // N is now a dead node.
453
454   // Adjust all of the type entries we are merging in by the offset...
455   //
456   if (NOffset != 0) {  // This case is common enough to optimize for
457     // Offset all of the TypeEntries in N with their new offset
458     for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
459       N->TypeEntries[i].Offset += NOffset;
460   }
461
462   // ... now add them to the TypeEntries list.
463   MergeSortedVectors(TypeEntries, N->TypeEntries);
464   N->TypeEntries.clear();   // N is dead, no type-entries need exist
465
466   // Merge the globals list...
467   if (!N->Globals.empty()) {
468     MergeSortedVectors(Globals, N->Globals);
469
470     // Delete the globals from the old node...
471     N->Globals.clear();
472   }
473 }
474
475 //===----------------------------------------------------------------------===//
476 // DSCallSite Implementation
477 //===----------------------------------------------------------------------===//
478
479 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
480 Function &DSCallSite::getCaller() const {
481   return *Inst->getParent()->getParent();
482 }
483
484
485 //===----------------------------------------------------------------------===//
486 // DSGraph Implementation
487 //===----------------------------------------------------------------------===//
488
489 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
490   std::map<const DSNode*, DSNode*> NodeMap;
491   RetNode = cloneInto(G, ScalarMap, NodeMap);
492 }
493
494 DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
495   : Func(G.Func) {
496   RetNode = cloneInto(G, ScalarMap, NodeMap);
497 }
498
499 DSGraph::~DSGraph() {
500   FunctionCalls.clear();
501   ScalarMap.clear();
502   RetNode.setNode(0);
503
504 #ifndef NDEBUG
505   // Drop all intra-node references, so that assertions don't fail...
506   std::for_each(Nodes.begin(), Nodes.end(),
507                 std::mem_fun(&DSNode::dropAllReferences));
508 #endif
509
510   // Delete all of the nodes themselves...
511   std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
512 }
513
514 // dump - Allow inspection of graph in a debugger.
515 void DSGraph::dump() const { print(std::cerr); }
516
517
518 // Helper function used to clone a function list.
519 // 
520 static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
521                                   vector<DSCallSite> &toCalls,
522                                   std::map<const DSNode*, DSNode*> &NodeMap) {
523   unsigned FC = toCalls.size();  // FirstCall
524   toCalls.reserve(FC+fromCalls.size());
525   for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
526     toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
527 }
528
529 /// remapLinks - Change all of the Links in the current node according to the
530 /// specified mapping.
531 ///
532 void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
533   for (unsigned i = 0, e = Links.size(); i != e; ++i) 
534     Links[i].setNode(OldNodeMap[Links[i].getNode()]);
535 }
536
537
538 // cloneInto - Clone the specified DSGraph into the current graph, returning the
539 // Return node of the graph.  The translated ScalarMap for the old function is
540 // filled into the OldValMap member.  If StripAllocas is set to true, Alloca
541 // markers are removed from the graph, as the graph is being cloned into a
542 // calling function's graph.
543 //
544 DSNodeHandle DSGraph::cloneInto(const DSGraph &G, 
545                                 std::map<Value*, DSNodeHandle> &OldValMap,
546                                 std::map<const DSNode*, DSNode*> &OldNodeMap,
547                                 bool StripScalars,  // FIXME: Kill StripScalars
548                                 bool StripAllocas) {
549   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
550
551   unsigned FN = Nodes.size();           // First new node...
552
553   // Duplicate all of the nodes, populating the node map...
554   Nodes.reserve(FN+G.Nodes.size());
555   for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
556     DSNode *Old = G.Nodes[i];
557     DSNode *New = new DSNode(*Old);
558     Nodes.push_back(New);
559     OldNodeMap[Old] = New;
560   }
561
562   // Rewrite the links in the new nodes to point into the current graph now.
563   for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
564     Nodes[i]->remapLinks(OldNodeMap);
565
566   // Remove local markers as specified
567   unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
568   if (StripBits)
569     for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
570       Nodes[i]->NodeType &= ~StripBits;
571
572   // Copy the value map... and merge all of the global nodes...
573   for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
574          E = G.ScalarMap.end(); I != E; ++I) {
575     DSNodeHandle &H = OldValMap[I->first];
576     H.setNode(OldNodeMap[I->second.getNode()]);
577     H.setOffset(I->second.getOffset());
578
579     if (isa<GlobalValue>(I->first)) {  // Is this a global?
580       std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
581       if (GVI != ScalarMap.end()) {   // Is the global value in this fn already?
582         GVI->second.mergeWith(H);
583       } else {
584         ScalarMap[I->first] = H;      // Add global pointer to this graph
585       }
586     }
587   }
588   // Copy the function calls list...
589   CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
590
591
592   // Return the returned node pointer...
593   return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
594 }
595
596 #if 0
597 // cloneGlobalInto - Clone the given global node and all its target links
598 // (and all their llinks, recursively).
599 // 
600 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
601   if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
602
603   // If a clone has already been created for GNode, return it.
604   DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
605   if (ValMapEntry != 0)
606     return ValMapEntry;
607
608   // Clone the node and update the ValMap.
609   DSNode* NewNode = new DSNode(*GNode);
610   ValMapEntry = NewNode;                // j=0 case of loop below!
611   Nodes.push_back(NewNode);
612   for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
613     ScalarMap[NewNode->getGlobals()[j]] = NewNode;
614
615   // Rewrite the links in the new node to point into the current graph.
616   for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
617     NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
618
619   return NewNode;
620 }
621 #endif
622
623
624 // markIncompleteNodes - Mark the specified node as having contents that are not
625 // known with the current analysis we have performed.  Because a node makes all
626 // of the nodes it can reach imcomplete if the node itself is incomplete, we
627 // must recursively traverse the data structure graph, marking all reachable
628 // nodes as incomplete.
629 //
630 static void markIncompleteNode(DSNode *N) {
631   // Stop recursion if no node, or if node already marked...
632   if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
633
634   // Actually mark the node
635   N->NodeType |= DSNode::Incomplete;
636
637   // Recusively process children...
638   for (unsigned i = 0, e = N->getSize(); i != e; ++i)
639     if (DSNodeHandle *DSNH = N->getLink(i))
640       markIncompleteNode(DSNH->getNode());
641 }
642
643
644 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
645 // modified by other functions that have not been resolved yet.  This marks
646 // nodes that are reachable through three sources of "unknownness":
647 //
648 //  Global Variables, Function Calls, and Incoming Arguments
649 //
650 // For any node that may have unknown components (because something outside the
651 // scope of current analysis may have modified it), the 'Incomplete' flag is
652 // added to the NodeType.
653 //
654 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
655   // Mark any incoming arguments as incomplete...
656   if (markFormalArgs && Func)
657     for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
658       if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
659         markIncompleteNode(ScalarMap[I].getNode());
660
661   // Mark stuff passed into functions calls as being incomplete...
662   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
663     DSCallSite &Call = FunctionCalls[i];
664     // Then the return value is certainly incomplete!
665     markIncompleteNode(Call.getRetVal().getNode());
666
667     // All objects pointed to by function arguments are incomplete though!
668     for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
669       markIncompleteNode(Call.getPtrArg(i).getNode());
670   }
671
672   // Mark all of the nodes pointed to by global nodes as incomplete...
673   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
674     if (Nodes[i]->NodeType & DSNode::GlobalNode) {
675       DSNode *N = Nodes[i];
676       // FIXME: Make more efficient by looking over Links directly
677       for (unsigned i = 0, e = N->getSize(); i != e; ++i)
678         if (DSNodeHandle *DSNH = N->getLink(i))
679           markIncompleteNode(DSNH->getNode());
680     }
681 }
682
683 // removeRefsToGlobal - Helper function that removes globals from the
684 // ScalarMap so that the referrer count will go down to zero.
685 static void removeRefsToGlobal(DSNode* N,
686                                std::map<Value*, DSNodeHandle> &ScalarMap) {
687   while (!N->getGlobals().empty()) {
688     GlobalValue *GV = N->getGlobals().back();
689     N->getGlobals().pop_back();      
690     ScalarMap.erase(GV);
691   }
692 }
693
694
695 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
696 // checks to see if there are simple transformations that it can do to make it
697 // dead.
698 //
699 bool DSGraph::isNodeDead(DSNode *N) {
700   // Is it a trivially dead shadow node...
701   if (N->getReferrers().empty() && N->NodeType == 0)
702     return true;
703
704   // Is it a function node or some other trivially unused global?
705   if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
706       N->getReferrers().size() == N->getGlobals().size()) {
707
708     // Remove the globals from the ScalarMap, so that the referrer count will go
709     // down to zero.
710     removeRefsToGlobal(N, ScalarMap);
711     assert(N->getReferrers().empty() && "Referrers should all be gone now!");
712     return true;
713   }
714
715   return false;
716 }
717
718 static void removeIdenticalCalls(vector<DSCallSite> &Calls,
719                                  const std::string &where) {
720   // Remove trivially identical function calls
721   unsigned NumFns = Calls.size();
722   std::sort(Calls.begin(), Calls.end());
723   Calls.erase(std::unique(Calls.begin(), Calls.end()),
724               Calls.end());
725
726   DEBUG(if (NumFns != Calls.size())
727           std::cerr << "Merged " << (NumFns-Calls.size())
728                     << " call nodes in " << where << "\n";);
729 }
730
731 // removeTriviallyDeadNodes - After the graph has been constructed, this method
732 // removes all unreachable nodes that are created because they got merged with
733 // other nodes in the graph.  These nodes will all be trivially unreachable, so
734 // we don't have to perform any non-trivial analysis here.
735 //
736 void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
737   for (unsigned i = 0; i != Nodes.size(); ++i)
738     if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
739       if (isNodeDead(Nodes[i])) {               // This node is dead!
740         delete Nodes[i];                        // Free memory...
741         Nodes.erase(Nodes.begin()+i--);         // Remove from node list...
742       }
743
744   removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
745 }
746
747
748 // markAlive - Simple graph walker that recursively traverses the graph, marking
749 // stuff to be alive.
750 //
751 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
752   if (N == 0) return;
753
754   Alive.insert(N);
755   // FIXME: Make more efficient by looking over Links directly
756   for (unsigned i = 0, e = N->getSize(); i != e; ++i)
757     if (DSNodeHandle *DSNH = N->getLink(i))
758       if (!Alive.count(DSNH->getNode()))
759         markAlive(DSNH->getNode(), Alive);
760 }
761
762 static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
763                              std::set<DSNode*> &Visiting) {
764   if (N == 0) return false;
765
766   if (Visiting.count(N)) return false; // terminate recursion on a cycle
767   Visiting.insert(N);
768
769   // If any immediate successor is alive, N is alive
770   for (unsigned i = 0, e = N->getSize(); i != e; ++i)
771     if (DSNodeHandle *DSNH = N->getLink(i))
772       if (Alive.count(DSNH->getNode())) {
773         Visiting.erase(N);
774         return true;
775       }
776
777   // Else if any successor reaches a live node, N is alive
778   for (unsigned i = 0, e = N->getSize(); i != e; ++i)
779     if (DSNodeHandle *DSNH = N->getLink(i))
780       if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
781         Visiting.erase(N); return true;
782       }
783
784   Visiting.erase(N);
785   return false;
786 }
787
788
789 // markGlobalsIteration - Recursive helper function for markGlobalsAlive().
790 // This would be unnecessary if function calls were real nodes!  In that case,
791 // the simple iterative loop in the first few lines below suffice.
792 // 
793 static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
794                                  vector<DSCallSite> &Calls,
795                                  std::set<DSNode*> &Alive,
796                                  bool FilterCalls) {
797
798   // Iterate, marking globals or cast nodes alive until no new live nodes
799   // are added to Alive
800   std::set<DSNode*> Visiting;           // Used to identify cycles 
801   std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
802   for (size_t liveCount = 0; liveCount < Alive.size(); ) {
803     liveCount = Alive.size();
804     for ( ; I != E; ++I)
805       if (Alive.count(*I) == 0) {
806         Visiting.clear();
807         if (checkGlobalAlive(*I, Alive, Visiting))
808           markAlive(*I, Alive);
809       }
810   }
811
812   // Find function calls with some dead and some live nodes.
813   // Since all call nodes must be live if any one is live, we have to mark
814   // all nodes of the call as live and continue the iteration (via recursion).
815   if (FilterCalls) {
816     bool Recurse = false;
817     for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
818       bool CallIsDead = true, CallHasDeadArg = false;
819       DSCallSite &CS = Calls[i];
820       for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
821         if (DSNode *N = CS.getPtrArg(j).getNode()) {
822           bool ArgIsDead  = !Alive.count(N);
823           CallHasDeadArg |= ArgIsDead;
824           CallIsDead     &= ArgIsDead;
825         }
826
827       if (DSNode *N = CS.getRetVal().getNode()) {
828         bool RetIsDead  = !Alive.count(N);
829         CallHasDeadArg |= RetIsDead;
830         CallIsDead     &= RetIsDead;
831       }
832
833       DSNode *N = CS.getCallee().getNode();
834       bool FnIsDead  = !Alive.count(N);
835       CallHasDeadArg |= FnIsDead;
836       CallIsDead     &= FnIsDead;
837
838       if (!CallIsDead && CallHasDeadArg) {
839         // Some node in this call is live and another is dead.
840         // Mark all nodes of call as live and iterate once more.
841         Recurse = true;
842         for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
843           markAlive(CS.getPtrArg(j).getNode(), Alive);
844         markAlive(CS.getRetVal().getNode(), Alive);
845         markAlive(CS.getCallee().getNode(), Alive);
846       }
847     }
848     if (Recurse)
849       markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
850   }
851 }
852
853
854 // markGlobalsAlive - Mark global nodes and cast nodes alive if they
855 // can reach any other live node.  Since this can produce new live nodes,
856 // we use a simple iterative algorithm.
857 // 
858 static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
859                              bool FilterCalls) {
860   // Add global and cast nodes to a set so we don't walk all nodes every time
861   std::set<DSNode*> GlobalNodes;
862   for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
863     if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
864       GlobalNodes.insert(G.getNodes()[i]);
865
866   // Add all call nodes to the same set
867   vector<DSCallSite> &Calls = G.getFunctionCalls();
868   if (FilterCalls) {
869     for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
870       for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
871         if (DSNode *N = Calls[i].getPtrArg(j).getNode())
872           GlobalNodes.insert(N);
873       if (DSNode *N = Calls[i].getRetVal().getNode())
874         GlobalNodes.insert(N);
875       if (DSNode *N = Calls[i].getCallee().getNode())
876         GlobalNodes.insert(N);
877     }
878   }
879
880   // Iterate and recurse until no new live node are discovered.
881   // This would be a simple iterative loop if function calls were real nodes!
882   markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
883
884   // Free up references to dead globals from the ScalarMap
885   std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
886   for( ; I != E; ++I)
887     if (Alive.count(*I) == 0)
888       removeRefsToGlobal(*I, G.getScalarMap());
889
890   // Delete dead function calls
891   if (FilterCalls)
892     for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
893       bool CallIsDead = true;
894       for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
895            CallIsDead && j != ej; ++j)
896         CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
897       if (CallIsDead)
898         Calls.erase(Calls.begin() + i); // remove the call entirely
899     }
900 }
901
902 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
903 // subgraphs that are unreachable.  This often occurs because the data
904 // structure doesn't "escape" into it's caller, and thus should be eliminated
905 // from the caller's graph entirely.  This is only appropriate to use when
906 // inlining graphs.
907 //
908 void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
909   assert((!KeepAllGlobals || KeepCalls) &&
910          "KeepAllGlobals without KeepCalls is meaningless");
911
912   // Reduce the amount of work we have to do...
913   removeTriviallyDeadNodes(KeepAllGlobals);
914
915   // FIXME: Merge nontrivially identical call nodes...
916
917   // Alive - a set that holds all nodes found to be reachable/alive.
918   std::set<DSNode*> Alive;
919
920   // If KeepCalls, mark all nodes reachable by call nodes as alive...
921   if (KeepCalls)
922     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
923       for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
924         markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
925       markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
926       markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
927     }
928
929   // Mark all nodes reachable by scalar nodes as alive...
930   for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
931          E = ScalarMap.end(); I != E; ++I)
932     markAlive(I->second.getNode(), Alive);
933
934 #if 0
935   // Marge all nodes reachable by global nodes, as alive.  Isn't this covered by
936   // the ScalarMap?
937   //
938   if (KeepAllGlobals)
939     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
940       if (Nodes[i]->NodeType & DSNode::GlobalNode)
941         markAlive(Nodes[i], Alive);
942 #endif
943
944   // The return value is alive as well...
945   markAlive(RetNode.getNode(), Alive);
946
947   // Mark all globals or cast nodes that can reach a live node as alive.
948   // This also marks all nodes reachable from such nodes as alive.
949   // Of course, if KeepAllGlobals is specified, they would be live already.
950   if (!KeepAllGlobals)
951     markGlobalsAlive(*this, Alive, !KeepCalls);
952
953   // Loop over all unreachable nodes, dropping their references...
954   vector<DSNode*> DeadNodes;
955   DeadNodes.reserve(Nodes.size());     // Only one allocation is allowed.
956   for (unsigned i = 0; i != Nodes.size(); ++i)
957     if (!Alive.count(Nodes[i])) {
958       DSNode *N = Nodes[i];
959       Nodes.erase(Nodes.begin()+i--);  // Erase node from alive list.
960       DeadNodes.push_back(N);          // Add node to our list of dead nodes
961       N->dropAllReferences();          // Drop all outgoing edges
962     }
963   
964   // Delete all dead nodes...
965   std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
966 }
967
968
969
970 // maskNodeTypes - Apply a mask to all of the node types in the graph.  This
971 // is useful for clearing out markers like Scalar or Incomplete.
972 //
973 void DSGraph::maskNodeTypes(unsigned char Mask) {
974   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
975     Nodes[i]->NodeType &= Mask;
976 }
977
978
979 #if 0
980 //===----------------------------------------------------------------------===//
981 // GlobalDSGraph Implementation
982 //===----------------------------------------------------------------------===//
983
984 GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
985 }
986
987 GlobalDSGraph::~GlobalDSGraph() {
988   assert(Referrers.size() == 0 &&
989          "Deleting global graph while references from other graphs exist");
990 }
991
992 void GlobalDSGraph::addReference(const DSGraph* referrer) {
993   if (referrer != this)
994     Referrers.insert(referrer);
995 }
996
997 void GlobalDSGraph::removeReference(const DSGraph* referrer) {
998   if (referrer != this) {
999     assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1000     Referrers.erase(referrer);
1001     if (Referrers.size() == 0)
1002       delete this;
1003   }
1004 }
1005
1006 #if 0
1007 // Bits used in the next function
1008 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1009
1010
1011 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1012 // visible target links (and recursively their such links) into this graph.
1013 // NodeCache maps the node being cloned to its clone in the Globals graph,
1014 // in order to track cycles.
1015 // GlobalsAreFinal is a flag that says whether it is safe to assume that
1016 // an existing global node is complete.  This is important to avoid
1017 // reinserting all globals when inserting Calls to functions.
1018 // This is a helper function for cloneGlobals and cloneCalls.
1019 // 
1020 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1021                                     std::map<const DSNode*, DSNode*> &NodeCache,
1022                                     bool GlobalsAreFinal) {
1023   if (OldNode == 0) return 0;
1024
1025   // The caller should check this is an external node.  Just more  efficient...
1026   assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1027
1028   // If a clone has already been created for OldNode, return it.
1029   DSNode*& CacheEntry = NodeCache[OldNode];
1030   if (CacheEntry != 0)
1031     return CacheEntry;
1032
1033   // The result value...
1034   DSNode* NewNode = 0;
1035
1036   // If nodes already exist for any of the globals of OldNode,
1037   // merge all such nodes together since they are merged in OldNode.
1038   // If ValueCacheIsFinal==true, look for an existing node that has
1039   // an identical list of globals and return it if it exists.
1040   //
1041   for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1042     if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
1043       if (NewNode == 0) {
1044         NewNode = PrevNode;             // first existing node found
1045         if (GlobalsAreFinal && j == 0)
1046           if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1047             CacheEntry = NewNode;
1048             return NewNode;
1049           }
1050       }
1051       else if (NewNode != PrevNode) {   // found another, different from prev
1052         // update ValMap *before* merging PrevNode into NewNode
1053         for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1054           ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
1055         NewNode->mergeWith(PrevNode);
1056       }
1057     } else if (NewNode != 0) {
1058       ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1059     }
1060
1061   // If no existing node was found, clone the node and update the ValMap.
1062   if (NewNode == 0) {
1063     NewNode = new DSNode(*OldNode);
1064     Nodes.push_back(NewNode);
1065     for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1066       NewNode->setLink(j, 0);
1067     for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1068       ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1069   }
1070   else
1071     NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1072
1073   // Add the entry to NodeCache
1074   CacheEntry = NewNode;
1075
1076   // Rewrite the links in the new node to point into the current graph,
1077   // but only for links to external nodes.  Set other links to NULL.
1078   for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1079     DSNode* OldTarget = OldNode->getLink(j);
1080     if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1081       DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1082       if (NewNode->getLink(j))
1083         NewNode->getLink(j)->mergeWith(NewLink);
1084       else
1085         NewNode->setLink(j, NewLink);
1086     }
1087   }
1088
1089   // Remove all local markers
1090   NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1091
1092   return NewNode;
1093 }
1094
1095
1096 // GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1097 // visible target links (and recursively their such links) into this graph.
1098 // 
1099 void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1100   std::map<const DSNode*, DSNode*> NodeCache;
1101 #if 0
1102   for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1103     if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1104       GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
1105   if (CloneCalls)
1106     GlobalsGraph->cloneCalls(Graph);
1107
1108   GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
1109 #endif
1110 }
1111
1112
1113 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1114 // links (and recursively their such links) into this graph.
1115 // 
1116 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1117   std::map<const DSNode*, DSNode*> NodeCache;
1118   vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
1119
1120   FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1121
1122   for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
1123     DSCallSite& callCopy = FunctionCalls.back();
1124     callCopy.reserve(FromCalls[i].size());
1125     for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
1126       callCopy.push_back
1127         ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1128          ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1129          : 0);
1130   }
1131
1132   // remove trivially identical function calls
1133   removeIdenticalCalls(FunctionCalls, "Globals Graph");
1134 }
1135 #endif
1136
1137 #endif