blob: 4411babc5de2ca355e8b828fd0d1053ba2fc51ed [file] [log] [blame]
Chris Lattnerd28b0d72004-06-25 04:24:22 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattnere995a2a2004-05-23 21:00:47 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattnere995a2a2004-05-23 21:00:47 +00008//===----------------------------------------------------------------------===//
9//
Daniel Berlinaad15882007-09-16 21:45:02 +000010// This file defines an implementation of Andersen's interprocedural alias
11// analysis
Chris Lattnere995a2a2004-05-23 21:00:47 +000012//
13// In pointer analysis terms, this is a subset-based, flow-insensitive,
Daniel Berlinaad15882007-09-16 21:45:02 +000014// field-sensitive, and context-insensitive algorithm pointer algorithm.
Chris Lattnere995a2a2004-05-23 21:00:47 +000015//
16// This algorithm is implemented as three stages:
17// 1. Object identification.
18// 2. Inclusion constraint identification.
Daniel Berlind81ccc22007-09-24 19:45:49 +000019// 3. Offline constraint graph optimization
20// 4. Inclusion constraint solving.
Chris Lattnere995a2a2004-05-23 21:00:47 +000021//
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
Daniel Berlinaad15882007-09-16 21:45:02 +000030// B can point to. Constraints can handle copies, loads, and stores, and
31// address taking.
Chris Lattnere995a2a2004-05-23 21:00:47 +000032//
Daniel Berline6f04792007-09-24 22:20:45 +000033// The offline constraint graph optimization portion includes offline variable
Daniel Berlinc864edb2008-03-05 19:31:47 +000034// substitution algorithms intended to compute pointer and location
Daniel Berline6f04792007-09-24 22:20:45 +000035// equivalences. Pointer equivalences are those pointers that will have the
36// same points-to sets, and location equivalences are those variables that
Daniel Berlinc864edb2008-03-05 19:31:47 +000037// always appear together in points-to sets. It also includes an offline
38// cycle detection algorithm that allows cycles to be collapsed sooner
39// during solving.
Daniel Berlind81ccc22007-09-24 19:45:49 +000040//
Chris Lattnere995a2a2004-05-23 21:00:47 +000041// The inclusion constraint solving phase iteratively propagates the inclusion
42// constraints until a fixed point is reached. This is an O(N^3) algorithm.
43//
Daniel Berlinaad15882007-09-16 21:45:02 +000044// 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
Daniel Berlind81ccc22007-09-24 19:45:49 +000047// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlinaad15882007-09-16 21:45:02 +000048// *(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.
Chris Lattnere995a2a2004-05-23 21:00:47 +000051//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000052// Future Improvements:
Daniel Berlinc864edb2008-03-05 19:31:47 +000053// Use of BDD's.
Chris Lattnere995a2a2004-05-23 21:00:47 +000054//===----------------------------------------------------------------------===//
55
56#define DEBUG_TYPE "anders-aa"
57#include "llvm/Constants.h"
58#include "llvm/DerivedTypes.h"
59#include "llvm/Instructions.h"
60#include "llvm/Module.h"
61#include "llvm/Pass.h"
Reid Spencerd7d83db2007-02-05 23:42:17 +000062#include "llvm/Support/Compiler.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000063#include "llvm/Support/InstIterator.h"
64#include "llvm/Support/InstVisitor.h"
65#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000066#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000067#include "llvm/Support/Debug.h"
68#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000069#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000070#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000071#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000072#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000073#include <list>
74#include <stack>
75#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000076#include <queue>
77
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
Chris Lattnere995a2a2004-05-23 21:00:47 +000083
Daniel Berlinaad15882007-09-16 21:45:02 +000084using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000085STATISTIC(NumIters , "Number of iterations to reach convergence");
86STATISTIC(NumConstraints, "Number of constraints");
87STATISTIC(NumNodes , "Number of nodes");
88STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000089STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000090
Chris Lattner3b27d682006-12-19 22:30:33 +000091namespace {
Daniel Berlinaad15882007-09-16 21:45:02 +000092 const unsigned SelfRep = (unsigned)-1;
93 const unsigned Unvisited = (unsigned)-1;
94 // Position of the function return node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000095 const unsigned CallReturnPos = 1;
Daniel Berlinaad15882007-09-16 21:45:02 +000096 // Position of the function call node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000097 const unsigned CallFirstArgPos = 2;
98
99 struct BitmapKeyInfo {
100 static inline SparseBitVector<> *getEmptyKey() {
101 return reinterpret_cast<SparseBitVector<> *>(-1);
102 }
103 static inline SparseBitVector<> *getTombstoneKey() {
104 return reinterpret_cast<SparseBitVector<> *>(-2);
105 }
106 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
107 return bitmap->getHashValue();
108 }
109 static bool isEqual(const SparseBitVector<> *LHS,
110 const SparseBitVector<> *RHS) {
111 if (LHS == RHS)
112 return true;
113 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
114 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
115 return false;
116
117 return *LHS == *RHS;
118 }
119
120 static bool isPod() { return true; }
121 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000122
Reid Spencerd7d83db2007-02-05 23:42:17 +0000123 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
124 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000125 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000126
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
Daniel Berlind81ccc22007-09-24 19:45:49 +0000133 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000134 /// resolvable to A = &C where C = B + K)
135
136 struct Constraint {
137 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
138 unsigned Dest;
139 unsigned Src;
140 unsigned Offset;
141
142 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
143 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000144 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000145 "Offset is illegal on addressof constraints");
146 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000147
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000148 bool operator==(const Constraint &RHS) const {
149 return RHS.Type == Type
150 && RHS.Dest == Dest
151 && RHS.Src == Src
152 && RHS.Offset == Offset;
153 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000154
155 bool operator!=(const Constraint &RHS) const {
156 return !(*this == RHS);
157 }
158
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000159 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;
167 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000168 };
169
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000170 // Information DenseSet requires implemented in order to be able to do
171 // it's thing
172 struct PairKeyInfo {
173 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000174 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000175 }
176 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000177 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000178 }
179 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
180 return P.first ^ P.second;
181 }
182 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
183 const std::pair<unsigned, unsigned> &RHS) {
184 return LHS == RHS;
185 }
186 };
187
Daniel Berlin336c6c02007-09-29 00:50:40 +0000188 struct ConstraintKeyInfo {
189 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000190 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000191 }
192 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000193 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000194 }
195 static unsigned getHashValue(const Constraint &C) {
196 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
197 }
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;
202 }
203 };
204
Daniel Berlind81ccc22007-09-24 19:45:49 +0000205 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000206 // 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.
Daniel Berlinaad15882007-09-16 21:45:02 +0000210 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000211 private:
212 static unsigned Counter;
213
214 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000215 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000216 SparseBitVector<> *Edges;
217 SparseBitVector<> *PointsTo;
218 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000219 std::list<Constraint> Constraints;
220
Daniel Berlind81ccc22007-09-24 19:45:49 +0000221 // 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
231 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000232 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000233 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000234 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000235 bool Direct;
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.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000240 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000241
Daniel Berlind81ccc22007-09-24 19:45:49 +0000242 // 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.
245 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000246
247 // Modification timestamp. Assigned from Counter.
248 // Used for work list prioritization.
249 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000250
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000251 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000252 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000253 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
254 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
255 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000256 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000257
Chris Lattnere995a2a2004-05-23 21:00:47 +0000258 Node *setValue(Value *V) {
259 assert(Val == 0 && "Value already set for this node!");
260 Val = V;
261 return this;
262 }
263
264 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000265 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000266 Value *getValue() const { return Val; }
267
Chris Lattnere995a2a2004-05-23 21:00:47 +0000268 /// 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.
Daniel Berlinaad15882007-09-16 21:45:02 +0000271 bool addPointerTo(unsigned Node) {
272 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000273 }
274
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;
278
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.
Daniel Berlinaad15882007-09-16 21:45:02 +0000282 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000283
284 // Timestamp a node (used for work list prioritization)
285 void Stamp() {
286 Timestamp = Counter++;
287 }
288
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000289 bool isRep() const {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000290 return( (int) NodeRep < 0 );
291 }
292 };
293
294 struct WorkListElement {
295 Node* node;
296 unsigned Timestamp;
297 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
298
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 );
305 }
306 };
307
308 // Priority-queue based work list specialized for Nodes.
309 class WorkList {
310 std::priority_queue<WorkListElement> Q;
311
312 public:
313 void insert(Node* n) {
314 Q.push( WorkListElement(n, n->Timestamp) );
315 }
316
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).
321 Node* pop() {
322 while( !Q.empty() ) {
323 WorkListElement x = Q.top(); Q.pop();
324 Node* INode = x.node;
325
326 if( INode->isRep() &&
327 INode->Timestamp == x.Timestamp ) {
328 return(x.node);
329 }
330 }
331 return(0);
332 }
333
334 bool empty() {
335 return Q.empty();
336 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000337 };
338
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;
343
344 /// ValueNodes - This map indicates the Node that a particular Value* is
345 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000346 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000347
348 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000349 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000350 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000351
352 /// ReturnNodes - This map contains an entry for each function in the
353 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000354 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000355
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.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000360 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000361
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000362
Chris Lattnere995a2a2004-05-23 21:00:47 +0000363 /// Constraints - This vector contains a list of all of the constraints
364 /// identified by the program.
365 std::vector<Constraint> Constraints;
366
Daniel Berlind81ccc22007-09-24 19:45:49 +0000367 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000368 // this is equivalent to the number of arguments + CallFirstArgPos)
369 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000370
371 /// This enum defines the GraphNodes indices that correspond to important
372 /// fixed sets.
373 enum {
374 UniversalSet = 0,
375 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000376 NullObject = 2,
377 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000378 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000379 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000380 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000381 // 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;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000385 // Same as Node Maps, but implemented as std::map because it is faster to
386 // clear
387 std::map<unsigned, unsigned> Tarjan2DFS;
388 std::map<unsigned, bool> Tarjan2Deleted;
389 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000390 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000391
392 // Work lists.
393 WorkList w1, w2;
394 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000395
Daniel Berlind81ccc22007-09-24 19:45:49 +0000396 // Offline variable substitution related things
397
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
412 unsigned PEClass;
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;
Daniel Berlinc864edb2008-03-05 19:31:47 +0000423 // 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)
429 bool SDTActive;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000430
Chris Lattnere995a2a2004-05-23 21:00:47 +0000431 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000432 static char ID;
Devang Patelc7582092008-03-19 21:56:59 +0000433 Andersens() : ModulePass((intptr_t)&ID) {}
Devang Patel1cee94f2008-03-18 00:39:19 +0000434
Chris Lattnerb12914b2004-09-20 04:48:05 +0000435 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000436 InitializeAliasAnalysis(this);
437 IdentifyObjects(M);
438 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000439#undef DEBUG_TYPE
440#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000441 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000442#undef DEBUG_TYPE
443#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000444 SolveConstraints();
445 DEBUG(PrintPointsToGraph());
446
447 // Free the constraints list, as we don't need it to respond to alias
448 // requests.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000449 std::vector<Constraint>().swap(Constraints);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000450 //These are needed for Print() (-analyze in opt)
451 //ObjectNodes.clear();
452 //ReturnNodes.clear();
453 //VarargNodes.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000454 return false;
455 }
456
457 void releaseMemory() {
458 // FIXME: Until we have transitively required passes working correctly,
459 // this cannot be enabled! Otherwise, using -count-aa with the pass
460 // causes memory to be freed too early. :(
461#if 0
462 // The memory objects and ValueNodes data structures at the only ones that
463 // are still live after construction.
464 std::vector<Node>().swap(GraphNodes);
465 ValueNodes.clear();
466#endif
467 }
468
469 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
470 AliasAnalysis::getAnalysisUsage(AU);
471 AU.setPreservesAll(); // Does not transform code
472 }
473
474 //------------------------------------------------
475 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000476 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000477 AliasResult alias(const Value *V1, unsigned V1Size,
478 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000479 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
480 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000481 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
482 bool pointsToConstantMemory(const Value *P);
483
484 virtual void deleteValue(Value *V) {
485 ValueNodes.erase(V);
486 getAnalysis<AliasAnalysis>().deleteValue(V);
487 }
488
489 virtual void copyValue(Value *From, Value *To) {
490 ValueNodes[To] = ValueNodes[From];
491 getAnalysis<AliasAnalysis>().copyValue(From, To);
492 }
493
494 private:
495 /// getNode - Return the node corresponding to the specified pointer scalar.
496 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000497 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000498 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000499 if (!isa<GlobalValue>(C))
500 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000501
Daniel Berlind81ccc22007-09-24 19:45:49 +0000502 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000503 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000504#ifndef NDEBUG
505 V->dump();
506#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000507 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000508 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000509 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000510 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000511
Chris Lattnere995a2a2004-05-23 21:00:47 +0000512 /// getObject - Return the node corresponding to the memory object for the
513 /// specified global or allocation instruction.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000514 unsigned getObject(Value *V) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000515 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000516 assert(I != ObjectNodes.end() &&
517 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000518 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000519 }
520
521 /// getReturnNode - Return the node representing the return value for the
522 /// specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000523 unsigned getReturnNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000524 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000525 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000526 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000527 }
528
529 /// getVarargNode - Return the node representing the variable arguments
530 /// formal for the specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000531 unsigned getVarargNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000532 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000533 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000534 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000535 }
536
537 /// getNodeValue - Get the node for the specified LLVM value and set the
538 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000539 unsigned getNodeValue(Value &V) {
540 unsigned Index = getNode(&V);
541 GraphNodes[Index].setValue(&V);
542 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000543 }
544
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000545 unsigned UniteNodes(unsigned First, unsigned Second,
546 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000547 unsigned FindNode(unsigned Node);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000548 unsigned FindNode(unsigned Node) const;
Daniel Berlinaad15882007-09-16 21:45:02 +0000549
Chris Lattnere995a2a2004-05-23 21:00:47 +0000550 void IdentifyObjects(Module &M);
551 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000552 bool AnalyzeUsesOfFunction(Value *);
553 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000554 void OptimizeConstraints();
555 unsigned FindEquivalentNode(unsigned, unsigned);
556 void ClumpAddressTaken();
557 void RewriteConstraints();
558 void HU();
559 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000560 void HCD();
561 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000562 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000563 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000564 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000565 void Condense(unsigned Node);
566 void HUValNum(unsigned Node);
567 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000568 unsigned getNodeForConstantPointer(Constant *C);
569 unsigned getNodeForConstantPointerTarget(Constant *C);
570 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000571
Chris Lattnere995a2a2004-05-23 21:00:47 +0000572 void AddConstraintsForNonInternalLinkage(Function *F);
573 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000574 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000575
576
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000577 void PrintNode(const Node *N) const;
578 void PrintConstraints() const ;
579 void PrintConstraint(const Constraint &) const;
580 void PrintLabels() const;
581 void PrintPointsToGraph() const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000582
583 //===------------------------------------------------------------------===//
584 // Instruction visitation methods for adding constraints
585 //
586 friend class InstVisitor<Andersens>;
587 void visitReturnInst(ReturnInst &RI);
588 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
589 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
590 void visitCallSite(CallSite CS);
591 void visitAllocationInst(AllocationInst &AI);
592 void visitLoadInst(LoadInst &LI);
593 void visitStoreInst(StoreInst &SI);
594 void visitGetElementPtrInst(GetElementPtrInst &GEP);
595 void visitPHINode(PHINode &PN);
596 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000597 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
598 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000599 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000600 void visitVAArg(VAArgInst &I);
601 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000602
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000603 //===------------------------------------------------------------------===//
604 // Implement Analyize interface
605 //
606 void print(std::ostream &O, const Module* M) const {
607 PrintPointsToGraph();
608 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000609 };
610
Devang Patel19974732007-05-03 01:11:54 +0000611 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000612 RegisterPass<Andersens> X("anders-aa",
Devang Patel4f4c28f2008-03-20 02:25:21 +0000613 "Andersen's Interprocedural Alias Analysis", false,
Devang Patelc7582092008-03-19 21:56:59 +0000614 true);
Chris Lattnera5370172006-08-28 00:42:29 +0000615 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000616
617 // Initialize Timestamp Counter (static).
618 unsigned Andersens::Node::Counter = 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000619}
620
Jeff Cohen534927d2005-01-08 22:01:16 +0000621ModulePass *llvm::createAndersensPass() { return new Andersens(); }
622
Chris Lattnere995a2a2004-05-23 21:00:47 +0000623//===----------------------------------------------------------------------===//
624// AliasAnalysis Interface Implementation
625//===----------------------------------------------------------------------===//
626
627AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
628 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000629 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
630 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000631
632 // Check to see if the two pointers are known to not alias. They don't alias
633 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000634 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000635 return NoAlias;
636
637 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
638}
639
Chris Lattnerf392c642005-03-28 06:21:17 +0000640AliasAnalysis::ModRefResult
641Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
642 // The only thing useful that we can contribute for mod/ref information is
643 // when calling external function calls: if we know that memory never escapes
644 // from the program, it cannot be modified by an external call.
645 //
646 // NOTE: This is not really safe, at least not when the entire program is not
647 // available. The deal is that the external function could call back into the
648 // program and modify stuff. We ignore this technical niggle for now. This
649 // is, after all, a "research quality" implementation of Andersen's analysis.
650 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000651 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000652 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000653
Daniel Berlinaad15882007-09-16 21:45:02 +0000654 if (N1->PointsTo->empty())
655 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000656#if FULL_UNIVERSAL
657 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
658 return NoModRef; // Universal set does not contain P
659#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000660 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000661 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000662#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000663 }
664
665 return AliasAnalysis::getModRefInfo(CS, P, Size);
666}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000667
Reid Spencer3a9ec242006-08-28 01:02:49 +0000668AliasAnalysis::ModRefResult
669Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
670 return AliasAnalysis::getModRefInfo(CS1,CS2);
671}
672
Chris Lattnere995a2a2004-05-23 21:00:47 +0000673/// getMustAlias - We can provide must alias information if we know that a
674/// pointer can only point to a specific function or the null pointer.
675/// Unfortunately we cannot determine must-alias information for global
676/// variables or any other memory memory objects because we do not track whether
677/// a pointer points to the beginning of an object or a field of it.
678void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000679 Node *N = &GraphNodes[FindNode(getNode(P))];
680 if (N->PointsTo->count() == 1) {
681 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
682 // If a function is the only object in the points-to set, then it must be
683 // the destination. Note that we can't handle global variables here,
684 // because we don't know if the pointer is actually pointing to a field of
685 // the global or to the beginning of it.
686 if (Value *V = Pointee->getValue()) {
687 if (Function *F = dyn_cast<Function>(V))
688 RetVals.push_back(F);
689 } else {
690 // If the object in the points-to set is the null object, then the null
691 // pointer is a must alias.
692 if (Pointee == &GraphNodes[NullObject])
693 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000694 }
695 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000696 AliasAnalysis::getMustAliases(P, RetVals);
697}
698
699/// pointsToConstantMemory - If we can determine that this pointer only points
700/// to constant memory, return true. In practice, this means that if the
701/// pointer can only point to constant globals, functions, or the null pointer,
702/// return true.
703///
704bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000705 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000706 unsigned i;
707
708 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
709 bi != N->PointsTo->end();
710 ++bi) {
711 i = *bi;
712 Node *Pointee = &GraphNodes[i];
713 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000714 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
715 !cast<GlobalVariable>(V)->isConstant()))
716 return AliasAnalysis::pointsToConstantMemory(P);
717 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000718 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000719 return AliasAnalysis::pointsToConstantMemory(P);
720 }
721 }
722
723 return true;
724}
725
726//===----------------------------------------------------------------------===//
727// Object Identification Phase
728//===----------------------------------------------------------------------===//
729
730/// IdentifyObjects - This stage scans the program, adding an entry to the
731/// GraphNodes list for each memory object in the program (global stack or
732/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
733///
734void Andersens::IdentifyObjects(Module &M) {
735 unsigned NumObjects = 0;
736
737 // Object #0 is always the universal set: the object that we don't know
738 // anything about.
739 assert(NumObjects == UniversalSet && "Something changed!");
740 ++NumObjects;
741
742 // Object #1 always represents the null pointer.
743 assert(NumObjects == NullPtr && "Something changed!");
744 ++NumObjects;
745
746 // Object #2 always represents the null object (the object pointed to by null)
747 assert(NumObjects == NullObject && "Something changed!");
748 ++NumObjects;
749
750 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000751 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
752 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000753 ObjectNodes[I] = NumObjects++;
754 ValueNodes[I] = NumObjects++;
755 }
756
757 // Add nodes for all of the functions and the instructions inside of them.
758 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
759 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000760 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000761 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000762 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
763 ReturnNodes[F] = NumObjects++;
764 if (F->getFunctionType()->isVarArg())
765 VarargNodes[F] = NumObjects++;
766
Daniel Berlinaad15882007-09-16 21:45:02 +0000767
Chris Lattnere995a2a2004-05-23 21:00:47 +0000768 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000769 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
770 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000771 {
772 if (isa<PointerType>(I->getType()))
773 ValueNodes[I] = NumObjects++;
774 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000775 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000776
777 // Scan the function body, creating a memory object for each heap/stack
778 // allocation in the body of the function and a node to represent all
779 // pointer values defined by instructions and used as operands.
780 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
781 // If this is an heap or stack allocation, create a node for the memory
782 // object.
783 if (isa<PointerType>(II->getType())) {
784 ValueNodes[&*II] = NumObjects++;
785 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
786 ObjectNodes[AI] = NumObjects++;
787 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000788
789 // Calls to inline asm need to be added as well because the callee isn't
790 // referenced anywhere else.
791 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
792 Value *Callee = CI->getCalledValue();
793 if (isa<InlineAsm>(Callee))
794 ValueNodes[Callee] = NumObjects++;
795 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000796 }
797 }
798
799 // Now that we know how many objects to create, make them all now!
800 GraphNodes.resize(NumObjects);
801 NumNodes += NumObjects;
802}
803
804//===----------------------------------------------------------------------===//
805// Constraint Identification Phase
806//===----------------------------------------------------------------------===//
807
808/// getNodeForConstantPointer - Return the node corresponding to the constant
809/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000810unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000811 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
812
Chris Lattner267a1b02005-03-27 18:58:23 +0000813 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000814 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000815 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
816 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000817 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
818 switch (CE->getOpcode()) {
819 case Instruction::GetElementPtr:
820 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000821 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000822 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000823 case Instruction::BitCast:
824 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000825 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000826 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000827 assert(0);
828 }
829 } else {
830 assert(0 && "Unknown constant pointer!");
831 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000832 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000833}
834
835/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
836/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000837unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000838 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
839
840 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000841 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000842 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
843 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000844 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
845 switch (CE->getOpcode()) {
846 case Instruction::GetElementPtr:
847 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000848 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000849 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000850 case Instruction::BitCast:
851 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000852 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000853 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000854 assert(0);
855 }
856 } else {
857 assert(0 && "Unknown constant pointer!");
858 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000859 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000860}
861
862/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
863/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000864void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
865 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000866 if (C->getType()->isFirstClassType()) {
867 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000868 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
869 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000870 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000871 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
872 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000873 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000874 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000875 // If this is an array or struct, include constraints for each element.
876 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
877 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000878 AddGlobalInitializerConstraints(NodeIndex,
879 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000880 }
881}
882
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000883/// AddConstraintsForNonInternalLinkage - If this function does not have
884/// internal linkage, realize that we can't trust anything passed into or
885/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000886void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000887 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000888 if (isa<PointerType>(I->getType()))
889 // If this is an argument of an externally accessible function, the
890 // incoming pointer might point to anything.
891 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000892 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000893}
894
Chris Lattner8a446432005-03-29 06:09:07 +0000895/// AddConstraintsForCall - If this is a call to a "known" function, add the
896/// constraints and return true. If this is a call to an unknown function,
897/// return false.
898bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000899 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000900
901 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000902 if (F->getName() == "atoi" || F->getName() == "atof" ||
903 F->getName() == "atol" || F->getName() == "atoll" ||
904 F->getName() == "remove" || F->getName() == "unlink" ||
905 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000906 F->getName() == "llvm.memset.i32" ||
907 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000908 F->getName() == "strcmp" || F->getName() == "strncmp" ||
909 F->getName() == "execl" || F->getName() == "execlp" ||
910 F->getName() == "execle" || F->getName() == "execv" ||
911 F->getName() == "execvp" || F->getName() == "chmod" ||
912 F->getName() == "puts" || F->getName() == "write" ||
913 F->getName() == "open" || F->getName() == "create" ||
914 F->getName() == "truncate" || F->getName() == "chdir" ||
915 F->getName() == "mkdir" || F->getName() == "rmdir" ||
916 F->getName() == "read" || F->getName() == "pipe" ||
917 F->getName() == "wait" || F->getName() == "time" ||
918 F->getName() == "stat" || F->getName() == "fstat" ||
919 F->getName() == "lstat" || F->getName() == "strtod" ||
920 F->getName() == "strtof" || F->getName() == "strtold" ||
921 F->getName() == "fopen" || F->getName() == "fdopen" ||
922 F->getName() == "freopen" ||
923 F->getName() == "fflush" || F->getName() == "feof" ||
924 F->getName() == "fileno" || F->getName() == "clearerr" ||
925 F->getName() == "rewind" || F->getName() == "ftell" ||
926 F->getName() == "ferror" || F->getName() == "fgetc" ||
927 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
928 F->getName() == "fwrite" || F->getName() == "fread" ||
929 F->getName() == "fgets" || F->getName() == "ungetc" ||
930 F->getName() == "fputc" ||
931 F->getName() == "fputs" || F->getName() == "putc" ||
932 F->getName() == "ftell" || F->getName() == "rewind" ||
933 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
934 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
935 F->getName() == "printf" || F->getName() == "fprintf" ||
936 F->getName() == "sprintf" || F->getName() == "vprintf" ||
937 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
938 F->getName() == "scanf" || F->getName() == "fscanf" ||
939 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
940 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000941 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000942
Chris Lattner175b9632005-03-29 20:36:05 +0000943
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000944 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000945 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000946 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000947 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000948
949 // *Dest = *Src, which requires an artificial graph node to represent the
950 // constraint. It is broken up into *Dest = temp, temp = *Src
951 unsigned FirstArg = getNode(CS.getArgument(0));
952 unsigned SecondArg = getNode(CS.getArgument(1));
953 unsigned TempArg = GraphNodes.size();
954 GraphNodes.push_back(Node());
955 Constraints.push_back(Constraint(Constraint::Store,
956 FirstArg, TempArg));
957 Constraints.push_back(Constraint(Constraint::Load,
958 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000959 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000960 }
961
Chris Lattner77b50562005-03-29 20:04:24 +0000962 // Result = Arg0
963 if (F->getName() == "realloc" || F->getName() == "strchr" ||
964 F->getName() == "strrchr" || F->getName() == "strstr" ||
965 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000966 Constraints.push_back(Constraint(Constraint::Copy,
967 getNode(CS.getInstruction()),
968 getNode(CS.getArgument(0))));
969 return true;
970 }
971
972 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000973}
974
975
Chris Lattnere995a2a2004-05-23 21:00:47 +0000976
Daniel Berlinaad15882007-09-16 21:45:02 +0000977/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
978/// If this is used by anything complex (i.e., the address escapes), return
979/// true.
980bool Andersens::AnalyzeUsesOfFunction(Value *V) {
981
982 if (!isa<PointerType>(V->getType())) return true;
983
984 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
985 if (dyn_cast<LoadInst>(*UI)) {
986 return false;
987 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
988 if (V == SI->getOperand(1)) {
989 return false;
990 } else if (SI->getOperand(1)) {
991 return true; // Storing the pointer
992 }
993 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
994 if (AnalyzeUsesOfFunction(GEP)) return true;
995 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
996 // Make sure that this is just the function being called, not that it is
997 // passing into the function.
998 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
999 if (CI->getOperand(i) == V) return true;
1000 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1001 // Make sure that this is just the function being called, not that it is
1002 // passing into the function.
1003 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
1004 if (II->getOperand(i) == V) return true;
1005 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1006 if (CE->getOpcode() == Instruction::GetElementPtr ||
1007 CE->getOpcode() == Instruction::BitCast) {
1008 if (AnalyzeUsesOfFunction(CE))
1009 return true;
1010 } else {
1011 return true;
1012 }
1013 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1014 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1015 return true; // Allow comparison against null.
1016 } else if (dyn_cast<FreeInst>(*UI)) {
1017 return false;
1018 } else {
1019 return true;
1020 }
1021 return false;
1022}
1023
Chris Lattnere995a2a2004-05-23 21:00:47 +00001024/// CollectConstraints - This stage scans the program, adding a constraint to
1025/// the Constraints list for each instruction in the program that induces a
1026/// constraint, and setting up the initial points-to graph.
1027///
1028void Andersens::CollectConstraints(Module &M) {
1029 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001030 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1031 UniversalSet));
1032 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1033 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001034
1035 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001036 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001037
1038 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001039 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1040 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001041 // Associate the address of the global object as pointing to the memory for
1042 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001043 unsigned ObjectIndex = getObject(I);
1044 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001045 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001046 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1047 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001048
1049 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001050 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001051 } else {
1052 // If it doesn't have an initializer (i.e. it's defined in another
1053 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001054 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1055 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001056 }
1057 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001058
Chris Lattnere995a2a2004-05-23 21:00:47 +00001059 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001060 // Set up the return value node.
1061 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001062 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001063 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001064 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001065
1066 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001067 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1068 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001069 if (isa<PointerType>(I->getType()))
1070 getNodeValue(*I);
1071
Daniel Berlinaad15882007-09-16 21:45:02 +00001072 // At some point we should just add constraints for the escaping functions
1073 // at solve time, but this slows down solving. For now, we simply mark
1074 // address taken functions as escaping and treat them as external.
1075 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001076 AddConstraintsForNonInternalLinkage(F);
1077
Reid Spencer5cbf9852007-01-30 20:08:39 +00001078 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001079 // Scan the function body, creating a memory object for each heap/stack
1080 // allocation in the body of the function and a node to represent all
1081 // pointer values defined by instructions and used as operands.
1082 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001083 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001084 // External functions that return pointers return the universal set.
1085 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1086 Constraints.push_back(Constraint(Constraint::Copy,
1087 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001088 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001089
1090 // Any pointers that are passed into the function have the universal set
1091 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001092 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1093 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001094 if (isa<PointerType>(I->getType())) {
1095 // Pointers passed into external functions could have anything stored
1096 // through them.
1097 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001098 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001099 // Memory objects passed into external function calls can have the
1100 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001101#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001102 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001103 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001104 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001105#else
1106 Constraints.push_back(Constraint(Constraint::Copy,
1107 getNode(I),
1108 UniversalSet));
1109#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001110 }
1111
1112 // If this is an external varargs function, it can also store pointers
1113 // into any pointers passed through the varargs section.
1114 if (F->getFunctionType()->isVarArg())
1115 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001116 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001117 }
1118 }
1119 NumConstraints += Constraints.size();
1120}
1121
1122
1123void Andersens::visitInstruction(Instruction &I) {
1124#ifdef NDEBUG
1125 return; // This function is just a big assert.
1126#endif
1127 if (isa<BinaryOperator>(I))
1128 return;
1129 // Most instructions don't have any effect on pointer values.
1130 switch (I.getOpcode()) {
1131 case Instruction::Br:
1132 case Instruction::Switch:
1133 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001134 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001135 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001136 case Instruction::ICmp:
1137 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001138 return;
1139 default:
1140 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001141 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001142 abort();
1143 }
1144}
1145
1146void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001147 unsigned ObjectIndex = getObject(&AI);
1148 GraphNodes[ObjectIndex].setValue(&AI);
1149 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1150 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001151}
1152
1153void Andersens::visitReturnInst(ReturnInst &RI) {
1154 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1155 // return V --> <Copy/retval{F}/v>
1156 Constraints.push_back(Constraint(Constraint::Copy,
1157 getReturnNode(RI.getParent()->getParent()),
1158 getNode(RI.getOperand(0))));
1159}
1160
1161void Andersens::visitLoadInst(LoadInst &LI) {
1162 if (isa<PointerType>(LI.getType()))
1163 // P1 = load P2 --> <Load/P1/P2>
1164 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1165 getNode(LI.getOperand(0))));
1166}
1167
1168void Andersens::visitStoreInst(StoreInst &SI) {
1169 if (isa<PointerType>(SI.getOperand(0)->getType()))
1170 // store P1, P2 --> <Store/P2/P1>
1171 Constraints.push_back(Constraint(Constraint::Store,
1172 getNode(SI.getOperand(1)),
1173 getNode(SI.getOperand(0))));
1174}
1175
1176void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1177 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1178 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1179 getNode(GEP.getOperand(0))));
1180}
1181
1182void Andersens::visitPHINode(PHINode &PN) {
1183 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001184 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001185 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1186 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1187 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1188 getNode(PN.getIncomingValue(i))));
1189 }
1190}
1191
1192void Andersens::visitCastInst(CastInst &CI) {
1193 Value *Op = CI.getOperand(0);
1194 if (isa<PointerType>(CI.getType())) {
1195 if (isa<PointerType>(Op->getType())) {
1196 // P1 = cast P2 --> <Copy/P1/P2>
1197 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1198 getNode(CI.getOperand(0))));
1199 } else {
1200 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001201#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001202 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001203 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001204#else
1205 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001206#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001207 }
1208 } else if (isa<PointerType>(Op->getType())) {
1209 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001210#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001211 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001212 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001213 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001214#else
1215 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001216#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001217 }
1218}
1219
1220void Andersens::visitSelectInst(SelectInst &SI) {
1221 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001222 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001223 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1224 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1225 getNode(SI.getOperand(1))));
1226 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1227 getNode(SI.getOperand(2))));
1228 }
1229}
1230
Chris Lattnere995a2a2004-05-23 21:00:47 +00001231void Andersens::visitVAArg(VAArgInst &I) {
1232 assert(0 && "vaarg not handled yet!");
1233}
1234
1235/// AddConstraintsForCall - Add constraints for a call with actual arguments
1236/// specified by CS to the function specified by F. Note that the types of
1237/// arguments might not match up in the case where this is an indirect call and
1238/// the function pointer has been casted. If this is the case, do something
1239/// reasonable.
1240void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001241 Value *CallValue = CS.getCalledValue();
1242 bool IsDeref = F == NULL;
1243
1244 // If this is a call to an external function, try to handle it directly to get
1245 // some taste of context sensitivity.
1246 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001247 return;
1248
Chris Lattnere995a2a2004-05-23 21:00:47 +00001249 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001250 unsigned CSN = getNode(CS.getInstruction());
1251 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1252 if (IsDeref)
1253 Constraints.push_back(Constraint(Constraint::Load, CSN,
1254 getNode(CallValue), CallReturnPos));
1255 else
1256 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1257 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001258 } else {
1259 // If the function returns a non-pointer value, handle this just like we
1260 // treat a nonpointer cast to pointer.
1261 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001262 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001263 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001264 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001265#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001266 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001267 UniversalSet,
1268 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001269#else
1270 Constraints.push_back(Constraint(Constraint::Copy,
1271 getNode(CallValue) + CallReturnPos,
1272 UniversalSet));
1273#endif
1274
1275
Chris Lattnere995a2a2004-05-23 21:00:47 +00001276 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001277
Chris Lattnere995a2a2004-05-23 21:00:47 +00001278 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001279 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001280 if (F) {
1281 // Direct Call
1282 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001283 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1284 {
1285#if !FULL_UNIVERSAL
1286 if (external && isa<PointerType>((*ArgI)->getType()))
1287 {
1288 // Add constraint that ArgI can now point to anything due to
1289 // escaping, as can everything it points to. The second portion of
1290 // this should be taken care of by universal = *universal
1291 Constraints.push_back(Constraint(Constraint::Copy,
1292 getNode(*ArgI),
1293 UniversalSet));
1294 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001295#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001296 if (isa<PointerType>(AI->getType())) {
1297 if (isa<PointerType>((*ArgI)->getType())) {
1298 // Copy the actual argument into the formal argument.
1299 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1300 getNode(*ArgI)));
1301 } else {
1302 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1303 UniversalSet));
1304 }
1305 } else if (isa<PointerType>((*ArgI)->getType())) {
1306#if FULL_UNIVERSAL
1307 Constraints.push_back(Constraint(Constraint::Copy,
1308 UniversalSet,
1309 getNode(*ArgI)));
1310#else
1311 Constraints.push_back(Constraint(Constraint::Copy,
1312 getNode(*ArgI),
1313 UniversalSet));
1314#endif
1315 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001316 }
1317 } else {
1318 //Indirect Call
1319 unsigned ArgPos = CallFirstArgPos;
1320 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001321 if (isa<PointerType>((*ArgI)->getType())) {
1322 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001323 Constraints.push_back(Constraint(Constraint::Store,
1324 getNode(CallValue),
1325 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001326 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001327 Constraints.push_back(Constraint(Constraint::Store,
1328 getNode (CallValue),
1329 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001330 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001331 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001332 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001333 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001334 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001335 for (; ArgI != ArgE; ++ArgI)
1336 if (isa<PointerType>((*ArgI)->getType()))
1337 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1338 getNode(*ArgI)));
1339 // If more arguments are passed in than we track, just drop them on the floor.
1340}
1341
1342void Andersens::visitCallSite(CallSite CS) {
1343 if (isa<PointerType>(CS.getType()))
1344 getNodeValue(*CS.getInstruction());
1345
1346 if (Function *F = CS.getCalledFunction()) {
1347 AddConstraintsForCall(CS, F);
1348 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001349 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001350 }
1351}
1352
1353//===----------------------------------------------------------------------===//
1354// Constraint Solving Phase
1355//===----------------------------------------------------------------------===//
1356
1357/// intersects - Return true if the points-to set of this node intersects
1358/// with the points-to set of the specified node.
1359bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001360 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001361}
1362
1363/// intersectsIgnoring - Return true if the points-to set of this node
1364/// intersects with the points-to set of the specified node on any nodes
1365/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001366bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1367 // TODO: If we are only going to call this with the same value for Ignoring,
1368 // we should move the special values out of the points-to bitmap.
1369 bool WeHadIt = PointsTo->test(Ignoring);
1370 bool NHadIt = N->PointsTo->test(Ignoring);
1371 bool Result = false;
1372 if (WeHadIt)
1373 PointsTo->reset(Ignoring);
1374 if (NHadIt)
1375 N->PointsTo->reset(Ignoring);
1376 Result = PointsTo->intersects(N->PointsTo);
1377 if (WeHadIt)
1378 PointsTo->set(Ignoring);
1379 if (NHadIt)
1380 N->PointsTo->set(Ignoring);
1381 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001382}
1383
Daniel Berlind81ccc22007-09-24 19:45:49 +00001384void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001385#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001386 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001387#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001388}
1389
1390
1391/// Clump together address taken variables so that the points-to sets use up
1392/// less space and can be operated on faster.
1393
1394void Andersens::ClumpAddressTaken() {
1395#undef DEBUG_TYPE
1396#define DEBUG_TYPE "anders-aa-renumber"
1397 std::vector<unsigned> Translate;
1398 std::vector<Node> NewGraphNodes;
1399
1400 Translate.resize(GraphNodes.size());
1401 unsigned NewPos = 0;
1402
1403 for (unsigned i = 0; i < Constraints.size(); ++i) {
1404 Constraint &C = Constraints[i];
1405 if (C.Type == Constraint::AddressOf) {
1406 GraphNodes[C.Src].AddressTaken = true;
1407 }
1408 }
1409 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1410 unsigned Pos = NewPos++;
1411 Translate[i] = Pos;
1412 NewGraphNodes.push_back(GraphNodes[i]);
1413 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1414 }
1415
1416 // I believe this ends up being faster than making two vectors and splicing
1417 // them.
1418 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1419 if (GraphNodes[i].AddressTaken) {
1420 unsigned Pos = NewPos++;
1421 Translate[i] = Pos;
1422 NewGraphNodes.push_back(GraphNodes[i]);
1423 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1424 }
1425 }
1426
1427 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1428 if (!GraphNodes[i].AddressTaken) {
1429 unsigned Pos = NewPos++;
1430 Translate[i] = Pos;
1431 NewGraphNodes.push_back(GraphNodes[i]);
1432 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1433 }
1434 }
1435
1436 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1437 Iter != ValueNodes.end();
1438 ++Iter)
1439 Iter->second = Translate[Iter->second];
1440
1441 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1442 Iter != ObjectNodes.end();
1443 ++Iter)
1444 Iter->second = Translate[Iter->second];
1445
1446 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1447 Iter != ReturnNodes.end();
1448 ++Iter)
1449 Iter->second = Translate[Iter->second];
1450
1451 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1452 Iter != VarargNodes.end();
1453 ++Iter)
1454 Iter->second = Translate[Iter->second];
1455
1456 for (unsigned i = 0; i < Constraints.size(); ++i) {
1457 Constraint &C = Constraints[i];
1458 C.Src = Translate[C.Src];
1459 C.Dest = Translate[C.Dest];
1460 }
1461
1462 GraphNodes.swap(NewGraphNodes);
1463#undef DEBUG_TYPE
1464#define DEBUG_TYPE "anders-aa"
1465}
1466
1467/// The technique used here is described in "Exploiting Pointer and Location
1468/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1469/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1470/// and is equivalent to value numbering the collapsed constraint graph without
1471/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1472/// first order pointer dereferences and speed up/reduce memory usage of HU.
1473/// Running both is equivalent to HRU without the iteration
1474/// HVN in more detail:
1475/// Imagine the set of constraints was simply straight line code with no loops
1476/// (we eliminate cycles, so there are no loops), such as:
1477/// E = &D
1478/// E = &C
1479/// E = F
1480/// F = G
1481/// G = F
1482/// Applying value numbering to this code tells us:
1483/// G == F == E
1484///
1485/// For HVN, this is as far as it goes. We assign new value numbers to every
1486/// "address node", and every "reference node".
1487/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1488/// cycle must have the same value number since the = operation is really
1489/// inclusion, not overwrite), and value number nodes we receive points-to sets
1490/// before we value our own node.
1491/// The advantage of HU over HVN is that HU considers the inclusion property, so
1492/// that if you have
1493/// E = &D
1494/// E = &C
1495/// E = F
1496/// F = G
1497/// F = &D
1498/// G = F
1499/// HU will determine that G == F == E. HVN will not, because it cannot prove
1500/// that the points to information ends up being the same because they all
1501/// receive &D from E anyway.
1502
1503void Andersens::HVN() {
1504 DOUT << "Beginning HVN\n";
1505 // Build a predecessor graph. This is like our constraint graph with the
1506 // edges going in the opposite direction, and there are edges for all the
1507 // constraints, instead of just copy constraints. We also build implicit
1508 // edges for constraints are implied but not explicit. I.E for the constraint
1509 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1510 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1511 Constraint &C = Constraints[i];
1512 if (C.Type == Constraint::AddressOf) {
1513 GraphNodes[C.Src].AddressTaken = true;
1514 GraphNodes[C.Src].Direct = false;
1515
1516 // Dest = &src edge
1517 unsigned AdrNode = C.Src + FirstAdrNode;
1518 if (!GraphNodes[C.Dest].PredEdges)
1519 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1520 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1521
1522 // *Dest = src edge
1523 unsigned RefNode = C.Dest + FirstRefNode;
1524 if (!GraphNodes[RefNode].ImplicitPredEdges)
1525 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1526 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1527 } else if (C.Type == Constraint::Load) {
1528 if (C.Offset == 0) {
1529 // dest = *src edge
1530 if (!GraphNodes[C.Dest].PredEdges)
1531 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1532 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1533 } else {
1534 GraphNodes[C.Dest].Direct = false;
1535 }
1536 } else if (C.Type == Constraint::Store) {
1537 if (C.Offset == 0) {
1538 // *dest = src edge
1539 unsigned RefNode = C.Dest + FirstRefNode;
1540 if (!GraphNodes[RefNode].PredEdges)
1541 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1542 GraphNodes[RefNode].PredEdges->set(C.Src);
1543 }
1544 } else {
1545 // Dest = Src edge and *Dest = *Src edge
1546 if (!GraphNodes[C.Dest].PredEdges)
1547 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1548 GraphNodes[C.Dest].PredEdges->set(C.Src);
1549 unsigned RefNode = C.Dest + FirstRefNode;
1550 if (!GraphNodes[RefNode].ImplicitPredEdges)
1551 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1552 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1553 }
1554 }
1555 PEClass = 1;
1556 // Do SCC finding first to condense our predecessor graph
1557 DFSNumber = 0;
1558 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1559 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1560 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1561
1562 for (unsigned i = 0; i < FirstRefNode; ++i) {
1563 unsigned Node = VSSCCRep[i];
1564 if (!Node2Visited[Node])
1565 HVNValNum(Node);
1566 }
1567 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1568 Iter != Set2PEClass.end();
1569 ++Iter)
1570 delete Iter->first;
1571 Set2PEClass.clear();
1572 Node2DFS.clear();
1573 Node2Deleted.clear();
1574 Node2Visited.clear();
1575 DOUT << "Finished HVN\n";
1576
1577}
1578
1579/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1580/// same time because it's easy.
1581void Andersens::HVNValNum(unsigned NodeIndex) {
1582 unsigned MyDFS = DFSNumber++;
1583 Node *N = &GraphNodes[NodeIndex];
1584 Node2Visited[NodeIndex] = true;
1585 Node2DFS[NodeIndex] = MyDFS;
1586
1587 // First process all our explicit edges
1588 if (N->PredEdges)
1589 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1590 Iter != N->PredEdges->end();
1591 ++Iter) {
1592 unsigned j = VSSCCRep[*Iter];
1593 if (!Node2Deleted[j]) {
1594 if (!Node2Visited[j])
1595 HVNValNum(j);
1596 if (Node2DFS[NodeIndex] > Node2DFS[j])
1597 Node2DFS[NodeIndex] = Node2DFS[j];
1598 }
1599 }
1600
1601 // Now process all the implicit edges
1602 if (N->ImplicitPredEdges)
1603 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1604 Iter != N->ImplicitPredEdges->end();
1605 ++Iter) {
1606 unsigned j = VSSCCRep[*Iter];
1607 if (!Node2Deleted[j]) {
1608 if (!Node2Visited[j])
1609 HVNValNum(j);
1610 if (Node2DFS[NodeIndex] > Node2DFS[j])
1611 Node2DFS[NodeIndex] = Node2DFS[j];
1612 }
1613 }
1614
1615 // See if we found any cycles
1616 if (MyDFS == Node2DFS[NodeIndex]) {
1617 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1618 unsigned CycleNodeIndex = SCCStack.top();
1619 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1620 VSSCCRep[CycleNodeIndex] = NodeIndex;
1621 // Unify the nodes
1622 N->Direct &= CycleNode->Direct;
1623
1624 if (CycleNode->PredEdges) {
1625 if (!N->PredEdges)
1626 N->PredEdges = new SparseBitVector<>;
1627 *(N->PredEdges) |= CycleNode->PredEdges;
1628 delete CycleNode->PredEdges;
1629 CycleNode->PredEdges = NULL;
1630 }
1631 if (CycleNode->ImplicitPredEdges) {
1632 if (!N->ImplicitPredEdges)
1633 N->ImplicitPredEdges = new SparseBitVector<>;
1634 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1635 delete CycleNode->ImplicitPredEdges;
1636 CycleNode->ImplicitPredEdges = NULL;
1637 }
1638
1639 SCCStack.pop();
1640 }
1641
1642 Node2Deleted[NodeIndex] = true;
1643
1644 if (!N->Direct) {
1645 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1646 return;
1647 }
1648
1649 // Collect labels of successor nodes
1650 bool AllSame = true;
1651 unsigned First = ~0;
1652 SparseBitVector<> *Labels = new SparseBitVector<>;
1653 bool Used = false;
1654
1655 if (N->PredEdges)
1656 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1657 Iter != N->PredEdges->end();
1658 ++Iter) {
1659 unsigned j = VSSCCRep[*Iter];
1660 unsigned Label = GraphNodes[j].PointerEquivLabel;
1661 // Ignore labels that are equal to us or non-pointers
1662 if (j == NodeIndex || Label == 0)
1663 continue;
1664 if (First == (unsigned)~0)
1665 First = Label;
1666 else if (First != Label)
1667 AllSame = false;
1668 Labels->set(Label);
1669 }
1670
1671 // We either have a non-pointer, a copy of an existing node, or a new node.
1672 // Assign the appropriate pointer equivalence label.
1673 if (Labels->empty()) {
1674 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1675 } else if (AllSame) {
1676 GraphNodes[NodeIndex].PointerEquivLabel = First;
1677 } else {
1678 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1679 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1680 unsigned EquivClass = PEClass++;
1681 Set2PEClass[Labels] = EquivClass;
1682 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1683 Used = true;
1684 }
1685 }
1686 if (!Used)
1687 delete Labels;
1688 } else {
1689 SCCStack.push(NodeIndex);
1690 }
1691}
1692
1693/// The technique used here is described in "Exploiting Pointer and Location
1694/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1695/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1696/// and is equivalent to value numbering the collapsed constraint graph
1697/// including evaluating unions.
1698void Andersens::HU() {
1699 DOUT << "Beginning HU\n";
1700 // Build a predecessor graph. This is like our constraint graph with the
1701 // edges going in the opposite direction, and there are edges for all the
1702 // constraints, instead of just copy constraints. We also build implicit
1703 // edges for constraints are implied but not explicit. I.E for the constraint
1704 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1705 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1706 Constraint &C = Constraints[i];
1707 if (C.Type == Constraint::AddressOf) {
1708 GraphNodes[C.Src].AddressTaken = true;
1709 GraphNodes[C.Src].Direct = false;
1710
1711 GraphNodes[C.Dest].PointsTo->set(C.Src);
1712 // *Dest = src edge
1713 unsigned RefNode = C.Dest + FirstRefNode;
1714 if (!GraphNodes[RefNode].ImplicitPredEdges)
1715 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1716 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1717 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1718 } else if (C.Type == Constraint::Load) {
1719 if (C.Offset == 0) {
1720 // dest = *src edge
1721 if (!GraphNodes[C.Dest].PredEdges)
1722 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1723 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1724 } else {
1725 GraphNodes[C.Dest].Direct = false;
1726 }
1727 } else if (C.Type == Constraint::Store) {
1728 if (C.Offset == 0) {
1729 // *dest = src edge
1730 unsigned RefNode = C.Dest + FirstRefNode;
1731 if (!GraphNodes[RefNode].PredEdges)
1732 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1733 GraphNodes[RefNode].PredEdges->set(C.Src);
1734 }
1735 } else {
1736 // Dest = Src edge and *Dest = *Src edg
1737 if (!GraphNodes[C.Dest].PredEdges)
1738 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1739 GraphNodes[C.Dest].PredEdges->set(C.Src);
1740 unsigned RefNode = C.Dest + FirstRefNode;
1741 if (!GraphNodes[RefNode].ImplicitPredEdges)
1742 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1743 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1744 }
1745 }
1746 PEClass = 1;
1747 // Do SCC finding first to condense our predecessor graph
1748 DFSNumber = 0;
1749 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1750 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1751 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1752
1753 for (unsigned i = 0; i < FirstRefNode; ++i) {
1754 if (FindNode(i) == i) {
1755 unsigned Node = VSSCCRep[i];
1756 if (!Node2Visited[Node])
1757 Condense(Node);
1758 }
1759 }
1760
1761 // Reset tables for actual labeling
1762 Node2DFS.clear();
1763 Node2Visited.clear();
1764 Node2Deleted.clear();
1765 // Pre-grow our densemap so that we don't get really bad behavior
1766 Set2PEClass.resize(GraphNodes.size());
1767
1768 // Visit the condensed graph and generate pointer equivalence labels.
1769 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1770 for (unsigned i = 0; i < FirstRefNode; ++i) {
1771 if (FindNode(i) == i) {
1772 unsigned Node = VSSCCRep[i];
1773 if (!Node2Visited[Node])
1774 HUValNum(Node);
1775 }
1776 }
1777 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1778 Set2PEClass.clear();
1779 DOUT << "Finished HU\n";
1780}
1781
1782
1783/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1784void Andersens::Condense(unsigned NodeIndex) {
1785 unsigned MyDFS = DFSNumber++;
1786 Node *N = &GraphNodes[NodeIndex];
1787 Node2Visited[NodeIndex] = true;
1788 Node2DFS[NodeIndex] = MyDFS;
1789
1790 // First process all our explicit edges
1791 if (N->PredEdges)
1792 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1793 Iter != N->PredEdges->end();
1794 ++Iter) {
1795 unsigned j = VSSCCRep[*Iter];
1796 if (!Node2Deleted[j]) {
1797 if (!Node2Visited[j])
1798 Condense(j);
1799 if (Node2DFS[NodeIndex] > Node2DFS[j])
1800 Node2DFS[NodeIndex] = Node2DFS[j];
1801 }
1802 }
1803
1804 // Now process all the implicit edges
1805 if (N->ImplicitPredEdges)
1806 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1807 Iter != N->ImplicitPredEdges->end();
1808 ++Iter) {
1809 unsigned j = VSSCCRep[*Iter];
1810 if (!Node2Deleted[j]) {
1811 if (!Node2Visited[j])
1812 Condense(j);
1813 if (Node2DFS[NodeIndex] > Node2DFS[j])
1814 Node2DFS[NodeIndex] = Node2DFS[j];
1815 }
1816 }
1817
1818 // See if we found any cycles
1819 if (MyDFS == Node2DFS[NodeIndex]) {
1820 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1821 unsigned CycleNodeIndex = SCCStack.top();
1822 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1823 VSSCCRep[CycleNodeIndex] = NodeIndex;
1824 // Unify the nodes
1825 N->Direct &= CycleNode->Direct;
1826
1827 *(N->PointsTo) |= CycleNode->PointsTo;
1828 delete CycleNode->PointsTo;
1829 CycleNode->PointsTo = NULL;
1830 if (CycleNode->PredEdges) {
1831 if (!N->PredEdges)
1832 N->PredEdges = new SparseBitVector<>;
1833 *(N->PredEdges) |= CycleNode->PredEdges;
1834 delete CycleNode->PredEdges;
1835 CycleNode->PredEdges = NULL;
1836 }
1837 if (CycleNode->ImplicitPredEdges) {
1838 if (!N->ImplicitPredEdges)
1839 N->ImplicitPredEdges = new SparseBitVector<>;
1840 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1841 delete CycleNode->ImplicitPredEdges;
1842 CycleNode->ImplicitPredEdges = NULL;
1843 }
1844 SCCStack.pop();
1845 }
1846
1847 Node2Deleted[NodeIndex] = true;
1848
1849 // Set up number of incoming edges for other nodes
1850 if (N->PredEdges)
1851 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1852 Iter != N->PredEdges->end();
1853 ++Iter)
1854 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1855 } else {
1856 SCCStack.push(NodeIndex);
1857 }
1858}
1859
1860void Andersens::HUValNum(unsigned NodeIndex) {
1861 Node *N = &GraphNodes[NodeIndex];
1862 Node2Visited[NodeIndex] = true;
1863
1864 // Eliminate dereferences of non-pointers for those non-pointers we have
1865 // already identified. These are ref nodes whose non-ref node:
1866 // 1. Has already been visited determined to point to nothing (and thus, a
1867 // dereference of it must point to nothing)
1868 // 2. Any direct node with no predecessor edges in our graph and with no
1869 // points-to set (since it can't point to anything either, being that it
1870 // receives no points-to sets and has none).
1871 if (NodeIndex >= FirstRefNode) {
1872 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1873 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1874 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1875 && GraphNodes[j].PointsTo->empty())){
1876 return;
1877 }
1878 }
1879 // Process all our explicit edges
1880 if (N->PredEdges)
1881 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1882 Iter != N->PredEdges->end();
1883 ++Iter) {
1884 unsigned j = VSSCCRep[*Iter];
1885 if (!Node2Visited[j])
1886 HUValNum(j);
1887
1888 // If this edge turned out to be the same as us, or got no pointer
1889 // equivalence label (and thus points to nothing) , just decrement our
1890 // incoming edges and continue.
1891 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1892 --GraphNodes[j].NumInEdges;
1893 continue;
1894 }
1895
1896 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1897
1898 // If we didn't end up storing this in the hash, and we're done with all
1899 // the edges, we don't need the points-to set anymore.
1900 --GraphNodes[j].NumInEdges;
1901 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1902 delete GraphNodes[j].PointsTo;
1903 GraphNodes[j].PointsTo = NULL;
1904 }
1905 }
1906 // If this isn't a direct node, generate a fresh variable.
1907 if (!N->Direct) {
1908 N->PointsTo->set(FirstRefNode + NodeIndex);
1909 }
1910
1911 // See If we have something equivalent to us, if not, generate a new
1912 // equivalence class.
1913 if (N->PointsTo->empty()) {
1914 delete N->PointsTo;
1915 N->PointsTo = NULL;
1916 } else {
1917 if (N->Direct) {
1918 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1919 if (N->PointerEquivLabel == 0) {
1920 unsigned EquivClass = PEClass++;
1921 N->StoredInHash = true;
1922 Set2PEClass[N->PointsTo] = EquivClass;
1923 N->PointerEquivLabel = EquivClass;
1924 }
1925 } else {
1926 N->PointerEquivLabel = PEClass++;
1927 }
1928 }
1929}
1930
1931/// Rewrite our list of constraints so that pointer equivalent nodes are
1932/// replaced by their the pointer equivalence class representative.
1933void Andersens::RewriteConstraints() {
1934 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001935 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001936
1937 PEClass2Node.clear();
1938 PENLEClass2Node.clear();
1939
1940 // We may have from 1 to Graphnodes + 1 equivalence classes.
1941 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1942 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1943
1944 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1945 // nodes, and rewriting constraints to use the representative nodes.
1946 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1947 Constraint &C = Constraints[i];
1948 unsigned RHSNode = FindNode(C.Src);
1949 unsigned LHSNode = FindNode(C.Dest);
1950 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1951 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1952
1953 // First we try to eliminate constraints for things we can prove don't point
1954 // to anything.
1955 if (LHSLabel == 0) {
1956 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1957 DOUT << " is a non-pointer, ignoring constraint.\n";
1958 continue;
1959 }
1960 if (RHSLabel == 0) {
1961 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1962 DOUT << " is a non-pointer, ignoring constraint.\n";
1963 continue;
1964 }
1965 // This constraint may be useless, and it may become useless as we translate
1966 // it.
1967 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1968 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001969
Daniel Berlind81ccc22007-09-24 19:45:49 +00001970 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1971 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001972 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001973 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001974 continue;
1975
Chris Lattnerbe207732007-09-30 00:47:20 +00001976 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001977 NewConstraints.push_back(C);
1978 }
1979 Constraints.swap(NewConstraints);
1980 PEClass2Node.clear();
1981}
1982
1983/// See if we have a node that is pointer equivalent to the one being asked
1984/// about, and if so, unite them and return the equivalent node. Otherwise,
1985/// return the original node.
1986unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1987 unsigned NodeLabel) {
1988 if (!GraphNodes[NodeIndex].AddressTaken) {
1989 if (PEClass2Node[NodeLabel] != -1) {
1990 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001991 // We specifically request that Union-By-Rank not be used so that
1992 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1993 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001994 } else {
1995 PEClass2Node[NodeLabel] = NodeIndex;
1996 PENLEClass2Node[NodeLabel] = NodeIndex;
1997 }
1998 } else if (PENLEClass2Node[NodeLabel] == -1) {
1999 PENLEClass2Node[NodeLabel] = NodeIndex;
2000 }
2001
2002 return NodeIndex;
2003}
2004
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002005void Andersens::PrintLabels() const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002006 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2007 if (i < FirstRefNode) {
2008 PrintNode(&GraphNodes[i]);
2009 } else if (i < FirstAdrNode) {
2010 DOUT << "REF(";
2011 PrintNode(&GraphNodes[i-FirstRefNode]);
2012 DOUT <<")";
2013 } else {
2014 DOUT << "ADR(";
2015 PrintNode(&GraphNodes[i-FirstAdrNode]);
2016 DOUT <<")";
2017 }
2018
2019 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2020 << " and SCC rep " << VSSCCRep[i]
2021 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2022 << "\n";
2023 }
2024}
2025
Daniel Berlinc864edb2008-03-05 19:31:47 +00002026/// The technique used here is described in "The Ant and the
2027/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2028/// Lines of Code. In Programming Language Design and Implementation
2029/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2030/// Detection) algorithm. It is called a hybrid because it performs an
2031/// offline analysis and uses its results during the solving (online)
2032/// phase. This is just the offline portion; the results of this
2033/// operation are stored in SDT and are later used in SolveContraints()
2034/// and UniteNodes().
2035void Andersens::HCD() {
2036 DOUT << "Starting HCD.\n";
2037 HCDSCCRep.resize(GraphNodes.size());
2038
2039 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2040 GraphNodes[i].Edges = new SparseBitVector<>;
2041 HCDSCCRep[i] = i;
2042 }
2043
2044 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2045 Constraint &C = Constraints[i];
2046 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2047 if (C.Type == Constraint::AddressOf) {
2048 continue;
2049 } else if (C.Type == Constraint::Load) {
2050 if( C.Offset == 0 )
2051 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2052 } else if (C.Type == Constraint::Store) {
2053 if( C.Offset == 0 )
2054 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2055 } else {
2056 GraphNodes[C.Dest].Edges->set(C.Src);
2057 }
2058 }
2059
2060 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2061 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2062 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2063 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2064
2065 DFSNumber = 0;
2066 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2067 unsigned Node = HCDSCCRep[i];
2068 if (!Node2Deleted[Node])
2069 Search(Node);
2070 }
2071
2072 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2073 if (GraphNodes[i].Edges != NULL) {
2074 delete GraphNodes[i].Edges;
2075 GraphNodes[i].Edges = NULL;
2076 }
2077
2078 while( !SCCStack.empty() )
2079 SCCStack.pop();
2080
2081 Node2DFS.clear();
2082 Node2Visited.clear();
2083 Node2Deleted.clear();
2084 HCDSCCRep.clear();
2085 DOUT << "HCD complete.\n";
2086}
2087
2088// Component of HCD:
2089// Use Nuutila's variant of Tarjan's algorithm to detect
2090// Strongly-Connected Components (SCCs). For non-trivial SCCs
2091// containing ref nodes, insert the appropriate information in SDT.
2092void Andersens::Search(unsigned Node) {
2093 unsigned MyDFS = DFSNumber++;
2094
2095 Node2Visited[Node] = true;
2096 Node2DFS[Node] = MyDFS;
2097
2098 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2099 End = GraphNodes[Node].Edges->end();
2100 Iter != End;
2101 ++Iter) {
2102 unsigned J = HCDSCCRep[*Iter];
2103 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2104 if (!Node2Deleted[J]) {
2105 if (!Node2Visited[J])
2106 Search(J);
2107 if (Node2DFS[Node] > Node2DFS[J])
2108 Node2DFS[Node] = Node2DFS[J];
2109 }
2110 }
2111
2112 if( MyDFS != Node2DFS[Node] ) {
2113 SCCStack.push(Node);
2114 return;
2115 }
2116
2117 // This node is the root of a SCC, so process it.
2118 //
2119 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2120 // node, we place this SCC into SDT. We unite the nodes in any case.
2121 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2122 SparseBitVector<> SCC;
2123
2124 SCC.set(Node);
2125
2126 bool Ref = (Node >= FirstRefNode);
2127
2128 Node2Deleted[Node] = true;
2129
2130 do {
2131 unsigned P = SCCStack.top(); SCCStack.pop();
2132 Ref |= (P >= FirstRefNode);
2133 SCC.set(P);
2134 HCDSCCRep[P] = Node;
2135 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2136
2137 if (Ref) {
2138 unsigned Rep = SCC.find_first();
2139 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2140
2141 SparseBitVector<>::iterator i = SCC.begin();
2142
2143 // Skip over the non-ref nodes
2144 while( *i < FirstRefNode )
2145 ++i;
2146
2147 while( i != SCC.end() )
2148 SDT[ (*i++) - FirstRefNode ] = Rep;
2149 }
2150 }
2151}
2152
2153
Daniel Berlind81ccc22007-09-24 19:45:49 +00002154/// Optimize the constraints by performing offline variable substitution and
2155/// other optimizations.
2156void Andersens::OptimizeConstraints() {
2157 DOUT << "Beginning constraint optimization\n";
2158
Daniel Berlinc864edb2008-03-05 19:31:47 +00002159 SDTActive = false;
2160
Daniel Berlind81ccc22007-09-24 19:45:49 +00002161 // Function related nodes need to stay in the same relative position and can't
2162 // be location equivalent.
2163 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2164 Iter != MaxK.end();
2165 ++Iter) {
2166 for (unsigned i = Iter->first;
2167 i != Iter->first + Iter->second;
2168 ++i) {
2169 GraphNodes[i].AddressTaken = true;
2170 GraphNodes[i].Direct = false;
2171 }
2172 }
2173
2174 ClumpAddressTaken();
2175 FirstRefNode = GraphNodes.size();
2176 FirstAdrNode = FirstRefNode + GraphNodes.size();
2177 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2178 Node(false));
2179 VSSCCRep.resize(GraphNodes.size());
2180 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2181 VSSCCRep[i] = i;
2182 }
2183 HVN();
2184 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2185 Node *N = &GraphNodes[i];
2186 delete N->PredEdges;
2187 N->PredEdges = NULL;
2188 delete N->ImplicitPredEdges;
2189 N->ImplicitPredEdges = NULL;
2190 }
2191#undef DEBUG_TYPE
2192#define DEBUG_TYPE "anders-aa-labels"
2193 DEBUG(PrintLabels());
2194#undef DEBUG_TYPE
2195#define DEBUG_TYPE "anders-aa"
2196 RewriteConstraints();
2197 // Delete the adr nodes.
2198 GraphNodes.resize(FirstRefNode * 2);
2199
2200 // Now perform HU
2201 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2202 Node *N = &GraphNodes[i];
2203 if (FindNode(i) == i) {
2204 N->PointsTo = new SparseBitVector<>;
2205 N->PointedToBy = new SparseBitVector<>;
2206 // Reset our labels
2207 }
2208 VSSCCRep[i] = i;
2209 N->PointerEquivLabel = 0;
2210 }
2211 HU();
2212#undef DEBUG_TYPE
2213#define DEBUG_TYPE "anders-aa-labels"
2214 DEBUG(PrintLabels());
2215#undef DEBUG_TYPE
2216#define DEBUG_TYPE "anders-aa"
2217 RewriteConstraints();
2218 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2219 if (FindNode(i) == i) {
2220 Node *N = &GraphNodes[i];
2221 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002222 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002223 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002224 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002225 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002226 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002227 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002228 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002229 }
2230 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002231
2232 // perform Hybrid Cycle Detection (HCD)
2233 HCD();
2234 SDTActive = true;
2235
2236 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002237 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002238
2239 // HCD complete.
2240
Daniel Berlind81ccc22007-09-24 19:45:49 +00002241 DOUT << "Finished constraint optimization\n";
2242 FirstRefNode = 0;
2243 FirstAdrNode = 0;
2244}
2245
2246/// Unite pointer but not location equivalent variables, now that the constraint
2247/// graph is built.
2248void Andersens::UnitePointerEquivalences() {
2249 DOUT << "Uniting remaining pointer equivalences\n";
2250 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002251 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002252 unsigned Label = GraphNodes[i].PointerEquivLabel;
2253
2254 if (Label && PENLEClass2Node[Label] != -1)
2255 UniteNodes(i, PENLEClass2Node[Label]);
2256 }
2257 }
2258 DOUT << "Finished remaining pointer equivalences\n";
2259 PENLEClass2Node.clear();
2260}
2261
2262/// Create the constraint graph used for solving points-to analysis.
2263///
Daniel Berlinaad15882007-09-16 21:45:02 +00002264void Andersens::CreateConstraintGraph() {
2265 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2266 Constraint &C = Constraints[i];
2267 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2268 if (C.Type == Constraint::AddressOf)
2269 GraphNodes[C.Dest].PointsTo->set(C.Src);
2270 else if (C.Type == Constraint::Load)
2271 GraphNodes[C.Src].Constraints.push_back(C);
2272 else if (C.Type == Constraint::Store)
2273 GraphNodes[C.Dest].Constraints.push_back(C);
2274 else if (C.Offset != 0)
2275 GraphNodes[C.Src].Constraints.push_back(C);
2276 else
2277 GraphNodes[C.Src].Edges->set(C.Dest);
2278 }
2279}
2280
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002281// Perform DFS and cycle detection.
2282bool Andersens::QueryNode(unsigned Node) {
2283 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002284 unsigned OurDFS = ++DFSNumber;
2285 SparseBitVector<> ToErase;
2286 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002287 Tarjan2DFS[Node] = OurDFS;
2288
2289 // Changed denotes a change from a recursive call that we will bubble up.
2290 // Merged is set if we actually merge a node ourselves.
2291 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002292
2293 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2294 bi != GraphNodes[Node].Edges->end();
2295 ++bi) {
2296 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002297 // If this edge points to a non-representative node but we are
2298 // already planning to add an edge to its representative, we have no
2299 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002300 if (RepNode != *bi && NewEdges.test(RepNode)){
2301 ToErase.set(*bi);
2302 continue;
2303 }
2304
2305 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002306 if (!Tarjan2Deleted[RepNode]){
2307 if (Tarjan2DFS[RepNode] == 0) {
2308 Changed |= QueryNode(RepNode);
2309 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002310 RepNode = FindNode(RepNode);
2311 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002312 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2313 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002314 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002315
2316 // We may have just discovered that this node is part of a cycle, in
2317 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002318 if (RepNode != *bi) {
2319 ToErase.set(*bi);
2320 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002321 }
2322 }
2323
Daniel Berlinaad15882007-09-16 21:45:02 +00002324 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2325 GraphNodes[Node].Edges |= NewEdges;
2326
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002327 // If this node is a root of a non-trivial SCC, place it on our
2328 // worklist to be processed.
2329 if (OurDFS == Tarjan2DFS[Node]) {
2330 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2331 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002332
2333 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002334 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002335 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002336 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002337
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002338 if (Merged)
2339 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002340 } else {
2341 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002342 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002343
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002344 return(Changed | Merged);
2345}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002346
2347/// SolveConstraints - This stage iteratively processes the constraints list
2348/// propagating constraints (adding edges to the Nodes in the points-to graph)
2349/// until a fixed point is reached.
2350///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002351/// We use a variant of the technique called "Lazy Cycle Detection", which is
2352/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2353/// Analysis for Millions of Lines of Code. In Programming Language Design and
2354/// Implementation (PLDI), June 2007."
2355/// The paper describes performing cycle detection one node at a time, which can
2356/// be expensive if there are no cycles, but there are long chains of nodes that
2357/// it heuristically believes are cycles (because it will DFS from each node
2358/// without state from previous nodes).
2359/// Instead, we use the heuristic to build a worklist of nodes to check, then
2360/// cycle detect them all at the same time to do this more cheaply. This
2361/// catches cycles slightly later than the original technique did, but does it
2362/// make significantly cheaper.
2363
Chris Lattnere995a2a2004-05-23 21:00:47 +00002364void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002365 CurrWL = &w1;
2366 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002367
Daniel Berlind81ccc22007-09-24 19:45:49 +00002368 OptimizeConstraints();
2369#undef DEBUG_TYPE
2370#define DEBUG_TYPE "anders-aa-constraints"
2371 DEBUG(PrintConstraints());
2372#undef DEBUG_TYPE
2373#define DEBUG_TYPE "anders-aa"
2374
Daniel Berlinaad15882007-09-16 21:45:02 +00002375 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2376 Node *N = &GraphNodes[i];
2377 N->PointsTo = new SparseBitVector<>;
2378 N->OldPointsTo = new SparseBitVector<>;
2379 N->Edges = new SparseBitVector<>;
2380 }
2381 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002382 UnitePointerEquivalences();
2383 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002384 Node2DFS.clear();
2385 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002386 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2387 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2388 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002389 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2390 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2391
2392 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002393 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002394 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002395
2396 // Add to work list if it's a representative and can contribute to the
2397 // calculation right now.
2398 if (INode->isRep() && !INode->PointsTo->empty()
2399 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2400 INode->Stamp();
2401 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002402 }
2403 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002404 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002405#if !FULL_UNIVERSAL
2406 // "Rep and special variables" - in order for HCD to maintain conservative
2407 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2408 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2409 // the analysis - it's ok to add edges from the special nodes, but never
2410 // *to* the special nodes.
2411 std::vector<unsigned int> RSV;
2412#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002413 while( !CurrWL->empty() ) {
2414 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002415
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002416 Node* CurrNode;
2417 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002418
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002419 // Actual cycle checking code. We cycle check all of the lazy cycle
2420 // candidates from the last iteration in one go.
2421 if (!TarjanWL.empty()) {
2422 DFSNumber = 0;
2423
2424 Tarjan2DFS.clear();
2425 Tarjan2Deleted.clear();
2426 while (!TarjanWL.empty()) {
2427 unsigned int ToTarjan = TarjanWL.front();
2428 TarjanWL.pop();
2429 if (!Tarjan2Deleted[ToTarjan]
2430 && GraphNodes[ToTarjan].isRep()
2431 && Tarjan2DFS[ToTarjan] == 0)
2432 QueryNode(ToTarjan);
2433 }
2434 }
2435
2436 // Add to work list if it's a representative and can contribute to the
2437 // calculation right now.
2438 while( (CurrNode = CurrWL->pop()) != NULL ) {
2439 CurrNodeIndex = CurrNode - &GraphNodes[0];
2440 CurrNode->Stamp();
2441
2442
Daniel Berlinaad15882007-09-16 21:45:02 +00002443 // Figure out the changed points to bits
2444 SparseBitVector<> CurrPointsTo;
2445 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2446 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002447 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002448 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002449
Daniel Berlinaad15882007-09-16 21:45:02 +00002450 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002451
2452 // Check the offline-computed equivalencies from HCD.
2453 bool SCC = false;
2454 unsigned Rep;
2455
2456 if (SDT[CurrNodeIndex] >= 0) {
2457 SCC = true;
2458 Rep = FindNode(SDT[CurrNodeIndex]);
2459
2460#if !FULL_UNIVERSAL
2461 RSV.clear();
2462#endif
2463 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2464 bi != CurrPointsTo.end(); ++bi) {
2465 unsigned Node = FindNode(*bi);
2466#if !FULL_UNIVERSAL
2467 if (Node < NumberSpecialNodes) {
2468 RSV.push_back(Node);
2469 continue;
2470 }
2471#endif
2472 Rep = UniteNodes(Rep,Node);
2473 }
2474#if !FULL_UNIVERSAL
2475 RSV.push_back(Rep);
2476#endif
2477
2478 NextWL->insert(&GraphNodes[Rep]);
2479
2480 if ( ! CurrNode->isRep() )
2481 continue;
2482 }
2483
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002484 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002485
Daniel Berlinaad15882007-09-16 21:45:02 +00002486 /* Now process the constraints for this node. */
2487 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2488 li != CurrNode->Constraints.end(); ) {
2489 li->Src = FindNode(li->Src);
2490 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002491
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002492 // Delete redundant constraints
2493 if( Seen.count(*li) ) {
2494 std::list<Constraint>::iterator lk = li; li++;
2495
2496 CurrNode->Constraints.erase(lk);
2497 ++NumErased;
2498 continue;
2499 }
2500 Seen.insert(*li);
2501
Daniel Berlinaad15882007-09-16 21:45:02 +00002502 // Src and Dest will be the vars we are going to process.
2503 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002504 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002505 // Load constraints say that every member of our RHS solution has K
2506 // added to it, and that variable gets an edge to LHS. We also union
2507 // RHS+K's solution into the LHS solution.
2508 // Store constraints say that every member of our LHS solution has K
2509 // added to it, and that variable gets an edge from RHS. We also union
2510 // RHS's solution into the LHS+K solution.
2511 unsigned *Src;
2512 unsigned *Dest;
2513 unsigned K = li->Offset;
2514 unsigned CurrMember;
2515 if (li->Type == Constraint::Load) {
2516 Src = &CurrMember;
2517 Dest = &li->Dest;
2518 } else if (li->Type == Constraint::Store) {
2519 Src = &li->Src;
2520 Dest = &CurrMember;
2521 } else {
2522 // TODO Handle offseted copy constraint
2523 li++;
2524 continue;
2525 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002526
2527 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002528 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002529 // involves pointers; if so, remove the redundant constraints).
2530 if( SCC && K == 0 ) {
2531#if FULL_UNIVERSAL
2532 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002533
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002534 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2535 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2536 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002537#else
2538 for (unsigned i=0; i < RSV.size(); ++i) {
2539 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002540
Daniel Berlinc864edb2008-03-05 19:31:47 +00002541 if (*Dest < NumberSpecialNodes)
2542 continue;
2543 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2544 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2545 NextWL->insert(&GraphNodes[*Dest]);
2546 }
2547#endif
2548 // since all future elements of the points-to set will be
2549 // equivalent to the current ones, the complex constraints
2550 // become redundant.
2551 //
2552 std::list<Constraint>::iterator lk = li; li++;
2553#if !FULL_UNIVERSAL
2554 // In this case, we can still erase the constraints when the
2555 // elements of the points-to sets are referenced by *Dest,
2556 // but not when they are referenced by *Src (i.e. for a Load
2557 // constraint). This is because if another special variable is
2558 // put into the points-to set later, we still need to add the
2559 // new edge from that special variable.
2560 if( lk->Type != Constraint::Load)
2561#endif
2562 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2563 } else {
2564 const SparseBitVector<> &Solution = CurrPointsTo;
2565
2566 for (SparseBitVector<>::iterator bi = Solution.begin();
2567 bi != Solution.end();
2568 ++bi) {
2569 CurrMember = *bi;
2570
2571 // Need to increment the member by K since that is where we are
2572 // supposed to copy to/from. Note that in positive weight cycles,
2573 // which occur in address taking of fields, K can go past
2574 // MaxK[CurrMember] elements, even though that is all it could point
2575 // to.
2576 if (K > 0 && K > MaxK[CurrMember])
2577 continue;
2578 else
2579 CurrMember = FindNode(CurrMember + K);
2580
2581 // Add an edge to the graph, so we can just do regular
2582 // bitmap ior next time. It may also let us notice a cycle.
2583#if !FULL_UNIVERSAL
2584 if (*Dest < NumberSpecialNodes)
2585 continue;
2586#endif
2587 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2588 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2589 NextWL->insert(&GraphNodes[*Dest]);
2590
2591 }
2592 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002593 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002594 }
2595 SparseBitVector<> NewEdges;
2596 SparseBitVector<> ToErase;
2597
2598 // Now all we have left to do is propagate points-to info along the
2599 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002600 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2601 bi != CurrNode->Edges->end();
2602 ++bi) {
2603
2604 unsigned DestVar = *bi;
2605 unsigned Rep = FindNode(DestVar);
2606
Bill Wendlingf059deb2008-02-26 10:51:52 +00002607 // If we ended up with this node as our destination, or we've already
2608 // got an edge for the representative, delete the current edge.
2609 if (Rep == CurrNodeIndex ||
2610 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002611 ToErase.set(DestVar);
2612 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002613 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002614
Bill Wendlingf059deb2008-02-26 10:51:52 +00002615 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002616
2617 // This is where we do lazy cycle detection.
2618 // If this is a cycle candidate (equal points-to sets and this
2619 // particular edge has not been cycle-checked previously), add to the
2620 // list to check for cycles on the next iteration.
2621 if (!EdgesChecked.count(edge) &&
2622 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2623 EdgesChecked.insert(edge);
2624 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002625 }
2626 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002627#if !FULL_UNIVERSAL
2628 if (Rep >= NumberSpecialNodes)
2629#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002630 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002631 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002632 }
2633 // If this edge's destination was collapsed, rewrite the edge.
2634 if (Rep != DestVar) {
2635 ToErase.set(DestVar);
2636 NewEdges.set(Rep);
2637 }
2638 }
2639 CurrNode->Edges->intersectWithComplement(ToErase);
2640 CurrNode->Edges |= NewEdges;
2641 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002642
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002643 // Switch to other work list.
2644 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2645 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002646
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002647
Daniel Berlinaad15882007-09-16 21:45:02 +00002648 Node2DFS.clear();
2649 Node2Deleted.clear();
2650 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2651 Node *N = &GraphNodes[i];
2652 delete N->OldPointsTo;
2653 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002654 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002655 SDTActive = false;
2656 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002657}
2658
Daniel Berlinaad15882007-09-16 21:45:02 +00002659//===----------------------------------------------------------------------===//
2660// Union-Find
2661//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002662
Daniel Berlinaad15882007-09-16 21:45:02 +00002663// Unite nodes First and Second, returning the one which is now the
2664// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002665unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2666 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002667 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2668 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002669
Daniel Berlinaad15882007-09-16 21:45:02 +00002670 Node *FirstNode = &GraphNodes[First];
2671 Node *SecondNode = &GraphNodes[Second];
2672
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002673 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002674 "Trying to unite two non-representative nodes!");
2675 if (First == Second)
2676 return First;
2677
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002678 if (UnionByRank) {
2679 int RankFirst = (int) FirstNode ->NodeRep;
2680 int RankSecond = (int) SecondNode->NodeRep;
2681
2682 // Rank starts at -1 and gets decremented as it increases.
2683 // Translation: higher rank, lower NodeRep value, which is always negative.
2684 if (RankFirst > RankSecond) {
2685 unsigned t = First; First = Second; Second = t;
2686 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2687 } else if (RankFirst == RankSecond) {
2688 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2689 }
2690 }
2691
Daniel Berlinaad15882007-09-16 21:45:02 +00002692 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002693#if !FULL_UNIVERSAL
2694 if (First >= NumberSpecialNodes)
2695#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002696 if (FirstNode->PointsTo && SecondNode->PointsTo)
2697 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2698 if (FirstNode->Edges && SecondNode->Edges)
2699 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002700 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002701 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2702 SecondNode->Constraints);
2703 if (FirstNode->OldPointsTo) {
2704 delete FirstNode->OldPointsTo;
2705 FirstNode->OldPointsTo = new SparseBitVector<>;
2706 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002707
2708 // Destroy interesting parts of the merged-from node.
2709 delete SecondNode->OldPointsTo;
2710 delete SecondNode->Edges;
2711 delete SecondNode->PointsTo;
2712 SecondNode->Edges = NULL;
2713 SecondNode->PointsTo = NULL;
2714 SecondNode->OldPointsTo = NULL;
2715
2716 NumUnified++;
2717 DOUT << "Unified Node ";
2718 DEBUG(PrintNode(FirstNode));
2719 DOUT << " and Node ";
2720 DEBUG(PrintNode(SecondNode));
2721 DOUT << "\n";
2722
Daniel Berlinc864edb2008-03-05 19:31:47 +00002723 if (SDTActive)
2724 if (SDT[Second] >= 0)
2725 if (SDT[First] < 0)
2726 SDT[First] = SDT[Second];
2727 else {
2728 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2729 First = FindNode(First);
2730 }
2731
Daniel Berlinaad15882007-09-16 21:45:02 +00002732 return First;
2733}
2734
2735// Find the index into GraphNodes of the node representing Node, performing
2736// path compression along the way
2737unsigned Andersens::FindNode(unsigned NodeIndex) {
2738 assert (NodeIndex < GraphNodes.size()
2739 && "Attempting to find a node that can't exist");
2740 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002741 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002742 return NodeIndex;
2743 else
2744 return (N->NodeRep = FindNode(N->NodeRep));
2745}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002746
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002747// Find the index into GraphNodes of the node representing Node,
2748// don't perform path compression along the way (for Print)
2749unsigned Andersens::FindNode(unsigned NodeIndex) const {
2750 assert (NodeIndex < GraphNodes.size()
2751 && "Attempting to find a node that can't exist");
2752 const Node *N = &GraphNodes[NodeIndex];
2753 if (N->isRep())
2754 return NodeIndex;
2755 else
2756 return FindNode(N->NodeRep);
2757}
2758
Chris Lattnere995a2a2004-05-23 21:00:47 +00002759//===----------------------------------------------------------------------===//
2760// Debugging Output
2761//===----------------------------------------------------------------------===//
2762
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002763void Andersens::PrintNode(const Node *N) const {
Chris Lattnere995a2a2004-05-23 21:00:47 +00002764 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002765 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002766 return;
2767 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002768 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002769 return;
2770 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002771 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002772 return;
2773 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002774 if (!N->getValue()) {
2775 cerr << "artificial" << (intptr_t) N;
2776 return;
2777 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002778
2779 assert(N->getValue() != 0 && "Never set node label!");
2780 Value *V = N->getValue();
2781 if (Function *F = dyn_cast<Function>(V)) {
2782 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002783 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002784 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002785 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002786 } else if (F->getFunctionType()->isVarArg() &&
2787 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002788 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002789 return;
2790 }
2791 }
2792
2793 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002794 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002795 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002796 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002797
2798 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002799 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002800 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002801 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002802
2803 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002804 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002805 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002806}
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002807void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002808 if (C.Type == Constraint::Store) {
2809 cerr << "*";
2810 if (C.Offset != 0)
2811 cerr << "(";
2812 }
2813 PrintNode(&GraphNodes[C.Dest]);
2814 if (C.Type == Constraint::Store && C.Offset != 0)
2815 cerr << " + " << C.Offset << ")";
2816 cerr << " = ";
2817 if (C.Type == Constraint::Load) {
2818 cerr << "*";
2819 if (C.Offset != 0)
2820 cerr << "(";
2821 }
2822 else if (C.Type == Constraint::AddressOf)
2823 cerr << "&";
2824 PrintNode(&GraphNodes[C.Src]);
2825 if (C.Offset != 0 && C.Type != Constraint::Store)
2826 cerr << " + " << C.Offset;
2827 if (C.Type == Constraint::Load && C.Offset != 0)
2828 cerr << ")";
2829 cerr << "\n";
2830}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002831
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002832void Andersens::PrintConstraints() const {
Bill Wendlinge8156192006-12-07 01:30:32 +00002833 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002834
Daniel Berlind81ccc22007-09-24 19:45:49 +00002835 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2836 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002837}
2838
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002839void Andersens::PrintPointsToGraph() const {
Bill Wendlinge8156192006-12-07 01:30:32 +00002840 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002841 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002842 const Node *N = &GraphNodes[i];
2843 if (FindNode(i) != i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002844 PrintNode(N);
2845 cerr << "\t--> same as ";
2846 PrintNode(&GraphNodes[FindNode(i)]);
2847 cerr << "\n";
2848 } else {
2849 cerr << "[" << (N->PointsTo->count()) << "] ";
2850 PrintNode(N);
2851 cerr << "\t--> ";
2852
2853 bool first = true;
2854 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2855 bi != N->PointsTo->end();
2856 ++bi) {
2857 if (!first)
2858 cerr << ", ";
2859 PrintNode(&GraphNodes[*bi]);
2860 first = false;
2861 }
2862 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002863 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002864 }
2865}