blob: 1c9159dfbfcc103a551cdcd839f484c83ca20f14 [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"
Victor Hernandez46e83122009-09-18 21:34:51 +000067#include "llvm/Analysis/MallocHelper.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000068#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000069#include "llvm/Support/Debug.h"
Owen Anderson2e693102009-06-24 22:16:52 +000070#include "llvm/System/Atomic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000071#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000072#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000073#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000074#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000075#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000076#include <list>
Dan Gohmanc9235d22008-03-21 23:51:57 +000077#include <map>
Daniel Berlinaad15882007-09-16 21:45:02 +000078#include <stack>
79#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000080#include <queue>
81
82// Determining the actual set of nodes the universal set can consist of is very
83// expensive because it means propagating around very large sets. We rely on
84// other analysis being able to determine which nodes can never be pointed to in
85// order to disambiguate further than "points-to anything".
86#define FULL_UNIVERSAL 0
Chris Lattnere995a2a2004-05-23 21:00:47 +000087
Daniel Berlinaad15882007-09-16 21:45:02 +000088using namespace llvm;
Daniel Dunbare317bcc2009-08-23 10:29:55 +000089#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +000090STATISTIC(NumIters , "Number of iterations to reach convergence");
Daniel Dunbare317bcc2009-08-23 10:29:55 +000091#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +000092STATISTIC(NumConstraints, "Number of constraints");
93STATISTIC(NumNodes , "Number of nodes");
94STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000095STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000096
Dan Gohman844731a2008-05-13 00:00:25 +000097static const unsigned SelfRep = (unsigned)-1;
98static const unsigned Unvisited = (unsigned)-1;
99// Position of the function return node relative to the function node.
100static const unsigned CallReturnPos = 1;
101// Position of the function call node relative to the function node.
102static const unsigned CallFirstArgPos = 2;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000103
Dan Gohman844731a2008-05-13 00:00:25 +0000104namespace {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000105 struct BitmapKeyInfo {
106 static inline SparseBitVector<> *getEmptyKey() {
107 return reinterpret_cast<SparseBitVector<> *>(-1);
108 }
109 static inline SparseBitVector<> *getTombstoneKey() {
110 return reinterpret_cast<SparseBitVector<> *>(-2);
111 }
112 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
113 return bitmap->getHashValue();
114 }
115 static bool isEqual(const SparseBitVector<> *LHS,
116 const SparseBitVector<> *RHS) {
117 if (LHS == RHS)
118 return true;
119 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
120 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
121 return false;
122
123 return *LHS == *RHS;
124 }
125
126 static bool isPod() { return true; }
127 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000128
Reid Spencerd7d83db2007-02-05 23:42:17 +0000129 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
130 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000131 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000132
133 /// Constraint - Objects of this structure are used to represent the various
134 /// constraints identified by the algorithm. The constraints are 'copy',
135 /// for statements like "A = B", 'load' for statements like "A = *B",
136 /// 'store' for statements like "*A = B", and AddressOf for statements like
137 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
138 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000139 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000140 /// resolvable to A = &C where C = B + K)
141
142 struct Constraint {
143 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
144 unsigned Dest;
145 unsigned Src;
146 unsigned Offset;
147
148 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
149 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000150 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000151 "Offset is illegal on addressof constraints");
152 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000153
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000154 bool operator==(const Constraint &RHS) const {
155 return RHS.Type == Type
156 && RHS.Dest == Dest
157 && RHS.Src == Src
158 && RHS.Offset == Offset;
159 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000160
161 bool operator!=(const Constraint &RHS) const {
162 return !(*this == RHS);
163 }
164
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000165 bool operator<(const Constraint &RHS) const {
166 if (RHS.Type != Type)
167 return RHS.Type < Type;
168 else if (RHS.Dest != Dest)
169 return RHS.Dest < Dest;
170 else if (RHS.Src != Src)
171 return RHS.Src < Src;
172 return RHS.Offset < Offset;
173 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000174 };
175
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000176 // Information DenseSet requires implemented in order to be able to do
177 // it's thing
178 struct PairKeyInfo {
179 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000180 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000181 }
182 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000183 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000184 }
185 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
186 return P.first ^ P.second;
187 }
188 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
189 const std::pair<unsigned, unsigned> &RHS) {
190 return LHS == RHS;
191 }
192 };
193
Daniel Berlin336c6c02007-09-29 00:50:40 +0000194 struct ConstraintKeyInfo {
195 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000196 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000197 }
198 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000199 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000200 }
201 static unsigned getHashValue(const Constraint &C) {
202 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
203 }
204 static bool isEqual(const Constraint &LHS,
205 const Constraint &RHS) {
206 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
207 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
208 }
209 };
210
Daniel Berlind81ccc22007-09-24 19:45:49 +0000211 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000212 // graph. Due to various optimizations, it is not always the case that
213 // there is a mapping from a Node to a Value. In particular, we add
214 // artificial Node's that represent the set of pointed-to variables shared
215 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000216 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000217 private:
Owen Anderson5ec56cc2009-06-30 05:33:46 +0000218 static volatile sys::cas_flag Counter;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000219
220 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000221 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000222 SparseBitVector<> *Edges;
223 SparseBitVector<> *PointsTo;
224 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000225 std::list<Constraint> Constraints;
226
Daniel Berlind81ccc22007-09-24 19:45:49 +0000227 // Pointer and location equivalence labels
228 unsigned PointerEquivLabel;
229 unsigned LocationEquivLabel;
230 // Predecessor edges, both real and implicit
231 SparseBitVector<> *PredEdges;
232 SparseBitVector<> *ImplicitPredEdges;
233 // Set of nodes that point to us, only use for location equivalence.
234 SparseBitVector<> *PointedToBy;
235 // Number of incoming edges, used during variable substitution to early
236 // free the points-to sets
237 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000238 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000239 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000240 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000241 bool Direct;
242 // True if the node is address taken, *or* it is part of a group of nodes
243 // that must be kept together. This is set to true for functions and
244 // their arg nodes, which must be kept at the same position relative to
245 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000246 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000247
Daniel Berlind81ccc22007-09-24 19:45:49 +0000248 // Nodes in cycles (or in equivalence classes) are united together using a
249 // standard union-find representation with path compression. NodeRep
250 // gives the index into GraphNodes for the representative Node.
251 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000252
253 // Modification timestamp. Assigned from Counter.
254 // Used for work list prioritization.
255 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000256
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000257 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000258 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000259 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
260 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
261 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000262 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000263
Chris Lattnere995a2a2004-05-23 21:00:47 +0000264 Node *setValue(Value *V) {
265 assert(Val == 0 && "Value already set for this node!");
266 Val = V;
267 return this;
268 }
269
270 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000271 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000272 Value *getValue() const { return Val; }
273
Chris Lattnere995a2a2004-05-23 21:00:47 +0000274 /// addPointerTo - Add a pointer to the list of pointees of this node,
275 /// returning true if this caused a new pointer to be added, or false if
276 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000277 bool addPointerTo(unsigned Node) {
278 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000279 }
280
281 /// intersects - Return true if the points-to set of this node intersects
282 /// with the points-to set of the specified node.
283 bool intersects(Node *N) const;
284
285 /// intersectsIgnoring - Return true if the points-to set of this node
286 /// intersects with the points-to set of the specified node on any nodes
287 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000288 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000289
290 // Timestamp a node (used for work list prioritization)
291 void Stamp() {
Owen Anderson2d7f78e2009-06-25 16:32:45 +0000292 Timestamp = sys::AtomicIncrement(&Counter);
293 --Timestamp;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000294 }
295
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000296 bool isRep() const {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000297 return( (int) NodeRep < 0 );
298 }
299 };
300
301 struct WorkListElement {
302 Node* node;
303 unsigned Timestamp;
304 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
305
306 // Note that we reverse the sense of the comparison because we
307 // actually want to give low timestamps the priority over high,
308 // whereas priority is typically interpreted as a greater value is
309 // given high priority.
310 bool operator<(const WorkListElement& that) const {
311 return( this->Timestamp > that.Timestamp );
312 }
313 };
314
315 // Priority-queue based work list specialized for Nodes.
316 class WorkList {
317 std::priority_queue<WorkListElement> Q;
318
319 public:
320 void insert(Node* n) {
321 Q.push( WorkListElement(n, n->Timestamp) );
322 }
323
324 // We automatically discard non-representative nodes and nodes
325 // that were in the work list twice (we keep a copy of the
326 // timestamp in the work list so we can detect this situation by
327 // comparing against the node's current timestamp).
328 Node* pop() {
329 while( !Q.empty() ) {
330 WorkListElement x = Q.top(); Q.pop();
331 Node* INode = x.node;
332
333 if( INode->isRep() &&
334 INode->Timestamp == x.Timestamp ) {
335 return(x.node);
336 }
337 }
338 return(0);
339 }
340
341 bool empty() {
342 return Q.empty();
343 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000344 };
345
346 /// GraphNodes - This vector is populated as part of the object
347 /// identification stage of the analysis, which populates this vector with a
348 /// node for each memory object and fills in the ValueNodes map.
349 std::vector<Node> GraphNodes;
350
351 /// ValueNodes - This map indicates the Node that a particular Value* is
352 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000353 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000354
355 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000356 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000357 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000358
359 /// ReturnNodes - This map contains an entry for each function in the
360 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000361 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000362
363 /// VarargNodes - This map contains the entry used to represent all pointers
364 /// passed through the varargs portion of a function call for a particular
365 /// function. An entry is not present in this map for functions that do not
366 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000367 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000368
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000369
Chris Lattnere995a2a2004-05-23 21:00:47 +0000370 /// Constraints - This vector contains a list of all of the constraints
371 /// identified by the program.
372 std::vector<Constraint> Constraints;
373
Daniel Berlind81ccc22007-09-24 19:45:49 +0000374 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000375 // this is equivalent to the number of arguments + CallFirstArgPos)
376 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000377
378 /// This enum defines the GraphNodes indices that correspond to important
379 /// fixed sets.
380 enum {
381 UniversalSet = 0,
382 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000383 NullObject = 2,
384 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000385 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000386 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000387 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000388 // Map from Graph Node to DFS number
389 std::vector<unsigned> Node2DFS;
390 // Map from Graph Node to Deleted from graph.
391 std::vector<bool> Node2Deleted;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000392 // Same as Node Maps, but implemented as std::map because it is faster to
393 // clear
394 std::map<unsigned, unsigned> Tarjan2DFS;
395 std::map<unsigned, bool> Tarjan2Deleted;
396 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000397 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000398
399 // Work lists.
400 WorkList w1, w2;
401 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000402
Daniel Berlind81ccc22007-09-24 19:45:49 +0000403 // Offline variable substitution related things
404
405 // Temporary rep storage, used because we can't collapse SCC's in the
406 // predecessor graph by uniting the variables permanently, we can only do so
407 // for the successor graph.
408 std::vector<unsigned> VSSCCRep;
409 // Mapping from node to whether we have visited it during SCC finding yet.
410 std::vector<bool> Node2Visited;
411 // During variable substitution, we create unknowns to represent the unknown
412 // value that is a dereference of a variable. These nodes are known as
413 // "ref" nodes (since they represent the value of dereferences).
414 unsigned FirstRefNode;
415 // During HVN, we create represent address taken nodes as if they were
416 // unknown (since HVN, unlike HU, does not evaluate unions).
417 unsigned FirstAdrNode;
418 // Current pointer equivalence class number
419 unsigned PEClass;
420 // Mapping from points-to sets to equivalence classes
421 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
422 BitVectorMap Set2PEClass;
423 // Mapping from pointer equivalences to the representative node. -1 if we
424 // have no representative node for this pointer equivalence class yet.
425 std::vector<int> PEClass2Node;
426 // Mapping from pointer equivalences to representative node. This includes
427 // pointer equivalent but not location equivalent variables. -1 if we have
428 // no representative node for this pointer equivalence class yet.
429 std::vector<int> PENLEClass2Node;
Daniel Berlinc864edb2008-03-05 19:31:47 +0000430 // Union/Find for HCD
431 std::vector<unsigned> HCDSCCRep;
432 // HCD's offline-detected cycles; "Statically DeTected"
433 // -1 if not part of such a cycle, otherwise a representative node.
434 std::vector<int> SDT;
435 // Whether to use SDT (UniteNodes can use it during solving, but not before)
436 bool SDTActive;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000437
Chris Lattnere995a2a2004-05-23 21:00:47 +0000438 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000439 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000440 Andersens() : ModulePass(&ID) {}
Devang Patel1cee94f2008-03-18 00:39:19 +0000441
Chris Lattnerb12914b2004-09-20 04:48:05 +0000442 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000443 InitializeAliasAnalysis(this);
444 IdentifyObjects(M);
445 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000446#undef DEBUG_TYPE
447#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000448 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000449#undef DEBUG_TYPE
450#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000451 SolveConstraints();
452 DEBUG(PrintPointsToGraph());
453
454 // Free the constraints list, as we don't need it to respond to alias
455 // requests.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000456 std::vector<Constraint>().swap(Constraints);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000457 //These are needed for Print() (-analyze in opt)
458 //ObjectNodes.clear();
459 //ReturnNodes.clear();
460 //VarargNodes.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000461 return false;
462 }
463
464 void releaseMemory() {
465 // FIXME: Until we have transitively required passes working correctly,
466 // this cannot be enabled! Otherwise, using -count-aa with the pass
467 // causes memory to be freed too early. :(
468#if 0
469 // The memory objects and ValueNodes data structures at the only ones that
470 // are still live after construction.
471 std::vector<Node>().swap(GraphNodes);
472 ValueNodes.clear();
473#endif
474 }
475
476 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
477 AliasAnalysis::getAnalysisUsage(AU);
478 AU.setPreservesAll(); // Does not transform code
479 }
480
481 //------------------------------------------------
482 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000483 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000484 AliasResult alias(const Value *V1, unsigned V1Size,
485 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000486 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
487 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000488 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
489 bool pointsToConstantMemory(const Value *P);
490
491 virtual void deleteValue(Value *V) {
492 ValueNodes.erase(V);
493 getAnalysis<AliasAnalysis>().deleteValue(V);
494 }
495
496 virtual void copyValue(Value *From, Value *To) {
497 ValueNodes[To] = ValueNodes[From];
498 getAnalysis<AliasAnalysis>().copyValue(From, To);
499 }
500
501 private:
502 /// getNode - Return the node corresponding to the specified pointer scalar.
503 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000504 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000505 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000506 if (!isa<GlobalValue>(C))
507 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000508
Daniel Berlind81ccc22007-09-24 19:45:49 +0000509 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000510 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000511#ifndef NDEBUG
512 V->dump();
513#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000514 llvm_unreachable("Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000515 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000516 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000517 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000518
Chris Lattnere995a2a2004-05-23 21:00:47 +0000519 /// getObject - Return the node corresponding to the memory object for the
520 /// specified global or allocation instruction.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000521 unsigned getObject(Value *V) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000522 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000523 assert(I != ObjectNodes.end() &&
524 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000525 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000526 }
527
528 /// getReturnNode - Return the node representing the return value for the
529 /// specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000530 unsigned getReturnNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000531 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000532 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000533 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000534 }
535
536 /// getVarargNode - Return the node representing the variable arguments
537 /// formal for the specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000538 unsigned getVarargNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000539 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000540 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000541 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000542 }
543
544 /// getNodeValue - Get the node for the specified LLVM value and set the
545 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000546 unsigned getNodeValue(Value &V) {
547 unsigned Index = getNode(&V);
548 GraphNodes[Index].setValue(&V);
549 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000550 }
551
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000552 unsigned UniteNodes(unsigned First, unsigned Second,
553 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000554 unsigned FindNode(unsigned Node);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000555 unsigned FindNode(unsigned Node) const;
Daniel Berlinaad15882007-09-16 21:45:02 +0000556
Chris Lattnere995a2a2004-05-23 21:00:47 +0000557 void IdentifyObjects(Module &M);
558 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000559 bool AnalyzeUsesOfFunction(Value *);
560 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000561 void OptimizeConstraints();
562 unsigned FindEquivalentNode(unsigned, unsigned);
563 void ClumpAddressTaken();
564 void RewriteConstraints();
565 void HU();
566 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000567 void HCD();
568 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000569 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000570 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000571 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000572 void Condense(unsigned Node);
573 void HUValNum(unsigned Node);
574 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000575 unsigned getNodeForConstantPointer(Constant *C);
576 unsigned getNodeForConstantPointerTarget(Constant *C);
577 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000578
Chris Lattnere995a2a2004-05-23 21:00:47 +0000579 void AddConstraintsForNonInternalLinkage(Function *F);
580 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000581 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000582
583
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000584 void PrintNode(const Node *N) const;
585 void PrintConstraints() const ;
586 void PrintConstraint(const Constraint &) const;
587 void PrintLabels() const;
588 void PrintPointsToGraph() const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000589
590 //===------------------------------------------------------------------===//
591 // Instruction visitation methods for adding constraints
592 //
593 friend class InstVisitor<Andersens>;
594 void visitReturnInst(ReturnInst &RI);
595 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
Victor Hernandez46e83122009-09-18 21:34:51 +0000596 void visitCallInst(CallInst &CI) {
597 if (isMalloc(&CI)) visitAllocationInst(CI);
598 else visitCallSite(CallSite(&CI));
599 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000600 void visitCallSite(CallSite CS);
Victor Hernandez46e83122009-09-18 21:34:51 +0000601 void visitAllocationInst(Instruction &I);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000602 void visitLoadInst(LoadInst &LI);
603 void visitStoreInst(StoreInst &SI);
604 void visitGetElementPtrInst(GetElementPtrInst &GEP);
605 void visitPHINode(PHINode &PN);
606 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000607 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
608 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000609 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000610 void visitVAArg(VAArgInst &I);
611 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000612
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000613 //===------------------------------------------------------------------===//
614 // Implement Analyize interface
615 //
Chris Lattner45cfe542009-08-23 06:03:38 +0000616 void print(raw_ostream &O, const Module*) const {
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000617 PrintPointsToGraph();
618 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000619 };
Chris Lattnere995a2a2004-05-23 21:00:47 +0000620}
621
Dan Gohman844731a2008-05-13 00:00:25 +0000622char Andersens::ID = 0;
623static RegisterPass<Andersens>
Chris Lattnerb80e1ab2009-08-28 00:45:47 +0000624X("anders-aa", "Andersen's Interprocedural Alias Analysis (experimental)",
625 false, true);
Dan Gohman844731a2008-05-13 00:00:25 +0000626static RegisterAnalysisGroup<AliasAnalysis> Y(X);
627
628// Initialize Timestamp Counter (static).
Owen Anderson5ec56cc2009-06-30 05:33:46 +0000629volatile llvm::sys::cas_flag Andersens::Node::Counter = 0;
Dan Gohman844731a2008-05-13 00:00:25 +0000630
Jeff Cohen534927d2005-01-08 22:01:16 +0000631ModulePass *llvm::createAndersensPass() { return new Andersens(); }
632
Chris Lattnere995a2a2004-05-23 21:00:47 +0000633//===----------------------------------------------------------------------===//
634// AliasAnalysis Interface Implementation
635//===----------------------------------------------------------------------===//
636
637AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
638 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000639 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
640 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000641
642 // Check to see if the two pointers are known to not alias. They don't alias
643 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000644 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000645 return NoAlias;
646
647 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
648}
649
Chris Lattnerf392c642005-03-28 06:21:17 +0000650AliasAnalysis::ModRefResult
651Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
652 // The only thing useful that we can contribute for mod/ref information is
653 // when calling external function calls: if we know that memory never escapes
654 // from the program, it cannot be modified by an external call.
655 //
656 // NOTE: This is not really safe, at least not when the entire program is not
657 // available. The deal is that the external function could call back into the
658 // program and modify stuff. We ignore this technical niggle for now. This
659 // is, after all, a "research quality" implementation of Andersen's analysis.
660 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000661 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000662 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000663
Daniel Berlinaad15882007-09-16 21:45:02 +0000664 if (N1->PointsTo->empty())
665 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000666#if FULL_UNIVERSAL
667 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
668 return NoModRef; // Universal set does not contain P
669#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000670 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000671 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000672#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000673 }
674
675 return AliasAnalysis::getModRefInfo(CS, P, Size);
676}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000677
Reid Spencer3a9ec242006-08-28 01:02:49 +0000678AliasAnalysis::ModRefResult
679Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
680 return AliasAnalysis::getModRefInfo(CS1,CS2);
681}
682
Chris Lattnere995a2a2004-05-23 21:00:47 +0000683/// getMustAlias - We can provide must alias information if we know that a
684/// pointer can only point to a specific function or the null pointer.
685/// Unfortunately we cannot determine must-alias information for global
686/// variables or any other memory memory objects because we do not track whether
687/// a pointer points to the beginning of an object or a field of it.
688void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000689 Node *N = &GraphNodes[FindNode(getNode(P))];
690 if (N->PointsTo->count() == 1) {
691 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
692 // If a function is the only object in the points-to set, then it must be
693 // the destination. Note that we can't handle global variables here,
694 // because we don't know if the pointer is actually pointing to a field of
695 // the global or to the beginning of it.
696 if (Value *V = Pointee->getValue()) {
697 if (Function *F = dyn_cast<Function>(V))
698 RetVals.push_back(F);
699 } else {
700 // If the object in the points-to set is the null object, then the null
701 // pointer is a must alias.
702 if (Pointee == &GraphNodes[NullObject])
Owen Andersona7235ea2009-07-31 20:28:14 +0000703 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000704 }
705 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000706 AliasAnalysis::getMustAliases(P, RetVals);
707}
708
709/// pointsToConstantMemory - If we can determine that this pointer only points
710/// to constant memory, return true. In practice, this means that if the
711/// pointer can only point to constant globals, functions, or the null pointer,
712/// return true.
713///
714bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000715 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000716 unsigned i;
717
718 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
719 bi != N->PointsTo->end();
720 ++bi) {
721 i = *bi;
722 Node *Pointee = &GraphNodes[i];
723 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000724 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
725 !cast<GlobalVariable>(V)->isConstant()))
726 return AliasAnalysis::pointsToConstantMemory(P);
727 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000728 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000729 return AliasAnalysis::pointsToConstantMemory(P);
730 }
731 }
732
733 return true;
734}
735
736//===----------------------------------------------------------------------===//
737// Object Identification Phase
738//===----------------------------------------------------------------------===//
739
740/// IdentifyObjects - This stage scans the program, adding an entry to the
741/// GraphNodes list for each memory object in the program (global stack or
742/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
743///
744void Andersens::IdentifyObjects(Module &M) {
745 unsigned NumObjects = 0;
746
747 // Object #0 is always the universal set: the object that we don't know
748 // anything about.
749 assert(NumObjects == UniversalSet && "Something changed!");
750 ++NumObjects;
751
752 // Object #1 always represents the null pointer.
753 assert(NumObjects == NullPtr && "Something changed!");
754 ++NumObjects;
755
756 // Object #2 always represents the null object (the object pointed to by null)
757 assert(NumObjects == NullObject && "Something changed!");
758 ++NumObjects;
759
760 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000761 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
762 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000763 ObjectNodes[I] = NumObjects++;
764 ValueNodes[I] = NumObjects++;
765 }
766
767 // Add nodes for all of the functions and the instructions inside of them.
768 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
769 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000770 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000771 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000772 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
773 ReturnNodes[F] = NumObjects++;
774 if (F->getFunctionType()->isVarArg())
775 VarargNodes[F] = NumObjects++;
776
Daniel Berlinaad15882007-09-16 21:45:02 +0000777
Chris Lattnere995a2a2004-05-23 21:00:47 +0000778 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000779 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
780 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000781 {
782 if (isa<PointerType>(I->getType()))
783 ValueNodes[I] = NumObjects++;
784 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000785 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000786
787 // Scan the function body, creating a memory object for each heap/stack
788 // allocation in the body of the function and a node to represent all
789 // pointer values defined by instructions and used as operands.
790 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
791 // If this is an heap or stack allocation, create a node for the memory
792 // object.
793 if (isa<PointerType>(II->getType())) {
794 ValueNodes[&*II] = NumObjects++;
795 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
796 ObjectNodes[AI] = NumObjects++;
Victor Hernandez46e83122009-09-18 21:34:51 +0000797 else if (isMalloc(&*II))
798 ObjectNodes[&*II] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000799 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000800
801 // Calls to inline asm need to be added as well because the callee isn't
802 // referenced anywhere else.
803 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
804 Value *Callee = CI->getCalledValue();
805 if (isa<InlineAsm>(Callee))
806 ValueNodes[Callee] = NumObjects++;
807 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000808 }
809 }
810
811 // Now that we know how many objects to create, make them all now!
812 GraphNodes.resize(NumObjects);
813 NumNodes += NumObjects;
814}
815
816//===----------------------------------------------------------------------===//
817// Constraint Identification Phase
818//===----------------------------------------------------------------------===//
819
820/// getNodeForConstantPointer - Return the node corresponding to the constant
821/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000822unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000823 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
824
Chris Lattner267a1b02005-03-27 18:58:23 +0000825 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000826 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000827 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
828 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000829 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
830 switch (CE->getOpcode()) {
831 case Instruction::GetElementPtr:
832 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000833 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000834 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000835 case Instruction::BitCast:
836 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000837 default:
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000838 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000839 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000840 }
841 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000842 llvm_unreachable("Unknown constant pointer!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000843 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000844 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000845}
846
847/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
848/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000849unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000850 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
851
852 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000853 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000854 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
855 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000856 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
857 switch (CE->getOpcode()) {
858 case Instruction::GetElementPtr:
859 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000860 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000861 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000862 case Instruction::BitCast:
863 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000864 default:
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000865 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000866 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000867 }
868 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000869 llvm_unreachable("Unknown constant pointer!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000870 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000871 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000872}
873
874/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
875/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000876void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
877 Constant *C) {
Dan Gohmanb64aa112008-05-22 23:43:22 +0000878 if (C->getType()->isSingleValueType()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000879 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000880 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
881 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000882 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000883 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
884 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000885 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000886 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000887 // If this is an array or struct, include constraints for each element.
888 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
889 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000890 AddGlobalInitializerConstraints(NodeIndex,
891 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000892 }
893}
894
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000895/// AddConstraintsForNonInternalLinkage - If this function does not have
896/// internal linkage, realize that we can't trust anything passed into or
897/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000898void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000899 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000900 if (isa<PointerType>(I->getType()))
901 // If this is an argument of an externally accessible function, the
902 // incoming pointer might point to anything.
903 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000904 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000905}
906
Chris Lattner8a446432005-03-29 06:09:07 +0000907/// AddConstraintsForCall - If this is a call to a "known" function, add the
908/// constraints and return true. If this is a call to an unknown function,
909/// return false.
910bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000911 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000912
913 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000914 if (F->getName() == "atoi" || F->getName() == "atof" ||
915 F->getName() == "atol" || F->getName() == "atoll" ||
916 F->getName() == "remove" || F->getName() == "unlink" ||
917 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner824b9582008-11-21 16:42:48 +0000918 F->getName() == "llvm.memset" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000919 F->getName() == "strcmp" || F->getName() == "strncmp" ||
920 F->getName() == "execl" || F->getName() == "execlp" ||
921 F->getName() == "execle" || F->getName() == "execv" ||
922 F->getName() == "execvp" || F->getName() == "chmod" ||
923 F->getName() == "puts" || F->getName() == "write" ||
924 F->getName() == "open" || F->getName() == "create" ||
925 F->getName() == "truncate" || F->getName() == "chdir" ||
926 F->getName() == "mkdir" || F->getName() == "rmdir" ||
927 F->getName() == "read" || F->getName() == "pipe" ||
928 F->getName() == "wait" || F->getName() == "time" ||
929 F->getName() == "stat" || F->getName() == "fstat" ||
930 F->getName() == "lstat" || F->getName() == "strtod" ||
931 F->getName() == "strtof" || F->getName() == "strtold" ||
932 F->getName() == "fopen" || F->getName() == "fdopen" ||
933 F->getName() == "freopen" ||
934 F->getName() == "fflush" || F->getName() == "feof" ||
935 F->getName() == "fileno" || F->getName() == "clearerr" ||
936 F->getName() == "rewind" || F->getName() == "ftell" ||
937 F->getName() == "ferror" || F->getName() == "fgetc" ||
938 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
939 F->getName() == "fwrite" || F->getName() == "fread" ||
940 F->getName() == "fgets" || F->getName() == "ungetc" ||
941 F->getName() == "fputc" ||
942 F->getName() == "fputs" || F->getName() == "putc" ||
943 F->getName() == "ftell" || F->getName() == "rewind" ||
944 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
945 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
946 F->getName() == "printf" || F->getName() == "fprintf" ||
947 F->getName() == "sprintf" || F->getName() == "vprintf" ||
948 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
949 F->getName() == "scanf" || F->getName() == "fscanf" ||
950 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
951 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000952 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000953
Chris Lattner175b9632005-03-29 20:36:05 +0000954
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000955 // These functions do induce points-to edges.
Chris Lattner824b9582008-11-21 16:42:48 +0000956 if (F->getName() == "llvm.memcpy" ||
957 F->getName() == "llvm.memmove" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000958 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000959
Nick Lewycky3037eda2008-12-27 16:20:53 +0000960 const FunctionType *FTy = F->getFunctionType();
961 if (FTy->getNumParams() > 1 &&
962 isa<PointerType>(FTy->getParamType(0)) &&
963 isa<PointerType>(FTy->getParamType(1))) {
964
965 // *Dest = *Src, which requires an artificial graph node to represent the
966 // constraint. It is broken up into *Dest = temp, temp = *Src
967 unsigned FirstArg = getNode(CS.getArgument(0));
968 unsigned SecondArg = getNode(CS.getArgument(1));
969 unsigned TempArg = GraphNodes.size();
970 GraphNodes.push_back(Node());
971 Constraints.push_back(Constraint(Constraint::Store,
972 FirstArg, TempArg));
973 Constraints.push_back(Constraint(Constraint::Load,
974 TempArg, SecondArg));
975 // In addition, Dest = Src
976 Constraints.push_back(Constraint(Constraint::Copy,
977 FirstArg, SecondArg));
978 return true;
979 }
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000980 }
981
Chris Lattner77b50562005-03-29 20:04:24 +0000982 // Result = Arg0
983 if (F->getName() == "realloc" || F->getName() == "strchr" ||
984 F->getName() == "strrchr" || F->getName() == "strstr" ||
985 F->getName() == "strtok") {
Nick Lewycky3037eda2008-12-27 16:20:53 +0000986 const FunctionType *FTy = F->getFunctionType();
987 if (FTy->getNumParams() > 0 &&
988 isa<PointerType>(FTy->getParamType(0))) {
989 Constraints.push_back(Constraint(Constraint::Copy,
990 getNode(CS.getInstruction()),
991 getNode(CS.getArgument(0))));
992 return true;
993 }
Chris Lattner8a446432005-03-29 06:09:07 +0000994 }
995
996 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000997}
998
999
Chris Lattnere995a2a2004-05-23 21:00:47 +00001000
Daniel Berlinaad15882007-09-16 21:45:02 +00001001/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
1002/// If this is used by anything complex (i.e., the address escapes), return
1003/// true.
1004bool Andersens::AnalyzeUsesOfFunction(Value *V) {
1005
1006 if (!isa<PointerType>(V->getType())) return true;
1007
1008 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Dan Gohman104eac12009-08-11 17:20:16 +00001009 if (isa<LoadInst>(*UI)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001010 return false;
1011 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1012 if (V == SI->getOperand(1)) {
1013 return false;
1014 } else if (SI->getOperand(1)) {
1015 return true; // Storing the pointer
1016 }
1017 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1018 if (AnalyzeUsesOfFunction(GEP)) return true;
1019 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1020 // Make sure that this is just the function being called, not that it is
1021 // passing into the function.
1022 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1023 if (CI->getOperand(i) == V) return true;
1024 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1025 // Make sure that this is just the function being called, not that it is
1026 // passing into the function.
Gabor Greif03a5f132009-09-03 02:02:59 +00001027 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +00001028 if (II->getOperand(i) == V) return true;
1029 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1030 if (CE->getOpcode() == Instruction::GetElementPtr ||
1031 CE->getOpcode() == Instruction::BitCast) {
1032 if (AnalyzeUsesOfFunction(CE))
1033 return true;
1034 } else {
1035 return true;
1036 }
1037 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1038 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1039 return true; // Allow comparison against null.
Dan Gohman104eac12009-08-11 17:20:16 +00001040 } else if (isa<FreeInst>(*UI)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001041 return false;
1042 } else {
1043 return true;
1044 }
1045 return false;
1046}
1047
Chris Lattnere995a2a2004-05-23 21:00:47 +00001048/// CollectConstraints - This stage scans the program, adding a constraint to
1049/// the Constraints list for each instruction in the program that induces a
1050/// constraint, and setting up the initial points-to graph.
1051///
1052void Andersens::CollectConstraints(Module &M) {
1053 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001054 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1055 UniversalSet));
1056 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1057 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001058
1059 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001060 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001061
1062 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001063 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1064 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001065 // Associate the address of the global object as pointing to the memory for
1066 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001067 unsigned ObjectIndex = getObject(I);
1068 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001069 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001070 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1071 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001072
Dan Gohman82555732009-08-19 18:20:44 +00001073 if (I->hasDefinitiveInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001074 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001075 } else {
1076 // If it doesn't have an initializer (i.e. it's defined in another
1077 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001078 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1079 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001080 }
1081 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001082
Chris Lattnere995a2a2004-05-23 21:00:47 +00001083 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001084 // Set up the return value node.
1085 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001086 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001087 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001088 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001089
1090 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001091 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1092 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001093 if (isa<PointerType>(I->getType()))
1094 getNodeValue(*I);
1095
Daniel Berlinaad15882007-09-16 21:45:02 +00001096 // At some point we should just add constraints for the escaping functions
1097 // at solve time, but this slows down solving. For now, we simply mark
1098 // address taken functions as escaping and treat them as external.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001099 if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001100 AddConstraintsForNonInternalLinkage(F);
1101
Reid Spencer5cbf9852007-01-30 20:08:39 +00001102 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001103 // Scan the function body, creating a memory object for each heap/stack
1104 // allocation in the body of the function and a node to represent all
1105 // pointer values defined by instructions and used as operands.
1106 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001107 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001108 // External functions that return pointers return the universal set.
1109 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1110 Constraints.push_back(Constraint(Constraint::Copy,
1111 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001112 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001113
1114 // Any pointers that are passed into the function have the universal set
1115 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001116 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1117 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001118 if (isa<PointerType>(I->getType())) {
1119 // Pointers passed into external functions could have anything stored
1120 // through them.
1121 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001122 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001123 // Memory objects passed into external function calls can have the
1124 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001125#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001126 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001127 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001128 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001129#else
1130 Constraints.push_back(Constraint(Constraint::Copy,
1131 getNode(I),
1132 UniversalSet));
1133#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001134 }
1135
1136 // If this is an external varargs function, it can also store pointers
1137 // into any pointers passed through the varargs section.
1138 if (F->getFunctionType()->isVarArg())
1139 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001140 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001141 }
1142 }
1143 NumConstraints += Constraints.size();
1144}
1145
1146
1147void Andersens::visitInstruction(Instruction &I) {
1148#ifdef NDEBUG
1149 return; // This function is just a big assert.
1150#endif
1151 if (isa<BinaryOperator>(I))
1152 return;
1153 // Most instructions don't have any effect on pointer values.
1154 switch (I.getOpcode()) {
1155 case Instruction::Br:
1156 case Instruction::Switch:
1157 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001158 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001159 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001160 case Instruction::ICmp:
1161 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001162 return;
1163 default:
1164 // Is this something we aren't handling yet?
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00001165 errs() << "Unknown instruction: " << I;
Torok Edwinc23197a2009-07-14 16:55:14 +00001166 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001167 }
1168}
1169
Victor Hernandez46e83122009-09-18 21:34:51 +00001170void Andersens::visitAllocationInst(Instruction &I) {
1171 unsigned ObjectIndex = getObject(&I);
1172 GraphNodes[ObjectIndex].setValue(&I);
1173 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001174 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001175}
1176
1177void Andersens::visitReturnInst(ReturnInst &RI) {
1178 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1179 // return V --> <Copy/retval{F}/v>
1180 Constraints.push_back(Constraint(Constraint::Copy,
1181 getReturnNode(RI.getParent()->getParent()),
1182 getNode(RI.getOperand(0))));
1183}
1184
1185void Andersens::visitLoadInst(LoadInst &LI) {
1186 if (isa<PointerType>(LI.getType()))
1187 // P1 = load P2 --> <Load/P1/P2>
1188 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1189 getNode(LI.getOperand(0))));
1190}
1191
1192void Andersens::visitStoreInst(StoreInst &SI) {
1193 if (isa<PointerType>(SI.getOperand(0)->getType()))
1194 // store P1, P2 --> <Store/P2/P1>
1195 Constraints.push_back(Constraint(Constraint::Store,
1196 getNode(SI.getOperand(1)),
1197 getNode(SI.getOperand(0))));
1198}
1199
1200void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1201 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1202 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1203 getNode(GEP.getOperand(0))));
1204}
1205
1206void Andersens::visitPHINode(PHINode &PN) {
1207 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001208 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001209 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1210 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1211 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1212 getNode(PN.getIncomingValue(i))));
1213 }
1214}
1215
1216void Andersens::visitCastInst(CastInst &CI) {
1217 Value *Op = CI.getOperand(0);
1218 if (isa<PointerType>(CI.getType())) {
1219 if (isa<PointerType>(Op->getType())) {
1220 // P1 = cast P2 --> <Copy/P1/P2>
1221 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1222 getNode(CI.getOperand(0))));
1223 } else {
1224 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001225#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001226 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001227 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001228#else
1229 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001230#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001231 }
1232 } else if (isa<PointerType>(Op->getType())) {
1233 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001234#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001235 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001236 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001237 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001238#else
1239 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001240#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001241 }
1242}
1243
1244void Andersens::visitSelectInst(SelectInst &SI) {
1245 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001246 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001247 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1248 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1249 getNode(SI.getOperand(1))));
1250 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1251 getNode(SI.getOperand(2))));
1252 }
1253}
1254
Chris Lattnere995a2a2004-05-23 21:00:47 +00001255void Andersens::visitVAArg(VAArgInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001256 llvm_unreachable("vaarg not handled yet!");
Chris Lattnere995a2a2004-05-23 21:00:47 +00001257}
1258
1259/// AddConstraintsForCall - Add constraints for a call with actual arguments
1260/// specified by CS to the function specified by F. Note that the types of
1261/// arguments might not match up in the case where this is an indirect call and
1262/// the function pointer has been casted. If this is the case, do something
1263/// reasonable.
1264void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001265 Value *CallValue = CS.getCalledValue();
1266 bool IsDeref = F == NULL;
1267
1268 // If this is a call to an external function, try to handle it directly to get
1269 // some taste of context sensitivity.
1270 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001271 return;
1272
Chris Lattnere995a2a2004-05-23 21:00:47 +00001273 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001274 unsigned CSN = getNode(CS.getInstruction());
1275 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1276 if (IsDeref)
1277 Constraints.push_back(Constraint(Constraint::Load, CSN,
1278 getNode(CallValue), CallReturnPos));
1279 else
1280 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1281 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001282 } else {
1283 // If the function returns a non-pointer value, handle this just like we
1284 // treat a nonpointer cast to pointer.
1285 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001286 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001287 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001288 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001289#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001290 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001291 UniversalSet,
1292 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001293#else
1294 Constraints.push_back(Constraint(Constraint::Copy,
1295 getNode(CallValue) + CallReturnPos,
1296 UniversalSet));
1297#endif
1298
1299
Chris Lattnere995a2a2004-05-23 21:00:47 +00001300 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001301
Chris Lattnere995a2a2004-05-23 21:00:47 +00001302 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001303 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001304 if (F) {
1305 // Direct Call
1306 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001307 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1308 {
1309#if !FULL_UNIVERSAL
1310 if (external && isa<PointerType>((*ArgI)->getType()))
1311 {
1312 // Add constraint that ArgI can now point to anything due to
1313 // escaping, as can everything it points to. The second portion of
1314 // this should be taken care of by universal = *universal
1315 Constraints.push_back(Constraint(Constraint::Copy,
1316 getNode(*ArgI),
1317 UniversalSet));
1318 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001319#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001320 if (isa<PointerType>(AI->getType())) {
1321 if (isa<PointerType>((*ArgI)->getType())) {
1322 // Copy the actual argument into the formal argument.
1323 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1324 getNode(*ArgI)));
1325 } else {
1326 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1327 UniversalSet));
1328 }
1329 } else if (isa<PointerType>((*ArgI)->getType())) {
1330#if FULL_UNIVERSAL
1331 Constraints.push_back(Constraint(Constraint::Copy,
1332 UniversalSet,
1333 getNode(*ArgI)));
1334#else
1335 Constraints.push_back(Constraint(Constraint::Copy,
1336 getNode(*ArgI),
1337 UniversalSet));
1338#endif
1339 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001340 }
1341 } else {
1342 //Indirect Call
1343 unsigned ArgPos = CallFirstArgPos;
1344 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001345 if (isa<PointerType>((*ArgI)->getType())) {
1346 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001347 Constraints.push_back(Constraint(Constraint::Store,
1348 getNode(CallValue),
1349 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001350 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001351 Constraints.push_back(Constraint(Constraint::Store,
1352 getNode (CallValue),
1353 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001354 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001355 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001356 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001357 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001358 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001359 for (; ArgI != ArgE; ++ArgI)
1360 if (isa<PointerType>((*ArgI)->getType()))
1361 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1362 getNode(*ArgI)));
1363 // If more arguments are passed in than we track, just drop them on the floor.
1364}
1365
1366void Andersens::visitCallSite(CallSite CS) {
1367 if (isa<PointerType>(CS.getType()))
1368 getNodeValue(*CS.getInstruction());
1369
1370 if (Function *F = CS.getCalledFunction()) {
1371 AddConstraintsForCall(CS, F);
1372 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001373 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001374 }
1375}
1376
1377//===----------------------------------------------------------------------===//
1378// Constraint Solving Phase
1379//===----------------------------------------------------------------------===//
1380
1381/// intersects - Return true if the points-to set of this node intersects
1382/// with the points-to set of the specified node.
1383bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001384 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001385}
1386
1387/// intersectsIgnoring - Return true if the points-to set of this node
1388/// intersects with the points-to set of the specified node on any nodes
1389/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001390bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1391 // TODO: If we are only going to call this with the same value for Ignoring,
1392 // we should move the special values out of the points-to bitmap.
1393 bool WeHadIt = PointsTo->test(Ignoring);
1394 bool NHadIt = N->PointsTo->test(Ignoring);
1395 bool Result = false;
1396 if (WeHadIt)
1397 PointsTo->reset(Ignoring);
1398 if (NHadIt)
1399 N->PointsTo->reset(Ignoring);
1400 Result = PointsTo->intersects(N->PointsTo);
1401 if (WeHadIt)
1402 PointsTo->set(Ignoring);
1403 if (NHadIt)
1404 N->PointsTo->set(Ignoring);
1405 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001406}
1407
Daniel Berlind81ccc22007-09-24 19:45:49 +00001408
1409/// Clump together address taken variables so that the points-to sets use up
1410/// less space and can be operated on faster.
1411
1412void Andersens::ClumpAddressTaken() {
1413#undef DEBUG_TYPE
1414#define DEBUG_TYPE "anders-aa-renumber"
1415 std::vector<unsigned> Translate;
1416 std::vector<Node> NewGraphNodes;
1417
1418 Translate.resize(GraphNodes.size());
1419 unsigned NewPos = 0;
1420
1421 for (unsigned i = 0; i < Constraints.size(); ++i) {
1422 Constraint &C = Constraints[i];
1423 if (C.Type == Constraint::AddressOf) {
1424 GraphNodes[C.Src].AddressTaken = true;
1425 }
1426 }
1427 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1428 unsigned Pos = NewPos++;
1429 Translate[i] = Pos;
1430 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001431 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001432 }
1433
1434 // I believe this ends up being faster than making two vectors and splicing
1435 // them.
1436 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1437 if (GraphNodes[i].AddressTaken) {
1438 unsigned Pos = NewPos++;
1439 Translate[i] = Pos;
1440 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001441 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001442 }
1443 }
1444
1445 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1446 if (!GraphNodes[i].AddressTaken) {
1447 unsigned Pos = NewPos++;
1448 Translate[i] = Pos;
1449 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001450 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001451 }
1452 }
1453
1454 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1455 Iter != ValueNodes.end();
1456 ++Iter)
1457 Iter->second = Translate[Iter->second];
1458
1459 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1460 Iter != ObjectNodes.end();
1461 ++Iter)
1462 Iter->second = Translate[Iter->second];
1463
1464 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1465 Iter != ReturnNodes.end();
1466 ++Iter)
1467 Iter->second = Translate[Iter->second];
1468
1469 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1470 Iter != VarargNodes.end();
1471 ++Iter)
1472 Iter->second = Translate[Iter->second];
1473
1474 for (unsigned i = 0; i < Constraints.size(); ++i) {
1475 Constraint &C = Constraints[i];
1476 C.Src = Translate[C.Src];
1477 C.Dest = Translate[C.Dest];
1478 }
1479
1480 GraphNodes.swap(NewGraphNodes);
1481#undef DEBUG_TYPE
1482#define DEBUG_TYPE "anders-aa"
1483}
1484
1485/// The technique used here is described in "Exploiting Pointer and Location
1486/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1487/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1488/// and is equivalent to value numbering the collapsed constraint graph without
1489/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1490/// first order pointer dereferences and speed up/reduce memory usage of HU.
1491/// Running both is equivalent to HRU without the iteration
1492/// HVN in more detail:
1493/// Imagine the set of constraints was simply straight line code with no loops
1494/// (we eliminate cycles, so there are no loops), such as:
1495/// E = &D
1496/// E = &C
1497/// E = F
1498/// F = G
1499/// G = F
1500/// Applying value numbering to this code tells us:
1501/// G == F == E
1502///
1503/// For HVN, this is as far as it goes. We assign new value numbers to every
1504/// "address node", and every "reference node".
1505/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1506/// cycle must have the same value number since the = operation is really
1507/// inclusion, not overwrite), and value number nodes we receive points-to sets
1508/// before we value our own node.
1509/// The advantage of HU over HVN is that HU considers the inclusion property, so
1510/// that if you have
1511/// E = &D
1512/// E = &C
1513/// E = F
1514/// F = G
1515/// F = &D
1516/// G = F
1517/// HU will determine that G == F == E. HVN will not, because it cannot prove
1518/// that the points to information ends up being the same because they all
1519/// receive &D from E anyway.
1520
1521void Andersens::HVN() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001522 DEBUG(errs() << "Beginning HVN\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001523 // Build a predecessor graph. This is like our constraint graph with the
1524 // edges going in the opposite direction, and there are edges for all the
1525 // constraints, instead of just copy constraints. We also build implicit
1526 // edges for constraints are implied but not explicit. I.E for the constraint
1527 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1528 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1529 Constraint &C = Constraints[i];
1530 if (C.Type == Constraint::AddressOf) {
1531 GraphNodes[C.Src].AddressTaken = true;
1532 GraphNodes[C.Src].Direct = false;
1533
1534 // Dest = &src edge
1535 unsigned AdrNode = C.Src + FirstAdrNode;
1536 if (!GraphNodes[C.Dest].PredEdges)
1537 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1538 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1539
1540 // *Dest = src edge
1541 unsigned RefNode = C.Dest + FirstRefNode;
1542 if (!GraphNodes[RefNode].ImplicitPredEdges)
1543 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1544 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1545 } else if (C.Type == Constraint::Load) {
1546 if (C.Offset == 0) {
1547 // dest = *src edge
1548 if (!GraphNodes[C.Dest].PredEdges)
1549 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1550 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1551 } else {
1552 GraphNodes[C.Dest].Direct = false;
1553 }
1554 } else if (C.Type == Constraint::Store) {
1555 if (C.Offset == 0) {
1556 // *dest = src edge
1557 unsigned RefNode = C.Dest + FirstRefNode;
1558 if (!GraphNodes[RefNode].PredEdges)
1559 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1560 GraphNodes[RefNode].PredEdges->set(C.Src);
1561 }
1562 } else {
1563 // Dest = Src edge and *Dest = *Src edge
1564 if (!GraphNodes[C.Dest].PredEdges)
1565 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1566 GraphNodes[C.Dest].PredEdges->set(C.Src);
1567 unsigned RefNode = C.Dest + FirstRefNode;
1568 if (!GraphNodes[RefNode].ImplicitPredEdges)
1569 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1570 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1571 }
1572 }
1573 PEClass = 1;
1574 // Do SCC finding first to condense our predecessor graph
1575 DFSNumber = 0;
1576 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1577 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1578 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1579
1580 for (unsigned i = 0; i < FirstRefNode; ++i) {
1581 unsigned Node = VSSCCRep[i];
1582 if (!Node2Visited[Node])
1583 HVNValNum(Node);
1584 }
1585 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1586 Iter != Set2PEClass.end();
1587 ++Iter)
1588 delete Iter->first;
1589 Set2PEClass.clear();
1590 Node2DFS.clear();
1591 Node2Deleted.clear();
1592 Node2Visited.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001593 DEBUG(errs() << "Finished HVN\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001594
1595}
1596
1597/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1598/// same time because it's easy.
1599void Andersens::HVNValNum(unsigned NodeIndex) {
1600 unsigned MyDFS = DFSNumber++;
1601 Node *N = &GraphNodes[NodeIndex];
1602 Node2Visited[NodeIndex] = true;
1603 Node2DFS[NodeIndex] = MyDFS;
1604
1605 // First process all our explicit edges
1606 if (N->PredEdges)
1607 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1608 Iter != N->PredEdges->end();
1609 ++Iter) {
1610 unsigned j = VSSCCRep[*Iter];
1611 if (!Node2Deleted[j]) {
1612 if (!Node2Visited[j])
1613 HVNValNum(j);
1614 if (Node2DFS[NodeIndex] > Node2DFS[j])
1615 Node2DFS[NodeIndex] = Node2DFS[j];
1616 }
1617 }
1618
1619 // Now process all the implicit edges
1620 if (N->ImplicitPredEdges)
1621 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1622 Iter != N->ImplicitPredEdges->end();
1623 ++Iter) {
1624 unsigned j = VSSCCRep[*Iter];
1625 if (!Node2Deleted[j]) {
1626 if (!Node2Visited[j])
1627 HVNValNum(j);
1628 if (Node2DFS[NodeIndex] > Node2DFS[j])
1629 Node2DFS[NodeIndex] = Node2DFS[j];
1630 }
1631 }
1632
1633 // See if we found any cycles
1634 if (MyDFS == Node2DFS[NodeIndex]) {
1635 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1636 unsigned CycleNodeIndex = SCCStack.top();
1637 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1638 VSSCCRep[CycleNodeIndex] = NodeIndex;
1639 // Unify the nodes
1640 N->Direct &= CycleNode->Direct;
1641
1642 if (CycleNode->PredEdges) {
1643 if (!N->PredEdges)
1644 N->PredEdges = new SparseBitVector<>;
1645 *(N->PredEdges) |= CycleNode->PredEdges;
1646 delete CycleNode->PredEdges;
1647 CycleNode->PredEdges = NULL;
1648 }
1649 if (CycleNode->ImplicitPredEdges) {
1650 if (!N->ImplicitPredEdges)
1651 N->ImplicitPredEdges = new SparseBitVector<>;
1652 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1653 delete CycleNode->ImplicitPredEdges;
1654 CycleNode->ImplicitPredEdges = NULL;
1655 }
1656
1657 SCCStack.pop();
1658 }
1659
1660 Node2Deleted[NodeIndex] = true;
1661
1662 if (!N->Direct) {
1663 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1664 return;
1665 }
1666
1667 // Collect labels of successor nodes
1668 bool AllSame = true;
1669 unsigned First = ~0;
1670 SparseBitVector<> *Labels = new SparseBitVector<>;
1671 bool Used = false;
1672
1673 if (N->PredEdges)
1674 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1675 Iter != N->PredEdges->end();
1676 ++Iter) {
1677 unsigned j = VSSCCRep[*Iter];
1678 unsigned Label = GraphNodes[j].PointerEquivLabel;
1679 // Ignore labels that are equal to us or non-pointers
1680 if (j == NodeIndex || Label == 0)
1681 continue;
1682 if (First == (unsigned)~0)
1683 First = Label;
1684 else if (First != Label)
1685 AllSame = false;
1686 Labels->set(Label);
1687 }
1688
1689 // We either have a non-pointer, a copy of an existing node, or a new node.
1690 // Assign the appropriate pointer equivalence label.
1691 if (Labels->empty()) {
1692 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1693 } else if (AllSame) {
1694 GraphNodes[NodeIndex].PointerEquivLabel = First;
1695 } else {
1696 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1697 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1698 unsigned EquivClass = PEClass++;
1699 Set2PEClass[Labels] = EquivClass;
1700 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1701 Used = true;
1702 }
1703 }
1704 if (!Used)
1705 delete Labels;
1706 } else {
1707 SCCStack.push(NodeIndex);
1708 }
1709}
1710
1711/// The technique used here is described in "Exploiting Pointer and Location
1712/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1713/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1714/// and is equivalent to value numbering the collapsed constraint graph
1715/// including evaluating unions.
1716void Andersens::HU() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001717 DEBUG(errs() << "Beginning HU\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001718 // Build a predecessor graph. This is like our constraint graph with the
1719 // edges going in the opposite direction, and there are edges for all the
1720 // constraints, instead of just copy constraints. We also build implicit
1721 // edges for constraints are implied but not explicit. I.E for the constraint
1722 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1723 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1724 Constraint &C = Constraints[i];
1725 if (C.Type == Constraint::AddressOf) {
1726 GraphNodes[C.Src].AddressTaken = true;
1727 GraphNodes[C.Src].Direct = false;
1728
1729 GraphNodes[C.Dest].PointsTo->set(C.Src);
1730 // *Dest = src edge
1731 unsigned RefNode = C.Dest + FirstRefNode;
1732 if (!GraphNodes[RefNode].ImplicitPredEdges)
1733 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1734 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1735 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1736 } else if (C.Type == Constraint::Load) {
1737 if (C.Offset == 0) {
1738 // dest = *src edge
1739 if (!GraphNodes[C.Dest].PredEdges)
1740 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1741 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1742 } else {
1743 GraphNodes[C.Dest].Direct = false;
1744 }
1745 } else if (C.Type == Constraint::Store) {
1746 if (C.Offset == 0) {
1747 // *dest = src edge
1748 unsigned RefNode = C.Dest + FirstRefNode;
1749 if (!GraphNodes[RefNode].PredEdges)
1750 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1751 GraphNodes[RefNode].PredEdges->set(C.Src);
1752 }
1753 } else {
1754 // Dest = Src edge and *Dest = *Src edg
1755 if (!GraphNodes[C.Dest].PredEdges)
1756 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1757 GraphNodes[C.Dest].PredEdges->set(C.Src);
1758 unsigned RefNode = C.Dest + FirstRefNode;
1759 if (!GraphNodes[RefNode].ImplicitPredEdges)
1760 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1761 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1762 }
1763 }
1764 PEClass = 1;
1765 // Do SCC finding first to condense our predecessor graph
1766 DFSNumber = 0;
1767 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1768 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1769 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1770
1771 for (unsigned i = 0; i < FirstRefNode; ++i) {
1772 if (FindNode(i) == i) {
1773 unsigned Node = VSSCCRep[i];
1774 if (!Node2Visited[Node])
1775 Condense(Node);
1776 }
1777 }
1778
1779 // Reset tables for actual labeling
1780 Node2DFS.clear();
1781 Node2Visited.clear();
1782 Node2Deleted.clear();
1783 // Pre-grow our densemap so that we don't get really bad behavior
1784 Set2PEClass.resize(GraphNodes.size());
1785
1786 // Visit the condensed graph and generate pointer equivalence labels.
1787 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1788 for (unsigned i = 0; i < FirstRefNode; ++i) {
1789 if (FindNode(i) == i) {
1790 unsigned Node = VSSCCRep[i];
1791 if (!Node2Visited[Node])
1792 HUValNum(Node);
1793 }
1794 }
1795 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1796 Set2PEClass.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001797 DEBUG(errs() << "Finished HU\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001798}
1799
1800
1801/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1802void Andersens::Condense(unsigned NodeIndex) {
1803 unsigned MyDFS = DFSNumber++;
1804 Node *N = &GraphNodes[NodeIndex];
1805 Node2Visited[NodeIndex] = true;
1806 Node2DFS[NodeIndex] = MyDFS;
1807
1808 // First process all our explicit edges
1809 if (N->PredEdges)
1810 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1811 Iter != N->PredEdges->end();
1812 ++Iter) {
1813 unsigned j = VSSCCRep[*Iter];
1814 if (!Node2Deleted[j]) {
1815 if (!Node2Visited[j])
1816 Condense(j);
1817 if (Node2DFS[NodeIndex] > Node2DFS[j])
1818 Node2DFS[NodeIndex] = Node2DFS[j];
1819 }
1820 }
1821
1822 // Now process all the implicit edges
1823 if (N->ImplicitPredEdges)
1824 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1825 Iter != N->ImplicitPredEdges->end();
1826 ++Iter) {
1827 unsigned j = VSSCCRep[*Iter];
1828 if (!Node2Deleted[j]) {
1829 if (!Node2Visited[j])
1830 Condense(j);
1831 if (Node2DFS[NodeIndex] > Node2DFS[j])
1832 Node2DFS[NodeIndex] = Node2DFS[j];
1833 }
1834 }
1835
1836 // See if we found any cycles
1837 if (MyDFS == Node2DFS[NodeIndex]) {
1838 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1839 unsigned CycleNodeIndex = SCCStack.top();
1840 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1841 VSSCCRep[CycleNodeIndex] = NodeIndex;
1842 // Unify the nodes
1843 N->Direct &= CycleNode->Direct;
1844
1845 *(N->PointsTo) |= CycleNode->PointsTo;
1846 delete CycleNode->PointsTo;
1847 CycleNode->PointsTo = NULL;
1848 if (CycleNode->PredEdges) {
1849 if (!N->PredEdges)
1850 N->PredEdges = new SparseBitVector<>;
1851 *(N->PredEdges) |= CycleNode->PredEdges;
1852 delete CycleNode->PredEdges;
1853 CycleNode->PredEdges = NULL;
1854 }
1855 if (CycleNode->ImplicitPredEdges) {
1856 if (!N->ImplicitPredEdges)
1857 N->ImplicitPredEdges = new SparseBitVector<>;
1858 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1859 delete CycleNode->ImplicitPredEdges;
1860 CycleNode->ImplicitPredEdges = NULL;
1861 }
1862 SCCStack.pop();
1863 }
1864
1865 Node2Deleted[NodeIndex] = true;
1866
1867 // Set up number of incoming edges for other nodes
1868 if (N->PredEdges)
1869 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1870 Iter != N->PredEdges->end();
1871 ++Iter)
1872 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1873 } else {
1874 SCCStack.push(NodeIndex);
1875 }
1876}
1877
1878void Andersens::HUValNum(unsigned NodeIndex) {
1879 Node *N = &GraphNodes[NodeIndex];
1880 Node2Visited[NodeIndex] = true;
1881
1882 // Eliminate dereferences of non-pointers for those non-pointers we have
1883 // already identified. These are ref nodes whose non-ref node:
1884 // 1. Has already been visited determined to point to nothing (and thus, a
1885 // dereference of it must point to nothing)
1886 // 2. Any direct node with no predecessor edges in our graph and with no
1887 // points-to set (since it can't point to anything either, being that it
1888 // receives no points-to sets and has none).
1889 if (NodeIndex >= FirstRefNode) {
1890 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1891 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1892 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1893 && GraphNodes[j].PointsTo->empty())){
1894 return;
1895 }
1896 }
1897 // Process all our explicit edges
1898 if (N->PredEdges)
1899 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1900 Iter != N->PredEdges->end();
1901 ++Iter) {
1902 unsigned j = VSSCCRep[*Iter];
1903 if (!Node2Visited[j])
1904 HUValNum(j);
1905
1906 // If this edge turned out to be the same as us, or got no pointer
1907 // equivalence label (and thus points to nothing) , just decrement our
1908 // incoming edges and continue.
1909 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1910 --GraphNodes[j].NumInEdges;
1911 continue;
1912 }
1913
1914 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1915
1916 // If we didn't end up storing this in the hash, and we're done with all
1917 // the edges, we don't need the points-to set anymore.
1918 --GraphNodes[j].NumInEdges;
1919 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1920 delete GraphNodes[j].PointsTo;
1921 GraphNodes[j].PointsTo = NULL;
1922 }
1923 }
1924 // If this isn't a direct node, generate a fresh variable.
1925 if (!N->Direct) {
1926 N->PointsTo->set(FirstRefNode + NodeIndex);
1927 }
1928
1929 // See If we have something equivalent to us, if not, generate a new
1930 // equivalence class.
1931 if (N->PointsTo->empty()) {
1932 delete N->PointsTo;
1933 N->PointsTo = NULL;
1934 } else {
1935 if (N->Direct) {
1936 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1937 if (N->PointerEquivLabel == 0) {
1938 unsigned EquivClass = PEClass++;
1939 N->StoredInHash = true;
1940 Set2PEClass[N->PointsTo] = EquivClass;
1941 N->PointerEquivLabel = EquivClass;
1942 }
1943 } else {
1944 N->PointerEquivLabel = PEClass++;
1945 }
1946 }
1947}
1948
1949/// Rewrite our list of constraints so that pointer equivalent nodes are
1950/// replaced by their the pointer equivalence class representative.
1951void Andersens::RewriteConstraints() {
1952 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001953 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001954
1955 PEClass2Node.clear();
1956 PENLEClass2Node.clear();
1957
1958 // We may have from 1 to Graphnodes + 1 equivalence classes.
1959 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1960 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1961
1962 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1963 // nodes, and rewriting constraints to use the representative nodes.
1964 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1965 Constraint &C = Constraints[i];
1966 unsigned RHSNode = FindNode(C.Src);
1967 unsigned LHSNode = FindNode(C.Dest);
1968 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1969 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1970
1971 // First we try to eliminate constraints for things we can prove don't point
1972 // to anything.
1973 if (LHSLabel == 0) {
1974 DEBUG(PrintNode(&GraphNodes[LHSNode]));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001975 DEBUG(errs() << " is a non-pointer, ignoring constraint.\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001976 continue;
1977 }
1978 if (RHSLabel == 0) {
1979 DEBUG(PrintNode(&GraphNodes[RHSNode]));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001980 DEBUG(errs() << " is a non-pointer, ignoring constraint.\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001981 continue;
1982 }
1983 // This constraint may be useless, and it may become useless as we translate
1984 // it.
1985 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1986 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001987
Daniel Berlind81ccc22007-09-24 19:45:49 +00001988 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1989 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001990 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001991 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001992 continue;
1993
Chris Lattnerbe207732007-09-30 00:47:20 +00001994 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001995 NewConstraints.push_back(C);
1996 }
1997 Constraints.swap(NewConstraints);
1998 PEClass2Node.clear();
1999}
2000
2001/// See if we have a node that is pointer equivalent to the one being asked
2002/// about, and if so, unite them and return the equivalent node. Otherwise,
2003/// return the original node.
2004unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
2005 unsigned NodeLabel) {
2006 if (!GraphNodes[NodeIndex].AddressTaken) {
2007 if (PEClass2Node[NodeLabel] != -1) {
2008 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002009 // We specifically request that Union-By-Rank not be used so that
2010 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
2011 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002012 } else {
2013 PEClass2Node[NodeLabel] = NodeIndex;
2014 PENLEClass2Node[NodeLabel] = NodeIndex;
2015 }
2016 } else if (PENLEClass2Node[NodeLabel] == -1) {
2017 PENLEClass2Node[NodeLabel] = NodeIndex;
2018 }
2019
2020 return NodeIndex;
2021}
2022
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002023void Andersens::PrintLabels() const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002024 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2025 if (i < FirstRefNode) {
2026 PrintNode(&GraphNodes[i]);
2027 } else if (i < FirstAdrNode) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002028 DEBUG(errs() << "REF(");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002029 PrintNode(&GraphNodes[i-FirstRefNode]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002030 DEBUG(errs() <<")");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002031 } else {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002032 DEBUG(errs() << "ADR(");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002033 PrintNode(&GraphNodes[i-FirstAdrNode]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002034 DEBUG(errs() <<")");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002035 }
2036
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002037 DEBUG(errs() << " has pointer label " << GraphNodes[i].PointerEquivLabel
Daniel Berlind81ccc22007-09-24 19:45:49 +00002038 << " and SCC rep " << VSSCCRep[i]
2039 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002040 << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002041 }
2042}
2043
Daniel Berlinc864edb2008-03-05 19:31:47 +00002044/// The technique used here is described in "The Ant and the
2045/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2046/// Lines of Code. In Programming Language Design and Implementation
2047/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2048/// Detection) algorithm. It is called a hybrid because it performs an
2049/// offline analysis and uses its results during the solving (online)
2050/// phase. This is just the offline portion; the results of this
2051/// operation are stored in SDT and are later used in SolveContraints()
2052/// and UniteNodes().
2053void Andersens::HCD() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002054 DEBUG(errs() << "Starting HCD.\n");
Daniel Berlinc864edb2008-03-05 19:31:47 +00002055 HCDSCCRep.resize(GraphNodes.size());
2056
2057 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2058 GraphNodes[i].Edges = new SparseBitVector<>;
2059 HCDSCCRep[i] = i;
2060 }
2061
2062 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2063 Constraint &C = Constraints[i];
2064 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2065 if (C.Type == Constraint::AddressOf) {
2066 continue;
2067 } else if (C.Type == Constraint::Load) {
2068 if( C.Offset == 0 )
2069 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2070 } else if (C.Type == Constraint::Store) {
2071 if( C.Offset == 0 )
2072 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2073 } else {
2074 GraphNodes[C.Dest].Edges->set(C.Src);
2075 }
2076 }
2077
2078 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2079 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2080 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2081 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2082
2083 DFSNumber = 0;
2084 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2085 unsigned Node = HCDSCCRep[i];
2086 if (!Node2Deleted[Node])
2087 Search(Node);
2088 }
2089
2090 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2091 if (GraphNodes[i].Edges != NULL) {
2092 delete GraphNodes[i].Edges;
2093 GraphNodes[i].Edges = NULL;
2094 }
2095
2096 while( !SCCStack.empty() )
2097 SCCStack.pop();
2098
2099 Node2DFS.clear();
2100 Node2Visited.clear();
2101 Node2Deleted.clear();
2102 HCDSCCRep.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002103 DEBUG(errs() << "HCD complete.\n");
Daniel Berlinc864edb2008-03-05 19:31:47 +00002104}
2105
2106// Component of HCD:
2107// Use Nuutila's variant of Tarjan's algorithm to detect
2108// Strongly-Connected Components (SCCs). For non-trivial SCCs
2109// containing ref nodes, insert the appropriate information in SDT.
2110void Andersens::Search(unsigned Node) {
2111 unsigned MyDFS = DFSNumber++;
2112
2113 Node2Visited[Node] = true;
2114 Node2DFS[Node] = MyDFS;
2115
2116 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2117 End = GraphNodes[Node].Edges->end();
2118 Iter != End;
2119 ++Iter) {
2120 unsigned J = HCDSCCRep[*Iter];
2121 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2122 if (!Node2Deleted[J]) {
2123 if (!Node2Visited[J])
2124 Search(J);
2125 if (Node2DFS[Node] > Node2DFS[J])
2126 Node2DFS[Node] = Node2DFS[J];
2127 }
2128 }
2129
2130 if( MyDFS != Node2DFS[Node] ) {
2131 SCCStack.push(Node);
2132 return;
2133 }
2134
2135 // This node is the root of a SCC, so process it.
2136 //
2137 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2138 // node, we place this SCC into SDT. We unite the nodes in any case.
2139 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2140 SparseBitVector<> SCC;
2141
2142 SCC.set(Node);
2143
2144 bool Ref = (Node >= FirstRefNode);
2145
2146 Node2Deleted[Node] = true;
2147
2148 do {
2149 unsigned P = SCCStack.top(); SCCStack.pop();
2150 Ref |= (P >= FirstRefNode);
2151 SCC.set(P);
2152 HCDSCCRep[P] = Node;
2153 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2154
2155 if (Ref) {
2156 unsigned Rep = SCC.find_first();
2157 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2158
2159 SparseBitVector<>::iterator i = SCC.begin();
2160
2161 // Skip over the non-ref nodes
2162 while( *i < FirstRefNode )
2163 ++i;
2164
2165 while( i != SCC.end() )
2166 SDT[ (*i++) - FirstRefNode ] = Rep;
2167 }
2168 }
2169}
2170
2171
Daniel Berlind81ccc22007-09-24 19:45:49 +00002172/// Optimize the constraints by performing offline variable substitution and
2173/// other optimizations.
2174void Andersens::OptimizeConstraints() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002175 DEBUG(errs() << "Beginning constraint optimization\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002176
Daniel Berlinc864edb2008-03-05 19:31:47 +00002177 SDTActive = false;
2178
Daniel Berlind81ccc22007-09-24 19:45:49 +00002179 // Function related nodes need to stay in the same relative position and can't
2180 // be location equivalent.
2181 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2182 Iter != MaxK.end();
2183 ++Iter) {
2184 for (unsigned i = Iter->first;
2185 i != Iter->first + Iter->second;
2186 ++i) {
2187 GraphNodes[i].AddressTaken = true;
2188 GraphNodes[i].Direct = false;
2189 }
2190 }
2191
2192 ClumpAddressTaken();
2193 FirstRefNode = GraphNodes.size();
2194 FirstAdrNode = FirstRefNode + GraphNodes.size();
2195 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2196 Node(false));
2197 VSSCCRep.resize(GraphNodes.size());
2198 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2199 VSSCCRep[i] = i;
2200 }
2201 HVN();
2202 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2203 Node *N = &GraphNodes[i];
2204 delete N->PredEdges;
2205 N->PredEdges = NULL;
2206 delete N->ImplicitPredEdges;
2207 N->ImplicitPredEdges = NULL;
2208 }
2209#undef DEBUG_TYPE
2210#define DEBUG_TYPE "anders-aa-labels"
2211 DEBUG(PrintLabels());
2212#undef DEBUG_TYPE
2213#define DEBUG_TYPE "anders-aa"
2214 RewriteConstraints();
2215 // Delete the adr nodes.
2216 GraphNodes.resize(FirstRefNode * 2);
2217
2218 // Now perform HU
2219 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2220 Node *N = &GraphNodes[i];
2221 if (FindNode(i) == i) {
2222 N->PointsTo = new SparseBitVector<>;
2223 N->PointedToBy = new SparseBitVector<>;
2224 // Reset our labels
2225 }
2226 VSSCCRep[i] = i;
2227 N->PointerEquivLabel = 0;
2228 }
2229 HU();
2230#undef DEBUG_TYPE
2231#define DEBUG_TYPE "anders-aa-labels"
2232 DEBUG(PrintLabels());
2233#undef DEBUG_TYPE
2234#define DEBUG_TYPE "anders-aa"
2235 RewriteConstraints();
2236 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2237 if (FindNode(i) == i) {
2238 Node *N = &GraphNodes[i];
2239 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002240 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002241 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002242 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002243 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002244 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002245 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002246 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002247 }
2248 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002249
2250 // perform Hybrid Cycle Detection (HCD)
2251 HCD();
2252 SDTActive = true;
2253
2254 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002255 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002256
2257 // HCD complete.
2258
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002259 DEBUG(errs() << "Finished constraint optimization\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002260 FirstRefNode = 0;
2261 FirstAdrNode = 0;
2262}
2263
2264/// Unite pointer but not location equivalent variables, now that the constraint
2265/// graph is built.
2266void Andersens::UnitePointerEquivalences() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002267 DEBUG(errs() << "Uniting remaining pointer equivalences\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002268 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002269 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002270 unsigned Label = GraphNodes[i].PointerEquivLabel;
2271
2272 if (Label && PENLEClass2Node[Label] != -1)
2273 UniteNodes(i, PENLEClass2Node[Label]);
2274 }
2275 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002276 DEBUG(errs() << "Finished remaining pointer equivalences\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002277 PENLEClass2Node.clear();
2278}
2279
2280/// Create the constraint graph used for solving points-to analysis.
2281///
Daniel Berlinaad15882007-09-16 21:45:02 +00002282void Andersens::CreateConstraintGraph() {
2283 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2284 Constraint &C = Constraints[i];
2285 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2286 if (C.Type == Constraint::AddressOf)
2287 GraphNodes[C.Dest].PointsTo->set(C.Src);
2288 else if (C.Type == Constraint::Load)
2289 GraphNodes[C.Src].Constraints.push_back(C);
2290 else if (C.Type == Constraint::Store)
2291 GraphNodes[C.Dest].Constraints.push_back(C);
2292 else if (C.Offset != 0)
2293 GraphNodes[C.Src].Constraints.push_back(C);
2294 else
2295 GraphNodes[C.Src].Edges->set(C.Dest);
2296 }
2297}
2298
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002299// Perform DFS and cycle detection.
2300bool Andersens::QueryNode(unsigned Node) {
2301 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002302 unsigned OurDFS = ++DFSNumber;
2303 SparseBitVector<> ToErase;
2304 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002305 Tarjan2DFS[Node] = OurDFS;
2306
2307 // Changed denotes a change from a recursive call that we will bubble up.
2308 // Merged is set if we actually merge a node ourselves.
2309 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002310
2311 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2312 bi != GraphNodes[Node].Edges->end();
2313 ++bi) {
2314 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002315 // If this edge points to a non-representative node but we are
2316 // already planning to add an edge to its representative, we have no
2317 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002318 if (RepNode != *bi && NewEdges.test(RepNode)){
2319 ToErase.set(*bi);
2320 continue;
2321 }
2322
2323 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002324 if (!Tarjan2Deleted[RepNode]){
2325 if (Tarjan2DFS[RepNode] == 0) {
2326 Changed |= QueryNode(RepNode);
2327 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002328 RepNode = FindNode(RepNode);
2329 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002330 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2331 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002332 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002333
2334 // We may have just discovered that this node is part of a cycle, in
2335 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002336 if (RepNode != *bi) {
2337 ToErase.set(*bi);
2338 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002339 }
2340 }
2341
Daniel Berlinaad15882007-09-16 21:45:02 +00002342 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2343 GraphNodes[Node].Edges |= NewEdges;
2344
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002345 // If this node is a root of a non-trivial SCC, place it on our
2346 // worklist to be processed.
2347 if (OurDFS == Tarjan2DFS[Node]) {
2348 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2349 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002350
2351 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002352 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002353 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002354 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002355
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002356 if (Merged)
2357 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002358 } else {
2359 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002360 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002361
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002362 return(Changed | Merged);
2363}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002364
2365/// SolveConstraints - This stage iteratively processes the constraints list
2366/// propagating constraints (adding edges to the Nodes in the points-to graph)
2367/// until a fixed point is reached.
2368///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002369/// We use a variant of the technique called "Lazy Cycle Detection", which is
2370/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2371/// Analysis for Millions of Lines of Code. In Programming Language Design and
2372/// Implementation (PLDI), June 2007."
2373/// The paper describes performing cycle detection one node at a time, which can
2374/// be expensive if there are no cycles, but there are long chains of nodes that
2375/// it heuristically believes are cycles (because it will DFS from each node
2376/// without state from previous nodes).
2377/// Instead, we use the heuristic to build a worklist of nodes to check, then
2378/// cycle detect them all at the same time to do this more cheaply. This
2379/// catches cycles slightly later than the original technique did, but does it
2380/// make significantly cheaper.
2381
Chris Lattnere995a2a2004-05-23 21:00:47 +00002382void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002383 CurrWL = &w1;
2384 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002385
Daniel Berlind81ccc22007-09-24 19:45:49 +00002386 OptimizeConstraints();
2387#undef DEBUG_TYPE
2388#define DEBUG_TYPE "anders-aa-constraints"
2389 DEBUG(PrintConstraints());
2390#undef DEBUG_TYPE
2391#define DEBUG_TYPE "anders-aa"
2392
Daniel Berlinaad15882007-09-16 21:45:02 +00002393 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2394 Node *N = &GraphNodes[i];
2395 N->PointsTo = new SparseBitVector<>;
2396 N->OldPointsTo = new SparseBitVector<>;
2397 N->Edges = new SparseBitVector<>;
2398 }
2399 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002400 UnitePointerEquivalences();
2401 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002402 Node2DFS.clear();
2403 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002404 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2405 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2406 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002407 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2408 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2409
2410 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002411 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002412 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002413
2414 // Add to work list if it's a representative and can contribute to the
2415 // calculation right now.
2416 if (INode->isRep() && !INode->PointsTo->empty()
2417 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2418 INode->Stamp();
2419 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002420 }
2421 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002422 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002423#if !FULL_UNIVERSAL
2424 // "Rep and special variables" - in order for HCD to maintain conservative
2425 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2426 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2427 // the analysis - it's ok to add edges from the special nodes, but never
2428 // *to* the special nodes.
2429 std::vector<unsigned int> RSV;
2430#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002431 while( !CurrWL->empty() ) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002432 DEBUG(errs() << "Starting iteration #" << ++NumIters << "\n");
Daniel Berlinaad15882007-09-16 21:45:02 +00002433
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002434 Node* CurrNode;
2435 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002436
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002437 // Actual cycle checking code. We cycle check all of the lazy cycle
2438 // candidates from the last iteration in one go.
2439 if (!TarjanWL.empty()) {
2440 DFSNumber = 0;
2441
2442 Tarjan2DFS.clear();
2443 Tarjan2Deleted.clear();
2444 while (!TarjanWL.empty()) {
2445 unsigned int ToTarjan = TarjanWL.front();
2446 TarjanWL.pop();
2447 if (!Tarjan2Deleted[ToTarjan]
2448 && GraphNodes[ToTarjan].isRep()
2449 && Tarjan2DFS[ToTarjan] == 0)
2450 QueryNode(ToTarjan);
2451 }
2452 }
2453
2454 // Add to work list if it's a representative and can contribute to the
2455 // calculation right now.
2456 while( (CurrNode = CurrWL->pop()) != NULL ) {
2457 CurrNodeIndex = CurrNode - &GraphNodes[0];
2458 CurrNode->Stamp();
2459
2460
Daniel Berlinaad15882007-09-16 21:45:02 +00002461 // Figure out the changed points to bits
2462 SparseBitVector<> CurrPointsTo;
2463 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2464 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002465 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002466 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002467
Daniel Berlinaad15882007-09-16 21:45:02 +00002468 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002469
2470 // Check the offline-computed equivalencies from HCD.
2471 bool SCC = false;
2472 unsigned Rep;
2473
2474 if (SDT[CurrNodeIndex] >= 0) {
2475 SCC = true;
2476 Rep = FindNode(SDT[CurrNodeIndex]);
2477
2478#if !FULL_UNIVERSAL
2479 RSV.clear();
2480#endif
2481 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2482 bi != CurrPointsTo.end(); ++bi) {
2483 unsigned Node = FindNode(*bi);
2484#if !FULL_UNIVERSAL
2485 if (Node < NumberSpecialNodes) {
2486 RSV.push_back(Node);
2487 continue;
2488 }
2489#endif
2490 Rep = UniteNodes(Rep,Node);
2491 }
2492#if !FULL_UNIVERSAL
2493 RSV.push_back(Rep);
2494#endif
2495
2496 NextWL->insert(&GraphNodes[Rep]);
2497
2498 if ( ! CurrNode->isRep() )
2499 continue;
2500 }
2501
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002502 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002503
Daniel Berlinaad15882007-09-16 21:45:02 +00002504 /* Now process the constraints for this node. */
2505 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2506 li != CurrNode->Constraints.end(); ) {
2507 li->Src = FindNode(li->Src);
2508 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002509
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002510 // Delete redundant constraints
2511 if( Seen.count(*li) ) {
2512 std::list<Constraint>::iterator lk = li; li++;
2513
2514 CurrNode->Constraints.erase(lk);
2515 ++NumErased;
2516 continue;
2517 }
2518 Seen.insert(*li);
2519
Daniel Berlinaad15882007-09-16 21:45:02 +00002520 // Src and Dest will be the vars we are going to process.
2521 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002522 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002523 // Load constraints say that every member of our RHS solution has K
2524 // added to it, and that variable gets an edge to LHS. We also union
2525 // RHS+K's solution into the LHS solution.
2526 // Store constraints say that every member of our LHS solution has K
2527 // added to it, and that variable gets an edge from RHS. We also union
2528 // RHS's solution into the LHS+K solution.
2529 unsigned *Src;
2530 unsigned *Dest;
2531 unsigned K = li->Offset;
2532 unsigned CurrMember;
2533 if (li->Type == Constraint::Load) {
2534 Src = &CurrMember;
2535 Dest = &li->Dest;
2536 } else if (li->Type == Constraint::Store) {
2537 Src = &li->Src;
2538 Dest = &CurrMember;
2539 } else {
2540 // TODO Handle offseted copy constraint
2541 li++;
2542 continue;
2543 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002544
2545 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002546 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002547 // involves pointers; if so, remove the redundant constraints).
2548 if( SCC && K == 0 ) {
2549#if FULL_UNIVERSAL
2550 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002551
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002552 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2553 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2554 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002555#else
2556 for (unsigned i=0; i < RSV.size(); ++i) {
2557 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002558
Daniel Berlinc864edb2008-03-05 19:31:47 +00002559 if (*Dest < NumberSpecialNodes)
2560 continue;
2561 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2562 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2563 NextWL->insert(&GraphNodes[*Dest]);
2564 }
2565#endif
2566 // since all future elements of the points-to set will be
2567 // equivalent to the current ones, the complex constraints
2568 // become redundant.
2569 //
2570 std::list<Constraint>::iterator lk = li; li++;
2571#if !FULL_UNIVERSAL
2572 // In this case, we can still erase the constraints when the
2573 // elements of the points-to sets are referenced by *Dest,
2574 // but not when they are referenced by *Src (i.e. for a Load
2575 // constraint). This is because if another special variable is
2576 // put into the points-to set later, we still need to add the
2577 // new edge from that special variable.
2578 if( lk->Type != Constraint::Load)
2579#endif
2580 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2581 } else {
2582 const SparseBitVector<> &Solution = CurrPointsTo;
2583
2584 for (SparseBitVector<>::iterator bi = Solution.begin();
2585 bi != Solution.end();
2586 ++bi) {
2587 CurrMember = *bi;
2588
2589 // Need to increment the member by K since that is where we are
2590 // supposed to copy to/from. Note that in positive weight cycles,
2591 // which occur in address taking of fields, K can go past
2592 // MaxK[CurrMember] elements, even though that is all it could point
2593 // to.
2594 if (K > 0 && K > MaxK[CurrMember])
2595 continue;
2596 else
2597 CurrMember = FindNode(CurrMember + K);
2598
2599 // Add an edge to the graph, so we can just do regular
2600 // bitmap ior next time. It may also let us notice a cycle.
2601#if !FULL_UNIVERSAL
2602 if (*Dest < NumberSpecialNodes)
2603 continue;
2604#endif
2605 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2606 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2607 NextWL->insert(&GraphNodes[*Dest]);
2608
2609 }
2610 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002611 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002612 }
2613 SparseBitVector<> NewEdges;
2614 SparseBitVector<> ToErase;
2615
2616 // Now all we have left to do is propagate points-to info along the
2617 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002618 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2619 bi != CurrNode->Edges->end();
2620 ++bi) {
2621
2622 unsigned DestVar = *bi;
2623 unsigned Rep = FindNode(DestVar);
2624
Bill Wendlingf059deb2008-02-26 10:51:52 +00002625 // If we ended up with this node as our destination, or we've already
2626 // got an edge for the representative, delete the current edge.
2627 if (Rep == CurrNodeIndex ||
2628 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002629 ToErase.set(DestVar);
2630 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002631 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002632
Bill Wendlingf059deb2008-02-26 10:51:52 +00002633 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002634
2635 // This is where we do lazy cycle detection.
2636 // If this is a cycle candidate (equal points-to sets and this
2637 // particular edge has not been cycle-checked previously), add to the
2638 // list to check for cycles on the next iteration.
2639 if (!EdgesChecked.count(edge) &&
2640 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2641 EdgesChecked.insert(edge);
2642 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002643 }
2644 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002645#if !FULL_UNIVERSAL
2646 if (Rep >= NumberSpecialNodes)
2647#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002648 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002649 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002650 }
2651 // If this edge's destination was collapsed, rewrite the edge.
2652 if (Rep != DestVar) {
2653 ToErase.set(DestVar);
2654 NewEdges.set(Rep);
2655 }
2656 }
2657 CurrNode->Edges->intersectWithComplement(ToErase);
2658 CurrNode->Edges |= NewEdges;
2659 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002660
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002661 // Switch to other work list.
2662 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2663 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002664
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002665
Daniel Berlinaad15882007-09-16 21:45:02 +00002666 Node2DFS.clear();
2667 Node2Deleted.clear();
2668 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2669 Node *N = &GraphNodes[i];
2670 delete N->OldPointsTo;
2671 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002672 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002673 SDTActive = false;
2674 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002675}
2676
Daniel Berlinaad15882007-09-16 21:45:02 +00002677//===----------------------------------------------------------------------===//
2678// Union-Find
2679//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002680
Daniel Berlinaad15882007-09-16 21:45:02 +00002681// Unite nodes First and Second, returning the one which is now the
2682// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002683unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2684 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002685 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2686 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002687
Daniel Berlinaad15882007-09-16 21:45:02 +00002688 Node *FirstNode = &GraphNodes[First];
2689 Node *SecondNode = &GraphNodes[Second];
2690
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002691 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002692 "Trying to unite two non-representative nodes!");
2693 if (First == Second)
2694 return First;
2695
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002696 if (UnionByRank) {
2697 int RankFirst = (int) FirstNode ->NodeRep;
2698 int RankSecond = (int) SecondNode->NodeRep;
2699
2700 // Rank starts at -1 and gets decremented as it increases.
2701 // Translation: higher rank, lower NodeRep value, which is always negative.
2702 if (RankFirst > RankSecond) {
2703 unsigned t = First; First = Second; Second = t;
2704 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2705 } else if (RankFirst == RankSecond) {
2706 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2707 }
2708 }
2709
Daniel Berlinaad15882007-09-16 21:45:02 +00002710 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002711#if !FULL_UNIVERSAL
2712 if (First >= NumberSpecialNodes)
2713#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002714 if (FirstNode->PointsTo && SecondNode->PointsTo)
2715 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2716 if (FirstNode->Edges && SecondNode->Edges)
2717 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002718 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002719 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2720 SecondNode->Constraints);
2721 if (FirstNode->OldPointsTo) {
2722 delete FirstNode->OldPointsTo;
2723 FirstNode->OldPointsTo = new SparseBitVector<>;
2724 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002725
2726 // Destroy interesting parts of the merged-from node.
2727 delete SecondNode->OldPointsTo;
2728 delete SecondNode->Edges;
2729 delete SecondNode->PointsTo;
2730 SecondNode->Edges = NULL;
2731 SecondNode->PointsTo = NULL;
2732 SecondNode->OldPointsTo = NULL;
2733
2734 NumUnified++;
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002735 DEBUG(errs() << "Unified Node ");
Daniel Berlinaad15882007-09-16 21:45:02 +00002736 DEBUG(PrintNode(FirstNode));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002737 DEBUG(errs() << " and Node ");
Daniel Berlinaad15882007-09-16 21:45:02 +00002738 DEBUG(PrintNode(SecondNode));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002739 DEBUG(errs() << "\n");
Daniel Berlinaad15882007-09-16 21:45:02 +00002740
Daniel Berlinc864edb2008-03-05 19:31:47 +00002741 if (SDTActive)
Duncan Sands43e2a032008-05-27 11:50:51 +00002742 if (SDT[Second] >= 0) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002743 if (SDT[First] < 0)
2744 SDT[First] = SDT[Second];
2745 else {
2746 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2747 First = FindNode(First);
2748 }
Duncan Sands43e2a032008-05-27 11:50:51 +00002749 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002750
Daniel Berlinaad15882007-09-16 21:45:02 +00002751 return First;
2752}
2753
2754// Find the index into GraphNodes of the node representing Node, performing
2755// path compression along the way
2756unsigned Andersens::FindNode(unsigned NodeIndex) {
2757 assert (NodeIndex < GraphNodes.size()
2758 && "Attempting to find a node that can't exist");
2759 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002760 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002761 return NodeIndex;
2762 else
2763 return (N->NodeRep = FindNode(N->NodeRep));
2764}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002765
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002766// Find the index into GraphNodes of the node representing Node,
2767// don't perform path compression along the way (for Print)
2768unsigned Andersens::FindNode(unsigned NodeIndex) const {
2769 assert (NodeIndex < GraphNodes.size()
2770 && "Attempting to find a node that can't exist");
2771 const Node *N = &GraphNodes[NodeIndex];
2772 if (N->isRep())
2773 return NodeIndex;
2774 else
2775 return FindNode(N->NodeRep);
2776}
2777
Chris Lattnere995a2a2004-05-23 21:00:47 +00002778//===----------------------------------------------------------------------===//
2779// Debugging Output
2780//===----------------------------------------------------------------------===//
2781
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002782void Andersens::PrintNode(const Node *N) const {
Chris Lattnere995a2a2004-05-23 21:00:47 +00002783 if (N == &GraphNodes[UniversalSet]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002784 errs() << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002785 return;
2786 } else if (N == &GraphNodes[NullPtr]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002787 errs() << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002788 return;
2789 } else if (N == &GraphNodes[NullObject]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002790 errs() << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002791 return;
2792 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002793 if (!N->getValue()) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002794 errs() << "artificial" << (intptr_t) N;
Daniel Berlinaad15882007-09-16 21:45:02 +00002795 return;
2796 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002797
2798 assert(N->getValue() != 0 && "Never set node label!");
2799 Value *V = N->getValue();
2800 if (Function *F = dyn_cast<Function>(V)) {
2801 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002802 N == &GraphNodes[getReturnNode(F)]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002803 errs() << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002804 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002805 } else if (F->getFunctionType()->isVarArg() &&
2806 N == &GraphNodes[getVarargNode(F)]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002807 errs() << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002808 return;
2809 }
2810 }
2811
2812 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002813 errs() << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002814 else if (Argument *Arg = dyn_cast<Argument>(V))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002815 errs() << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002816
2817 if (V->hasName())
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002818 errs() << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002819 else
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002820 errs() << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002821
Victor Hernandez46e83122009-09-18 21:34:51 +00002822 if (isa<GlobalValue>(V) || isa<AllocationInst>(V) || isMalloc(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002823 if (N == &GraphNodes[getObject(V)])
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002824 errs() << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002825}
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002826void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002827 if (C.Type == Constraint::Store) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002828 errs() << "*";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002829 if (C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002830 errs() << "(";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002831 }
2832 PrintNode(&GraphNodes[C.Dest]);
2833 if (C.Type == Constraint::Store && C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002834 errs() << " + " << C.Offset << ")";
2835 errs() << " = ";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002836 if (C.Type == Constraint::Load) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002837 errs() << "*";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002838 if (C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002839 errs() << "(";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002840 }
2841 else if (C.Type == Constraint::AddressOf)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002842 errs() << "&";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002843 PrintNode(&GraphNodes[C.Src]);
2844 if (C.Offset != 0 && C.Type != Constraint::Store)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002845 errs() << " + " << C.Offset;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002846 if (C.Type == Constraint::Load && C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002847 errs() << ")";
2848 errs() << "\n";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002849}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002850
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002851void Andersens::PrintConstraints() const {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002852 errs() << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002853
Daniel Berlind81ccc22007-09-24 19:45:49 +00002854 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2855 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002856}
2857
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002858void Andersens::PrintPointsToGraph() const {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002859 errs() << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002860 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002861 const Node *N = &GraphNodes[i];
2862 if (FindNode(i) != i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002863 PrintNode(N);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002864 errs() << "\t--> same as ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002865 PrintNode(&GraphNodes[FindNode(i)]);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002866 errs() << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002867 } else {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002868 errs() << "[" << (N->PointsTo->count()) << "] ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002869 PrintNode(N);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002870 errs() << "\t--> ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002871
2872 bool first = true;
2873 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2874 bi != N->PointsTo->end();
2875 ++bi) {
2876 if (!first)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002877 errs() << ", ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002878 PrintNode(&GraphNodes[*bi]);
2879 first = false;
2880 }
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002881 errs() << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002882 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002883 }
2884}