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