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