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