blob: 3c07d24bef459e92ea579c51b7c06d90310c6dc7 [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"
Torok Edwin7d696d82009-07-11 13:10:19 +000063#include "llvm/Support/ErrorHandling.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000064#include "llvm/Support/InstIterator.h"
65#include "llvm/Support/InstVisitor.h"
66#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000067#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000068#include "llvm/Support/Debug.h"
Owen Anderson2e693102009-06-24 22:16:52 +000069#include "llvm/System/Atomic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000070#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000071#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000072#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000073#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000074#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000075#include <list>
Dan Gohmanc9235d22008-03-21 23:51:57 +000076#include <map>
Daniel Berlinaad15882007-09-16 21:45:02 +000077#include <stack>
78#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000079#include <queue>
80
81// Determining the actual set of nodes the universal set can consist of is very
82// expensive because it means propagating around very large sets. We rely on
83// other analysis being able to determine which nodes can never be pointed to in
84// order to disambiguate further than "points-to anything".
85#define FULL_UNIVERSAL 0
Chris Lattnere995a2a2004-05-23 21:00:47 +000086
Daniel Berlinaad15882007-09-16 21:45:02 +000087using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000088STATISTIC(NumIters , "Number of iterations to reach convergence");
89STATISTIC(NumConstraints, "Number of constraints");
90STATISTIC(NumNodes , "Number of nodes");
91STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000092STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000093
Dan Gohman844731a2008-05-13 00:00:25 +000094static const unsigned SelfRep = (unsigned)-1;
95static const unsigned Unvisited = (unsigned)-1;
96// Position of the function return node relative to the function node.
97static const unsigned CallReturnPos = 1;
98// Position of the function call node relative to the function node.
99static const unsigned CallFirstArgPos = 2;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000100
Dan Gohman844731a2008-05-13 00:00:25 +0000101namespace {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000102 struct BitmapKeyInfo {
103 static inline SparseBitVector<> *getEmptyKey() {
104 return reinterpret_cast<SparseBitVector<> *>(-1);
105 }
106 static inline SparseBitVector<> *getTombstoneKey() {
107 return reinterpret_cast<SparseBitVector<> *>(-2);
108 }
109 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
110 return bitmap->getHashValue();
111 }
112 static bool isEqual(const SparseBitVector<> *LHS,
113 const SparseBitVector<> *RHS) {
114 if (LHS == RHS)
115 return true;
116 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
117 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
118 return false;
119
120 return *LHS == *RHS;
121 }
122
123 static bool isPod() { return true; }
124 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000125
Reid Spencerd7d83db2007-02-05 23:42:17 +0000126 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
127 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000128 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000129
130 /// Constraint - Objects of this structure are used to represent the various
131 /// constraints identified by the algorithm. The constraints are 'copy',
132 /// for statements like "A = B", 'load' for statements like "A = *B",
133 /// 'store' for statements like "*A = B", and AddressOf for statements like
134 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
135 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000136 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000137 /// resolvable to A = &C where C = B + K)
138
139 struct Constraint {
140 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
141 unsigned Dest;
142 unsigned Src;
143 unsigned Offset;
144
145 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
146 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000147 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000148 "Offset is illegal on addressof constraints");
149 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000150
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000151 bool operator==(const Constraint &RHS) const {
152 return RHS.Type == Type
153 && RHS.Dest == Dest
154 && RHS.Src == Src
155 && RHS.Offset == Offset;
156 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000157
158 bool operator!=(const Constraint &RHS) const {
159 return !(*this == RHS);
160 }
161
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000162 bool operator<(const Constraint &RHS) const {
163 if (RHS.Type != Type)
164 return RHS.Type < Type;
165 else if (RHS.Dest != Dest)
166 return RHS.Dest < Dest;
167 else if (RHS.Src != Src)
168 return RHS.Src < Src;
169 return RHS.Offset < Offset;
170 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000171 };
172
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000173 // Information DenseSet requires implemented in order to be able to do
174 // it's thing
175 struct PairKeyInfo {
176 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000177 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000178 }
179 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000180 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000181 }
182 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
183 return P.first ^ P.second;
184 }
185 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
186 const std::pair<unsigned, unsigned> &RHS) {
187 return LHS == RHS;
188 }
189 };
190
Daniel Berlin336c6c02007-09-29 00:50:40 +0000191 struct ConstraintKeyInfo {
192 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000193 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000194 }
195 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000196 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000197 }
198 static unsigned getHashValue(const Constraint &C) {
199 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
200 }
201 static bool isEqual(const Constraint &LHS,
202 const Constraint &RHS) {
203 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
204 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
205 }
206 };
207
Daniel Berlind81ccc22007-09-24 19:45:49 +0000208 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000209 // graph. Due to various optimizations, it is not always the case that
210 // there is a mapping from a Node to a Value. In particular, we add
211 // artificial Node's that represent the set of pointed-to variables shared
212 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000213 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000214 private:
Owen Anderson5ec56cc2009-06-30 05:33:46 +0000215 static volatile sys::cas_flag Counter;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000216
217 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000218 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000219 SparseBitVector<> *Edges;
220 SparseBitVector<> *PointsTo;
221 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000222 std::list<Constraint> Constraints;
223
Daniel Berlind81ccc22007-09-24 19:45:49 +0000224 // Pointer and location equivalence labels
225 unsigned PointerEquivLabel;
226 unsigned LocationEquivLabel;
227 // Predecessor edges, both real and implicit
228 SparseBitVector<> *PredEdges;
229 SparseBitVector<> *ImplicitPredEdges;
230 // Set of nodes that point to us, only use for location equivalence.
231 SparseBitVector<> *PointedToBy;
232 // Number of incoming edges, used during variable substitution to early
233 // free the points-to sets
234 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000235 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000236 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000237 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000238 bool Direct;
239 // True if the node is address taken, *or* it is part of a group of nodes
240 // that must be kept together. This is set to true for functions and
241 // their arg nodes, which must be kept at the same position relative to
242 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000243 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000244
Daniel Berlind81ccc22007-09-24 19:45:49 +0000245 // Nodes in cycles (or in equivalence classes) are united together using a
246 // standard union-find representation with path compression. NodeRep
247 // gives the index into GraphNodes for the representative Node.
248 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000249
250 // Modification timestamp. Assigned from Counter.
251 // Used for work list prioritization.
252 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000253
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000254 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000255 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000256 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
257 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
258 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000259 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000260
Chris Lattnere995a2a2004-05-23 21:00:47 +0000261 Node *setValue(Value *V) {
262 assert(Val == 0 && "Value already set for this node!");
263 Val = V;
264 return this;
265 }
266
267 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000268 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000269 Value *getValue() const { return Val; }
270
Chris Lattnere995a2a2004-05-23 21:00:47 +0000271 /// addPointerTo - Add a pointer to the list of pointees of this node,
272 /// returning true if this caused a new pointer to be added, or false if
273 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000274 bool addPointerTo(unsigned Node) {
275 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000276 }
277
278 /// intersects - Return true if the points-to set of this node intersects
279 /// with the points-to set of the specified node.
280 bool intersects(Node *N) const;
281
282 /// intersectsIgnoring - Return true if the points-to set of this node
283 /// intersects with the points-to set of the specified node on any nodes
284 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000285 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000286
287 // Timestamp a node (used for work list prioritization)
288 void Stamp() {
Owen Anderson2d7f78e2009-06-25 16:32:45 +0000289 Timestamp = sys::AtomicIncrement(&Counter);
290 --Timestamp;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000291 }
292
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000293 bool isRep() const {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000294 return( (int) NodeRep < 0 );
295 }
296 };
297
298 struct WorkListElement {
299 Node* node;
300 unsigned Timestamp;
301 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
302
303 // Note that we reverse the sense of the comparison because we
304 // actually want to give low timestamps the priority over high,
305 // whereas priority is typically interpreted as a greater value is
306 // given high priority.
307 bool operator<(const WorkListElement& that) const {
308 return( this->Timestamp > that.Timestamp );
309 }
310 };
311
312 // Priority-queue based work list specialized for Nodes.
313 class WorkList {
314 std::priority_queue<WorkListElement> Q;
315
316 public:
317 void insert(Node* n) {
318 Q.push( WorkListElement(n, n->Timestamp) );
319 }
320
321 // We automatically discard non-representative nodes and nodes
322 // that were in the work list twice (we keep a copy of the
323 // timestamp in the work list so we can detect this situation by
324 // comparing against the node's current timestamp).
325 Node* pop() {
326 while( !Q.empty() ) {
327 WorkListElement x = Q.top(); Q.pop();
328 Node* INode = x.node;
329
330 if( INode->isRep() &&
331 INode->Timestamp == x.Timestamp ) {
332 return(x.node);
333 }
334 }
335 return(0);
336 }
337
338 bool empty() {
339 return Q.empty();
340 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000341 };
342
343 /// GraphNodes - This vector is populated as part of the object
344 /// identification stage of the analysis, which populates this vector with a
345 /// node for each memory object and fills in the ValueNodes map.
346 std::vector<Node> GraphNodes;
347
348 /// ValueNodes - This map indicates the Node that a particular Value* is
349 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000350 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000351
352 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000353 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000354 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000355
356 /// ReturnNodes - This map contains an entry for each function in the
357 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000358 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000359
360 /// VarargNodes - This map contains the entry used to represent all pointers
361 /// passed through the varargs portion of a function call for a particular
362 /// function. An entry is not present in this map for functions that do not
363 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000364 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000365
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000366
Chris Lattnere995a2a2004-05-23 21:00:47 +0000367 /// Constraints - This vector contains a list of all of the constraints
368 /// identified by the program.
369 std::vector<Constraint> Constraints;
370
Daniel Berlind81ccc22007-09-24 19:45:49 +0000371 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000372 // this is equivalent to the number of arguments + CallFirstArgPos)
373 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000374
375 /// This enum defines the GraphNodes indices that correspond to important
376 /// fixed sets.
377 enum {
378 UniversalSet = 0,
379 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000380 NullObject = 2,
381 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000382 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000383 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000384 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000385 // Map from Graph Node to DFS number
386 std::vector<unsigned> Node2DFS;
387 // Map from Graph Node to Deleted from graph.
388 std::vector<bool> Node2Deleted;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000389 // Same as Node Maps, but implemented as std::map because it is faster to
390 // clear
391 std::map<unsigned, unsigned> Tarjan2DFS;
392 std::map<unsigned, bool> Tarjan2Deleted;
393 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000394 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000395
396 // Work lists.
397 WorkList w1, w2;
398 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000399
Daniel Berlind81ccc22007-09-24 19:45:49 +0000400 // Offline variable substitution related things
401
402 // Temporary rep storage, used because we can't collapse SCC's in the
403 // predecessor graph by uniting the variables permanently, we can only do so
404 // for the successor graph.
405 std::vector<unsigned> VSSCCRep;
406 // Mapping from node to whether we have visited it during SCC finding yet.
407 std::vector<bool> Node2Visited;
408 // During variable substitution, we create unknowns to represent the unknown
409 // value that is a dereference of a variable. These nodes are known as
410 // "ref" nodes (since they represent the value of dereferences).
411 unsigned FirstRefNode;
412 // During HVN, we create represent address taken nodes as if they were
413 // unknown (since HVN, unlike HU, does not evaluate unions).
414 unsigned FirstAdrNode;
415 // Current pointer equivalence class number
416 unsigned PEClass;
417 // Mapping from points-to sets to equivalence classes
418 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
419 BitVectorMap Set2PEClass;
420 // Mapping from pointer equivalences to the representative node. -1 if we
421 // have no representative node for this pointer equivalence class yet.
422 std::vector<int> PEClass2Node;
423 // Mapping from pointer equivalences to representative node. This includes
424 // pointer equivalent but not location equivalent variables. -1 if we have
425 // no representative node for this pointer equivalence class yet.
426 std::vector<int> PENLEClass2Node;
Daniel Berlinc864edb2008-03-05 19:31:47 +0000427 // Union/Find for HCD
428 std::vector<unsigned> HCDSCCRep;
429 // HCD's offline-detected cycles; "Statically DeTected"
430 // -1 if not part of such a cycle, otherwise a representative node.
431 std::vector<int> SDT;
432 // Whether to use SDT (UniteNodes can use it during solving, but not before)
433 bool SDTActive;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000434
Chris Lattnere995a2a2004-05-23 21:00:47 +0000435 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000436 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000437 Andersens() : ModulePass(&ID) {}
Devang Patel1cee94f2008-03-18 00:39:19 +0000438
Chris Lattnerb12914b2004-09-20 04:48:05 +0000439 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000440 InitializeAliasAnalysis(this);
441 IdentifyObjects(M);
442 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000443#undef DEBUG_TYPE
444#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000445 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000446#undef DEBUG_TYPE
447#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000448 SolveConstraints();
449 DEBUG(PrintPointsToGraph());
450
451 // Free the constraints list, as we don't need it to respond to alias
452 // requests.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000453 std::vector<Constraint>().swap(Constraints);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000454 //These are needed for Print() (-analyze in opt)
455 //ObjectNodes.clear();
456 //ReturnNodes.clear();
457 //VarargNodes.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000458 return false;
459 }
460
461 void releaseMemory() {
462 // FIXME: Until we have transitively required passes working correctly,
463 // this cannot be enabled! Otherwise, using -count-aa with the pass
464 // causes memory to be freed too early. :(
465#if 0
466 // The memory objects and ValueNodes data structures at the only ones that
467 // are still live after construction.
468 std::vector<Node>().swap(GraphNodes);
469 ValueNodes.clear();
470#endif
471 }
472
473 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
474 AliasAnalysis::getAnalysisUsage(AU);
475 AU.setPreservesAll(); // Does not transform code
476 }
477
478 //------------------------------------------------
479 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000480 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000481 AliasResult alias(const Value *V1, unsigned V1Size,
482 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000483 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
484 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000485 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
486 bool pointsToConstantMemory(const Value *P);
487
488 virtual void deleteValue(Value *V) {
489 ValueNodes.erase(V);
490 getAnalysis<AliasAnalysis>().deleteValue(V);
491 }
492
493 virtual void copyValue(Value *From, Value *To) {
494 ValueNodes[To] = ValueNodes[From];
495 getAnalysis<AliasAnalysis>().copyValue(From, To);
496 }
497
498 private:
499 /// getNode - Return the node corresponding to the specified pointer scalar.
500 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000501 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000502 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000503 if (!isa<GlobalValue>(C))
504 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000505
Daniel Berlind81ccc22007-09-24 19:45:49 +0000506 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000507 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000508#ifndef NDEBUG
509 V->dump();
510#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000511 llvm_unreachable("Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000512 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000513 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000514 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000515
Chris Lattnere995a2a2004-05-23 21:00:47 +0000516 /// getObject - Return the node corresponding to the memory object for the
517 /// specified global or allocation instruction.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000518 unsigned getObject(Value *V) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000519 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000520 assert(I != ObjectNodes.end() &&
521 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000522 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000523 }
524
525 /// getReturnNode - Return the node representing the return value for the
526 /// specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000527 unsigned getReturnNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000528 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000529 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000530 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000531 }
532
533 /// getVarargNode - Return the node representing the variable arguments
534 /// formal for the specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000535 unsigned getVarargNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000536 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000537 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000538 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000539 }
540
541 /// getNodeValue - Get the node for the specified LLVM value and set the
542 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000543 unsigned getNodeValue(Value &V) {
544 unsigned Index = getNode(&V);
545 GraphNodes[Index].setValue(&V);
546 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000547 }
548
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000549 unsigned UniteNodes(unsigned First, unsigned Second,
550 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000551 unsigned FindNode(unsigned Node);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000552 unsigned FindNode(unsigned Node) const;
Daniel Berlinaad15882007-09-16 21:45:02 +0000553
Chris Lattnere995a2a2004-05-23 21:00:47 +0000554 void IdentifyObjects(Module &M);
555 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000556 bool AnalyzeUsesOfFunction(Value *);
557 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000558 void OptimizeConstraints();
559 unsigned FindEquivalentNode(unsigned, unsigned);
560 void ClumpAddressTaken();
561 void RewriteConstraints();
562 void HU();
563 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000564 void HCD();
565 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000566 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000567 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000568 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000569 void Condense(unsigned Node);
570 void HUValNum(unsigned Node);
571 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000572 unsigned getNodeForConstantPointer(Constant *C);
573 unsigned getNodeForConstantPointerTarget(Constant *C);
574 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000575
Chris Lattnere995a2a2004-05-23 21:00:47 +0000576 void AddConstraintsForNonInternalLinkage(Function *F);
577 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000578 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000579
580
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000581 void PrintNode(const Node *N) const;
582 void PrintConstraints() const ;
583 void PrintConstraint(const Constraint &) const;
584 void PrintLabels() const;
585 void PrintPointsToGraph() const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000586
587 //===------------------------------------------------------------------===//
588 // Instruction visitation methods for adding constraints
589 //
590 friend class InstVisitor<Andersens>;
591 void visitReturnInst(ReturnInst &RI);
592 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
593 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
594 void visitCallSite(CallSite CS);
595 void visitAllocationInst(AllocationInst &AI);
596 void visitLoadInst(LoadInst &LI);
597 void visitStoreInst(StoreInst &SI);
598 void visitGetElementPtrInst(GetElementPtrInst &GEP);
599 void visitPHINode(PHINode &PN);
600 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000601 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
602 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000603 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000604 void visitVAArg(VAArgInst &I);
605 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000606
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000607 //===------------------------------------------------------------------===//
608 // Implement Analyize interface
609 //
610 void print(std::ostream &O, const Module* M) const {
611 PrintPointsToGraph();
612 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000613 };
Chris Lattnere995a2a2004-05-23 21:00:47 +0000614}
615
Dan Gohman844731a2008-05-13 00:00:25 +0000616char Andersens::ID = 0;
617static RegisterPass<Andersens>
618X("anders-aa", "Andersen's Interprocedural Alias Analysis", false, true);
619static RegisterAnalysisGroup<AliasAnalysis> Y(X);
620
621// Initialize Timestamp Counter (static).
Owen Anderson5ec56cc2009-06-30 05:33:46 +0000622volatile llvm::sys::cas_flag Andersens::Node::Counter = 0;
Dan Gohman844731a2008-05-13 00:00:25 +0000623
Jeff Cohen534927d2005-01-08 22:01:16 +0000624ModulePass *llvm::createAndersensPass() { return new Andersens(); }
625
Chris Lattnere995a2a2004-05-23 21:00:47 +0000626//===----------------------------------------------------------------------===//
627// AliasAnalysis Interface Implementation
628//===----------------------------------------------------------------------===//
629
630AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
631 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000632 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
633 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000634
635 // Check to see if the two pointers are known to not alias. They don't alias
636 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000637 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000638 return NoAlias;
639
640 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
641}
642
Chris Lattnerf392c642005-03-28 06:21:17 +0000643AliasAnalysis::ModRefResult
644Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
645 // The only thing useful that we can contribute for mod/ref information is
646 // when calling external function calls: if we know that memory never escapes
647 // from the program, it cannot be modified by an external call.
648 //
649 // NOTE: This is not really safe, at least not when the entire program is not
650 // available. The deal is that the external function could call back into the
651 // program and modify stuff. We ignore this technical niggle for now. This
652 // is, after all, a "research quality" implementation of Andersen's analysis.
653 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000654 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000655 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000656
Daniel Berlinaad15882007-09-16 21:45:02 +0000657 if (N1->PointsTo->empty())
658 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000659#if FULL_UNIVERSAL
660 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
661 return NoModRef; // Universal set does not contain P
662#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000663 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000664 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000665#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000666 }
667
668 return AliasAnalysis::getModRefInfo(CS, P, Size);
669}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000670
Reid Spencer3a9ec242006-08-28 01:02:49 +0000671AliasAnalysis::ModRefResult
672Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
673 return AliasAnalysis::getModRefInfo(CS1,CS2);
674}
675
Chris Lattnere995a2a2004-05-23 21:00:47 +0000676/// getMustAlias - We can provide must alias information if we know that a
677/// pointer can only point to a specific function or the null pointer.
678/// Unfortunately we cannot determine must-alias information for global
679/// variables or any other memory memory objects because we do not track whether
680/// a pointer points to the beginning of an object or a field of it.
681void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000682 Node *N = &GraphNodes[FindNode(getNode(P))];
683 if (N->PointsTo->count() == 1) {
684 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
685 // If a function is the only object in the points-to set, then it must be
686 // the destination. Note that we can't handle global variables here,
687 // because we don't know if the pointer is actually pointing to a field of
688 // the global or to the beginning of it.
689 if (Value *V = Pointee->getValue()) {
690 if (Function *F = dyn_cast<Function>(V))
691 RetVals.push_back(F);
692 } else {
693 // If the object in the points-to set is the null object, then the null
694 // pointer is a must alias.
695 if (Pointee == &GraphNodes[NullObject])
Owen Andersona7235ea2009-07-31 20:28:14 +0000696 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000697 }
698 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000699 AliasAnalysis::getMustAliases(P, RetVals);
700}
701
702/// pointsToConstantMemory - If we can determine that this pointer only points
703/// to constant memory, return true. In practice, this means that if the
704/// pointer can only point to constant globals, functions, or the null pointer,
705/// return true.
706///
707bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000708 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000709 unsigned i;
710
711 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
712 bi != N->PointsTo->end();
713 ++bi) {
714 i = *bi;
715 Node *Pointee = &GraphNodes[i];
716 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000717 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
718 !cast<GlobalVariable>(V)->isConstant()))
719 return AliasAnalysis::pointsToConstantMemory(P);
720 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000721 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000722 return AliasAnalysis::pointsToConstantMemory(P);
723 }
724 }
725
726 return true;
727}
728
729//===----------------------------------------------------------------------===//
730// Object Identification Phase
731//===----------------------------------------------------------------------===//
732
733/// IdentifyObjects - This stage scans the program, adding an entry to the
734/// GraphNodes list for each memory object in the program (global stack or
735/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
736///
737void Andersens::IdentifyObjects(Module &M) {
738 unsigned NumObjects = 0;
739
740 // Object #0 is always the universal set: the object that we don't know
741 // anything about.
742 assert(NumObjects == UniversalSet && "Something changed!");
743 ++NumObjects;
744
745 // Object #1 always represents the null pointer.
746 assert(NumObjects == NullPtr && "Something changed!");
747 ++NumObjects;
748
749 // Object #2 always represents the null object (the object pointed to by null)
750 assert(NumObjects == NullObject && "Something changed!");
751 ++NumObjects;
752
753 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000754 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
755 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000756 ObjectNodes[I] = NumObjects++;
757 ValueNodes[I] = NumObjects++;
758 }
759
760 // Add nodes for all of the functions and the instructions inside of them.
761 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
762 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000763 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000764 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000765 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
766 ReturnNodes[F] = NumObjects++;
767 if (F->getFunctionType()->isVarArg())
768 VarargNodes[F] = NumObjects++;
769
Daniel Berlinaad15882007-09-16 21:45:02 +0000770
Chris Lattnere995a2a2004-05-23 21:00:47 +0000771 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000772 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
773 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000774 {
775 if (isa<PointerType>(I->getType()))
776 ValueNodes[I] = NumObjects++;
777 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000778 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000779
780 // Scan the function body, creating a memory object for each heap/stack
781 // allocation in the body of the function and a node to represent all
782 // pointer values defined by instructions and used as operands.
783 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
784 // If this is an heap or stack allocation, create a node for the memory
785 // object.
786 if (isa<PointerType>(II->getType())) {
787 ValueNodes[&*II] = NumObjects++;
788 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
789 ObjectNodes[AI] = NumObjects++;
790 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000791
792 // Calls to inline asm need to be added as well because the callee isn't
793 // referenced anywhere else.
794 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
795 Value *Callee = CI->getCalledValue();
796 if (isa<InlineAsm>(Callee))
797 ValueNodes[Callee] = NumObjects++;
798 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000799 }
800 }
801
802 // Now that we know how many objects to create, make them all now!
803 GraphNodes.resize(NumObjects);
804 NumNodes += NumObjects;
805}
806
807//===----------------------------------------------------------------------===//
808// Constraint Identification Phase
809//===----------------------------------------------------------------------===//
810
811/// getNodeForConstantPointer - Return the node corresponding to the constant
812/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000813unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000814 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
815
Chris Lattner267a1b02005-03-27 18:58:23 +0000816 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000817 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000818 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
819 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000820 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
821 switch (CE->getOpcode()) {
822 case Instruction::GetElementPtr:
823 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000824 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000825 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000826 case Instruction::BitCast:
827 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000828 default:
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000829 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000830 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000831 }
832 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000833 llvm_unreachable("Unknown constant pointer!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000834 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000835 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000836}
837
838/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
839/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000840unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000841 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
842
843 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000844 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000845 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
846 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000847 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
848 switch (CE->getOpcode()) {
849 case Instruction::GetElementPtr:
850 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000851 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000852 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000853 case Instruction::BitCast:
854 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000855 default:
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000856 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000857 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000858 }
859 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000860 llvm_unreachable("Unknown constant pointer!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000861 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000862 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000863}
864
865/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
866/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000867void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
868 Constant *C) {
Dan Gohmanb64aa112008-05-22 23:43:22 +0000869 if (C->getType()->isSingleValueType()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000870 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000871 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
872 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000873 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000874 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
875 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000876 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000877 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000878 // If this is an array or struct, include constraints for each element.
879 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
880 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000881 AddGlobalInitializerConstraints(NodeIndex,
882 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000883 }
884}
885
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000886/// AddConstraintsForNonInternalLinkage - If this function does not have
887/// internal linkage, realize that we can't trust anything passed into or
888/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000889void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000890 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000891 if (isa<PointerType>(I->getType()))
892 // If this is an argument of an externally accessible function, the
893 // incoming pointer might point to anything.
894 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000895 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000896}
897
Chris Lattner8a446432005-03-29 06:09:07 +0000898/// AddConstraintsForCall - If this is a call to a "known" function, add the
899/// constraints and return true. If this is a call to an unknown function,
900/// return false.
901bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000902 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000903
904 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000905 if (F->getName() == "atoi" || F->getName() == "atof" ||
906 F->getName() == "atol" || F->getName() == "atoll" ||
907 F->getName() == "remove" || F->getName() == "unlink" ||
908 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner824b9582008-11-21 16:42:48 +0000909 F->getName() == "llvm.memset" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000910 F->getName() == "strcmp" || F->getName() == "strncmp" ||
911 F->getName() == "execl" || F->getName() == "execlp" ||
912 F->getName() == "execle" || F->getName() == "execv" ||
913 F->getName() == "execvp" || F->getName() == "chmod" ||
914 F->getName() == "puts" || F->getName() == "write" ||
915 F->getName() == "open" || F->getName() == "create" ||
916 F->getName() == "truncate" || F->getName() == "chdir" ||
917 F->getName() == "mkdir" || F->getName() == "rmdir" ||
918 F->getName() == "read" || F->getName() == "pipe" ||
919 F->getName() == "wait" || F->getName() == "time" ||
920 F->getName() == "stat" || F->getName() == "fstat" ||
921 F->getName() == "lstat" || F->getName() == "strtod" ||
922 F->getName() == "strtof" || F->getName() == "strtold" ||
923 F->getName() == "fopen" || F->getName() == "fdopen" ||
924 F->getName() == "freopen" ||
925 F->getName() == "fflush" || F->getName() == "feof" ||
926 F->getName() == "fileno" || F->getName() == "clearerr" ||
927 F->getName() == "rewind" || F->getName() == "ftell" ||
928 F->getName() == "ferror" || F->getName() == "fgetc" ||
929 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
930 F->getName() == "fwrite" || F->getName() == "fread" ||
931 F->getName() == "fgets" || F->getName() == "ungetc" ||
932 F->getName() == "fputc" ||
933 F->getName() == "fputs" || F->getName() == "putc" ||
934 F->getName() == "ftell" || F->getName() == "rewind" ||
935 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
936 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
937 F->getName() == "printf" || F->getName() == "fprintf" ||
938 F->getName() == "sprintf" || F->getName() == "vprintf" ||
939 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
940 F->getName() == "scanf" || F->getName() == "fscanf" ||
941 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
942 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000943 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000944
Chris Lattner175b9632005-03-29 20:36:05 +0000945
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000946 // These functions do induce points-to edges.
Chris Lattner824b9582008-11-21 16:42:48 +0000947 if (F->getName() == "llvm.memcpy" ||
948 F->getName() == "llvm.memmove" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000949 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000950
Nick Lewycky3037eda2008-12-27 16:20:53 +0000951 const FunctionType *FTy = F->getFunctionType();
952 if (FTy->getNumParams() > 1 &&
953 isa<PointerType>(FTy->getParamType(0)) &&
954 isa<PointerType>(FTy->getParamType(1))) {
955
956 // *Dest = *Src, which requires an artificial graph node to represent the
957 // constraint. It is broken up into *Dest = temp, temp = *Src
958 unsigned FirstArg = getNode(CS.getArgument(0));
959 unsigned SecondArg = getNode(CS.getArgument(1));
960 unsigned TempArg = GraphNodes.size();
961 GraphNodes.push_back(Node());
962 Constraints.push_back(Constraint(Constraint::Store,
963 FirstArg, TempArg));
964 Constraints.push_back(Constraint(Constraint::Load,
965 TempArg, SecondArg));
966 // In addition, Dest = Src
967 Constraints.push_back(Constraint(Constraint::Copy,
968 FirstArg, SecondArg));
969 return true;
970 }
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000971 }
972
Chris Lattner77b50562005-03-29 20:04:24 +0000973 // Result = Arg0
974 if (F->getName() == "realloc" || F->getName() == "strchr" ||
975 F->getName() == "strrchr" || F->getName() == "strstr" ||
976 F->getName() == "strtok") {
Nick Lewycky3037eda2008-12-27 16:20:53 +0000977 const FunctionType *FTy = F->getFunctionType();
978 if (FTy->getNumParams() > 0 &&
979 isa<PointerType>(FTy->getParamType(0))) {
980 Constraints.push_back(Constraint(Constraint::Copy,
981 getNode(CS.getInstruction()),
982 getNode(CS.getArgument(0))));
983 return true;
984 }
Chris Lattner8a446432005-03-29 06:09:07 +0000985 }
986
987 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000988}
989
990
Chris Lattnere995a2a2004-05-23 21:00:47 +0000991
Daniel Berlinaad15882007-09-16 21:45:02 +0000992/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
993/// If this is used by anything complex (i.e., the address escapes), return
994/// true.
995bool Andersens::AnalyzeUsesOfFunction(Value *V) {
996
997 if (!isa<PointerType>(V->getType())) return true;
998
999 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
1000 if (dyn_cast<LoadInst>(*UI)) {
1001 return false;
1002 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1003 if (V == SI->getOperand(1)) {
1004 return false;
1005 } else if (SI->getOperand(1)) {
1006 return true; // Storing the pointer
1007 }
1008 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1009 if (AnalyzeUsesOfFunction(GEP)) return true;
1010 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1011 // Make sure that this is just the function being called, not that it is
1012 // passing into the function.
1013 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1014 if (CI->getOperand(i) == V) return true;
1015 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1016 // Make sure that this is just the function being called, not that it is
1017 // passing into the function.
Bill Wendling9a507cd2009-03-13 21:15:59 +00001018 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +00001019 if (II->getOperand(i) == V) return true;
1020 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1021 if (CE->getOpcode() == Instruction::GetElementPtr ||
1022 CE->getOpcode() == Instruction::BitCast) {
1023 if (AnalyzeUsesOfFunction(CE))
1024 return true;
1025 } else {
1026 return true;
1027 }
1028 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1029 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1030 return true; // Allow comparison against null.
1031 } else if (dyn_cast<FreeInst>(*UI)) {
1032 return false;
1033 } else {
1034 return true;
1035 }
1036 return false;
1037}
1038
Chris Lattnere995a2a2004-05-23 21:00:47 +00001039/// CollectConstraints - This stage scans the program, adding a constraint to
1040/// the Constraints list for each instruction in the program that induces a
1041/// constraint, and setting up the initial points-to graph.
1042///
1043void Andersens::CollectConstraints(Module &M) {
1044 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001045 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1046 UniversalSet));
1047 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1048 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001049
1050 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001051 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001052
1053 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001054 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1055 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001056 // Associate the address of the global object as pointing to the memory for
1057 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001058 unsigned ObjectIndex = getObject(I);
1059 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001060 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001061 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1062 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001063
1064 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001065 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001066 } else {
1067 // If it doesn't have an initializer (i.e. it's defined in another
1068 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001069 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1070 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001071 }
1072 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001073
Chris Lattnere995a2a2004-05-23 21:00:47 +00001074 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001075 // Set up the return value node.
1076 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001077 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001078 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001079 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001080
1081 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001082 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1083 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001084 if (isa<PointerType>(I->getType()))
1085 getNodeValue(*I);
1086
Daniel Berlinaad15882007-09-16 21:45:02 +00001087 // At some point we should just add constraints for the escaping functions
1088 // at solve time, but this slows down solving. For now, we simply mark
1089 // address taken functions as escaping and treat them as external.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001090 if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001091 AddConstraintsForNonInternalLinkage(F);
1092
Reid Spencer5cbf9852007-01-30 20:08:39 +00001093 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001094 // Scan the function body, creating a memory object for each heap/stack
1095 // allocation in the body of the function and a node to represent all
1096 // pointer values defined by instructions and used as operands.
1097 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001098 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001099 // External functions that return pointers return the universal set.
1100 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1101 Constraints.push_back(Constraint(Constraint::Copy,
1102 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001103 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001104
1105 // Any pointers that are passed into the function have the universal set
1106 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001107 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1108 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001109 if (isa<PointerType>(I->getType())) {
1110 // Pointers passed into external functions could have anything stored
1111 // through them.
1112 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001113 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001114 // Memory objects passed into external function calls can have the
1115 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001116#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001117 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001118 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001119 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001120#else
1121 Constraints.push_back(Constraint(Constraint::Copy,
1122 getNode(I),
1123 UniversalSet));
1124#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001125 }
1126
1127 // If this is an external varargs function, it can also store pointers
1128 // into any pointers passed through the varargs section.
1129 if (F->getFunctionType()->isVarArg())
1130 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001131 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001132 }
1133 }
1134 NumConstraints += Constraints.size();
1135}
1136
1137
1138void Andersens::visitInstruction(Instruction &I) {
1139#ifdef NDEBUG
1140 return; // This function is just a big assert.
1141#endif
1142 if (isa<BinaryOperator>(I))
1143 return;
1144 // Most instructions don't have any effect on pointer values.
1145 switch (I.getOpcode()) {
1146 case Instruction::Br:
1147 case Instruction::Switch:
1148 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001149 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001150 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001151 case Instruction::ICmp:
1152 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001153 return;
1154 default:
1155 // Is this something we aren't handling yet?
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00001156 errs() << "Unknown instruction: " << I;
Torok Edwinc23197a2009-07-14 16:55:14 +00001157 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001158 }
1159}
1160
1161void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001162 unsigned ObjectIndex = getObject(&AI);
1163 GraphNodes[ObjectIndex].setValue(&AI);
1164 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1165 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001166}
1167
1168void Andersens::visitReturnInst(ReturnInst &RI) {
1169 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1170 // return V --> <Copy/retval{F}/v>
1171 Constraints.push_back(Constraint(Constraint::Copy,
1172 getReturnNode(RI.getParent()->getParent()),
1173 getNode(RI.getOperand(0))));
1174}
1175
1176void Andersens::visitLoadInst(LoadInst &LI) {
1177 if (isa<PointerType>(LI.getType()))
1178 // P1 = load P2 --> <Load/P1/P2>
1179 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1180 getNode(LI.getOperand(0))));
1181}
1182
1183void Andersens::visitStoreInst(StoreInst &SI) {
1184 if (isa<PointerType>(SI.getOperand(0)->getType()))
1185 // store P1, P2 --> <Store/P2/P1>
1186 Constraints.push_back(Constraint(Constraint::Store,
1187 getNode(SI.getOperand(1)),
1188 getNode(SI.getOperand(0))));
1189}
1190
1191void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1192 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1193 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1194 getNode(GEP.getOperand(0))));
1195}
1196
1197void Andersens::visitPHINode(PHINode &PN) {
1198 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001199 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001200 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1201 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1202 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1203 getNode(PN.getIncomingValue(i))));
1204 }
1205}
1206
1207void Andersens::visitCastInst(CastInst &CI) {
1208 Value *Op = CI.getOperand(0);
1209 if (isa<PointerType>(CI.getType())) {
1210 if (isa<PointerType>(Op->getType())) {
1211 // P1 = cast P2 --> <Copy/P1/P2>
1212 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1213 getNode(CI.getOperand(0))));
1214 } else {
1215 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001216#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001217 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001218 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001219#else
1220 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001221#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001222 }
1223 } else if (isa<PointerType>(Op->getType())) {
1224 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001225#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001226 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001227 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001228 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001229#else
1230 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001231#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001232 }
1233}
1234
1235void Andersens::visitSelectInst(SelectInst &SI) {
1236 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001237 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001238 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1239 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1240 getNode(SI.getOperand(1))));
1241 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1242 getNode(SI.getOperand(2))));
1243 }
1244}
1245
Chris Lattnere995a2a2004-05-23 21:00:47 +00001246void Andersens::visitVAArg(VAArgInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001247 llvm_unreachable("vaarg not handled yet!");
Chris Lattnere995a2a2004-05-23 21:00:47 +00001248}
1249
1250/// AddConstraintsForCall - Add constraints for a call with actual arguments
1251/// specified by CS to the function specified by F. Note that the types of
1252/// arguments might not match up in the case where this is an indirect call and
1253/// the function pointer has been casted. If this is the case, do something
1254/// reasonable.
1255void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001256 Value *CallValue = CS.getCalledValue();
1257 bool IsDeref = F == NULL;
1258
1259 // If this is a call to an external function, try to handle it directly to get
1260 // some taste of context sensitivity.
1261 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001262 return;
1263
Chris Lattnere995a2a2004-05-23 21:00:47 +00001264 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001265 unsigned CSN = getNode(CS.getInstruction());
1266 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1267 if (IsDeref)
1268 Constraints.push_back(Constraint(Constraint::Load, CSN,
1269 getNode(CallValue), CallReturnPos));
1270 else
1271 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1272 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001273 } else {
1274 // If the function returns a non-pointer value, handle this just like we
1275 // treat a nonpointer cast to pointer.
1276 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001277 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001278 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001279 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001280#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001281 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001282 UniversalSet,
1283 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001284#else
1285 Constraints.push_back(Constraint(Constraint::Copy,
1286 getNode(CallValue) + CallReturnPos,
1287 UniversalSet));
1288#endif
1289
1290
Chris Lattnere995a2a2004-05-23 21:00:47 +00001291 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001292
Chris Lattnere995a2a2004-05-23 21:00:47 +00001293 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001294 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001295 if (F) {
1296 // Direct Call
1297 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001298 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1299 {
1300#if !FULL_UNIVERSAL
1301 if (external && isa<PointerType>((*ArgI)->getType()))
1302 {
1303 // Add constraint that ArgI can now point to anything due to
1304 // escaping, as can everything it points to. The second portion of
1305 // this should be taken care of by universal = *universal
1306 Constraints.push_back(Constraint(Constraint::Copy,
1307 getNode(*ArgI),
1308 UniversalSet));
1309 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001310#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001311 if (isa<PointerType>(AI->getType())) {
1312 if (isa<PointerType>((*ArgI)->getType())) {
1313 // Copy the actual argument into the formal argument.
1314 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1315 getNode(*ArgI)));
1316 } else {
1317 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1318 UniversalSet));
1319 }
1320 } else if (isa<PointerType>((*ArgI)->getType())) {
1321#if FULL_UNIVERSAL
1322 Constraints.push_back(Constraint(Constraint::Copy,
1323 UniversalSet,
1324 getNode(*ArgI)));
1325#else
1326 Constraints.push_back(Constraint(Constraint::Copy,
1327 getNode(*ArgI),
1328 UniversalSet));
1329#endif
1330 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001331 }
1332 } else {
1333 //Indirect Call
1334 unsigned ArgPos = CallFirstArgPos;
1335 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001336 if (isa<PointerType>((*ArgI)->getType())) {
1337 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001338 Constraints.push_back(Constraint(Constraint::Store,
1339 getNode(CallValue),
1340 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001341 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001342 Constraints.push_back(Constraint(Constraint::Store,
1343 getNode (CallValue),
1344 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001345 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001346 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001347 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001348 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001349 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001350 for (; ArgI != ArgE; ++ArgI)
1351 if (isa<PointerType>((*ArgI)->getType()))
1352 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1353 getNode(*ArgI)));
1354 // If more arguments are passed in than we track, just drop them on the floor.
1355}
1356
1357void Andersens::visitCallSite(CallSite CS) {
1358 if (isa<PointerType>(CS.getType()))
1359 getNodeValue(*CS.getInstruction());
1360
1361 if (Function *F = CS.getCalledFunction()) {
1362 AddConstraintsForCall(CS, F);
1363 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001364 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001365 }
1366}
1367
1368//===----------------------------------------------------------------------===//
1369// Constraint Solving Phase
1370//===----------------------------------------------------------------------===//
1371
1372/// intersects - Return true if the points-to set of this node intersects
1373/// with the points-to set of the specified node.
1374bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001375 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001376}
1377
1378/// intersectsIgnoring - Return true if the points-to set of this node
1379/// intersects with the points-to set of the specified node on any nodes
1380/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001381bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1382 // TODO: If we are only going to call this with the same value for Ignoring,
1383 // we should move the special values out of the points-to bitmap.
1384 bool WeHadIt = PointsTo->test(Ignoring);
1385 bool NHadIt = N->PointsTo->test(Ignoring);
1386 bool Result = false;
1387 if (WeHadIt)
1388 PointsTo->reset(Ignoring);
1389 if (NHadIt)
1390 N->PointsTo->reset(Ignoring);
1391 Result = PointsTo->intersects(N->PointsTo);
1392 if (WeHadIt)
1393 PointsTo->set(Ignoring);
1394 if (NHadIt)
1395 N->PointsTo->set(Ignoring);
1396 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001397}
1398
Daniel Berlind81ccc22007-09-24 19:45:49 +00001399void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001400#ifndef NDEBUG
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00001401 raw_os_ostream OS(*DOUT);
1402 dump(*bitmap, OS);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001403#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001404}
1405
1406
1407/// Clump together address taken variables so that the points-to sets use up
1408/// less space and can be operated on faster.
1409
1410void Andersens::ClumpAddressTaken() {
1411#undef DEBUG_TYPE
1412#define DEBUG_TYPE "anders-aa-renumber"
1413 std::vector<unsigned> Translate;
1414 std::vector<Node> NewGraphNodes;
1415
1416 Translate.resize(GraphNodes.size());
1417 unsigned NewPos = 0;
1418
1419 for (unsigned i = 0; i < Constraints.size(); ++i) {
1420 Constraint &C = Constraints[i];
1421 if (C.Type == Constraint::AddressOf) {
1422 GraphNodes[C.Src].AddressTaken = true;
1423 }
1424 }
1425 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1426 unsigned Pos = NewPos++;
1427 Translate[i] = Pos;
1428 NewGraphNodes.push_back(GraphNodes[i]);
1429 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1430 }
1431
1432 // I believe this ends up being faster than making two vectors and splicing
1433 // them.
1434 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1435 if (GraphNodes[i].AddressTaken) {
1436 unsigned Pos = NewPos++;
1437 Translate[i] = Pos;
1438 NewGraphNodes.push_back(GraphNodes[i]);
1439 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1440 }
1441 }
1442
1443 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1444 if (!GraphNodes[i].AddressTaken) {
1445 unsigned Pos = NewPos++;
1446 Translate[i] = Pos;
1447 NewGraphNodes.push_back(GraphNodes[i]);
1448 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1449 }
1450 }
1451
1452 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1453 Iter != ValueNodes.end();
1454 ++Iter)
1455 Iter->second = Translate[Iter->second];
1456
1457 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1458 Iter != ObjectNodes.end();
1459 ++Iter)
1460 Iter->second = Translate[Iter->second];
1461
1462 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1463 Iter != ReturnNodes.end();
1464 ++Iter)
1465 Iter->second = Translate[Iter->second];
1466
1467 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1468 Iter != VarargNodes.end();
1469 ++Iter)
1470 Iter->second = Translate[Iter->second];
1471
1472 for (unsigned i = 0; i < Constraints.size(); ++i) {
1473 Constraint &C = Constraints[i];
1474 C.Src = Translate[C.Src];
1475 C.Dest = Translate[C.Dest];
1476 }
1477
1478 GraphNodes.swap(NewGraphNodes);
1479#undef DEBUG_TYPE
1480#define DEBUG_TYPE "anders-aa"
1481}
1482
1483/// The technique used here is described in "Exploiting Pointer and Location
1484/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1485/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1486/// and is equivalent to value numbering the collapsed constraint graph without
1487/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1488/// first order pointer dereferences and speed up/reduce memory usage of HU.
1489/// Running both is equivalent to HRU without the iteration
1490/// HVN in more detail:
1491/// Imagine the set of constraints was simply straight line code with no loops
1492/// (we eliminate cycles, so there are no loops), such as:
1493/// E = &D
1494/// E = &C
1495/// E = F
1496/// F = G
1497/// G = F
1498/// Applying value numbering to this code tells us:
1499/// G == F == E
1500///
1501/// For HVN, this is as far as it goes. We assign new value numbers to every
1502/// "address node", and every "reference node".
1503/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1504/// cycle must have the same value number since the = operation is really
1505/// inclusion, not overwrite), and value number nodes we receive points-to sets
1506/// before we value our own node.
1507/// The advantage of HU over HVN is that HU considers the inclusion property, so
1508/// that if you have
1509/// E = &D
1510/// E = &C
1511/// E = F
1512/// F = G
1513/// F = &D
1514/// G = F
1515/// HU will determine that G == F == E. HVN will not, because it cannot prove
1516/// that the points to information ends up being the same because they all
1517/// receive &D from E anyway.
1518
1519void Andersens::HVN() {
1520 DOUT << "Beginning HVN\n";
1521 // Build a predecessor graph. This is like our constraint graph with the
1522 // edges going in the opposite direction, and there are edges for all the
1523 // constraints, instead of just copy constraints. We also build implicit
1524 // edges for constraints are implied but not explicit. I.E for the constraint
1525 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1526 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1527 Constraint &C = Constraints[i];
1528 if (C.Type == Constraint::AddressOf) {
1529 GraphNodes[C.Src].AddressTaken = true;
1530 GraphNodes[C.Src].Direct = false;
1531
1532 // Dest = &src edge
1533 unsigned AdrNode = C.Src + FirstAdrNode;
1534 if (!GraphNodes[C.Dest].PredEdges)
1535 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1536 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1537
1538 // *Dest = src edge
1539 unsigned RefNode = C.Dest + FirstRefNode;
1540 if (!GraphNodes[RefNode].ImplicitPredEdges)
1541 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1542 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1543 } else if (C.Type == Constraint::Load) {
1544 if (C.Offset == 0) {
1545 // dest = *src edge
1546 if (!GraphNodes[C.Dest].PredEdges)
1547 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1548 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1549 } else {
1550 GraphNodes[C.Dest].Direct = false;
1551 }
1552 } else if (C.Type == Constraint::Store) {
1553 if (C.Offset == 0) {
1554 // *dest = src edge
1555 unsigned RefNode = C.Dest + FirstRefNode;
1556 if (!GraphNodes[RefNode].PredEdges)
1557 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1558 GraphNodes[RefNode].PredEdges->set(C.Src);
1559 }
1560 } else {
1561 // Dest = Src edge and *Dest = *Src edge
1562 if (!GraphNodes[C.Dest].PredEdges)
1563 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1564 GraphNodes[C.Dest].PredEdges->set(C.Src);
1565 unsigned RefNode = C.Dest + FirstRefNode;
1566 if (!GraphNodes[RefNode].ImplicitPredEdges)
1567 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1568 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1569 }
1570 }
1571 PEClass = 1;
1572 // Do SCC finding first to condense our predecessor graph
1573 DFSNumber = 0;
1574 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1575 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1576 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1577
1578 for (unsigned i = 0; i < FirstRefNode; ++i) {
1579 unsigned Node = VSSCCRep[i];
1580 if (!Node2Visited[Node])
1581 HVNValNum(Node);
1582 }
1583 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1584 Iter != Set2PEClass.end();
1585 ++Iter)
1586 delete Iter->first;
1587 Set2PEClass.clear();
1588 Node2DFS.clear();
1589 Node2Deleted.clear();
1590 Node2Visited.clear();
1591 DOUT << "Finished HVN\n";
1592
1593}
1594
1595/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1596/// same time because it's easy.
1597void Andersens::HVNValNum(unsigned NodeIndex) {
1598 unsigned MyDFS = DFSNumber++;
1599 Node *N = &GraphNodes[NodeIndex];
1600 Node2Visited[NodeIndex] = true;
1601 Node2DFS[NodeIndex] = MyDFS;
1602
1603 // First process all our explicit edges
1604 if (N->PredEdges)
1605 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1606 Iter != N->PredEdges->end();
1607 ++Iter) {
1608 unsigned j = VSSCCRep[*Iter];
1609 if (!Node2Deleted[j]) {
1610 if (!Node2Visited[j])
1611 HVNValNum(j);
1612 if (Node2DFS[NodeIndex] > Node2DFS[j])
1613 Node2DFS[NodeIndex] = Node2DFS[j];
1614 }
1615 }
1616
1617 // Now process all the implicit edges
1618 if (N->ImplicitPredEdges)
1619 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1620 Iter != N->ImplicitPredEdges->end();
1621 ++Iter) {
1622 unsigned j = VSSCCRep[*Iter];
1623 if (!Node2Deleted[j]) {
1624 if (!Node2Visited[j])
1625 HVNValNum(j);
1626 if (Node2DFS[NodeIndex] > Node2DFS[j])
1627 Node2DFS[NodeIndex] = Node2DFS[j];
1628 }
1629 }
1630
1631 // See if we found any cycles
1632 if (MyDFS == Node2DFS[NodeIndex]) {
1633 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1634 unsigned CycleNodeIndex = SCCStack.top();
1635 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1636 VSSCCRep[CycleNodeIndex] = NodeIndex;
1637 // Unify the nodes
1638 N->Direct &= CycleNode->Direct;
1639
1640 if (CycleNode->PredEdges) {
1641 if (!N->PredEdges)
1642 N->PredEdges = new SparseBitVector<>;
1643 *(N->PredEdges) |= CycleNode->PredEdges;
1644 delete CycleNode->PredEdges;
1645 CycleNode->PredEdges = NULL;
1646 }
1647 if (CycleNode->ImplicitPredEdges) {
1648 if (!N->ImplicitPredEdges)
1649 N->ImplicitPredEdges = new SparseBitVector<>;
1650 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1651 delete CycleNode->ImplicitPredEdges;
1652 CycleNode->ImplicitPredEdges = NULL;
1653 }
1654
1655 SCCStack.pop();
1656 }
1657
1658 Node2Deleted[NodeIndex] = true;
1659
1660 if (!N->Direct) {
1661 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1662 return;
1663 }
1664
1665 // Collect labels of successor nodes
1666 bool AllSame = true;
1667 unsigned First = ~0;
1668 SparseBitVector<> *Labels = new SparseBitVector<>;
1669 bool Used = false;
1670
1671 if (N->PredEdges)
1672 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1673 Iter != N->PredEdges->end();
1674 ++Iter) {
1675 unsigned j = VSSCCRep[*Iter];
1676 unsigned Label = GraphNodes[j].PointerEquivLabel;
1677 // Ignore labels that are equal to us or non-pointers
1678 if (j == NodeIndex || Label == 0)
1679 continue;
1680 if (First == (unsigned)~0)
1681 First = Label;
1682 else if (First != Label)
1683 AllSame = false;
1684 Labels->set(Label);
1685 }
1686
1687 // We either have a non-pointer, a copy of an existing node, or a new node.
1688 // Assign the appropriate pointer equivalence label.
1689 if (Labels->empty()) {
1690 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1691 } else if (AllSame) {
1692 GraphNodes[NodeIndex].PointerEquivLabel = First;
1693 } else {
1694 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1695 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1696 unsigned EquivClass = PEClass++;
1697 Set2PEClass[Labels] = EquivClass;
1698 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1699 Used = true;
1700 }
1701 }
1702 if (!Used)
1703 delete Labels;
1704 } else {
1705 SCCStack.push(NodeIndex);
1706 }
1707}
1708
1709/// The technique used here is described in "Exploiting Pointer and Location
1710/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1711/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1712/// and is equivalent to value numbering the collapsed constraint graph
1713/// including evaluating unions.
1714void Andersens::HU() {
1715 DOUT << "Beginning HU\n";
1716 // Build a predecessor graph. This is like our constraint graph with the
1717 // edges going in the opposite direction, and there are edges for all the
1718 // constraints, instead of just copy constraints. We also build implicit
1719 // edges for constraints are implied but not explicit. I.E for the constraint
1720 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1721 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1722 Constraint &C = Constraints[i];
1723 if (C.Type == Constraint::AddressOf) {
1724 GraphNodes[C.Src].AddressTaken = true;
1725 GraphNodes[C.Src].Direct = false;
1726
1727 GraphNodes[C.Dest].PointsTo->set(C.Src);
1728 // *Dest = src edge
1729 unsigned RefNode = C.Dest + FirstRefNode;
1730 if (!GraphNodes[RefNode].ImplicitPredEdges)
1731 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1732 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1733 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1734 } else if (C.Type == Constraint::Load) {
1735 if (C.Offset == 0) {
1736 // dest = *src edge
1737 if (!GraphNodes[C.Dest].PredEdges)
1738 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1739 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1740 } else {
1741 GraphNodes[C.Dest].Direct = false;
1742 }
1743 } else if (C.Type == Constraint::Store) {
1744 if (C.Offset == 0) {
1745 // *dest = src edge
1746 unsigned RefNode = C.Dest + FirstRefNode;
1747 if (!GraphNodes[RefNode].PredEdges)
1748 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1749 GraphNodes[RefNode].PredEdges->set(C.Src);
1750 }
1751 } else {
1752 // Dest = Src edge and *Dest = *Src edg
1753 if (!GraphNodes[C.Dest].PredEdges)
1754 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1755 GraphNodes[C.Dest].PredEdges->set(C.Src);
1756 unsigned RefNode = C.Dest + FirstRefNode;
1757 if (!GraphNodes[RefNode].ImplicitPredEdges)
1758 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1759 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1760 }
1761 }
1762 PEClass = 1;
1763 // Do SCC finding first to condense our predecessor graph
1764 DFSNumber = 0;
1765 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1766 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1767 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1768
1769 for (unsigned i = 0; i < FirstRefNode; ++i) {
1770 if (FindNode(i) == i) {
1771 unsigned Node = VSSCCRep[i];
1772 if (!Node2Visited[Node])
1773 Condense(Node);
1774 }
1775 }
1776
1777 // Reset tables for actual labeling
1778 Node2DFS.clear();
1779 Node2Visited.clear();
1780 Node2Deleted.clear();
1781 // Pre-grow our densemap so that we don't get really bad behavior
1782 Set2PEClass.resize(GraphNodes.size());
1783
1784 // Visit the condensed graph and generate pointer equivalence labels.
1785 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1786 for (unsigned i = 0; i < FirstRefNode; ++i) {
1787 if (FindNode(i) == i) {
1788 unsigned Node = VSSCCRep[i];
1789 if (!Node2Visited[Node])
1790 HUValNum(Node);
1791 }
1792 }
1793 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1794 Set2PEClass.clear();
1795 DOUT << "Finished HU\n";
1796}
1797
1798
1799/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1800void Andersens::Condense(unsigned NodeIndex) {
1801 unsigned MyDFS = DFSNumber++;
1802 Node *N = &GraphNodes[NodeIndex];
1803 Node2Visited[NodeIndex] = true;
1804 Node2DFS[NodeIndex] = MyDFS;
1805
1806 // First process all our explicit edges
1807 if (N->PredEdges)
1808 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1809 Iter != N->PredEdges->end();
1810 ++Iter) {
1811 unsigned j = VSSCCRep[*Iter];
1812 if (!Node2Deleted[j]) {
1813 if (!Node2Visited[j])
1814 Condense(j);
1815 if (Node2DFS[NodeIndex] > Node2DFS[j])
1816 Node2DFS[NodeIndex] = Node2DFS[j];
1817 }
1818 }
1819
1820 // Now process all the implicit edges
1821 if (N->ImplicitPredEdges)
1822 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1823 Iter != N->ImplicitPredEdges->end();
1824 ++Iter) {
1825 unsigned j = VSSCCRep[*Iter];
1826 if (!Node2Deleted[j]) {
1827 if (!Node2Visited[j])
1828 Condense(j);
1829 if (Node2DFS[NodeIndex] > Node2DFS[j])
1830 Node2DFS[NodeIndex] = Node2DFS[j];
1831 }
1832 }
1833
1834 // See if we found any cycles
1835 if (MyDFS == Node2DFS[NodeIndex]) {
1836 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1837 unsigned CycleNodeIndex = SCCStack.top();
1838 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1839 VSSCCRep[CycleNodeIndex] = NodeIndex;
1840 // Unify the nodes
1841 N->Direct &= CycleNode->Direct;
1842
1843 *(N->PointsTo) |= CycleNode->PointsTo;
1844 delete CycleNode->PointsTo;
1845 CycleNode->PointsTo = NULL;
1846 if (CycleNode->PredEdges) {
1847 if (!N->PredEdges)
1848 N->PredEdges = new SparseBitVector<>;
1849 *(N->PredEdges) |= CycleNode->PredEdges;
1850 delete CycleNode->PredEdges;
1851 CycleNode->PredEdges = NULL;
1852 }
1853 if (CycleNode->ImplicitPredEdges) {
1854 if (!N->ImplicitPredEdges)
1855 N->ImplicitPredEdges = new SparseBitVector<>;
1856 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1857 delete CycleNode->ImplicitPredEdges;
1858 CycleNode->ImplicitPredEdges = NULL;
1859 }
1860 SCCStack.pop();
1861 }
1862
1863 Node2Deleted[NodeIndex] = true;
1864
1865 // Set up number of incoming edges for other nodes
1866 if (N->PredEdges)
1867 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1868 Iter != N->PredEdges->end();
1869 ++Iter)
1870 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1871 } else {
1872 SCCStack.push(NodeIndex);
1873 }
1874}
1875
1876void Andersens::HUValNum(unsigned NodeIndex) {
1877 Node *N = &GraphNodes[NodeIndex];
1878 Node2Visited[NodeIndex] = true;
1879
1880 // Eliminate dereferences of non-pointers for those non-pointers we have
1881 // already identified. These are ref nodes whose non-ref node:
1882 // 1. Has already been visited determined to point to nothing (and thus, a
1883 // dereference of it must point to nothing)
1884 // 2. Any direct node with no predecessor edges in our graph and with no
1885 // points-to set (since it can't point to anything either, being that it
1886 // receives no points-to sets and has none).
1887 if (NodeIndex >= FirstRefNode) {
1888 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1889 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1890 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1891 && GraphNodes[j].PointsTo->empty())){
1892 return;
1893 }
1894 }
1895 // Process all our explicit edges
1896 if (N->PredEdges)
1897 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1898 Iter != N->PredEdges->end();
1899 ++Iter) {
1900 unsigned j = VSSCCRep[*Iter];
1901 if (!Node2Visited[j])
1902 HUValNum(j);
1903
1904 // If this edge turned out to be the same as us, or got no pointer
1905 // equivalence label (and thus points to nothing) , just decrement our
1906 // incoming edges and continue.
1907 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1908 --GraphNodes[j].NumInEdges;
1909 continue;
1910 }
1911
1912 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1913
1914 // If we didn't end up storing this in the hash, and we're done with all
1915 // the edges, we don't need the points-to set anymore.
1916 --GraphNodes[j].NumInEdges;
1917 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1918 delete GraphNodes[j].PointsTo;
1919 GraphNodes[j].PointsTo = NULL;
1920 }
1921 }
1922 // If this isn't a direct node, generate a fresh variable.
1923 if (!N->Direct) {
1924 N->PointsTo->set(FirstRefNode + NodeIndex);
1925 }
1926
1927 // See If we have something equivalent to us, if not, generate a new
1928 // equivalence class.
1929 if (N->PointsTo->empty()) {
1930 delete N->PointsTo;
1931 N->PointsTo = NULL;
1932 } else {
1933 if (N->Direct) {
1934 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1935 if (N->PointerEquivLabel == 0) {
1936 unsigned EquivClass = PEClass++;
1937 N->StoredInHash = true;
1938 Set2PEClass[N->PointsTo] = EquivClass;
1939 N->PointerEquivLabel = EquivClass;
1940 }
1941 } else {
1942 N->PointerEquivLabel = PEClass++;
1943 }
1944 }
1945}
1946
1947/// Rewrite our list of constraints so that pointer equivalent nodes are
1948/// replaced by their the pointer equivalence class representative.
1949void Andersens::RewriteConstraints() {
1950 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001951 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001952
1953 PEClass2Node.clear();
1954 PENLEClass2Node.clear();
1955
1956 // We may have from 1 to Graphnodes + 1 equivalence classes.
1957 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1958 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1959
1960 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1961 // nodes, and rewriting constraints to use the representative nodes.
1962 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1963 Constraint &C = Constraints[i];
1964 unsigned RHSNode = FindNode(C.Src);
1965 unsigned LHSNode = FindNode(C.Dest);
1966 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1967 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1968
1969 // First we try to eliminate constraints for things we can prove don't point
1970 // to anything.
1971 if (LHSLabel == 0) {
1972 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1973 DOUT << " is a non-pointer, ignoring constraint.\n";
1974 continue;
1975 }
1976 if (RHSLabel == 0) {
1977 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1978 DOUT << " is a non-pointer, ignoring constraint.\n";
1979 continue;
1980 }
1981 // This constraint may be useless, and it may become useless as we translate
1982 // it.
1983 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1984 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001985
Daniel Berlind81ccc22007-09-24 19:45:49 +00001986 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1987 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001988 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001989 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001990 continue;
1991
Chris Lattnerbe207732007-09-30 00:47:20 +00001992 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001993 NewConstraints.push_back(C);
1994 }
1995 Constraints.swap(NewConstraints);
1996 PEClass2Node.clear();
1997}
1998
1999/// See if we have a node that is pointer equivalent to the one being asked
2000/// about, and if so, unite them and return the equivalent node. Otherwise,
2001/// return the original node.
2002unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
2003 unsigned NodeLabel) {
2004 if (!GraphNodes[NodeIndex].AddressTaken) {
2005 if (PEClass2Node[NodeLabel] != -1) {
2006 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002007 // We specifically request that Union-By-Rank not be used so that
2008 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
2009 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002010 } else {
2011 PEClass2Node[NodeLabel] = NodeIndex;
2012 PENLEClass2Node[NodeLabel] = NodeIndex;
2013 }
2014 } else if (PENLEClass2Node[NodeLabel] == -1) {
2015 PENLEClass2Node[NodeLabel] = NodeIndex;
2016 }
2017
2018 return NodeIndex;
2019}
2020
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002021void Andersens::PrintLabels() const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002022 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2023 if (i < FirstRefNode) {
2024 PrintNode(&GraphNodes[i]);
2025 } else if (i < FirstAdrNode) {
2026 DOUT << "REF(";
2027 PrintNode(&GraphNodes[i-FirstRefNode]);
2028 DOUT <<")";
2029 } else {
2030 DOUT << "ADR(";
2031 PrintNode(&GraphNodes[i-FirstAdrNode]);
2032 DOUT <<")";
2033 }
2034
2035 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2036 << " and SCC rep " << VSSCCRep[i]
2037 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2038 << "\n";
2039 }
2040}
2041
Daniel Berlinc864edb2008-03-05 19:31:47 +00002042/// The technique used here is described in "The Ant and the
2043/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2044/// Lines of Code. In Programming Language Design and Implementation
2045/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2046/// Detection) algorithm. It is called a hybrid because it performs an
2047/// offline analysis and uses its results during the solving (online)
2048/// phase. This is just the offline portion; the results of this
2049/// operation are stored in SDT and are later used in SolveContraints()
2050/// and UniteNodes().
2051void Andersens::HCD() {
2052 DOUT << "Starting HCD.\n";
2053 HCDSCCRep.resize(GraphNodes.size());
2054
2055 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2056 GraphNodes[i].Edges = new SparseBitVector<>;
2057 HCDSCCRep[i] = i;
2058 }
2059
2060 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2061 Constraint &C = Constraints[i];
2062 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2063 if (C.Type == Constraint::AddressOf) {
2064 continue;
2065 } else if (C.Type == Constraint::Load) {
2066 if( C.Offset == 0 )
2067 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2068 } else if (C.Type == Constraint::Store) {
2069 if( C.Offset == 0 )
2070 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2071 } else {
2072 GraphNodes[C.Dest].Edges->set(C.Src);
2073 }
2074 }
2075
2076 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2077 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2078 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2079 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2080
2081 DFSNumber = 0;
2082 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2083 unsigned Node = HCDSCCRep[i];
2084 if (!Node2Deleted[Node])
2085 Search(Node);
2086 }
2087
2088 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2089 if (GraphNodes[i].Edges != NULL) {
2090 delete GraphNodes[i].Edges;
2091 GraphNodes[i].Edges = NULL;
2092 }
2093
2094 while( !SCCStack.empty() )
2095 SCCStack.pop();
2096
2097 Node2DFS.clear();
2098 Node2Visited.clear();
2099 Node2Deleted.clear();
2100 HCDSCCRep.clear();
2101 DOUT << "HCD complete.\n";
2102}
2103
2104// Component of HCD:
2105// Use Nuutila's variant of Tarjan's algorithm to detect
2106// Strongly-Connected Components (SCCs). For non-trivial SCCs
2107// containing ref nodes, insert the appropriate information in SDT.
2108void Andersens::Search(unsigned Node) {
2109 unsigned MyDFS = DFSNumber++;
2110
2111 Node2Visited[Node] = true;
2112 Node2DFS[Node] = MyDFS;
2113
2114 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2115 End = GraphNodes[Node].Edges->end();
2116 Iter != End;
2117 ++Iter) {
2118 unsigned J = HCDSCCRep[*Iter];
2119 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2120 if (!Node2Deleted[J]) {
2121 if (!Node2Visited[J])
2122 Search(J);
2123 if (Node2DFS[Node] > Node2DFS[J])
2124 Node2DFS[Node] = Node2DFS[J];
2125 }
2126 }
2127
2128 if( MyDFS != Node2DFS[Node] ) {
2129 SCCStack.push(Node);
2130 return;
2131 }
2132
2133 // This node is the root of a SCC, so process it.
2134 //
2135 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2136 // node, we place this SCC into SDT. We unite the nodes in any case.
2137 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2138 SparseBitVector<> SCC;
2139
2140 SCC.set(Node);
2141
2142 bool Ref = (Node >= FirstRefNode);
2143
2144 Node2Deleted[Node] = true;
2145
2146 do {
2147 unsigned P = SCCStack.top(); SCCStack.pop();
2148 Ref |= (P >= FirstRefNode);
2149 SCC.set(P);
2150 HCDSCCRep[P] = Node;
2151 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2152
2153 if (Ref) {
2154 unsigned Rep = SCC.find_first();
2155 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2156
2157 SparseBitVector<>::iterator i = SCC.begin();
2158
2159 // Skip over the non-ref nodes
2160 while( *i < FirstRefNode )
2161 ++i;
2162
2163 while( i != SCC.end() )
2164 SDT[ (*i++) - FirstRefNode ] = Rep;
2165 }
2166 }
2167}
2168
2169
Daniel Berlind81ccc22007-09-24 19:45:49 +00002170/// Optimize the constraints by performing offline variable substitution and
2171/// other optimizations.
2172void Andersens::OptimizeConstraints() {
2173 DOUT << "Beginning constraint optimization\n";
2174
Daniel Berlinc864edb2008-03-05 19:31:47 +00002175 SDTActive = false;
2176
Daniel Berlind81ccc22007-09-24 19:45:49 +00002177 // Function related nodes need to stay in the same relative position and can't
2178 // be location equivalent.
2179 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2180 Iter != MaxK.end();
2181 ++Iter) {
2182 for (unsigned i = Iter->first;
2183 i != Iter->first + Iter->second;
2184 ++i) {
2185 GraphNodes[i].AddressTaken = true;
2186 GraphNodes[i].Direct = false;
2187 }
2188 }
2189
2190 ClumpAddressTaken();
2191 FirstRefNode = GraphNodes.size();
2192 FirstAdrNode = FirstRefNode + GraphNodes.size();
2193 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2194 Node(false));
2195 VSSCCRep.resize(GraphNodes.size());
2196 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2197 VSSCCRep[i] = i;
2198 }
2199 HVN();
2200 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2201 Node *N = &GraphNodes[i];
2202 delete N->PredEdges;
2203 N->PredEdges = NULL;
2204 delete N->ImplicitPredEdges;
2205 N->ImplicitPredEdges = NULL;
2206 }
2207#undef DEBUG_TYPE
2208#define DEBUG_TYPE "anders-aa-labels"
2209 DEBUG(PrintLabels());
2210#undef DEBUG_TYPE
2211#define DEBUG_TYPE "anders-aa"
2212 RewriteConstraints();
2213 // Delete the adr nodes.
2214 GraphNodes.resize(FirstRefNode * 2);
2215
2216 // Now perform HU
2217 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2218 Node *N = &GraphNodes[i];
2219 if (FindNode(i) == i) {
2220 N->PointsTo = new SparseBitVector<>;
2221 N->PointedToBy = new SparseBitVector<>;
2222 // Reset our labels
2223 }
2224 VSSCCRep[i] = i;
2225 N->PointerEquivLabel = 0;
2226 }
2227 HU();
2228#undef DEBUG_TYPE
2229#define DEBUG_TYPE "anders-aa-labels"
2230 DEBUG(PrintLabels());
2231#undef DEBUG_TYPE
2232#define DEBUG_TYPE "anders-aa"
2233 RewriteConstraints();
2234 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2235 if (FindNode(i) == i) {
2236 Node *N = &GraphNodes[i];
2237 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002238 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002239 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002240 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002241 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002242 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002243 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002244 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002245 }
2246 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002247
2248 // perform Hybrid Cycle Detection (HCD)
2249 HCD();
2250 SDTActive = true;
2251
2252 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002253 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002254
2255 // HCD complete.
2256
Daniel Berlind81ccc22007-09-24 19:45:49 +00002257 DOUT << "Finished constraint optimization\n";
2258 FirstRefNode = 0;
2259 FirstAdrNode = 0;
2260}
2261
2262/// Unite pointer but not location equivalent variables, now that the constraint
2263/// graph is built.
2264void Andersens::UnitePointerEquivalences() {
2265 DOUT << "Uniting remaining pointer equivalences\n";
2266 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002267 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002268 unsigned Label = GraphNodes[i].PointerEquivLabel;
2269
2270 if (Label && PENLEClass2Node[Label] != -1)
2271 UniteNodes(i, PENLEClass2Node[Label]);
2272 }
2273 }
2274 DOUT << "Finished remaining pointer equivalences\n";
2275 PENLEClass2Node.clear();
2276}
2277
2278/// Create the constraint graph used for solving points-to analysis.
2279///
Daniel Berlinaad15882007-09-16 21:45:02 +00002280void Andersens::CreateConstraintGraph() {
2281 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2282 Constraint &C = Constraints[i];
2283 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2284 if (C.Type == Constraint::AddressOf)
2285 GraphNodes[C.Dest].PointsTo->set(C.Src);
2286 else if (C.Type == Constraint::Load)
2287 GraphNodes[C.Src].Constraints.push_back(C);
2288 else if (C.Type == Constraint::Store)
2289 GraphNodes[C.Dest].Constraints.push_back(C);
2290 else if (C.Offset != 0)
2291 GraphNodes[C.Src].Constraints.push_back(C);
2292 else
2293 GraphNodes[C.Src].Edges->set(C.Dest);
2294 }
2295}
2296
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002297// Perform DFS and cycle detection.
2298bool Andersens::QueryNode(unsigned Node) {
2299 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002300 unsigned OurDFS = ++DFSNumber;
2301 SparseBitVector<> ToErase;
2302 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002303 Tarjan2DFS[Node] = OurDFS;
2304
2305 // Changed denotes a change from a recursive call that we will bubble up.
2306 // Merged is set if we actually merge a node ourselves.
2307 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002308
2309 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2310 bi != GraphNodes[Node].Edges->end();
2311 ++bi) {
2312 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002313 // If this edge points to a non-representative node but we are
2314 // already planning to add an edge to its representative, we have no
2315 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002316 if (RepNode != *bi && NewEdges.test(RepNode)){
2317 ToErase.set(*bi);
2318 continue;
2319 }
2320
2321 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002322 if (!Tarjan2Deleted[RepNode]){
2323 if (Tarjan2DFS[RepNode] == 0) {
2324 Changed |= QueryNode(RepNode);
2325 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002326 RepNode = FindNode(RepNode);
2327 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002328 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2329 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002330 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002331
2332 // We may have just discovered that this node is part of a cycle, in
2333 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002334 if (RepNode != *bi) {
2335 ToErase.set(*bi);
2336 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002337 }
2338 }
2339
Daniel Berlinaad15882007-09-16 21:45:02 +00002340 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2341 GraphNodes[Node].Edges |= NewEdges;
2342
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002343 // If this node is a root of a non-trivial SCC, place it on our
2344 // worklist to be processed.
2345 if (OurDFS == Tarjan2DFS[Node]) {
2346 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2347 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002348
2349 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002350 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002351 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002352 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002353
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002354 if (Merged)
2355 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002356 } else {
2357 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002358 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002359
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002360 return(Changed | Merged);
2361}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002362
2363/// SolveConstraints - This stage iteratively processes the constraints list
2364/// propagating constraints (adding edges to the Nodes in the points-to graph)
2365/// until a fixed point is reached.
2366///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002367/// We use a variant of the technique called "Lazy Cycle Detection", which is
2368/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2369/// Analysis for Millions of Lines of Code. In Programming Language Design and
2370/// Implementation (PLDI), June 2007."
2371/// The paper describes performing cycle detection one node at a time, which can
2372/// be expensive if there are no cycles, but there are long chains of nodes that
2373/// it heuristically believes are cycles (because it will DFS from each node
2374/// without state from previous nodes).
2375/// Instead, we use the heuristic to build a worklist of nodes to check, then
2376/// cycle detect them all at the same time to do this more cheaply. This
2377/// catches cycles slightly later than the original technique did, but does it
2378/// make significantly cheaper.
2379
Chris Lattnere995a2a2004-05-23 21:00:47 +00002380void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002381 CurrWL = &w1;
2382 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002383
Daniel Berlind81ccc22007-09-24 19:45:49 +00002384 OptimizeConstraints();
2385#undef DEBUG_TYPE
2386#define DEBUG_TYPE "anders-aa-constraints"
2387 DEBUG(PrintConstraints());
2388#undef DEBUG_TYPE
2389#define DEBUG_TYPE "anders-aa"
2390
Daniel Berlinaad15882007-09-16 21:45:02 +00002391 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2392 Node *N = &GraphNodes[i];
2393 N->PointsTo = new SparseBitVector<>;
2394 N->OldPointsTo = new SparseBitVector<>;
2395 N->Edges = new SparseBitVector<>;
2396 }
2397 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002398 UnitePointerEquivalences();
2399 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002400 Node2DFS.clear();
2401 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002402 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2403 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2404 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002405 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2406 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2407
2408 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002409 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002410 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002411
2412 // Add to work list if it's a representative and can contribute to the
2413 // calculation right now.
2414 if (INode->isRep() && !INode->PointsTo->empty()
2415 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2416 INode->Stamp();
2417 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002418 }
2419 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002420 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002421#if !FULL_UNIVERSAL
2422 // "Rep and special variables" - in order for HCD to maintain conservative
2423 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2424 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2425 // the analysis - it's ok to add edges from the special nodes, but never
2426 // *to* the special nodes.
2427 std::vector<unsigned int> RSV;
2428#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002429 while( !CurrWL->empty() ) {
2430 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002431
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002432 Node* CurrNode;
2433 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002434
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002435 // Actual cycle checking code. We cycle check all of the lazy cycle
2436 // candidates from the last iteration in one go.
2437 if (!TarjanWL.empty()) {
2438 DFSNumber = 0;
2439
2440 Tarjan2DFS.clear();
2441 Tarjan2Deleted.clear();
2442 while (!TarjanWL.empty()) {
2443 unsigned int ToTarjan = TarjanWL.front();
2444 TarjanWL.pop();
2445 if (!Tarjan2Deleted[ToTarjan]
2446 && GraphNodes[ToTarjan].isRep()
2447 && Tarjan2DFS[ToTarjan] == 0)
2448 QueryNode(ToTarjan);
2449 }
2450 }
2451
2452 // Add to work list if it's a representative and can contribute to the
2453 // calculation right now.
2454 while( (CurrNode = CurrWL->pop()) != NULL ) {
2455 CurrNodeIndex = CurrNode - &GraphNodes[0];
2456 CurrNode->Stamp();
2457
2458
Daniel Berlinaad15882007-09-16 21:45:02 +00002459 // Figure out the changed points to bits
2460 SparseBitVector<> CurrPointsTo;
2461 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2462 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002463 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002464 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002465
Daniel Berlinaad15882007-09-16 21:45:02 +00002466 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002467
2468 // Check the offline-computed equivalencies from HCD.
2469 bool SCC = false;
2470 unsigned Rep;
2471
2472 if (SDT[CurrNodeIndex] >= 0) {
2473 SCC = true;
2474 Rep = FindNode(SDT[CurrNodeIndex]);
2475
2476#if !FULL_UNIVERSAL
2477 RSV.clear();
2478#endif
2479 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2480 bi != CurrPointsTo.end(); ++bi) {
2481 unsigned Node = FindNode(*bi);
2482#if !FULL_UNIVERSAL
2483 if (Node < NumberSpecialNodes) {
2484 RSV.push_back(Node);
2485 continue;
2486 }
2487#endif
2488 Rep = UniteNodes(Rep,Node);
2489 }
2490#if !FULL_UNIVERSAL
2491 RSV.push_back(Rep);
2492#endif
2493
2494 NextWL->insert(&GraphNodes[Rep]);
2495
2496 if ( ! CurrNode->isRep() )
2497 continue;
2498 }
2499
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002500 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002501
Daniel Berlinaad15882007-09-16 21:45:02 +00002502 /* Now process the constraints for this node. */
2503 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2504 li != CurrNode->Constraints.end(); ) {
2505 li->Src = FindNode(li->Src);
2506 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002507
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002508 // Delete redundant constraints
2509 if( Seen.count(*li) ) {
2510 std::list<Constraint>::iterator lk = li; li++;
2511
2512 CurrNode->Constraints.erase(lk);
2513 ++NumErased;
2514 continue;
2515 }
2516 Seen.insert(*li);
2517
Daniel Berlinaad15882007-09-16 21:45:02 +00002518 // Src and Dest will be the vars we are going to process.
2519 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002520 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002521 // Load constraints say that every member of our RHS solution has K
2522 // added to it, and that variable gets an edge to LHS. We also union
2523 // RHS+K's solution into the LHS solution.
2524 // Store constraints say that every member of our LHS solution has K
2525 // added to it, and that variable gets an edge from RHS. We also union
2526 // RHS's solution into the LHS+K solution.
2527 unsigned *Src;
2528 unsigned *Dest;
2529 unsigned K = li->Offset;
2530 unsigned CurrMember;
2531 if (li->Type == Constraint::Load) {
2532 Src = &CurrMember;
2533 Dest = &li->Dest;
2534 } else if (li->Type == Constraint::Store) {
2535 Src = &li->Src;
2536 Dest = &CurrMember;
2537 } else {
2538 // TODO Handle offseted copy constraint
2539 li++;
2540 continue;
2541 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002542
2543 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002544 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002545 // involves pointers; if so, remove the redundant constraints).
2546 if( SCC && K == 0 ) {
2547#if FULL_UNIVERSAL
2548 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002549
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002550 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2551 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2552 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002553#else
2554 for (unsigned i=0; i < RSV.size(); ++i) {
2555 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002556
Daniel Berlinc864edb2008-03-05 19:31:47 +00002557 if (*Dest < NumberSpecialNodes)
2558 continue;
2559 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2560 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2561 NextWL->insert(&GraphNodes[*Dest]);
2562 }
2563#endif
2564 // since all future elements of the points-to set will be
2565 // equivalent to the current ones, the complex constraints
2566 // become redundant.
2567 //
2568 std::list<Constraint>::iterator lk = li; li++;
2569#if !FULL_UNIVERSAL
2570 // In this case, we can still erase the constraints when the
2571 // elements of the points-to sets are referenced by *Dest,
2572 // but not when they are referenced by *Src (i.e. for a Load
2573 // constraint). This is because if another special variable is
2574 // put into the points-to set later, we still need to add the
2575 // new edge from that special variable.
2576 if( lk->Type != Constraint::Load)
2577#endif
2578 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2579 } else {
2580 const SparseBitVector<> &Solution = CurrPointsTo;
2581
2582 for (SparseBitVector<>::iterator bi = Solution.begin();
2583 bi != Solution.end();
2584 ++bi) {
2585 CurrMember = *bi;
2586
2587 // Need to increment the member by K since that is where we are
2588 // supposed to copy to/from. Note that in positive weight cycles,
2589 // which occur in address taking of fields, K can go past
2590 // MaxK[CurrMember] elements, even though that is all it could point
2591 // to.
2592 if (K > 0 && K > MaxK[CurrMember])
2593 continue;
2594 else
2595 CurrMember = FindNode(CurrMember + K);
2596
2597 // Add an edge to the graph, so we can just do regular
2598 // bitmap ior next time. It may also let us notice a cycle.
2599#if !FULL_UNIVERSAL
2600 if (*Dest < NumberSpecialNodes)
2601 continue;
2602#endif
2603 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2604 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2605 NextWL->insert(&GraphNodes[*Dest]);
2606
2607 }
2608 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002609 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002610 }
2611 SparseBitVector<> NewEdges;
2612 SparseBitVector<> ToErase;
2613
2614 // Now all we have left to do is propagate points-to info along the
2615 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002616 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2617 bi != CurrNode->Edges->end();
2618 ++bi) {
2619
2620 unsigned DestVar = *bi;
2621 unsigned Rep = FindNode(DestVar);
2622
Bill Wendlingf059deb2008-02-26 10:51:52 +00002623 // If we ended up with this node as our destination, or we've already
2624 // got an edge for the representative, delete the current edge.
2625 if (Rep == CurrNodeIndex ||
2626 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002627 ToErase.set(DestVar);
2628 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002629 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002630
Bill Wendlingf059deb2008-02-26 10:51:52 +00002631 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002632
2633 // This is where we do lazy cycle detection.
2634 // If this is a cycle candidate (equal points-to sets and this
2635 // particular edge has not been cycle-checked previously), add to the
2636 // list to check for cycles on the next iteration.
2637 if (!EdgesChecked.count(edge) &&
2638 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2639 EdgesChecked.insert(edge);
2640 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002641 }
2642 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002643#if !FULL_UNIVERSAL
2644 if (Rep >= NumberSpecialNodes)
2645#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002646 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002647 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002648 }
2649 // If this edge's destination was collapsed, rewrite the edge.
2650 if (Rep != DestVar) {
2651 ToErase.set(DestVar);
2652 NewEdges.set(Rep);
2653 }
2654 }
2655 CurrNode->Edges->intersectWithComplement(ToErase);
2656 CurrNode->Edges |= NewEdges;
2657 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002658
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002659 // Switch to other work list.
2660 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2661 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002662
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002663
Daniel Berlinaad15882007-09-16 21:45:02 +00002664 Node2DFS.clear();
2665 Node2Deleted.clear();
2666 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2667 Node *N = &GraphNodes[i];
2668 delete N->OldPointsTo;
2669 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002670 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002671 SDTActive = false;
2672 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002673}
2674
Daniel Berlinaad15882007-09-16 21:45:02 +00002675//===----------------------------------------------------------------------===//
2676// Union-Find
2677//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002678
Daniel Berlinaad15882007-09-16 21:45:02 +00002679// Unite nodes First and Second, returning the one which is now the
2680// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002681unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2682 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002683 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2684 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002685
Daniel Berlinaad15882007-09-16 21:45:02 +00002686 Node *FirstNode = &GraphNodes[First];
2687 Node *SecondNode = &GraphNodes[Second];
2688
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002689 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002690 "Trying to unite two non-representative nodes!");
2691 if (First == Second)
2692 return First;
2693
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002694 if (UnionByRank) {
2695 int RankFirst = (int) FirstNode ->NodeRep;
2696 int RankSecond = (int) SecondNode->NodeRep;
2697
2698 // Rank starts at -1 and gets decremented as it increases.
2699 // Translation: higher rank, lower NodeRep value, which is always negative.
2700 if (RankFirst > RankSecond) {
2701 unsigned t = First; First = Second; Second = t;
2702 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2703 } else if (RankFirst == RankSecond) {
2704 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2705 }
2706 }
2707
Daniel Berlinaad15882007-09-16 21:45:02 +00002708 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002709#if !FULL_UNIVERSAL
2710 if (First >= NumberSpecialNodes)
2711#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002712 if (FirstNode->PointsTo && SecondNode->PointsTo)
2713 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2714 if (FirstNode->Edges && SecondNode->Edges)
2715 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002716 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002717 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2718 SecondNode->Constraints);
2719 if (FirstNode->OldPointsTo) {
2720 delete FirstNode->OldPointsTo;
2721 FirstNode->OldPointsTo = new SparseBitVector<>;
2722 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002723
2724 // Destroy interesting parts of the merged-from node.
2725 delete SecondNode->OldPointsTo;
2726 delete SecondNode->Edges;
2727 delete SecondNode->PointsTo;
2728 SecondNode->Edges = NULL;
2729 SecondNode->PointsTo = NULL;
2730 SecondNode->OldPointsTo = NULL;
2731
2732 NumUnified++;
2733 DOUT << "Unified Node ";
2734 DEBUG(PrintNode(FirstNode));
2735 DOUT << " and Node ";
2736 DEBUG(PrintNode(SecondNode));
2737 DOUT << "\n";
2738
Daniel Berlinc864edb2008-03-05 19:31:47 +00002739 if (SDTActive)
Duncan Sands43e2a032008-05-27 11:50:51 +00002740 if (SDT[Second] >= 0) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002741 if (SDT[First] < 0)
2742 SDT[First] = SDT[Second];
2743 else {
2744 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2745 First = FindNode(First);
2746 }
Duncan Sands43e2a032008-05-27 11:50:51 +00002747 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002748
Daniel Berlinaad15882007-09-16 21:45:02 +00002749 return First;
2750}
2751
2752// Find the index into GraphNodes of the node representing Node, performing
2753// path compression along the way
2754unsigned Andersens::FindNode(unsigned NodeIndex) {
2755 assert (NodeIndex < GraphNodes.size()
2756 && "Attempting to find a node that can't exist");
2757 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002758 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002759 return NodeIndex;
2760 else
2761 return (N->NodeRep = FindNode(N->NodeRep));
2762}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002763
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002764// Find the index into GraphNodes of the node representing Node,
2765// don't perform path compression along the way (for Print)
2766unsigned Andersens::FindNode(unsigned NodeIndex) const {
2767 assert (NodeIndex < GraphNodes.size()
2768 && "Attempting to find a node that can't exist");
2769 const Node *N = &GraphNodes[NodeIndex];
2770 if (N->isRep())
2771 return NodeIndex;
2772 else
2773 return FindNode(N->NodeRep);
2774}
2775
Chris Lattnere995a2a2004-05-23 21:00:47 +00002776//===----------------------------------------------------------------------===//
2777// Debugging Output
2778//===----------------------------------------------------------------------===//
2779
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002780void Andersens::PrintNode(const Node *N) const {
Chris Lattnere995a2a2004-05-23 21:00:47 +00002781 if (N == &GraphNodes[UniversalSet]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002782 errs() << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002783 return;
2784 } else if (N == &GraphNodes[NullPtr]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002785 errs() << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002786 return;
2787 } else if (N == &GraphNodes[NullObject]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002788 errs() << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002789 return;
2790 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002791 if (!N->getValue()) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002792 errs() << "artificial" << (intptr_t) N;
Daniel Berlinaad15882007-09-16 21:45:02 +00002793 return;
2794 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002795
2796 assert(N->getValue() != 0 && "Never set node label!");
2797 Value *V = N->getValue();
2798 if (Function *F = dyn_cast<Function>(V)) {
2799 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002800 N == &GraphNodes[getReturnNode(F)]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002801 errs() << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002802 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002803 } else if (F->getFunctionType()->isVarArg() &&
2804 N == &GraphNodes[getVarargNode(F)]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002805 errs() << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002806 return;
2807 }
2808 }
2809
2810 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002811 errs() << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002812 else if (Argument *Arg = dyn_cast<Argument>(V))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002813 errs() << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002814
2815 if (V->hasName())
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002816 errs() << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002817 else
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002818 errs() << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002819
2820 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002821 if (N == &GraphNodes[getObject(V)])
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002822 errs() << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002823}
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002824void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002825 if (C.Type == Constraint::Store) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002826 errs() << "*";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002827 if (C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002828 errs() << "(";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002829 }
2830 PrintNode(&GraphNodes[C.Dest]);
2831 if (C.Type == Constraint::Store && C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002832 errs() << " + " << C.Offset << ")";
2833 errs() << " = ";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002834 if (C.Type == Constraint::Load) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002835 errs() << "*";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002836 if (C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002837 errs() << "(";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002838 }
2839 else if (C.Type == Constraint::AddressOf)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002840 errs() << "&";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002841 PrintNode(&GraphNodes[C.Src]);
2842 if (C.Offset != 0 && C.Type != Constraint::Store)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002843 errs() << " + " << C.Offset;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002844 if (C.Type == Constraint::Load && C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002845 errs() << ")";
2846 errs() << "\n";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002847}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002848
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002849void Andersens::PrintConstraints() const {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002850 errs() << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002851
Daniel Berlind81ccc22007-09-24 19:45:49 +00002852 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2853 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002854}
2855
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002856void Andersens::PrintPointsToGraph() const {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002857 errs() << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002858 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002859 const Node *N = &GraphNodes[i];
2860 if (FindNode(i) != i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002861 PrintNode(N);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002862 errs() << "\t--> same as ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002863 PrintNode(&GraphNodes[FindNode(i)]);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002864 errs() << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002865 } else {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002866 errs() << "[" << (N->PointsTo->count()) << "] ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002867 PrintNode(N);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002868 errs() << "\t--> ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002869
2870 bool first = true;
2871 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2872 bi != N->PointsTo->end();
2873 ++bi) {
2874 if (!first)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002875 errs() << ", ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002876 PrintNode(&GraphNodes[*bi]);
2877 first = false;
2878 }
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002879 errs() << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002880 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002881 }
2882}