Make error messages more useful than jsut an abort
[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 "Support/Timer.h"
15 #include <algorithm>
16
17 namespace {
18   Statistic<> NumFolds          ("dsnode", "Number of nodes completely folded");
19   Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
20 };
21
22 namespace DS {   // TODO: FIXME
23   extern TargetData TD;
24 }
25 using namespace DS;
26
27 DSNode *DSNodeHandle::HandleForwarding() const {
28   assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
29
30   // Handle node forwarding here!
31   DSNode *Next = N->ForwardNH.getNode();  // Cause recursive shrinkage
32   Offset += N->ForwardNH.getOffset();
33
34   if (--N->NumReferrers == 0) {
35     // Removing the last referrer to the node, sever the forwarding link
36     N->stopForwarding();
37   }
38
39   N = Next;
40   N->NumReferrers++;
41   if (N->Size <= Offset) {
42     assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
43     Offset = 0;
44   }
45   return N;
46 }
47
48 //===----------------------------------------------------------------------===//
49 // DSNode Implementation
50 //===----------------------------------------------------------------------===//
51
52 DSNode::DSNode(unsigned NT, const Type *T, DSGraph *G)
53   : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(NT) {
54   // Add the type entry if it is specified...
55   if (T) mergeTypeInfo(T, 0);
56   G->getNodes().push_back(this);
57 }
58
59 // DSNode copy constructor... do not copy over the referrers list!
60 DSNode::DSNode(const DSNode &N, DSGraph *G)
61   : NumReferrers(0), Size(N.Size), ParentGraph(G), Ty(N.Ty),
62     Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
63   G->getNodes().push_back(this);
64 }
65
66 void DSNode::assertOK() const {
67   assert((Ty != Type::VoidTy ||
68           Ty == Type::VoidTy && (Size == 0 ||
69                                  (NodeType & DSNode::Array))) &&
70          "Node not OK!");
71 }
72
73 /// forwardNode - Mark this node as being obsolete, and all references to it
74 /// should be forwarded to the specified node and offset.
75 ///
76 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
77   assert(this != To && "Cannot forward a node to itself!");
78   assert(ForwardNH.isNull() && "Already forwarding from this node!");
79   if (To->Size <= 1) Offset = 0;
80   assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
81          "Forwarded offset is wrong!");
82   ForwardNH.setNode(To);
83   ForwardNH.setOffset(Offset);
84   NodeType = DEAD;
85   Size = 0;
86   Ty = Type::VoidTy;
87 }
88
89 // addGlobal - Add an entry for a global value to the Globals list.  This also
90 // marks the node with the 'G' flag if it does not already have it.
91 //
92 void DSNode::addGlobal(GlobalValue *GV) {
93   // Keep the list sorted.
94   std::vector<GlobalValue*>::iterator I =
95     std::lower_bound(Globals.begin(), Globals.end(), GV);
96
97   if (I == Globals.end() || *I != GV) {
98     //assert(GV->getType()->getElementType() == Ty);
99     Globals.insert(I, GV);
100     NodeType |= GlobalNode;
101   }
102 }
103
104 /// foldNodeCompletely - If we determine that this node has some funny
105 /// behavior happening to it that we cannot represent, we fold it down to a
106 /// single, completely pessimistic, node.  This node is represented as a
107 /// single byte with a single TypeEntry of "void".
108 ///
109 void DSNode::foldNodeCompletely() {
110   assert(!hasNoReferrers() &&
111          "Why would we collapse a node with no referrers?");
112   if (isNodeCompletelyFolded()) return;  // If this node is already folded...
113
114   ++NumFolds;
115
116   // Create the node we are going to forward to...
117   DSNode *DestNode = new DSNode(NodeType|DSNode::Array, 0, ParentGraph);
118   DestNode->Ty = Type::VoidTy;
119   DestNode->Size = 1;
120   DestNode->Globals.swap(Globals);
121
122   // Start forwarding to the destination node...
123   forwardNode(DestNode, 0);
124   
125   if (Links.size()) {
126     DestNode->Links.push_back(Links[0]);
127     DSNodeHandle NH(DestNode);
128
129     // If we have links, merge all of our outgoing links together...
130     for (unsigned i = Links.size()-1; i != 0; --i)
131       NH.getNode()->Links[0].mergeWith(Links[i]);
132     Links.clear();
133   } else {
134     DestNode->Links.resize(1);
135   }
136 }
137
138 /// isNodeCompletelyFolded - Return true if this node has been completely
139 /// folded down to something that can never be expanded, effectively losing
140 /// all of the field sensitivity that may be present in the node.
141 ///
142 bool DSNode::isNodeCompletelyFolded() const {
143   return getSize() == 1 && Ty == Type::VoidTy && isArray();
144 }
145
146
147 /// mergeTypeInfo - This method merges the specified type into the current node
148 /// at the specified offset.  This may update the current node's type record if
149 /// this gives more information to the node, it may do nothing to the node if
150 /// this information is already known, or it may merge the node completely (and
151 /// return true) if the information is incompatible with what is already known.
152 ///
153 /// This method returns true if the node is completely folded, otherwise false.
154 ///
155 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
156                            bool FoldIfIncompatible) {
157   // Check to make sure the Size member is up-to-date.  Size can be one of the
158   // following:
159   //  Size = 0, Ty = Void: Nothing is known about this node.
160   //  Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
161   //  Size = 1, Ty = Void, Array = 1: The node is collapsed
162   //  Otherwise, sizeof(Ty) = Size
163   //
164   assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
165           (Size == 0 && !Ty->isSized() && !isArray()) ||
166           (Size == 1 && Ty == Type::VoidTy && isArray()) ||
167           (Size == 0 && !Ty->isSized() && !isArray()) ||
168           (TD.getTypeSize(Ty) == Size)) &&
169          "Size member of DSNode doesn't match the type structure!");
170   assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
171
172   if (Offset == 0 && NewTy == Ty)
173     return false;  // This should be a common case, handle it efficiently
174
175   // Return true immediately if the node is completely folded.
176   if (isNodeCompletelyFolded()) return true;
177
178   // If this is an array type, eliminate the outside arrays because they won't
179   // be used anyway.  This greatly reduces the size of large static arrays used
180   // as global variables, for example.
181   //
182   bool WillBeArray = false;
183   while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
184     // FIXME: we might want to keep small arrays, but must be careful about
185     // things like: [2 x [10000 x int*]]
186     NewTy = AT->getElementType();
187     WillBeArray = true;
188   }
189
190   // Figure out how big the new type we're merging in is...
191   unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
192
193   // Otherwise check to see if we can fold this type into the current node.  If
194   // we can't, we fold the node completely, if we can, we potentially update our
195   // internal state.
196   //
197   if (Ty == Type::VoidTy) {
198     // If this is the first type that this node has seen, just accept it without
199     // question....
200     assert(Offset == 0 && "Cannot have an offset into a void node!");
201     assert(!isArray() && "This shouldn't happen!");
202     Ty = NewTy;
203     NodeType &= ~Array;
204     if (WillBeArray) NodeType |= Array;
205     Size = NewTySize;
206
207     // Calculate the number of outgoing links from this node.
208     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
209     return false;
210   }
211
212   // Handle node expansion case here...
213   if (Offset+NewTySize > Size) {
214     // It is illegal to grow this node if we have treated it as an array of
215     // objects...
216     if (isArray()) {
217       if (FoldIfIncompatible) foldNodeCompletely();
218       return true;
219     }
220
221     if (Offset) {  // We could handle this case, but we don't for now...
222       DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
223                       << "offset != 0: Collapsing!\n");
224       if (FoldIfIncompatible) foldNodeCompletely();
225       return true;
226     }
227
228     // Okay, the situation is nice and simple, we are trying to merge a type in
229     // at offset 0 that is bigger than our current type.  Implement this by
230     // switching to the new type and then merge in the smaller one, which should
231     // hit the other code path here.  If the other code path decides it's not
232     // ok, it will collapse the node as appropriate.
233     //
234     const Type *OldTy = Ty;
235     Ty = NewTy;
236     NodeType &= ~Array;
237     if (WillBeArray) NodeType |= Array;
238     Size = NewTySize;
239
240     // Must grow links to be the appropriate size...
241     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
242
243     // Merge in the old type now... which is guaranteed to be smaller than the
244     // "current" type.
245     return mergeTypeInfo(OldTy, 0);
246   }
247
248   assert(Offset <= Size &&
249          "Cannot merge something into a part of our type that doesn't exist!");
250
251   // Find the section of Ty that NewTy overlaps with... first we find the
252   // type that starts at offset Offset.
253   //
254   unsigned O = 0;
255   const Type *SubType = Ty;
256   while (O < Offset) {
257     assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
258
259     switch (SubType->getPrimitiveID()) {
260     case Type::StructTyID: {
261       const StructType *STy = cast<StructType>(SubType);
262       const StructLayout &SL = *TD.getStructLayout(STy);
263
264       unsigned i = 0, e = SL.MemberOffsets.size();
265       for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
266         /* empty */;
267
268       // The offset we are looking for must be in the i'th element...
269       SubType = STy->getElementTypes()[i];
270       O += SL.MemberOffsets[i];
271       break;
272     }
273     case Type::ArrayTyID: {
274       SubType = cast<ArrayType>(SubType)->getElementType();
275       unsigned ElSize = TD.getTypeSize(SubType);
276       unsigned Remainder = (Offset-O) % ElSize;
277       O = Offset-Remainder;
278       break;
279     }
280     default:
281       if (FoldIfIncompatible) foldNodeCompletely();
282       return true;
283     }
284   }
285
286   assert(O == Offset && "Could not achieve the correct offset!");
287
288   // If we found our type exactly, early exit
289   if (SubType == NewTy) return false;
290
291   // Okay, so we found the leader type at the offset requested.  Search the list
292   // of types that starts at this offset.  If SubType is currently an array or
293   // structure, the type desired may actually be the first element of the
294   // composite type...
295   //
296   unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
297   unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
298   while (SubType != NewTy) {
299     const Type *NextSubType = 0;
300     unsigned NextSubTypeSize = 0;
301     unsigned NextPadSize = 0;
302     switch (SubType->getPrimitiveID()) {
303     case Type::StructTyID: {
304       const StructType *STy = cast<StructType>(SubType);
305       const StructLayout &SL = *TD.getStructLayout(STy);
306       if (SL.MemberOffsets.size() > 1)
307         NextPadSize = SL.MemberOffsets[1];
308       else
309         NextPadSize = SubTypeSize;
310       NextSubType = STy->getElementTypes()[0];
311       NextSubTypeSize = TD.getTypeSize(NextSubType);
312       break;
313     }
314     case Type::ArrayTyID:
315       NextSubType = cast<ArrayType>(SubType)->getElementType();
316       NextSubTypeSize = TD.getTypeSize(NextSubType);
317       NextPadSize = NextSubTypeSize;
318       break;
319     default: ;
320       // fall out 
321     }
322
323     if (NextSubType == 0)
324       break;   // In the default case, break out of the loop
325
326     if (NextPadSize < NewTySize)
327       break;   // Don't allow shrinking to a smaller type than NewTySize
328     SubType = NextSubType;
329     SubTypeSize = NextSubTypeSize;
330     PadSize = NextPadSize;
331   }
332
333   // If we found the type exactly, return it...
334   if (SubType == NewTy)
335     return false;
336
337   // Check to see if we have a compatible, but different type...
338   if (NewTySize == SubTypeSize) {
339     // Check to see if this type is obviously convertable... int -> uint f.e.
340     if (NewTy->isLosslesslyConvertableTo(SubType))
341       return false;
342
343     // Check to see if we have a pointer & integer mismatch going on here,
344     // loading a pointer as a long, for example.
345     //
346     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
347         NewTy->isInteger() && isa<PointerType>(SubType))
348       return false;
349   } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
350     // We are accessing the field, plus some structure padding.  Ignore the
351     // structure padding.
352     return false;
353   }
354
355
356   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
357                   << "\n due to:" << NewTy << " @ " << Offset << "!\n"
358                   << "SubType: " << SubType << "\n\n");
359
360   if (FoldIfIncompatible) foldNodeCompletely();
361   return true;
362 }
363
364
365
366 // addEdgeTo - Add an edge from the current node to the specified node.  This
367 // can cause merging of nodes in the graph.
368 //
369 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
370   if (NH.getNode() == 0) return;       // Nothing to do
371
372   DSNodeHandle &ExistingEdge = getLink(Offset);
373   if (ExistingEdge.getNode()) {
374     // Merge the two nodes...
375     ExistingEdge.mergeWith(NH);
376   } else {                             // No merging to perform...
377     setLink(Offset, NH);               // Just force a link in there...
378   }
379 }
380
381
382 // MergeSortedVectors - Efficiently merge a vector into another vector where
383 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
384 // efficiently copyable and have sane comparison semantics.
385 //
386 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
387                                const std::vector<GlobalValue*> &Src) {
388   // By far, the most common cases will be the simple ones.  In these cases,
389   // avoid having to allocate a temporary vector...
390   //
391   if (Src.empty()) {             // Nothing to merge in...
392     return;
393   } else if (Dest.empty()) {     // Just copy the result in...
394     Dest = Src;
395   } else if (Src.size() == 1) {  // Insert a single element...
396     const GlobalValue *V = Src[0];
397     std::vector<GlobalValue*>::iterator I =
398       std::lower_bound(Dest.begin(), Dest.end(), V);
399     if (I == Dest.end() || *I != Src[0])  // If not already contained...
400       Dest.insert(I, Src[0]);
401   } else if (Dest.size() == 1) {
402     GlobalValue *Tmp = Dest[0];           // Save value in temporary...
403     Dest = Src;                           // Copy over list...
404     std::vector<GlobalValue*>::iterator I =
405       std::lower_bound(Dest.begin(), Dest.end(), Tmp);
406     if (I == Dest.end() || *I != Tmp)     // If not already contained...
407       Dest.insert(I, Tmp);
408
409   } else {
410     // Make a copy to the side of Dest...
411     std::vector<GlobalValue*> Old(Dest);
412     
413     // Make space for all of the type entries now...
414     Dest.resize(Dest.size()+Src.size());
415     
416     // Merge the two sorted ranges together... into Dest.
417     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
418     
419     // Now erase any duplicate entries that may have accumulated into the 
420     // vectors (because they were in both of the input sets)
421     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
422   }
423 }
424
425
426 // MergeNodes() - Helper function for DSNode::mergeWith().
427 // This function does the hard work of merging two nodes, CurNodeH
428 // and NH after filtering out trivial cases and making sure that
429 // CurNodeH.offset >= NH.offset.
430 // 
431 // ***WARNING***
432 // Since merging may cause either node to go away, we must always
433 // use the node-handles to refer to the nodes.  These node handles are
434 // automatically updated during merging, so will always provide access
435 // to the correct node after a merge.
436 //
437 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
438   assert(CurNodeH.getOffset() >= NH.getOffset() &&
439          "This should have been enforced in the caller.");
440
441   // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
442   // respect to NH.Offset) is now zero.  NOffset is the distance from the base
443   // of our object that N starts from.
444   //
445   unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
446   unsigned NSize = NH.getNode()->getSize();
447
448   // Merge the type entries of the two nodes together...
449   if (NH.getNode()->Ty != Type::VoidTy)
450     CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
451   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
452
453   // If we are merging a node with a completely folded node, then both nodes are
454   // now completely folded.
455   //
456   if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
457     if (!NH.getNode()->isNodeCompletelyFolded()) {
458       NH.getNode()->foldNodeCompletely();
459       assert(NH.getNode() && NH.getOffset() == 0 &&
460              "folding did not make offset 0?");
461       NOffset = NH.getOffset();
462       NSize = NH.getNode()->getSize();
463       assert(NOffset == 0 && NSize == 1);
464     }
465   } else if (NH.getNode()->isNodeCompletelyFolded()) {
466     CurNodeH.getNode()->foldNodeCompletely();
467     assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
468            "folding did not make offset 0?");
469     NOffset = NH.getOffset();
470     NSize = NH.getNode()->getSize();
471     assert(NOffset == 0 && NSize == 1);
472   }
473
474   DSNode *N = NH.getNode();
475   if (CurNodeH.getNode() == N || N == 0) return;
476   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
477
478   // Start forwarding to the new node!
479   CurNodeH.getNode()->NodeType |= N->NodeType;
480   N->forwardNode(CurNodeH.getNode(), NOffset);
481   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
482
483   // Make all of the outgoing links of N now be outgoing links of CurNodeH.
484   //
485   for (unsigned i = 0; i < N->getNumLinks(); ++i) {
486     DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
487     if (Link.getNode()) {
488       // Compute the offset into the current node at which to
489       // merge this link.  In the common case, this is a linear
490       // relation to the offset in the original node (with
491       // wrapping), but if the current node gets collapsed due to
492       // recursive merging, we must make sure to merge in all remaining
493       // links at offset zero.
494       unsigned MergeOffset = 0;
495       DSNode *CN = CurNodeH.getNode();
496       if (CN->Size != 1)
497         MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
498       CN->addEdgeTo(MergeOffset, Link);
499     }
500   }
501
502   // Now that there are no outgoing edges, all of the Links are dead.
503   N->Links.clear();
504
505   // Merge the globals list...
506   if (!N->Globals.empty()) {
507     MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
508
509     // Delete the globals from the old node...
510     std::vector<GlobalValue*>().swap(N->Globals);
511   }
512 }
513
514
515 // mergeWith - Merge this node and the specified node, moving all links to and
516 // from the argument node into the current node, deleting the node argument.
517 // Offset indicates what offset the specified node is to be merged into the
518 // current node.
519 //
520 // The specified node may be a null pointer (in which case, nothing happens).
521 //
522 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
523   DSNode *N = NH.getNode();
524   if (N == 0 || (N == this && NH.getOffset() == Offset))
525     return;  // Noop
526
527   assert((N->NodeType & DSNode::DEAD) == 0);
528   assert((NodeType & DSNode::DEAD) == 0);
529   assert(!hasNoReferrers() && "Should not try to fold a useless node!");
530
531   if (N == this) {
532     // We cannot merge two pieces of the same node together, collapse the node
533     // completely.
534     DEBUG(std::cerr << "Attempting to merge two chunks of"
535                     << " the same node together!\n");
536     foldNodeCompletely();
537     return;
538   }
539
540   // If both nodes are not at offset 0, make sure that we are merging the node
541   // at an later offset into the node with the zero offset.
542   //
543   if (Offset < NH.getOffset()) {
544     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
545     return;
546   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
547     // If the offsets are the same, merge the smaller node into the bigger node
548     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
549     return;
550   }
551
552   // Ok, now we can merge the two nodes.  Use a static helper that works with
553   // two node handles, since "this" may get merged away at intermediate steps.
554   DSNodeHandle CurNodeH(this, Offset);
555   DSNodeHandle NHCopy(NH);
556   DSNode::MergeNodes(CurNodeH, NHCopy);
557 }
558
559 //===----------------------------------------------------------------------===//
560 // DSCallSite Implementation
561 //===----------------------------------------------------------------------===//
562
563 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
564 Function &DSCallSite::getCaller() const {
565   return *Inst->getParent()->getParent();
566 }
567
568
569 //===----------------------------------------------------------------------===//
570 // DSGraph Implementation
571 //===----------------------------------------------------------------------===//
572
573 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
574   PrintAuxCalls = false;
575   hash_map<const DSNode*, DSNodeHandle> NodeMap;
576   RetNode = cloneInto(G, ScalarMap, NodeMap);
577 }
578
579 DSGraph::DSGraph(const DSGraph &G,
580                  hash_map<const DSNode*, DSNodeHandle> &NodeMap)
581   : Func(G.Func), GlobalsGraph(0) {
582   PrintAuxCalls = false;
583   RetNode = cloneInto(G, ScalarMap, NodeMap);
584 }
585
586 DSGraph::~DSGraph() {
587   FunctionCalls.clear();
588   AuxFunctionCalls.clear();
589   ScalarMap.clear();
590   RetNode.setNode(0);
591
592   // Drop all intra-node references, so that assertions don't fail...
593   std::for_each(Nodes.begin(), Nodes.end(),
594                 std::mem_fun(&DSNode::dropAllReferences));
595
596   // Delete all of the nodes themselves...
597   std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
598 }
599
600 // dump - Allow inspection of graph in a debugger.
601 void DSGraph::dump() const { print(std::cerr); }
602
603
604 /// remapLinks - Change all of the Links in the current node according to the
605 /// specified mapping.
606 ///
607 void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
608   for (unsigned i = 0, e = Links.size(); i != e; ++i) {
609     DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
610     Links[i].setNode(H.getNode());
611     Links[i].setOffset(Links[i].getOffset()+H.getOffset());
612   }
613 }
614
615
616 // cloneInto - Clone the specified DSGraph into the current graph, returning the
617 // Return node of the graph.  The translated ScalarMap for the old function is
618 // filled into the OldValMap member.  If StripAllocas is set to true, Alloca
619 // markers are removed from the graph, as the graph is being cloned into a
620 // calling function's graph.
621 //
622 DSNodeHandle DSGraph::cloneInto(const DSGraph &G, 
623                                 hash_map<Value*, DSNodeHandle> &OldValMap,
624                               hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
625                                 unsigned CloneFlags) {
626   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
627   assert(&G != this && "Cannot clone graph into itself!");
628
629   unsigned FN = Nodes.size();           // First new node...
630
631   // Duplicate all of the nodes, populating the node map...
632   Nodes.reserve(FN+G.Nodes.size());
633
634   // Remove alloca or mod/ref bits as specified...
635   unsigned clearBits = (CloneFlags & StripAllocaBit ? DSNode::AllocaNode : 0)
636     | (CloneFlags & StripModRefBits ? (DSNode::Modified | DSNode::Read) : 0);
637   clearBits |= DSNode::DEAD;  // Clear dead flag...
638   for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
639     DSNode *Old = G.Nodes[i];
640     DSNode *New = new DSNode(*Old, this);
641     New->NodeType &= ~clearBits;
642     OldNodeMap[Old] = New;
643   }
644
645 #ifndef NDEBUG
646   Timer::addPeakMemoryMeasurement();
647 #endif
648
649   // Rewrite the links in the new nodes to point into the current graph now.
650   for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
651     Nodes[i]->remapLinks(OldNodeMap);
652
653   // Copy the scalar map... merging all of the global nodes...
654   for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
655          E = G.ScalarMap.end(); I != E; ++I) {
656     DSNodeHandle &H = OldValMap[I->first];
657     DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
658     H.setOffset(I->second.getOffset()+MappedNode.getOffset());
659     H.setNode(MappedNode.getNode());
660
661     if (isa<GlobalValue>(I->first)) {  // Is this a global?
662       hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
663       if (GVI != ScalarMap.end())     // Is the global value in this fn already?
664         GVI->second.mergeWith(H);
665       else
666         ScalarMap[I->first] = H;      // Add global pointer to this graph
667     }
668   }
669
670   if (!(CloneFlags & DontCloneCallNodes)) {
671     // Copy the function calls list...
672     unsigned FC = FunctionCalls.size();  // FirstCall
673     FunctionCalls.reserve(FC+G.FunctionCalls.size());
674     for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
675       FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
676   }
677
678   if (!(CloneFlags & DontCloneAuxCallNodes)) {
679     // Copy the auxillary function calls list...
680     unsigned FC = AuxFunctionCalls.size();  // FirstCall
681     AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
682     for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
683       AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
684   }
685
686   // Return the returned node pointer...
687   DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
688   return DSNodeHandle(MappedRet.getNode(),
689                       MappedRet.getOffset()+G.RetNode.getOffset());
690 }
691
692 /// mergeInGraph - The method is used for merging graphs together.  If the
693 /// argument graph is not *this, it makes a clone of the specified graph, then
694 /// merges the nodes specified in the call site with the formal arguments in the
695 /// graph.
696 ///
697 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
698                            unsigned CloneFlags) {
699   hash_map<Value*, DSNodeHandle> OldValMap;
700   DSNodeHandle RetVal;
701   hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
702
703   // If this is not a recursive call, clone the graph into this graph...
704   if (&Graph != this) {
705     // Clone the callee's graph into the current graph, keeping
706     // track of where scalars in the old graph _used_ to point,
707     // and of the new nodes matching nodes of the old graph.
708     hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
709     
710     // The clone call may invalidate any of the vectors in the data
711     // structure graph.  Strip locals and don't copy the list of callers
712     RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
713     ScalarMap = &OldValMap;
714   } else {
715     RetVal = getRetNode();
716     ScalarMap = &getScalarMap();
717   }
718
719   // Merge the return value with the return value of the context...
720   RetVal.mergeWith(CS.getRetVal());
721
722   // Resolve all of the function arguments...
723   Function &F = Graph.getFunction();
724   Function::aiterator AI = F.abegin();
725
726   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
727     // Advance the argument iterator to the first pointer argument...
728     while (AI != F.aend() && !isPointerType(AI->getType())) {
729       ++AI;
730 #ifndef NDEBUG
731       if (AI == F.aend())
732         std::cerr << "Bad call to Function: " << F.getName() << "\n";
733 #endif
734     }
735     if (AI == F.aend()) break;
736     
737     // Add the link from the argument scalar to the provided value
738     assert(ScalarMap->count(AI) && "Argument not in scalar map?");
739     DSNodeHandle &NH = (*ScalarMap)[AI];
740     assert(NH.getNode() && "Pointer argument without scalarmap entry?");
741     NH.mergeWith(CS.getPtrArg(i));
742   }
743 }
744
745
746 // markIncompleteNodes - Mark the specified node as having contents that are not
747 // known with the current analysis we have performed.  Because a node makes all
748 // of the nodes it can reach imcomplete if the node itself is incomplete, we
749 // must recursively traverse the data structure graph, marking all reachable
750 // nodes as incomplete.
751 //
752 static void markIncompleteNode(DSNode *N) {
753   // Stop recursion if no node, or if node already marked...
754   if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
755
756   // Actually mark the node
757   N->NodeType |= DSNode::Incomplete;
758
759   // Recusively process children...
760   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
761     if (DSNode *DSN = N->getLink(i).getNode())
762       markIncompleteNode(DSN);
763 }
764
765 static void markIncomplete(DSCallSite &Call) {
766   // Then the return value is certainly incomplete!
767   markIncompleteNode(Call.getRetVal().getNode());
768
769   // All objects pointed to by function arguments are incomplete!
770   for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
771     markIncompleteNode(Call.getPtrArg(i).getNode());
772 }
773
774 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
775 // modified by other functions that have not been resolved yet.  This marks
776 // nodes that are reachable through three sources of "unknownness":
777 //
778 //  Global Variables, Function Calls, and Incoming Arguments
779 //
780 // For any node that may have unknown components (because something outside the
781 // scope of current analysis may have modified it), the 'Incomplete' flag is
782 // added to the NodeType.
783 //
784 void DSGraph::markIncompleteNodes(unsigned Flags) {
785   // Mark any incoming arguments as incomplete...
786   if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
787     for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
788       if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
789         markIncompleteNode(ScalarMap[I].getNode());
790
791   // Mark stuff passed into functions calls as being incomplete...
792   if (!shouldPrintAuxCalls())
793     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
794       markIncomplete(FunctionCalls[i]);
795   else
796     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
797       markIncomplete(AuxFunctionCalls[i]);
798     
799
800   // Mark all global nodes as incomplete...
801   if ((Flags & DSGraph::IgnoreGlobals) == 0)
802     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
803       if (Nodes[i]->NodeType & DSNode::GlobalNode && Nodes[i]->getNumLinks())
804         markIncompleteNode(Nodes[i]);
805 }
806
807 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
808   if (DSNode *N = Edge.getNode())  // Is there an edge?
809     if (N->getNumReferrers() == 1)  // Does it point to a lonely node?
810       if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
811           N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
812         Edge.setNode(0);  // Kill the edge!
813 }
814
815 static inline bool nodeContainsExternalFunction(const DSNode *N) {
816   const std::vector<GlobalValue*> &Globals = N->getGlobals();
817   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
818     if (Globals[i]->isExternal())
819       return true;
820   return false;
821 }
822
823 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
824                                  const std::string &where) {
825   // Remove trivially identical function calls
826   unsigned NumFns = Calls.size();
827   std::sort(Calls.begin(), Calls.end());  // Sort by callee as primary key!
828
829   // Scan the call list cleaning it up as necessary...
830   DSNode   *LastCalleeNode = 0;
831   Function *LastCalleeFunc = 0;
832   unsigned NumDuplicateCalls = 0;
833   bool LastCalleeContainsExternalFunction = false;
834   for (unsigned i = 0; i != Calls.size(); ++i) {
835     DSCallSite &CS = Calls[i];
836
837     // If the Callee is a useless edge, this must be an unreachable call site,
838     // eliminate it.
839     if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
840         CS.getCalleeNode()->NodeType == 0) {  // No useful info?
841       std::cerr << "WARNING: Useless call site found??\n";
842       CS.swap(Calls.back());
843       Calls.pop_back();
844       --i;
845     } else {
846       // If the return value or any arguments point to a void node with no
847       // information at all in it, and the call node is the only node to point
848       // to it, remove the edge to the node (killing the node).
849       //
850       killIfUselessEdge(CS.getRetVal());
851       for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
852         killIfUselessEdge(CS.getPtrArg(a));
853       
854       // If this call site calls the same function as the last call site, and if
855       // the function pointer contains an external function, this node will
856       // never be resolved.  Merge the arguments of the call node because no
857       // information will be lost.
858       //
859       if ((CS.isDirectCall()   && CS.getCalleeFunc() == LastCalleeFunc) ||
860           (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
861         ++NumDuplicateCalls;
862         if (NumDuplicateCalls == 1) {
863           if (LastCalleeNode)
864             LastCalleeContainsExternalFunction =
865               nodeContainsExternalFunction(LastCalleeNode);
866           else
867             LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
868         }
869         
870         if (LastCalleeContainsExternalFunction ||
871             // This should be more than enough context sensitivity!
872             // FIXME: Evaluate how many times this is tripped!
873             NumDuplicateCalls > 20) {
874           DSCallSite &OCS = Calls[i-1];
875           OCS.mergeWith(CS);
876           
877           // The node will now be eliminated as a duplicate!
878           if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
879             CS = OCS;
880           else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
881             OCS = CS;
882         }
883       } else {
884         if (CS.isDirectCall()) {
885           LastCalleeFunc = CS.getCalleeFunc();
886           LastCalleeNode = 0;
887         } else {
888           LastCalleeNode = CS.getCalleeNode();
889           LastCalleeFunc = 0;
890         }
891         NumDuplicateCalls = 0;
892       }
893     }
894   }
895
896   Calls.erase(std::unique(Calls.begin(), Calls.end()),
897               Calls.end());
898
899   // Track the number of call nodes merged away...
900   NumCallNodesMerged += NumFns-Calls.size();
901
902   DEBUG(if (NumFns != Calls.size())
903           std::cerr << "Merged " << (NumFns-Calls.size())
904                     << " call nodes in " << where << "\n";);
905 }
906
907
908 // removeTriviallyDeadNodes - After the graph has been constructed, this method
909 // removes all unreachable nodes that are created because they got merged with
910 // other nodes in the graph.  These nodes will all be trivially unreachable, so
911 // we don't have to perform any non-trivial analysis here.
912 //
913 void DSGraph::removeTriviallyDeadNodes() {
914   removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
915   removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
916
917   for (unsigned i = 0; i != Nodes.size(); ++i) {
918     DSNode *Node = Nodes[i];
919     if (!(Node->NodeType & ~(DSNode::Composition | DSNode::Array |
920                              DSNode::DEAD))) {
921       // This is a useless node if it has no mod/ref info (checked above),
922       // outgoing edges (which it cannot, as it is not modified in this
923       // context), and it has no incoming edges.  If it is a global node it may
924       // have all of these properties and still have incoming edges, due to the
925       // scalar map, so we check those now.
926       //
927       if (Node->getNumReferrers() == Node->getGlobals().size()) {
928         std::vector<GlobalValue*> &Globals = Node->getGlobals();
929
930         // Loop through and make sure all of the globals are referring directly
931         // to the node...
932         for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
933           DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
934           assert(N == Node && "ScalarMap doesn't match globals list!");
935         }
936
937         // Make sure numreferrers still agrees, if so, the node is truely dead.
938         if (Node->getNumReferrers() == Globals.size()) {
939           for (unsigned j = 0, e = Globals.size(); j != e; ++j)
940             ScalarMap.erase(Globals[j]);
941
942           Globals.clear();
943           assert(Node->hasNoReferrers() && "Shouldn't have refs now!");
944           
945           Node->NodeType = DSNode::DEAD;
946         }
947       }
948     }
949
950     if ((Node->NodeType & ~DSNode::DEAD) == 0 && Node->hasNoReferrers()) {
951       // This node is dead!
952       delete Node;                        // Free memory...
953       Nodes[i--] = Nodes.back();
954       Nodes.pop_back();                   // Remove from node list...
955     }
956   }
957 }
958
959
960 /// markReachableNodes - This method recursively traverses the specified
961 /// DSNodes, marking any nodes which are reachable.  All reachable nodes it adds
962 /// to the set, which allows it to only traverse visited nodes once.
963 ///
964 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
965   if (this == 0) return;
966   assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
967   if (ReachableNodes.count(this)) return;          // Already marked reachable
968   ReachableNodes.insert(this);                     // Is reachable now
969
970   for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
971     getLink(i).getNode()->markReachableNodes(ReachableNodes);
972 }
973
974 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
975   getRetVal().getNode()->markReachableNodes(Nodes);
976   if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
977   
978   for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
979     getPtrArg(i).getNode()->markReachableNodes(Nodes);
980 }
981
982 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
983 // looking for a node that is marked alive.  If an alive node is found, return
984 // true, otherwise return false.  If an alive node is reachable, this node is
985 // marked as alive...
986 //
987 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
988                                hash_set<DSNode*> &Visited) {
989   if (N == 0) return false;
990   assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
991
992   // If we know that this node is alive, return so!
993   if (Alive.count(N)) return true;
994
995   // Otherwise, we don't think the node is alive yet, check for infinite
996   // recursion.
997   if (Visited.count(N)) return false;  // Found a cycle
998   Visited.insert(N);   // No recursion, insert into Visited...
999
1000   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1001     if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
1002       N->markReachableNodes(Alive);
1003       return true;
1004     }
1005   return false;
1006 }
1007
1008 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1009 // alive nodes.
1010 //
1011 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1012                                   hash_set<DSNode*> &Visited) {
1013   if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
1014     return true;
1015   if (CS.isIndirectCall() &&
1016       CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
1017     return true;
1018   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1019     if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
1020       return true;
1021   return false;
1022 }
1023
1024 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1025 // subgraphs that are unreachable.  This often occurs because the data
1026 // structure doesn't "escape" into it's caller, and thus should be eliminated
1027 // from the caller's graph entirely.  This is only appropriate to use when
1028 // inlining graphs.
1029 //
1030 void DSGraph::removeDeadNodes(unsigned Flags) {
1031   // Reduce the amount of work we have to do... remove dummy nodes left over by
1032   // merging...
1033   removeTriviallyDeadNodes();
1034
1035   // FIXME: Merge nontrivially identical call nodes...
1036
1037   // Alive - a set that holds all nodes found to be reachable/alive.
1038   hash_set<DSNode*> Alive;
1039   std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1040
1041   // Mark all nodes reachable by (non-global) scalar nodes as alive...
1042   for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
1043          E = ScalarMap.end(); I != E; )
1044     if (isa<GlobalValue>(I->first)) {             // Keep track of global nodes
1045       assert(I->second.getNode() && "Null global node?");
1046       GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1047       ++I;
1048     } else {
1049       // Check to see if this is a worthless node generated for non-pointer
1050       // values, such as integers.  Consider an addition of long types: A+B.
1051       // Assuming we can track all uses of the value in this context, and it is
1052       // NOT used as a pointer, we can delete the node.  We will be able to
1053       // detect this situation if the node pointed to ONLY has Unknown bit set
1054       // in the node.  In this case, the node is not incomplete, does not point
1055       // to any other nodes (no mod/ref bits set), and is therefore
1056       // uninteresting for data structure analysis.  If we run across one of
1057       // these, prune the scalar pointing to it.
1058       //
1059       DSNode *N = I->second.getNode();
1060       if (N->NodeType == DSNode::UnknownNode && !isa<Argument>(I->first)) {
1061         ScalarMap.erase(I++);
1062       } else {
1063         I->second.getNode()->markReachableNodes(Alive);
1064         ++I;
1065       }
1066     }
1067
1068   // The return value is alive as well...
1069   RetNode.getNode()->markReachableNodes(Alive);
1070
1071   // Mark any nodes reachable by primary calls as alive...
1072   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1073     FunctionCalls[i].markReachableNodes(Alive);
1074
1075   bool Iterate;
1076   hash_set<DSNode*> Visited;
1077   std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1078   do {
1079     Visited.clear();
1080     // If any global nodes points to a non-global that is "alive", the global is
1081     // "alive" as well...  Remove it from the GlobalNodes list so we only have
1082     // unreachable globals in the list.
1083     //
1084     Iterate = false;
1085     for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1086       if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1087         std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1088         GlobalNodes.pop_back();                          // Erase efficiently
1089         Iterate = true;
1090       }
1091
1092     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1093       if (!AuxFCallsAlive[i] &&
1094           CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1095         AuxFunctionCalls[i].markReachableNodes(Alive);
1096         AuxFCallsAlive[i] = true;
1097         Iterate = true;
1098       }
1099   } while (Iterate);
1100
1101   // Remove all dead aux function calls...
1102   unsigned CurIdx = 0;
1103   for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1104     if (AuxFCallsAlive[i])
1105       AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1106   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1107     assert(GlobalsGraph && "No globals graph available??");
1108     // Move the unreachable call nodes to the globals graph...
1109     GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1110                                           AuxFunctionCalls.begin()+CurIdx,
1111                                           AuxFunctionCalls.end());
1112   }
1113   // Crop all the useless ones out...
1114   AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1115                          AuxFunctionCalls.end());
1116
1117   // At this point, any nodes which are visited, but not alive, are nodes which
1118   // should be moved to the globals graph.  Loop over all nodes, eliminating
1119   // completely unreachable nodes, and moving visited nodes to the globals graph
1120   //
1121   std::vector<DSNode*> DeadNodes;
1122   DeadNodes.reserve(Nodes.size());
1123   for (unsigned i = 0; i != Nodes.size(); ++i)
1124     if (!Alive.count(Nodes[i])) {
1125       DSNode *N = Nodes[i];
1126       Nodes[i--] = Nodes.back();            // move node to end of vector
1127       Nodes.pop_back();                     // Erase node from alive list.
1128       if (!(Flags & DSGraph::RemoveUnreachableGlobals) &&  // Not in TD pass
1129           Visited.count(N)) {                    // Visited but not alive?
1130         GlobalsGraph->Nodes.push_back(N);        // Move node to globals graph
1131         N->setParentGraph(GlobalsGraph);
1132       } else {                                 // Otherwise, delete the node
1133         assert(((N->NodeType & DSNode::GlobalNode) == 0 ||
1134                 (Flags & DSGraph::RemoveUnreachableGlobals))
1135                && "Killing a global?");
1136         //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1137         //          << "] Node is dead: "; N->dump();
1138         DeadNodes.push_back(N);
1139         N->dropAllReferences();
1140       }
1141     } else {
1142       assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1143     }
1144
1145   // Now that the nodes have either been deleted or moved to the globals graph,
1146   // loop over the scalarmap, updating the entries for globals...
1147   //
1148   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {  // Not in the TD pass?
1149     // In this array we start the remapping, which can cause merging.  Because
1150     // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1151     // must always go through the ScalarMap (which contains DSNodeHandles [which
1152     // cannot be invalidated by merging]).
1153     //
1154     for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1155       Value *G = GlobalNodes[i].first;
1156       hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1157       assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1158       assert(I->second.getNode() && "Global not pointing to anything?");
1159       assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1160       GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1161       assert(GlobalsGraph->ScalarMap[G].getNode() &&
1162              "Global not pointing to anything?");
1163       ScalarMap.erase(I);
1164     }
1165
1166     // Merging leaves behind silly nodes, we remove them to avoid polluting the
1167     // globals graph.
1168     if (!GlobalNodes.empty())
1169       GlobalsGraph->removeTriviallyDeadNodes();
1170   } else {
1171     // If we are in the top-down pass, remove all unreachable globals from the
1172     // ScalarMap...
1173     for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1174       ScalarMap.erase(GlobalNodes[i].first);
1175   }
1176
1177   // Loop over all of the dead nodes now, deleting them since their referrer
1178   // count is zero.
1179   for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1180     delete DeadNodes[i];
1181
1182   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1183 }
1184
1185 void DSGraph::AssertGraphOK() const {
1186   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1187     Nodes[i]->assertOK();
1188   return;  // FIXME: remove
1189   for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1190          E = ScalarMap.end(); I != E; ++I) {
1191     assert(I->second.getNode() && "Null node in scalarmap!");
1192     AssertNodeInGraph(I->second.getNode());
1193     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1194       assert((I->second.getNode()->NodeType & DSNode::GlobalNode) &&
1195              "Global points to node, but node isn't global?");
1196       AssertNodeContainsGlobal(I->second.getNode(), GV);
1197     }
1198   }
1199   AssertCallNodesInGraph();
1200   AssertAuxCallNodesInGraph();
1201 }