1 //===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines an implementation of Andersen's interprocedural alias
13 // In pointer analysis terms, this is a subset-based, flow-insensitive,
14 // field-sensitive, and context-insensitive algorithm pointer algorithm.
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.
22 // The object identification stage identifies all of the memory objects in the
23 // program, which includes globals, heap allocated objects, and stack allocated
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
33 // The offline constraint graph optimization portion includes offline variable
34 // substitution algorithms intended to compute pointer and location
35 // equivalences. Pointer equivalences are those pointers that will have the
36 // same points-to sets, and location equivalences are those variables that
37 // always appear together in points-to sets. It also includes an offline
38 // cycle detection algorithm that allows cycles to be collapsed sooner
41 // The inclusion constraint solving phase iteratively propagates the inclusion
42 // constraints until a fixed point is reached. This is an O(N^3) algorithm.
44 // Function constraints are handled as if they were structs with X fields.
45 // Thus, an access to argument X of function Y is an access to node index
46 // getNode(Y) + X. This representation allows handling of indirect calls
47 // without any issues. To wit, an indirect call Y(a,b) is equivalent to
48 // *(Y + 1) = a, *(Y + 2) = b.
49 // The return node for a function is always located at getNode(F) +
50 // CallReturnPos. The arguments start at getNode(F) + CallArgPos.
52 // Future Improvements:
54 //===----------------------------------------------------------------------===//
56 #define DEBUG_TYPE "anders-aa"
57 #include "llvm/Constants.h"
58 #include "llvm/DerivedTypes.h"
59 #include "llvm/Instructions.h"
60 #include "llvm/Module.h"
61 #include "llvm/Pass.h"
62 #include "llvm/Support/Compiler.h"
63 #include "llvm/Support/InstIterator.h"
64 #include "llvm/Support/InstVisitor.h"
65 #include "llvm/Analysis/AliasAnalysis.h"
66 #include "llvm/Analysis/Passes.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/ADT/Statistic.h"
69 #include "llvm/ADT/SparseBitVector.h"
70 #include "llvm/ADT/DenseSet.h"
78 // Determining the actual set of nodes the universal set can consist of is very
79 // expensive because it means propagating around very large sets. We rely on
80 // other analysis being able to determine which nodes can never be pointed to in
81 // order to disambiguate further than "points-to anything".
82 #define FULL_UNIVERSAL 0
85 STATISTIC(NumIters , "Number of iterations to reach convergence");
86 STATISTIC(NumConstraints, "Number of constraints");
87 STATISTIC(NumNodes , "Number of nodes");
88 STATISTIC(NumUnified , "Number of variables unified");
89 STATISTIC(NumErased , "Number of redundant constraints erased");
92 const unsigned SelfRep = (unsigned)-1;
93 const unsigned Unvisited = (unsigned)-1;
94 // Position of the function return node relative to the function node.
95 const unsigned CallReturnPos = 1;
96 // Position of the function call node relative to the function node.
97 const unsigned CallFirstArgPos = 2;
99 struct BitmapKeyInfo {
100 static inline SparseBitVector<> *getEmptyKey() {
101 return reinterpret_cast<SparseBitVector<> *>(-1);
103 static inline SparseBitVector<> *getTombstoneKey() {
104 return reinterpret_cast<SparseBitVector<> *>(-2);
106 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
107 return bitmap->getHashValue();
109 static bool isEqual(const SparseBitVector<> *LHS,
110 const SparseBitVector<> *RHS) {
113 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
114 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
120 static bool isPod() { return true; }
123 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
124 private InstVisitor<Andersens> {
127 /// Constraint - Objects of this structure are used to represent the various
128 /// constraints identified by the algorithm. The constraints are 'copy',
129 /// for statements like "A = B", 'load' for statements like "A = *B",
130 /// 'store' for statements like "*A = B", and AddressOf for statements like
131 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
132 /// A = *(B + K) for loads, and A = B + K for copies. It is
133 /// illegal on addressof constraints (because it is statically
134 /// resolvable to A = &C where C = B + K)
137 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
142 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
143 : Type(Ty), Dest(D), Src(S), Offset(O) {
144 assert((Offset == 0 || Ty != AddressOf) &&
145 "Offset is illegal on addressof constraints");
148 bool operator==(const Constraint &RHS) const {
149 return RHS.Type == Type
152 && RHS.Offset == Offset;
155 bool operator!=(const Constraint &RHS) const {
156 return !(*this == RHS);
159 bool operator<(const Constraint &RHS) const {
160 if (RHS.Type != Type)
161 return RHS.Type < Type;
162 else if (RHS.Dest != Dest)
163 return RHS.Dest < Dest;
164 else if (RHS.Src != Src)
165 return RHS.Src < Src;
166 return RHS.Offset < Offset;
170 // Information DenseSet requires implemented in order to be able to do
173 static inline std::pair<unsigned, unsigned> getEmptyKey() {
174 return std::make_pair(~0U, ~0U);
176 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
177 return std::make_pair(~0U - 1, ~0U - 1);
179 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
180 return P.first ^ P.second;
182 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
183 const std::pair<unsigned, unsigned> &RHS) {
188 struct ConstraintKeyInfo {
189 static inline Constraint getEmptyKey() {
190 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
192 static inline Constraint getTombstoneKey() {
193 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
195 static unsigned getHashValue(const Constraint &C) {
196 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
198 static bool isEqual(const Constraint &LHS,
199 const Constraint &RHS) {
200 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
201 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
205 // Node class - This class is used to represent a node in the constraint
206 // graph. Due to various optimizations, it is not always the case that
207 // there is a mapping from a Node to a Value. In particular, we add
208 // artificial Node's that represent the set of pointed-to variables shared
209 // for each location equivalent Node.
212 static unsigned Counter;
216 SparseBitVector<> *Edges;
217 SparseBitVector<> *PointsTo;
218 SparseBitVector<> *OldPointsTo;
219 std::list<Constraint> Constraints;
221 // Pointer and location equivalence labels
222 unsigned PointerEquivLabel;
223 unsigned LocationEquivLabel;
224 // Predecessor edges, both real and implicit
225 SparseBitVector<> *PredEdges;
226 SparseBitVector<> *ImplicitPredEdges;
227 // Set of nodes that point to us, only use for location equivalence.
228 SparseBitVector<> *PointedToBy;
229 // Number of incoming edges, used during variable substitution to early
230 // free the points-to sets
232 // True if our points-to set is in the Set2PEClass map
234 // True if our node has no indirect constraints (complex or otherwise)
236 // True if the node is address taken, *or* it is part of a group of nodes
237 // that must be kept together. This is set to true for functions and
238 // their arg nodes, which must be kept at the same position relative to
239 // their base function node.
242 // Nodes in cycles (or in equivalence classes) are united together using a
243 // standard union-find representation with path compression. NodeRep
244 // gives the index into GraphNodes for the representative Node.
247 // Modification timestamp. Assigned from Counter.
248 // Used for work list prioritization.
251 explicit Node(bool direct = true) :
252 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
253 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
254 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
255 StoredInHash(false), Direct(direct), AddressTaken(false),
256 NodeRep(SelfRep), Timestamp(0) { }
258 Node *setValue(Value *V) {
259 assert(Val == 0 && "Value already set for this node!");
264 /// getValue - Return the LLVM value corresponding to this node.
266 Value *getValue() const { return Val; }
268 /// addPointerTo - Add a pointer to the list of pointees of this node,
269 /// returning true if this caused a new pointer to be added, or false if
270 /// we already knew about the points-to relation.
271 bool addPointerTo(unsigned Node) {
272 return PointsTo->test_and_set(Node);
275 /// intersects - Return true if the points-to set of this node intersects
276 /// with the points-to set of the specified node.
277 bool intersects(Node *N) const;
279 /// intersectsIgnoring - Return true if the points-to set of this node
280 /// intersects with the points-to set of the specified node on any nodes
281 /// except for the specified node to ignore.
282 bool intersectsIgnoring(Node *N, unsigned) const;
284 // Timestamp a node (used for work list prioritization)
286 Timestamp = Counter++;
290 return( (int) NodeRep < 0 );
294 struct WorkListElement {
297 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
299 // Note that we reverse the sense of the comparison because we
300 // actually want to give low timestamps the priority over high,
301 // whereas priority is typically interpreted as a greater value is
302 // given high priority.
303 bool operator<(const WorkListElement& that) const {
304 return( this->Timestamp > that.Timestamp );
308 // Priority-queue based work list specialized for Nodes.
310 std::priority_queue<WorkListElement> Q;
313 void insert(Node* n) {
314 Q.push( WorkListElement(n, n->Timestamp) );
317 // We automatically discard non-representative nodes and nodes
318 // that were in the work list twice (we keep a copy of the
319 // timestamp in the work list so we can detect this situation by
320 // comparing against the node's current timestamp).
322 while( !Q.empty() ) {
323 WorkListElement x = Q.top(); Q.pop();
324 Node* INode = x.node;
326 if( INode->isRep() &&
327 INode->Timestamp == x.Timestamp ) {
339 /// GraphNodes - This vector is populated as part of the object
340 /// identification stage of the analysis, which populates this vector with a
341 /// node for each memory object and fills in the ValueNodes map.
342 std::vector<Node> GraphNodes;
344 /// ValueNodes - This map indicates the Node that a particular Value* is
345 /// represented by. This contains entries for all pointers.
346 DenseMap<Value*, unsigned> ValueNodes;
348 /// ObjectNodes - This map contains entries for each memory object in the
349 /// program: globals, alloca's and mallocs.
350 DenseMap<Value*, unsigned> ObjectNodes;
352 /// ReturnNodes - This map contains an entry for each function in the
353 /// program that returns a value.
354 DenseMap<Function*, unsigned> ReturnNodes;
356 /// VarargNodes - This map contains the entry used to represent all pointers
357 /// passed through the varargs portion of a function call for a particular
358 /// function. An entry is not present in this map for functions that do not
359 /// take variable arguments.
360 DenseMap<Function*, unsigned> VarargNodes;
363 /// Constraints - This vector contains a list of all of the constraints
364 /// identified by the program.
365 std::vector<Constraint> Constraints;
367 // Map from graph node to maximum K value that is allowed (for functions,
368 // this is equivalent to the number of arguments + CallFirstArgPos)
369 std::map<unsigned, unsigned> MaxK;
371 /// This enum defines the GraphNodes indices that correspond to important
379 // Stack for Tarjan's
380 std::stack<unsigned> SCCStack;
381 // Map from Graph Node to DFS number
382 std::vector<unsigned> Node2DFS;
383 // Map from Graph Node to Deleted from graph.
384 std::vector<bool> Node2Deleted;
385 // Same as Node Maps, but implemented as std::map because it is faster to
387 std::map<unsigned, unsigned> Tarjan2DFS;
388 std::map<unsigned, bool> Tarjan2Deleted;
389 // Current DFS number
394 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
396 // Offline variable substitution related things
398 // Temporary rep storage, used because we can't collapse SCC's in the
399 // predecessor graph by uniting the variables permanently, we can only do so
400 // for the successor graph.
401 std::vector<unsigned> VSSCCRep;
402 // Mapping from node to whether we have visited it during SCC finding yet.
403 std::vector<bool> Node2Visited;
404 // During variable substitution, we create unknowns to represent the unknown
405 // value that is a dereference of a variable. These nodes are known as
406 // "ref" nodes (since they represent the value of dereferences).
407 unsigned FirstRefNode;
408 // During HVN, we create represent address taken nodes as if they were
409 // unknown (since HVN, unlike HU, does not evaluate unions).
410 unsigned FirstAdrNode;
411 // Current pointer equivalence class number
413 // Mapping from points-to sets to equivalence classes
414 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
415 BitVectorMap Set2PEClass;
416 // Mapping from pointer equivalences to the representative node. -1 if we
417 // have no representative node for this pointer equivalence class yet.
418 std::vector<int> PEClass2Node;
419 // Mapping from pointer equivalences to representative node. This includes
420 // pointer equivalent but not location equivalent variables. -1 if we have
421 // no representative node for this pointer equivalence class yet.
422 std::vector<int> PENLEClass2Node;
423 // Union/Find for HCD
424 std::vector<unsigned> HCDSCCRep;
425 // HCD's offline-detected cycles; "Statically DeTected"
426 // -1 if not part of such a cycle, otherwise a representative node.
427 std::vector<int> SDT;
428 // Whether to use SDT (UniteNodes can use it during solving, but not before)
433 Andersens() : ModulePass((intptr_t)&ID) {}
435 bool runOnModule(Module &M) {
436 InitializeAliasAnalysis(this);
438 CollectConstraints(M);
440 #define DEBUG_TYPE "anders-aa-constraints"
441 DEBUG(PrintConstraints());
443 #define DEBUG_TYPE "anders-aa"
445 DEBUG(PrintPointsToGraph());
447 // Free the constraints list, as we don't need it to respond to alias
452 std::vector<Constraint>().swap(Constraints);
456 void releaseMemory() {
457 // FIXME: Until we have transitively required passes working correctly,
458 // this cannot be enabled! Otherwise, using -count-aa with the pass
459 // causes memory to be freed too early. :(
461 // The memory objects and ValueNodes data structures at the only ones that
462 // are still live after construction.
463 std::vector<Node>().swap(GraphNodes);
468 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
469 AliasAnalysis::getAnalysisUsage(AU);
470 AU.setPreservesAll(); // Does not transform code
473 //------------------------------------------------
474 // Implement the AliasAnalysis API
476 AliasResult alias(const Value *V1, unsigned V1Size,
477 const Value *V2, unsigned V2Size);
478 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
479 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
480 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
481 bool pointsToConstantMemory(const Value *P);
483 virtual void deleteValue(Value *V) {
485 getAnalysis<AliasAnalysis>().deleteValue(V);
488 virtual void copyValue(Value *From, Value *To) {
489 ValueNodes[To] = ValueNodes[From];
490 getAnalysis<AliasAnalysis>().copyValue(From, To);
494 /// getNode - Return the node corresponding to the specified pointer scalar.
496 unsigned getNode(Value *V) {
497 if (Constant *C = dyn_cast<Constant>(V))
498 if (!isa<GlobalValue>(C))
499 return getNodeForConstantPointer(C);
501 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
502 if (I == ValueNodes.end()) {
506 assert(0 && "Value does not have a node in the points-to graph!");
511 /// getObject - Return the node corresponding to the memory object for the
512 /// specified global or allocation instruction.
513 unsigned getObject(Value *V) {
514 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
515 assert(I != ObjectNodes.end() &&
516 "Value does not have an object in the points-to graph!");
520 /// getReturnNode - Return the node representing the return value for the
521 /// specified function.
522 unsigned getReturnNode(Function *F) {
523 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
524 assert(I != ReturnNodes.end() && "Function does not return a value!");
528 /// getVarargNode - Return the node representing the variable arguments
529 /// formal for the specified function.
530 unsigned getVarargNode(Function *F) {
531 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
532 assert(I != VarargNodes.end() && "Function does not take var args!");
536 /// getNodeValue - Get the node for the specified LLVM value and set the
537 /// value for it to be the specified value.
538 unsigned getNodeValue(Value &V) {
539 unsigned Index = getNode(&V);
540 GraphNodes[Index].setValue(&V);
544 unsigned UniteNodes(unsigned First, unsigned Second,
545 bool UnionByRank = true);
546 unsigned FindNode(unsigned Node);
548 void IdentifyObjects(Module &M);
549 void CollectConstraints(Module &M);
550 bool AnalyzeUsesOfFunction(Value *);
551 void CreateConstraintGraph();
552 void OptimizeConstraints();
553 unsigned FindEquivalentNode(unsigned, unsigned);
554 void ClumpAddressTaken();
555 void RewriteConstraints();
559 void Search(unsigned Node);
560 void UnitePointerEquivalences();
561 void SolveConstraints();
562 bool QueryNode(unsigned Node);
563 void Condense(unsigned Node);
564 void HUValNum(unsigned Node);
565 void HVNValNum(unsigned Node);
566 unsigned getNodeForConstantPointer(Constant *C);
567 unsigned getNodeForConstantPointerTarget(Constant *C);
568 void AddGlobalInitializerConstraints(unsigned, Constant *C);
570 void AddConstraintsForNonInternalLinkage(Function *F);
571 void AddConstraintsForCall(CallSite CS, Function *F);
572 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
575 void PrintNode(Node *N);
576 void PrintConstraints();
577 void PrintConstraint(const Constraint &);
579 void PrintPointsToGraph();
581 //===------------------------------------------------------------------===//
582 // Instruction visitation methods for adding constraints
584 friend class InstVisitor<Andersens>;
585 void visitReturnInst(ReturnInst &RI);
586 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
587 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
588 void visitCallSite(CallSite CS);
589 void visitAllocationInst(AllocationInst &AI);
590 void visitLoadInst(LoadInst &LI);
591 void visitStoreInst(StoreInst &SI);
592 void visitGetElementPtrInst(GetElementPtrInst &GEP);
593 void visitPHINode(PHINode &PN);
594 void visitCastInst(CastInst &CI);
595 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
596 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
597 void visitSelectInst(SelectInst &SI);
598 void visitVAArg(VAArgInst &I);
599 void visitInstruction(Instruction &I);
603 char Andersens::ID = 0;
604 RegisterPass<Andersens> X("anders-aa",
605 "Andersen's Interprocedural Alias Analysis", true,
607 RegisterAnalysisGroup<AliasAnalysis> Y(X);
609 // Initialize Timestamp Counter (static).
610 unsigned Andersens::Node::Counter = 0;
613 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
615 //===----------------------------------------------------------------------===//
616 // AliasAnalysis Interface Implementation
617 //===----------------------------------------------------------------------===//
619 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
620 const Value *V2, unsigned V2Size) {
621 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
622 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
624 // Check to see if the two pointers are known to not alias. They don't alias
625 // if their points-to sets do not intersect.
626 if (!N1->intersectsIgnoring(N2, NullObject))
629 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
632 AliasAnalysis::ModRefResult
633 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
634 // The only thing useful that we can contribute for mod/ref information is
635 // when calling external function calls: if we know that memory never escapes
636 // from the program, it cannot be modified by an external call.
638 // NOTE: This is not really safe, at least not when the entire program is not
639 // available. The deal is that the external function could call back into the
640 // program and modify stuff. We ignore this technical niggle for now. This
641 // is, after all, a "research quality" implementation of Andersen's analysis.
642 if (Function *F = CS.getCalledFunction())
643 if (F->isDeclaration()) {
644 Node *N1 = &GraphNodes[FindNode(getNode(P))];
646 if (N1->PointsTo->empty())
649 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
650 return NoModRef; // Universal set does not contain P
652 if (!N1->PointsTo->test(UniversalSet))
653 return NoModRef; // P doesn't point to the universal set.
657 return AliasAnalysis::getModRefInfo(CS, P, Size);
660 AliasAnalysis::ModRefResult
661 Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
662 return AliasAnalysis::getModRefInfo(CS1,CS2);
665 /// getMustAlias - We can provide must alias information if we know that a
666 /// pointer can only point to a specific function or the null pointer.
667 /// Unfortunately we cannot determine must-alias information for global
668 /// variables or any other memory memory objects because we do not track whether
669 /// a pointer points to the beginning of an object or a field of it.
670 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
671 Node *N = &GraphNodes[FindNode(getNode(P))];
672 if (N->PointsTo->count() == 1) {
673 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
674 // If a function is the only object in the points-to set, then it must be
675 // the destination. Note that we can't handle global variables here,
676 // because we don't know if the pointer is actually pointing to a field of
677 // the global or to the beginning of it.
678 if (Value *V = Pointee->getValue()) {
679 if (Function *F = dyn_cast<Function>(V))
680 RetVals.push_back(F);
682 // If the object in the points-to set is the null object, then the null
683 // pointer is a must alias.
684 if (Pointee == &GraphNodes[NullObject])
685 RetVals.push_back(Constant::getNullValue(P->getType()));
688 AliasAnalysis::getMustAliases(P, RetVals);
691 /// pointsToConstantMemory - If we can determine that this pointer only points
692 /// to constant memory, return true. In practice, this means that if the
693 /// pointer can only point to constant globals, functions, or the null pointer,
696 bool Andersens::pointsToConstantMemory(const Value *P) {
697 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
700 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
701 bi != N->PointsTo->end();
704 Node *Pointee = &GraphNodes[i];
705 if (Value *V = Pointee->getValue()) {
706 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
707 !cast<GlobalVariable>(V)->isConstant()))
708 return AliasAnalysis::pointsToConstantMemory(P);
711 return AliasAnalysis::pointsToConstantMemory(P);
718 //===----------------------------------------------------------------------===//
719 // Object Identification Phase
720 //===----------------------------------------------------------------------===//
722 /// IdentifyObjects - This stage scans the program, adding an entry to the
723 /// GraphNodes list for each memory object in the program (global stack or
724 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
726 void Andersens::IdentifyObjects(Module &M) {
727 unsigned NumObjects = 0;
729 // Object #0 is always the universal set: the object that we don't know
731 assert(NumObjects == UniversalSet && "Something changed!");
734 // Object #1 always represents the null pointer.
735 assert(NumObjects == NullPtr && "Something changed!");
738 // Object #2 always represents the null object (the object pointed to by null)
739 assert(NumObjects == NullObject && "Something changed!");
742 // Add all the globals first.
743 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
745 ObjectNodes[I] = NumObjects++;
746 ValueNodes[I] = NumObjects++;
749 // Add nodes for all of the functions and the instructions inside of them.
750 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
751 // The function itself is a memory object.
752 unsigned First = NumObjects;
753 ValueNodes[F] = NumObjects++;
754 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
755 ReturnNodes[F] = NumObjects++;
756 if (F->getFunctionType()->isVarArg())
757 VarargNodes[F] = NumObjects++;
760 // Add nodes for all of the incoming pointer arguments.
761 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
764 if (isa<PointerType>(I->getType()))
765 ValueNodes[I] = NumObjects++;
767 MaxK[First] = NumObjects - First;
769 // Scan the function body, creating a memory object for each heap/stack
770 // allocation in the body of the function and a node to represent all
771 // pointer values defined by instructions and used as operands.
772 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
773 // If this is an heap or stack allocation, create a node for the memory
775 if (isa<PointerType>(II->getType())) {
776 ValueNodes[&*II] = NumObjects++;
777 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
778 ObjectNodes[AI] = NumObjects++;
781 // Calls to inline asm need to be added as well because the callee isn't
782 // referenced anywhere else.
783 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
784 Value *Callee = CI->getCalledValue();
785 if (isa<InlineAsm>(Callee))
786 ValueNodes[Callee] = NumObjects++;
791 // Now that we know how many objects to create, make them all now!
792 GraphNodes.resize(NumObjects);
793 NumNodes += NumObjects;
796 //===----------------------------------------------------------------------===//
797 // Constraint Identification Phase
798 //===----------------------------------------------------------------------===//
800 /// getNodeForConstantPointer - Return the node corresponding to the constant
802 unsigned Andersens::getNodeForConstantPointer(Constant *C) {
803 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
805 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
807 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
809 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
810 switch (CE->getOpcode()) {
811 case Instruction::GetElementPtr:
812 return getNodeForConstantPointer(CE->getOperand(0));
813 case Instruction::IntToPtr:
815 case Instruction::BitCast:
816 return getNodeForConstantPointer(CE->getOperand(0));
818 cerr << "Constant Expr not yet handled: " << *CE << "\n";
822 assert(0 && "Unknown constant pointer!");
827 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
828 /// specified constant pointer.
829 unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
830 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
832 if (isa<ConstantPointerNull>(C))
834 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
835 return getObject(GV);
836 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
837 switch (CE->getOpcode()) {
838 case Instruction::GetElementPtr:
839 return getNodeForConstantPointerTarget(CE->getOperand(0));
840 case Instruction::IntToPtr:
842 case Instruction::BitCast:
843 return getNodeForConstantPointerTarget(CE->getOperand(0));
845 cerr << "Constant Expr not yet handled: " << *CE << "\n";
849 assert(0 && "Unknown constant pointer!");
854 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
855 /// object N, which contains values indicated by C.
856 void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
858 if (C->getType()->isFirstClassType()) {
859 if (isa<PointerType>(C->getType()))
860 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
861 getNodeForConstantPointer(C)));
862 } else if (C->isNullValue()) {
863 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
866 } else if (!isa<UndefValue>(C)) {
867 // If this is an array or struct, include constraints for each element.
868 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
869 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
870 AddGlobalInitializerConstraints(NodeIndex,
871 cast<Constant>(C->getOperand(i)));
875 /// AddConstraintsForNonInternalLinkage - If this function does not have
876 /// internal linkage, realize that we can't trust anything passed into or
877 /// returned by this function.
878 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
879 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
880 if (isa<PointerType>(I->getType()))
881 // If this is an argument of an externally accessible function, the
882 // incoming pointer might point to anything.
883 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
887 /// AddConstraintsForCall - If this is a call to a "known" function, add the
888 /// constraints and return true. If this is a call to an unknown function,
890 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
891 assert(F->isDeclaration() && "Not an external function!");
893 // These functions don't induce any points-to constraints.
894 if (F->getName() == "atoi" || F->getName() == "atof" ||
895 F->getName() == "atol" || F->getName() == "atoll" ||
896 F->getName() == "remove" || F->getName() == "unlink" ||
897 F->getName() == "rename" || F->getName() == "memcmp" ||
898 F->getName() == "llvm.memset.i32" ||
899 F->getName() == "llvm.memset.i64" ||
900 F->getName() == "strcmp" || F->getName() == "strncmp" ||
901 F->getName() == "execl" || F->getName() == "execlp" ||
902 F->getName() == "execle" || F->getName() == "execv" ||
903 F->getName() == "execvp" || F->getName() == "chmod" ||
904 F->getName() == "puts" || F->getName() == "write" ||
905 F->getName() == "open" || F->getName() == "create" ||
906 F->getName() == "truncate" || F->getName() == "chdir" ||
907 F->getName() == "mkdir" || F->getName() == "rmdir" ||
908 F->getName() == "read" || F->getName() == "pipe" ||
909 F->getName() == "wait" || F->getName() == "time" ||
910 F->getName() == "stat" || F->getName() == "fstat" ||
911 F->getName() == "lstat" || F->getName() == "strtod" ||
912 F->getName() == "strtof" || F->getName() == "strtold" ||
913 F->getName() == "fopen" || F->getName() == "fdopen" ||
914 F->getName() == "freopen" ||
915 F->getName() == "fflush" || F->getName() == "feof" ||
916 F->getName() == "fileno" || F->getName() == "clearerr" ||
917 F->getName() == "rewind" || F->getName() == "ftell" ||
918 F->getName() == "ferror" || F->getName() == "fgetc" ||
919 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
920 F->getName() == "fwrite" || F->getName() == "fread" ||
921 F->getName() == "fgets" || F->getName() == "ungetc" ||
922 F->getName() == "fputc" ||
923 F->getName() == "fputs" || F->getName() == "putc" ||
924 F->getName() == "ftell" || F->getName() == "rewind" ||
925 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
926 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
927 F->getName() == "printf" || F->getName() == "fprintf" ||
928 F->getName() == "sprintf" || F->getName() == "vprintf" ||
929 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
930 F->getName() == "scanf" || F->getName() == "fscanf" ||
931 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
932 F->getName() == "modf")
936 // These functions do induce points-to edges.
937 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
938 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
939 F->getName() == "memmove") {
941 // *Dest = *Src, which requires an artificial graph node to represent the
942 // constraint. It is broken up into *Dest = temp, temp = *Src
943 unsigned FirstArg = getNode(CS.getArgument(0));
944 unsigned SecondArg = getNode(CS.getArgument(1));
945 unsigned TempArg = GraphNodes.size();
946 GraphNodes.push_back(Node());
947 Constraints.push_back(Constraint(Constraint::Store,
949 Constraints.push_back(Constraint(Constraint::Load,
950 TempArg, SecondArg));
955 if (F->getName() == "realloc" || F->getName() == "strchr" ||
956 F->getName() == "strrchr" || F->getName() == "strstr" ||
957 F->getName() == "strtok") {
958 Constraints.push_back(Constraint(Constraint::Copy,
959 getNode(CS.getInstruction()),
960 getNode(CS.getArgument(0))));
969 /// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
970 /// If this is used by anything complex (i.e., the address escapes), return
972 bool Andersens::AnalyzeUsesOfFunction(Value *V) {
974 if (!isa<PointerType>(V->getType())) return true;
976 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
977 if (dyn_cast<LoadInst>(*UI)) {
979 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
980 if (V == SI->getOperand(1)) {
982 } else if (SI->getOperand(1)) {
983 return true; // Storing the pointer
985 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
986 if (AnalyzeUsesOfFunction(GEP)) return true;
987 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
988 // Make sure that this is just the function being called, not that it is
989 // passing into the function.
990 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
991 if (CI->getOperand(i) == V) return true;
992 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
993 // Make sure that this is just the function being called, not that it is
994 // passing into the function.
995 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
996 if (II->getOperand(i) == V) return true;
997 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
998 if (CE->getOpcode() == Instruction::GetElementPtr ||
999 CE->getOpcode() == Instruction::BitCast) {
1000 if (AnalyzeUsesOfFunction(CE))
1005 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1006 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1007 return true; // Allow comparison against null.
1008 } else if (dyn_cast<FreeInst>(*UI)) {
1016 /// CollectConstraints - This stage scans the program, adding a constraint to
1017 /// the Constraints list for each instruction in the program that induces a
1018 /// constraint, and setting up the initial points-to graph.
1020 void Andersens::CollectConstraints(Module &M) {
1021 // First, the universal set points to itself.
1022 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1024 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1027 // Next, the null pointer points to the null object.
1028 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
1030 // Next, add any constraints on global variables and their initializers.
1031 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1033 // Associate the address of the global object as pointing to the memory for
1034 // the global: &G = <G memory>
1035 unsigned ObjectIndex = getObject(I);
1036 Node *Object = &GraphNodes[ObjectIndex];
1037 Object->setValue(I);
1038 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1041 if (I->hasInitializer()) {
1042 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
1044 // If it doesn't have an initializer (i.e. it's defined in another
1045 // translation unit), it points to the universal set.
1046 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1051 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1052 // Set up the return value node.
1053 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1054 GraphNodes[getReturnNode(F)].setValue(F);
1055 if (F->getFunctionType()->isVarArg())
1056 GraphNodes[getVarargNode(F)].setValue(F);
1058 // Set up incoming argument nodes.
1059 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1061 if (isa<PointerType>(I->getType()))
1064 // At some point we should just add constraints for the escaping functions
1065 // at solve time, but this slows down solving. For now, we simply mark
1066 // address taken functions as escaping and treat them as external.
1067 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
1068 AddConstraintsForNonInternalLinkage(F);
1070 if (!F->isDeclaration()) {
1071 // Scan the function body, creating a memory object for each heap/stack
1072 // allocation in the body of the function and a node to represent all
1073 // pointer values defined by instructions and used as operands.
1076 // External functions that return pointers return the universal set.
1077 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1078 Constraints.push_back(Constraint(Constraint::Copy,
1082 // Any pointers that are passed into the function have the universal set
1083 // stored into them.
1084 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1086 if (isa<PointerType>(I->getType())) {
1087 // Pointers passed into external functions could have anything stored
1089 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
1091 // Memory objects passed into external function calls can have the
1092 // universal set point to them.
1094 Constraints.push_back(Constraint(Constraint::Copy,
1098 Constraints.push_back(Constraint(Constraint::Copy,
1104 // If this is an external varargs function, it can also store pointers
1105 // into any pointers passed through the varargs section.
1106 if (F->getFunctionType()->isVarArg())
1107 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
1111 NumConstraints += Constraints.size();
1115 void Andersens::visitInstruction(Instruction &I) {
1117 return; // This function is just a big assert.
1119 if (isa<BinaryOperator>(I))
1121 // Most instructions don't have any effect on pointer values.
1122 switch (I.getOpcode()) {
1123 case Instruction::Br:
1124 case Instruction::Switch:
1125 case Instruction::Unwind:
1126 case Instruction::Unreachable:
1127 case Instruction::Free:
1128 case Instruction::ICmp:
1129 case Instruction::FCmp:
1132 // Is this something we aren't handling yet?
1133 cerr << "Unknown instruction: " << I;
1138 void Andersens::visitAllocationInst(AllocationInst &AI) {
1139 unsigned ObjectIndex = getObject(&AI);
1140 GraphNodes[ObjectIndex].setValue(&AI);
1141 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1145 void Andersens::visitReturnInst(ReturnInst &RI) {
1146 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1147 // return V --> <Copy/retval{F}/v>
1148 Constraints.push_back(Constraint(Constraint::Copy,
1149 getReturnNode(RI.getParent()->getParent()),
1150 getNode(RI.getOperand(0))));
1153 void Andersens::visitLoadInst(LoadInst &LI) {
1154 if (isa<PointerType>(LI.getType()))
1155 // P1 = load P2 --> <Load/P1/P2>
1156 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1157 getNode(LI.getOperand(0))));
1160 void Andersens::visitStoreInst(StoreInst &SI) {
1161 if (isa<PointerType>(SI.getOperand(0)->getType()))
1162 // store P1, P2 --> <Store/P2/P1>
1163 Constraints.push_back(Constraint(Constraint::Store,
1164 getNode(SI.getOperand(1)),
1165 getNode(SI.getOperand(0))));
1168 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1169 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1170 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1171 getNode(GEP.getOperand(0))));
1174 void Andersens::visitPHINode(PHINode &PN) {
1175 if (isa<PointerType>(PN.getType())) {
1176 unsigned PNN = getNodeValue(PN);
1177 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1178 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1179 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1180 getNode(PN.getIncomingValue(i))));
1184 void Andersens::visitCastInst(CastInst &CI) {
1185 Value *Op = CI.getOperand(0);
1186 if (isa<PointerType>(CI.getType())) {
1187 if (isa<PointerType>(Op->getType())) {
1188 // P1 = cast P2 --> <Copy/P1/P2>
1189 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1190 getNode(CI.getOperand(0))));
1192 // P1 = cast int --> <Copy/P1/Univ>
1194 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1200 } else if (isa<PointerType>(Op->getType())) {
1201 // int = cast P1 --> <Copy/Univ/P1>
1203 Constraints.push_back(Constraint(Constraint::Copy,
1205 getNode(CI.getOperand(0))));
1207 getNode(CI.getOperand(0));
1212 void Andersens::visitSelectInst(SelectInst &SI) {
1213 if (isa<PointerType>(SI.getType())) {
1214 unsigned SIN = getNodeValue(SI);
1215 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1216 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1217 getNode(SI.getOperand(1))));
1218 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1219 getNode(SI.getOperand(2))));
1223 void Andersens::visitVAArg(VAArgInst &I) {
1224 assert(0 && "vaarg not handled yet!");
1227 /// AddConstraintsForCall - Add constraints for a call with actual arguments
1228 /// specified by CS to the function specified by F. Note that the types of
1229 /// arguments might not match up in the case where this is an indirect call and
1230 /// the function pointer has been casted. If this is the case, do something
1232 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
1233 Value *CallValue = CS.getCalledValue();
1234 bool IsDeref = F == NULL;
1236 // If this is a call to an external function, try to handle it directly to get
1237 // some taste of context sensitivity.
1238 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
1241 if (isa<PointerType>(CS.getType())) {
1242 unsigned CSN = getNode(CS.getInstruction());
1243 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1245 Constraints.push_back(Constraint(Constraint::Load, CSN,
1246 getNode(CallValue), CallReturnPos));
1248 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1249 getNode(CallValue) + CallReturnPos));
1251 // If the function returns a non-pointer value, handle this just like we
1252 // treat a nonpointer cast to pointer.
1253 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1256 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
1258 Constraints.push_back(Constraint(Constraint::Copy,
1260 getNode(CallValue) + CallReturnPos));
1262 Constraints.push_back(Constraint(Constraint::Copy,
1263 getNode(CallValue) + CallReturnPos,
1270 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
1271 bool external = !F || F->isDeclaration();
1274 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1275 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1278 if (external && isa<PointerType>((*ArgI)->getType()))
1280 // Add constraint that ArgI can now point to anything due to
1281 // escaping, as can everything it points to. The second portion of
1282 // this should be taken care of by universal = *universal
1283 Constraints.push_back(Constraint(Constraint::Copy,
1288 if (isa<PointerType>(AI->getType())) {
1289 if (isa<PointerType>((*ArgI)->getType())) {
1290 // Copy the actual argument into the formal argument.
1291 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1294 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1297 } else if (isa<PointerType>((*ArgI)->getType())) {
1299 Constraints.push_back(Constraint(Constraint::Copy,
1303 Constraints.push_back(Constraint(Constraint::Copy,
1311 unsigned ArgPos = CallFirstArgPos;
1312 for (; ArgI != ArgE; ++ArgI) {
1313 if (isa<PointerType>((*ArgI)->getType())) {
1314 // Copy the actual argument into the formal argument.
1315 Constraints.push_back(Constraint(Constraint::Store,
1317 getNode(*ArgI), ArgPos++));
1319 Constraints.push_back(Constraint(Constraint::Store,
1320 getNode (CallValue),
1321 UniversalSet, ArgPos++));
1325 // Copy all pointers passed through the varargs section to the varargs node.
1326 if (F && F->getFunctionType()->isVarArg())
1327 for (; ArgI != ArgE; ++ArgI)
1328 if (isa<PointerType>((*ArgI)->getType()))
1329 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1331 // If more arguments are passed in than we track, just drop them on the floor.
1334 void Andersens::visitCallSite(CallSite CS) {
1335 if (isa<PointerType>(CS.getType()))
1336 getNodeValue(*CS.getInstruction());
1338 if (Function *F = CS.getCalledFunction()) {
1339 AddConstraintsForCall(CS, F);
1341 AddConstraintsForCall(CS, NULL);
1345 //===----------------------------------------------------------------------===//
1346 // Constraint Solving Phase
1347 //===----------------------------------------------------------------------===//
1349 /// intersects - Return true if the points-to set of this node intersects
1350 /// with the points-to set of the specified node.
1351 bool Andersens::Node::intersects(Node *N) const {
1352 return PointsTo->intersects(N->PointsTo);
1355 /// intersectsIgnoring - Return true if the points-to set of this node
1356 /// intersects with the points-to set of the specified node on any nodes
1357 /// except for the specified node to ignore.
1358 bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1359 // TODO: If we are only going to call this with the same value for Ignoring,
1360 // we should move the special values out of the points-to bitmap.
1361 bool WeHadIt = PointsTo->test(Ignoring);
1362 bool NHadIt = N->PointsTo->test(Ignoring);
1363 bool Result = false;
1365 PointsTo->reset(Ignoring);
1367 N->PointsTo->reset(Ignoring);
1368 Result = PointsTo->intersects(N->PointsTo);
1370 PointsTo->set(Ignoring);
1372 N->PointsTo->set(Ignoring);
1376 void dumpToDOUT(SparseBitVector<> *bitmap) {
1378 dump(*bitmap, DOUT);
1383 /// Clump together address taken variables so that the points-to sets use up
1384 /// less space and can be operated on faster.
1386 void Andersens::ClumpAddressTaken() {
1388 #define DEBUG_TYPE "anders-aa-renumber"
1389 std::vector<unsigned> Translate;
1390 std::vector<Node> NewGraphNodes;
1392 Translate.resize(GraphNodes.size());
1393 unsigned NewPos = 0;
1395 for (unsigned i = 0; i < Constraints.size(); ++i) {
1396 Constraint &C = Constraints[i];
1397 if (C.Type == Constraint::AddressOf) {
1398 GraphNodes[C.Src].AddressTaken = true;
1401 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1402 unsigned Pos = NewPos++;
1404 NewGraphNodes.push_back(GraphNodes[i]);
1405 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1408 // I believe this ends up being faster than making two vectors and splicing
1410 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1411 if (GraphNodes[i].AddressTaken) {
1412 unsigned Pos = NewPos++;
1414 NewGraphNodes.push_back(GraphNodes[i]);
1415 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1419 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1420 if (!GraphNodes[i].AddressTaken) {
1421 unsigned Pos = NewPos++;
1423 NewGraphNodes.push_back(GraphNodes[i]);
1424 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1428 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1429 Iter != ValueNodes.end();
1431 Iter->second = Translate[Iter->second];
1433 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1434 Iter != ObjectNodes.end();
1436 Iter->second = Translate[Iter->second];
1438 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1439 Iter != ReturnNodes.end();
1441 Iter->second = Translate[Iter->second];
1443 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1444 Iter != VarargNodes.end();
1446 Iter->second = Translate[Iter->second];
1448 for (unsigned i = 0; i < Constraints.size(); ++i) {
1449 Constraint &C = Constraints[i];
1450 C.Src = Translate[C.Src];
1451 C.Dest = Translate[C.Dest];
1454 GraphNodes.swap(NewGraphNodes);
1456 #define DEBUG_TYPE "anders-aa"
1459 /// The technique used here is described in "Exploiting Pointer and Location
1460 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1461 /// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1462 /// and is equivalent to value numbering the collapsed constraint graph without
1463 /// evaluating unions. This is used as a pre-pass to HU in order to resolve
1464 /// first order pointer dereferences and speed up/reduce memory usage of HU.
1465 /// Running both is equivalent to HRU without the iteration
1466 /// HVN in more detail:
1467 /// Imagine the set of constraints was simply straight line code with no loops
1468 /// (we eliminate cycles, so there are no loops), such as:
1474 /// Applying value numbering to this code tells us:
1477 /// For HVN, this is as far as it goes. We assign new value numbers to every
1478 /// "address node", and every "reference node".
1479 /// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1480 /// cycle must have the same value number since the = operation is really
1481 /// inclusion, not overwrite), and value number nodes we receive points-to sets
1482 /// before we value our own node.
1483 /// The advantage of HU over HVN is that HU considers the inclusion property, so
1484 /// that if you have
1491 /// HU will determine that G == F == E. HVN will not, because it cannot prove
1492 /// that the points to information ends up being the same because they all
1493 /// receive &D from E anyway.
1495 void Andersens::HVN() {
1496 DOUT << "Beginning HVN\n";
1497 // Build a predecessor graph. This is like our constraint graph with the
1498 // edges going in the opposite direction, and there are edges for all the
1499 // constraints, instead of just copy constraints. We also build implicit
1500 // edges for constraints are implied but not explicit. I.E for the constraint
1501 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1502 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1503 Constraint &C = Constraints[i];
1504 if (C.Type == Constraint::AddressOf) {
1505 GraphNodes[C.Src].AddressTaken = true;
1506 GraphNodes[C.Src].Direct = false;
1509 unsigned AdrNode = C.Src + FirstAdrNode;
1510 if (!GraphNodes[C.Dest].PredEdges)
1511 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1512 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1515 unsigned RefNode = C.Dest + FirstRefNode;
1516 if (!GraphNodes[RefNode].ImplicitPredEdges)
1517 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1518 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1519 } else if (C.Type == Constraint::Load) {
1520 if (C.Offset == 0) {
1522 if (!GraphNodes[C.Dest].PredEdges)
1523 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1524 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1526 GraphNodes[C.Dest].Direct = false;
1528 } else if (C.Type == Constraint::Store) {
1529 if (C.Offset == 0) {
1531 unsigned RefNode = C.Dest + FirstRefNode;
1532 if (!GraphNodes[RefNode].PredEdges)
1533 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1534 GraphNodes[RefNode].PredEdges->set(C.Src);
1537 // Dest = Src edge and *Dest = *Src edge
1538 if (!GraphNodes[C.Dest].PredEdges)
1539 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1540 GraphNodes[C.Dest].PredEdges->set(C.Src);
1541 unsigned RefNode = C.Dest + FirstRefNode;
1542 if (!GraphNodes[RefNode].ImplicitPredEdges)
1543 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1544 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1548 // Do SCC finding first to condense our predecessor graph
1550 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1551 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1552 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1554 for (unsigned i = 0; i < FirstRefNode; ++i) {
1555 unsigned Node = VSSCCRep[i];
1556 if (!Node2Visited[Node])
1559 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1560 Iter != Set2PEClass.end();
1563 Set2PEClass.clear();
1565 Node2Deleted.clear();
1566 Node2Visited.clear();
1567 DOUT << "Finished HVN\n";
1571 /// This is the workhorse of HVN value numbering. We combine SCC finding at the
1572 /// same time because it's easy.
1573 void Andersens::HVNValNum(unsigned NodeIndex) {
1574 unsigned MyDFS = DFSNumber++;
1575 Node *N = &GraphNodes[NodeIndex];
1576 Node2Visited[NodeIndex] = true;
1577 Node2DFS[NodeIndex] = MyDFS;
1579 // First process all our explicit edges
1581 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1582 Iter != N->PredEdges->end();
1584 unsigned j = VSSCCRep[*Iter];
1585 if (!Node2Deleted[j]) {
1586 if (!Node2Visited[j])
1588 if (Node2DFS[NodeIndex] > Node2DFS[j])
1589 Node2DFS[NodeIndex] = Node2DFS[j];
1593 // Now process all the implicit edges
1594 if (N->ImplicitPredEdges)
1595 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1596 Iter != N->ImplicitPredEdges->end();
1598 unsigned j = VSSCCRep[*Iter];
1599 if (!Node2Deleted[j]) {
1600 if (!Node2Visited[j])
1602 if (Node2DFS[NodeIndex] > Node2DFS[j])
1603 Node2DFS[NodeIndex] = Node2DFS[j];
1607 // See if we found any cycles
1608 if (MyDFS == Node2DFS[NodeIndex]) {
1609 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1610 unsigned CycleNodeIndex = SCCStack.top();
1611 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1612 VSSCCRep[CycleNodeIndex] = NodeIndex;
1614 N->Direct &= CycleNode->Direct;
1616 if (CycleNode->PredEdges) {
1618 N->PredEdges = new SparseBitVector<>;
1619 *(N->PredEdges) |= CycleNode->PredEdges;
1620 delete CycleNode->PredEdges;
1621 CycleNode->PredEdges = NULL;
1623 if (CycleNode->ImplicitPredEdges) {
1624 if (!N->ImplicitPredEdges)
1625 N->ImplicitPredEdges = new SparseBitVector<>;
1626 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1627 delete CycleNode->ImplicitPredEdges;
1628 CycleNode->ImplicitPredEdges = NULL;
1634 Node2Deleted[NodeIndex] = true;
1637 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1641 // Collect labels of successor nodes
1642 bool AllSame = true;
1643 unsigned First = ~0;
1644 SparseBitVector<> *Labels = new SparseBitVector<>;
1648 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1649 Iter != N->PredEdges->end();
1651 unsigned j = VSSCCRep[*Iter];
1652 unsigned Label = GraphNodes[j].PointerEquivLabel;
1653 // Ignore labels that are equal to us or non-pointers
1654 if (j == NodeIndex || Label == 0)
1656 if (First == (unsigned)~0)
1658 else if (First != Label)
1663 // We either have a non-pointer, a copy of an existing node, or a new node.
1664 // Assign the appropriate pointer equivalence label.
1665 if (Labels->empty()) {
1666 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1667 } else if (AllSame) {
1668 GraphNodes[NodeIndex].PointerEquivLabel = First;
1670 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1671 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1672 unsigned EquivClass = PEClass++;
1673 Set2PEClass[Labels] = EquivClass;
1674 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1681 SCCStack.push(NodeIndex);
1685 /// The technique used here is described in "Exploiting Pointer and Location
1686 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1687 /// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1688 /// and is equivalent to value numbering the collapsed constraint graph
1689 /// including evaluating unions.
1690 void Andersens::HU() {
1691 DOUT << "Beginning HU\n";
1692 // Build a predecessor graph. This is like our constraint graph with the
1693 // edges going in the opposite direction, and there are edges for all the
1694 // constraints, instead of just copy constraints. We also build implicit
1695 // edges for constraints are implied but not explicit. I.E for the constraint
1696 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1697 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1698 Constraint &C = Constraints[i];
1699 if (C.Type == Constraint::AddressOf) {
1700 GraphNodes[C.Src].AddressTaken = true;
1701 GraphNodes[C.Src].Direct = false;
1703 GraphNodes[C.Dest].PointsTo->set(C.Src);
1705 unsigned RefNode = C.Dest + FirstRefNode;
1706 if (!GraphNodes[RefNode].ImplicitPredEdges)
1707 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1708 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1709 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1710 } else if (C.Type == Constraint::Load) {
1711 if (C.Offset == 0) {
1713 if (!GraphNodes[C.Dest].PredEdges)
1714 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1715 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1717 GraphNodes[C.Dest].Direct = false;
1719 } else if (C.Type == Constraint::Store) {
1720 if (C.Offset == 0) {
1722 unsigned RefNode = C.Dest + FirstRefNode;
1723 if (!GraphNodes[RefNode].PredEdges)
1724 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1725 GraphNodes[RefNode].PredEdges->set(C.Src);
1728 // Dest = Src edge and *Dest = *Src edg
1729 if (!GraphNodes[C.Dest].PredEdges)
1730 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1731 GraphNodes[C.Dest].PredEdges->set(C.Src);
1732 unsigned RefNode = C.Dest + FirstRefNode;
1733 if (!GraphNodes[RefNode].ImplicitPredEdges)
1734 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1735 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1739 // Do SCC finding first to condense our predecessor graph
1741 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1742 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1743 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1745 for (unsigned i = 0; i < FirstRefNode; ++i) {
1746 if (FindNode(i) == i) {
1747 unsigned Node = VSSCCRep[i];
1748 if (!Node2Visited[Node])
1753 // Reset tables for actual labeling
1755 Node2Visited.clear();
1756 Node2Deleted.clear();
1757 // Pre-grow our densemap so that we don't get really bad behavior
1758 Set2PEClass.resize(GraphNodes.size());
1760 // Visit the condensed graph and generate pointer equivalence labels.
1761 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1762 for (unsigned i = 0; i < FirstRefNode; ++i) {
1763 if (FindNode(i) == i) {
1764 unsigned Node = VSSCCRep[i];
1765 if (!Node2Visited[Node])
1769 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1770 Set2PEClass.clear();
1771 DOUT << "Finished HU\n";
1775 /// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1776 void Andersens::Condense(unsigned NodeIndex) {
1777 unsigned MyDFS = DFSNumber++;
1778 Node *N = &GraphNodes[NodeIndex];
1779 Node2Visited[NodeIndex] = true;
1780 Node2DFS[NodeIndex] = MyDFS;
1782 // First process all our explicit edges
1784 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1785 Iter != N->PredEdges->end();
1787 unsigned j = VSSCCRep[*Iter];
1788 if (!Node2Deleted[j]) {
1789 if (!Node2Visited[j])
1791 if (Node2DFS[NodeIndex] > Node2DFS[j])
1792 Node2DFS[NodeIndex] = Node2DFS[j];
1796 // Now process all the implicit edges
1797 if (N->ImplicitPredEdges)
1798 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1799 Iter != N->ImplicitPredEdges->end();
1801 unsigned j = VSSCCRep[*Iter];
1802 if (!Node2Deleted[j]) {
1803 if (!Node2Visited[j])
1805 if (Node2DFS[NodeIndex] > Node2DFS[j])
1806 Node2DFS[NodeIndex] = Node2DFS[j];
1810 // See if we found any cycles
1811 if (MyDFS == Node2DFS[NodeIndex]) {
1812 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1813 unsigned CycleNodeIndex = SCCStack.top();
1814 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1815 VSSCCRep[CycleNodeIndex] = NodeIndex;
1817 N->Direct &= CycleNode->Direct;
1819 *(N->PointsTo) |= CycleNode->PointsTo;
1820 delete CycleNode->PointsTo;
1821 CycleNode->PointsTo = NULL;
1822 if (CycleNode->PredEdges) {
1824 N->PredEdges = new SparseBitVector<>;
1825 *(N->PredEdges) |= CycleNode->PredEdges;
1826 delete CycleNode->PredEdges;
1827 CycleNode->PredEdges = NULL;
1829 if (CycleNode->ImplicitPredEdges) {
1830 if (!N->ImplicitPredEdges)
1831 N->ImplicitPredEdges = new SparseBitVector<>;
1832 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1833 delete CycleNode->ImplicitPredEdges;
1834 CycleNode->ImplicitPredEdges = NULL;
1839 Node2Deleted[NodeIndex] = true;
1841 // Set up number of incoming edges for other nodes
1843 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1844 Iter != N->PredEdges->end();
1846 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1848 SCCStack.push(NodeIndex);
1852 void Andersens::HUValNum(unsigned NodeIndex) {
1853 Node *N = &GraphNodes[NodeIndex];
1854 Node2Visited[NodeIndex] = true;
1856 // Eliminate dereferences of non-pointers for those non-pointers we have
1857 // already identified. These are ref nodes whose non-ref node:
1858 // 1. Has already been visited determined to point to nothing (and thus, a
1859 // dereference of it must point to nothing)
1860 // 2. Any direct node with no predecessor edges in our graph and with no
1861 // points-to set (since it can't point to anything either, being that it
1862 // receives no points-to sets and has none).
1863 if (NodeIndex >= FirstRefNode) {
1864 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1865 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1866 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1867 && GraphNodes[j].PointsTo->empty())){
1871 // Process all our explicit edges
1873 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1874 Iter != N->PredEdges->end();
1876 unsigned j = VSSCCRep[*Iter];
1877 if (!Node2Visited[j])
1880 // If this edge turned out to be the same as us, or got no pointer
1881 // equivalence label (and thus points to nothing) , just decrement our
1882 // incoming edges and continue.
1883 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1884 --GraphNodes[j].NumInEdges;
1888 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1890 // If we didn't end up storing this in the hash, and we're done with all
1891 // the edges, we don't need the points-to set anymore.
1892 --GraphNodes[j].NumInEdges;
1893 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1894 delete GraphNodes[j].PointsTo;
1895 GraphNodes[j].PointsTo = NULL;
1898 // If this isn't a direct node, generate a fresh variable.
1900 N->PointsTo->set(FirstRefNode + NodeIndex);
1903 // See If we have something equivalent to us, if not, generate a new
1904 // equivalence class.
1905 if (N->PointsTo->empty()) {
1910 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1911 if (N->PointerEquivLabel == 0) {
1912 unsigned EquivClass = PEClass++;
1913 N->StoredInHash = true;
1914 Set2PEClass[N->PointsTo] = EquivClass;
1915 N->PointerEquivLabel = EquivClass;
1918 N->PointerEquivLabel = PEClass++;
1923 /// Rewrite our list of constraints so that pointer equivalent nodes are
1924 /// replaced by their the pointer equivalence class representative.
1925 void Andersens::RewriteConstraints() {
1926 std::vector<Constraint> NewConstraints;
1927 DenseSet<Constraint, ConstraintKeyInfo> Seen;
1929 PEClass2Node.clear();
1930 PENLEClass2Node.clear();
1932 // We may have from 1 to Graphnodes + 1 equivalence classes.
1933 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1934 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1936 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1937 // nodes, and rewriting constraints to use the representative nodes.
1938 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1939 Constraint &C = Constraints[i];
1940 unsigned RHSNode = FindNode(C.Src);
1941 unsigned LHSNode = FindNode(C.Dest);
1942 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1943 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1945 // First we try to eliminate constraints for things we can prove don't point
1947 if (LHSLabel == 0) {
1948 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1949 DOUT << " is a non-pointer, ignoring constraint.\n";
1952 if (RHSLabel == 0) {
1953 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1954 DOUT << " is a non-pointer, ignoring constraint.\n";
1957 // This constraint may be useless, and it may become useless as we translate
1959 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1962 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1963 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
1964 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
1969 NewConstraints.push_back(C);
1971 Constraints.swap(NewConstraints);
1972 PEClass2Node.clear();
1975 /// See if we have a node that is pointer equivalent to the one being asked
1976 /// about, and if so, unite them and return the equivalent node. Otherwise,
1977 /// return the original node.
1978 unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1979 unsigned NodeLabel) {
1980 if (!GraphNodes[NodeIndex].AddressTaken) {
1981 if (PEClass2Node[NodeLabel] != -1) {
1982 // We found an existing node with the same pointer label, so unify them.
1983 // We specifically request that Union-By-Rank not be used so that
1984 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1985 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
1987 PEClass2Node[NodeLabel] = NodeIndex;
1988 PENLEClass2Node[NodeLabel] = NodeIndex;
1990 } else if (PENLEClass2Node[NodeLabel] == -1) {
1991 PENLEClass2Node[NodeLabel] = NodeIndex;
1997 void Andersens::PrintLabels() {
1998 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1999 if (i < FirstRefNode) {
2000 PrintNode(&GraphNodes[i]);
2001 } else if (i < FirstAdrNode) {
2003 PrintNode(&GraphNodes[i-FirstRefNode]);
2007 PrintNode(&GraphNodes[i-FirstAdrNode]);
2011 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2012 << " and SCC rep " << VSSCCRep[i]
2013 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2018 /// The technique used here is described in "The Ant and the
2019 /// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2020 /// Lines of Code. In Programming Language Design and Implementation
2021 /// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2022 /// Detection) algorithm. It is called a hybrid because it performs an
2023 /// offline analysis and uses its results during the solving (online)
2024 /// phase. This is just the offline portion; the results of this
2025 /// operation are stored in SDT and are later used in SolveContraints()
2026 /// and UniteNodes().
2027 void Andersens::HCD() {
2028 DOUT << "Starting HCD.\n";
2029 HCDSCCRep.resize(GraphNodes.size());
2031 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2032 GraphNodes[i].Edges = new SparseBitVector<>;
2036 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2037 Constraint &C = Constraints[i];
2038 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2039 if (C.Type == Constraint::AddressOf) {
2041 } else if (C.Type == Constraint::Load) {
2043 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2044 } else if (C.Type == Constraint::Store) {
2046 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2048 GraphNodes[C.Dest].Edges->set(C.Src);
2052 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2053 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2054 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2055 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2058 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2059 unsigned Node = HCDSCCRep[i];
2060 if (!Node2Deleted[Node])
2064 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2065 if (GraphNodes[i].Edges != NULL) {
2066 delete GraphNodes[i].Edges;
2067 GraphNodes[i].Edges = NULL;
2070 while( !SCCStack.empty() )
2074 Node2Visited.clear();
2075 Node2Deleted.clear();
2077 DOUT << "HCD complete.\n";
2080 // Component of HCD:
2081 // Use Nuutila's variant of Tarjan's algorithm to detect
2082 // Strongly-Connected Components (SCCs). For non-trivial SCCs
2083 // containing ref nodes, insert the appropriate information in SDT.
2084 void Andersens::Search(unsigned Node) {
2085 unsigned MyDFS = DFSNumber++;
2087 Node2Visited[Node] = true;
2088 Node2DFS[Node] = MyDFS;
2090 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2091 End = GraphNodes[Node].Edges->end();
2094 unsigned J = HCDSCCRep[*Iter];
2095 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2096 if (!Node2Deleted[J]) {
2097 if (!Node2Visited[J])
2099 if (Node2DFS[Node] > Node2DFS[J])
2100 Node2DFS[Node] = Node2DFS[J];
2104 if( MyDFS != Node2DFS[Node] ) {
2105 SCCStack.push(Node);
2109 // This node is the root of a SCC, so process it.
2111 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2112 // node, we place this SCC into SDT. We unite the nodes in any case.
2113 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2114 SparseBitVector<> SCC;
2118 bool Ref = (Node >= FirstRefNode);
2120 Node2Deleted[Node] = true;
2123 unsigned P = SCCStack.top(); SCCStack.pop();
2124 Ref |= (P >= FirstRefNode);
2126 HCDSCCRep[P] = Node;
2127 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2130 unsigned Rep = SCC.find_first();
2131 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2133 SparseBitVector<>::iterator i = SCC.begin();
2135 // Skip over the non-ref nodes
2136 while( *i < FirstRefNode )
2139 while( i != SCC.end() )
2140 SDT[ (*i++) - FirstRefNode ] = Rep;
2146 /// Optimize the constraints by performing offline variable substitution and
2147 /// other optimizations.
2148 void Andersens::OptimizeConstraints() {
2149 DOUT << "Beginning constraint optimization\n";
2153 // Function related nodes need to stay in the same relative position and can't
2154 // be location equivalent.
2155 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2158 for (unsigned i = Iter->first;
2159 i != Iter->first + Iter->second;
2161 GraphNodes[i].AddressTaken = true;
2162 GraphNodes[i].Direct = false;
2166 ClumpAddressTaken();
2167 FirstRefNode = GraphNodes.size();
2168 FirstAdrNode = FirstRefNode + GraphNodes.size();
2169 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2171 VSSCCRep.resize(GraphNodes.size());
2172 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2176 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2177 Node *N = &GraphNodes[i];
2178 delete N->PredEdges;
2179 N->PredEdges = NULL;
2180 delete N->ImplicitPredEdges;
2181 N->ImplicitPredEdges = NULL;
2184 #define DEBUG_TYPE "anders-aa-labels"
2185 DEBUG(PrintLabels());
2187 #define DEBUG_TYPE "anders-aa"
2188 RewriteConstraints();
2189 // Delete the adr nodes.
2190 GraphNodes.resize(FirstRefNode * 2);
2193 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2194 Node *N = &GraphNodes[i];
2195 if (FindNode(i) == i) {
2196 N->PointsTo = new SparseBitVector<>;
2197 N->PointedToBy = new SparseBitVector<>;
2201 N->PointerEquivLabel = 0;
2205 #define DEBUG_TYPE "anders-aa-labels"
2206 DEBUG(PrintLabels());
2208 #define DEBUG_TYPE "anders-aa"
2209 RewriteConstraints();
2210 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2211 if (FindNode(i) == i) {
2212 Node *N = &GraphNodes[i];
2215 delete N->PredEdges;
2216 N->PredEdges = NULL;
2217 delete N->ImplicitPredEdges;
2218 N->ImplicitPredEdges = NULL;
2219 delete N->PointedToBy;
2220 N->PointedToBy = NULL;
2224 // perform Hybrid Cycle Detection (HCD)
2228 // No longer any need for the upper half of GraphNodes (for ref nodes).
2229 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
2233 DOUT << "Finished constraint optimization\n";
2238 /// Unite pointer but not location equivalent variables, now that the constraint
2240 void Andersens::UnitePointerEquivalences() {
2241 DOUT << "Uniting remaining pointer equivalences\n";
2242 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2243 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
2244 unsigned Label = GraphNodes[i].PointerEquivLabel;
2246 if (Label && PENLEClass2Node[Label] != -1)
2247 UniteNodes(i, PENLEClass2Node[Label]);
2250 DOUT << "Finished remaining pointer equivalences\n";
2251 PENLEClass2Node.clear();
2254 /// Create the constraint graph used for solving points-to analysis.
2256 void Andersens::CreateConstraintGraph() {
2257 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2258 Constraint &C = Constraints[i];
2259 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2260 if (C.Type == Constraint::AddressOf)
2261 GraphNodes[C.Dest].PointsTo->set(C.Src);
2262 else if (C.Type == Constraint::Load)
2263 GraphNodes[C.Src].Constraints.push_back(C);
2264 else if (C.Type == Constraint::Store)
2265 GraphNodes[C.Dest].Constraints.push_back(C);
2266 else if (C.Offset != 0)
2267 GraphNodes[C.Src].Constraints.push_back(C);
2269 GraphNodes[C.Src].Edges->set(C.Dest);
2273 // Perform DFS and cycle detection.
2274 bool Andersens::QueryNode(unsigned Node) {
2275 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
2276 unsigned OurDFS = ++DFSNumber;
2277 SparseBitVector<> ToErase;
2278 SparseBitVector<> NewEdges;
2279 Tarjan2DFS[Node] = OurDFS;
2281 // Changed denotes a change from a recursive call that we will bubble up.
2282 // Merged is set if we actually merge a node ourselves.
2283 bool Changed = false, Merged = false;
2285 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2286 bi != GraphNodes[Node].Edges->end();
2288 unsigned RepNode = FindNode(*bi);
2289 // If this edge points to a non-representative node but we are
2290 // already planning to add an edge to its representative, we have no
2291 // need for this edge anymore.
2292 if (RepNode != *bi && NewEdges.test(RepNode)){
2297 // Continue about our DFS.
2298 if (!Tarjan2Deleted[RepNode]){
2299 if (Tarjan2DFS[RepNode] == 0) {
2300 Changed |= QueryNode(RepNode);
2301 // May have been changed by QueryNode
2302 RepNode = FindNode(RepNode);
2304 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2305 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
2308 // We may have just discovered that this node is part of a cycle, in
2309 // which case we can also erase it.
2310 if (RepNode != *bi) {
2312 NewEdges.set(RepNode);
2316 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2317 GraphNodes[Node].Edges |= NewEdges;
2319 // If this node is a root of a non-trivial SCC, place it on our
2320 // worklist to be processed.
2321 if (OurDFS == Tarjan2DFS[Node]) {
2322 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2323 Node = UniteNodes(Node, SCCStack.top());
2328 Tarjan2Deleted[Node] = true;
2331 NextWL->insert(&GraphNodes[Node]);
2333 SCCStack.push(Node);
2336 return(Changed | Merged);
2339 /// SolveConstraints - This stage iteratively processes the constraints list
2340 /// propagating constraints (adding edges to the Nodes in the points-to graph)
2341 /// until a fixed point is reached.
2343 /// We use a variant of the technique called "Lazy Cycle Detection", which is
2344 /// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2345 /// Analysis for Millions of Lines of Code. In Programming Language Design and
2346 /// Implementation (PLDI), June 2007."
2347 /// The paper describes performing cycle detection one node at a time, which can
2348 /// be expensive if there are no cycles, but there are long chains of nodes that
2349 /// it heuristically believes are cycles (because it will DFS from each node
2350 /// without state from previous nodes).
2351 /// Instead, we use the heuristic to build a worklist of nodes to check, then
2352 /// cycle detect them all at the same time to do this more cheaply. This
2353 /// catches cycles slightly later than the original technique did, but does it
2354 /// make significantly cheaper.
2356 void Andersens::SolveConstraints() {
2360 OptimizeConstraints();
2362 #define DEBUG_TYPE "anders-aa-constraints"
2363 DEBUG(PrintConstraints());
2365 #define DEBUG_TYPE "anders-aa"
2367 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2368 Node *N = &GraphNodes[i];
2369 N->PointsTo = new SparseBitVector<>;
2370 N->OldPointsTo = new SparseBitVector<>;
2371 N->Edges = new SparseBitVector<>;
2373 CreateConstraintGraph();
2374 UnitePointerEquivalences();
2375 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
2377 Node2Deleted.clear();
2378 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2379 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2381 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2382 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2384 // Order graph and add initial nodes to work list.
2385 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2386 Node *INode = &GraphNodes[i];
2388 // Add to work list if it's a representative and can contribute to the
2389 // calculation right now.
2390 if (INode->isRep() && !INode->PointsTo->empty()
2391 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2393 CurrWL->insert(INode);
2396 std::queue<unsigned int> TarjanWL;
2398 // "Rep and special variables" - in order for HCD to maintain conservative
2399 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2400 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2401 // the analysis - it's ok to add edges from the special nodes, but never
2402 // *to* the special nodes.
2403 std::vector<unsigned int> RSV;
2405 while( !CurrWL->empty() ) {
2406 DOUT << "Starting iteration #" << ++NumIters << "\n";
2409 unsigned CurrNodeIndex;
2411 // Actual cycle checking code. We cycle check all of the lazy cycle
2412 // candidates from the last iteration in one go.
2413 if (!TarjanWL.empty()) {
2417 Tarjan2Deleted.clear();
2418 while (!TarjanWL.empty()) {
2419 unsigned int ToTarjan = TarjanWL.front();
2421 if (!Tarjan2Deleted[ToTarjan]
2422 && GraphNodes[ToTarjan].isRep()
2423 && Tarjan2DFS[ToTarjan] == 0)
2424 QueryNode(ToTarjan);
2428 // Add to work list if it's a representative and can contribute to the
2429 // calculation right now.
2430 while( (CurrNode = CurrWL->pop()) != NULL ) {
2431 CurrNodeIndex = CurrNode - &GraphNodes[0];
2435 // Figure out the changed points to bits
2436 SparseBitVector<> CurrPointsTo;
2437 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2438 CurrNode->OldPointsTo);
2439 if (CurrPointsTo.empty())
2442 *(CurrNode->OldPointsTo) |= CurrPointsTo;
2444 // Check the offline-computed equivalencies from HCD.
2448 if (SDT[CurrNodeIndex] >= 0) {
2450 Rep = FindNode(SDT[CurrNodeIndex]);
2455 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2456 bi != CurrPointsTo.end(); ++bi) {
2457 unsigned Node = FindNode(*bi);
2459 if (Node < NumberSpecialNodes) {
2460 RSV.push_back(Node);
2464 Rep = UniteNodes(Rep,Node);
2470 NextWL->insert(&GraphNodes[Rep]);
2472 if ( ! CurrNode->isRep() )
2478 /* Now process the constraints for this node. */
2479 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2480 li != CurrNode->Constraints.end(); ) {
2481 li->Src = FindNode(li->Src);
2482 li->Dest = FindNode(li->Dest);
2484 // Delete redundant constraints
2485 if( Seen.count(*li) ) {
2486 std::list<Constraint>::iterator lk = li; li++;
2488 CurrNode->Constraints.erase(lk);
2494 // Src and Dest will be the vars we are going to process.
2495 // This may look a bit ugly, but what it does is allow us to process
2496 // both store and load constraints with the same code.
2497 // Load constraints say that every member of our RHS solution has K
2498 // added to it, and that variable gets an edge to LHS. We also union
2499 // RHS+K's solution into the LHS solution.
2500 // Store constraints say that every member of our LHS solution has K
2501 // added to it, and that variable gets an edge from RHS. We also union
2502 // RHS's solution into the LHS+K solution.
2505 unsigned K = li->Offset;
2506 unsigned CurrMember;
2507 if (li->Type == Constraint::Load) {
2510 } else if (li->Type == Constraint::Store) {
2514 // TODO Handle offseted copy constraint
2519 // See if we can use Hybrid Cycle Detection (that is, check
2520 // if it was a statically detected offline equivalence that
2521 // involves pointers; if so, remove the redundant constraints).
2522 if( SCC && K == 0 ) {
2526 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2527 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2528 NextWL->insert(&GraphNodes[*Dest]);
2530 for (unsigned i=0; i < RSV.size(); ++i) {
2531 CurrMember = RSV[i];
2533 if (*Dest < NumberSpecialNodes)
2535 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2536 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2537 NextWL->insert(&GraphNodes[*Dest]);
2540 // since all future elements of the points-to set will be
2541 // equivalent to the current ones, the complex constraints
2542 // become redundant.
2544 std::list<Constraint>::iterator lk = li; li++;
2546 // In this case, we can still erase the constraints when the
2547 // elements of the points-to sets are referenced by *Dest,
2548 // but not when they are referenced by *Src (i.e. for a Load
2549 // constraint). This is because if another special variable is
2550 // put into the points-to set later, we still need to add the
2551 // new edge from that special variable.
2552 if( lk->Type != Constraint::Load)
2554 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2556 const SparseBitVector<> &Solution = CurrPointsTo;
2558 for (SparseBitVector<>::iterator bi = Solution.begin();
2559 bi != Solution.end();
2563 // Need to increment the member by K since that is where we are
2564 // supposed to copy to/from. Note that in positive weight cycles,
2565 // which occur in address taking of fields, K can go past
2566 // MaxK[CurrMember] elements, even though that is all it could point
2568 if (K > 0 && K > MaxK[CurrMember])
2571 CurrMember = FindNode(CurrMember + K);
2573 // Add an edge to the graph, so we can just do regular
2574 // bitmap ior next time. It may also let us notice a cycle.
2576 if (*Dest < NumberSpecialNodes)
2579 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2580 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2581 NextWL->insert(&GraphNodes[*Dest]);
2587 SparseBitVector<> NewEdges;
2588 SparseBitVector<> ToErase;
2590 // Now all we have left to do is propagate points-to info along the
2591 // edges, erasing the redundant edges.
2592 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2593 bi != CurrNode->Edges->end();
2596 unsigned DestVar = *bi;
2597 unsigned Rep = FindNode(DestVar);
2599 // If we ended up with this node as our destination, or we've already
2600 // got an edge for the representative, delete the current edge.
2601 if (Rep == CurrNodeIndex ||
2602 (Rep != DestVar && NewEdges.test(Rep))) {
2603 ToErase.set(DestVar);
2607 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
2609 // This is where we do lazy cycle detection.
2610 // If this is a cycle candidate (equal points-to sets and this
2611 // particular edge has not been cycle-checked previously), add to the
2612 // list to check for cycles on the next iteration.
2613 if (!EdgesChecked.count(edge) &&
2614 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2615 EdgesChecked.insert(edge);
2618 // Union the points-to sets into the dest
2620 if (Rep >= NumberSpecialNodes)
2622 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2623 NextWL->insert(&GraphNodes[Rep]);
2625 // If this edge's destination was collapsed, rewrite the edge.
2626 if (Rep != DestVar) {
2627 ToErase.set(DestVar);
2631 CurrNode->Edges->intersectWithComplement(ToErase);
2632 CurrNode->Edges |= NewEdges;
2635 // Switch to other work list.
2636 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2641 Node2Deleted.clear();
2642 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2643 Node *N = &GraphNodes[i];
2644 delete N->OldPointsTo;
2651 //===----------------------------------------------------------------------===//
2653 //===----------------------------------------------------------------------===//
2655 // Unite nodes First and Second, returning the one which is now the
2656 // representative node. First and Second are indexes into GraphNodes
2657 unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2659 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2660 "Attempting to merge nodes that don't exist");
2662 Node *FirstNode = &GraphNodes[First];
2663 Node *SecondNode = &GraphNodes[Second];
2665 assert (SecondNode->isRep() && FirstNode->isRep() &&
2666 "Trying to unite two non-representative nodes!");
2667 if (First == Second)
2671 int RankFirst = (int) FirstNode ->NodeRep;
2672 int RankSecond = (int) SecondNode->NodeRep;
2674 // Rank starts at -1 and gets decremented as it increases.
2675 // Translation: higher rank, lower NodeRep value, which is always negative.
2676 if (RankFirst > RankSecond) {
2677 unsigned t = First; First = Second; Second = t;
2678 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2679 } else if (RankFirst == RankSecond) {
2680 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2684 SecondNode->NodeRep = First;
2686 if (First >= NumberSpecialNodes)
2688 if (FirstNode->PointsTo && SecondNode->PointsTo)
2689 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2690 if (FirstNode->Edges && SecondNode->Edges)
2691 FirstNode->Edges |= *(SecondNode->Edges);
2692 if (!SecondNode->Constraints.empty())
2693 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2694 SecondNode->Constraints);
2695 if (FirstNode->OldPointsTo) {
2696 delete FirstNode->OldPointsTo;
2697 FirstNode->OldPointsTo = new SparseBitVector<>;
2700 // Destroy interesting parts of the merged-from node.
2701 delete SecondNode->OldPointsTo;
2702 delete SecondNode->Edges;
2703 delete SecondNode->PointsTo;
2704 SecondNode->Edges = NULL;
2705 SecondNode->PointsTo = NULL;
2706 SecondNode->OldPointsTo = NULL;
2709 DOUT << "Unified Node ";
2710 DEBUG(PrintNode(FirstNode));
2711 DOUT << " and Node ";
2712 DEBUG(PrintNode(SecondNode));
2716 if (SDT[Second] >= 0)
2718 SDT[First] = SDT[Second];
2720 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2721 First = FindNode(First);
2727 // Find the index into GraphNodes of the node representing Node, performing
2728 // path compression along the way
2729 unsigned Andersens::FindNode(unsigned NodeIndex) {
2730 assert (NodeIndex < GraphNodes.size()
2731 && "Attempting to find a node that can't exist");
2732 Node *N = &GraphNodes[NodeIndex];
2736 return (N->NodeRep = FindNode(N->NodeRep));
2739 //===----------------------------------------------------------------------===//
2741 //===----------------------------------------------------------------------===//
2743 void Andersens::PrintNode(Node *N) {
2744 if (N == &GraphNodes[UniversalSet]) {
2745 cerr << "<universal>";
2747 } else if (N == &GraphNodes[NullPtr]) {
2748 cerr << "<nullptr>";
2750 } else if (N == &GraphNodes[NullObject]) {
2754 if (!N->getValue()) {
2755 cerr << "artificial" << (intptr_t) N;
2759 assert(N->getValue() != 0 && "Never set node label!");
2760 Value *V = N->getValue();
2761 if (Function *F = dyn_cast<Function>(V)) {
2762 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
2763 N == &GraphNodes[getReturnNode(F)]) {
2764 cerr << F->getName() << ":retval";
2766 } else if (F->getFunctionType()->isVarArg() &&
2767 N == &GraphNodes[getVarargNode(F)]) {
2768 cerr << F->getName() << ":vararg";
2773 if (Instruction *I = dyn_cast<Instruction>(V))
2774 cerr << I->getParent()->getParent()->getName() << ":";
2775 else if (Argument *Arg = dyn_cast<Argument>(V))
2776 cerr << Arg->getParent()->getName() << ":";
2779 cerr << V->getName();
2781 cerr << "(unnamed)";
2783 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
2784 if (N == &GraphNodes[getObject(V)])
2787 void Andersens::PrintConstraint(const Constraint &C) {
2788 if (C.Type == Constraint::Store) {
2793 PrintNode(&GraphNodes[C.Dest]);
2794 if (C.Type == Constraint::Store && C.Offset != 0)
2795 cerr << " + " << C.Offset << ")";
2797 if (C.Type == Constraint::Load) {
2802 else if (C.Type == Constraint::AddressOf)
2804 PrintNode(&GraphNodes[C.Src]);
2805 if (C.Offset != 0 && C.Type != Constraint::Store)
2806 cerr << " + " << C.Offset;
2807 if (C.Type == Constraint::Load && C.Offset != 0)
2812 void Andersens::PrintConstraints() {
2813 cerr << "Constraints:\n";
2815 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2816 PrintConstraint(Constraints[i]);
2819 void Andersens::PrintPointsToGraph() {
2820 cerr << "Points-to graph:\n";
2821 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2822 Node *N = &GraphNodes[i];
2823 if (FindNode (i) != i) {
2825 cerr << "\t--> same as ";
2826 PrintNode(&GraphNodes[FindNode(i)]);
2829 cerr << "[" << (N->PointsTo->count()) << "] ";
2834 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2835 bi != N->PointsTo->end();
2839 PrintNode(&GraphNodes[*bi]);