Add support for 'rename'
[oota-llvm.git] / lib / Analysis / DataStructure / DataStructure.cpp
1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the core data structure functionality.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/DSGraph.h"
15 #include "llvm/Function.h"
16 #include "llvm/iOther.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "Support/CommandLine.h"
21 #include "Support/Debug.h"
22 #include "Support/STLExtras.h"
23 #include "Support/Statistic.h"
24 #include "Support/Timer.h"
25 #include <algorithm>
26 using namespace llvm;
27
28 namespace {
29   Statistic<> NumFolds          ("dsa", "Number of nodes completely folded");
30   Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
31   Statistic<> NumNodeAllocated  ("dsa", "Number of nodes allocated");
32   Statistic<> NumDNE            ("dsa", "Number of nodes removed by reachability");
33   Statistic<> NumTrivialDNE     ("dsa", "Number of nodes trivially removed");
34   Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
35
36   cl::opt<bool>
37   EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
38                 cl::desc("Make DSA less aggressive when cloning graphs"));
39 };
40
41 #if 1
42 #define TIME_REGION(VARNAME, DESC) \
43    NamedRegionTimer VARNAME(DESC)
44 #else
45 #define TIME_REGION(VARNAME, DESC)
46 #endif
47
48 using namespace DS;
49
50 DSNode *DSNodeHandle::HandleForwarding() const {
51   assert(N->isForwarding() && "Can only be invoked if forwarding!");
52
53   // Handle node forwarding here!
54   DSNode *Next = N->ForwardNH.getNode();  // Cause recursive shrinkage
55   Offset += N->ForwardNH.getOffset();
56
57   if (--N->NumReferrers == 0) {
58     // Removing the last referrer to the node, sever the forwarding link
59     N->stopForwarding();
60   }
61
62   N = Next;
63   N->NumReferrers++;
64   if (N->Size <= Offset) {
65     assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
66     Offset = 0;
67   }
68   return N;
69 }
70
71 //===----------------------------------------------------------------------===//
72 // DSNode Implementation
73 //===----------------------------------------------------------------------===//
74
75 DSNode::DSNode(const Type *T, DSGraph *G)
76   : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
77   // Add the type entry if it is specified...
78   if (T) mergeTypeInfo(T, 0);
79   if (G) G->addNode(this);
80   ++NumNodeAllocated;
81 }
82
83 // DSNode copy constructor... do not copy over the referrers list!
84 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
85   : NumReferrers(0), Size(N.Size), ParentGraph(G),
86     Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
87   if (!NullLinks)
88     Links = N.Links;
89   else
90     Links.resize(N.Links.size()); // Create the appropriate number of null links
91   G->addNode(this);
92   ++NumNodeAllocated;
93 }
94
95 /// getTargetData - Get the target data object used to construct this node.
96 ///
97 const TargetData &DSNode::getTargetData() const {
98   return ParentGraph->getTargetData();
99 }
100
101 void DSNode::assertOK() const {
102   assert((Ty != Type::VoidTy ||
103           Ty == Type::VoidTy && (Size == 0 ||
104                                  (NodeType & DSNode::Array))) &&
105          "Node not OK!");
106
107   assert(ParentGraph && "Node has no parent?");
108   const DSScalarMap &SM = ParentGraph->getScalarMap();
109   for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
110     assert(SM.count(Globals[i]));
111     assert(SM.find(Globals[i])->second.getNode() == this);
112   }
113 }
114
115 /// forwardNode - Mark this node as being obsolete, and all references to it
116 /// should be forwarded to the specified node and offset.
117 ///
118 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
119   assert(this != To && "Cannot forward a node to itself!");
120   assert(ForwardNH.isNull() && "Already forwarding from this node!");
121   if (To->Size <= 1) Offset = 0;
122   assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
123          "Forwarded offset is wrong!");
124   ForwardNH.setNode(To);
125   ForwardNH.setOffset(Offset);
126   NodeType = DEAD;
127   Size = 0;
128   Ty = Type::VoidTy;
129
130   // Remove this node from the parent graph's Nodes list.
131   ParentGraph->unlinkNode(this);  
132   ParentGraph = 0;
133 }
134
135 // addGlobal - Add an entry for a global value to the Globals list.  This also
136 // marks the node with the 'G' flag if it does not already have it.
137 //
138 void DSNode::addGlobal(GlobalValue *GV) {
139   // Keep the list sorted.
140   std::vector<GlobalValue*>::iterator I =
141     std::lower_bound(Globals.begin(), Globals.end(), GV);
142
143   if (I == Globals.end() || *I != GV) {
144     //assert(GV->getType()->getElementType() == Ty);
145     Globals.insert(I, GV);
146     NodeType |= GlobalNode;
147   }
148 }
149
150 /// foldNodeCompletely - If we determine that this node has some funny
151 /// behavior happening to it that we cannot represent, we fold it down to a
152 /// single, completely pessimistic, node.  This node is represented as a
153 /// single byte with a single TypeEntry of "void".
154 ///
155 void DSNode::foldNodeCompletely() {
156   if (isNodeCompletelyFolded()) return;  // If this node is already folded...
157
158   ++NumFolds;
159
160   // If this node has a size that is <= 1, we don't need to create a forwarding
161   // node.
162   if (getSize() <= 1) {
163     NodeType |= DSNode::Array;
164     Ty = Type::VoidTy;
165     Size = 1;
166     assert(Links.size() <= 1 && "Size is 1, but has more links?");
167     Links.resize(1);
168   } else {
169     // Create the node we are going to forward to.  This is required because
170     // some referrers may have an offset that is > 0.  By forcing them to
171     // forward, the forwarder has the opportunity to correct the offset.
172     DSNode *DestNode = new DSNode(0, ParentGraph);
173     DestNode->NodeType = NodeType|DSNode::Array;
174     DestNode->Ty = Type::VoidTy;
175     DestNode->Size = 1;
176     DestNode->Globals.swap(Globals);
177     
178     // Start forwarding to the destination node...
179     forwardNode(DestNode, 0);
180     
181     if (!Links.empty()) {
182       DestNode->Links.reserve(1);
183       
184       DSNodeHandle NH(DestNode);
185       DestNode->Links.push_back(Links[0]);
186       
187       // If we have links, merge all of our outgoing links together...
188       for (unsigned i = Links.size()-1; i != 0; --i)
189         NH.getNode()->Links[0].mergeWith(Links[i]);
190       Links.clear();
191     } else {
192       DestNode->Links.resize(1);
193     }
194   }
195 }
196
197 /// isNodeCompletelyFolded - Return true if this node has been completely
198 /// folded down to something that can never be expanded, effectively losing
199 /// all of the field sensitivity that may be present in the node.
200 ///
201 bool DSNode::isNodeCompletelyFolded() const {
202   return getSize() == 1 && Ty == Type::VoidTy && isArray();
203 }
204
205 namespace {
206   /// TypeElementWalker Class - Used for implementation of physical subtyping...
207   ///
208   class TypeElementWalker {
209     struct StackState {
210       const Type *Ty;
211       unsigned Offset;
212       unsigned Idx;
213       StackState(const Type *T, unsigned Off = 0)
214         : Ty(T), Offset(Off), Idx(0) {}
215     };
216
217     std::vector<StackState> Stack;
218     const TargetData &TD;
219   public:
220     TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
221       Stack.push_back(T);
222       StepToLeaf();
223     }
224
225     bool isDone() const { return Stack.empty(); }
226     const Type *getCurrentType()   const { return Stack.back().Ty;     }
227     unsigned    getCurrentOffset() const { return Stack.back().Offset; }
228
229     void StepToNextType() {
230       PopStackAndAdvance();
231       StepToLeaf();
232     }
233
234   private:
235     /// PopStackAndAdvance - Pop the current element off of the stack and
236     /// advance the underlying element to the next contained member.
237     void PopStackAndAdvance() {
238       assert(!Stack.empty() && "Cannot pop an empty stack!");
239       Stack.pop_back();
240       while (!Stack.empty()) {
241         StackState &SS = Stack.back();
242         if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
243           ++SS.Idx;
244           if (SS.Idx != ST->getNumElements()) {
245             const StructLayout *SL = TD.getStructLayout(ST);
246             SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
247             return;
248           }
249           Stack.pop_back();  // At the end of the structure
250         } else {
251           const ArrayType *AT = cast<ArrayType>(SS.Ty);
252           ++SS.Idx;
253           if (SS.Idx != AT->getNumElements()) {
254             SS.Offset += TD.getTypeSize(AT->getElementType());
255             return;
256           }
257           Stack.pop_back();  // At the end of the array
258         }
259       }
260     }
261
262     /// StepToLeaf - Used by physical subtyping to move to the first leaf node
263     /// on the type stack.
264     void StepToLeaf() {
265       if (Stack.empty()) return;
266       while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
267         StackState &SS = Stack.back();
268         if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
269           if (ST->getNumElements() == 0) {
270             assert(SS.Idx == 0);
271             PopStackAndAdvance();
272           } else {
273             // Step into the structure...
274             assert(SS.Idx < ST->getNumElements());
275             const StructLayout *SL = TD.getStructLayout(ST);
276             Stack.push_back(StackState(ST->getElementType(SS.Idx),
277                                        SS.Offset+SL->MemberOffsets[SS.Idx]));
278           }
279         } else {
280           const ArrayType *AT = cast<ArrayType>(SS.Ty);
281           if (AT->getNumElements() == 0) {
282             assert(SS.Idx == 0);
283             PopStackAndAdvance();
284           } else {
285             // Step into the array...
286             assert(SS.Idx < AT->getNumElements());
287             Stack.push_back(StackState(AT->getElementType(),
288                                        SS.Offset+SS.Idx*
289                                        TD.getTypeSize(AT->getElementType())));
290           }
291         }
292       }
293     }
294   };
295 } // end anonymous namespace
296
297 /// ElementTypesAreCompatible - Check to see if the specified types are
298 /// "physically" compatible.  If so, return true, else return false.  We only
299 /// have to check the fields in T1: T2 may be larger than T1.  If AllowLargerT1
300 /// is true, then we also allow a larger T1.
301 ///
302 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
303                                       bool AllowLargerT1, const TargetData &TD){
304   TypeElementWalker T1W(T1, TD), T2W(T2, TD);
305   
306   while (!T1W.isDone() && !T2W.isDone()) {
307     if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
308       return false;
309
310     const Type *T1 = T1W.getCurrentType();
311     const Type *T2 = T2W.getCurrentType();
312     if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
313       return false;
314     
315     T1W.StepToNextType();
316     T2W.StepToNextType();
317   }
318   
319   return AllowLargerT1 || T1W.isDone();
320 }
321
322
323 /// mergeTypeInfo - This method merges the specified type into the current node
324 /// at the specified offset.  This may update the current node's type record if
325 /// this gives more information to the node, it may do nothing to the node if
326 /// this information is already known, or it may merge the node completely (and
327 /// return true) if the information is incompatible with what is already known.
328 ///
329 /// This method returns true if the node is completely folded, otherwise false.
330 ///
331 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
332                            bool FoldIfIncompatible) {
333   const TargetData &TD = getTargetData();
334   // Check to make sure the Size member is up-to-date.  Size can be one of the
335   // following:
336   //  Size = 0, Ty = Void: Nothing is known about this node.
337   //  Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
338   //  Size = 1, Ty = Void, Array = 1: The node is collapsed
339   //  Otherwise, sizeof(Ty) = Size
340   //
341   assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
342           (Size == 0 && !Ty->isSized() && !isArray()) ||
343           (Size == 1 && Ty == Type::VoidTy && isArray()) ||
344           (Size == 0 && !Ty->isSized() && !isArray()) ||
345           (TD.getTypeSize(Ty) == Size)) &&
346          "Size member of DSNode doesn't match the type structure!");
347   assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
348
349   if (Offset == 0 && NewTy == Ty)
350     return false;  // This should be a common case, handle it efficiently
351
352   // Return true immediately if the node is completely folded.
353   if (isNodeCompletelyFolded()) return true;
354
355   // If this is an array type, eliminate the outside arrays because they won't
356   // be used anyway.  This greatly reduces the size of large static arrays used
357   // as global variables, for example.
358   //
359   bool WillBeArray = false;
360   while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
361     // FIXME: we might want to keep small arrays, but must be careful about
362     // things like: [2 x [10000 x int*]]
363     NewTy = AT->getElementType();
364     WillBeArray = true;
365   }
366
367   // Figure out how big the new type we're merging in is...
368   unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
369
370   // Otherwise check to see if we can fold this type into the current node.  If
371   // we can't, we fold the node completely, if we can, we potentially update our
372   // internal state.
373   //
374   if (Ty == Type::VoidTy) {
375     // If this is the first type that this node has seen, just accept it without
376     // question....
377     assert(Offset == 0 && !isArray() &&
378            "Cannot have an offset into a void node!");
379     Ty = NewTy;
380     NodeType &= ~Array;
381     if (WillBeArray) NodeType |= Array;
382     Size = NewTySize;
383
384     // Calculate the number of outgoing links from this node.
385     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
386     return false;
387   }
388
389   // Handle node expansion case here...
390   if (Offset+NewTySize > Size) {
391     // It is illegal to grow this node if we have treated it as an array of
392     // objects...
393     if (isArray()) {
394       if (FoldIfIncompatible) foldNodeCompletely();
395       return true;
396     }
397
398     if (Offset) {  // We could handle this case, but we don't for now...
399       std::cerr << "UNIMP: Trying to merge a growth type into "
400                 << "offset != 0: Collapsing!\n";
401       if (FoldIfIncompatible) foldNodeCompletely();
402       return true;
403     }
404
405     // Okay, the situation is nice and simple, we are trying to merge a type in
406     // at offset 0 that is bigger than our current type.  Implement this by
407     // switching to the new type and then merge in the smaller one, which should
408     // hit the other code path here.  If the other code path decides it's not
409     // ok, it will collapse the node as appropriate.
410     //
411     const Type *OldTy = Ty;
412     Ty = NewTy;
413     NodeType &= ~Array;
414     if (WillBeArray) NodeType |= Array;
415     Size = NewTySize;
416
417     // Must grow links to be the appropriate size...
418     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
419
420     // Merge in the old type now... which is guaranteed to be smaller than the
421     // "current" type.
422     return mergeTypeInfo(OldTy, 0);
423   }
424
425   assert(Offset <= Size &&
426          "Cannot merge something into a part of our type that doesn't exist!");
427
428   // Find the section of Ty that NewTy overlaps with... first we find the
429   // type that starts at offset Offset.
430   //
431   unsigned O = 0;
432   const Type *SubType = Ty;
433   while (O < Offset) {
434     assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
435
436     switch (SubType->getPrimitiveID()) {
437     case Type::StructTyID: {
438       const StructType *STy = cast<StructType>(SubType);
439       const StructLayout &SL = *TD.getStructLayout(STy);
440
441       unsigned i = 0, e = SL.MemberOffsets.size();
442       for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
443         /* empty */;
444
445       // The offset we are looking for must be in the i'th element...
446       SubType = STy->getElementType(i);
447       O += SL.MemberOffsets[i];
448       break;
449     }
450     case Type::ArrayTyID: {
451       SubType = cast<ArrayType>(SubType)->getElementType();
452       unsigned ElSize = TD.getTypeSize(SubType);
453       unsigned Remainder = (Offset-O) % ElSize;
454       O = Offset-Remainder;
455       break;
456     }
457     default:
458       if (FoldIfIncompatible) foldNodeCompletely();
459       return true;
460     }
461   }
462
463   assert(O == Offset && "Could not achieve the correct offset!");
464
465   // If we found our type exactly, early exit
466   if (SubType == NewTy) return false;
467
468   // Differing function types don't require us to merge.  They are not values anyway.
469   if (isa<FunctionType>(SubType) &&
470       isa<FunctionType>(NewTy)) return false;
471
472   unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
473
474   // Ok, we are getting desperate now.  Check for physical subtyping, where we
475   // just require each element in the node to be compatible.
476   if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
477       SubTypeSize && SubTypeSize < 256 && 
478       ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
479     return false;
480
481   // Okay, so we found the leader type at the offset requested.  Search the list
482   // of types that starts at this offset.  If SubType is currently an array or
483   // structure, the type desired may actually be the first element of the
484   // composite type...
485   //
486   unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
487   while (SubType != NewTy) {
488     const Type *NextSubType = 0;
489     unsigned NextSubTypeSize = 0;
490     unsigned NextPadSize = 0;
491     switch (SubType->getPrimitiveID()) {
492     case Type::StructTyID: {
493       const StructType *STy = cast<StructType>(SubType);
494       const StructLayout &SL = *TD.getStructLayout(STy);
495       if (SL.MemberOffsets.size() > 1)
496         NextPadSize = SL.MemberOffsets[1];
497       else
498         NextPadSize = SubTypeSize;
499       NextSubType = STy->getElementType(0);
500       NextSubTypeSize = TD.getTypeSize(NextSubType);
501       break;
502     }
503     case Type::ArrayTyID:
504       NextSubType = cast<ArrayType>(SubType)->getElementType();
505       NextSubTypeSize = TD.getTypeSize(NextSubType);
506       NextPadSize = NextSubTypeSize;
507       break;
508     default: ;
509       // fall out 
510     }
511
512     if (NextSubType == 0)
513       break;   // In the default case, break out of the loop
514
515     if (NextPadSize < NewTySize)
516       break;   // Don't allow shrinking to a smaller type than NewTySize
517     SubType = NextSubType;
518     SubTypeSize = NextSubTypeSize;
519     PadSize = NextPadSize;
520   }
521
522   // If we found the type exactly, return it...
523   if (SubType == NewTy)
524     return false;
525
526   // Check to see if we have a compatible, but different type...
527   if (NewTySize == SubTypeSize) {
528     // Check to see if this type is obviously convertible... int -> uint f.e.
529     if (NewTy->isLosslesslyConvertibleTo(SubType))
530       return false;
531
532     // Check to see if we have a pointer & integer mismatch going on here,
533     // loading a pointer as a long, for example.
534     //
535     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
536         NewTy->isInteger() && isa<PointerType>(SubType))
537       return false;
538   } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
539     // We are accessing the field, plus some structure padding.  Ignore the
540     // structure padding.
541     return false;
542   }
543
544   Module *M = 0;
545   if (getParentGraph()->getReturnNodes().size())
546     M = getParentGraph()->getReturnNodes().begin()->first->getParent();
547   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
548         WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
549         WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
550                   << "SubType: ";
551         WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
552
553   if (FoldIfIncompatible) foldNodeCompletely();
554   return true;
555 }
556
557
558
559 // addEdgeTo - Add an edge from the current node to the specified node.  This
560 // can cause merging of nodes in the graph.
561 //
562 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
563   if (NH.isNull()) return;       // Nothing to do
564
565   DSNodeHandle &ExistingEdge = getLink(Offset);
566   if (!ExistingEdge.isNull()) {
567     // Merge the two nodes...
568     ExistingEdge.mergeWith(NH);
569   } else {                             // No merging to perform...
570     setLink(Offset, NH);               // Just force a link in there...
571   }
572 }
573
574
575 // MergeSortedVectors - Efficiently merge a vector into another vector where
576 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
577 // efficiently copyable and have sane comparison semantics.
578 //
579 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
580                                const std::vector<GlobalValue*> &Src) {
581   // By far, the most common cases will be the simple ones.  In these cases,
582   // avoid having to allocate a temporary vector...
583   //
584   if (Src.empty()) {             // Nothing to merge in...
585     return;
586   } else if (Dest.empty()) {     // Just copy the result in...
587     Dest = Src;
588   } else if (Src.size() == 1) {  // Insert a single element...
589     const GlobalValue *V = Src[0];
590     std::vector<GlobalValue*>::iterator I =
591       std::lower_bound(Dest.begin(), Dest.end(), V);
592     if (I == Dest.end() || *I != Src[0])  // If not already contained...
593       Dest.insert(I, Src[0]);
594   } else if (Dest.size() == 1) {
595     GlobalValue *Tmp = Dest[0];           // Save value in temporary...
596     Dest = Src;                           // Copy over list...
597     std::vector<GlobalValue*>::iterator I =
598       std::lower_bound(Dest.begin(), Dest.end(), Tmp);
599     if (I == Dest.end() || *I != Tmp)     // If not already contained...
600       Dest.insert(I, Tmp);
601
602   } else {
603     // Make a copy to the side of Dest...
604     std::vector<GlobalValue*> Old(Dest);
605     
606     // Make space for all of the type entries now...
607     Dest.resize(Dest.size()+Src.size());
608     
609     // Merge the two sorted ranges together... into Dest.
610     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
611     
612     // Now erase any duplicate entries that may have accumulated into the 
613     // vectors (because they were in both of the input sets)
614     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
615   }
616 }
617
618 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
619   MergeSortedVectors(Globals, RHS);
620 }
621
622 // MergeNodes - Helper function for DSNode::mergeWith().
623 // This function does the hard work of merging two nodes, CurNodeH
624 // and NH after filtering out trivial cases and making sure that
625 // CurNodeH.offset >= NH.offset.
626 // 
627 // ***WARNING***
628 // Since merging may cause either node to go away, we must always
629 // use the node-handles to refer to the nodes.  These node handles are
630 // automatically updated during merging, so will always provide access
631 // to the correct node after a merge.
632 //
633 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
634   assert(CurNodeH.getOffset() >= NH.getOffset() &&
635          "This should have been enforced in the caller.");
636
637   // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
638   // respect to NH.Offset) is now zero.  NOffset is the distance from the base
639   // of our object that N starts from.
640   //
641   unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
642   unsigned NSize = NH.getNode()->getSize();
643
644   // If the two nodes are of different size, and the smaller node has the array
645   // bit set, collapse!
646   if (NSize != CurNodeH.getNode()->getSize()) {
647     if (NSize < CurNodeH.getNode()->getSize()) {
648       if (NH.getNode()->isArray())
649         NH.getNode()->foldNodeCompletely();
650     } else if (CurNodeH.getNode()->isArray()) {
651       NH.getNode()->foldNodeCompletely();
652     }
653   }
654
655   // Merge the type entries of the two nodes together...    
656   if (NH.getNode()->Ty != Type::VoidTy)
657     CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
658   assert(!CurNodeH.getNode()->isDeadNode());
659
660   // If we are merging a node with a completely folded node, then both nodes are
661   // now completely folded.
662   //
663   if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
664     if (!NH.getNode()->isNodeCompletelyFolded()) {
665       NH.getNode()->foldNodeCompletely();
666       assert(NH.getNode() && NH.getOffset() == 0 &&
667              "folding did not make offset 0?");
668       NOffset = NH.getOffset();
669       NSize = NH.getNode()->getSize();
670       assert(NOffset == 0 && NSize == 1);
671     }
672   } else if (NH.getNode()->isNodeCompletelyFolded()) {
673     CurNodeH.getNode()->foldNodeCompletely();
674     assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
675            "folding did not make offset 0?");
676     NOffset = NH.getOffset();
677     NSize = NH.getNode()->getSize();
678     assert(NOffset == 0 && NSize == 1);
679   }
680
681   DSNode *N = NH.getNode();
682   if (CurNodeH.getNode() == N || N == 0) return;
683   assert(!CurNodeH.getNode()->isDeadNode());
684
685   // Merge the NodeType information.
686   CurNodeH.getNode()->NodeType |= N->NodeType;
687
688   // Start forwarding to the new node!
689   N->forwardNode(CurNodeH.getNode(), NOffset);
690   assert(!CurNodeH.getNode()->isDeadNode());
691
692   // Make all of the outgoing links of N now be outgoing links of CurNodeH.
693   //
694   for (unsigned i = 0; i < N->getNumLinks(); ++i) {
695     DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
696     if (Link.getNode()) {
697       // Compute the offset into the current node at which to
698       // merge this link.  In the common case, this is a linear
699       // relation to the offset in the original node (with
700       // wrapping), but if the current node gets collapsed due to
701       // recursive merging, we must make sure to merge in all remaining
702       // links at offset zero.
703       unsigned MergeOffset = 0;
704       DSNode *CN = CurNodeH.getNode();
705       if (CN->Size != 1)
706         MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
707       CN->addEdgeTo(MergeOffset, Link);
708     }
709   }
710
711   // Now that there are no outgoing edges, all of the Links are dead.
712   N->Links.clear();
713
714   // Merge the globals list...
715   if (!N->Globals.empty()) {
716     CurNodeH.getNode()->mergeGlobals(N->Globals);
717
718     // Delete the globals from the old node...
719     std::vector<GlobalValue*>().swap(N->Globals);
720   }
721 }
722
723
724 // mergeWith - Merge this node and the specified node, moving all links to and
725 // from the argument node into the current node, deleting the node argument.
726 // Offset indicates what offset the specified node is to be merged into the
727 // current node.
728 //
729 // The specified node may be a null pointer (in which case, we update it to
730 // point to this node).
731 //
732 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
733   DSNode *N = NH.getNode();
734   if (N == this && NH.getOffset() == Offset)
735     return;  // Noop
736
737   // If the RHS is a null node, make it point to this node!
738   if (N == 0) {
739     NH.mergeWith(DSNodeHandle(this, Offset));
740     return;
741   }
742
743   assert(!N->isDeadNode() && !isDeadNode());
744   assert(!hasNoReferrers() && "Should not try to fold a useless node!");
745
746   if (N == this) {
747     // We cannot merge two pieces of the same node together, collapse the node
748     // completely.
749     DEBUG(std::cerr << "Attempting to merge two chunks of"
750                     << " the same node together!\n");
751     foldNodeCompletely();
752     return;
753   }
754
755   // If both nodes are not at offset 0, make sure that we are merging the node
756   // at an later offset into the node with the zero offset.
757   //
758   if (Offset < NH.getOffset()) {
759     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
760     return;
761   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
762     // If the offsets are the same, merge the smaller node into the bigger node
763     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
764     return;
765   }
766
767   // Ok, now we can merge the two nodes.  Use a static helper that works with
768   // two node handles, since "this" may get merged away at intermediate steps.
769   DSNodeHandle CurNodeH(this, Offset);
770   DSNodeHandle NHCopy(NH);
771   DSNode::MergeNodes(CurNodeH, NHCopy);
772 }
773
774
775 //===----------------------------------------------------------------------===//
776 // ReachabilityCloner Implementation
777 //===----------------------------------------------------------------------===//
778
779 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
780   if (SrcNH.isNull()) return DSNodeHandle();
781   const DSNode *SN = SrcNH.getNode();
782
783   DSNodeHandle &NH = NodeMap[SN];
784   if (!NH.isNull())    // Node already mapped?
785     return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
786
787   DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
788   DN->maskNodeTypes(BitsToKeep);
789   NH = DN;
790   
791   // Next, recursively clone all outgoing links as necessary.  Note that
792   // adding these links can cause the node to collapse itself at any time, and
793   // the current node may be merged with arbitrary other nodes.  For this
794   // reason, we must always go through NH.
795   DN = 0;
796   for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
797     const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
798     if (!SrcEdge.isNull()) {
799       const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
800       // Compute the offset into the current node at which to
801       // merge this link.  In the common case, this is a linear
802       // relation to the offset in the original node (with
803       // wrapping), but if the current node gets collapsed due to
804       // recursive merging, we must make sure to merge in all remaining
805       // links at offset zero.
806       unsigned MergeOffset = 0;
807       DSNode *CN = NH.getNode();
808       if (CN->getSize() != 1)
809         MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
810                        - SrcNH.getOffset()) %CN->getSize();
811       CN->addEdgeTo(MergeOffset, DestEdge);
812     }
813   }
814   
815   // If this node contains any globals, make sure they end up in the scalar
816   // map with the correct offset.
817   for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
818        I != E; ++I) {
819     GlobalValue *GV = *I;
820     const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
821     DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
822     assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
823     Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
824                                        DestGNH.getOffset()+SrcGNH.getOffset()));
825     
826     if (CloneFlags & DSGraph::UpdateInlinedGlobals)
827       Dest.getInlinedGlobals().insert(GV);
828   }
829
830   return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
831 }
832
833 void ReachabilityCloner::merge(const DSNodeHandle &NH,
834                                const DSNodeHandle &SrcNH) {
835   if (SrcNH.isNull()) return;  // Noop
836   if (NH.isNull()) {
837     // If there is no destination node, just clone the source and assign the
838     // destination node to be it.
839     NH.mergeWith(getClonedNH(SrcNH));
840     return;
841   }
842
843   // Okay, at this point, we know that we have both a destination and a source
844   // node that need to be merged.  Check to see if the source node has already
845   // been cloned.
846   const DSNode *SN = SrcNH.getNode();
847   DSNodeHandle &SCNH = NodeMap[SN];  // SourceClonedNodeHandle
848   if (!SCNH.isNull()) {   // Node already cloned?
849     NH.mergeWith(DSNodeHandle(SCNH.getNode(),
850                               SCNH.getOffset()+SrcNH.getOffset()));
851
852     return;  // Nothing to do!
853   }
854
855   // Okay, so the source node has not already been cloned.  Instead of creating
856   // a new DSNode, only to merge it into the one we already have, try to perform
857   // the merge in-place.  The only case we cannot handle here is when the offset
858   // into the existing node is less than the offset into the virtual node we are
859   // merging in.  In this case, we have to extend the existing node, which
860   // requires an allocation anyway.
861   DSNode *DN = NH.getNode();   // Make sure the Offset is up-to-date
862   if (NH.getOffset() >= SrcNH.getOffset()) {
863     if (!DN->isNodeCompletelyFolded()) {
864       // Make sure the destination node is folded if the source node is folded.
865       if (SN->isNodeCompletelyFolded()) {
866         DN->foldNodeCompletely();
867         DN = NH.getNode();
868       } else if (SN->getSize() != DN->getSize()) {
869         // If the two nodes are of different size, and the smaller node has the
870         // array bit set, collapse!
871         if (SN->getSize() < DN->getSize()) {
872           if (SN->isArray()) {
873             DN->foldNodeCompletely();
874             DN = NH.getNode();
875           }
876         } else if (DN->isArray()) {
877           DN->foldNodeCompletely();
878           DN = NH.getNode();
879         }
880       }
881     
882       // Merge the type entries of the two nodes together...    
883       if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
884         DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
885         DN = NH.getNode();
886       }
887     }
888
889     assert(!DN->isDeadNode());
890     
891     // Merge the NodeType information.
892     DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
893
894     // Before we start merging outgoing links and updating the scalar map, make
895     // sure it is known that this is the representative node for the src node.
896     SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
897
898     // If the source node contains any globals, make sure they end up in the
899     // scalar map with the correct offset.
900     if (SN->global_begin() != SN->global_end()) {
901       // Update the globals in the destination node itself.
902       DN->mergeGlobals(SN->getGlobals());
903
904       // Update the scalar map for the graph we are merging the source node
905       // into.
906       for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
907            I != E; ++I) {
908         GlobalValue *GV = *I;
909         const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
910         DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
911         assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
912         Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
913                                       DestGNH.getOffset()+SrcGNH.getOffset()));
914         
915         if (CloneFlags & DSGraph::UpdateInlinedGlobals)
916           Dest.getInlinedGlobals().insert(GV);
917       }
918     }
919   } else {
920     // We cannot handle this case without allocating a temporary node.  Fall
921     // back on being simple.
922     DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
923     NewDN->maskNodeTypes(BitsToKeep);
924
925     unsigned NHOffset = NH.getOffset();
926     NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
927
928     assert(NH.getNode() &&
929            (NH.getOffset() > NHOffset ||
930             (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
931            "Merging did not adjust the offset!");
932
933     // Before we start merging outgoing links and updating the scalar map, make
934     // sure it is known that this is the representative node for the src node.
935     SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
936
937     // If the source node contained any globals, make sure to create entries 
938     // in the scalar map for them!
939     for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
940          I != E; ++I) {
941       GlobalValue *GV = *I;
942       const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
943       DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
944       assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
945       assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
946       Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
947                                     DestGNH.getOffset()+SrcGNH.getOffset()));
948       
949       if (CloneFlags & DSGraph::UpdateInlinedGlobals)
950         Dest.getInlinedGlobals().insert(GV);
951     }
952   }
953
954
955   // Next, recursively merge all outgoing links as necessary.  Note that
956   // adding these links can cause the destination node to collapse itself at
957   // any time, and the current node may be merged with arbitrary other nodes.
958   // For this reason, we must always go through NH.
959   DN = 0;
960   for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
961     const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
962     if (!SrcEdge.isNull()) {
963       // Compute the offset into the current node at which to
964       // merge this link.  In the common case, this is a linear
965       // relation to the offset in the original node (with
966       // wrapping), but if the current node gets collapsed due to
967       // recursive merging, we must make sure to merge in all remaining
968       // links at offset zero.
969       unsigned MergeOffset = 0;
970       DSNode *CN = SCNH.getNode();
971       if (CN->getSize() != 1)
972         MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
973       
974       DSNodeHandle &Link = CN->getLink(MergeOffset);
975       if (!Link.isNull()) {
976         // Perform the recursive merging.  Make sure to create a temporary NH,
977         // because the Link can disappear in the process of recursive merging.
978         DSNodeHandle Tmp = Link;
979         merge(Tmp, SrcEdge);
980       } else {
981         merge(Link, SrcEdge);
982       }
983     }
984   }
985 }
986
987 /// mergeCallSite - Merge the nodes reachable from the specified src call
988 /// site into the nodes reachable from DestCS.
989 void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
990                                        const DSCallSite &SrcCS) {
991   merge(DestCS.getRetVal(), SrcCS.getRetVal());
992   unsigned MinArgs = DestCS.getNumPtrArgs();
993   if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
994   
995   for (unsigned a = 0; a != MinArgs; ++a)
996     merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
997 }
998
999
1000 //===----------------------------------------------------------------------===//
1001 // DSCallSite Implementation
1002 //===----------------------------------------------------------------------===//
1003
1004 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1005 Function &DSCallSite::getCaller() const {
1006   return *Site.getInstruction()->getParent()->getParent();
1007 }
1008
1009 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1010                         ReachabilityCloner &RC) {
1011   NH = RC.getClonedNH(Src);
1012 }
1013
1014 //===----------------------------------------------------------------------===//
1015 // DSGraph Implementation
1016 //===----------------------------------------------------------------------===//
1017
1018 /// getFunctionNames - Return a space separated list of the name of the
1019 /// functions in this graph (if any)
1020 std::string DSGraph::getFunctionNames() const {
1021   switch (getReturnNodes().size()) {
1022   case 0: return "Globals graph";
1023   case 1: return getReturnNodes().begin()->first->getName();
1024   default:
1025     std::string Return;
1026     for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1027          I != getReturnNodes().end(); ++I)
1028       Return += I->first->getName() + " ";
1029     Return.erase(Return.end()-1, Return.end());   // Remove last space character
1030     return Return;
1031   }
1032 }
1033
1034
1035 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
1036   PrintAuxCalls = false;
1037   NodeMapTy NodeMap;
1038   cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1039 }
1040
1041 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
1042   : GlobalsGraph(0), TD(G.TD) {
1043   PrintAuxCalls = false;
1044   cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1045 }
1046
1047 DSGraph::~DSGraph() {
1048   FunctionCalls.clear();
1049   AuxFunctionCalls.clear();
1050   InlinedGlobals.clear();
1051   ScalarMap.clear();
1052   ReturnNodes.clear();
1053
1054   // Drop all intra-node references, so that assertions don't fail...
1055   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1056     (*NI)->dropAllReferences();
1057
1058   // Free all of the nodes.
1059   Nodes.clear();
1060 }
1061
1062 // dump - Allow inspection of graph in a debugger.
1063 void DSGraph::dump() const { print(std::cerr); }
1064
1065
1066 /// remapLinks - Change all of the Links in the current node according to the
1067 /// specified mapping.
1068 ///
1069 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1070   for (unsigned i = 0, e = Links.size(); i != e; ++i)
1071     if (DSNode *N = Links[i].getNode()) {
1072       DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1073       if (ONMI != OldNodeMap.end()) {
1074         Links[i].setNode(ONMI->second.getNode());
1075         Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1076       }
1077     }
1078 }
1079
1080 /// updateFromGlobalGraph - This function rematerializes global nodes and
1081 /// nodes reachable from them from the globals graph into the current graph.
1082 /// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1083 /// are already up-to-date in the current graph.  In practice, in the TD pass,
1084 /// this is likely to be a large fraction of the live global nodes in each
1085 /// function (since most live nodes are likely to have been brought up-to-date
1086 /// in at _some_ caller or callee).
1087 /// 
1088 void DSGraph::updateFromGlobalGraph() {
1089   TIME_REGION(X, "updateFromGlobalGraph");
1090   ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1091
1092   // Clone the non-up-to-date global nodes into this graph.
1093   for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1094          E = getScalarMap().global_end(); I != E; ++I)
1095     if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
1096       DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
1097       if (It != GlobalsGraph->ScalarMap.end())
1098         RC.merge(getNodeForValue(*I), It->second);
1099     }
1100 }
1101
1102 /// cloneInto - Clone the specified DSGraph into the current graph.  The
1103 /// translated ScalarMap for the old function is filled into the OldValMap
1104 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
1105 ///
1106 /// The CloneFlags member controls various aspects of the cloning process.
1107 ///
1108 void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
1109                         ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1110                         unsigned CloneFlags) {
1111   TIME_REGION(X, "cloneInto");
1112   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1113   assert(&G != this && "Cannot clone graph into itself!");
1114
1115   // Remove alloca or mod/ref bits as specified...
1116   unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1117     | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1118     | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1119   BitsToClear |= DSNode::DEAD;  // Clear dead flag...
1120
1121   for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1122     assert(!(*I)->isForwarding() &&
1123            "Forward nodes shouldn't be in node list!");
1124     DSNode *New = new DSNode(**I, this);
1125     New->maskNodeTypes(~BitsToClear);
1126     OldNodeMap[*I] = New;
1127   }
1128   
1129 #ifndef NDEBUG
1130   Timer::addPeakMemoryMeasurement();
1131 #endif
1132   
1133   // Rewrite the links in the new nodes to point into the current graph now.
1134   // Note that we don't loop over the node's list to do this.  The problem is
1135   // that remaping links can cause recursive merging to happen, which means
1136   // that node_iterator's can get easily invalidated!  Because of this, we
1137   // loop over the OldNodeMap, which contains all of the new nodes as the
1138   // .second element of the map elements.  Also note that if we remap a node
1139   // more than once, we won't break anything.
1140   for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1141        I != E; ++I)
1142     I->second.getNode()->remapLinks(OldNodeMap);
1143
1144   // Copy the scalar map... merging all of the global nodes...
1145   for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1146          E = G.ScalarMap.end(); I != E; ++I) {
1147     DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1148     DSNodeHandle &H = OldValMap[I->first];
1149     H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1150                              I->second.getOffset()+MappedNode.getOffset()));
1151
1152     // If this is a global, add the global to this fn or merge if already exists
1153     if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1154       ScalarMap[GV].mergeWith(H);
1155       if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1156         InlinedGlobals.insert(GV);
1157     }
1158   }
1159
1160   if (!(CloneFlags & DontCloneCallNodes)) {
1161     // Copy the function calls list...
1162     unsigned FC = FunctionCalls.size();  // FirstCall
1163     FunctionCalls.reserve(FC+G.FunctionCalls.size());
1164     for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1165       FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1166   }
1167
1168   if (!(CloneFlags & DontCloneAuxCallNodes)) {
1169     // Copy the auxiliary function calls list...
1170     unsigned FC = AuxFunctionCalls.size();  // FirstCall
1171     AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1172     for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1173       AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1174   }
1175
1176   // Map the return node pointers over...
1177   for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1178          E = G.getReturnNodes().end(); I != E; ++I) {
1179     const DSNodeHandle &Ret = I->second;
1180     DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1181     OldReturnNodes.insert(std::make_pair(I->first,
1182                           DSNodeHandle(MappedRet.getNode(),
1183                                        MappedRet.getOffset()+Ret.getOffset())));
1184   }
1185 }
1186
1187
1188 /// mergeInGraph - The method is used for merging graphs together.  If the
1189 /// argument graph is not *this, it makes a clone of the specified graph, then
1190 /// merges the nodes specified in the call site with the formal arguments in the
1191 /// graph.
1192 ///
1193 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1194                            const DSGraph &Graph, unsigned CloneFlags) {
1195   TIME_REGION(X, "mergeInGraph");
1196
1197   // If this is not a recursive call, clone the graph into this graph...
1198   if (&Graph != this) {
1199     // Clone the callee's graph into the current graph, keeping track of where
1200     // scalars in the old graph _used_ to point, and of the new nodes matching
1201     // nodes of the old graph.
1202     ReachabilityCloner RC(*this, Graph, CloneFlags);
1203     
1204     // Set up argument bindings
1205     Function::aiterator AI = F.abegin();
1206     for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1207       // Advance the argument iterator to the first pointer argument...
1208       while (AI != F.aend() && !isPointerType(AI->getType())) {
1209         ++AI;
1210 #ifndef NDEBUG  // FIXME: We should merge vararg arguments!
1211         if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1212           std::cerr << "Bad call to Function: " << F.getName() << "\n";
1213 #endif
1214       }
1215       if (AI == F.aend()) break;
1216       
1217       // Add the link from the argument scalar to the provided value.
1218       RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
1219     }
1220     
1221     // Map the return node pointer over.
1222     if (!CS.getRetVal().isNull())
1223       RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1224     
1225     // If requested, copy the calls or aux-calls lists.
1226     if (!(CloneFlags & DontCloneCallNodes)) {
1227       // Copy the function calls list...
1228       FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1229       for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1230         FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1231     }
1232     
1233     if (!(CloneFlags & DontCloneAuxCallNodes)) {
1234       // Copy the auxiliary function calls list...
1235       AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1236                                Graph.AuxFunctionCalls.size());
1237       for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1238         AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1239     }
1240     
1241     // If the user requested it, add the nodes that we need to clone to the
1242     // RootNodes set.
1243     if (!EnableDSNodeGlobalRootsHack)
1244       // FIXME: Why is this not iterating over the globals in the graph??
1245       for (node_iterator NI = Graph.node_begin(), E = Graph.node_end();
1246            NI != E; ++NI)
1247         if (!(*NI)->getGlobals().empty())
1248           RC.getClonedNH(*NI);
1249                                                  
1250   } else {
1251     DSNodeHandle RetVal = getReturnNodeFor(F);
1252
1253     // Merge the return value with the return value of the context...
1254     RetVal.mergeWith(CS.getRetVal());
1255     
1256     // Resolve all of the function arguments...
1257     Function::aiterator AI = F.abegin();
1258     
1259     for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1260       // Advance the argument iterator to the first pointer argument...
1261       while (AI != F.aend() && !isPointerType(AI->getType())) {
1262         ++AI;
1263 #ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1264         if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1265           std::cerr << "Bad call to Function: " << F.getName() << "\n";
1266 #endif
1267       }
1268       if (AI == F.aend()) break;
1269       
1270       // Add the link from the argument scalar to the provided value
1271       DSNodeHandle &NH = getNodeForValue(AI);
1272       assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1273       NH.mergeWith(CS.getPtrArg(i));
1274     }
1275   }
1276 }
1277
1278 /// getCallSiteForArguments - Get the arguments and return value bindings for
1279 /// the specified function in the current graph.
1280 ///
1281 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1282   std::vector<DSNodeHandle> Args;
1283
1284   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1285     if (isPointerType(I->getType()))
1286       Args.push_back(getNodeForValue(I));
1287
1288   return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1289 }
1290
1291
1292
1293 // markIncompleteNodes - Mark the specified node as having contents that are not
1294 // known with the current analysis we have performed.  Because a node makes all
1295 // of the nodes it can reach incomplete if the node itself is incomplete, we
1296 // must recursively traverse the data structure graph, marking all reachable
1297 // nodes as incomplete.
1298 //
1299 static void markIncompleteNode(DSNode *N) {
1300   // Stop recursion if no node, or if node already marked...
1301   if (N == 0 || N->isIncomplete()) return;
1302
1303   // Actually mark the node
1304   N->setIncompleteMarker();
1305
1306   // Recursively process children...
1307   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1308     if (DSNode *DSN = N->getLink(i).getNode())
1309       markIncompleteNode(DSN);
1310 }
1311
1312 static void markIncomplete(DSCallSite &Call) {
1313   // Then the return value is certainly incomplete!
1314   markIncompleteNode(Call.getRetVal().getNode());
1315
1316   // All objects pointed to by function arguments are incomplete!
1317   for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1318     markIncompleteNode(Call.getPtrArg(i).getNode());
1319 }
1320
1321 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1322 // modified by other functions that have not been resolved yet.  This marks
1323 // nodes that are reachable through three sources of "unknownness":
1324 //
1325 //  Global Variables, Function Calls, and Incoming Arguments
1326 //
1327 // For any node that may have unknown components (because something outside the
1328 // scope of current analysis may have modified it), the 'Incomplete' flag is
1329 // added to the NodeType.
1330 //
1331 void DSGraph::markIncompleteNodes(unsigned Flags) {
1332   // Mark any incoming arguments as incomplete...
1333   if (Flags & DSGraph::MarkFormalArgs)
1334     for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1335          FI != E; ++FI) {
1336       Function &F = *FI->first;
1337       if (F.getName() != "main")
1338         for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1339           if (isPointerType(I->getType()))
1340             markIncompleteNode(getNodeForValue(I).getNode());
1341     }
1342
1343   // Mark stuff passed into functions calls as being incomplete...
1344   if (!shouldPrintAuxCalls())
1345     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1346       markIncomplete(FunctionCalls[i]);
1347   else
1348     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1349       markIncomplete(AuxFunctionCalls[i]);
1350     
1351
1352   // Mark all global nodes as incomplete...
1353   if ((Flags & DSGraph::IgnoreGlobals) == 0)
1354     for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1355       if ((*NI)->isGlobalNode() && (*NI)->getNumLinks())
1356         markIncompleteNode(*NI);
1357 }
1358
1359 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1360   if (DSNode *N = Edge.getNode())  // Is there an edge?
1361     if (N->getNumReferrers() == 1)  // Does it point to a lonely node?
1362       // No interesting info?
1363       if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1364           N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1365         Edge.setNode(0);  // Kill the edge!
1366 }
1367
1368 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1369   const std::vector<GlobalValue*> &Globals = N->getGlobals();
1370   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1371     if (Globals[i]->isExternal())
1372       return true;
1373   return false;
1374 }
1375
1376 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1377   // Remove trivially identical function calls
1378   unsigned NumFns = Calls.size();
1379   std::sort(Calls.begin(), Calls.end());  // Sort by callee as primary key!
1380
1381 #if 1
1382   // Scan the call list cleaning it up as necessary...
1383   DSNode   *LastCalleeNode = 0;
1384   Function *LastCalleeFunc = 0;
1385   unsigned NumDuplicateCalls = 0;
1386   bool LastCalleeContainsExternalFunction = false;
1387   for (unsigned i = 0; i != Calls.size(); ++i) {
1388     DSCallSite &CS = Calls[i];
1389
1390     // If the Callee is a useless edge, this must be an unreachable call site,
1391     // eliminate it.
1392     if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1393         CS.getCalleeNode()->getNodeFlags() == 0) {  // No useful info?
1394 #ifndef NDEBUG
1395       std::cerr << "WARNING: Useless call site found??\n";
1396 #endif
1397       CS.swap(Calls.back());
1398       Calls.pop_back();
1399       --i;
1400     } else {
1401       // If the return value or any arguments point to a void node with no
1402       // information at all in it, and the call node is the only node to point
1403       // to it, remove the edge to the node (killing the node).
1404       //
1405       killIfUselessEdge(CS.getRetVal());
1406       for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1407         killIfUselessEdge(CS.getPtrArg(a));
1408       
1409       // If this call site calls the same function as the last call site, and if
1410       // the function pointer contains an external function, this node will
1411       // never be resolved.  Merge the arguments of the call node because no
1412       // information will be lost.
1413       //
1414       if ((CS.isDirectCall()   && CS.getCalleeFunc() == LastCalleeFunc) ||
1415           (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1416         ++NumDuplicateCalls;
1417         if (NumDuplicateCalls == 1) {
1418           if (LastCalleeNode)
1419             LastCalleeContainsExternalFunction =
1420               nodeContainsExternalFunction(LastCalleeNode);
1421           else
1422             LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1423         }
1424      
1425         // It is not clear why, but enabling this code makes DSA really
1426         // sensitive to node forwarding.  Basically, with this enabled, DSA
1427         // performs different number of inlinings based on which nodes are
1428         // forwarding or not.  This is clearly a problem, so this code is
1429         // disabled until this can be resolved.
1430 #if 1
1431         if (LastCalleeContainsExternalFunction
1432 #if 0
1433             ||
1434             // This should be more than enough context sensitivity!
1435             // FIXME: Evaluate how many times this is tripped!
1436             NumDuplicateCalls > 20
1437 #endif
1438             ) {
1439           DSCallSite &OCS = Calls[i-1];
1440           OCS.mergeWith(CS);
1441           
1442           // The node will now be eliminated as a duplicate!
1443           if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1444             CS = OCS;
1445           else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1446             OCS = CS;
1447         }
1448 #endif
1449       } else {
1450         if (CS.isDirectCall()) {
1451           LastCalleeFunc = CS.getCalleeFunc();
1452           LastCalleeNode = 0;
1453         } else {
1454           LastCalleeNode = CS.getCalleeNode();
1455           LastCalleeFunc = 0;
1456         }
1457         NumDuplicateCalls = 0;
1458       }
1459     }
1460   }
1461 #endif
1462   Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1463
1464   // Track the number of call nodes merged away...
1465   NumCallNodesMerged += NumFns-Calls.size();
1466
1467   DEBUG(if (NumFns != Calls.size())
1468           std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1469 }
1470
1471
1472 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1473 // removes all unreachable nodes that are created because they got merged with
1474 // other nodes in the graph.  These nodes will all be trivially unreachable, so
1475 // we don't have to perform any non-trivial analysis here.
1476 //
1477 void DSGraph::removeTriviallyDeadNodes() {
1478   TIME_REGION(X, "removeTriviallyDeadNodes");
1479
1480   // Loop over all of the nodes in the graph, calling getNode on each field.
1481   // This will cause all nodes to update their forwarding edges, causing
1482   // forwarded nodes to be delete-able.
1483   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1484     DSNode *N = *NI;
1485     for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1486       N->getLink(l*N->getPointerSize()).getNode();
1487   }
1488
1489   // NOTE: This code is disabled.  Though it should, in theory, allow us to
1490   // remove more nodes down below, the scan of the scalar map is incredibly
1491   // expensive for certain programs (with large SCCs).  In the future, if we can
1492   // make the scalar map scan more efficient, then we can reenable this.
1493 #if 0
1494   { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1495
1496   // Likewise, forward any edges from the scalar nodes.  While we are at it,
1497   // clean house a bit.
1498   for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1499     I->second.getNode();
1500     ++I;
1501   }
1502   }
1503 #endif
1504   bool isGlobalsGraph = !GlobalsGraph;
1505
1506   for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1507     DSNode &Node = *NI;
1508
1509     // Do not remove *any* global nodes in the globals graph.
1510     // This is a special case because such nodes may not have I, M, R flags set.
1511     if (Node.isGlobalNode() && isGlobalsGraph) {
1512       ++NI;
1513       continue;
1514     }
1515
1516     if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1517       // This is a useless node if it has no mod/ref info (checked above),
1518       // outgoing edges (which it cannot, as it is not modified in this
1519       // context), and it has no incoming edges.  If it is a global node it may
1520       // have all of these properties and still have incoming edges, due to the
1521       // scalar map, so we check those now.
1522       //
1523       if (Node.getNumReferrers() == Node.getGlobals().size()) {
1524         const std::vector<GlobalValue*> &Globals = Node.getGlobals();
1525
1526         // Loop through and make sure all of the globals are referring directly
1527         // to the node...
1528         for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1529           DSNode *N = getNodeForValue(Globals[j]).getNode();
1530           assert(N == &Node && "ScalarMap doesn't match globals list!");
1531         }
1532
1533         // Make sure NumReferrers still agrees, if so, the node is truly dead.
1534         if (Node.getNumReferrers() == Globals.size()) {
1535           for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1536             ScalarMap.erase(Globals[j]);
1537           Node.makeNodeDead();
1538           ++NumTrivialGlobalDNE;
1539         }
1540       }
1541     }
1542
1543     if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1544       // This node is dead!
1545       NI = Nodes.erase(NI);    // Erase & remove from node list.
1546       ++NumTrivialDNE;
1547     } else {
1548       ++NI;
1549     }
1550   }
1551
1552   removeIdenticalCalls(FunctionCalls);
1553   removeIdenticalCalls(AuxFunctionCalls);
1554 }
1555
1556
1557 /// markReachableNodes - This method recursively traverses the specified
1558 /// DSNodes, marking any nodes which are reachable.  All reachable nodes it adds
1559 /// to the set, which allows it to only traverse visited nodes once.
1560 ///
1561 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1562   if (this == 0) return;
1563   assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1564   if (ReachableNodes.insert(this).second)        // Is newly reachable?
1565     for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1566       getLink(i).getNode()->markReachableNodes(ReachableNodes);
1567 }
1568
1569 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1570   getRetVal().getNode()->markReachableNodes(Nodes);
1571   if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1572   
1573   for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1574     getPtrArg(i).getNode()->markReachableNodes(Nodes);
1575 }
1576
1577 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1578 // looking for a node that is marked alive.  If an alive node is found, return
1579 // true, otherwise return false.  If an alive node is reachable, this node is
1580 // marked as alive...
1581 //
1582 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1583                                hash_set<DSNode*> &Visited,
1584                                bool IgnoreGlobals) {
1585   if (N == 0) return false;
1586   assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1587
1588   // If this is a global node, it will end up in the globals graph anyway, so we
1589   // don't need to worry about it.
1590   if (IgnoreGlobals && N->isGlobalNode()) return false;
1591
1592   // If we know that this node is alive, return so!
1593   if (Alive.count(N)) return true;
1594
1595   // Otherwise, we don't think the node is alive yet, check for infinite
1596   // recursion.
1597   if (Visited.count(N)) return false;  // Found a cycle
1598   Visited.insert(N);   // No recursion, insert into Visited...
1599
1600   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1601     if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1602                            IgnoreGlobals)) {
1603       N->markReachableNodes(Alive);
1604       return true;
1605     }
1606   return false;
1607 }
1608
1609 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1610 // alive nodes.
1611 //
1612 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1613                                   hash_set<DSNode*> &Visited,
1614                                   bool IgnoreGlobals) {
1615   if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1616                          IgnoreGlobals))
1617     return true;
1618   if (CS.isIndirectCall() &&
1619       CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1620     return true;
1621   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1622     if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1623                            IgnoreGlobals))
1624       return true;
1625   return false;
1626 }
1627
1628 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1629 // subgraphs that are unreachable.  This often occurs because the data
1630 // structure doesn't "escape" into it's caller, and thus should be eliminated
1631 // from the caller's graph entirely.  This is only appropriate to use when
1632 // inlining graphs.
1633 //
1634 void DSGraph::removeDeadNodes(unsigned Flags) {
1635   DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1636
1637   // Reduce the amount of work we have to do... remove dummy nodes left over by
1638   // merging...
1639   removeTriviallyDeadNodes();
1640
1641   TIME_REGION(X, "removeDeadNodes");
1642
1643   // FIXME: Merge non-trivially identical call nodes...
1644
1645   // Alive - a set that holds all nodes found to be reachable/alive.
1646   hash_set<DSNode*> Alive;
1647   std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1648
1649   // Copy and merge all information about globals to the GlobalsGraph if this is
1650   // not a final pass (where unreachable globals are removed).
1651   //
1652   // Strip all alloca bits since the current function is only for the BU pass.
1653   // Strip all incomplete bits since they are short-lived properties and they
1654   // will be correctly computed when rematerializing nodes into the functions.
1655   //
1656   ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1657                               DSGraph::StripIncompleteBit);
1658
1659   // Mark all nodes reachable by (non-global) scalar nodes as alive...
1660   { TIME_REGION(Y, "removeDeadNodes:scalarscan");
1661   for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1662     if (isa<GlobalValue>(I->first)) {             // Keep track of global nodes
1663       assert(I->second.getNode() && "Null global node?");
1664       assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1665       GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1666
1667       // Make sure that all globals are cloned over as roots.
1668       if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1669         DSGraph::ScalarMapTy::iterator SMI = 
1670           GlobalsGraph->getScalarMap().find(I->first);
1671         if (SMI != GlobalsGraph->getScalarMap().end())
1672           GGCloner.merge(SMI->second, I->second);
1673         else
1674           GGCloner.getClonedNH(I->second);
1675       }
1676       ++I;
1677     } else {
1678       DSNode *N = I->second.getNode();
1679 #if 0
1680       // Check to see if this is a worthless node generated for non-pointer
1681       // values, such as integers.  Consider an addition of long types: A+B.
1682       // Assuming we can track all uses of the value in this context, and it is
1683       // NOT used as a pointer, we can delete the node.  We will be able to
1684       // detect this situation if the node pointed to ONLY has Unknown bit set
1685       // in the node.  In this case, the node is not incomplete, does not point
1686       // to any other nodes (no mod/ref bits set), and is therefore
1687       // uninteresting for data structure analysis.  If we run across one of
1688       // these, prune the scalar pointing to it.
1689       //
1690       if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1691         ScalarMap.erase(I++);
1692       else {
1693 #endif
1694         N->markReachableNodes(Alive);
1695         ++I;
1696       //}
1697     }
1698   }
1699
1700   // The return values are alive as well.
1701   for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1702        I != E; ++I)
1703     I->second.getNode()->markReachableNodes(Alive);
1704
1705   // Mark any nodes reachable by primary calls as alive...
1706   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1707     FunctionCalls[i].markReachableNodes(Alive);
1708
1709
1710   // Now find globals and aux call nodes that are already live or reach a live
1711   // value (which makes them live in turn), and continue till no more are found.
1712   // 
1713   bool Iterate;
1714   hash_set<DSNode*> Visited;
1715   std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1716   do {
1717     Visited.clear();
1718     // If any global node points to a non-global that is "alive", the global is
1719     // "alive" as well...  Remove it from the GlobalNodes list so we only have
1720     // unreachable globals in the list.
1721     //
1722     Iterate = false;
1723     if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1724       for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1725         if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited, 
1726                                Flags & DSGraph::RemoveUnreachableGlobals)) {
1727           std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1728           GlobalNodes.pop_back();                          // erase efficiently
1729           Iterate = true;
1730         }
1731
1732     // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1733     // call nodes that get resolved will be difficult to remove from that graph.
1734     // The final unresolved call nodes must be handled specially at the end of
1735     // the BU pass (i.e., in main or other roots of the call graph).
1736     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1737       if (!AuxFCallsAlive[i] &&
1738           (AuxFunctionCalls[i].isIndirectCall()
1739            || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1740                                   Flags & DSGraph::RemoveUnreachableGlobals))) {
1741         AuxFunctionCalls[i].markReachableNodes(Alive);
1742         AuxFCallsAlive[i] = true;
1743         Iterate = true;
1744       }
1745   } while (Iterate);
1746
1747   // Move dead aux function calls to the end of the list
1748   unsigned CurIdx = 0;
1749   for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1750     if (AuxFCallsAlive[i])
1751       AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1752
1753   // Copy and merge all global nodes and dead aux call nodes into the
1754   // GlobalsGraph, and all nodes reachable from those nodes
1755   // 
1756   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1757     // Copy the unreachable call nodes to the globals graph, updating their
1758     // target pointers using the GGCloner
1759     for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1760       GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1761                                                           GGCloner));
1762   }
1763   // Crop all the useless ones out...
1764   AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1765                          AuxFunctionCalls.end());
1766
1767   // We are finally done with the GGCloner so we can destroy it.
1768   GGCloner.destroy();
1769
1770   // At this point, any nodes which are visited, but not alive, are nodes
1771   // which can be removed.  Loop over all nodes, eliminating completely
1772   // unreachable nodes.
1773   //
1774   std::vector<DSNode*> DeadNodes;
1775   DeadNodes.reserve(Nodes.size());
1776   for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;)
1777     if (!Alive.count(NI)) {
1778       ++NumDNE;
1779       DSNode *N = Nodes.remove(NI++);
1780       DeadNodes.push_back(N);
1781       N->dropAllReferences();
1782     } else {
1783       assert(NI->getForwardNode() == 0 && "Alive forwarded node?");
1784       ++NI;
1785     }
1786
1787   // Remove all unreachable globals from the ScalarMap.
1788   // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1789   // In either case, the dead nodes will not be in the set Alive.
1790   for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1791     if (!Alive.count(GlobalNodes[i].second))
1792       ScalarMap.erase(GlobalNodes[i].first);
1793     else
1794       assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
1795
1796   // Delete all dead nodes now since their referrer counts are zero.
1797   for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1798     delete DeadNodes[i];
1799
1800   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1801 }
1802
1803 void DSGraph::AssertGraphOK() const {
1804   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1805     (*NI)->assertOK();
1806
1807   for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1808          E = ScalarMap.end(); I != E; ++I) {
1809     assert(I->second.getNode() && "Null node in scalarmap!");
1810     AssertNodeInGraph(I->second.getNode());
1811     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1812       assert(I->second.getNode()->isGlobalNode() &&
1813              "Global points to node, but node isn't global?");
1814       AssertNodeContainsGlobal(I->second.getNode(), GV);
1815     }
1816   }
1817   AssertCallNodesInGraph();
1818   AssertAuxCallNodesInGraph();
1819 }
1820
1821 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1822 /// nodes reachable from the two graphs, computing the mapping of nodes from
1823 /// the first to the second graph.
1824 ///
1825 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
1826                                  const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1827                                  bool StrictChecking) {
1828   DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1829   if (N1 == 0 || N2 == 0) return;
1830
1831   DSNodeHandle &Entry = NodeMap[N1];
1832   if (Entry.getNode()) {
1833     // Termination of recursion!
1834     assert(!StrictChecking ||
1835            (Entry.getNode() == N2 &&
1836             Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
1837            "Inconsistent mapping detected!");
1838     return;
1839   }
1840   
1841   Entry.setNode(N2);
1842   Entry.setOffset(NH2.getOffset()-NH1.getOffset());
1843
1844   // Loop over all of the fields that N1 and N2 have in common, recursively
1845   // mapping the edges together now.
1846   int N2Idx = NH2.getOffset()-NH1.getOffset();
1847   unsigned N2Size = N2->getSize();
1848   for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1849     if (unsigned(N2Idx)+i < N2Size)
1850       computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1851 }