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