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