blob: 4ace049afa59dea3f5f50589ffcadfd83d7a171a [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"
Owen Anderson2e693102009-06-24 22:16:52 +000068#include "llvm/System/Atomic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000069#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000070#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000071#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000072#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000073#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000074#include <list>
Dan Gohmanc9235d22008-03-21 23:51:57 +000075#include <map>
Daniel Berlinaad15882007-09-16 21:45:02 +000076#include <stack>
77#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000078#include <queue>
79
80// Determining the actual set of nodes the universal set can consist of is very
81// expensive because it means propagating around very large sets. We rely on
82// other analysis being able to determine which nodes can never be pointed to in
83// order to disambiguate further than "points-to anything".
84#define FULL_UNIVERSAL 0
Chris Lattnere995a2a2004-05-23 21:00:47 +000085
Daniel Berlinaad15882007-09-16 21:45:02 +000086using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000087STATISTIC(NumIters , "Number of iterations to reach convergence");
88STATISTIC(NumConstraints, "Number of constraints");
89STATISTIC(NumNodes , "Number of nodes");
90STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000091STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000092
Dan Gohman844731a2008-05-13 00:00:25 +000093static const unsigned SelfRep = (unsigned)-1;
94static const unsigned Unvisited = (unsigned)-1;
95// Position of the function return node relative to the function node.
96static const unsigned CallReturnPos = 1;
97// Position of the function call node relative to the function node.
98static const unsigned CallFirstArgPos = 2;
Daniel Berlind81ccc22007-09-24 19:45:49 +000099
Dan Gohman844731a2008-05-13 00:00:25 +0000100namespace {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000101 struct BitmapKeyInfo {
102 static inline SparseBitVector<> *getEmptyKey() {
103 return reinterpret_cast<SparseBitVector<> *>(-1);
104 }
105 static inline SparseBitVector<> *getTombstoneKey() {
106 return reinterpret_cast<SparseBitVector<> *>(-2);
107 }
108 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
109 return bitmap->getHashValue();
110 }
111 static bool isEqual(const SparseBitVector<> *LHS,
112 const SparseBitVector<> *RHS) {
113 if (LHS == RHS)
114 return true;
115 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
116 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
117 return false;
118
119 return *LHS == *RHS;
120 }
121
122 static bool isPod() { return true; }
123 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000124
Reid Spencerd7d83db2007-02-05 23:42:17 +0000125 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
126 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000127 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000128
129 /// Constraint - Objects of this structure are used to represent the various
130 /// constraints identified by the algorithm. The constraints are 'copy',
131 /// for statements like "A = B", 'load' for statements like "A = *B",
132 /// 'store' for statements like "*A = B", and AddressOf for statements like
133 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
134 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000135 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000136 /// resolvable to A = &C where C = B + K)
137
138 struct Constraint {
139 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
140 unsigned Dest;
141 unsigned Src;
142 unsigned Offset;
143
144 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
145 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000146 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000147 "Offset is illegal on addressof constraints");
148 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000149
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000150 bool operator==(const Constraint &RHS) const {
151 return RHS.Type == Type
152 && RHS.Dest == Dest
153 && RHS.Src == Src
154 && RHS.Offset == Offset;
155 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000156
157 bool operator!=(const Constraint &RHS) const {
158 return !(*this == RHS);
159 }
160
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000161 bool operator<(const Constraint &RHS) const {
162 if (RHS.Type != Type)
163 return RHS.Type < Type;
164 else if (RHS.Dest != Dest)
165 return RHS.Dest < Dest;
166 else if (RHS.Src != Src)
167 return RHS.Src < Src;
168 return RHS.Offset < Offset;
169 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000170 };
171
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000172 // Information DenseSet requires implemented in order to be able to do
173 // it's thing
174 struct PairKeyInfo {
175 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000176 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000177 }
178 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000179 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000180 }
181 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
182 return P.first ^ P.second;
183 }
184 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
185 const std::pair<unsigned, unsigned> &RHS) {
186 return LHS == RHS;
187 }
188 };
189
Daniel Berlin336c6c02007-09-29 00:50:40 +0000190 struct ConstraintKeyInfo {
191 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000192 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000193 }
194 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000195 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000196 }
197 static unsigned getHashValue(const Constraint &C) {
198 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
199 }
200 static bool isEqual(const Constraint &LHS,
201 const Constraint &RHS) {
202 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
203 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
204 }
205 };
206
Daniel Berlind81ccc22007-09-24 19:45:49 +0000207 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000208 // graph. Due to various optimizations, it is not always the case that
209 // there is a mapping from a Node to a Value. In particular, we add
210 // artificial Node's that represent the set of pointed-to variables shared
211 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000212 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000213 private:
214 static unsigned Counter;
215
216 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000217 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000218 SparseBitVector<> *Edges;
219 SparseBitVector<> *PointsTo;
220 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000221 std::list<Constraint> Constraints;
222
Daniel Berlind81ccc22007-09-24 19:45:49 +0000223 // Pointer and location equivalence labels
224 unsigned PointerEquivLabel;
225 unsigned LocationEquivLabel;
226 // Predecessor edges, both real and implicit
227 SparseBitVector<> *PredEdges;
228 SparseBitVector<> *ImplicitPredEdges;
229 // Set of nodes that point to us, only use for location equivalence.
230 SparseBitVector<> *PointedToBy;
231 // Number of incoming edges, used during variable substitution to early
232 // free the points-to sets
233 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000234 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000235 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000236 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000237 bool Direct;
238 // True if the node is address taken, *or* it is part of a group of nodes
239 // that must be kept together. This is set to true for functions and
240 // their arg nodes, which must be kept at the same position relative to
241 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000242 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000243
Daniel Berlind81ccc22007-09-24 19:45:49 +0000244 // Nodes in cycles (or in equivalence classes) are united together using a
245 // standard union-find representation with path compression. NodeRep
246 // gives the index into GraphNodes for the representative Node.
247 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000248
249 // Modification timestamp. Assigned from Counter.
250 // Used for work list prioritization.
251 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000252
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000253 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000254 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000255 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
256 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
257 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000258 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000259
Chris Lattnere995a2a2004-05-23 21:00:47 +0000260 Node *setValue(Value *V) {
261 assert(Val == 0 && "Value already set for this node!");
262 Val = V;
263 return this;
264 }
265
266 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000267 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000268 Value *getValue() const { return Val; }
269
Chris Lattnere995a2a2004-05-23 21:00:47 +0000270 /// addPointerTo - Add a pointer to the list of pointees of this node,
271 /// returning true if this caused a new pointer to be added, or false if
272 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000273 bool addPointerTo(unsigned Node) {
274 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000275 }
276
277 /// intersects - Return true if the points-to set of this node intersects
278 /// with the points-to set of the specified node.
279 bool intersects(Node *N) const;
280
281 /// intersectsIgnoring - Return true if the points-to set of this node
282 /// intersects with the points-to set of the specified node on any nodes
283 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000284 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000285
286 // Timestamp a node (used for work list prioritization)
287 void Stamp() {
Owen Anderson2d7f78e2009-06-25 16:32:45 +0000288 Timestamp = sys::AtomicIncrement(&Counter);
289 --Timestamp;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000290 }
291
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000292 bool isRep() const {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000293 return( (int) NodeRep < 0 );
294 }
295 };
296
297 struct WorkListElement {
298 Node* node;
299 unsigned Timestamp;
300 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
301
302 // Note that we reverse the sense of the comparison because we
303 // actually want to give low timestamps the priority over high,
304 // whereas priority is typically interpreted as a greater value is
305 // given high priority.
306 bool operator<(const WorkListElement& that) const {
307 return( this->Timestamp > that.Timestamp );
308 }
309 };
310
311 // Priority-queue based work list specialized for Nodes.
312 class WorkList {
313 std::priority_queue<WorkListElement> Q;
314
315 public:
316 void insert(Node* n) {
317 Q.push( WorkListElement(n, n->Timestamp) );
318 }
319
320 // We automatically discard non-representative nodes and nodes
321 // that were in the work list twice (we keep a copy of the
322 // timestamp in the work list so we can detect this situation by
323 // comparing against the node's current timestamp).
324 Node* pop() {
325 while( !Q.empty() ) {
326 WorkListElement x = Q.top(); Q.pop();
327 Node* INode = x.node;
328
329 if( INode->isRep() &&
330 INode->Timestamp == x.Timestamp ) {
331 return(x.node);
332 }
333 }
334 return(0);
335 }
336
337 bool empty() {
338 return Q.empty();
339 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000340 };
341
342 /// GraphNodes - This vector is populated as part of the object
343 /// identification stage of the analysis, which populates this vector with a
344 /// node for each memory object and fills in the ValueNodes map.
345 std::vector<Node> GraphNodes;
346
347 /// ValueNodes - This map indicates the Node that a particular Value* is
348 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000349 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000350
351 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000352 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000353 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000354
355 /// ReturnNodes - This map contains an entry for each function in the
356 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000357 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000358
359 /// VarargNodes - This map contains the entry used to represent all pointers
360 /// passed through the varargs portion of a function call for a particular
361 /// function. An entry is not present in this map for functions that do not
362 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000363 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000364
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000365
Chris Lattnere995a2a2004-05-23 21:00:47 +0000366 /// Constraints - This vector contains a list of all of the constraints
367 /// identified by the program.
368 std::vector<Constraint> Constraints;
369
Daniel Berlind81ccc22007-09-24 19:45:49 +0000370 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000371 // this is equivalent to the number of arguments + CallFirstArgPos)
372 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000373
374 /// This enum defines the GraphNodes indices that correspond to important
375 /// fixed sets.
376 enum {
377 UniversalSet = 0,
378 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000379 NullObject = 2,
380 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000381 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000382 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000383 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000384 // Map from Graph Node to DFS number
385 std::vector<unsigned> Node2DFS;
386 // Map from Graph Node to Deleted from graph.
387 std::vector<bool> Node2Deleted;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000388 // Same as Node Maps, but implemented as std::map because it is faster to
389 // clear
390 std::map<unsigned, unsigned> Tarjan2DFS;
391 std::map<unsigned, bool> Tarjan2Deleted;
392 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000393 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000394
395 // Work lists.
396 WorkList w1, w2;
397 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000398
Daniel Berlind81ccc22007-09-24 19:45:49 +0000399 // Offline variable substitution related things
400
401 // Temporary rep storage, used because we can't collapse SCC's in the
402 // predecessor graph by uniting the variables permanently, we can only do so
403 // for the successor graph.
404 std::vector<unsigned> VSSCCRep;
405 // Mapping from node to whether we have visited it during SCC finding yet.
406 std::vector<bool> Node2Visited;
407 // During variable substitution, we create unknowns to represent the unknown
408 // value that is a dereference of a variable. These nodes are known as
409 // "ref" nodes (since they represent the value of dereferences).
410 unsigned FirstRefNode;
411 // During HVN, we create represent address taken nodes as if they were
412 // unknown (since HVN, unlike HU, does not evaluate unions).
413 unsigned FirstAdrNode;
414 // Current pointer equivalence class number
415 unsigned PEClass;
416 // Mapping from points-to sets to equivalence classes
417 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
418 BitVectorMap Set2PEClass;
419 // Mapping from pointer equivalences to the representative node. -1 if we
420 // have no representative node for this pointer equivalence class yet.
421 std::vector<int> PEClass2Node;
422 // Mapping from pointer equivalences to representative node. This includes
423 // pointer equivalent but not location equivalent variables. -1 if we have
424 // no representative node for this pointer equivalence class yet.
425 std::vector<int> PENLEClass2Node;
Daniel Berlinc864edb2008-03-05 19:31:47 +0000426 // Union/Find for HCD
427 std::vector<unsigned> HCDSCCRep;
428 // HCD's offline-detected cycles; "Statically DeTected"
429 // -1 if not part of such a cycle, otherwise a representative node.
430 std::vector<int> SDT;
431 // Whether to use SDT (UniteNodes can use it during solving, but not before)
432 bool SDTActive;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000433
Chris Lattnere995a2a2004-05-23 21:00:47 +0000434 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000435 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000436 Andersens() : ModulePass(&ID) {}
Devang Patel1cee94f2008-03-18 00:39:19 +0000437
Chris Lattnerb12914b2004-09-20 04:48:05 +0000438 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000439 InitializeAliasAnalysis(this);
440 IdentifyObjects(M);
441 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000442#undef DEBUG_TYPE
443#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000444 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000445#undef DEBUG_TYPE
446#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000447 SolveConstraints();
448 DEBUG(PrintPointsToGraph());
449
450 // Free the constraints list, as we don't need it to respond to alias
451 // requests.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000452 std::vector<Constraint>().swap(Constraints);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000453 //These are needed for Print() (-analyze in opt)
454 //ObjectNodes.clear();
455 //ReturnNodes.clear();
456 //VarargNodes.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000457 return false;
458 }
459
460 void releaseMemory() {
461 // FIXME: Until we have transitively required passes working correctly,
462 // this cannot be enabled! Otherwise, using -count-aa with the pass
463 // causes memory to be freed too early. :(
464#if 0
465 // The memory objects and ValueNodes data structures at the only ones that
466 // are still live after construction.
467 std::vector<Node>().swap(GraphNodes);
468 ValueNodes.clear();
469#endif
470 }
471
472 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
473 AliasAnalysis::getAnalysisUsage(AU);
474 AU.setPreservesAll(); // Does not transform code
475 }
476
477 //------------------------------------------------
478 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000479 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000480 AliasResult alias(const Value *V1, unsigned V1Size,
481 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000482 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
483 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000484 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
485 bool pointsToConstantMemory(const Value *P);
486
487 virtual void deleteValue(Value *V) {
488 ValueNodes.erase(V);
489 getAnalysis<AliasAnalysis>().deleteValue(V);
490 }
491
492 virtual void copyValue(Value *From, Value *To) {
493 ValueNodes[To] = ValueNodes[From];
494 getAnalysis<AliasAnalysis>().copyValue(From, To);
495 }
496
497 private:
498 /// getNode - Return the node corresponding to the specified pointer scalar.
499 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000500 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000501 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000502 if (!isa<GlobalValue>(C))
503 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000504
Daniel Berlind81ccc22007-09-24 19:45:49 +0000505 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000506 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000507#ifndef NDEBUG
508 V->dump();
509#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000510 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000511 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000512 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000513 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000514
Chris Lattnere995a2a2004-05-23 21:00:47 +0000515 /// getObject - Return the node corresponding to the memory object for the
516 /// specified global or allocation instruction.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000517 unsigned getObject(Value *V) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000518 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000519 assert(I != ObjectNodes.end() &&
520 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000521 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000522 }
523
524 /// getReturnNode - Return the node representing the return value for the
525 /// specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000526 unsigned getReturnNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000527 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000528 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000529 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000530 }
531
532 /// getVarargNode - Return the node representing the variable arguments
533 /// formal for the specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000534 unsigned getVarargNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000535 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000536 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000537 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000538 }
539
540 /// getNodeValue - Get the node for the specified LLVM value and set the
541 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000542 unsigned getNodeValue(Value &V) {
543 unsigned Index = getNode(&V);
544 GraphNodes[Index].setValue(&V);
545 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000546 }
547
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000548 unsigned UniteNodes(unsigned First, unsigned Second,
549 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000550 unsigned FindNode(unsigned Node);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000551 unsigned FindNode(unsigned Node) const;
Daniel Berlinaad15882007-09-16 21:45:02 +0000552
Chris Lattnere995a2a2004-05-23 21:00:47 +0000553 void IdentifyObjects(Module &M);
554 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000555 bool AnalyzeUsesOfFunction(Value *);
556 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000557 void OptimizeConstraints();
558 unsigned FindEquivalentNode(unsigned, unsigned);
559 void ClumpAddressTaken();
560 void RewriteConstraints();
561 void HU();
562 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000563 void HCD();
564 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000565 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000566 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000567 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000568 void Condense(unsigned Node);
569 void HUValNum(unsigned Node);
570 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000571 unsigned getNodeForConstantPointer(Constant *C);
572 unsigned getNodeForConstantPointerTarget(Constant *C);
573 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000574
Chris Lattnere995a2a2004-05-23 21:00:47 +0000575 void AddConstraintsForNonInternalLinkage(Function *F);
576 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000577 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000578
579
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000580 void PrintNode(const Node *N) const;
581 void PrintConstraints() const ;
582 void PrintConstraint(const Constraint &) const;
583 void PrintLabels() const;
584 void PrintPointsToGraph() const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000585
586 //===------------------------------------------------------------------===//
587 // Instruction visitation methods for adding constraints
588 //
589 friend class InstVisitor<Andersens>;
590 void visitReturnInst(ReturnInst &RI);
591 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
592 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
593 void visitCallSite(CallSite CS);
594 void visitAllocationInst(AllocationInst &AI);
595 void visitLoadInst(LoadInst &LI);
596 void visitStoreInst(StoreInst &SI);
597 void visitGetElementPtrInst(GetElementPtrInst &GEP);
598 void visitPHINode(PHINode &PN);
599 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000600 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
601 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000602 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000603 void visitVAArg(VAArgInst &I);
604 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000605
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000606 //===------------------------------------------------------------------===//
607 // Implement Analyize interface
608 //
609 void print(std::ostream &O, const Module* M) const {
610 PrintPointsToGraph();
611 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000612 };
Chris Lattnere995a2a2004-05-23 21:00:47 +0000613}
614
Dan Gohman844731a2008-05-13 00:00:25 +0000615char Andersens::ID = 0;
616static RegisterPass<Andersens>
617X("anders-aa", "Andersen's Interprocedural Alias Analysis", false, true);
618static RegisterAnalysisGroup<AliasAnalysis> Y(X);
619
620// Initialize Timestamp Counter (static).
621unsigned Andersens::Node::Counter = 0;
622
Jeff Cohen534927d2005-01-08 22:01:16 +0000623ModulePass *llvm::createAndersensPass() { return new Andersens(); }
624
Chris Lattnere995a2a2004-05-23 21:00:47 +0000625//===----------------------------------------------------------------------===//
626// AliasAnalysis Interface Implementation
627//===----------------------------------------------------------------------===//
628
629AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
630 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000631 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
632 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000633
634 // Check to see if the two pointers are known to not alias. They don't alias
635 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000636 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000637 return NoAlias;
638
639 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
640}
641
Chris Lattnerf392c642005-03-28 06:21:17 +0000642AliasAnalysis::ModRefResult
643Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
644 // The only thing useful that we can contribute for mod/ref information is
645 // when calling external function calls: if we know that memory never escapes
646 // from the program, it cannot be modified by an external call.
647 //
648 // NOTE: This is not really safe, at least not when the entire program is not
649 // available. The deal is that the external function could call back into the
650 // program and modify stuff. We ignore this technical niggle for now. This
651 // is, after all, a "research quality" implementation of Andersen's analysis.
652 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000653 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000654 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000655
Daniel Berlinaad15882007-09-16 21:45:02 +0000656 if (N1->PointsTo->empty())
657 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000658#if FULL_UNIVERSAL
659 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
660 return NoModRef; // Universal set does not contain P
661#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000662 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000663 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000664#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000665 }
666
667 return AliasAnalysis::getModRefInfo(CS, P, Size);
668}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000669
Reid Spencer3a9ec242006-08-28 01:02:49 +0000670AliasAnalysis::ModRefResult
671Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
672 return AliasAnalysis::getModRefInfo(CS1,CS2);
673}
674
Chris Lattnere995a2a2004-05-23 21:00:47 +0000675/// getMustAlias - We can provide must alias information if we know that a
676/// pointer can only point to a specific function or the null pointer.
677/// Unfortunately we cannot determine must-alias information for global
678/// variables or any other memory memory objects because we do not track whether
679/// a pointer points to the beginning of an object or a field of it.
680void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000681 Node *N = &GraphNodes[FindNode(getNode(P))];
682 if (N->PointsTo->count() == 1) {
683 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
684 // If a function is the only object in the points-to set, then it must be
685 // the destination. Note that we can't handle global variables here,
686 // because we don't know if the pointer is actually pointing to a field of
687 // the global or to the beginning of it.
688 if (Value *V = Pointee->getValue()) {
689 if (Function *F = dyn_cast<Function>(V))
690 RetVals.push_back(F);
691 } else {
692 // If the object in the points-to set is the null object, then the null
693 // pointer is a must alias.
694 if (Pointee == &GraphNodes[NullObject])
695 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000696 }
697 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000698 AliasAnalysis::getMustAliases(P, RetVals);
699}
700
701/// pointsToConstantMemory - If we can determine that this pointer only points
702/// to constant memory, return true. In practice, this means that if the
703/// pointer can only point to constant globals, functions, or the null pointer,
704/// return true.
705///
706bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000707 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000708 unsigned i;
709
710 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
711 bi != N->PointsTo->end();
712 ++bi) {
713 i = *bi;
714 Node *Pointee = &GraphNodes[i];
715 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000716 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
717 !cast<GlobalVariable>(V)->isConstant()))
718 return AliasAnalysis::pointsToConstantMemory(P);
719 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000720 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000721 return AliasAnalysis::pointsToConstantMemory(P);
722 }
723 }
724
725 return true;
726}
727
728//===----------------------------------------------------------------------===//
729// Object Identification Phase
730//===----------------------------------------------------------------------===//
731
732/// IdentifyObjects - This stage scans the program, adding an entry to the
733/// GraphNodes list for each memory object in the program (global stack or
734/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
735///
736void Andersens::IdentifyObjects(Module &M) {
737 unsigned NumObjects = 0;
738
739 // Object #0 is always the universal set: the object that we don't know
740 // anything about.
741 assert(NumObjects == UniversalSet && "Something changed!");
742 ++NumObjects;
743
744 // Object #1 always represents the null pointer.
745 assert(NumObjects == NullPtr && "Something changed!");
746 ++NumObjects;
747
748 // Object #2 always represents the null object (the object pointed to by null)
749 assert(NumObjects == NullObject && "Something changed!");
750 ++NumObjects;
751
752 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000753 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
754 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000755 ObjectNodes[I] = NumObjects++;
756 ValueNodes[I] = NumObjects++;
757 }
758
759 // Add nodes for all of the functions and the instructions inside of them.
760 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
761 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000762 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000763 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000764 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
765 ReturnNodes[F] = NumObjects++;
766 if (F->getFunctionType()->isVarArg())
767 VarargNodes[F] = NumObjects++;
768
Daniel Berlinaad15882007-09-16 21:45:02 +0000769
Chris Lattnere995a2a2004-05-23 21:00:47 +0000770 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000771 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
772 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000773 {
774 if (isa<PointerType>(I->getType()))
775 ValueNodes[I] = NumObjects++;
776 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000777 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000778
779 // Scan the function body, creating a memory object for each heap/stack
780 // allocation in the body of the function and a node to represent all
781 // pointer values defined by instructions and used as operands.
782 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
783 // If this is an heap or stack allocation, create a node for the memory
784 // object.
785 if (isa<PointerType>(II->getType())) {
786 ValueNodes[&*II] = NumObjects++;
787 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
788 ObjectNodes[AI] = NumObjects++;
789 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000790
791 // Calls to inline asm need to be added as well because the callee isn't
792 // referenced anywhere else.
793 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
794 Value *Callee = CI->getCalledValue();
795 if (isa<InlineAsm>(Callee))
796 ValueNodes[Callee] = NumObjects++;
797 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000798 }
799 }
800
801 // Now that we know how many objects to create, make them all now!
802 GraphNodes.resize(NumObjects);
803 NumNodes += NumObjects;
804}
805
806//===----------------------------------------------------------------------===//
807// Constraint Identification Phase
808//===----------------------------------------------------------------------===//
809
810/// getNodeForConstantPointer - Return the node corresponding to the constant
811/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000812unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000813 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
814
Chris Lattner267a1b02005-03-27 18:58:23 +0000815 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000816 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000817 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
818 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000819 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
820 switch (CE->getOpcode()) {
821 case Instruction::GetElementPtr:
822 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000823 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000824 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000825 case Instruction::BitCast:
826 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000827 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000828 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000829 assert(0);
830 }
831 } else {
832 assert(0 && "Unknown constant pointer!");
833 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000834 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000835}
836
837/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
838/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000839unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000840 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
841
842 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000843 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000844 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
845 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000846 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
847 switch (CE->getOpcode()) {
848 case Instruction::GetElementPtr:
849 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000850 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000851 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000852 case Instruction::BitCast:
853 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000854 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000855 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000856 assert(0);
857 }
858 } else {
859 assert(0 && "Unknown constant pointer!");
860 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000861 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000862}
863
864/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
865/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000866void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
867 Constant *C) {
Dan Gohmanb64aa112008-05-22 23:43:22 +0000868 if (C->getType()->isSingleValueType()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000869 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000870 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
871 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000872 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000873 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
874 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000875 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000876 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000877 // If this is an array or struct, include constraints for each element.
878 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
879 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000880 AddGlobalInitializerConstraints(NodeIndex,
881 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000882 }
883}
884
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000885/// AddConstraintsForNonInternalLinkage - If this function does not have
886/// internal linkage, realize that we can't trust anything passed into or
887/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000888void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000889 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000890 if (isa<PointerType>(I->getType()))
891 // If this is an argument of an externally accessible function, the
892 // incoming pointer might point to anything.
893 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000894 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000895}
896
Chris Lattner8a446432005-03-29 06:09:07 +0000897/// AddConstraintsForCall - If this is a call to a "known" function, add the
898/// constraints and return true. If this is a call to an unknown function,
899/// return false.
900bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000901 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000902
903 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000904 if (F->getName() == "atoi" || F->getName() == "atof" ||
905 F->getName() == "atol" || F->getName() == "atoll" ||
906 F->getName() == "remove" || F->getName() == "unlink" ||
907 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner824b9582008-11-21 16:42:48 +0000908 F->getName() == "llvm.memset" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000909 F->getName() == "strcmp" || F->getName() == "strncmp" ||
910 F->getName() == "execl" || F->getName() == "execlp" ||
911 F->getName() == "execle" || F->getName() == "execv" ||
912 F->getName() == "execvp" || F->getName() == "chmod" ||
913 F->getName() == "puts" || F->getName() == "write" ||
914 F->getName() == "open" || F->getName() == "create" ||
915 F->getName() == "truncate" || F->getName() == "chdir" ||
916 F->getName() == "mkdir" || F->getName() == "rmdir" ||
917 F->getName() == "read" || F->getName() == "pipe" ||
918 F->getName() == "wait" || F->getName() == "time" ||
919 F->getName() == "stat" || F->getName() == "fstat" ||
920 F->getName() == "lstat" || F->getName() == "strtod" ||
921 F->getName() == "strtof" || F->getName() == "strtold" ||
922 F->getName() == "fopen" || F->getName() == "fdopen" ||
923 F->getName() == "freopen" ||
924 F->getName() == "fflush" || F->getName() == "feof" ||
925 F->getName() == "fileno" || F->getName() == "clearerr" ||
926 F->getName() == "rewind" || F->getName() == "ftell" ||
927 F->getName() == "ferror" || F->getName() == "fgetc" ||
928 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
929 F->getName() == "fwrite" || F->getName() == "fread" ||
930 F->getName() == "fgets" || F->getName() == "ungetc" ||
931 F->getName() == "fputc" ||
932 F->getName() == "fputs" || F->getName() == "putc" ||
933 F->getName() == "ftell" || F->getName() == "rewind" ||
934 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
935 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
936 F->getName() == "printf" || F->getName() == "fprintf" ||
937 F->getName() == "sprintf" || F->getName() == "vprintf" ||
938 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
939 F->getName() == "scanf" || F->getName() == "fscanf" ||
940 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
941 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000942 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000943
Chris Lattner175b9632005-03-29 20:36:05 +0000944
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000945 // These functions do induce points-to edges.
Chris Lattner824b9582008-11-21 16:42:48 +0000946 if (F->getName() == "llvm.memcpy" ||
947 F->getName() == "llvm.memmove" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000948 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000949
Nick Lewycky3037eda2008-12-27 16:20:53 +0000950 const FunctionType *FTy = F->getFunctionType();
951 if (FTy->getNumParams() > 1 &&
952 isa<PointerType>(FTy->getParamType(0)) &&
953 isa<PointerType>(FTy->getParamType(1))) {
954
955 // *Dest = *Src, which requires an artificial graph node to represent the
956 // constraint. It is broken up into *Dest = temp, temp = *Src
957 unsigned FirstArg = getNode(CS.getArgument(0));
958 unsigned SecondArg = getNode(CS.getArgument(1));
959 unsigned TempArg = GraphNodes.size();
960 GraphNodes.push_back(Node());
961 Constraints.push_back(Constraint(Constraint::Store,
962 FirstArg, TempArg));
963 Constraints.push_back(Constraint(Constraint::Load,
964 TempArg, SecondArg));
965 // In addition, Dest = Src
966 Constraints.push_back(Constraint(Constraint::Copy,
967 FirstArg, SecondArg));
968 return true;
969 }
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000970 }
971
Chris Lattner77b50562005-03-29 20:04:24 +0000972 // Result = Arg0
973 if (F->getName() == "realloc" || F->getName() == "strchr" ||
974 F->getName() == "strrchr" || F->getName() == "strstr" ||
975 F->getName() == "strtok") {
Nick Lewycky3037eda2008-12-27 16:20:53 +0000976 const FunctionType *FTy = F->getFunctionType();
977 if (FTy->getNumParams() > 0 &&
978 isa<PointerType>(FTy->getParamType(0))) {
979 Constraints.push_back(Constraint(Constraint::Copy,
980 getNode(CS.getInstruction()),
981 getNode(CS.getArgument(0))));
982 return true;
983 }
Chris Lattner8a446432005-03-29 06:09:07 +0000984 }
985
986 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000987}
988
989
Chris Lattnere995a2a2004-05-23 21:00:47 +0000990
Daniel Berlinaad15882007-09-16 21:45:02 +0000991/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
992/// If this is used by anything complex (i.e., the address escapes), return
993/// true.
994bool Andersens::AnalyzeUsesOfFunction(Value *V) {
995
996 if (!isa<PointerType>(V->getType())) return true;
997
998 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
999 if (dyn_cast<LoadInst>(*UI)) {
1000 return false;
1001 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1002 if (V == SI->getOperand(1)) {
1003 return false;
1004 } else if (SI->getOperand(1)) {
1005 return true; // Storing the pointer
1006 }
1007 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1008 if (AnalyzeUsesOfFunction(GEP)) return true;
1009 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1010 // Make sure that this is just the function being called, not that it is
1011 // passing into the function.
1012 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1013 if (CI->getOperand(i) == V) return true;
1014 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1015 // Make sure that this is just the function being called, not that it is
1016 // passing into the function.
Bill Wendling9a507cd2009-03-13 21:15:59 +00001017 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +00001018 if (II->getOperand(i) == V) return true;
1019 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1020 if (CE->getOpcode() == Instruction::GetElementPtr ||
1021 CE->getOpcode() == Instruction::BitCast) {
1022 if (AnalyzeUsesOfFunction(CE))
1023 return true;
1024 } else {
1025 return true;
1026 }
1027 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1028 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1029 return true; // Allow comparison against null.
1030 } else if (dyn_cast<FreeInst>(*UI)) {
1031 return false;
1032 } else {
1033 return true;
1034 }
1035 return false;
1036}
1037
Chris Lattnere995a2a2004-05-23 21:00:47 +00001038/// CollectConstraints - This stage scans the program, adding a constraint to
1039/// the Constraints list for each instruction in the program that induces a
1040/// constraint, and setting up the initial points-to graph.
1041///
1042void Andersens::CollectConstraints(Module &M) {
1043 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001044 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1045 UniversalSet));
1046 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1047 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001048
1049 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001050 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001051
1052 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001053 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1054 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001055 // Associate the address of the global object as pointing to the memory for
1056 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001057 unsigned ObjectIndex = getObject(I);
1058 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001059 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001060 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1061 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001062
1063 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001064 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001065 } else {
1066 // If it doesn't have an initializer (i.e. it's defined in another
1067 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001068 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1069 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001070 }
1071 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001072
Chris Lattnere995a2a2004-05-23 21:00:47 +00001073 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001074 // Set up the return value node.
1075 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001076 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001077 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001078 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001079
1080 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001081 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1082 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001083 if (isa<PointerType>(I->getType()))
1084 getNodeValue(*I);
1085
Daniel Berlinaad15882007-09-16 21:45:02 +00001086 // At some point we should just add constraints for the escaping functions
1087 // at solve time, but this slows down solving. For now, we simply mark
1088 // address taken functions as escaping and treat them as external.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001089 if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001090 AddConstraintsForNonInternalLinkage(F);
1091
Reid Spencer5cbf9852007-01-30 20:08:39 +00001092 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001093 // Scan the function body, creating a memory object for each heap/stack
1094 // allocation in the body of the function and a node to represent all
1095 // pointer values defined by instructions and used as operands.
1096 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001097 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001098 // External functions that return pointers return the universal set.
1099 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1100 Constraints.push_back(Constraint(Constraint::Copy,
1101 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001102 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001103
1104 // Any pointers that are passed into the function have the universal set
1105 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001106 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1107 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001108 if (isa<PointerType>(I->getType())) {
1109 // Pointers passed into external functions could have anything stored
1110 // through them.
1111 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001112 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001113 // Memory objects passed into external function calls can have the
1114 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001115#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001116 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001117 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001118 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001119#else
1120 Constraints.push_back(Constraint(Constraint::Copy,
1121 getNode(I),
1122 UniversalSet));
1123#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001124 }
1125
1126 // If this is an external varargs function, it can also store pointers
1127 // into any pointers passed through the varargs section.
1128 if (F->getFunctionType()->isVarArg())
1129 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001130 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001131 }
1132 }
1133 NumConstraints += Constraints.size();
1134}
1135
1136
1137void Andersens::visitInstruction(Instruction &I) {
1138#ifdef NDEBUG
1139 return; // This function is just a big assert.
1140#endif
1141 if (isa<BinaryOperator>(I))
1142 return;
1143 // Most instructions don't have any effect on pointer values.
1144 switch (I.getOpcode()) {
1145 case Instruction::Br:
1146 case Instruction::Switch:
1147 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001148 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001149 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001150 case Instruction::ICmp:
1151 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001152 return;
1153 default:
1154 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001155 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001156 abort();
1157 }
1158}
1159
1160void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001161 unsigned ObjectIndex = getObject(&AI);
1162 GraphNodes[ObjectIndex].setValue(&AI);
1163 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1164 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001165}
1166
1167void Andersens::visitReturnInst(ReturnInst &RI) {
1168 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1169 // return V --> <Copy/retval{F}/v>
1170 Constraints.push_back(Constraint(Constraint::Copy,
1171 getReturnNode(RI.getParent()->getParent()),
1172 getNode(RI.getOperand(0))));
1173}
1174
1175void Andersens::visitLoadInst(LoadInst &LI) {
1176 if (isa<PointerType>(LI.getType()))
1177 // P1 = load P2 --> <Load/P1/P2>
1178 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1179 getNode(LI.getOperand(0))));
1180}
1181
1182void Andersens::visitStoreInst(StoreInst &SI) {
1183 if (isa<PointerType>(SI.getOperand(0)->getType()))
1184 // store P1, P2 --> <Store/P2/P1>
1185 Constraints.push_back(Constraint(Constraint::Store,
1186 getNode(SI.getOperand(1)),
1187 getNode(SI.getOperand(0))));
1188}
1189
1190void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1191 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1192 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1193 getNode(GEP.getOperand(0))));
1194}
1195
1196void Andersens::visitPHINode(PHINode &PN) {
1197 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001198 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001199 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1200 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1201 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1202 getNode(PN.getIncomingValue(i))));
1203 }
1204}
1205
1206void Andersens::visitCastInst(CastInst &CI) {
1207 Value *Op = CI.getOperand(0);
1208 if (isa<PointerType>(CI.getType())) {
1209 if (isa<PointerType>(Op->getType())) {
1210 // P1 = cast P2 --> <Copy/P1/P2>
1211 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1212 getNode(CI.getOperand(0))));
1213 } else {
1214 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001215#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001216 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001217 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001218#else
1219 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001220#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001221 }
1222 } else if (isa<PointerType>(Op->getType())) {
1223 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001224#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001225 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001226 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001227 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001228#else
1229 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001230#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001231 }
1232}
1233
1234void Andersens::visitSelectInst(SelectInst &SI) {
1235 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001236 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001237 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1238 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1239 getNode(SI.getOperand(1))));
1240 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1241 getNode(SI.getOperand(2))));
1242 }
1243}
1244
Chris Lattnere995a2a2004-05-23 21:00:47 +00001245void Andersens::visitVAArg(VAArgInst &I) {
1246 assert(0 && "vaarg not handled yet!");
1247}
1248
1249/// AddConstraintsForCall - Add constraints for a call with actual arguments
1250/// specified by CS to the function specified by F. Note that the types of
1251/// arguments might not match up in the case where this is an indirect call and
1252/// the function pointer has been casted. If this is the case, do something
1253/// reasonable.
1254void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001255 Value *CallValue = CS.getCalledValue();
1256 bool IsDeref = F == NULL;
1257
1258 // If this is a call to an external function, try to handle it directly to get
1259 // some taste of context sensitivity.
1260 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001261 return;
1262
Chris Lattnere995a2a2004-05-23 21:00:47 +00001263 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001264 unsigned CSN = getNode(CS.getInstruction());
1265 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1266 if (IsDeref)
1267 Constraints.push_back(Constraint(Constraint::Load, CSN,
1268 getNode(CallValue), CallReturnPos));
1269 else
1270 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1271 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001272 } else {
1273 // If the function returns a non-pointer value, handle this just like we
1274 // treat a nonpointer cast to pointer.
1275 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001276 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001277 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001278 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001279#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001280 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001281 UniversalSet,
1282 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001283#else
1284 Constraints.push_back(Constraint(Constraint::Copy,
1285 getNode(CallValue) + CallReturnPos,
1286 UniversalSet));
1287#endif
1288
1289
Chris Lattnere995a2a2004-05-23 21:00:47 +00001290 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001291
Chris Lattnere995a2a2004-05-23 21:00:47 +00001292 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001293 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001294 if (F) {
1295 // Direct Call
1296 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001297 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1298 {
1299#if !FULL_UNIVERSAL
1300 if (external && isa<PointerType>((*ArgI)->getType()))
1301 {
1302 // Add constraint that ArgI can now point to anything due to
1303 // escaping, as can everything it points to. The second portion of
1304 // this should be taken care of by universal = *universal
1305 Constraints.push_back(Constraint(Constraint::Copy,
1306 getNode(*ArgI),
1307 UniversalSet));
1308 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001309#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001310 if (isa<PointerType>(AI->getType())) {
1311 if (isa<PointerType>((*ArgI)->getType())) {
1312 // Copy the actual argument into the formal argument.
1313 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1314 getNode(*ArgI)));
1315 } else {
1316 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1317 UniversalSet));
1318 }
1319 } else if (isa<PointerType>((*ArgI)->getType())) {
1320#if FULL_UNIVERSAL
1321 Constraints.push_back(Constraint(Constraint::Copy,
1322 UniversalSet,
1323 getNode(*ArgI)));
1324#else
1325 Constraints.push_back(Constraint(Constraint::Copy,
1326 getNode(*ArgI),
1327 UniversalSet));
1328#endif
1329 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001330 }
1331 } else {
1332 //Indirect Call
1333 unsigned ArgPos = CallFirstArgPos;
1334 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001335 if (isa<PointerType>((*ArgI)->getType())) {
1336 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001337 Constraints.push_back(Constraint(Constraint::Store,
1338 getNode(CallValue),
1339 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001340 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001341 Constraints.push_back(Constraint(Constraint::Store,
1342 getNode (CallValue),
1343 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001344 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001345 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001346 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001347 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001348 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001349 for (; ArgI != ArgE; ++ArgI)
1350 if (isa<PointerType>((*ArgI)->getType()))
1351 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1352 getNode(*ArgI)));
1353 // If more arguments are passed in than we track, just drop them on the floor.
1354}
1355
1356void Andersens::visitCallSite(CallSite CS) {
1357 if (isa<PointerType>(CS.getType()))
1358 getNodeValue(*CS.getInstruction());
1359
1360 if (Function *F = CS.getCalledFunction()) {
1361 AddConstraintsForCall(CS, F);
1362 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001363 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001364 }
1365}
1366
1367//===----------------------------------------------------------------------===//
1368// Constraint Solving Phase
1369//===----------------------------------------------------------------------===//
1370
1371/// intersects - Return true if the points-to set of this node intersects
1372/// with the points-to set of the specified node.
1373bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001374 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001375}
1376
1377/// intersectsIgnoring - Return true if the points-to set of this node
1378/// intersects with the points-to set of the specified node on any nodes
1379/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001380bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1381 // TODO: If we are only going to call this with the same value for Ignoring,
1382 // we should move the special values out of the points-to bitmap.
1383 bool WeHadIt = PointsTo->test(Ignoring);
1384 bool NHadIt = N->PointsTo->test(Ignoring);
1385 bool Result = false;
1386 if (WeHadIt)
1387 PointsTo->reset(Ignoring);
1388 if (NHadIt)
1389 N->PointsTo->reset(Ignoring);
1390 Result = PointsTo->intersects(N->PointsTo);
1391 if (WeHadIt)
1392 PointsTo->set(Ignoring);
1393 if (NHadIt)
1394 N->PointsTo->set(Ignoring);
1395 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001396}
1397
Daniel Berlind81ccc22007-09-24 19:45:49 +00001398void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001399#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001400 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001401#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001402}
1403
1404
1405/// Clump together address taken variables so that the points-to sets use up
1406/// less space and can be operated on faster.
1407
1408void Andersens::ClumpAddressTaken() {
1409#undef DEBUG_TYPE
1410#define DEBUG_TYPE "anders-aa-renumber"
1411 std::vector<unsigned> Translate;
1412 std::vector<Node> NewGraphNodes;
1413
1414 Translate.resize(GraphNodes.size());
1415 unsigned NewPos = 0;
1416
1417 for (unsigned i = 0; i < Constraints.size(); ++i) {
1418 Constraint &C = Constraints[i];
1419 if (C.Type == Constraint::AddressOf) {
1420 GraphNodes[C.Src].AddressTaken = true;
1421 }
1422 }
1423 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1424 unsigned Pos = NewPos++;
1425 Translate[i] = Pos;
1426 NewGraphNodes.push_back(GraphNodes[i]);
1427 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1428 }
1429
1430 // I believe this ends up being faster than making two vectors and splicing
1431 // them.
1432 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1433 if (GraphNodes[i].AddressTaken) {
1434 unsigned Pos = NewPos++;
1435 Translate[i] = Pos;
1436 NewGraphNodes.push_back(GraphNodes[i]);
1437 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1438 }
1439 }
1440
1441 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1442 if (!GraphNodes[i].AddressTaken) {
1443 unsigned Pos = NewPos++;
1444 Translate[i] = Pos;
1445 NewGraphNodes.push_back(GraphNodes[i]);
1446 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1447 }
1448 }
1449
1450 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1451 Iter != ValueNodes.end();
1452 ++Iter)
1453 Iter->second = Translate[Iter->second];
1454
1455 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1456 Iter != ObjectNodes.end();
1457 ++Iter)
1458 Iter->second = Translate[Iter->second];
1459
1460 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1461 Iter != ReturnNodes.end();
1462 ++Iter)
1463 Iter->second = Translate[Iter->second];
1464
1465 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1466 Iter != VarargNodes.end();
1467 ++Iter)
1468 Iter->second = Translate[Iter->second];
1469
1470 for (unsigned i = 0; i < Constraints.size(); ++i) {
1471 Constraint &C = Constraints[i];
1472 C.Src = Translate[C.Src];
1473 C.Dest = Translate[C.Dest];
1474 }
1475
1476 GraphNodes.swap(NewGraphNodes);
1477#undef DEBUG_TYPE
1478#define DEBUG_TYPE "anders-aa"
1479}
1480
1481/// The technique used here is described in "Exploiting Pointer and Location
1482/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1483/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1484/// and is equivalent to value numbering the collapsed constraint graph without
1485/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1486/// first order pointer dereferences and speed up/reduce memory usage of HU.
1487/// Running both is equivalent to HRU without the iteration
1488/// HVN in more detail:
1489/// Imagine the set of constraints was simply straight line code with no loops
1490/// (we eliminate cycles, so there are no loops), such as:
1491/// E = &D
1492/// E = &C
1493/// E = F
1494/// F = G
1495/// G = F
1496/// Applying value numbering to this code tells us:
1497/// G == F == E
1498///
1499/// For HVN, this is as far as it goes. We assign new value numbers to every
1500/// "address node", and every "reference node".
1501/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1502/// cycle must have the same value number since the = operation is really
1503/// inclusion, not overwrite), and value number nodes we receive points-to sets
1504/// before we value our own node.
1505/// The advantage of HU over HVN is that HU considers the inclusion property, so
1506/// that if you have
1507/// E = &D
1508/// E = &C
1509/// E = F
1510/// F = G
1511/// F = &D
1512/// G = F
1513/// HU will determine that G == F == E. HVN will not, because it cannot prove
1514/// that the points to information ends up being the same because they all
1515/// receive &D from E anyway.
1516
1517void Andersens::HVN() {
1518 DOUT << "Beginning HVN\n";
1519 // Build a predecessor graph. This is like our constraint graph with the
1520 // edges going in the opposite direction, and there are edges for all the
1521 // constraints, instead of just copy constraints. We also build implicit
1522 // edges for constraints are implied but not explicit. I.E for the constraint
1523 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1524 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1525 Constraint &C = Constraints[i];
1526 if (C.Type == Constraint::AddressOf) {
1527 GraphNodes[C.Src].AddressTaken = true;
1528 GraphNodes[C.Src].Direct = false;
1529
1530 // Dest = &src edge
1531 unsigned AdrNode = C.Src + FirstAdrNode;
1532 if (!GraphNodes[C.Dest].PredEdges)
1533 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1534 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1535
1536 // *Dest = src edge
1537 unsigned RefNode = C.Dest + FirstRefNode;
1538 if (!GraphNodes[RefNode].ImplicitPredEdges)
1539 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1540 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1541 } else if (C.Type == Constraint::Load) {
1542 if (C.Offset == 0) {
1543 // dest = *src edge
1544 if (!GraphNodes[C.Dest].PredEdges)
1545 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1546 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1547 } else {
1548 GraphNodes[C.Dest].Direct = false;
1549 }
1550 } else if (C.Type == Constraint::Store) {
1551 if (C.Offset == 0) {
1552 // *dest = src edge
1553 unsigned RefNode = C.Dest + FirstRefNode;
1554 if (!GraphNodes[RefNode].PredEdges)
1555 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1556 GraphNodes[RefNode].PredEdges->set(C.Src);
1557 }
1558 } else {
1559 // Dest = Src edge and *Dest = *Src edge
1560 if (!GraphNodes[C.Dest].PredEdges)
1561 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1562 GraphNodes[C.Dest].PredEdges->set(C.Src);
1563 unsigned RefNode = C.Dest + FirstRefNode;
1564 if (!GraphNodes[RefNode].ImplicitPredEdges)
1565 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1566 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1567 }
1568 }
1569 PEClass = 1;
1570 // Do SCC finding first to condense our predecessor graph
1571 DFSNumber = 0;
1572 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1573 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1574 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1575
1576 for (unsigned i = 0; i < FirstRefNode; ++i) {
1577 unsigned Node = VSSCCRep[i];
1578 if (!Node2Visited[Node])
1579 HVNValNum(Node);
1580 }
1581 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1582 Iter != Set2PEClass.end();
1583 ++Iter)
1584 delete Iter->first;
1585 Set2PEClass.clear();
1586 Node2DFS.clear();
1587 Node2Deleted.clear();
1588 Node2Visited.clear();
1589 DOUT << "Finished HVN\n";
1590
1591}
1592
1593/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1594/// same time because it's easy.
1595void Andersens::HVNValNum(unsigned NodeIndex) {
1596 unsigned MyDFS = DFSNumber++;
1597 Node *N = &GraphNodes[NodeIndex];
1598 Node2Visited[NodeIndex] = true;
1599 Node2DFS[NodeIndex] = MyDFS;
1600
1601 // First process all our explicit edges
1602 if (N->PredEdges)
1603 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1604 Iter != N->PredEdges->end();
1605 ++Iter) {
1606 unsigned j = VSSCCRep[*Iter];
1607 if (!Node2Deleted[j]) {
1608 if (!Node2Visited[j])
1609 HVNValNum(j);
1610 if (Node2DFS[NodeIndex] > Node2DFS[j])
1611 Node2DFS[NodeIndex] = Node2DFS[j];
1612 }
1613 }
1614
1615 // Now process all the implicit edges
1616 if (N->ImplicitPredEdges)
1617 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1618 Iter != N->ImplicitPredEdges->end();
1619 ++Iter) {
1620 unsigned j = VSSCCRep[*Iter];
1621 if (!Node2Deleted[j]) {
1622 if (!Node2Visited[j])
1623 HVNValNum(j);
1624 if (Node2DFS[NodeIndex] > Node2DFS[j])
1625 Node2DFS[NodeIndex] = Node2DFS[j];
1626 }
1627 }
1628
1629 // See if we found any cycles
1630 if (MyDFS == Node2DFS[NodeIndex]) {
1631 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1632 unsigned CycleNodeIndex = SCCStack.top();
1633 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1634 VSSCCRep[CycleNodeIndex] = NodeIndex;
1635 // Unify the nodes
1636 N->Direct &= CycleNode->Direct;
1637
1638 if (CycleNode->PredEdges) {
1639 if (!N->PredEdges)
1640 N->PredEdges = new SparseBitVector<>;
1641 *(N->PredEdges) |= CycleNode->PredEdges;
1642 delete CycleNode->PredEdges;
1643 CycleNode->PredEdges = NULL;
1644 }
1645 if (CycleNode->ImplicitPredEdges) {
1646 if (!N->ImplicitPredEdges)
1647 N->ImplicitPredEdges = new SparseBitVector<>;
1648 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1649 delete CycleNode->ImplicitPredEdges;
1650 CycleNode->ImplicitPredEdges = NULL;
1651 }
1652
1653 SCCStack.pop();
1654 }
1655
1656 Node2Deleted[NodeIndex] = true;
1657
1658 if (!N->Direct) {
1659 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1660 return;
1661 }
1662
1663 // Collect labels of successor nodes
1664 bool AllSame = true;
1665 unsigned First = ~0;
1666 SparseBitVector<> *Labels = new SparseBitVector<>;
1667 bool Used = false;
1668
1669 if (N->PredEdges)
1670 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1671 Iter != N->PredEdges->end();
1672 ++Iter) {
1673 unsigned j = VSSCCRep[*Iter];
1674 unsigned Label = GraphNodes[j].PointerEquivLabel;
1675 // Ignore labels that are equal to us or non-pointers
1676 if (j == NodeIndex || Label == 0)
1677 continue;
1678 if (First == (unsigned)~0)
1679 First = Label;
1680 else if (First != Label)
1681 AllSame = false;
1682 Labels->set(Label);
1683 }
1684
1685 // We either have a non-pointer, a copy of an existing node, or a new node.
1686 // Assign the appropriate pointer equivalence label.
1687 if (Labels->empty()) {
1688 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1689 } else if (AllSame) {
1690 GraphNodes[NodeIndex].PointerEquivLabel = First;
1691 } else {
1692 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1693 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1694 unsigned EquivClass = PEClass++;
1695 Set2PEClass[Labels] = EquivClass;
1696 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1697 Used = true;
1698 }
1699 }
1700 if (!Used)
1701 delete Labels;
1702 } else {
1703 SCCStack.push(NodeIndex);
1704 }
1705}
1706
1707/// The technique used here is described in "Exploiting Pointer and Location
1708/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1709/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1710/// and is equivalent to value numbering the collapsed constraint graph
1711/// including evaluating unions.
1712void Andersens::HU() {
1713 DOUT << "Beginning HU\n";
1714 // Build a predecessor graph. This is like our constraint graph with the
1715 // edges going in the opposite direction, and there are edges for all the
1716 // constraints, instead of just copy constraints. We also build implicit
1717 // edges for constraints are implied but not explicit. I.E for the constraint
1718 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1719 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1720 Constraint &C = Constraints[i];
1721 if (C.Type == Constraint::AddressOf) {
1722 GraphNodes[C.Src].AddressTaken = true;
1723 GraphNodes[C.Src].Direct = false;
1724
1725 GraphNodes[C.Dest].PointsTo->set(C.Src);
1726 // *Dest = src edge
1727 unsigned RefNode = C.Dest + FirstRefNode;
1728 if (!GraphNodes[RefNode].ImplicitPredEdges)
1729 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1730 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1731 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1732 } else if (C.Type == Constraint::Load) {
1733 if (C.Offset == 0) {
1734 // dest = *src edge
1735 if (!GraphNodes[C.Dest].PredEdges)
1736 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1737 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1738 } else {
1739 GraphNodes[C.Dest].Direct = false;
1740 }
1741 } else if (C.Type == Constraint::Store) {
1742 if (C.Offset == 0) {
1743 // *dest = src edge
1744 unsigned RefNode = C.Dest + FirstRefNode;
1745 if (!GraphNodes[RefNode].PredEdges)
1746 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1747 GraphNodes[RefNode].PredEdges->set(C.Src);
1748 }
1749 } else {
1750 // Dest = Src edge and *Dest = *Src edg
1751 if (!GraphNodes[C.Dest].PredEdges)
1752 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1753 GraphNodes[C.Dest].PredEdges->set(C.Src);
1754 unsigned RefNode = C.Dest + FirstRefNode;
1755 if (!GraphNodes[RefNode].ImplicitPredEdges)
1756 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1757 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1758 }
1759 }
1760 PEClass = 1;
1761 // Do SCC finding first to condense our predecessor graph
1762 DFSNumber = 0;
1763 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1764 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1765 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1766
1767 for (unsigned i = 0; i < FirstRefNode; ++i) {
1768 if (FindNode(i) == i) {
1769 unsigned Node = VSSCCRep[i];
1770 if (!Node2Visited[Node])
1771 Condense(Node);
1772 }
1773 }
1774
1775 // Reset tables for actual labeling
1776 Node2DFS.clear();
1777 Node2Visited.clear();
1778 Node2Deleted.clear();
1779 // Pre-grow our densemap so that we don't get really bad behavior
1780 Set2PEClass.resize(GraphNodes.size());
1781
1782 // Visit the condensed graph and generate pointer equivalence labels.
1783 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1784 for (unsigned i = 0; i < FirstRefNode; ++i) {
1785 if (FindNode(i) == i) {
1786 unsigned Node = VSSCCRep[i];
1787 if (!Node2Visited[Node])
1788 HUValNum(Node);
1789 }
1790 }
1791 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1792 Set2PEClass.clear();
1793 DOUT << "Finished HU\n";
1794}
1795
1796
1797/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1798void Andersens::Condense(unsigned NodeIndex) {
1799 unsigned MyDFS = DFSNumber++;
1800 Node *N = &GraphNodes[NodeIndex];
1801 Node2Visited[NodeIndex] = true;
1802 Node2DFS[NodeIndex] = MyDFS;
1803
1804 // First process all our explicit edges
1805 if (N->PredEdges)
1806 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1807 Iter != N->PredEdges->end();
1808 ++Iter) {
1809 unsigned j = VSSCCRep[*Iter];
1810 if (!Node2Deleted[j]) {
1811 if (!Node2Visited[j])
1812 Condense(j);
1813 if (Node2DFS[NodeIndex] > Node2DFS[j])
1814 Node2DFS[NodeIndex] = Node2DFS[j];
1815 }
1816 }
1817
1818 // Now process all the implicit edges
1819 if (N->ImplicitPredEdges)
1820 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1821 Iter != N->ImplicitPredEdges->end();
1822 ++Iter) {
1823 unsigned j = VSSCCRep[*Iter];
1824 if (!Node2Deleted[j]) {
1825 if (!Node2Visited[j])
1826 Condense(j);
1827 if (Node2DFS[NodeIndex] > Node2DFS[j])
1828 Node2DFS[NodeIndex] = Node2DFS[j];
1829 }
1830 }
1831
1832 // See if we found any cycles
1833 if (MyDFS == Node2DFS[NodeIndex]) {
1834 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1835 unsigned CycleNodeIndex = SCCStack.top();
1836 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1837 VSSCCRep[CycleNodeIndex] = NodeIndex;
1838 // Unify the nodes
1839 N->Direct &= CycleNode->Direct;
1840
1841 *(N->PointsTo) |= CycleNode->PointsTo;
1842 delete CycleNode->PointsTo;
1843 CycleNode->PointsTo = NULL;
1844 if (CycleNode->PredEdges) {
1845 if (!N->PredEdges)
1846 N->PredEdges = new SparseBitVector<>;
1847 *(N->PredEdges) |= CycleNode->PredEdges;
1848 delete CycleNode->PredEdges;
1849 CycleNode->PredEdges = NULL;
1850 }
1851 if (CycleNode->ImplicitPredEdges) {
1852 if (!N->ImplicitPredEdges)
1853 N->ImplicitPredEdges = new SparseBitVector<>;
1854 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1855 delete CycleNode->ImplicitPredEdges;
1856 CycleNode->ImplicitPredEdges = NULL;
1857 }
1858 SCCStack.pop();
1859 }
1860
1861 Node2Deleted[NodeIndex] = true;
1862
1863 // Set up number of incoming edges for other nodes
1864 if (N->PredEdges)
1865 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1866 Iter != N->PredEdges->end();
1867 ++Iter)
1868 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1869 } else {
1870 SCCStack.push(NodeIndex);
1871 }
1872}
1873
1874void Andersens::HUValNum(unsigned NodeIndex) {
1875 Node *N = &GraphNodes[NodeIndex];
1876 Node2Visited[NodeIndex] = true;
1877
1878 // Eliminate dereferences of non-pointers for those non-pointers we have
1879 // already identified. These are ref nodes whose non-ref node:
1880 // 1. Has already been visited determined to point to nothing (and thus, a
1881 // dereference of it must point to nothing)
1882 // 2. Any direct node with no predecessor edges in our graph and with no
1883 // points-to set (since it can't point to anything either, being that it
1884 // receives no points-to sets and has none).
1885 if (NodeIndex >= FirstRefNode) {
1886 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1887 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1888 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1889 && GraphNodes[j].PointsTo->empty())){
1890 return;
1891 }
1892 }
1893 // Process all our explicit edges
1894 if (N->PredEdges)
1895 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1896 Iter != N->PredEdges->end();
1897 ++Iter) {
1898 unsigned j = VSSCCRep[*Iter];
1899 if (!Node2Visited[j])
1900 HUValNum(j);
1901
1902 // If this edge turned out to be the same as us, or got no pointer
1903 // equivalence label (and thus points to nothing) , just decrement our
1904 // incoming edges and continue.
1905 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1906 --GraphNodes[j].NumInEdges;
1907 continue;
1908 }
1909
1910 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1911
1912 // If we didn't end up storing this in the hash, and we're done with all
1913 // the edges, we don't need the points-to set anymore.
1914 --GraphNodes[j].NumInEdges;
1915 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1916 delete GraphNodes[j].PointsTo;
1917 GraphNodes[j].PointsTo = NULL;
1918 }
1919 }
1920 // If this isn't a direct node, generate a fresh variable.
1921 if (!N->Direct) {
1922 N->PointsTo->set(FirstRefNode + NodeIndex);
1923 }
1924
1925 // See If we have something equivalent to us, if not, generate a new
1926 // equivalence class.
1927 if (N->PointsTo->empty()) {
1928 delete N->PointsTo;
1929 N->PointsTo = NULL;
1930 } else {
1931 if (N->Direct) {
1932 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1933 if (N->PointerEquivLabel == 0) {
1934 unsigned EquivClass = PEClass++;
1935 N->StoredInHash = true;
1936 Set2PEClass[N->PointsTo] = EquivClass;
1937 N->PointerEquivLabel = EquivClass;
1938 }
1939 } else {
1940 N->PointerEquivLabel = PEClass++;
1941 }
1942 }
1943}
1944
1945/// Rewrite our list of constraints so that pointer equivalent nodes are
1946/// replaced by their the pointer equivalence class representative.
1947void Andersens::RewriteConstraints() {
1948 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001949 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001950
1951 PEClass2Node.clear();
1952 PENLEClass2Node.clear();
1953
1954 // We may have from 1 to Graphnodes + 1 equivalence classes.
1955 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1956 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1957
1958 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1959 // nodes, and rewriting constraints to use the representative nodes.
1960 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1961 Constraint &C = Constraints[i];
1962 unsigned RHSNode = FindNode(C.Src);
1963 unsigned LHSNode = FindNode(C.Dest);
1964 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1965 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1966
1967 // First we try to eliminate constraints for things we can prove don't point
1968 // to anything.
1969 if (LHSLabel == 0) {
1970 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1971 DOUT << " is a non-pointer, ignoring constraint.\n";
1972 continue;
1973 }
1974 if (RHSLabel == 0) {
1975 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1976 DOUT << " is a non-pointer, ignoring constraint.\n";
1977 continue;
1978 }
1979 // This constraint may be useless, and it may become useless as we translate
1980 // it.
1981 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1982 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001983
Daniel Berlind81ccc22007-09-24 19:45:49 +00001984 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1985 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001986 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001987 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001988 continue;
1989
Chris Lattnerbe207732007-09-30 00:47:20 +00001990 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001991 NewConstraints.push_back(C);
1992 }
1993 Constraints.swap(NewConstraints);
1994 PEClass2Node.clear();
1995}
1996
1997/// See if we have a node that is pointer equivalent to the one being asked
1998/// about, and if so, unite them and return the equivalent node. Otherwise,
1999/// return the original node.
2000unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
2001 unsigned NodeLabel) {
2002 if (!GraphNodes[NodeIndex].AddressTaken) {
2003 if (PEClass2Node[NodeLabel] != -1) {
2004 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002005 // We specifically request that Union-By-Rank not be used so that
2006 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
2007 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002008 } else {
2009 PEClass2Node[NodeLabel] = NodeIndex;
2010 PENLEClass2Node[NodeLabel] = NodeIndex;
2011 }
2012 } else if (PENLEClass2Node[NodeLabel] == -1) {
2013 PENLEClass2Node[NodeLabel] = NodeIndex;
2014 }
2015
2016 return NodeIndex;
2017}
2018
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002019void Andersens::PrintLabels() const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002020 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2021 if (i < FirstRefNode) {
2022 PrintNode(&GraphNodes[i]);
2023 } else if (i < FirstAdrNode) {
2024 DOUT << "REF(";
2025 PrintNode(&GraphNodes[i-FirstRefNode]);
2026 DOUT <<")";
2027 } else {
2028 DOUT << "ADR(";
2029 PrintNode(&GraphNodes[i-FirstAdrNode]);
2030 DOUT <<")";
2031 }
2032
2033 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2034 << " and SCC rep " << VSSCCRep[i]
2035 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2036 << "\n";
2037 }
2038}
2039
Daniel Berlinc864edb2008-03-05 19:31:47 +00002040/// The technique used here is described in "The Ant and the
2041/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2042/// Lines of Code. In Programming Language Design and Implementation
2043/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2044/// Detection) algorithm. It is called a hybrid because it performs an
2045/// offline analysis and uses its results during the solving (online)
2046/// phase. This is just the offline portion; the results of this
2047/// operation are stored in SDT and are later used in SolveContraints()
2048/// and UniteNodes().
2049void Andersens::HCD() {
2050 DOUT << "Starting HCD.\n";
2051 HCDSCCRep.resize(GraphNodes.size());
2052
2053 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2054 GraphNodes[i].Edges = new SparseBitVector<>;
2055 HCDSCCRep[i] = i;
2056 }
2057
2058 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2059 Constraint &C = Constraints[i];
2060 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2061 if (C.Type == Constraint::AddressOf) {
2062 continue;
2063 } else if (C.Type == Constraint::Load) {
2064 if( C.Offset == 0 )
2065 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2066 } else if (C.Type == Constraint::Store) {
2067 if( C.Offset == 0 )
2068 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2069 } else {
2070 GraphNodes[C.Dest].Edges->set(C.Src);
2071 }
2072 }
2073
2074 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2075 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2076 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2077 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2078
2079 DFSNumber = 0;
2080 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2081 unsigned Node = HCDSCCRep[i];
2082 if (!Node2Deleted[Node])
2083 Search(Node);
2084 }
2085
2086 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2087 if (GraphNodes[i].Edges != NULL) {
2088 delete GraphNodes[i].Edges;
2089 GraphNodes[i].Edges = NULL;
2090 }
2091
2092 while( !SCCStack.empty() )
2093 SCCStack.pop();
2094
2095 Node2DFS.clear();
2096 Node2Visited.clear();
2097 Node2Deleted.clear();
2098 HCDSCCRep.clear();
2099 DOUT << "HCD complete.\n";
2100}
2101
2102// Component of HCD:
2103// Use Nuutila's variant of Tarjan's algorithm to detect
2104// Strongly-Connected Components (SCCs). For non-trivial SCCs
2105// containing ref nodes, insert the appropriate information in SDT.
2106void Andersens::Search(unsigned Node) {
2107 unsigned MyDFS = DFSNumber++;
2108
2109 Node2Visited[Node] = true;
2110 Node2DFS[Node] = MyDFS;
2111
2112 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2113 End = GraphNodes[Node].Edges->end();
2114 Iter != End;
2115 ++Iter) {
2116 unsigned J = HCDSCCRep[*Iter];
2117 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2118 if (!Node2Deleted[J]) {
2119 if (!Node2Visited[J])
2120 Search(J);
2121 if (Node2DFS[Node] > Node2DFS[J])
2122 Node2DFS[Node] = Node2DFS[J];
2123 }
2124 }
2125
2126 if( MyDFS != Node2DFS[Node] ) {
2127 SCCStack.push(Node);
2128 return;
2129 }
2130
2131 // This node is the root of a SCC, so process it.
2132 //
2133 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2134 // node, we place this SCC into SDT. We unite the nodes in any case.
2135 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2136 SparseBitVector<> SCC;
2137
2138 SCC.set(Node);
2139
2140 bool Ref = (Node >= FirstRefNode);
2141
2142 Node2Deleted[Node] = true;
2143
2144 do {
2145 unsigned P = SCCStack.top(); SCCStack.pop();
2146 Ref |= (P >= FirstRefNode);
2147 SCC.set(P);
2148 HCDSCCRep[P] = Node;
2149 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2150
2151 if (Ref) {
2152 unsigned Rep = SCC.find_first();
2153 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2154
2155 SparseBitVector<>::iterator i = SCC.begin();
2156
2157 // Skip over the non-ref nodes
2158 while( *i < FirstRefNode )
2159 ++i;
2160
2161 while( i != SCC.end() )
2162 SDT[ (*i++) - FirstRefNode ] = Rep;
2163 }
2164 }
2165}
2166
2167
Daniel Berlind81ccc22007-09-24 19:45:49 +00002168/// Optimize the constraints by performing offline variable substitution and
2169/// other optimizations.
2170void Andersens::OptimizeConstraints() {
2171 DOUT << "Beginning constraint optimization\n";
2172
Daniel Berlinc864edb2008-03-05 19:31:47 +00002173 SDTActive = false;
2174
Daniel Berlind81ccc22007-09-24 19:45:49 +00002175 // Function related nodes need to stay in the same relative position and can't
2176 // be location equivalent.
2177 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2178 Iter != MaxK.end();
2179 ++Iter) {
2180 for (unsigned i = Iter->first;
2181 i != Iter->first + Iter->second;
2182 ++i) {
2183 GraphNodes[i].AddressTaken = true;
2184 GraphNodes[i].Direct = false;
2185 }
2186 }
2187
2188 ClumpAddressTaken();
2189 FirstRefNode = GraphNodes.size();
2190 FirstAdrNode = FirstRefNode + GraphNodes.size();
2191 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2192 Node(false));
2193 VSSCCRep.resize(GraphNodes.size());
2194 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2195 VSSCCRep[i] = i;
2196 }
2197 HVN();
2198 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2199 Node *N = &GraphNodes[i];
2200 delete N->PredEdges;
2201 N->PredEdges = NULL;
2202 delete N->ImplicitPredEdges;
2203 N->ImplicitPredEdges = NULL;
2204 }
2205#undef DEBUG_TYPE
2206#define DEBUG_TYPE "anders-aa-labels"
2207 DEBUG(PrintLabels());
2208#undef DEBUG_TYPE
2209#define DEBUG_TYPE "anders-aa"
2210 RewriteConstraints();
2211 // Delete the adr nodes.
2212 GraphNodes.resize(FirstRefNode * 2);
2213
2214 // Now perform HU
2215 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2216 Node *N = &GraphNodes[i];
2217 if (FindNode(i) == i) {
2218 N->PointsTo = new SparseBitVector<>;
2219 N->PointedToBy = new SparseBitVector<>;
2220 // Reset our labels
2221 }
2222 VSSCCRep[i] = i;
2223 N->PointerEquivLabel = 0;
2224 }
2225 HU();
2226#undef DEBUG_TYPE
2227#define DEBUG_TYPE "anders-aa-labels"
2228 DEBUG(PrintLabels());
2229#undef DEBUG_TYPE
2230#define DEBUG_TYPE "anders-aa"
2231 RewriteConstraints();
2232 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2233 if (FindNode(i) == i) {
2234 Node *N = &GraphNodes[i];
2235 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002236 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002237 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002238 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002239 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002240 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002241 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002242 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002243 }
2244 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002245
2246 // perform Hybrid Cycle Detection (HCD)
2247 HCD();
2248 SDTActive = true;
2249
2250 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002251 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002252
2253 // HCD complete.
2254
Daniel Berlind81ccc22007-09-24 19:45:49 +00002255 DOUT << "Finished constraint optimization\n";
2256 FirstRefNode = 0;
2257 FirstAdrNode = 0;
2258}
2259
2260/// Unite pointer but not location equivalent variables, now that the constraint
2261/// graph is built.
2262void Andersens::UnitePointerEquivalences() {
2263 DOUT << "Uniting remaining pointer equivalences\n";
2264 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002265 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002266 unsigned Label = GraphNodes[i].PointerEquivLabel;
2267
2268 if (Label && PENLEClass2Node[Label] != -1)
2269 UniteNodes(i, PENLEClass2Node[Label]);
2270 }
2271 }
2272 DOUT << "Finished remaining pointer equivalences\n";
2273 PENLEClass2Node.clear();
2274}
2275
2276/// Create the constraint graph used for solving points-to analysis.
2277///
Daniel Berlinaad15882007-09-16 21:45:02 +00002278void Andersens::CreateConstraintGraph() {
2279 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2280 Constraint &C = Constraints[i];
2281 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2282 if (C.Type == Constraint::AddressOf)
2283 GraphNodes[C.Dest].PointsTo->set(C.Src);
2284 else if (C.Type == Constraint::Load)
2285 GraphNodes[C.Src].Constraints.push_back(C);
2286 else if (C.Type == Constraint::Store)
2287 GraphNodes[C.Dest].Constraints.push_back(C);
2288 else if (C.Offset != 0)
2289 GraphNodes[C.Src].Constraints.push_back(C);
2290 else
2291 GraphNodes[C.Src].Edges->set(C.Dest);
2292 }
2293}
2294
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002295// Perform DFS and cycle detection.
2296bool Andersens::QueryNode(unsigned Node) {
2297 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002298 unsigned OurDFS = ++DFSNumber;
2299 SparseBitVector<> ToErase;
2300 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002301 Tarjan2DFS[Node] = OurDFS;
2302
2303 // Changed denotes a change from a recursive call that we will bubble up.
2304 // Merged is set if we actually merge a node ourselves.
2305 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002306
2307 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2308 bi != GraphNodes[Node].Edges->end();
2309 ++bi) {
2310 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002311 // If this edge points to a non-representative node but we are
2312 // already planning to add an edge to its representative, we have no
2313 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002314 if (RepNode != *bi && NewEdges.test(RepNode)){
2315 ToErase.set(*bi);
2316 continue;
2317 }
2318
2319 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002320 if (!Tarjan2Deleted[RepNode]){
2321 if (Tarjan2DFS[RepNode] == 0) {
2322 Changed |= QueryNode(RepNode);
2323 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002324 RepNode = FindNode(RepNode);
2325 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002326 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2327 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002328 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002329
2330 // We may have just discovered that this node is part of a cycle, in
2331 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002332 if (RepNode != *bi) {
2333 ToErase.set(*bi);
2334 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002335 }
2336 }
2337
Daniel Berlinaad15882007-09-16 21:45:02 +00002338 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2339 GraphNodes[Node].Edges |= NewEdges;
2340
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002341 // If this node is a root of a non-trivial SCC, place it on our
2342 // worklist to be processed.
2343 if (OurDFS == Tarjan2DFS[Node]) {
2344 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2345 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002346
2347 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002348 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002349 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002350 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002351
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002352 if (Merged)
2353 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002354 } else {
2355 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002356 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002357
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002358 return(Changed | Merged);
2359}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002360
2361/// SolveConstraints - This stage iteratively processes the constraints list
2362/// propagating constraints (adding edges to the Nodes in the points-to graph)
2363/// until a fixed point is reached.
2364///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002365/// We use a variant of the technique called "Lazy Cycle Detection", which is
2366/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2367/// Analysis for Millions of Lines of Code. In Programming Language Design and
2368/// Implementation (PLDI), June 2007."
2369/// The paper describes performing cycle detection one node at a time, which can
2370/// be expensive if there are no cycles, but there are long chains of nodes that
2371/// it heuristically believes are cycles (because it will DFS from each node
2372/// without state from previous nodes).
2373/// Instead, we use the heuristic to build a worklist of nodes to check, then
2374/// cycle detect them all at the same time to do this more cheaply. This
2375/// catches cycles slightly later than the original technique did, but does it
2376/// make significantly cheaper.
2377
Chris Lattnere995a2a2004-05-23 21:00:47 +00002378void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002379 CurrWL = &w1;
2380 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002381
Daniel Berlind81ccc22007-09-24 19:45:49 +00002382 OptimizeConstraints();
2383#undef DEBUG_TYPE
2384#define DEBUG_TYPE "anders-aa-constraints"
2385 DEBUG(PrintConstraints());
2386#undef DEBUG_TYPE
2387#define DEBUG_TYPE "anders-aa"
2388
Daniel Berlinaad15882007-09-16 21:45:02 +00002389 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2390 Node *N = &GraphNodes[i];
2391 N->PointsTo = new SparseBitVector<>;
2392 N->OldPointsTo = new SparseBitVector<>;
2393 N->Edges = new SparseBitVector<>;
2394 }
2395 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002396 UnitePointerEquivalences();
2397 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002398 Node2DFS.clear();
2399 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002400 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2401 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2402 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002403 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2404 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2405
2406 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002407 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002408 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002409
2410 // Add to work list if it's a representative and can contribute to the
2411 // calculation right now.
2412 if (INode->isRep() && !INode->PointsTo->empty()
2413 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2414 INode->Stamp();
2415 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002416 }
2417 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002418 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002419#if !FULL_UNIVERSAL
2420 // "Rep and special variables" - in order for HCD to maintain conservative
2421 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2422 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2423 // the analysis - it's ok to add edges from the special nodes, but never
2424 // *to* the special nodes.
2425 std::vector<unsigned int> RSV;
2426#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002427 while( !CurrWL->empty() ) {
2428 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002429
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002430 Node* CurrNode;
2431 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002432
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002433 // Actual cycle checking code. We cycle check all of the lazy cycle
2434 // candidates from the last iteration in one go.
2435 if (!TarjanWL.empty()) {
2436 DFSNumber = 0;
2437
2438 Tarjan2DFS.clear();
2439 Tarjan2Deleted.clear();
2440 while (!TarjanWL.empty()) {
2441 unsigned int ToTarjan = TarjanWL.front();
2442 TarjanWL.pop();
2443 if (!Tarjan2Deleted[ToTarjan]
2444 && GraphNodes[ToTarjan].isRep()
2445 && Tarjan2DFS[ToTarjan] == 0)
2446 QueryNode(ToTarjan);
2447 }
2448 }
2449
2450 // Add to work list if it's a representative and can contribute to the
2451 // calculation right now.
2452 while( (CurrNode = CurrWL->pop()) != NULL ) {
2453 CurrNodeIndex = CurrNode - &GraphNodes[0];
2454 CurrNode->Stamp();
2455
2456
Daniel Berlinaad15882007-09-16 21:45:02 +00002457 // Figure out the changed points to bits
2458 SparseBitVector<> CurrPointsTo;
2459 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2460 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002461 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002462 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002463
Daniel Berlinaad15882007-09-16 21:45:02 +00002464 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002465
2466 // Check the offline-computed equivalencies from HCD.
2467 bool SCC = false;
2468 unsigned Rep;
2469
2470 if (SDT[CurrNodeIndex] >= 0) {
2471 SCC = true;
2472 Rep = FindNode(SDT[CurrNodeIndex]);
2473
2474#if !FULL_UNIVERSAL
2475 RSV.clear();
2476#endif
2477 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2478 bi != CurrPointsTo.end(); ++bi) {
2479 unsigned Node = FindNode(*bi);
2480#if !FULL_UNIVERSAL
2481 if (Node < NumberSpecialNodes) {
2482 RSV.push_back(Node);
2483 continue;
2484 }
2485#endif
2486 Rep = UniteNodes(Rep,Node);
2487 }
2488#if !FULL_UNIVERSAL
2489 RSV.push_back(Rep);
2490#endif
2491
2492 NextWL->insert(&GraphNodes[Rep]);
2493
2494 if ( ! CurrNode->isRep() )
2495 continue;
2496 }
2497
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002498 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002499
Daniel Berlinaad15882007-09-16 21:45:02 +00002500 /* Now process the constraints for this node. */
2501 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2502 li != CurrNode->Constraints.end(); ) {
2503 li->Src = FindNode(li->Src);
2504 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002505
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002506 // Delete redundant constraints
2507 if( Seen.count(*li) ) {
2508 std::list<Constraint>::iterator lk = li; li++;
2509
2510 CurrNode->Constraints.erase(lk);
2511 ++NumErased;
2512 continue;
2513 }
2514 Seen.insert(*li);
2515
Daniel Berlinaad15882007-09-16 21:45:02 +00002516 // Src and Dest will be the vars we are going to process.
2517 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002518 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002519 // Load constraints say that every member of our RHS solution has K
2520 // added to it, and that variable gets an edge to LHS. We also union
2521 // RHS+K's solution into the LHS solution.
2522 // Store constraints say that every member of our LHS solution has K
2523 // added to it, and that variable gets an edge from RHS. We also union
2524 // RHS's solution into the LHS+K solution.
2525 unsigned *Src;
2526 unsigned *Dest;
2527 unsigned K = li->Offset;
2528 unsigned CurrMember;
2529 if (li->Type == Constraint::Load) {
2530 Src = &CurrMember;
2531 Dest = &li->Dest;
2532 } else if (li->Type == Constraint::Store) {
2533 Src = &li->Src;
2534 Dest = &CurrMember;
2535 } else {
2536 // TODO Handle offseted copy constraint
2537 li++;
2538 continue;
2539 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002540
2541 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002542 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002543 // involves pointers; if so, remove the redundant constraints).
2544 if( SCC && K == 0 ) {
2545#if FULL_UNIVERSAL
2546 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002547
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002548 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2549 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2550 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002551#else
2552 for (unsigned i=0; i < RSV.size(); ++i) {
2553 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002554
Daniel Berlinc864edb2008-03-05 19:31:47 +00002555 if (*Dest < NumberSpecialNodes)
2556 continue;
2557 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2558 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2559 NextWL->insert(&GraphNodes[*Dest]);
2560 }
2561#endif
2562 // since all future elements of the points-to set will be
2563 // equivalent to the current ones, the complex constraints
2564 // become redundant.
2565 //
2566 std::list<Constraint>::iterator lk = li; li++;
2567#if !FULL_UNIVERSAL
2568 // In this case, we can still erase the constraints when the
2569 // elements of the points-to sets are referenced by *Dest,
2570 // but not when they are referenced by *Src (i.e. for a Load
2571 // constraint). This is because if another special variable is
2572 // put into the points-to set later, we still need to add the
2573 // new edge from that special variable.
2574 if( lk->Type != Constraint::Load)
2575#endif
2576 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2577 } else {
2578 const SparseBitVector<> &Solution = CurrPointsTo;
2579
2580 for (SparseBitVector<>::iterator bi = Solution.begin();
2581 bi != Solution.end();
2582 ++bi) {
2583 CurrMember = *bi;
2584
2585 // Need to increment the member by K since that is where we are
2586 // supposed to copy to/from. Note that in positive weight cycles,
2587 // which occur in address taking of fields, K can go past
2588 // MaxK[CurrMember] elements, even though that is all it could point
2589 // to.
2590 if (K > 0 && K > MaxK[CurrMember])
2591 continue;
2592 else
2593 CurrMember = FindNode(CurrMember + K);
2594
2595 // Add an edge to the graph, so we can just do regular
2596 // bitmap ior next time. It may also let us notice a cycle.
2597#if !FULL_UNIVERSAL
2598 if (*Dest < NumberSpecialNodes)
2599 continue;
2600#endif
2601 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2602 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2603 NextWL->insert(&GraphNodes[*Dest]);
2604
2605 }
2606 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002607 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002608 }
2609 SparseBitVector<> NewEdges;
2610 SparseBitVector<> ToErase;
2611
2612 // Now all we have left to do is propagate points-to info along the
2613 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002614 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2615 bi != CurrNode->Edges->end();
2616 ++bi) {
2617
2618 unsigned DestVar = *bi;
2619 unsigned Rep = FindNode(DestVar);
2620
Bill Wendlingf059deb2008-02-26 10:51:52 +00002621 // If we ended up with this node as our destination, or we've already
2622 // got an edge for the representative, delete the current edge.
2623 if (Rep == CurrNodeIndex ||
2624 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002625 ToErase.set(DestVar);
2626 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002627 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002628
Bill Wendlingf059deb2008-02-26 10:51:52 +00002629 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002630
2631 // This is where we do lazy cycle detection.
2632 // If this is a cycle candidate (equal points-to sets and this
2633 // particular edge has not been cycle-checked previously), add to the
2634 // list to check for cycles on the next iteration.
2635 if (!EdgesChecked.count(edge) &&
2636 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2637 EdgesChecked.insert(edge);
2638 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002639 }
2640 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002641#if !FULL_UNIVERSAL
2642 if (Rep >= NumberSpecialNodes)
2643#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002644 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002645 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002646 }
2647 // If this edge's destination was collapsed, rewrite the edge.
2648 if (Rep != DestVar) {
2649 ToErase.set(DestVar);
2650 NewEdges.set(Rep);
2651 }
2652 }
2653 CurrNode->Edges->intersectWithComplement(ToErase);
2654 CurrNode->Edges |= NewEdges;
2655 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002656
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002657 // Switch to other work list.
2658 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2659 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002660
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002661
Daniel Berlinaad15882007-09-16 21:45:02 +00002662 Node2DFS.clear();
2663 Node2Deleted.clear();
2664 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2665 Node *N = &GraphNodes[i];
2666 delete N->OldPointsTo;
2667 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002668 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002669 SDTActive = false;
2670 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002671}
2672
Daniel Berlinaad15882007-09-16 21:45:02 +00002673//===----------------------------------------------------------------------===//
2674// Union-Find
2675//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002676
Daniel Berlinaad15882007-09-16 21:45:02 +00002677// Unite nodes First and Second, returning the one which is now the
2678// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002679unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2680 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002681 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2682 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002683
Daniel Berlinaad15882007-09-16 21:45:02 +00002684 Node *FirstNode = &GraphNodes[First];
2685 Node *SecondNode = &GraphNodes[Second];
2686
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002687 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002688 "Trying to unite two non-representative nodes!");
2689 if (First == Second)
2690 return First;
2691
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002692 if (UnionByRank) {
2693 int RankFirst = (int) FirstNode ->NodeRep;
2694 int RankSecond = (int) SecondNode->NodeRep;
2695
2696 // Rank starts at -1 and gets decremented as it increases.
2697 // Translation: higher rank, lower NodeRep value, which is always negative.
2698 if (RankFirst > RankSecond) {
2699 unsigned t = First; First = Second; Second = t;
2700 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2701 } else if (RankFirst == RankSecond) {
2702 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2703 }
2704 }
2705
Daniel Berlinaad15882007-09-16 21:45:02 +00002706 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002707#if !FULL_UNIVERSAL
2708 if (First >= NumberSpecialNodes)
2709#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002710 if (FirstNode->PointsTo && SecondNode->PointsTo)
2711 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2712 if (FirstNode->Edges && SecondNode->Edges)
2713 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002714 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002715 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2716 SecondNode->Constraints);
2717 if (FirstNode->OldPointsTo) {
2718 delete FirstNode->OldPointsTo;
2719 FirstNode->OldPointsTo = new SparseBitVector<>;
2720 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002721
2722 // Destroy interesting parts of the merged-from node.
2723 delete SecondNode->OldPointsTo;
2724 delete SecondNode->Edges;
2725 delete SecondNode->PointsTo;
2726 SecondNode->Edges = NULL;
2727 SecondNode->PointsTo = NULL;
2728 SecondNode->OldPointsTo = NULL;
2729
2730 NumUnified++;
2731 DOUT << "Unified Node ";
2732 DEBUG(PrintNode(FirstNode));
2733 DOUT << " and Node ";
2734 DEBUG(PrintNode(SecondNode));
2735 DOUT << "\n";
2736
Daniel Berlinc864edb2008-03-05 19:31:47 +00002737 if (SDTActive)
Duncan Sands43e2a032008-05-27 11:50:51 +00002738 if (SDT[Second] >= 0) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002739 if (SDT[First] < 0)
2740 SDT[First] = SDT[Second];
2741 else {
2742 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2743 First = FindNode(First);
2744 }
Duncan Sands43e2a032008-05-27 11:50:51 +00002745 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002746
Daniel Berlinaad15882007-09-16 21:45:02 +00002747 return First;
2748}
2749
2750// Find the index into GraphNodes of the node representing Node, performing
2751// path compression along the way
2752unsigned Andersens::FindNode(unsigned NodeIndex) {
2753 assert (NodeIndex < GraphNodes.size()
2754 && "Attempting to find a node that can't exist");
2755 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002756 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002757 return NodeIndex;
2758 else
2759 return (N->NodeRep = FindNode(N->NodeRep));
2760}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002761
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002762// Find the index into GraphNodes of the node representing Node,
2763// don't perform path compression along the way (for Print)
2764unsigned Andersens::FindNode(unsigned NodeIndex) const {
2765 assert (NodeIndex < GraphNodes.size()
2766 && "Attempting to find a node that can't exist");
2767 const Node *N = &GraphNodes[NodeIndex];
2768 if (N->isRep())
2769 return NodeIndex;
2770 else
2771 return FindNode(N->NodeRep);
2772}
2773
Chris Lattnere995a2a2004-05-23 21:00:47 +00002774//===----------------------------------------------------------------------===//
2775// Debugging Output
2776//===----------------------------------------------------------------------===//
2777
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002778void Andersens::PrintNode(const Node *N) const {
Chris Lattnere995a2a2004-05-23 21:00:47 +00002779 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002780 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002781 return;
2782 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002783 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002784 return;
2785 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002786 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002787 return;
2788 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002789 if (!N->getValue()) {
2790 cerr << "artificial" << (intptr_t) N;
2791 return;
2792 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002793
2794 assert(N->getValue() != 0 && "Never set node label!");
2795 Value *V = N->getValue();
2796 if (Function *F = dyn_cast<Function>(V)) {
2797 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002798 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002799 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002800 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002801 } else if (F->getFunctionType()->isVarArg() &&
2802 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002803 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002804 return;
2805 }
2806 }
2807
2808 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002809 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002810 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002811 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002812
2813 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002814 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002815 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002816 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002817
2818 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002819 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002820 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002821}
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002822void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002823 if (C.Type == Constraint::Store) {
2824 cerr << "*";
2825 if (C.Offset != 0)
2826 cerr << "(";
2827 }
2828 PrintNode(&GraphNodes[C.Dest]);
2829 if (C.Type == Constraint::Store && C.Offset != 0)
2830 cerr << " + " << C.Offset << ")";
2831 cerr << " = ";
2832 if (C.Type == Constraint::Load) {
2833 cerr << "*";
2834 if (C.Offset != 0)
2835 cerr << "(";
2836 }
2837 else if (C.Type == Constraint::AddressOf)
2838 cerr << "&";
2839 PrintNode(&GraphNodes[C.Src]);
2840 if (C.Offset != 0 && C.Type != Constraint::Store)
2841 cerr << " + " << C.Offset;
2842 if (C.Type == Constraint::Load && C.Offset != 0)
2843 cerr << ")";
2844 cerr << "\n";
2845}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002846
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002847void Andersens::PrintConstraints() const {
Bill Wendlinge8156192006-12-07 01:30:32 +00002848 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002849
Daniel Berlind81ccc22007-09-24 19:45:49 +00002850 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2851 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002852}
2853
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002854void Andersens::PrintPointsToGraph() const {
Bill Wendlinge8156192006-12-07 01:30:32 +00002855 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002856 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002857 const Node *N = &GraphNodes[i];
2858 if (FindNode(i) != i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002859 PrintNode(N);
2860 cerr << "\t--> same as ";
2861 PrintNode(&GraphNodes[FindNode(i)]);
2862 cerr << "\n";
2863 } else {
2864 cerr << "[" << (N->PointsTo->count()) << "] ";
2865 PrintNode(N);
2866 cerr << "\t--> ";
2867
2868 bool first = true;
2869 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2870 bi != N->PointsTo->end();
2871 ++bi) {
2872 if (!first)
2873 cerr << ", ";
2874 PrintNode(&GraphNodes[*bi]);
2875 first = false;
2876 }
2877 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002878 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002879 }
2880}