Silenced a VC++ warning.
[oota-llvm.git] / lib / Analysis / IPA / Andersens.cpp
1 //===- Andersens.cpp - Andersen's Interprocedural Alias 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 defines an implementation of Andersen's interprocedural alias
11 // analysis
12 //
13 // In pointer analysis terms, this is a subset-based, flow-insensitive,
14 // field-sensitive, and context-insensitive algorithm pointer algorithm.
15 //
16 // This algorithm is implemented as three stages:
17 //   1. Object identification.
18 //   2. Inclusion constraint identification.
19 //   3. Offline constraint graph optimization
20 //   4. Inclusion constraint solving.
21 //
22 // The object identification stage identifies all of the memory objects in the
23 // program, which includes globals, heap allocated objects, and stack allocated
24 // objects.
25 //
26 // The inclusion constraint identification stage finds all inclusion constraints
27 // in the program by scanning the program, looking for pointer assignments and
28 // other statements that effect the points-to graph.  For a statement like "A =
29 // B", this statement is processed to indicate that A can point to anything that
30 // B can point to.  Constraints can handle copies, loads, and stores, and
31 // address taking.
32 //
33 // The offline constraint graph optimization portion includes offline variable
34 // substitution algorithms intended to computer pointer and location
35 // equivalences.  Pointer equivalences are those pointers that will have the
36 // same points-to sets, and location equivalences are those variables that
37 // always appear together in points-to sets.
38 //
39 // The inclusion constraint solving phase iteratively propagates the inclusion
40 // constraints until a fixed point is reached.  This is an O(N^3) algorithm.
41 //
42 // Function constraints are handled as if they were structs with X fields.
43 // Thus, an access to argument X of function Y is an access to node index
44 // getNode(Y) + X.  This representation allows handling of indirect calls
45 // without any issues.  To wit, an indirect call Y(a,b) is equivalent to
46 // *(Y + 1) = a, *(Y + 2) = b.
47 // The return node for a function is always located at getNode(F) +
48 // CallReturnPos. The arguments start at getNode(F) + CallArgPos.
49 //
50 // Future Improvements:
51 //   Offline detection of online cycles.  Use of BDD's.
52 //===----------------------------------------------------------------------===//
53
54 #define DEBUG_TYPE "anders-aa"
55 #include "llvm/Constants.h"
56 #include "llvm/DerivedTypes.h"
57 #include "llvm/Instructions.h"
58 #include "llvm/Module.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/InstIterator.h"
62 #include "llvm/Support/InstVisitor.h"
63 #include "llvm/Analysis/AliasAnalysis.h"
64 #include "llvm/Analysis/Passes.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/ADT/Statistic.h"
67 #include "llvm/ADT/SparseBitVector.h"
68 #include "llvm/ADT/DenseSet.h"
69 #include <algorithm>
70 #include <set>
71 #include <list>
72 #include <stack>
73 #include <vector>
74
75 using namespace llvm;
76 STATISTIC(NumIters      , "Number of iterations to reach convergence");
77 STATISTIC(NumConstraints, "Number of constraints");
78 STATISTIC(NumNodes      , "Number of nodes");
79 STATISTIC(NumUnified    , "Number of variables unified");
80
81 namespace {
82   const unsigned SelfRep = (unsigned)-1;
83   const unsigned Unvisited = (unsigned)-1;
84   // Position of the function return node relative to the function node.
85   const unsigned CallReturnPos = 1;
86   // Position of the function call node relative to the function node.
87   const unsigned CallFirstArgPos = 2;
88
89   struct BitmapKeyInfo {
90     static inline SparseBitVector<> *getEmptyKey() {
91       return reinterpret_cast<SparseBitVector<> *>(-1);
92     }
93     static inline SparseBitVector<> *getTombstoneKey() {
94       return reinterpret_cast<SparseBitVector<> *>(-2);
95     }
96     static unsigned getHashValue(const SparseBitVector<> *bitmap) {
97       return bitmap->getHashValue();
98     }
99     static bool isEqual(const SparseBitVector<> *LHS,
100                         const SparseBitVector<> *RHS) {
101       if (LHS == RHS)
102         return true;
103       else if (LHS == getEmptyKey() || RHS == getEmptyKey()
104                || LHS == getTombstoneKey() || RHS == getTombstoneKey())
105         return false;
106
107       return *LHS == *RHS;
108     }
109
110     static bool isPod() { return true; }
111   };
112
113   class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
114                                       private InstVisitor<Andersens> {
115     struct Node;
116
117     /// Constraint - Objects of this structure are used to represent the various
118     /// constraints identified by the algorithm.  The constraints are 'copy',
119     /// for statements like "A = B", 'load' for statements like "A = *B",
120     /// 'store' for statements like "*A = B", and AddressOf for statements like
121     /// A = alloca;  The Offset is applied as *(A + K) = B for stores,
122     /// A = *(B + K) for loads, and A = B + K for copies.  It is
123     /// illegal on addressof constraints (because it is statically
124     /// resolvable to A = &C where C = B + K)
125
126     struct Constraint {
127       enum ConstraintType { Copy, Load, Store, AddressOf } Type;
128       unsigned Dest;
129       unsigned Src;
130       unsigned Offset;
131
132       Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
133         : Type(Ty), Dest(D), Src(S), Offset(O) {
134         assert(Offset == 0 || Ty != AddressOf &&
135                "Offset is illegal on addressof constraints");
136       }
137
138       bool operator==(const Constraint &RHS) const {
139         return RHS.Type == Type
140           && RHS.Dest == Dest
141           && RHS.Src == Src
142           && RHS.Offset == Offset;
143       }
144
145       bool operator!=(const Constraint &RHS) const {
146         return !(*this == RHS);
147       }
148
149       bool operator<(const Constraint &RHS) const {
150         if (RHS.Type != Type)
151           return RHS.Type < Type;
152         else if (RHS.Dest != Dest)
153           return RHS.Dest < Dest;
154         else if (RHS.Src != Src)
155           return RHS.Src < Src;
156         return RHS.Offset < Offset;
157       }
158     };
159
160     struct ConstraintKeyInfo {
161       static inline Constraint getEmptyKey() {
162         return Constraint(Constraint::Copy, ~0UL, ~0UL, ~0UL);
163       }
164       static inline Constraint getTombstoneKey() {
165         return Constraint(Constraint::Copy, ~0UL - 1, ~0UL - 1, ~0UL - 1);
166       }
167       static unsigned getHashValue(const Constraint &C) {
168         return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
169       }
170       static bool isEqual(const Constraint &LHS,
171                           const Constraint &RHS) {
172         return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
173           && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
174       }
175     };
176
177     // Node class - This class is used to represent a node in the constraint
178     // graph.  Due to various optimizations, it is not always the case that
179     // there is a mapping from a Node to a Value.  In particular, we add
180     // artificial Node's that represent the set of pointed-to variables shared
181     // for each location equivalent Node.
182     struct Node {
183       Value *Val;
184       SparseBitVector<> *Edges;
185       SparseBitVector<> *PointsTo;
186       SparseBitVector<> *OldPointsTo;
187       bool Changed;
188       std::list<Constraint> Constraints;
189
190       // Pointer and location equivalence labels
191       unsigned PointerEquivLabel;
192       unsigned LocationEquivLabel;
193       // Predecessor edges, both real and implicit
194       SparseBitVector<> *PredEdges;
195       SparseBitVector<> *ImplicitPredEdges;
196       // Set of nodes that point to us, only use for location equivalence.
197       SparseBitVector<> *PointedToBy;
198       // Number of incoming edges, used during variable substitution to early
199       // free the points-to sets
200       unsigned NumInEdges;
201       // True if our points-to set is in the Set2PEClass map
202       bool StoredInHash;
203       // True if our node has no indirect constraints (complex or otherwise)
204       bool Direct;
205       // True if the node is address taken, *or* it is part of a group of nodes
206       // that must be kept together.  This is set to true for functions and
207       // their arg nodes, which must be kept at the same position relative to
208       // their base function node.
209       bool AddressTaken;
210
211       // Nodes in cycles (or in equivalence classes) are united together using a
212       // standard union-find representation with path compression.  NodeRep
213       // gives the index into GraphNodes for the representative Node.
214       unsigned NodeRep;
215     public:
216
217       Node(bool direct = true) :
218         Val(0), Edges(0), PointsTo(0), OldPointsTo(0), Changed(false),
219         PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
220         ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
221         StoredInHash(false), Direct(direct), AddressTaken(false),
222         NodeRep(SelfRep) { }
223
224       Node *setValue(Value *V) {
225         assert(Val == 0 && "Value already set for this node!");
226         Val = V;
227         return this;
228       }
229
230       /// getValue - Return the LLVM value corresponding to this node.
231       ///
232       Value *getValue() const { return Val; }
233
234       /// addPointerTo - Add a pointer to the list of pointees of this node,
235       /// returning true if this caused a new pointer to be added, or false if
236       /// we already knew about the points-to relation.
237       bool addPointerTo(unsigned Node) {
238         return PointsTo->test_and_set(Node);
239       }
240
241       /// intersects - Return true if the points-to set of this node intersects
242       /// with the points-to set of the specified node.
243       bool intersects(Node *N) const;
244
245       /// intersectsIgnoring - Return true if the points-to set of this node
246       /// intersects with the points-to set of the specified node on any nodes
247       /// except for the specified node to ignore.
248       bool intersectsIgnoring(Node *N, unsigned) const;
249     };
250
251     /// GraphNodes - This vector is populated as part of the object
252     /// identification stage of the analysis, which populates this vector with a
253     /// node for each memory object and fills in the ValueNodes map.
254     std::vector<Node> GraphNodes;
255
256     /// ValueNodes - This map indicates the Node that a particular Value* is
257     /// represented by.  This contains entries for all pointers.
258     DenseMap<Value*, unsigned> ValueNodes;
259
260     /// ObjectNodes - This map contains entries for each memory object in the
261     /// program: globals, alloca's and mallocs.
262     DenseMap<Value*, unsigned> ObjectNodes;
263
264     /// ReturnNodes - This map contains an entry for each function in the
265     /// program that returns a value.
266     DenseMap<Function*, unsigned> ReturnNodes;
267
268     /// VarargNodes - This map contains the entry used to represent all pointers
269     /// passed through the varargs portion of a function call for a particular
270     /// function.  An entry is not present in this map for functions that do not
271     /// take variable arguments.
272     DenseMap<Function*, unsigned> VarargNodes;
273
274
275     /// Constraints - This vector contains a list of all of the constraints
276     /// identified by the program.
277     std::vector<Constraint> Constraints;
278
279     // Map from graph node to maximum K value that is allowed (for functions,
280     // this is equivalent to the number of arguments + CallFirstArgPos)
281     std::map<unsigned, unsigned> MaxK;
282
283     /// This enum defines the GraphNodes indices that correspond to important
284     /// fixed sets.
285     enum {
286       UniversalSet = 0,
287       NullPtr      = 1,
288       NullObject   = 2,
289       NumberSpecialNodes
290     };
291     // Stack for Tarjan's
292     std::stack<unsigned> SCCStack;
293     // Topological Index -> Graph node
294     std::vector<unsigned> Topo2Node;
295     // Graph Node -> Topological Index;
296     std::vector<unsigned> Node2Topo;
297     // Map from Graph Node to DFS number
298     std::vector<unsigned> Node2DFS;
299     // Map from Graph Node to Deleted from graph.
300     std::vector<bool> Node2Deleted;
301     // Current DFS and RPO numbers
302     unsigned DFSNumber;
303     unsigned RPONumber;
304
305     // Offline variable substitution related things
306
307     // Temporary rep storage, used because we can't collapse SCC's in the
308     // predecessor graph by uniting the variables permanently, we can only do so
309     // for the successor graph.
310     std::vector<unsigned> VSSCCRep;
311     // Mapping from node to whether we have visited it during SCC finding yet.
312     std::vector<bool> Node2Visited;
313     // During variable substitution, we create unknowns to represent the unknown
314     // value that is a dereference of a variable.  These nodes are known as
315     // "ref" nodes (since they represent the value of dereferences).
316     unsigned FirstRefNode;
317     // During HVN, we create represent address taken nodes as if they were
318     // unknown (since HVN, unlike HU, does not evaluate unions).
319     unsigned FirstAdrNode;
320     // Current pointer equivalence class number
321     unsigned PEClass;
322     // Mapping from points-to sets to equivalence classes
323     typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
324     BitVectorMap Set2PEClass;
325     // Mapping from pointer equivalences to the representative node.  -1 if we
326     // have no representative node for this pointer equivalence class yet.
327     std::vector<int> PEClass2Node;
328     // Mapping from pointer equivalences to representative node.  This includes
329     // pointer equivalent but not location equivalent variables. -1 if we have
330     // no representative node for this pointer equivalence class yet.
331     std::vector<int> PENLEClass2Node;
332
333   public:
334     static char ID;
335     Andersens() : ModulePass((intptr_t)&ID) {}
336
337     bool runOnModule(Module &M) {
338       InitializeAliasAnalysis(this);
339       IdentifyObjects(M);
340       CollectConstraints(M);
341 #undef DEBUG_TYPE
342 #define DEBUG_TYPE "anders-aa-constraints"
343       DEBUG(PrintConstraints());
344 #undef DEBUG_TYPE
345 #define DEBUG_TYPE "anders-aa"
346       SolveConstraints();
347       DEBUG(PrintPointsToGraph());
348
349       // Free the constraints list, as we don't need it to respond to alias
350       // requests.
351       ObjectNodes.clear();
352       ReturnNodes.clear();
353       VarargNodes.clear();
354       std::vector<Constraint>().swap(Constraints);
355       return false;
356     }
357
358     void releaseMemory() {
359       // FIXME: Until we have transitively required passes working correctly,
360       // this cannot be enabled!  Otherwise, using -count-aa with the pass
361       // causes memory to be freed too early. :(
362 #if 0
363       // The memory objects and ValueNodes data structures at the only ones that
364       // are still live after construction.
365       std::vector<Node>().swap(GraphNodes);
366       ValueNodes.clear();
367 #endif
368     }
369
370     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
371       AliasAnalysis::getAnalysisUsage(AU);
372       AU.setPreservesAll();                         // Does not transform code
373     }
374
375     //------------------------------------------------
376     // Implement the AliasAnalysis API
377     //
378     AliasResult alias(const Value *V1, unsigned V1Size,
379                       const Value *V2, unsigned V2Size);
380     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
381     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
382     void getMustAliases(Value *P, std::vector<Value*> &RetVals);
383     bool pointsToConstantMemory(const Value *P);
384
385     virtual void deleteValue(Value *V) {
386       ValueNodes.erase(V);
387       getAnalysis<AliasAnalysis>().deleteValue(V);
388     }
389
390     virtual void copyValue(Value *From, Value *To) {
391       ValueNodes[To] = ValueNodes[From];
392       getAnalysis<AliasAnalysis>().copyValue(From, To);
393     }
394
395   private:
396     /// getNode - Return the node corresponding to the specified pointer scalar.
397     ///
398     unsigned getNode(Value *V) {
399       if (Constant *C = dyn_cast<Constant>(V))
400         if (!isa<GlobalValue>(C))
401           return getNodeForConstantPointer(C);
402
403       DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
404       if (I == ValueNodes.end()) {
405 #ifndef NDEBUG
406         V->dump();
407 #endif
408         assert(0 && "Value does not have a node in the points-to graph!");
409       }
410       return I->second;
411     }
412
413     /// getObject - Return the node corresponding to the memory object for the
414     /// specified global or allocation instruction.
415     unsigned getObject(Value *V) {
416       DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
417       assert(I != ObjectNodes.end() &&
418              "Value does not have an object in the points-to graph!");
419       return I->second;
420     }
421
422     /// getReturnNode - Return the node representing the return value for the
423     /// specified function.
424     unsigned getReturnNode(Function *F) {
425       DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
426       assert(I != ReturnNodes.end() && "Function does not return a value!");
427       return I->second;
428     }
429
430     /// getVarargNode - Return the node representing the variable arguments
431     /// formal for the specified function.
432     unsigned getVarargNode(Function *F) {
433       DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
434       assert(I != VarargNodes.end() && "Function does not take var args!");
435       return I->second;
436     }
437
438     /// getNodeValue - Get the node for the specified LLVM value and set the
439     /// value for it to be the specified value.
440     unsigned getNodeValue(Value &V) {
441       unsigned Index = getNode(&V);
442       GraphNodes[Index].setValue(&V);
443       return Index;
444     }
445
446     unsigned UniteNodes(unsigned First, unsigned Second);
447     unsigned FindNode(unsigned Node);
448
449     void IdentifyObjects(Module &M);
450     void CollectConstraints(Module &M);
451     bool AnalyzeUsesOfFunction(Value *);
452     void CreateConstraintGraph();
453     void OptimizeConstraints();
454     unsigned FindEquivalentNode(unsigned, unsigned);
455     void ClumpAddressTaken();
456     void RewriteConstraints();
457     void HU();
458     void HVN();
459     void UnitePointerEquivalences();
460     void SolveConstraints();
461     void QueryNode(unsigned Node);
462     void Condense(unsigned Node);
463     void HUValNum(unsigned Node);
464     void HVNValNum(unsigned Node);
465     unsigned getNodeForConstantPointer(Constant *C);
466     unsigned getNodeForConstantPointerTarget(Constant *C);
467     void AddGlobalInitializerConstraints(unsigned, Constant *C);
468
469     void AddConstraintsForNonInternalLinkage(Function *F);
470     void AddConstraintsForCall(CallSite CS, Function *F);
471     bool AddConstraintsForExternalCall(CallSite CS, Function *F);
472
473
474     void PrintNode(Node *N);
475     void PrintConstraints();
476     void PrintConstraint(const Constraint &);
477     void PrintLabels();
478     void PrintPointsToGraph();
479
480     //===------------------------------------------------------------------===//
481     // Instruction visitation methods for adding constraints
482     //
483     friend class InstVisitor<Andersens>;
484     void visitReturnInst(ReturnInst &RI);
485     void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
486     void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
487     void visitCallSite(CallSite CS);
488     void visitAllocationInst(AllocationInst &AI);
489     void visitLoadInst(LoadInst &LI);
490     void visitStoreInst(StoreInst &SI);
491     void visitGetElementPtrInst(GetElementPtrInst &GEP);
492     void visitPHINode(PHINode &PN);
493     void visitCastInst(CastInst &CI);
494     void visitICmpInst(ICmpInst &ICI) {} // NOOP!
495     void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
496     void visitSelectInst(SelectInst &SI);
497     void visitVAArg(VAArgInst &I);
498     void visitInstruction(Instruction &I);
499
500   };
501
502   char Andersens::ID = 0;
503   RegisterPass<Andersens> X("anders-aa",
504                             "Andersen's Interprocedural Alias Analysis");
505   RegisterAnalysisGroup<AliasAnalysis> Y(X);
506 }
507
508 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
509
510 //===----------------------------------------------------------------------===//
511 //                  AliasAnalysis Interface Implementation
512 //===----------------------------------------------------------------------===//
513
514 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
515                                             const Value *V2, unsigned V2Size) {
516   Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
517   Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
518
519   // Check to see if the two pointers are known to not alias.  They don't alias
520   // if their points-to sets do not intersect.
521   if (!N1->intersectsIgnoring(N2, NullObject))
522     return NoAlias;
523
524   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
525 }
526
527 AliasAnalysis::ModRefResult
528 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
529   // The only thing useful that we can contribute for mod/ref information is
530   // when calling external function calls: if we know that memory never escapes
531   // from the program, it cannot be modified by an external call.
532   //
533   // NOTE: This is not really safe, at least not when the entire program is not
534   // available.  The deal is that the external function could call back into the
535   // program and modify stuff.  We ignore this technical niggle for now.  This
536   // is, after all, a "research quality" implementation of Andersen's analysis.
537   if (Function *F = CS.getCalledFunction())
538     if (F->isDeclaration()) {
539       Node *N1 = &GraphNodes[FindNode(getNode(P))];
540
541       if (N1->PointsTo->empty())
542         return NoModRef;
543
544       if (!N1->PointsTo->test(UniversalSet))
545         return NoModRef;  // P doesn't point to the universal set.
546     }
547
548   return AliasAnalysis::getModRefInfo(CS, P, Size);
549 }
550
551 AliasAnalysis::ModRefResult
552 Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
553   return AliasAnalysis::getModRefInfo(CS1,CS2);
554 }
555
556 /// getMustAlias - We can provide must alias information if we know that a
557 /// pointer can only point to a specific function or the null pointer.
558 /// Unfortunately we cannot determine must-alias information for global
559 /// variables or any other memory memory objects because we do not track whether
560 /// a pointer points to the beginning of an object or a field of it.
561 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
562   Node *N = &GraphNodes[FindNode(getNode(P))];
563   if (N->PointsTo->count() == 1) {
564     Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
565     // If a function is the only object in the points-to set, then it must be
566     // the destination.  Note that we can't handle global variables here,
567     // because we don't know if the pointer is actually pointing to a field of
568     // the global or to the beginning of it.
569     if (Value *V = Pointee->getValue()) {
570       if (Function *F = dyn_cast<Function>(V))
571         RetVals.push_back(F);
572     } else {
573       // If the object in the points-to set is the null object, then the null
574       // pointer is a must alias.
575       if (Pointee == &GraphNodes[NullObject])
576         RetVals.push_back(Constant::getNullValue(P->getType()));
577     }
578   }
579   AliasAnalysis::getMustAliases(P, RetVals);
580 }
581
582 /// pointsToConstantMemory - If we can determine that this pointer only points
583 /// to constant memory, return true.  In practice, this means that if the
584 /// pointer can only point to constant globals, functions, or the null pointer,
585 /// return true.
586 ///
587 bool Andersens::pointsToConstantMemory(const Value *P) {
588   Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
589   unsigned i;
590
591   for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
592        bi != N->PointsTo->end();
593        ++bi) {
594     i = *bi;
595     Node *Pointee = &GraphNodes[i];
596     if (Value *V = Pointee->getValue()) {
597       if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
598                                    !cast<GlobalVariable>(V)->isConstant()))
599         return AliasAnalysis::pointsToConstantMemory(P);
600     } else {
601       if (i != NullObject)
602         return AliasAnalysis::pointsToConstantMemory(P);
603     }
604   }
605
606   return true;
607 }
608
609 //===----------------------------------------------------------------------===//
610 //                       Object Identification Phase
611 //===----------------------------------------------------------------------===//
612
613 /// IdentifyObjects - This stage scans the program, adding an entry to the
614 /// GraphNodes list for each memory object in the program (global stack or
615 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
616 ///
617 void Andersens::IdentifyObjects(Module &M) {
618   unsigned NumObjects = 0;
619
620   // Object #0 is always the universal set: the object that we don't know
621   // anything about.
622   assert(NumObjects == UniversalSet && "Something changed!");
623   ++NumObjects;
624
625   // Object #1 always represents the null pointer.
626   assert(NumObjects == NullPtr && "Something changed!");
627   ++NumObjects;
628
629   // Object #2 always represents the null object (the object pointed to by null)
630   assert(NumObjects == NullObject && "Something changed!");
631   ++NumObjects;
632
633   // Add all the globals first.
634   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
635        I != E; ++I) {
636     ObjectNodes[I] = NumObjects++;
637     ValueNodes[I] = NumObjects++;
638   }
639
640   // Add nodes for all of the functions and the instructions inside of them.
641   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
642     // The function itself is a memory object.
643     unsigned First = NumObjects;
644     ValueNodes[F] = NumObjects++;
645     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
646       ReturnNodes[F] = NumObjects++;
647     if (F->getFunctionType()->isVarArg())
648       VarargNodes[F] = NumObjects++;
649
650
651     // Add nodes for all of the incoming pointer arguments.
652     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
653          I != E; ++I)
654       {
655         if (isa<PointerType>(I->getType()))
656           ValueNodes[I] = NumObjects++;
657       }
658     MaxK[First] = NumObjects - First;
659
660     // Scan the function body, creating a memory object for each heap/stack
661     // allocation in the body of the function and a node to represent all
662     // pointer values defined by instructions and used as operands.
663     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
664       // If this is an heap or stack allocation, create a node for the memory
665       // object.
666       if (isa<PointerType>(II->getType())) {
667         ValueNodes[&*II] = NumObjects++;
668         if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
669           ObjectNodes[AI] = NumObjects++;
670       }
671     }
672   }
673
674   // Now that we know how many objects to create, make them all now!
675   GraphNodes.resize(NumObjects);
676   NumNodes += NumObjects;
677 }
678
679 //===----------------------------------------------------------------------===//
680 //                     Constraint Identification Phase
681 //===----------------------------------------------------------------------===//
682
683 /// getNodeForConstantPointer - Return the node corresponding to the constant
684 /// pointer itself.
685 unsigned Andersens::getNodeForConstantPointer(Constant *C) {
686   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
687
688   if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
689     return NullPtr;
690   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
691     return getNode(GV);
692   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
693     switch (CE->getOpcode()) {
694     case Instruction::GetElementPtr:
695       return getNodeForConstantPointer(CE->getOperand(0));
696     case Instruction::IntToPtr:
697       return UniversalSet;
698     case Instruction::BitCast:
699       return getNodeForConstantPointer(CE->getOperand(0));
700     default:
701       cerr << "Constant Expr not yet handled: " << *CE << "\n";
702       assert(0);
703     }
704   } else {
705     assert(0 && "Unknown constant pointer!");
706   }
707   return 0;
708 }
709
710 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
711 /// specified constant pointer.
712 unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
713   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
714
715   if (isa<ConstantPointerNull>(C))
716     return NullObject;
717   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
718     return getObject(GV);
719   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
720     switch (CE->getOpcode()) {
721     case Instruction::GetElementPtr:
722       return getNodeForConstantPointerTarget(CE->getOperand(0));
723     case Instruction::IntToPtr:
724       return UniversalSet;
725     case Instruction::BitCast:
726       return getNodeForConstantPointerTarget(CE->getOperand(0));
727     default:
728       cerr << "Constant Expr not yet handled: " << *CE << "\n";
729       assert(0);
730     }
731   } else {
732     assert(0 && "Unknown constant pointer!");
733   }
734   return 0;
735 }
736
737 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
738 /// object N, which contains values indicated by C.
739 void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
740                                                 Constant *C) {
741   if (C->getType()->isFirstClassType()) {
742     if (isa<PointerType>(C->getType()))
743       Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
744                                        getNodeForConstantPointer(C)));
745   } else if (C->isNullValue()) {
746     Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
747                                      NullObject));
748     return;
749   } else if (!isa<UndefValue>(C)) {
750     // If this is an array or struct, include constraints for each element.
751     assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
752     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
753       AddGlobalInitializerConstraints(NodeIndex,
754                                       cast<Constant>(C->getOperand(i)));
755   }
756 }
757
758 /// AddConstraintsForNonInternalLinkage - If this function does not have
759 /// internal linkage, realize that we can't trust anything passed into or
760 /// returned by this function.
761 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
762   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
763     if (isa<PointerType>(I->getType()))
764       // If this is an argument of an externally accessible function, the
765       // incoming pointer might point to anything.
766       Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
767                                        UniversalSet));
768 }
769
770 /// AddConstraintsForCall - If this is a call to a "known" function, add the
771 /// constraints and return true.  If this is a call to an unknown function,
772 /// return false.
773 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
774   assert(F->isDeclaration() && "Not an external function!");
775
776   // These functions don't induce any points-to constraints.
777   if (F->getName() == "atoi" || F->getName() == "atof" ||
778       F->getName() == "atol" || F->getName() == "atoll" ||
779       F->getName() == "remove" || F->getName() == "unlink" ||
780       F->getName() == "rename" || F->getName() == "memcmp" ||
781       F->getName() == "llvm.memset.i32" ||
782       F->getName() == "llvm.memset.i64" ||
783       F->getName() == "strcmp" || F->getName() == "strncmp" ||
784       F->getName() == "execl" || F->getName() == "execlp" ||
785       F->getName() == "execle" || F->getName() == "execv" ||
786       F->getName() == "execvp" || F->getName() == "chmod" ||
787       F->getName() == "puts" || F->getName() == "write" ||
788       F->getName() == "open" || F->getName() == "create" ||
789       F->getName() == "truncate" || F->getName() == "chdir" ||
790       F->getName() == "mkdir" || F->getName() == "rmdir" ||
791       F->getName() == "read" || F->getName() == "pipe" ||
792       F->getName() == "wait" || F->getName() == "time" ||
793       F->getName() == "stat" || F->getName() == "fstat" ||
794       F->getName() == "lstat" || F->getName() == "strtod" ||
795       F->getName() == "strtof" || F->getName() == "strtold" ||
796       F->getName() == "fopen" || F->getName() == "fdopen" ||
797       F->getName() == "freopen" ||
798       F->getName() == "fflush" || F->getName() == "feof" ||
799       F->getName() == "fileno" || F->getName() == "clearerr" ||
800       F->getName() == "rewind" || F->getName() == "ftell" ||
801       F->getName() == "ferror" || F->getName() == "fgetc" ||
802       F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
803       F->getName() == "fwrite" || F->getName() == "fread" ||
804       F->getName() == "fgets" || F->getName() == "ungetc" ||
805       F->getName() == "fputc" ||
806       F->getName() == "fputs" || F->getName() == "putc" ||
807       F->getName() == "ftell" || F->getName() == "rewind" ||
808       F->getName() == "_IO_putc" || F->getName() == "fseek" ||
809       F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
810       F->getName() == "printf" || F->getName() == "fprintf" ||
811       F->getName() == "sprintf" || F->getName() == "vprintf" ||
812       F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
813       F->getName() == "scanf" || F->getName() == "fscanf" ||
814       F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
815       F->getName() == "modf")
816     return true;
817
818
819   // These functions do induce points-to edges.
820   if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
821       F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
822       F->getName() == "memmove") {
823
824     // *Dest = *Src, which requires an artificial graph node to represent the
825     // constraint.  It is broken up into *Dest = temp, temp = *Src
826     unsigned FirstArg = getNode(CS.getArgument(0));
827     unsigned SecondArg = getNode(CS.getArgument(1));
828     unsigned TempArg = GraphNodes.size();
829     GraphNodes.push_back(Node());
830     Constraints.push_back(Constraint(Constraint::Store,
831                                      FirstArg, TempArg));
832     Constraints.push_back(Constraint(Constraint::Load,
833                                      TempArg, SecondArg));
834     return true;
835   }
836
837   // Result = Arg0
838   if (F->getName() == "realloc" || F->getName() == "strchr" ||
839       F->getName() == "strrchr" || F->getName() == "strstr" ||
840       F->getName() == "strtok") {
841     Constraints.push_back(Constraint(Constraint::Copy,
842                                      getNode(CS.getInstruction()),
843                                      getNode(CS.getArgument(0))));
844     return true;
845   }
846
847   return false;
848 }
849
850
851
852 /// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
853 /// If this is used by anything complex (i.e., the address escapes), return
854 /// true.
855 bool Andersens::AnalyzeUsesOfFunction(Value *V) {
856
857   if (!isa<PointerType>(V->getType())) return true;
858
859   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
860     if (dyn_cast<LoadInst>(*UI)) {
861       return false;
862     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
863       if (V == SI->getOperand(1)) {
864         return false;
865       } else if (SI->getOperand(1)) {
866         return true;  // Storing the pointer
867       }
868     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
869       if (AnalyzeUsesOfFunction(GEP)) return true;
870     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
871       // Make sure that this is just the function being called, not that it is
872       // passing into the function.
873       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
874         if (CI->getOperand(i) == V) return true;
875     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
876       // Make sure that this is just the function being called, not that it is
877       // passing into the function.
878       for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
879         if (II->getOperand(i) == V) return true;
880     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
881       if (CE->getOpcode() == Instruction::GetElementPtr ||
882           CE->getOpcode() == Instruction::BitCast) {
883         if (AnalyzeUsesOfFunction(CE))
884           return true;
885       } else {
886         return true;
887       }
888     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
889       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
890         return true;  // Allow comparison against null.
891     } else if (dyn_cast<FreeInst>(*UI)) {
892       return false;
893     } else {
894       return true;
895     }
896   return false;
897 }
898
899 /// CollectConstraints - This stage scans the program, adding a constraint to
900 /// the Constraints list for each instruction in the program that induces a
901 /// constraint, and setting up the initial points-to graph.
902 ///
903 void Andersens::CollectConstraints(Module &M) {
904   // First, the universal set points to itself.
905   Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
906                                    UniversalSet));
907   Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
908                                    UniversalSet));
909
910   // Next, the null pointer points to the null object.
911   Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
912
913   // Next, add any constraints on global variables and their initializers.
914   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
915        I != E; ++I) {
916     // Associate the address of the global object as pointing to the memory for
917     // the global: &G = <G memory>
918     unsigned ObjectIndex = getObject(I);
919     Node *Object = &GraphNodes[ObjectIndex];
920     Object->setValue(I);
921     Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
922                                      ObjectIndex));
923
924     if (I->hasInitializer()) {
925       AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
926     } else {
927       // If it doesn't have an initializer (i.e. it's defined in another
928       // translation unit), it points to the universal set.
929       Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
930                                        UniversalSet));
931     }
932   }
933
934   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
935     // Set up the return value node.
936     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
937       GraphNodes[getReturnNode(F)].setValue(F);
938     if (F->getFunctionType()->isVarArg())
939       GraphNodes[getVarargNode(F)].setValue(F);
940
941     // Set up incoming argument nodes.
942     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
943          I != E; ++I)
944       if (isa<PointerType>(I->getType()))
945         getNodeValue(*I);
946
947     // At some point we should just add constraints for the escaping functions
948     // at solve time, but this slows down solving. For now, we simply mark
949     // address taken functions as escaping and treat them as external.
950     if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
951       AddConstraintsForNonInternalLinkage(F);
952
953     if (!F->isDeclaration()) {
954       // Scan the function body, creating a memory object for each heap/stack
955       // allocation in the body of the function and a node to represent all
956       // pointer values defined by instructions and used as operands.
957       visit(F);
958     } else {
959       // External functions that return pointers return the universal set.
960       if (isa<PointerType>(F->getFunctionType()->getReturnType()))
961         Constraints.push_back(Constraint(Constraint::Copy,
962                                          getReturnNode(F),
963                                          UniversalSet));
964
965       // Any pointers that are passed into the function have the universal set
966       // stored into them.
967       for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
968            I != E; ++I)
969         if (isa<PointerType>(I->getType())) {
970           // Pointers passed into external functions could have anything stored
971           // through them.
972           Constraints.push_back(Constraint(Constraint::Store, getNode(I),
973                                            UniversalSet));
974           // Memory objects passed into external function calls can have the
975           // universal set point to them.
976           Constraints.push_back(Constraint(Constraint::Copy,
977                                            UniversalSet,
978                                            getNode(I)));
979         }
980
981       // If this is an external varargs function, it can also store pointers
982       // into any pointers passed through the varargs section.
983       if (F->getFunctionType()->isVarArg())
984         Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
985                                          UniversalSet));
986     }
987   }
988   NumConstraints += Constraints.size();
989 }
990
991
992 void Andersens::visitInstruction(Instruction &I) {
993 #ifdef NDEBUG
994   return;          // This function is just a big assert.
995 #endif
996   if (isa<BinaryOperator>(I))
997     return;
998   // Most instructions don't have any effect on pointer values.
999   switch (I.getOpcode()) {
1000   case Instruction::Br:
1001   case Instruction::Switch:
1002   case Instruction::Unwind:
1003   case Instruction::Unreachable:
1004   case Instruction::Free:
1005   case Instruction::ICmp:
1006   case Instruction::FCmp:
1007     return;
1008   default:
1009     // Is this something we aren't handling yet?
1010     cerr << "Unknown instruction: " << I;
1011     abort();
1012   }
1013 }
1014
1015 void Andersens::visitAllocationInst(AllocationInst &AI) {
1016   unsigned ObjectIndex = getObject(&AI);
1017   GraphNodes[ObjectIndex].setValue(&AI);
1018   Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1019                                    ObjectIndex));
1020 }
1021
1022 void Andersens::visitReturnInst(ReturnInst &RI) {
1023   if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1024     // return V   -->   <Copy/retval{F}/v>
1025     Constraints.push_back(Constraint(Constraint::Copy,
1026                                      getReturnNode(RI.getParent()->getParent()),
1027                                      getNode(RI.getOperand(0))));
1028 }
1029
1030 void Andersens::visitLoadInst(LoadInst &LI) {
1031   if (isa<PointerType>(LI.getType()))
1032     // P1 = load P2  -->  <Load/P1/P2>
1033     Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1034                                      getNode(LI.getOperand(0))));
1035 }
1036
1037 void Andersens::visitStoreInst(StoreInst &SI) {
1038   if (isa<PointerType>(SI.getOperand(0)->getType()))
1039     // store P1, P2  -->  <Store/P2/P1>
1040     Constraints.push_back(Constraint(Constraint::Store,
1041                                      getNode(SI.getOperand(1)),
1042                                      getNode(SI.getOperand(0))));
1043 }
1044
1045 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1046   // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1047   Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1048                                    getNode(GEP.getOperand(0))));
1049 }
1050
1051 void Andersens::visitPHINode(PHINode &PN) {
1052   if (isa<PointerType>(PN.getType())) {
1053     unsigned PNN = getNodeValue(PN);
1054     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1055       // P1 = phi P2, P3  -->  <Copy/P1/P2>, <Copy/P1/P3>, ...
1056       Constraints.push_back(Constraint(Constraint::Copy, PNN,
1057                                        getNode(PN.getIncomingValue(i))));
1058   }
1059 }
1060
1061 void Andersens::visitCastInst(CastInst &CI) {
1062   Value *Op = CI.getOperand(0);
1063   if (isa<PointerType>(CI.getType())) {
1064     if (isa<PointerType>(Op->getType())) {
1065       // P1 = cast P2  --> <Copy/P1/P2>
1066       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1067                                        getNode(CI.getOperand(0))));
1068     } else {
1069       // P1 = cast int --> <Copy/P1/Univ>
1070 #if 0
1071       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1072                                        UniversalSet));
1073 #else
1074       getNodeValue(CI);
1075 #endif
1076     }
1077   } else if (isa<PointerType>(Op->getType())) {
1078     // int = cast P1 --> <Copy/Univ/P1>
1079 #if 0
1080     Constraints.push_back(Constraint(Constraint::Copy,
1081                                      UniversalSet,
1082                                      getNode(CI.getOperand(0))));
1083 #else
1084     getNode(CI.getOperand(0));
1085 #endif
1086   }
1087 }
1088
1089 void Andersens::visitSelectInst(SelectInst &SI) {
1090   if (isa<PointerType>(SI.getType())) {
1091     unsigned SIN = getNodeValue(SI);
1092     // P1 = select C, P2, P3   ---> <Copy/P1/P2>, <Copy/P1/P3>
1093     Constraints.push_back(Constraint(Constraint::Copy, SIN,
1094                                      getNode(SI.getOperand(1))));
1095     Constraints.push_back(Constraint(Constraint::Copy, SIN,
1096                                      getNode(SI.getOperand(2))));
1097   }
1098 }
1099
1100 void Andersens::visitVAArg(VAArgInst &I) {
1101   assert(0 && "vaarg not handled yet!");
1102 }
1103
1104 /// AddConstraintsForCall - Add constraints for a call with actual arguments
1105 /// specified by CS to the function specified by F.  Note that the types of
1106 /// arguments might not match up in the case where this is an indirect call and
1107 /// the function pointer has been casted.  If this is the case, do something
1108 /// reasonable.
1109 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
1110   Value *CallValue = CS.getCalledValue();
1111   bool IsDeref = F == NULL;
1112
1113   // If this is a call to an external function, try to handle it directly to get
1114   // some taste of context sensitivity.
1115   if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
1116     return;
1117
1118   if (isa<PointerType>(CS.getType())) {
1119     unsigned CSN = getNode(CS.getInstruction());
1120     if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1121       if (IsDeref)
1122         Constraints.push_back(Constraint(Constraint::Load, CSN,
1123                                          getNode(CallValue), CallReturnPos));
1124       else
1125         Constraints.push_back(Constraint(Constraint::Copy, CSN,
1126                                          getNode(CallValue) + CallReturnPos));
1127     } else {
1128       // If the function returns a non-pointer value, handle this just like we
1129       // treat a nonpointer cast to pointer.
1130       Constraints.push_back(Constraint(Constraint::Copy, CSN,
1131                                        UniversalSet));
1132     }
1133   } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
1134     Constraints.push_back(Constraint(Constraint::Copy,
1135                                      UniversalSet,
1136                                      getNode(CallValue) + CallReturnPos));
1137   }
1138
1139   CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
1140   if (F) {
1141     // Direct Call
1142     Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1143     for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1144       if (isa<PointerType>(AI->getType())) {
1145         if (isa<PointerType>((*ArgI)->getType())) {
1146           // Copy the actual argument into the formal argument.
1147           Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1148                                            getNode(*ArgI)));
1149         } else {
1150           Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1151                                            UniversalSet));
1152         }
1153       } else if (isa<PointerType>((*ArgI)->getType())) {
1154         Constraints.push_back(Constraint(Constraint::Copy,
1155                                          UniversalSet,
1156                                          getNode(*ArgI)));
1157       }
1158   } else {
1159     //Indirect Call
1160     unsigned ArgPos = CallFirstArgPos;
1161     for (; ArgI != ArgE; ++ArgI) {
1162       if (isa<PointerType>((*ArgI)->getType())) {
1163         // Copy the actual argument into the formal argument.
1164         Constraints.push_back(Constraint(Constraint::Store,
1165                                          getNode(CallValue),
1166                                          getNode(*ArgI), ArgPos++));
1167       } else {
1168         Constraints.push_back(Constraint(Constraint::Store,
1169                                          getNode (CallValue),
1170                                          UniversalSet, ArgPos++));
1171       }
1172     }
1173   }
1174   // Copy all pointers passed through the varargs section to the varargs node.
1175   if (F && F->getFunctionType()->isVarArg())
1176     for (; ArgI != ArgE; ++ArgI)
1177       if (isa<PointerType>((*ArgI)->getType()))
1178         Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1179                                          getNode(*ArgI)));
1180   // If more arguments are passed in than we track, just drop them on the floor.
1181 }
1182
1183 void Andersens::visitCallSite(CallSite CS) {
1184   if (isa<PointerType>(CS.getType()))
1185     getNodeValue(*CS.getInstruction());
1186
1187   if (Function *F = CS.getCalledFunction()) {
1188     AddConstraintsForCall(CS, F);
1189   } else {
1190     AddConstraintsForCall(CS, NULL);
1191   }
1192 }
1193
1194 //===----------------------------------------------------------------------===//
1195 //                         Constraint Solving Phase
1196 //===----------------------------------------------------------------------===//
1197
1198 /// intersects - Return true if the points-to set of this node intersects
1199 /// with the points-to set of the specified node.
1200 bool Andersens::Node::intersects(Node *N) const {
1201   return PointsTo->intersects(N->PointsTo);
1202 }
1203
1204 /// intersectsIgnoring - Return true if the points-to set of this node
1205 /// intersects with the points-to set of the specified node on any nodes
1206 /// except for the specified node to ignore.
1207 bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1208   // TODO: If we are only going to call this with the same value for Ignoring,
1209   // we should move the special values out of the points-to bitmap.
1210   bool WeHadIt = PointsTo->test(Ignoring);
1211   bool NHadIt = N->PointsTo->test(Ignoring);
1212   bool Result = false;
1213   if (WeHadIt)
1214     PointsTo->reset(Ignoring);
1215   if (NHadIt)
1216     N->PointsTo->reset(Ignoring);
1217   Result = PointsTo->intersects(N->PointsTo);
1218   if (WeHadIt)
1219     PointsTo->set(Ignoring);
1220   if (NHadIt)
1221     N->PointsTo->set(Ignoring);
1222   return Result;
1223 }
1224
1225 void dumpToDOUT(SparseBitVector<> *bitmap) {
1226 #ifndef NDEBUG
1227   dump(*bitmap, DOUT);
1228 #endif
1229 }
1230
1231
1232 /// Clump together address taken variables so that the points-to sets use up
1233 /// less space and can be operated on faster.
1234
1235 void Andersens::ClumpAddressTaken() {
1236 #undef DEBUG_TYPE
1237 #define DEBUG_TYPE "anders-aa-renumber"
1238   std::vector<unsigned> Translate;
1239   std::vector<Node> NewGraphNodes;
1240
1241   Translate.resize(GraphNodes.size());
1242   unsigned NewPos = 0;
1243
1244   for (unsigned i = 0; i < Constraints.size(); ++i) {
1245     Constraint &C = Constraints[i];
1246     if (C.Type == Constraint::AddressOf) {
1247       GraphNodes[C.Src].AddressTaken = true;
1248     }
1249   }
1250   for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1251     unsigned Pos = NewPos++;
1252     Translate[i] = Pos;
1253     NewGraphNodes.push_back(GraphNodes[i]);
1254     DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1255   }
1256
1257   // I believe this ends up being faster than making two vectors and splicing
1258   // them.
1259   for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1260     if (GraphNodes[i].AddressTaken) {
1261       unsigned Pos = NewPos++;
1262       Translate[i] = Pos;
1263       NewGraphNodes.push_back(GraphNodes[i]);
1264       DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1265     }
1266   }
1267
1268   for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1269     if (!GraphNodes[i].AddressTaken) {
1270       unsigned Pos = NewPos++;
1271       Translate[i] = Pos;
1272       NewGraphNodes.push_back(GraphNodes[i]);
1273       DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1274     }
1275   }
1276
1277   for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1278        Iter != ValueNodes.end();
1279        ++Iter)
1280     Iter->second = Translate[Iter->second];
1281
1282   for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1283        Iter != ObjectNodes.end();
1284        ++Iter)
1285     Iter->second = Translate[Iter->second];
1286
1287   for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1288        Iter != ReturnNodes.end();
1289        ++Iter)
1290     Iter->second = Translate[Iter->second];
1291
1292   for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1293        Iter != VarargNodes.end();
1294        ++Iter)
1295     Iter->second = Translate[Iter->second];
1296
1297   for (unsigned i = 0; i < Constraints.size(); ++i) {
1298     Constraint &C = Constraints[i];
1299     C.Src = Translate[C.Src];
1300     C.Dest = Translate[C.Dest];
1301   }
1302
1303   GraphNodes.swap(NewGraphNodes);
1304 #undef DEBUG_TYPE
1305 #define DEBUG_TYPE "anders-aa"
1306 }
1307
1308 /// The technique used here is described in "Exploiting Pointer and Location
1309 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1310 /// Analysis Symposium (SAS), August 2007."  It is known as the "HVN" algorithm,
1311 /// and is equivalent to value numbering the collapsed constraint graph without
1312 /// evaluating unions.  This is used as a pre-pass to HU in order to resolve
1313 /// first order pointer dereferences and speed up/reduce memory usage of HU.
1314 /// Running both is equivalent to HRU without the iteration
1315 /// HVN in more detail:
1316 /// Imagine the set of constraints was simply straight line code with no loops
1317 /// (we eliminate cycles, so there are no loops), such as:
1318 /// E = &D
1319 /// E = &C
1320 /// E = F
1321 /// F = G
1322 /// G = F
1323 /// Applying value numbering to this code tells us:
1324 /// G == F == E
1325 ///
1326 /// For HVN, this is as far as it goes.  We assign new value numbers to every
1327 /// "address node", and every "reference node".
1328 /// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1329 /// cycle must have the same value number since the = operation is really
1330 /// inclusion, not overwrite), and value number nodes we receive points-to sets
1331 /// before we value our own node.
1332 /// The advantage of HU over HVN is that HU considers the inclusion property, so
1333 /// that if you have
1334 /// E = &D
1335 /// E = &C
1336 /// E = F
1337 /// F = G
1338 /// F = &D
1339 /// G = F
1340 /// HU will determine that G == F == E.  HVN will not, because it cannot prove
1341 /// that the points to information ends up being the same because they all
1342 /// receive &D from E anyway.
1343
1344 void Andersens::HVN() {
1345   DOUT << "Beginning HVN\n";
1346   // Build a predecessor graph.  This is like our constraint graph with the
1347   // edges going in the opposite direction, and there are edges for all the
1348   // constraints, instead of just copy constraints.  We also build implicit
1349   // edges for constraints are implied but not explicit.  I.E for the constraint
1350   // a = &b, we add implicit edges *a = b.  This helps us capture more cycles
1351   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1352     Constraint &C = Constraints[i];
1353     if (C.Type == Constraint::AddressOf) {
1354       GraphNodes[C.Src].AddressTaken = true;
1355       GraphNodes[C.Src].Direct = false;
1356
1357       // Dest = &src edge
1358       unsigned AdrNode = C.Src + FirstAdrNode;
1359       if (!GraphNodes[C.Dest].PredEdges)
1360         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1361       GraphNodes[C.Dest].PredEdges->set(AdrNode);
1362
1363       // *Dest = src edge
1364       unsigned RefNode = C.Dest + FirstRefNode;
1365       if (!GraphNodes[RefNode].ImplicitPredEdges)
1366         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1367       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1368     } else if (C.Type == Constraint::Load) {
1369       if (C.Offset == 0) {
1370         // dest = *src edge
1371         if (!GraphNodes[C.Dest].PredEdges)
1372           GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1373         GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1374       } else {
1375         GraphNodes[C.Dest].Direct = false;
1376       }
1377     } else if (C.Type == Constraint::Store) {
1378       if (C.Offset == 0) {
1379         // *dest = src edge
1380         unsigned RefNode = C.Dest + FirstRefNode;
1381         if (!GraphNodes[RefNode].PredEdges)
1382           GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1383         GraphNodes[RefNode].PredEdges->set(C.Src);
1384       }
1385     } else {
1386       // Dest = Src edge and *Dest = *Src edge
1387       if (!GraphNodes[C.Dest].PredEdges)
1388         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1389       GraphNodes[C.Dest].PredEdges->set(C.Src);
1390       unsigned RefNode = C.Dest + FirstRefNode;
1391       if (!GraphNodes[RefNode].ImplicitPredEdges)
1392         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1393       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1394     }
1395   }
1396   PEClass = 1;
1397   // Do SCC finding first to condense our predecessor graph
1398   DFSNumber = 0;
1399   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1400   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1401   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1402
1403   for (unsigned i = 0; i < FirstRefNode; ++i) {
1404     unsigned Node = VSSCCRep[i];
1405     if (!Node2Visited[Node])
1406       HVNValNum(Node);
1407   }
1408   for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1409        Iter != Set2PEClass.end();
1410        ++Iter)
1411     delete Iter->first;
1412   Set2PEClass.clear();
1413   Node2DFS.clear();
1414   Node2Deleted.clear();
1415   Node2Visited.clear();
1416   DOUT << "Finished HVN\n";
1417
1418 }
1419
1420 /// This is the workhorse of HVN value numbering. We combine SCC finding at the
1421 /// same time because it's easy.
1422 void Andersens::HVNValNum(unsigned NodeIndex) {
1423   unsigned MyDFS = DFSNumber++;
1424   Node *N = &GraphNodes[NodeIndex];
1425   Node2Visited[NodeIndex] = true;
1426   Node2DFS[NodeIndex] = MyDFS;
1427
1428   // First process all our explicit edges
1429   if (N->PredEdges)
1430     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1431          Iter != N->PredEdges->end();
1432          ++Iter) {
1433       unsigned j = VSSCCRep[*Iter];
1434       if (!Node2Deleted[j]) {
1435         if (!Node2Visited[j])
1436           HVNValNum(j);
1437         if (Node2DFS[NodeIndex] > Node2DFS[j])
1438           Node2DFS[NodeIndex] = Node2DFS[j];
1439       }
1440     }
1441
1442   // Now process all the implicit edges
1443   if (N->ImplicitPredEdges)
1444     for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1445          Iter != N->ImplicitPredEdges->end();
1446          ++Iter) {
1447       unsigned j = VSSCCRep[*Iter];
1448       if (!Node2Deleted[j]) {
1449         if (!Node2Visited[j])
1450           HVNValNum(j);
1451         if (Node2DFS[NodeIndex] > Node2DFS[j])
1452           Node2DFS[NodeIndex] = Node2DFS[j];
1453       }
1454     }
1455
1456   // See if we found any cycles
1457   if (MyDFS == Node2DFS[NodeIndex]) {
1458     while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1459       unsigned CycleNodeIndex = SCCStack.top();
1460       Node *CycleNode = &GraphNodes[CycleNodeIndex];
1461       VSSCCRep[CycleNodeIndex] = NodeIndex;
1462       // Unify the nodes
1463       N->Direct &= CycleNode->Direct;
1464
1465       if (CycleNode->PredEdges) {
1466         if (!N->PredEdges)
1467           N->PredEdges = new SparseBitVector<>;
1468         *(N->PredEdges) |= CycleNode->PredEdges;
1469         delete CycleNode->PredEdges;
1470         CycleNode->PredEdges = NULL;
1471       }
1472       if (CycleNode->ImplicitPredEdges) {
1473         if (!N->ImplicitPredEdges)
1474           N->ImplicitPredEdges = new SparseBitVector<>;
1475         *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1476         delete CycleNode->ImplicitPredEdges;
1477         CycleNode->ImplicitPredEdges = NULL;
1478       }
1479
1480       SCCStack.pop();
1481     }
1482
1483     Node2Deleted[NodeIndex] = true;
1484
1485     if (!N->Direct) {
1486       GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1487       return;
1488     }
1489
1490     // Collect labels of successor nodes
1491     bool AllSame = true;
1492     unsigned First = ~0;
1493     SparseBitVector<> *Labels = new SparseBitVector<>;
1494     bool Used = false;
1495
1496     if (N->PredEdges)
1497       for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1498            Iter != N->PredEdges->end();
1499          ++Iter) {
1500         unsigned j = VSSCCRep[*Iter];
1501         unsigned Label = GraphNodes[j].PointerEquivLabel;
1502         // Ignore labels that are equal to us or non-pointers
1503         if (j == NodeIndex || Label == 0)
1504           continue;
1505         if (First == (unsigned)~0)
1506           First = Label;
1507         else if (First != Label)
1508           AllSame = false;
1509         Labels->set(Label);
1510     }
1511
1512     // We either have a non-pointer, a copy of an existing node, or a new node.
1513     // Assign the appropriate pointer equivalence label.
1514     if (Labels->empty()) {
1515       GraphNodes[NodeIndex].PointerEquivLabel = 0;
1516     } else if (AllSame) {
1517       GraphNodes[NodeIndex].PointerEquivLabel = First;
1518     } else {
1519       GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1520       if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1521         unsigned EquivClass = PEClass++;
1522         Set2PEClass[Labels] = EquivClass;
1523         GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1524         Used = true;
1525       }
1526     }
1527     if (!Used)
1528       delete Labels;
1529   } else {
1530     SCCStack.push(NodeIndex);
1531   }
1532 }
1533
1534 /// The technique used here is described in "Exploiting Pointer and Location
1535 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1536 /// Analysis Symposium (SAS), August 2007."  It is known as the "HU" algorithm,
1537 /// and is equivalent to value numbering the collapsed constraint graph
1538 /// including evaluating unions.
1539 void Andersens::HU() {
1540   DOUT << "Beginning HU\n";
1541   // Build a predecessor graph.  This is like our constraint graph with the
1542   // edges going in the opposite direction, and there are edges for all the
1543   // constraints, instead of just copy constraints.  We also build implicit
1544   // edges for constraints are implied but not explicit.  I.E for the constraint
1545   // a = &b, we add implicit edges *a = b.  This helps us capture more cycles
1546   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1547     Constraint &C = Constraints[i];
1548     if (C.Type == Constraint::AddressOf) {
1549       GraphNodes[C.Src].AddressTaken = true;
1550       GraphNodes[C.Src].Direct = false;
1551
1552       GraphNodes[C.Dest].PointsTo->set(C.Src);
1553       // *Dest = src edge
1554       unsigned RefNode = C.Dest + FirstRefNode;
1555       if (!GraphNodes[RefNode].ImplicitPredEdges)
1556         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1557       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1558       GraphNodes[C.Src].PointedToBy->set(C.Dest);
1559     } else if (C.Type == Constraint::Load) {
1560       if (C.Offset == 0) {
1561         // dest = *src edge
1562         if (!GraphNodes[C.Dest].PredEdges)
1563           GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1564         GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1565       } else {
1566         GraphNodes[C.Dest].Direct = false;
1567       }
1568     } else if (C.Type == Constraint::Store) {
1569       if (C.Offset == 0) {
1570         // *dest = src edge
1571         unsigned RefNode = C.Dest + FirstRefNode;
1572         if (!GraphNodes[RefNode].PredEdges)
1573           GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1574         GraphNodes[RefNode].PredEdges->set(C.Src);
1575       }
1576     } else {
1577       // Dest = Src edge and *Dest = *Src edg
1578       if (!GraphNodes[C.Dest].PredEdges)
1579         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1580       GraphNodes[C.Dest].PredEdges->set(C.Src);
1581       unsigned RefNode = C.Dest + FirstRefNode;
1582       if (!GraphNodes[RefNode].ImplicitPredEdges)
1583         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1584       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1585     }
1586   }
1587   PEClass = 1;
1588   // Do SCC finding first to condense our predecessor graph
1589   DFSNumber = 0;
1590   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1591   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1592   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1593
1594   for (unsigned i = 0; i < FirstRefNode; ++i) {
1595     if (FindNode(i) == i) {
1596       unsigned Node = VSSCCRep[i];
1597       if (!Node2Visited[Node])
1598         Condense(Node);
1599     }
1600   }
1601
1602   // Reset tables for actual labeling
1603   Node2DFS.clear();
1604   Node2Visited.clear();
1605   Node2Deleted.clear();
1606   // Pre-grow our densemap so that we don't get really bad behavior
1607   Set2PEClass.resize(GraphNodes.size());
1608
1609   // Visit the condensed graph and generate pointer equivalence labels.
1610   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1611   for (unsigned i = 0; i < FirstRefNode; ++i) {
1612     if (FindNode(i) == i) {
1613       unsigned Node = VSSCCRep[i];
1614       if (!Node2Visited[Node])
1615         HUValNum(Node);
1616     }
1617   }
1618   // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1619   Set2PEClass.clear();
1620   DOUT << "Finished HU\n";
1621 }
1622
1623
1624 /// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1625 void Andersens::Condense(unsigned NodeIndex) {
1626   unsigned MyDFS = DFSNumber++;
1627   Node *N = &GraphNodes[NodeIndex];
1628   Node2Visited[NodeIndex] = true;
1629   Node2DFS[NodeIndex] = MyDFS;
1630
1631   // First process all our explicit edges
1632   if (N->PredEdges)
1633     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1634          Iter != N->PredEdges->end();
1635          ++Iter) {
1636       unsigned j = VSSCCRep[*Iter];
1637       if (!Node2Deleted[j]) {
1638         if (!Node2Visited[j])
1639           Condense(j);
1640         if (Node2DFS[NodeIndex] > Node2DFS[j])
1641           Node2DFS[NodeIndex] = Node2DFS[j];
1642       }
1643     }
1644
1645   // Now process all the implicit edges
1646   if (N->ImplicitPredEdges)
1647     for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1648          Iter != N->ImplicitPredEdges->end();
1649          ++Iter) {
1650       unsigned j = VSSCCRep[*Iter];
1651       if (!Node2Deleted[j]) {
1652         if (!Node2Visited[j])
1653           Condense(j);
1654         if (Node2DFS[NodeIndex] > Node2DFS[j])
1655           Node2DFS[NodeIndex] = Node2DFS[j];
1656       }
1657     }
1658
1659   // See if we found any cycles
1660   if (MyDFS == Node2DFS[NodeIndex]) {
1661     while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1662       unsigned CycleNodeIndex = SCCStack.top();
1663       Node *CycleNode = &GraphNodes[CycleNodeIndex];
1664       VSSCCRep[CycleNodeIndex] = NodeIndex;
1665       // Unify the nodes
1666       N->Direct &= CycleNode->Direct;
1667
1668       *(N->PointsTo) |= CycleNode->PointsTo;
1669       delete CycleNode->PointsTo;
1670       CycleNode->PointsTo = NULL;
1671       if (CycleNode->PredEdges) {
1672         if (!N->PredEdges)
1673           N->PredEdges = new SparseBitVector<>;
1674         *(N->PredEdges) |= CycleNode->PredEdges;
1675         delete CycleNode->PredEdges;
1676         CycleNode->PredEdges = NULL;
1677       }
1678       if (CycleNode->ImplicitPredEdges) {
1679         if (!N->ImplicitPredEdges)
1680           N->ImplicitPredEdges = new SparseBitVector<>;
1681         *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1682         delete CycleNode->ImplicitPredEdges;
1683         CycleNode->ImplicitPredEdges = NULL;
1684       }
1685       SCCStack.pop();
1686     }
1687
1688     Node2Deleted[NodeIndex] = true;
1689
1690     // Set up number of incoming edges for other nodes
1691     if (N->PredEdges)
1692       for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1693            Iter != N->PredEdges->end();
1694            ++Iter)
1695         ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1696   } else {
1697     SCCStack.push(NodeIndex);
1698   }
1699 }
1700
1701 void Andersens::HUValNum(unsigned NodeIndex) {
1702   Node *N = &GraphNodes[NodeIndex];
1703   Node2Visited[NodeIndex] = true;
1704
1705   // Eliminate dereferences of non-pointers for those non-pointers we have
1706   // already identified.  These are ref nodes whose non-ref node:
1707   // 1. Has already been visited determined to point to nothing (and thus, a
1708   // dereference of it must point to nothing)
1709   // 2. Any direct node with no predecessor edges in our graph and with no
1710   // points-to set (since it can't point to anything either, being that it
1711   // receives no points-to sets and has none).
1712   if (NodeIndex >= FirstRefNode) {
1713     unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1714     if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1715         || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1716             && GraphNodes[j].PointsTo->empty())){
1717       return;
1718     }
1719   }
1720     // Process all our explicit edges
1721   if (N->PredEdges)
1722     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1723          Iter != N->PredEdges->end();
1724          ++Iter) {
1725       unsigned j = VSSCCRep[*Iter];
1726       if (!Node2Visited[j])
1727         HUValNum(j);
1728
1729       // If this edge turned out to be the same as us, or got no pointer
1730       // equivalence label (and thus points to nothing) , just decrement our
1731       // incoming edges and continue.
1732       if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1733         --GraphNodes[j].NumInEdges;
1734         continue;
1735       }
1736
1737       *(N->PointsTo) |= GraphNodes[j].PointsTo;
1738
1739       // If we didn't end up storing this in the hash, and we're done with all
1740       // the edges, we don't need the points-to set anymore.
1741       --GraphNodes[j].NumInEdges;
1742       if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1743         delete GraphNodes[j].PointsTo;
1744         GraphNodes[j].PointsTo = NULL;
1745       }
1746     }
1747   // If this isn't a direct node, generate a fresh variable.
1748   if (!N->Direct) {
1749     N->PointsTo->set(FirstRefNode + NodeIndex);
1750   }
1751
1752   // See If we have something equivalent to us, if not, generate a new
1753   // equivalence class.
1754   if (N->PointsTo->empty()) {
1755     delete N->PointsTo;
1756     N->PointsTo = NULL;
1757   } else {
1758     if (N->Direct) {
1759       N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1760       if (N->PointerEquivLabel == 0) {
1761         unsigned EquivClass = PEClass++;
1762         N->StoredInHash = true;
1763         Set2PEClass[N->PointsTo] = EquivClass;
1764         N->PointerEquivLabel = EquivClass;
1765       }
1766     } else {
1767       N->PointerEquivLabel = PEClass++;
1768     }
1769   }
1770 }
1771
1772 /// Rewrite our list of constraints so that pointer equivalent nodes are
1773 /// replaced by their the pointer equivalence class representative.
1774 void Andersens::RewriteConstraints() {
1775   std::vector<Constraint> NewConstraints;
1776   DenseSet<Constraint, ConstraintKeyInfo> Seen;
1777
1778   PEClass2Node.clear();
1779   PENLEClass2Node.clear();
1780
1781   // We may have from 1 to Graphnodes + 1 equivalence classes.
1782   PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1783   PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1784
1785   // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1786   // nodes, and rewriting constraints to use the representative nodes.
1787   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1788     Constraint &C = Constraints[i];
1789     unsigned RHSNode = FindNode(C.Src);
1790     unsigned LHSNode = FindNode(C.Dest);
1791     unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1792     unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1793
1794     // First we try to eliminate constraints for things we can prove don't point
1795     // to anything.
1796     if (LHSLabel == 0) {
1797       DEBUG(PrintNode(&GraphNodes[LHSNode]));
1798       DOUT << " is a non-pointer, ignoring constraint.\n";
1799       continue;
1800     }
1801     if (RHSLabel == 0) {
1802       DEBUG(PrintNode(&GraphNodes[RHSNode]));
1803       DOUT << " is a non-pointer, ignoring constraint.\n";
1804       continue;
1805     }
1806     // This constraint may be useless, and it may become useless as we translate
1807     // it.
1808     if (C.Src == C.Dest && C.Type == Constraint::Copy)
1809       continue;
1810
1811     C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1812     C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
1813     if (C.Src == C.Dest && C.Type == Constraint::Copy
1814         || Seen.count(C))
1815       continue;
1816
1817     Seen.insert(C);
1818     NewConstraints.push_back(C);
1819   }
1820   Constraints.swap(NewConstraints);
1821   PEClass2Node.clear();
1822 }
1823
1824 /// See if we have a node that is pointer equivalent to the one being asked
1825 /// about, and if so, unite them and return the equivalent node.  Otherwise,
1826 /// return the original node.
1827 unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1828                                        unsigned NodeLabel) {
1829   if (!GraphNodes[NodeIndex].AddressTaken) {
1830     if (PEClass2Node[NodeLabel] != -1) {
1831       // We found an existing node with the same pointer label, so unify them.
1832       return UniteNodes(PEClass2Node[NodeLabel], NodeIndex);
1833     } else {
1834       PEClass2Node[NodeLabel] = NodeIndex;
1835       PENLEClass2Node[NodeLabel] = NodeIndex;
1836     }
1837   } else if (PENLEClass2Node[NodeLabel] == -1) {
1838     PENLEClass2Node[NodeLabel] = NodeIndex;
1839   }
1840
1841   return NodeIndex;
1842 }
1843
1844 void Andersens::PrintLabels() {
1845   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1846     if (i < FirstRefNode) {
1847       PrintNode(&GraphNodes[i]);
1848     } else if (i < FirstAdrNode) {
1849       DOUT << "REF(";
1850       PrintNode(&GraphNodes[i-FirstRefNode]);
1851       DOUT <<")";
1852     } else {
1853       DOUT << "ADR(";
1854       PrintNode(&GraphNodes[i-FirstAdrNode]);
1855       DOUT <<")";
1856     }
1857
1858     DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1859          << " and SCC rep " << VSSCCRep[i]
1860          << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1861          << "\n";
1862   }
1863 }
1864
1865 /// Optimize the constraints by performing offline variable substitution and
1866 /// other optimizations.
1867 void Andersens::OptimizeConstraints() {
1868   DOUT << "Beginning constraint optimization\n";
1869
1870   // Function related nodes need to stay in the same relative position and can't
1871   // be location equivalent.
1872   for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1873        Iter != MaxK.end();
1874        ++Iter) {
1875     for (unsigned i = Iter->first;
1876          i != Iter->first + Iter->second;
1877          ++i) {
1878       GraphNodes[i].AddressTaken = true;
1879       GraphNodes[i].Direct = false;
1880     }
1881   }
1882
1883   ClumpAddressTaken();
1884   FirstRefNode = GraphNodes.size();
1885   FirstAdrNode = FirstRefNode + GraphNodes.size();
1886   GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
1887                     Node(false));
1888   VSSCCRep.resize(GraphNodes.size());
1889   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1890     VSSCCRep[i] = i;
1891   }
1892   HVN();
1893   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1894     Node *N = &GraphNodes[i];
1895     delete N->PredEdges;
1896     N->PredEdges = NULL;
1897     delete N->ImplicitPredEdges;
1898     N->ImplicitPredEdges = NULL;
1899   }
1900 #undef DEBUG_TYPE
1901 #define DEBUG_TYPE "anders-aa-labels"
1902   DEBUG(PrintLabels());
1903 #undef DEBUG_TYPE
1904 #define DEBUG_TYPE "anders-aa"
1905   RewriteConstraints();
1906   // Delete the adr nodes.
1907   GraphNodes.resize(FirstRefNode * 2);
1908
1909   // Now perform HU
1910   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1911     Node *N = &GraphNodes[i];
1912     if (FindNode(i) == i) {
1913       N->PointsTo = new SparseBitVector<>;
1914       N->PointedToBy = new SparseBitVector<>;
1915       // Reset our labels
1916     }
1917     VSSCCRep[i] = i;
1918     N->PointerEquivLabel = 0;
1919   }
1920   HU();
1921 #undef DEBUG_TYPE
1922 #define DEBUG_TYPE "anders-aa-labels"
1923   DEBUG(PrintLabels());
1924 #undef DEBUG_TYPE
1925 #define DEBUG_TYPE "anders-aa"
1926   RewriteConstraints();
1927   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1928     if (FindNode(i) == i) {
1929       Node *N = &GraphNodes[i];
1930       delete N->PointsTo;
1931       delete N->PredEdges;
1932       delete N->ImplicitPredEdges;
1933       delete N->PointedToBy;
1934     }
1935   }
1936   GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
1937   DOUT << "Finished constraint optimization\n";
1938   FirstRefNode = 0;
1939   FirstAdrNode = 0;
1940 }
1941
1942 /// Unite pointer but not location equivalent variables, now that the constraint
1943 /// graph is built.
1944 void Andersens::UnitePointerEquivalences() {
1945   DOUT << "Uniting remaining pointer equivalences\n";
1946   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1947     if (GraphNodes[i].AddressTaken && GraphNodes[i].NodeRep == SelfRep) {
1948       unsigned Label = GraphNodes[i].PointerEquivLabel;
1949
1950       if (Label && PENLEClass2Node[Label] != -1)
1951         UniteNodes(i, PENLEClass2Node[Label]);
1952     }
1953   }
1954   DOUT << "Finished remaining pointer equivalences\n";
1955   PENLEClass2Node.clear();
1956 }
1957
1958 /// Create the constraint graph used for solving points-to analysis.
1959 ///
1960 void Andersens::CreateConstraintGraph() {
1961   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1962     Constraint &C = Constraints[i];
1963     assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1964     if (C.Type == Constraint::AddressOf)
1965       GraphNodes[C.Dest].PointsTo->set(C.Src);
1966     else if (C.Type == Constraint::Load)
1967       GraphNodes[C.Src].Constraints.push_back(C);
1968     else if (C.Type == Constraint::Store)
1969       GraphNodes[C.Dest].Constraints.push_back(C);
1970     else if (C.Offset != 0)
1971       GraphNodes[C.Src].Constraints.push_back(C);
1972     else
1973       GraphNodes[C.Src].Edges->set(C.Dest);
1974   }
1975 }
1976
1977 // Perform cycle detection, DFS, and RPO finding.
1978 void Andersens::QueryNode(unsigned Node) {
1979   assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1980   unsigned OurDFS = ++DFSNumber;
1981   SparseBitVector<> ToErase;
1982   SparseBitVector<> NewEdges;
1983   Node2DFS[Node] = OurDFS;
1984
1985   for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1986        bi != GraphNodes[Node].Edges->end();
1987        ++bi) {
1988     unsigned RepNode = FindNode(*bi);
1989     // If we are going to add an edge to repnode, we have no need for the edge
1990     // to e anymore.
1991     if (RepNode != *bi && NewEdges.test(RepNode)){
1992       ToErase.set(*bi);
1993       continue;
1994     }
1995
1996     // Continue about our DFS.
1997     if (!Node2Deleted[RepNode]){
1998       if (Node2DFS[RepNode] == 0) {
1999         QueryNode(RepNode);
2000         // May have been changed by query
2001         RepNode = FindNode(RepNode);
2002       }
2003       if (Node2DFS[RepNode] < Node2DFS[Node])
2004         Node2DFS[Node] = Node2DFS[RepNode];
2005     }
2006     // We may have just discovered that e belongs to a cycle, in which case we
2007     // can also erase it.
2008     if (RepNode != *bi) {
2009       ToErase.set(*bi);
2010       NewEdges.set(RepNode);
2011     }
2012   }
2013
2014   GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2015   GraphNodes[Node].Edges |= NewEdges;
2016
2017   // If this node is a root of a non-trivial SCC, place it on our worklist to be
2018   // processed
2019   if (OurDFS == Node2DFS[Node]) {
2020     bool Changed = false;
2021     while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
2022       Node = UniteNodes(Node, FindNode(SCCStack.top()));
2023
2024       SCCStack.pop();
2025       Changed = true;
2026     }
2027     Node2Deleted[Node] = true;
2028     RPONumber++;
2029
2030     Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
2031     Node2Topo[Node] = GraphNodes.size() - RPONumber;
2032     if (Changed)
2033       GraphNodes[Node].Changed = true;
2034   } else {
2035     SCCStack.push(Node);
2036   }
2037 }
2038
2039
2040 /// SolveConstraints - This stage iteratively processes the constraints list
2041 /// propagating constraints (adding edges to the Nodes in the points-to graph)
2042 /// until a fixed point is reached.
2043 ///
2044 void Andersens::SolveConstraints() {
2045   bool Changed = true;
2046   unsigned Iteration = 0;
2047
2048   OptimizeConstraints();
2049 #undef DEBUG_TYPE
2050 #define DEBUG_TYPE "anders-aa-constraints"
2051       DEBUG(PrintConstraints());
2052 #undef DEBUG_TYPE
2053 #define DEBUG_TYPE "anders-aa"
2054
2055   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2056     Node *N = &GraphNodes[i];
2057     N->PointsTo = new SparseBitVector<>;
2058     N->OldPointsTo = new SparseBitVector<>;
2059     N->Edges = new SparseBitVector<>;
2060   }
2061   CreateConstraintGraph();
2062   UnitePointerEquivalences();
2063   assert(SCCStack.empty() && "SCC Stack should be empty by now!");
2064   Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2065   Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2066   Node2DFS.clear();
2067   Node2Deleted.clear();
2068   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2069   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2070   DFSNumber = 0;
2071   RPONumber = 0;
2072   // Order graph and mark starting nodes as changed.
2073   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2074     unsigned N = FindNode(i);
2075     Node *INode = &GraphNodes[i];
2076     if (Node2DFS[N] == 0) {
2077       QueryNode(N);
2078       // Mark as changed if it's a representation and can contribute to the
2079       // calculation right now.
2080       if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
2081           && (!INode->Edges->empty() || !INode->Constraints.empty()))
2082         INode->Changed = true;
2083     }
2084   }
2085
2086   do {
2087     Changed = false;
2088     ++NumIters;
2089     DOUT << "Starting iteration #" << Iteration++ << "\n";
2090     // TODO: In the microoptimization category, we could just make Topo2Node
2091     // a fast map and thus only contain the visited nodes.
2092     for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2093       unsigned CurrNodeIndex = Topo2Node[i];
2094       Node *CurrNode;
2095
2096       // We may not revisit all nodes on every iteration
2097       if (CurrNodeIndex == Unvisited)
2098         continue;
2099       CurrNode = &GraphNodes[CurrNodeIndex];
2100       // See if this is a node we need to process on this iteration
2101       if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
2102         continue;
2103       CurrNode->Changed = false;
2104
2105       // Figure out the changed points to bits
2106       SparseBitVector<> CurrPointsTo;
2107       CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2108                                            CurrNode->OldPointsTo);
2109       if (CurrPointsTo.empty()){
2110         continue;
2111       }
2112       *(CurrNode->OldPointsTo) |= CurrPointsTo;
2113
2114       /* Now process the constraints for this node.  */
2115       for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2116            li != CurrNode->Constraints.end(); ) {
2117         li->Src = FindNode(li->Src);
2118         li->Dest = FindNode(li->Dest);
2119
2120         // TODO: We could delete redundant constraints here.
2121         // Src and Dest will be the vars we are going to process.
2122         // This may look a bit ugly, but what it does is allow us to process
2123         // both store and load constraints with the same code.
2124         // Load constraints say that every member of our RHS solution has K
2125         // added to it, and that variable gets an edge to LHS. We also union
2126         // RHS+K's solution into the LHS solution.
2127         // Store constraints say that every member of our LHS solution has K
2128         // added to it, and that variable gets an edge from RHS. We also union
2129         // RHS's solution into the LHS+K solution.
2130         unsigned *Src;
2131         unsigned *Dest;
2132         unsigned K = li->Offset;
2133         unsigned CurrMember;
2134         if (li->Type == Constraint::Load) {
2135           Src = &CurrMember;
2136           Dest = &li->Dest;
2137         } else if (li->Type == Constraint::Store) {
2138           Src = &li->Src;
2139           Dest = &CurrMember;
2140         } else {
2141           // TODO Handle offseted copy constraint
2142           li++;
2143           continue;
2144         }
2145         // TODO: hybrid cycle detection would go here, we should check
2146         // if it was a statically detected offline equivalence that
2147         // involves pointers , and if so, remove the redundant constraints.
2148
2149         const SparseBitVector<> &Solution = CurrPointsTo;
2150
2151         for (SparseBitVector<>::iterator bi = Solution.begin();
2152              bi != Solution.end();
2153              ++bi) {
2154           CurrMember = *bi;
2155
2156           // Need to increment the member by K since that is where we are
2157           // supposed to copy to/from.  Note that in positive weight cycles,
2158           // which occur in address taking of fields, K can go past
2159           // MaxK[CurrMember] elements, even though that is all it could point
2160           // to.
2161           if (K > 0 && K > MaxK[CurrMember])
2162             continue;
2163           else
2164             CurrMember = FindNode(CurrMember + K);
2165
2166           // Add an edge to the graph, so we can just do regular bitmap ior next
2167           // time.  It may also let us notice a cycle.
2168           if (GraphNodes[*Src].Edges->test_and_set(*Dest)) {
2169             if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
2170               GraphNodes[*Dest].Changed = true;
2171               // If we changed a node we've already processed, we need another
2172               // iteration.
2173               if (Node2Topo[*Dest] <= i)
2174                 Changed = true;
2175             }
2176           }
2177         }
2178         li++;
2179       }
2180       SparseBitVector<> NewEdges;
2181       SparseBitVector<> ToErase;
2182
2183       // Now all we have left to do is propagate points-to info along the
2184       // edges, erasing the redundant edges.
2185
2186
2187       for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2188            bi != CurrNode->Edges->end();
2189            ++bi) {
2190
2191         unsigned DestVar = *bi;
2192         unsigned Rep = FindNode(DestVar);
2193
2194         // If we ended up with this node as our destination, or we've already
2195         // got an edge for the representative, delete the current edge.
2196         if (Rep == CurrNodeIndex ||
2197             (Rep != DestVar && NewEdges.test(Rep))) {
2198           ToErase.set(DestVar);
2199           continue;
2200         }
2201         // Union the points-to sets into the dest
2202         if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2203           GraphNodes[Rep].Changed = true;
2204           if (Node2Topo[Rep] <= i)
2205             Changed = true;
2206         }
2207         // If this edge's destination was collapsed, rewrite the edge.
2208         if (Rep != DestVar) {
2209           ToErase.set(DestVar);
2210           NewEdges.set(Rep);
2211         }
2212       }
2213       CurrNode->Edges->intersectWithComplement(ToErase);
2214       CurrNode->Edges |= NewEdges;
2215     }
2216     if (Changed) {
2217       DFSNumber = RPONumber = 0;
2218       Node2Deleted.clear();
2219       Topo2Node.clear();
2220       Node2Topo.clear();
2221       Node2DFS.clear();
2222       Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2223       Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2224       Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2225       Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2226       // Rediscover the DFS/Topo ordering, and cycle detect.
2227       for (unsigned j = 0; j < GraphNodes.size(); j++) {
2228         unsigned JRep = FindNode(j);
2229         if (Node2DFS[JRep] == 0)
2230           QueryNode(JRep);
2231       }
2232     }
2233
2234   } while (Changed);
2235
2236   Node2Topo.clear();
2237   Topo2Node.clear();
2238   Node2DFS.clear();
2239   Node2Deleted.clear();
2240   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2241     Node *N = &GraphNodes[i];
2242     delete N->OldPointsTo;
2243     delete N->Edges;
2244   }
2245 }
2246
2247 //===----------------------------------------------------------------------===//
2248 //                               Union-Find
2249 //===----------------------------------------------------------------------===//
2250
2251 // Unite nodes First and Second, returning the one which is now the
2252 // representative node.  First and Second are indexes into GraphNodes
2253 unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
2254   assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2255           "Attempting to merge nodes that don't exist");
2256   // TODO: implement union by rank
2257   Node *FirstNode = &GraphNodes[First];
2258   Node *SecondNode = &GraphNodes[Second];
2259
2260   assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
2261           "Trying to unite two non-representative nodes!");
2262   if (First == Second)
2263     return First;
2264
2265   SecondNode->NodeRep = First;
2266   FirstNode->Changed |= SecondNode->Changed;
2267   if (FirstNode->PointsTo && SecondNode->PointsTo)
2268     FirstNode->PointsTo |= *(SecondNode->PointsTo);
2269   if (FirstNode->Edges && SecondNode->Edges)
2270     FirstNode->Edges |= *(SecondNode->Edges);
2271   if (!FirstNode->Constraints.empty() && !SecondNode->Constraints.empty())
2272     FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2273                                   SecondNode->Constraints);
2274   if (FirstNode->OldPointsTo) {
2275     delete FirstNode->OldPointsTo;
2276     FirstNode->OldPointsTo = new SparseBitVector<>;
2277   }
2278
2279   // Destroy interesting parts of the merged-from node.
2280   delete SecondNode->OldPointsTo;
2281   delete SecondNode->Edges;
2282   delete SecondNode->PointsTo;
2283   SecondNode->Edges = NULL;
2284   SecondNode->PointsTo = NULL;
2285   SecondNode->OldPointsTo = NULL;
2286
2287   NumUnified++;
2288   DOUT << "Unified Node ";
2289   DEBUG(PrintNode(FirstNode));
2290   DOUT << " and Node ";
2291   DEBUG(PrintNode(SecondNode));
2292   DOUT << "\n";
2293
2294   // TODO: Handle SDT
2295   return First;
2296 }
2297
2298 // Find the index into GraphNodes of the node representing Node, performing
2299 // path compression along the way
2300 unsigned Andersens::FindNode(unsigned NodeIndex) {
2301   assert (NodeIndex < GraphNodes.size()
2302           && "Attempting to find a node that can't exist");
2303   Node *N = &GraphNodes[NodeIndex];
2304   if (N->NodeRep == SelfRep)
2305     return NodeIndex;
2306   else
2307     return (N->NodeRep = FindNode(N->NodeRep));
2308 }
2309
2310 //===----------------------------------------------------------------------===//
2311 //                               Debugging Output
2312 //===----------------------------------------------------------------------===//
2313
2314 void Andersens::PrintNode(Node *N) {
2315   if (N == &GraphNodes[UniversalSet]) {
2316     cerr << "<universal>";
2317     return;
2318   } else if (N == &GraphNodes[NullPtr]) {
2319     cerr << "<nullptr>";
2320     return;
2321   } else if (N == &GraphNodes[NullObject]) {
2322     cerr << "<null>";
2323     return;
2324   }
2325   if (!N->getValue()) {
2326     cerr << "artificial" << (intptr_t) N;
2327     return;
2328   }
2329
2330   assert(N->getValue() != 0 && "Never set node label!");
2331   Value *V = N->getValue();
2332   if (Function *F = dyn_cast<Function>(V)) {
2333     if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
2334         N == &GraphNodes[getReturnNode(F)]) {
2335       cerr << F->getName() << ":retval";
2336       return;
2337     } else if (F->getFunctionType()->isVarArg() &&
2338                N == &GraphNodes[getVarargNode(F)]) {
2339       cerr << F->getName() << ":vararg";
2340       return;
2341     }
2342   }
2343
2344   if (Instruction *I = dyn_cast<Instruction>(V))
2345     cerr << I->getParent()->getParent()->getName() << ":";
2346   else if (Argument *Arg = dyn_cast<Argument>(V))
2347     cerr << Arg->getParent()->getName() << ":";
2348
2349   if (V->hasName())
2350     cerr << V->getName();
2351   else
2352     cerr << "(unnamed)";
2353
2354   if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
2355     if (N == &GraphNodes[getObject(V)])
2356       cerr << "<mem>";
2357 }
2358 void Andersens::PrintConstraint(const Constraint &C) {
2359   if (C.Type == Constraint::Store) {
2360     cerr << "*";
2361     if (C.Offset != 0)
2362       cerr << "(";
2363   }
2364   PrintNode(&GraphNodes[C.Dest]);
2365   if (C.Type == Constraint::Store && C.Offset != 0)
2366     cerr << " + " << C.Offset << ")";
2367   cerr << " = ";
2368   if (C.Type == Constraint::Load) {
2369     cerr << "*";
2370     if (C.Offset != 0)
2371       cerr << "(";
2372   }
2373   else if (C.Type == Constraint::AddressOf)
2374     cerr << "&";
2375   PrintNode(&GraphNodes[C.Src]);
2376   if (C.Offset != 0 && C.Type != Constraint::Store)
2377     cerr << " + " << C.Offset;
2378   if (C.Type == Constraint::Load && C.Offset != 0)
2379     cerr << ")";
2380   cerr << "\n";
2381 }
2382
2383 void Andersens::PrintConstraints() {
2384   cerr << "Constraints:\n";
2385
2386   for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2387     PrintConstraint(Constraints[i]);
2388 }
2389
2390 void Andersens::PrintPointsToGraph() {
2391   cerr << "Points-to graph:\n";
2392   for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2393     Node *N = &GraphNodes[i];
2394     if (FindNode (i) != i) {
2395       PrintNode(N);
2396       cerr << "\t--> same as ";
2397       PrintNode(&GraphNodes[FindNode(i)]);
2398       cerr << "\n";
2399     } else {
2400       cerr << "[" << (N->PointsTo->count()) << "] ";
2401       PrintNode(N);
2402       cerr << "\t--> ";
2403
2404       bool first = true;
2405       for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2406            bi != N->PointsTo->end();
2407            ++bi) {
2408         if (!first)
2409           cerr << ", ";
2410         PrintNode(&GraphNodes[*bi]);
2411         first = false;
2412       }
2413       cerr << "\n";
2414     }
2415   }
2416 }