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