c3d1705e3501459593b3bb80e8a0fc296d73ffc7
[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/DataStructure/DSGraphTraits.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SCCIterator.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Timer.h"
29 #include <algorithm>
30 using namespace llvm;
31
32 #define COLLAPSE_ARRAYS_AGGRESSIVELY 0
33
34 namespace {
35   Statistic<> NumFolds          ("dsa", "Number of nodes completely folded");
36   Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
37   Statistic<> NumNodeAllocated  ("dsa", "Number of nodes allocated");
38   Statistic<> NumDNE            ("dsa", "Number of nodes removed by reachability");
39   Statistic<> NumTrivialDNE     ("dsa", "Number of nodes trivially removed");
40   Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
41 };
42
43 #if 0
44 #define TIME_REGION(VARNAME, DESC) \
45    NamedRegionTimer VARNAME(DESC)
46 #else
47 #define TIME_REGION(VARNAME, DESC)
48 #endif
49
50 using namespace DS;
51
52 /// isForwarding - Return true if this NodeHandle is forwarding to another
53 /// one.
54 bool DSNodeHandle::isForwarding() const {
55   return N && N->isForwarding();
56 }
57
58 DSNode *DSNodeHandle::HandleForwarding() const {
59   assert(N->isForwarding() && "Can only be invoked if forwarding!");
60
61   // Handle node forwarding here!
62   DSNode *Next = N->ForwardNH.getNode();  // Cause recursive shrinkage
63   Offset += N->ForwardNH.getOffset();
64
65   if (--N->NumReferrers == 0) {
66     // Removing the last referrer to the node, sever the forwarding link
67     N->stopForwarding();
68   }
69
70   N = Next;
71   N->NumReferrers++;
72   if (N->Size <= Offset) {
73     assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
74     Offset = 0;
75   }
76   return N;
77 }
78
79 //===----------------------------------------------------------------------===//
80 // DSScalarMap Implementation
81 //===----------------------------------------------------------------------===//
82
83 DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
84   assert(ValueMap.count(GV) == 0 && "GV already exists!");
85
86   // If the node doesn't exist, check to see if it's a global that is
87   // equated to another global in the program.
88   EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
89   if (ECI != GlobalECs.end()) {
90     GlobalValue *Leader = *GlobalECs.findLeader(ECI);
91     if (Leader != GV) {
92       GV = Leader;
93       iterator I = ValueMap.find(GV);
94       if (I != ValueMap.end())
95         return I->second;
96     }
97   }
98   
99   // Okay, this is either not an equivalenced global or it is the leader, it
100   // will be inserted into the scalar map now.
101   GlobalSet.insert(GV);
102
103   return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
104 }
105
106
107 //===----------------------------------------------------------------------===//
108 // DSNode Implementation
109 //===----------------------------------------------------------------------===//
110
111 DSNode::DSNode(const Type *T, DSGraph *G)
112   : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
113   // Add the type entry if it is specified...
114   if (T) mergeTypeInfo(T, 0);
115   if (G) G->addNode(this);
116   ++NumNodeAllocated;
117 }
118
119 // DSNode copy constructor... do not copy over the referrers list!
120 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
121   : NumReferrers(0), Size(N.Size), ParentGraph(G),
122     Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
123   if (!NullLinks) {
124     Links = N.Links;
125   } else
126     Links.resize(N.Links.size()); // Create the appropriate number of null links
127   G->addNode(this);
128   ++NumNodeAllocated;
129 }
130
131 /// getTargetData - Get the target data object used to construct this node.
132 ///
133 const TargetData &DSNode::getTargetData() const {
134   return ParentGraph->getTargetData();
135 }
136
137 void DSNode::assertOK() const {
138   assert((Ty != Type::VoidTy ||
139           Ty == Type::VoidTy && (Size == 0 ||
140                                  (NodeType & DSNode::Array))) &&
141          "Node not OK!");
142
143   assert(ParentGraph && "Node has no parent?");
144   const DSScalarMap &SM = ParentGraph->getScalarMap();
145   for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
146     assert(SM.global_count(Globals[i]));
147     assert(SM.find(Globals[i])->second.getNode() == this);
148   }
149 }
150
151 /// forwardNode - Mark this node as being obsolete, and all references to it
152 /// should be forwarded to the specified node and offset.
153 ///
154 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
155   assert(this != To && "Cannot forward a node to itself!");
156   assert(ForwardNH.isNull() && "Already forwarding from this node!");
157   if (To->Size <= 1) Offset = 0;
158   assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
159          "Forwarded offset is wrong!");
160   ForwardNH.setTo(To, Offset);
161   NodeType = DEAD;
162   Size = 0;
163   Ty = Type::VoidTy;
164
165   // Remove this node from the parent graph's Nodes list.
166   ParentGraph->unlinkNode(this);  
167   ParentGraph = 0;
168 }
169
170 // addGlobal - Add an entry for a global value to the Globals list.  This also
171 // marks the node with the 'G' flag if it does not already have it.
172 //
173 void DSNode::addGlobal(GlobalValue *GV) {
174   // First, check to make sure this is the leader if the global is in an
175   // equivalence class.
176   GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
177
178   // Keep the list sorted.
179   std::vector<GlobalValue*>::iterator I =
180     std::lower_bound(Globals.begin(), Globals.end(), GV);
181
182   if (I == Globals.end() || *I != GV) {
183     Globals.insert(I, GV);
184     NodeType |= GlobalNode;
185   }
186 }
187
188 // removeGlobal - Remove the specified global that is explicitly in the globals
189 // list.
190 void DSNode::removeGlobal(GlobalValue *GV) {
191   std::vector<GlobalValue*>::iterator I =
192     std::lower_bound(Globals.begin(), Globals.end(), GV);
193   assert(I != Globals.end() && *I == GV && "Global not in node!");
194   Globals.erase(I);
195 }
196
197 /// foldNodeCompletely - If we determine that this node has some funny
198 /// behavior happening to it that we cannot represent, we fold it down to a
199 /// single, completely pessimistic, node.  This node is represented as a
200 /// single byte with a single TypeEntry of "void".
201 ///
202 void DSNode::foldNodeCompletely() {
203   if (isNodeCompletelyFolded()) return;  // If this node is already folded...
204
205   ++NumFolds;
206
207   // If this node has a size that is <= 1, we don't need to create a forwarding
208   // node.
209   if (getSize() <= 1) {
210     NodeType |= DSNode::Array;
211     Ty = Type::VoidTy;
212     Size = 1;
213     assert(Links.size() <= 1 && "Size is 1, but has more links?");
214     Links.resize(1);
215   } else {
216     // Create the node we are going to forward to.  This is required because
217     // some referrers may have an offset that is > 0.  By forcing them to
218     // forward, the forwarder has the opportunity to correct the offset.
219     DSNode *DestNode = new DSNode(0, ParentGraph);
220     DestNode->NodeType = NodeType|DSNode::Array;
221     DestNode->Ty = Type::VoidTy;
222     DestNode->Size = 1;
223     DestNode->Globals.swap(Globals);
224     
225     // Start forwarding to the destination node...
226     forwardNode(DestNode, 0);
227     
228     if (!Links.empty()) {
229       DestNode->Links.reserve(1);
230       
231       DSNodeHandle NH(DestNode);
232       DestNode->Links.push_back(Links[0]);
233       
234       // If we have links, merge all of our outgoing links together...
235       for (unsigned i = Links.size()-1; i != 0; --i)
236         NH.getNode()->Links[0].mergeWith(Links[i]);
237       Links.clear();
238     } else {
239       DestNode->Links.resize(1);
240     }
241   }
242 }
243
244 /// isNodeCompletelyFolded - Return true if this node has been completely
245 /// folded down to something that can never be expanded, effectively losing
246 /// all of the field sensitivity that may be present in the node.
247 ///
248 bool DSNode::isNodeCompletelyFolded() const {
249   return getSize() == 1 && Ty == Type::VoidTy && isArray();
250 }
251
252 /// addFullGlobalsList - Compute the full set of global values that are
253 /// represented by this node.  Unlike getGlobalsList(), this requires fair
254 /// amount of work to compute, so don't treat this method call as free.
255 void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
256   if (globals_begin() == globals_end()) return;
257
258   EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
259
260   for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
261     EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
262     if (ECI == EC.end())
263       List.push_back(*I);
264     else
265       List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
266   }
267 }
268
269 /// addFullFunctionList - Identical to addFullGlobalsList, but only return the
270 /// functions in the full list.
271 void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
272   if (globals_begin() == globals_end()) return;
273
274   EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
275
276   for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
277     EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
278     if (ECI == EC.end()) {
279       if (Function *F = dyn_cast<Function>(*I))
280         List.push_back(F);
281     } else {
282       for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
283              EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
284         if (Function *F = dyn_cast<Function>(*MI))
285           List.push_back(F);
286     }
287   }
288 }
289
290 namespace {
291   /// TypeElementWalker Class - Used for implementation of physical subtyping...
292   ///
293   class TypeElementWalker {
294     struct StackState {
295       const Type *Ty;
296       unsigned Offset;
297       unsigned Idx;
298       StackState(const Type *T, unsigned Off = 0)
299         : Ty(T), Offset(Off), Idx(0) {}
300     };
301
302     std::vector<StackState> Stack;
303     const TargetData &TD;
304   public:
305     TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
306       Stack.push_back(T);
307       StepToLeaf();
308     }
309
310     bool isDone() const { return Stack.empty(); }
311     const Type *getCurrentType()   const { return Stack.back().Ty;     }
312     unsigned    getCurrentOffset() const { return Stack.back().Offset; }
313
314     void StepToNextType() {
315       PopStackAndAdvance();
316       StepToLeaf();
317     }
318
319   private:
320     /// PopStackAndAdvance - Pop the current element off of the stack and
321     /// advance the underlying element to the next contained member.
322     void PopStackAndAdvance() {
323       assert(!Stack.empty() && "Cannot pop an empty stack!");
324       Stack.pop_back();
325       while (!Stack.empty()) {
326         StackState &SS = Stack.back();
327         if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
328           ++SS.Idx;
329           if (SS.Idx != ST->getNumElements()) {
330             const StructLayout *SL = TD.getStructLayout(ST);
331             SS.Offset += 
332                unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
333             return;
334           }
335           Stack.pop_back();  // At the end of the structure
336         } else {
337           const ArrayType *AT = cast<ArrayType>(SS.Ty);
338           ++SS.Idx;
339           if (SS.Idx != AT->getNumElements()) {
340             SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
341             return;
342           }
343           Stack.pop_back();  // At the end of the array
344         }
345       }
346     }
347
348     /// StepToLeaf - Used by physical subtyping to move to the first leaf node
349     /// on the type stack.
350     void StepToLeaf() {
351       if (Stack.empty()) return;
352       while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
353         StackState &SS = Stack.back();
354         if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
355           if (ST->getNumElements() == 0) {
356             assert(SS.Idx == 0);
357             PopStackAndAdvance();
358           } else {
359             // Step into the structure...
360             assert(SS.Idx < ST->getNumElements());
361             const StructLayout *SL = TD.getStructLayout(ST);
362             Stack.push_back(StackState(ST->getElementType(SS.Idx),
363                             SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
364           }
365         } else {
366           const ArrayType *AT = cast<ArrayType>(SS.Ty);
367           if (AT->getNumElements() == 0) {
368             assert(SS.Idx == 0);
369             PopStackAndAdvance();
370           } else {
371             // Step into the array...
372             assert(SS.Idx < AT->getNumElements());
373             Stack.push_back(StackState(AT->getElementType(),
374                                        SS.Offset+SS.Idx*
375                              unsigned(TD.getTypeSize(AT->getElementType()))));
376           }
377         }
378       }
379     }
380   };
381 } // end anonymous namespace
382
383 /// ElementTypesAreCompatible - Check to see if the specified types are
384 /// "physically" compatible.  If so, return true, else return false.  We only
385 /// have to check the fields in T1: T2 may be larger than T1.  If AllowLargerT1
386 /// is true, then we also allow a larger T1.
387 ///
388 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
389                                       bool AllowLargerT1, const TargetData &TD){
390   TypeElementWalker T1W(T1, TD), T2W(T2, TD);
391   
392   while (!T1W.isDone() && !T2W.isDone()) {
393     if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
394       return false;
395
396     const Type *T1 = T1W.getCurrentType();
397     const Type *T2 = T2W.getCurrentType();
398     if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
399       return false;
400     
401     T1W.StepToNextType();
402     T2W.StepToNextType();
403   }
404   
405   return AllowLargerT1 || T1W.isDone();
406 }
407
408
409 /// mergeTypeInfo - This method merges the specified type into the current node
410 /// at the specified offset.  This may update the current node's type record if
411 /// this gives more information to the node, it may do nothing to the node if
412 /// this information is already known, or it may merge the node completely (and
413 /// return true) if the information is incompatible with what is already known.
414 ///
415 /// This method returns true if the node is completely folded, otherwise false.
416 ///
417 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
418                            bool FoldIfIncompatible) {
419   const TargetData &TD = getTargetData();
420   // Check to make sure the Size member is up-to-date.  Size can be one of the
421   // following:
422   //  Size = 0, Ty = Void: Nothing is known about this node.
423   //  Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
424   //  Size = 1, Ty = Void, Array = 1: The node is collapsed
425   //  Otherwise, sizeof(Ty) = Size
426   //
427   assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
428           (Size == 0 && !Ty->isSized() && !isArray()) ||
429           (Size == 1 && Ty == Type::VoidTy && isArray()) ||
430           (Size == 0 && !Ty->isSized() && !isArray()) ||
431           (TD.getTypeSize(Ty) == Size)) &&
432          "Size member of DSNode doesn't match the type structure!");
433   assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
434
435   if (Offset == 0 && NewTy == Ty)
436     return false;  // This should be a common case, handle it efficiently
437
438   // Return true immediately if the node is completely folded.
439   if (isNodeCompletelyFolded()) return true;
440
441   // If this is an array type, eliminate the outside arrays because they won't
442   // be used anyway.  This greatly reduces the size of large static arrays used
443   // as global variables, for example.
444   //
445   bool WillBeArray = false;
446   while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
447     // FIXME: we might want to keep small arrays, but must be careful about
448     // things like: [2 x [10000 x int*]]
449     NewTy = AT->getElementType();
450     WillBeArray = true;
451   }
452
453   // Figure out how big the new type we're merging in is...
454   unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
455
456   // Otherwise check to see if we can fold this type into the current node.  If
457   // we can't, we fold the node completely, if we can, we potentially update our
458   // internal state.
459   //
460   if (Ty == Type::VoidTy) {
461     // If this is the first type that this node has seen, just accept it without
462     // question....
463     assert(Offset == 0 && !isArray() &&
464            "Cannot have an offset into a void node!");
465
466     // If this node would have to have an unreasonable number of fields, just
467     // collapse it.  This can occur for fortran common blocks, which have stupid
468     // things like { [100000000 x double], [1000000 x double] }.
469     unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
470     if (NumFields > 256) {
471       foldNodeCompletely();
472       return true;
473     }
474
475     Ty = NewTy;
476     NodeType &= ~Array;
477     if (WillBeArray) NodeType |= Array;
478     Size = NewTySize;
479
480     // Calculate the number of outgoing links from this node.
481     Links.resize(NumFields);
482     return false;
483   }
484
485   // Handle node expansion case here...
486   if (Offset+NewTySize > Size) {
487     // It is illegal to grow this node if we have treated it as an array of
488     // objects...
489     if (isArray()) {
490       if (FoldIfIncompatible) foldNodeCompletely();
491       return true;
492     }
493
494     if (Offset) {  // We could handle this case, but we don't for now...
495       std::cerr << "UNIMP: Trying to merge a growth type into "
496                 << "offset != 0: Collapsing!\n";
497       if (FoldIfIncompatible) foldNodeCompletely();
498       return true;
499     }
500
501     // Okay, the situation is nice and simple, we are trying to merge a type in
502     // at offset 0 that is bigger than our current type.  Implement this by
503     // switching to the new type and then merge in the smaller one, which should
504     // hit the other code path here.  If the other code path decides it's not
505     // ok, it will collapse the node as appropriate.
506     //
507
508     // If this node would have to have an unreasonable number of fields, just
509     // collapse it.  This can occur for fortran common blocks, which have stupid
510     // things like { [100000000 x double], [1000000 x double] }.
511     unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
512     if (NumFields > 256) {
513       foldNodeCompletely();
514       return true;
515     }
516
517     const Type *OldTy = Ty;
518     Ty = NewTy;
519     NodeType &= ~Array;
520     if (WillBeArray) NodeType |= Array;
521     Size = NewTySize;
522
523     // Must grow links to be the appropriate size...
524     Links.resize(NumFields);
525
526     // Merge in the old type now... which is guaranteed to be smaller than the
527     // "current" type.
528     return mergeTypeInfo(OldTy, 0);
529   }
530
531   assert(Offset <= Size &&
532          "Cannot merge something into a part of our type that doesn't exist!");
533
534   // Find the section of Ty that NewTy overlaps with... first we find the
535   // type that starts at offset Offset.
536   //
537   unsigned O = 0;
538   const Type *SubType = Ty;
539   while (O < Offset) {
540     assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
541
542     switch (SubType->getTypeID()) {
543     case Type::StructTyID: {
544       const StructType *STy = cast<StructType>(SubType);
545       const StructLayout &SL = *TD.getStructLayout(STy);
546       unsigned i = SL.getElementContainingOffset(Offset-O);
547
548       // The offset we are looking for must be in the i'th element...
549       SubType = STy->getElementType(i);
550       O += (unsigned)SL.MemberOffsets[i];
551       break;
552     }
553     case Type::ArrayTyID: {
554       SubType = cast<ArrayType>(SubType)->getElementType();
555       unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
556       unsigned Remainder = (Offset-O) % ElSize;
557       O = Offset-Remainder;
558       break;
559     }
560     default:
561       if (FoldIfIncompatible) foldNodeCompletely();
562       return true;
563     }
564   }
565
566   assert(O == Offset && "Could not achieve the correct offset!");
567
568   // If we found our type exactly, early exit
569   if (SubType == NewTy) return false;
570
571   // Differing function types don't require us to merge.  They are not values
572   // anyway.
573   if (isa<FunctionType>(SubType) &&
574       isa<FunctionType>(NewTy)) return false;
575
576   unsigned SubTypeSize = SubType->isSized() ? 
577        (unsigned)TD.getTypeSize(SubType) : 0;
578
579   // Ok, we are getting desperate now.  Check for physical subtyping, where we
580   // just require each element in the node to be compatible.
581   if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
582       SubTypeSize && SubTypeSize < 256 && 
583       ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
584     return false;
585
586   // Okay, so we found the leader type at the offset requested.  Search the list
587   // of types that starts at this offset.  If SubType is currently an array or
588   // structure, the type desired may actually be the first element of the
589   // composite type...
590   //
591   unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
592   while (SubType != NewTy) {
593     const Type *NextSubType = 0;
594     unsigned NextSubTypeSize = 0;
595     unsigned NextPadSize = 0;
596     switch (SubType->getTypeID()) {
597     case Type::StructTyID: {
598       const StructType *STy = cast<StructType>(SubType);
599       const StructLayout &SL = *TD.getStructLayout(STy);
600       if (SL.MemberOffsets.size() > 1)
601         NextPadSize = (unsigned)SL.MemberOffsets[1];
602       else
603         NextPadSize = SubTypeSize;
604       NextSubType = STy->getElementType(0);
605       NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
606       break;
607     }
608     case Type::ArrayTyID:
609       NextSubType = cast<ArrayType>(SubType)->getElementType();
610       NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
611       NextPadSize = NextSubTypeSize;
612       break;
613     default: ;
614       // fall out 
615     }
616
617     if (NextSubType == 0)
618       break;   // In the default case, break out of the loop
619
620     if (NextPadSize < NewTySize)
621       break;   // Don't allow shrinking to a smaller type than NewTySize
622     SubType = NextSubType;
623     SubTypeSize = NextSubTypeSize;
624     PadSize = NextPadSize;
625   }
626
627   // If we found the type exactly, return it...
628   if (SubType == NewTy)
629     return false;
630
631   // Check to see if we have a compatible, but different type...
632   if (NewTySize == SubTypeSize) {
633     // Check to see if this type is obviously convertible... int -> uint f.e.
634     if (NewTy->isLosslesslyConvertibleTo(SubType))
635       return false;
636
637     // Check to see if we have a pointer & integer mismatch going on here,
638     // loading a pointer as a long, for example.
639     //
640     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
641         NewTy->isInteger() && isa<PointerType>(SubType))
642       return false;
643   } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
644     // We are accessing the field, plus some structure padding.  Ignore the
645     // structure padding.
646     return false;
647   }
648
649   Module *M = 0;
650   if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
651     M = getParentGraph()->retnodes_begin()->first->getParent();
652   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
653         WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
654         WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
655                   << "SubType: ";
656         WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
657
658   if (FoldIfIncompatible) foldNodeCompletely();
659   return true;
660 }
661
662
663
664 /// addEdgeTo - Add an edge from the current node to the specified node.  This
665 /// can cause merging of nodes in the graph.
666 ///
667 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
668   if (NH.isNull()) return;       // Nothing to do
669
670   DSNodeHandle &ExistingEdge = getLink(Offset);
671   if (!ExistingEdge.isNull()) {
672     // Merge the two nodes...
673     ExistingEdge.mergeWith(NH);
674   } else {                             // No merging to perform...
675     setLink(Offset, NH);               // Just force a link in there...
676   }
677 }
678
679
680 /// MergeSortedVectors - Efficiently merge a vector into another vector where
681 /// duplicates are not allowed and both are sorted.  This assumes that 'T's are
682 /// efficiently copyable and have sane comparison semantics.
683 ///
684 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
685                                const std::vector<GlobalValue*> &Src) {
686   // By far, the most common cases will be the simple ones.  In these cases,
687   // avoid having to allocate a temporary vector...
688   //
689   if (Src.empty()) {             // Nothing to merge in...
690     return;
691   } else if (Dest.empty()) {     // Just copy the result in...
692     Dest = Src;
693   } else if (Src.size() == 1) {  // Insert a single element...
694     const GlobalValue *V = Src[0];
695     std::vector<GlobalValue*>::iterator I =
696       std::lower_bound(Dest.begin(), Dest.end(), V);
697     if (I == Dest.end() || *I != Src[0])  // If not already contained...
698       Dest.insert(I, Src[0]);
699   } else if (Dest.size() == 1) {
700     GlobalValue *Tmp = Dest[0];           // Save value in temporary...
701     Dest = Src;                           // Copy over list...
702     std::vector<GlobalValue*>::iterator I =
703       std::lower_bound(Dest.begin(), Dest.end(), Tmp);
704     if (I == Dest.end() || *I != Tmp)     // If not already contained...
705       Dest.insert(I, Tmp);
706
707   } else {
708     // Make a copy to the side of Dest...
709     std::vector<GlobalValue*> Old(Dest);
710     
711     // Make space for all of the type entries now...
712     Dest.resize(Dest.size()+Src.size());
713     
714     // Merge the two sorted ranges together... into Dest.
715     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
716     
717     // Now erase any duplicate entries that may have accumulated into the 
718     // vectors (because they were in both of the input sets)
719     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
720   }
721 }
722
723 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
724   MergeSortedVectors(Globals, RHS);
725 }
726
727 // MergeNodes - Helper function for DSNode::mergeWith().
728 // This function does the hard work of merging two nodes, CurNodeH
729 // and NH after filtering out trivial cases and making sure that
730 // CurNodeH.offset >= NH.offset.
731 // 
732 // ***WARNING***
733 // Since merging may cause either node to go away, we must always
734 // use the node-handles to refer to the nodes.  These node handles are
735 // automatically updated during merging, so will always provide access
736 // to the correct node after a merge.
737 //
738 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
739   assert(CurNodeH.getOffset() >= NH.getOffset() &&
740          "This should have been enforced in the caller.");
741   assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
742          "Cannot merge two nodes that are not in the same graph!");
743
744   // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
745   // respect to NH.Offset) is now zero.  NOffset is the distance from the base
746   // of our object that N starts from.
747   //
748   unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
749   unsigned NSize = NH.getNode()->getSize();
750
751   // If the two nodes are of different size, and the smaller node has the array
752   // bit set, collapse!
753   if (NSize != CurNodeH.getNode()->getSize()) {
754 #if COLLAPSE_ARRAYS_AGGRESSIVELY
755     if (NSize < CurNodeH.getNode()->getSize()) {
756       if (NH.getNode()->isArray())
757         NH.getNode()->foldNodeCompletely();
758     } else if (CurNodeH.getNode()->isArray()) {
759       NH.getNode()->foldNodeCompletely();
760     }
761 #endif
762   }
763
764   // Merge the type entries of the two nodes together...    
765   if (NH.getNode()->Ty != Type::VoidTy)
766     CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
767   assert(!CurNodeH.getNode()->isDeadNode());
768
769   // If we are merging a node with a completely folded node, then both nodes are
770   // now completely folded.
771   //
772   if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
773     if (!NH.getNode()->isNodeCompletelyFolded()) {
774       NH.getNode()->foldNodeCompletely();
775       assert(NH.getNode() && NH.getOffset() == 0 &&
776              "folding did not make offset 0?");
777       NOffset = NH.getOffset();
778       NSize = NH.getNode()->getSize();
779       assert(NOffset == 0 && NSize == 1);
780     }
781   } else if (NH.getNode()->isNodeCompletelyFolded()) {
782     CurNodeH.getNode()->foldNodeCompletely();
783     assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
784            "folding did not make offset 0?");
785     NSize = NH.getNode()->getSize();
786     NOffset = NH.getOffset();
787     assert(NOffset == 0 && NSize == 1);
788   }
789
790   DSNode *N = NH.getNode();
791   if (CurNodeH.getNode() == N || N == 0) return;
792   assert(!CurNodeH.getNode()->isDeadNode());
793
794   // Merge the NodeType information.
795   CurNodeH.getNode()->NodeType |= N->NodeType;
796
797   // Start forwarding to the new node!
798   N->forwardNode(CurNodeH.getNode(), NOffset);
799   assert(!CurNodeH.getNode()->isDeadNode());
800
801   // Make all of the outgoing links of N now be outgoing links of CurNodeH.
802   //
803   for (unsigned i = 0; i < N->getNumLinks(); ++i) {
804     DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
805     if (Link.getNode()) {
806       // Compute the offset into the current node at which to
807       // merge this link.  In the common case, this is a linear
808       // relation to the offset in the original node (with
809       // wrapping), but if the current node gets collapsed due to
810       // recursive merging, we must make sure to merge in all remaining
811       // links at offset zero.
812       unsigned MergeOffset = 0;
813       DSNode *CN = CurNodeH.getNode();
814       if (CN->Size != 1)
815         MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
816       CN->addEdgeTo(MergeOffset, Link);
817     }
818   }
819
820   // Now that there are no outgoing edges, all of the Links are dead.
821   N->Links.clear();
822
823   // Merge the globals list...
824   if (!N->Globals.empty()) {
825     CurNodeH.getNode()->mergeGlobals(N->Globals);
826
827     // Delete the globals from the old node...
828     std::vector<GlobalValue*>().swap(N->Globals);
829   }
830 }
831
832
833 /// mergeWith - Merge this node and the specified node, moving all links to and
834 /// from the argument node into the current node, deleting the node argument.
835 /// Offset indicates what offset the specified node is to be merged into the
836 /// current node.
837 ///
838 /// The specified node may be a null pointer (in which case, we update it to
839 /// point to this node).
840 ///
841 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
842   DSNode *N = NH.getNode();
843   if (N == this && NH.getOffset() == Offset)
844     return;  // Noop
845
846   // If the RHS is a null node, make it point to this node!
847   if (N == 0) {
848     NH.mergeWith(DSNodeHandle(this, Offset));
849     return;
850   }
851
852   assert(!N->isDeadNode() && !isDeadNode());
853   assert(!hasNoReferrers() && "Should not try to fold a useless node!");
854
855   if (N == this) {
856     // We cannot merge two pieces of the same node together, collapse the node
857     // completely.
858     DEBUG(std::cerr << "Attempting to merge two chunks of"
859                     << " the same node together!\n");
860     foldNodeCompletely();
861     return;
862   }
863
864   // If both nodes are not at offset 0, make sure that we are merging the node
865   // at an later offset into the node with the zero offset.
866   //
867   if (Offset < NH.getOffset()) {
868     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
869     return;
870   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
871     // If the offsets are the same, merge the smaller node into the bigger node
872     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
873     return;
874   }
875
876   // Ok, now we can merge the two nodes.  Use a static helper that works with
877   // two node handles, since "this" may get merged away at intermediate steps.
878   DSNodeHandle CurNodeH(this, Offset);
879   DSNodeHandle NHCopy(NH);
880   DSNode::MergeNodes(CurNodeH, NHCopy);
881 }
882
883
884 //===----------------------------------------------------------------------===//
885 // ReachabilityCloner Implementation
886 //===----------------------------------------------------------------------===//
887
888 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
889   if (SrcNH.isNull()) return DSNodeHandle();
890   const DSNode *SN = SrcNH.getNode();
891
892   DSNodeHandle &NH = NodeMap[SN];
893   if (!NH.isNull()) {   // Node already mapped?
894     DSNode *NHN = NH.getNode();
895     return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
896   }
897
898   // If SrcNH has globals and the destination graph has one of the same globals,
899   // merge this node with the destination node, which is much more efficient.
900   if (SN->globals_begin() != SN->globals_end()) {
901     DSScalarMap &DestSM = Dest.getScalarMap();
902     for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
903          I != E; ++I) {
904       GlobalValue *GV = *I;
905       DSScalarMap::iterator GI = DestSM.find(GV);
906       if (GI != DestSM.end() && !GI->second.isNull()) {
907         // We found one, use merge instead!
908         merge(GI->second, Src.getNodeForValue(GV));
909         assert(!NH.isNull() && "Didn't merge node!");
910         DSNode *NHN = NH.getNode();
911         return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
912       }
913     }
914   }
915
916   DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
917   DN->maskNodeTypes(BitsToKeep);
918   NH = DN;
919   
920   // Next, recursively clone all outgoing links as necessary.  Note that
921   // adding these links can cause the node to collapse itself at any time, and
922   // the current node may be merged with arbitrary other nodes.  For this
923   // reason, we must always go through NH.
924   DN = 0;
925   for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
926     const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
927     if (!SrcEdge.isNull()) {
928       const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
929       // Compute the offset into the current node at which to
930       // merge this link.  In the common case, this is a linear
931       // relation to the offset in the original node (with
932       // wrapping), but if the current node gets collapsed due to
933       // recursive merging, we must make sure to merge in all remaining
934       // links at offset zero.
935       unsigned MergeOffset = 0;
936       DSNode *CN = NH.getNode();
937       if (CN->getSize() != 1)
938         MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
939       CN->addEdgeTo(MergeOffset, DestEdge);
940     }
941   }
942   
943   // If this node contains any globals, make sure they end up in the scalar
944   // map with the correct offset.
945   for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
946        I != E; ++I) {
947     GlobalValue *GV = *I;
948     const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
949     DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
950     assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
951     Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
952                                        DestGNH.getOffset()+SrcGNH.getOffset()));
953   }
954   NH.getNode()->mergeGlobals(SN->getGlobalsList());
955
956   return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
957 }
958
959 void ReachabilityCloner::merge(const DSNodeHandle &NH,
960                                const DSNodeHandle &SrcNH) {
961   if (SrcNH.isNull()) return;  // Noop
962   if (NH.isNull()) {
963     // If there is no destination node, just clone the source and assign the
964     // destination node to be it.
965     NH.mergeWith(getClonedNH(SrcNH));
966     return;
967   }
968
969   // Okay, at this point, we know that we have both a destination and a source
970   // node that need to be merged.  Check to see if the source node has already
971   // been cloned.
972   const DSNode *SN = SrcNH.getNode();
973   DSNodeHandle &SCNH = NodeMap[SN];  // SourceClonedNodeHandle
974   if (!SCNH.isNull()) {   // Node already cloned?
975     DSNode *SCNHN = SCNH.getNode();
976     NH.mergeWith(DSNodeHandle(SCNHN,
977                               SCNH.getOffset()+SrcNH.getOffset()));
978     return;  // Nothing to do!
979   }
980   
981   // Okay, so the source node has not already been cloned.  Instead of creating
982   // a new DSNode, only to merge it into the one we already have, try to perform
983   // the merge in-place.  The only case we cannot handle here is when the offset
984   // into the existing node is less than the offset into the virtual node we are
985   // merging in.  In this case, we have to extend the existing node, which
986   // requires an allocation anyway.
987   DSNode *DN = NH.getNode();   // Make sure the Offset is up-to-date
988   if (NH.getOffset() >= SrcNH.getOffset()) {
989     if (!DN->isNodeCompletelyFolded()) {
990       // Make sure the destination node is folded if the source node is folded.
991       if (SN->isNodeCompletelyFolded()) {
992         DN->foldNodeCompletely();
993         DN = NH.getNode();
994       } else if (SN->getSize() != DN->getSize()) {
995         // If the two nodes are of different size, and the smaller node has the
996         // array bit set, collapse!
997 #if COLLAPSE_ARRAYS_AGGRESSIVELY
998         if (SN->getSize() < DN->getSize()) {
999           if (SN->isArray()) {
1000             DN->foldNodeCompletely();
1001             DN = NH.getNode();
1002           }
1003         } else if (DN->isArray()) {
1004           DN->foldNodeCompletely();
1005           DN = NH.getNode();
1006         }
1007 #endif
1008       }
1009     
1010       // Merge the type entries of the two nodes together...    
1011       if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1012         DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1013         DN = NH.getNode();
1014       }
1015     }
1016
1017     assert(!DN->isDeadNode());
1018     
1019     // Merge the NodeType information.
1020     DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1021
1022     // Before we start merging outgoing links and updating the scalar map, make
1023     // sure it is known that this is the representative node for the src node.
1024     SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1025
1026     // If the source node contains any globals, make sure they end up in the
1027     // scalar map with the correct offset.
1028     if (SN->globals_begin() != SN->globals_end()) {
1029       // Update the globals in the destination node itself.
1030       DN->mergeGlobals(SN->getGlobalsList());
1031
1032       // Update the scalar map for the graph we are merging the source node
1033       // into.
1034       for (DSNode::globals_iterator I = SN->globals_begin(),
1035              E = SN->globals_end(); I != E; ++I) {
1036         GlobalValue *GV = *I;
1037         const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1038         DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1039         assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1040         Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1041                                       DestGNH.getOffset()+SrcGNH.getOffset()));
1042       }
1043       NH.getNode()->mergeGlobals(SN->getGlobalsList());
1044     }
1045   } else {
1046     // We cannot handle this case without allocating a temporary node.  Fall
1047     // back on being simple.
1048     DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1049     NewDN->maskNodeTypes(BitsToKeep);
1050
1051     unsigned NHOffset = NH.getOffset();
1052     NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
1053
1054     assert(NH.getNode() &&
1055            (NH.getOffset() > NHOffset ||
1056             (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1057            "Merging did not adjust the offset!");
1058
1059     // Before we start merging outgoing links and updating the scalar map, make
1060     // sure it is known that this is the representative node for the src node.
1061     SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
1062
1063     // If the source node contained any globals, make sure to create entries 
1064     // in the scalar map for them!
1065     for (DSNode::globals_iterator I = SN->globals_begin(),
1066            E = SN->globals_end(); I != E; ++I) {
1067       GlobalValue *GV = *I;
1068       const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1069       DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1070       assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1071       assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1072       Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1073                                     DestGNH.getOffset()+SrcGNH.getOffset()));
1074     }
1075   }
1076
1077
1078   // Next, recursively merge all outgoing links as necessary.  Note that
1079   // adding these links can cause the destination node to collapse itself at
1080   // any time, and the current node may be merged with arbitrary other nodes.
1081   // For this reason, we must always go through NH.
1082   DN = 0;
1083   for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1084     const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1085     if (!SrcEdge.isNull()) {
1086       // Compute the offset into the current node at which to
1087       // merge this link.  In the common case, this is a linear
1088       // relation to the offset in the original node (with
1089       // wrapping), but if the current node gets collapsed due to
1090       // recursive merging, we must make sure to merge in all remaining
1091       // links at offset zero.
1092       DSNode *CN = SCNH.getNode();
1093       unsigned MergeOffset =
1094         ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
1095       
1096       DSNodeHandle Tmp = CN->getLink(MergeOffset);
1097       if (!Tmp.isNull()) {
1098         // Perform the recursive merging.  Make sure to create a temporary NH,
1099         // because the Link can disappear in the process of recursive merging.
1100         merge(Tmp, SrcEdge);
1101       } else {
1102         Tmp.mergeWith(getClonedNH(SrcEdge));
1103         // Merging this could cause all kinds of recursive things to happen,
1104         // culminating in the current node being eliminated.  Since this is
1105         // possible, make sure to reaquire the link from 'CN'.
1106
1107         unsigned MergeOffset = 0;
1108         CN = SCNH.getNode();
1109         MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1110         CN->getLink(MergeOffset).mergeWith(Tmp);
1111       }
1112     }
1113   }
1114 }
1115
1116 /// mergeCallSite - Merge the nodes reachable from the specified src call
1117 /// site into the nodes reachable from DestCS.
1118 void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
1119                                        const DSCallSite &SrcCS) {
1120   merge(DestCS.getRetVal(), SrcCS.getRetVal());
1121   unsigned MinArgs = DestCS.getNumPtrArgs();
1122   if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1123   
1124   for (unsigned a = 0; a != MinArgs; ++a)
1125     merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1126
1127   for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
1128     DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
1129 }
1130
1131
1132 //===----------------------------------------------------------------------===//
1133 // DSCallSite Implementation
1134 //===----------------------------------------------------------------------===//
1135
1136 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1137 Function &DSCallSite::getCaller() const {
1138   return *Site.getInstruction()->getParent()->getParent();
1139 }
1140
1141 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1142                         ReachabilityCloner &RC) {
1143   NH = RC.getClonedNH(Src);
1144 }
1145
1146 //===----------------------------------------------------------------------===//
1147 // DSGraph Implementation
1148 //===----------------------------------------------------------------------===//
1149
1150 /// getFunctionNames - Return a space separated list of the name of the
1151 /// functions in this graph (if any)
1152 std::string DSGraph::getFunctionNames() const {
1153   switch (getReturnNodes().size()) {
1154   case 0: return "Globals graph";
1155   case 1: return retnodes_begin()->first->getName();
1156   default:
1157     std::string Return;
1158     for (DSGraph::retnodes_iterator I = retnodes_begin();
1159          I != retnodes_end(); ++I)
1160       Return += I->first->getName() + " ";
1161     Return.erase(Return.end()-1, Return.end());   // Remove last space character
1162     return Return;
1163   }
1164 }
1165
1166
1167 DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1168                  unsigned CloneFlags)
1169   : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
1170   PrintAuxCalls = false;
1171   cloneInto(G, CloneFlags);
1172 }
1173
1174 DSGraph::~DSGraph() {
1175   FunctionCalls.clear();
1176   AuxFunctionCalls.clear();
1177   ScalarMap.clear();
1178   ReturnNodes.clear();
1179
1180   // Drop all intra-node references, so that assertions don't fail...
1181   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1182     NI->dropAllReferences();
1183
1184   // Free all of the nodes.
1185   Nodes.clear();
1186 }
1187
1188 // dump - Allow inspection of graph in a debugger.
1189 void DSGraph::dump() const { print(std::cerr); }
1190
1191
1192 /// remapLinks - Change all of the Links in the current node according to the
1193 /// specified mapping.
1194 ///
1195 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1196   for (unsigned i = 0, e = Links.size(); i != e; ++i)
1197     if (DSNode *N = Links[i].getNode()) {
1198       DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1199       if (ONMI != OldNodeMap.end()) {
1200         DSNode *ONMIN = ONMI->second.getNode();
1201         Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1202       }
1203     }
1204 }
1205
1206 /// addObjectToGraph - This method can be used to add global, stack, and heap
1207 /// objects to the graph.  This can be used when updating DSGraphs due to the
1208 /// introduction of new temporary objects.  The new object is not pointed to
1209 /// and does not point to any other objects in the graph.
1210 DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1211   assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1212   const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1213   DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
1214   assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
1215   ScalarMap[Ptr] = N;
1216
1217   if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1218     N->addGlobal(GV);
1219   } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1220     N->setHeapNodeMarker();
1221   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1222     N->setAllocaNodeMarker();
1223   } else {
1224     assert(0 && "Illegal memory object input!");
1225   }
1226   return N;
1227 }
1228
1229
1230 /// cloneInto - Clone the specified DSGraph into the current graph.  The
1231 /// translated ScalarMap for the old function is filled into the ScalarMap
1232 /// for the graph, and the translated ReturnNodes map is returned into
1233 /// ReturnNodes.
1234 ///
1235 /// The CloneFlags member controls various aspects of the cloning process.
1236 ///
1237 void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
1238   TIME_REGION(X, "cloneInto");
1239   assert(&G != this && "Cannot clone graph into itself!");
1240
1241   NodeMapTy OldNodeMap;
1242
1243   // Remove alloca or mod/ref bits as specified...
1244   unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1245     | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1246     | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1247   BitsToClear |= DSNode::DEAD;  // Clear dead flag...
1248
1249   for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1250     assert(!I->isForwarding() &&
1251            "Forward nodes shouldn't be in node list!");
1252     DSNode *New = new DSNode(*I, this);
1253     New->maskNodeTypes(~BitsToClear);
1254     OldNodeMap[I] = New;
1255   }
1256   
1257 #ifndef NDEBUG
1258   Timer::addPeakMemoryMeasurement();
1259 #endif
1260   
1261   // Rewrite the links in the new nodes to point into the current graph now.
1262   // Note that we don't loop over the node's list to do this.  The problem is
1263   // that remaping links can cause recursive merging to happen, which means
1264   // that node_iterator's can get easily invalidated!  Because of this, we
1265   // loop over the OldNodeMap, which contains all of the new nodes as the
1266   // .second element of the map elements.  Also note that if we remap a node
1267   // more than once, we won't break anything.
1268   for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1269        I != E; ++I)
1270     I->second.getNode()->remapLinks(OldNodeMap);
1271
1272   // Copy the scalar map... merging all of the global nodes...
1273   for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1274          E = G.ScalarMap.end(); I != E; ++I) {
1275     DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1276     DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
1277     DSNode *MappedNodeN = MappedNode.getNode();
1278     H.mergeWith(DSNodeHandle(MappedNodeN,
1279                              I->second.getOffset()+MappedNode.getOffset()));
1280   }
1281
1282   if (!(CloneFlags & DontCloneCallNodes)) {
1283     // Copy the function calls list.
1284     for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1285       FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1286   }
1287
1288   if (!(CloneFlags & DontCloneAuxCallNodes)) {
1289     // Copy the auxiliary function calls list.
1290     for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1291       AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1292   }
1293
1294   // Map the return node pointers over...
1295   for (retnodes_iterator I = G.retnodes_begin(),
1296          E = G.retnodes_end(); I != E; ++I) {
1297     const DSNodeHandle &Ret = I->second;
1298     DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1299     DSNode *MappedRetN = MappedRet.getNode();
1300     ReturnNodes.insert(std::make_pair(I->first,
1301                                       DSNodeHandle(MappedRetN,
1302                                      MappedRet.getOffset()+Ret.getOffset())));
1303   }
1304 }
1305
1306 /// spliceFrom - Logically perform the operation of cloning the RHS graph into
1307 /// this graph, then clearing the RHS graph.  Instead of performing this as
1308 /// two seperate operations, do it as a single, much faster, one.
1309 ///
1310 void DSGraph::spliceFrom(DSGraph &RHS) {
1311   // Change all of the nodes in RHS to think we are their parent.
1312   for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1313        I != E; ++I)
1314     I->setParentGraph(this);
1315   // Take all of the nodes.
1316   Nodes.splice(Nodes.end(), RHS.Nodes);
1317   
1318   // Take all of the calls.
1319   FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1320   AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1321
1322   // Take all of the return nodes.
1323   if (ReturnNodes.empty()) {
1324     ReturnNodes.swap(RHS.ReturnNodes);
1325   } else {
1326     ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1327     RHS.ReturnNodes.clear();
1328   }
1329
1330   // Merge the scalar map in.
1331   ScalarMap.spliceFrom(RHS.ScalarMap);
1332 }
1333
1334 /// spliceFrom - Copy all entries from RHS, then clear RHS.
1335 ///
1336 void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1337   // Special case if this is empty.
1338   if (ValueMap.empty()) {
1339     ValueMap.swap(RHS.ValueMap);
1340     GlobalSet.swap(RHS.GlobalSet);
1341   } else {
1342     GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1343     for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1344          I != E; ++I)
1345       ValueMap[I->first].mergeWith(I->second);
1346     RHS.ValueMap.clear();
1347   }
1348 }
1349
1350
1351 /// getFunctionArgumentsForCall - Given a function that is currently in this
1352 /// graph, return the DSNodeHandles that correspond to the pointer-compatible
1353 /// function arguments.  The vector is filled in with the return value (or
1354 /// null if it is not pointer compatible), followed by all of the
1355 /// pointer-compatible arguments.
1356 void DSGraph::getFunctionArgumentsForCall(Function *F,
1357                                        std::vector<DSNodeHandle> &Args) const {
1358   Args.push_back(getReturnNodeFor(*F));
1359   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1360        AI != E; ++AI)
1361     if (isPointerType(AI->getType())) {
1362       Args.push_back(getNodeForValue(AI));
1363       assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1364     }
1365 }
1366
1367 namespace {
1368   // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1369   // node to a node cloned by the ReachabilityCloner object contained.  To be
1370   // extra obnoxious it ignores edges from nodes that are globals, and truncates
1371   // search at RC marked nodes.  This is designed as an object so that
1372   // intermediate results can be memoized across invocations of
1373   // PathExistsToClonedNode.
1374   struct HackedGraphSCCFinder {
1375     ReachabilityCloner &RC;
1376     unsigned CurNodeId;
1377     std::vector<const DSNode*> SCCStack;
1378     std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
1379     
1380     HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1381       // Remove null pointer as a special case.
1382       NodeInfo[0] = std::make_pair(0, false);
1383     }
1384
1385     std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1386
1387     bool PathExistsToClonedNode(const DSNode *N) {
1388       return VisitForSCCs(N).second;
1389     }
1390
1391     bool PathExistsToClonedNode(const DSCallSite &CS) {
1392       if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1393         return true;
1394       for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1395         if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1396           return true;
1397       return false;
1398     }
1399   };
1400 }
1401
1402 std::pair<unsigned, bool> &HackedGraphSCCFinder::
1403 VisitForSCCs(const DSNode *N) {
1404   std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1405     NodeInfoIt = NodeInfo.lower_bound(N);
1406   if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1407     return NodeInfoIt->second;
1408
1409   unsigned Min = CurNodeId++;
1410   unsigned MyId = Min;
1411   std::pair<unsigned, bool> &ThisNodeInfo =
1412     NodeInfo.insert(NodeInfoIt,
1413                     std::make_pair(N, std::make_pair(MyId, false)))->second;
1414
1415   // Base case: if we find a global, this doesn't reach the cloned graph
1416   // portion.
1417   if (N->isGlobalNode()) {
1418     ThisNodeInfo.second = false;
1419     return ThisNodeInfo;
1420   }
1421
1422   // Base case: if this does reach the cloned graph portion... it does. :)
1423   if (RC.hasClonedNode(N)) {
1424     ThisNodeInfo.second = true;
1425     return ThisNodeInfo;
1426   }
1427
1428   SCCStack.push_back(N);
1429
1430   // Otherwise, check all successors.
1431   bool AnyDirectSuccessorsReachClonedNodes = false;
1432   for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1433        EI != EE; ++EI) {
1434     std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(EI->getNode());
1435     if (SuccInfo.first < Min) Min = SuccInfo.first;
1436     AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1437   }
1438
1439   if (Min != MyId)
1440     return ThisNodeInfo;  // Part of a large SCC.  Leave self on stack.
1441
1442   if (SCCStack.back() == N) {  // Special case single node SCC.
1443     SCCStack.pop_back();
1444     ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1445     return ThisNodeInfo;
1446   }
1447
1448   // Find out if any direct successors of any node reach cloned nodes.
1449   if (!AnyDirectSuccessorsReachClonedNodes)
1450     for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1451       for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1452            EI != EE; ++EI)
1453         if (DSNode *N = EI->getNode())
1454           if (NodeInfo[N].second) {
1455             AnyDirectSuccessorsReachClonedNodes = true;
1456             goto OutOfLoop;
1457           }
1458 OutOfLoop:
1459   // If any successor reaches a cloned node, mark all nodes in this SCC as
1460   // reaching the cloned node.
1461   if (AnyDirectSuccessorsReachClonedNodes)
1462     while (SCCStack.back() != N) {
1463       NodeInfo[SCCStack.back()].second = true;
1464       SCCStack.pop_back();
1465     }
1466   SCCStack.pop_back();
1467   ThisNodeInfo.second = true;
1468   return ThisNodeInfo;
1469 }
1470
1471 /// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1472 /// nodes from G2 into 'this' graph, merging the bindings specified by the
1473 /// call site (in this graph) with the bindings specified by the vector in G2.
1474 /// The two DSGraphs must be different.
1475 ///
1476 void DSGraph::mergeInGraph(const DSCallSite &CS, 
1477                            std::vector<DSNodeHandle> &Args,
1478                            const DSGraph &Graph, unsigned CloneFlags) {
1479   TIME_REGION(X, "mergeInGraph");
1480
1481   assert((CloneFlags & DontCloneCallNodes) &&
1482          "Doesn't support copying of call nodes!");
1483
1484   // If this is not a recursive call, clone the graph into this graph...
1485   if (&Graph == this) {
1486     // Merge the return value with the return value of the context.
1487     Args[0].mergeWith(CS.getRetVal());
1488     
1489     // Resolve all of the function arguments.
1490     for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1491       if (i == Args.size()-1)
1492         break;
1493       
1494       // Add the link from the argument scalar to the provided value.
1495       Args[i+1].mergeWith(CS.getPtrArg(i));
1496     }
1497     return;
1498   }
1499
1500   // Clone the callee's graph into the current graph, keeping track of where
1501   // scalars in the old graph _used_ to point, and of the new nodes matching
1502   // nodes of the old graph.
1503   ReachabilityCloner RC(*this, Graph, CloneFlags);
1504     
1505   // Map the return node pointer over.
1506   if (!CS.getRetVal().isNull())
1507     RC.merge(CS.getRetVal(), Args[0]);
1508
1509   // Map over all of the arguments.
1510   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1511     if (i == Args.size()-1)
1512       break;
1513       
1514     // Add the link from the argument scalar to the provided value.
1515     RC.merge(CS.getPtrArg(i), Args[i+1]);
1516   }
1517     
1518   // We generally don't want to copy global nodes or aux calls from the callee
1519   // graph to the caller graph.  However, we have to copy them if there is a
1520   // path from the node to a node we have already copied which does not go
1521   // through another global.  Compute the set of node that can reach globals and
1522   // aux call nodes to copy over, then do it.
1523   std::vector<const DSCallSite*> AuxCallToCopy;
1524   std::vector<GlobalValue*> GlobalsToCopy;
1525
1526   // NodesReachCopiedNodes - Memoize results for efficiency.  Contains a
1527   // true/false value for every visited node that reaches a copied node without
1528   // going through a global.
1529   HackedGraphSCCFinder SCCFinder(RC);
1530
1531   if (!(CloneFlags & DontCloneAuxCallNodes))
1532     for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1533       if (SCCFinder.PathExistsToClonedNode(*I))
1534         AuxCallToCopy.push_back(&*I);
1535
1536   const DSScalarMap &GSM = Graph.getScalarMap();
1537   for (DSScalarMap::global_iterator GI = GSM.global_begin(),
1538          E = GSM.global_end(); GI != E; ++GI) {
1539     DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1540     for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1541            EE = GlobalNode->edge_end(); EI != EE; ++EI)
1542       if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
1543         GlobalsToCopy.push_back(*GI);
1544         break;
1545       }
1546   }
1547
1548   // Copy aux calls that are needed.
1549   for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1550     AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
1551   
1552   // Copy globals that are needed.
1553   for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1554     RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
1555 }
1556
1557
1558
1559 /// mergeInGraph - The method is used for merging graphs together.  If the
1560 /// argument graph is not *this, it makes a clone of the specified graph, then
1561 /// merges the nodes specified in the call site with the formal arguments in the
1562 /// graph.
1563 ///
1564 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1565                            const DSGraph &Graph, unsigned CloneFlags) {
1566   // Set up argument bindings.
1567   std::vector<DSNodeHandle> Args;
1568   Graph.getFunctionArgumentsForCall(&F, Args);
1569
1570   mergeInGraph(CS, Args, Graph, CloneFlags);
1571 }
1572
1573 /// getCallSiteForArguments - Get the arguments and return value bindings for
1574 /// the specified function in the current graph.
1575 ///
1576 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1577   std::vector<DSNodeHandle> Args;
1578
1579   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
1580     if (isPointerType(I->getType()))
1581       Args.push_back(getNodeForValue(I));
1582
1583   return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1584 }
1585
1586 /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1587 /// the context of this graph, return the DSCallSite for it.
1588 DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1589   DSNodeHandle RetVal;
1590   Instruction *I = CS.getInstruction();
1591   if (isPointerType(I->getType()))
1592     RetVal = getNodeForValue(I);
1593
1594   std::vector<DSNodeHandle> Args;
1595   Args.reserve(CS.arg_end()-CS.arg_begin());
1596
1597   // Calculate the arguments vector...
1598   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1599     if (isPointerType((*I)->getType()))
1600       if (isa<ConstantPointerNull>(*I))
1601         Args.push_back(DSNodeHandle());
1602       else
1603         Args.push_back(getNodeForValue(*I));
1604
1605   // Add a new function call entry...
1606   if (Function *F = CS.getCalledFunction())
1607     return DSCallSite(CS, RetVal, F, Args);
1608   else
1609     return DSCallSite(CS, RetVal,
1610                       getNodeForValue(CS.getCalledValue()).getNode(), Args);
1611 }
1612
1613
1614
1615 // markIncompleteNodes - Mark the specified node as having contents that are not
1616 // known with the current analysis we have performed.  Because a node makes all
1617 // of the nodes it can reach incomplete if the node itself is incomplete, we
1618 // must recursively traverse the data structure graph, marking all reachable
1619 // nodes as incomplete.
1620 //
1621 static void markIncompleteNode(DSNode *N) {
1622   // Stop recursion if no node, or if node already marked...
1623   if (N == 0 || N->isIncomplete()) return;
1624
1625   // Actually mark the node
1626   N->setIncompleteMarker();
1627
1628   // Recursively process children...
1629   for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1630     if (DSNode *DSN = I->getNode())
1631       markIncompleteNode(DSN);
1632 }
1633
1634 static void markIncomplete(DSCallSite &Call) {
1635   // Then the return value is certainly incomplete!
1636   markIncompleteNode(Call.getRetVal().getNode());
1637
1638   // All objects pointed to by function arguments are incomplete!
1639   for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1640     markIncompleteNode(Call.getPtrArg(i).getNode());
1641 }
1642
1643 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1644 // modified by other functions that have not been resolved yet.  This marks
1645 // nodes that are reachable through three sources of "unknownness":
1646 //
1647 //  Global Variables, Function Calls, and Incoming Arguments
1648 //
1649 // For any node that may have unknown components (because something outside the
1650 // scope of current analysis may have modified it), the 'Incomplete' flag is
1651 // added to the NodeType.
1652 //
1653 void DSGraph::markIncompleteNodes(unsigned Flags) {
1654   // Mark any incoming arguments as incomplete.
1655   if (Flags & DSGraph::MarkFormalArgs)
1656     for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1657          FI != E; ++FI) {
1658       Function &F = *FI->first;
1659       for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1660            I != E; ++I)
1661         if (isPointerType(I->getType()))
1662           markIncompleteNode(getNodeForValue(I).getNode());
1663       markIncompleteNode(FI->second.getNode());
1664     }
1665
1666   // Mark stuff passed into functions calls as being incomplete.
1667   if (!shouldPrintAuxCalls())
1668     for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1669            E = FunctionCalls.end(); I != E; ++I)
1670       markIncomplete(*I);
1671   else
1672     for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1673            E = AuxFunctionCalls.end(); I != E; ++I)
1674       markIncomplete(*I);
1675
1676   // Mark all global nodes as incomplete.
1677   for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1678          E = ScalarMap.global_end(); I != E; ++I)
1679     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1680       if (!GV->hasInitializer() ||    // Always mark external globals incomp.
1681           (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1682         markIncompleteNode(ScalarMap[GV].getNode());
1683 }
1684
1685 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1686   if (DSNode *N = Edge.getNode())  // Is there an edge?
1687     if (N->getNumReferrers() == 1)  // Does it point to a lonely node?
1688       // No interesting info?
1689       if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1690           N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1691         Edge.setTo(0, 0);  // Kill the edge!
1692 }
1693
1694 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1695   std::vector<Function*> Funcs;
1696   N->addFullFunctionList(Funcs);
1697   for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1698     if (Funcs[i]->isExternal()) return true;
1699   return false;
1700 }
1701
1702 static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
1703   // Remove trivially identical function calls
1704   Calls.sort();  // Sort by callee as primary key!
1705
1706   // Scan the call list cleaning it up as necessary...
1707   DSNodeHandle LastCalleeNode;
1708   Function *LastCalleeFunc = 0;
1709   unsigned NumDuplicateCalls = 0;
1710   bool LastCalleeContainsExternalFunction = false;
1711
1712   unsigned NumDeleted = 0;
1713   for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1714        I != E;) {
1715     DSCallSite &CS = *I;
1716     std::list<DSCallSite>::iterator OldIt = I++;
1717
1718     if (!CS.isIndirectCall()) {
1719       LastCalleeNode = 0;
1720     } else {
1721       DSNode *Callee = CS.getCalleeNode();
1722
1723       // If the Callee is a useless edge, this must be an unreachable call site,
1724       // eliminate it.
1725       if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1726           Callee->getGlobalsList().empty()) {  // No useful info?
1727 #ifndef NDEBUG
1728         std::cerr << "WARNING: Useless call site found.\n";
1729 #endif
1730         Calls.erase(OldIt);
1731         ++NumDeleted;
1732         continue;
1733       }
1734
1735       // If the last call site in the list has the same callee as this one, and
1736       // if the callee contains an external function, it will never be
1737       // resolvable, just merge the call sites.
1738       if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1739         LastCalleeContainsExternalFunction =
1740           nodeContainsExternalFunction(Callee);
1741
1742         std::list<DSCallSite>::iterator PrevIt = OldIt;
1743         --PrevIt;
1744         PrevIt->mergeWith(CS);
1745
1746         // No need to keep this call anymore.
1747         Calls.erase(OldIt);
1748         ++NumDeleted;
1749         continue;
1750       } else {
1751         LastCalleeNode = Callee;
1752       }
1753     }
1754
1755     // If the return value or any arguments point to a void node with no
1756     // information at all in it, and the call node is the only node to point
1757     // to it, remove the edge to the node (killing the node).
1758     //
1759     killIfUselessEdge(CS.getRetVal());
1760     for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1761       killIfUselessEdge(CS.getPtrArg(a));
1762     
1763 #if 0
1764     // If this call site calls the same function as the last call site, and if
1765     // the function pointer contains an external function, this node will
1766     // never be resolved.  Merge the arguments of the call node because no
1767     // information will be lost.
1768     //
1769     if ((CS.isDirectCall()   && CS.getCalleeFunc() == LastCalleeFunc) ||
1770         (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1771       ++NumDuplicateCalls;
1772       if (NumDuplicateCalls == 1) {
1773         if (LastCalleeNode)
1774           LastCalleeContainsExternalFunction =
1775             nodeContainsExternalFunction(LastCalleeNode);
1776         else
1777           LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1778       }
1779       
1780       // It is not clear why, but enabling this code makes DSA really
1781       // sensitive to node forwarding.  Basically, with this enabled, DSA
1782       // performs different number of inlinings based on which nodes are
1783       // forwarding or not.  This is clearly a problem, so this code is
1784       // disabled until this can be resolved.
1785 #if 1
1786       if (LastCalleeContainsExternalFunction
1787 #if 0
1788           ||
1789           // This should be more than enough context sensitivity!
1790           // FIXME: Evaluate how many times this is tripped!
1791           NumDuplicateCalls > 20
1792 #endif
1793           ) {
1794         
1795         std::list<DSCallSite>::iterator PrevIt = OldIt;
1796         --PrevIt;
1797         PrevIt->mergeWith(CS);
1798         
1799         // No need to keep this call anymore.
1800         Calls.erase(OldIt);
1801         ++NumDeleted;
1802         continue;
1803       }
1804 #endif
1805     } else {
1806       if (CS.isDirectCall()) {
1807         LastCalleeFunc = CS.getCalleeFunc();
1808         LastCalleeNode = 0;
1809       } else {
1810         LastCalleeNode = CS.getCalleeNode();
1811         LastCalleeFunc = 0;
1812       }
1813       NumDuplicateCalls = 0;
1814     }
1815 #endif
1816
1817     if (I != Calls.end() && CS == *I) {
1818       LastCalleeNode = 0;
1819       Calls.erase(OldIt);
1820       ++NumDeleted;
1821       continue;
1822     }
1823   }
1824
1825   // Resort now that we simplified things.
1826   Calls.sort();
1827
1828   // Now that we are in sorted order, eliminate duplicates.
1829   std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1830   if (CI != CE)
1831     while (1) {
1832       std::list<DSCallSite>::iterator OldIt = CI++;
1833       if (CI == CE) break;
1834
1835       // If this call site is now the same as the previous one, we can delete it
1836       // as a duplicate.
1837       if (*OldIt == *CI) {
1838         Calls.erase(CI);
1839         CI = OldIt;
1840         ++NumDeleted;
1841       }
1842     }
1843
1844   //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1845
1846   // Track the number of call nodes merged away...
1847   NumCallNodesMerged += NumDeleted;
1848
1849   DEBUG(if (NumDeleted)
1850           std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
1851 }
1852
1853
1854 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1855 // removes all unreachable nodes that are created because they got merged with
1856 // other nodes in the graph.  These nodes will all be trivially unreachable, so
1857 // we don't have to perform any non-trivial analysis here.
1858 //
1859 void DSGraph::removeTriviallyDeadNodes() {
1860   TIME_REGION(X, "removeTriviallyDeadNodes");
1861
1862 #if 0
1863   /// NOTE: This code is disabled.  This slows down DSA on 177.mesa
1864   /// substantially!
1865
1866   // Loop over all of the nodes in the graph, calling getNode on each field.
1867   // This will cause all nodes to update their forwarding edges, causing
1868   // forwarded nodes to be delete-able.
1869   { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
1870   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1871     DSNode &N = *NI;
1872     for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1873       N.getLink(l*N.getPointerSize()).getNode();
1874   }
1875   }
1876
1877   // NOTE: This code is disabled.  Though it should, in theory, allow us to
1878   // remove more nodes down below, the scan of the scalar map is incredibly
1879   // expensive for certain programs (with large SCCs).  In the future, if we can
1880   // make the scalar map scan more efficient, then we can reenable this.
1881   { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1882
1883   // Likewise, forward any edges from the scalar nodes.  While we are at it,
1884   // clean house a bit.
1885   for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1886     I->second.getNode();
1887     ++I;
1888   }
1889   }
1890 #endif
1891   bool isGlobalsGraph = !GlobalsGraph;
1892
1893   for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1894     DSNode &Node = *NI;
1895
1896     // Do not remove *any* global nodes in the globals graph.
1897     // This is a special case because such nodes may not have I, M, R flags set.
1898     if (Node.isGlobalNode() && isGlobalsGraph) {
1899       ++NI;
1900       continue;
1901     }
1902
1903     if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1904       // This is a useless node if it has no mod/ref info (checked above),
1905       // outgoing edges (which it cannot, as it is not modified in this
1906       // context), and it has no incoming edges.  If it is a global node it may
1907       // have all of these properties and still have incoming edges, due to the
1908       // scalar map, so we check those now.
1909       //
1910       if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1911         const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
1912
1913         // Loop through and make sure all of the globals are referring directly
1914         // to the node...
1915         for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1916           DSNode *N = getNodeForValue(Globals[j]).getNode();
1917           assert(N == &Node && "ScalarMap doesn't match globals list!");
1918         }
1919
1920         // Make sure NumReferrers still agrees, if so, the node is truly dead.
1921         if (Node.getNumReferrers() == Globals.size()) {
1922           for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1923             ScalarMap.erase(Globals[j]);
1924           Node.makeNodeDead();
1925           ++NumTrivialGlobalDNE;
1926         }
1927       }
1928     }
1929
1930     if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1931       // This node is dead!
1932       NI = Nodes.erase(NI);    // Erase & remove from node list.
1933       ++NumTrivialDNE;
1934     } else {
1935       ++NI;
1936     }
1937   }
1938
1939   removeIdenticalCalls(FunctionCalls);
1940   removeIdenticalCalls(AuxFunctionCalls);
1941 }
1942
1943
1944 /// markReachableNodes - This method recursively traverses the specified
1945 /// DSNodes, marking any nodes which are reachable.  All reachable nodes it adds
1946 /// to the set, which allows it to only traverse visited nodes once.
1947 ///
1948 void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
1949   if (this == 0) return;
1950   assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1951   if (ReachableNodes.insert(this).second)        // Is newly reachable?
1952     for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1953          I != E; ++I)
1954       I->getNode()->markReachableNodes(ReachableNodes);
1955 }
1956
1957 void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
1958   getRetVal().getNode()->markReachableNodes(Nodes);
1959   if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1960   
1961   for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1962     getPtrArg(i).getNode()->markReachableNodes(Nodes);
1963 }
1964
1965 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1966 // looking for a node that is marked alive.  If an alive node is found, return
1967 // true, otherwise return false.  If an alive node is reachable, this node is
1968 // marked as alive...
1969 //
1970 static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1971                                hash_set<const DSNode*> &Visited,
1972                                bool IgnoreGlobals) {
1973   if (N == 0) return false;
1974   assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1975
1976   // If this is a global node, it will end up in the globals graph anyway, so we
1977   // don't need to worry about it.
1978   if (IgnoreGlobals && N->isGlobalNode()) return false;
1979
1980   // If we know that this node is alive, return so!
1981   if (Alive.count(N)) return true;
1982
1983   // Otherwise, we don't think the node is alive yet, check for infinite
1984   // recursion.
1985   if (Visited.count(N)) return false;  // Found a cycle
1986   Visited.insert(N);   // No recursion, insert into Visited...
1987
1988   for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1989     if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
1990       N->markReachableNodes(Alive);
1991       return true;
1992     }
1993   return false;
1994 }
1995
1996 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1997 // alive nodes.
1998 //
1999 static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2000                                   hash_set<const DSNode*> &Alive,
2001                                   hash_set<const DSNode*> &Visited,
2002                                   bool IgnoreGlobals) {
2003   if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2004                          IgnoreGlobals))
2005     return true;
2006   if (CS.isIndirectCall() &&
2007       CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
2008     return true;
2009   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
2010     if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2011                            IgnoreGlobals))
2012       return true;
2013   return false;
2014 }
2015
2016 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
2017 // subgraphs that are unreachable.  This often occurs because the data
2018 // structure doesn't "escape" into it's caller, and thus should be eliminated
2019 // from the caller's graph entirely.  This is only appropriate to use when
2020 // inlining graphs.
2021 //
2022 void DSGraph::removeDeadNodes(unsigned Flags) {
2023   DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
2024
2025   // Reduce the amount of work we have to do... remove dummy nodes left over by
2026   // merging...
2027   removeTriviallyDeadNodes();
2028
2029   TIME_REGION(X, "removeDeadNodes");
2030
2031   // FIXME: Merge non-trivially identical call nodes...
2032
2033   // Alive - a set that holds all nodes found to be reachable/alive.
2034   hash_set<const DSNode*> Alive;
2035   std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
2036
2037   // Copy and merge all information about globals to the GlobalsGraph if this is
2038   // not a final pass (where unreachable globals are removed).
2039   //
2040   // Strip all alloca bits since the current function is only for the BU pass.
2041   // Strip all incomplete bits since they are short-lived properties and they
2042   // will be correctly computed when rematerializing nodes into the functions.
2043   //
2044   ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2045                               DSGraph::StripIncompleteBit);
2046
2047   // Mark all nodes reachable by (non-global) scalar nodes as alive...
2048 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
2049   for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2050        I != E; ++I)
2051     if (isa<GlobalValue>(I->first)) {             // Keep track of global nodes
2052       assert(!I->second.isNull() && "Null global node?");
2053       assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
2054       GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
2055
2056       // Make sure that all globals are cloned over as roots.
2057       if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
2058         DSGraph::ScalarMapTy::iterator SMI = 
2059           GlobalsGraph->getScalarMap().find(I->first);
2060         if (SMI != GlobalsGraph->getScalarMap().end())
2061           GGCloner.merge(SMI->second, I->second);
2062         else
2063           GGCloner.getClonedNH(I->second);
2064       }
2065     } else {
2066       I->second.getNode()->markReachableNodes(Alive);
2067     }
2068 }
2069
2070   // The return values are alive as well.
2071   for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2072        I != E; ++I)
2073     I->second.getNode()->markReachableNodes(Alive);
2074
2075   // Mark any nodes reachable by primary calls as alive...
2076   for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2077     I->markReachableNodes(Alive);
2078
2079
2080   // Now find globals and aux call nodes that are already live or reach a live
2081   // value (which makes them live in turn), and continue till no more are found.
2082   // 
2083   bool Iterate;
2084   hash_set<const DSNode*> Visited;
2085   hash_set<const DSCallSite*> AuxFCallsAlive;
2086   do {
2087     Visited.clear();
2088     // If any global node points to a non-global that is "alive", the global is
2089     // "alive" as well...  Remove it from the GlobalNodes list so we only have
2090     // unreachable globals in the list.
2091     //
2092     Iterate = false;
2093     if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2094       for (unsigned i = 0; i != GlobalNodes.size(); ++i)
2095         if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited, 
2096                                Flags & DSGraph::RemoveUnreachableGlobals)) {
2097           std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2098           GlobalNodes.pop_back();                          // erase efficiently
2099           Iterate = true;
2100         }
2101
2102     // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2103     // call nodes that get resolved will be difficult to remove from that graph.
2104     // The final unresolved call nodes must be handled specially at the end of
2105     // the BU pass (i.e., in main or other roots of the call graph).
2106     for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
2107       if (!AuxFCallsAlive.count(&*CI) &&
2108           (CI->isIndirectCall()
2109            || CallSiteUsesAliveArgs(*CI, Alive, Visited,
2110                                   Flags & DSGraph::RemoveUnreachableGlobals))) {
2111         CI->markReachableNodes(Alive);
2112         AuxFCallsAlive.insert(&*CI);
2113         Iterate = true;
2114       }
2115   } while (Iterate);
2116
2117   // Move dead aux function calls to the end of the list
2118   unsigned CurIdx = 0;
2119   for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2120          E = AuxFunctionCalls.end(); CI != E; )
2121     if (AuxFCallsAlive.count(&*CI))
2122       ++CI;
2123     else {
2124       // Copy and merge global nodes and dead aux call nodes into the
2125       // GlobalsGraph, and all nodes reachable from those nodes.  Update their
2126       // target pointers using the GGCloner.
2127       // 
2128       if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2129         GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
2130
2131       AuxFunctionCalls.erase(CI++);
2132     }
2133
2134   // We are finally done with the GGCloner so we can destroy it.
2135   GGCloner.destroy();
2136
2137   // At this point, any nodes which are visited, but not alive, are nodes
2138   // which can be removed.  Loop over all nodes, eliminating completely
2139   // unreachable nodes.
2140   //
2141   std::vector<DSNode*> DeadNodes;
2142   DeadNodes.reserve(Nodes.size());
2143   for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2144     DSNode *N = NI++;
2145     assert(!N->isForwarding() && "Forwarded node in nodes list?");
2146
2147     if (!Alive.count(N)) {
2148       Nodes.remove(N);
2149       assert(!N->isForwarding() && "Cannot remove a forwarding node!");
2150       DeadNodes.push_back(N);
2151       N->dropAllReferences();
2152       ++NumDNE;
2153     }
2154   }
2155
2156   // Remove all unreachable globals from the ScalarMap.
2157   // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2158   // In either case, the dead nodes will not be in the set Alive.
2159   for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
2160     if (!Alive.count(GlobalNodes[i].second))
2161       ScalarMap.erase(GlobalNodes[i].first);
2162     else
2163       assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
2164
2165   // Delete all dead nodes now since their referrer counts are zero.
2166   for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2167     delete DeadNodes[i];
2168
2169   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
2170 }
2171
2172 void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
2173   assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2174          N->globals_end() && "Global value not in node!");
2175 }
2176
2177 void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2178   if (CS.isIndirectCall()) {
2179     AssertNodeInGraph(CS.getCalleeNode());
2180 #if 0
2181     if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2182         CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
2183       std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";      
2184 #endif
2185   }
2186   AssertNodeInGraph(CS.getRetVal().getNode());
2187   for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2188     AssertNodeInGraph(CS.getPtrArg(j).getNode());
2189 }
2190
2191 void DSGraph::AssertCallNodesInGraph() const {
2192   for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2193     AssertCallSiteInGraph(*I);
2194 }
2195 void DSGraph::AssertAuxCallNodesInGraph() const {
2196   for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2197     AssertCallSiteInGraph(*I);
2198 }
2199
2200 void DSGraph::AssertGraphOK() const {
2201   for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2202     NI->assertOK();
2203
2204   for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
2205          E = ScalarMap.end(); I != E; ++I) {
2206     assert(!I->second.isNull() && "Null node in scalarmap!");
2207     AssertNodeInGraph(I->second.getNode());
2208     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
2209       assert(I->second.getNode()->isGlobalNode() &&
2210              "Global points to node, but node isn't global?");
2211       AssertNodeContainsGlobal(I->second.getNode(), GV);
2212     }
2213   }
2214   AssertCallNodesInGraph();
2215   AssertAuxCallNodesInGraph();
2216
2217   // Check that all pointer arguments to any functions in this graph have
2218   // destinations.
2219   for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2220          E = ReturnNodes.end();
2221        RI != E; ++RI) {
2222     Function &F = *RI->first;
2223     for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
2224       if (isPointerType(AI->getType()))
2225         assert(!getNodeForValue(AI).isNull() &&
2226                "Pointer argument must be in the scalar map!");
2227   }
2228 }
2229
2230 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
2231 /// nodes reachable from the two graphs, computing the mapping of nodes from the
2232 /// first to the second graph.  This mapping may be many-to-one (i.e. the first
2233 /// graph may have multiple nodes representing one node in the second graph),
2234 /// but it will not work if there is a one-to-many or many-to-many mapping.
2235 ///
2236 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
2237                                  const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2238                                  bool StrictChecking) {
2239   DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2240   if (N1 == 0 || N2 == 0) return;
2241
2242   DSNodeHandle &Entry = NodeMap[N1];
2243   if (!Entry.isNull()) {
2244     // Termination of recursion!
2245     if (StrictChecking) {
2246       assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2247       assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2248               Entry.getNode()->isNodeCompletelyFolded()) &&
2249              "Inconsistent mapping detected!");
2250     }
2251     return;
2252   }
2253   
2254   Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
2255
2256   // Loop over all of the fields that N1 and N2 have in common, recursively
2257   // mapping the edges together now.
2258   int N2Idx = NH2.getOffset()-NH1.getOffset();
2259   unsigned N2Size = N2->getSize();
2260   if (N2Size == 0) return;   // No edges to map to.
2261
2262   for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2263     const DSNodeHandle &N1NH = N1->getLink(i);
2264     // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2265     // aligned right).
2266     if (!N1NH.isNull()) {
2267       if (unsigned(N2Idx)+i < N2Size)
2268         computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2269       else
2270         computeNodeMapping(N1NH,
2271                            N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2272     }
2273   }
2274 }
2275
2276
2277 /// computeGToGGMapping - Compute the mapping of nodes in the global graph to
2278 /// nodes in this graph.
2279 void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
2280   DSGraph &GG = *getGlobalsGraph();
2281
2282   DSScalarMap &SM = getScalarMap();
2283   for (DSScalarMap::global_iterator I = SM.global_begin(),
2284          E = SM.global_end(); I != E; ++I)
2285     DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2286 }
2287                                 
2288 /// computeGGToGMapping - Compute the mapping of nodes in the global graph to
2289 /// nodes in this graph.  Note that any uses of this method are probably bugs,
2290 /// unless it is known that the globals graph has been merged into this graph!
2291 void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2292   NodeMapTy NodeMap;
2293   computeGToGGMapping(NodeMap);
2294
2295   while (!NodeMap.empty()) {
2296     InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2297                                      NodeMap.begin()->first));
2298     NodeMap.erase(NodeMap.begin());
2299   }
2300 }
2301                                 
2302
2303 /// computeCalleeCallerMapping - Given a call from a function in the current
2304 /// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2305 /// mapping of nodes from the callee to nodes in the caller.
2306 void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2307                                          DSGraph &CalleeGraph,
2308                                          NodeMapTy &NodeMap) {
2309
2310   DSCallSite CalleeArgs =
2311     CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
2312   
2313   computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2314
2315   unsigned NumArgs = CS.getNumPtrArgs();
2316   if (NumArgs > CalleeArgs.getNumPtrArgs())
2317     NumArgs = CalleeArgs.getNumPtrArgs();
2318
2319   for (unsigned i = 0; i != NumArgs; ++i)
2320     computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2321     
2322   // Map the nodes that are pointed to by globals.
2323   DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2324   DSScalarMap &CallerSM = getScalarMap();
2325
2326   if (CalleeSM.global_size() >= CallerSM.global_size()) {
2327     for (DSScalarMap::global_iterator GI = CallerSM.global_begin(), 
2328            E = CallerSM.global_end(); GI != E; ++GI)
2329       if (CalleeSM.global_count(*GI))
2330         computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2331   } else {
2332     for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(), 
2333            E = CalleeSM.global_end(); GI != E; ++GI)
2334       if (CallerSM.global_count(*GI))
2335         computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2336   }
2337 }