blob: 01566a0651b73e6bbc5f365bbd5ba1a58ba1ef60 [file] [log] [blame]
Chris Lattnerd28b0d72004-06-25 04:24:22 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattnere995a2a2004-05-23 21:00:47 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattnere995a2a2004-05-23 21:00:47 +00008//===----------------------------------------------------------------------===//
9//
Daniel Berlinaad15882007-09-16 21:45:02 +000010// This file defines an implementation of Andersen's interprocedural alias
11// analysis
Chris Lattnere995a2a2004-05-23 21:00:47 +000012//
13// In pointer analysis terms, this is a subset-based, flow-insensitive,
Daniel Berlinaad15882007-09-16 21:45:02 +000014// field-sensitive, and context-insensitive algorithm pointer algorithm.
Chris Lattnere995a2a2004-05-23 21:00:47 +000015//
16// This algorithm is implemented as three stages:
17// 1. Object identification.
18// 2. Inclusion constraint identification.
Daniel Berlind81ccc22007-09-24 19:45:49 +000019// 3. Offline constraint graph optimization
20// 4. Inclusion constraint solving.
Chris Lattnere995a2a2004-05-23 21:00:47 +000021//
22// The object identification stage identifies all of the memory objects in the
23// program, which includes globals, heap allocated objects, and stack allocated
24// objects.
25//
26// The inclusion constraint identification stage finds all inclusion constraints
27// in the program by scanning the program, looking for pointer assignments and
28// other statements that effect the points-to graph. For a statement like "A =
29// B", this statement is processed to indicate that A can point to anything that
Daniel Berlinaad15882007-09-16 21:45:02 +000030// B can point to. Constraints can handle copies, loads, and stores, and
31// address taking.
Chris Lattnere995a2a2004-05-23 21:00:47 +000032//
Daniel Berline6f04792007-09-24 22:20:45 +000033// The offline constraint graph optimization portion includes offline variable
Daniel Berlinc864edb2008-03-05 19:31:47 +000034// substitution algorithms intended to compute pointer and location
Daniel Berline6f04792007-09-24 22:20:45 +000035// equivalences. Pointer equivalences are those pointers that will have the
36// same points-to sets, and location equivalences are those variables that
Daniel Berlinc864edb2008-03-05 19:31:47 +000037// always appear together in points-to sets. It also includes an offline
38// cycle detection algorithm that allows cycles to be collapsed sooner
39// during solving.
Daniel Berlind81ccc22007-09-24 19:45:49 +000040//
Chris Lattnere995a2a2004-05-23 21:00:47 +000041// The inclusion constraint solving phase iteratively propagates the inclusion
42// constraints until a fixed point is reached. This is an O(N^3) algorithm.
43//
Daniel Berlinaad15882007-09-16 21:45:02 +000044// Function constraints are handled as if they were structs with X fields.
45// Thus, an access to argument X of function Y is an access to node index
46// getNode(Y) + X. This representation allows handling of indirect calls
Daniel Berlind81ccc22007-09-24 19:45:49 +000047// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlinaad15882007-09-16 21:45:02 +000048// *(Y + 1) = a, *(Y + 2) = b.
49// The return node for a function is always located at getNode(F) +
50// CallReturnPos. The arguments start at getNode(F) + CallArgPos.
Chris Lattnere995a2a2004-05-23 21:00:47 +000051//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000052// Future Improvements:
Daniel Berlinc864edb2008-03-05 19:31:47 +000053// Use of BDD's.
Chris Lattnere995a2a2004-05-23 21:00:47 +000054//===----------------------------------------------------------------------===//
55
56#define DEBUG_TYPE "anders-aa"
57#include "llvm/Constants.h"
58#include "llvm/DerivedTypes.h"
59#include "llvm/Instructions.h"
60#include "llvm/Module.h"
61#include "llvm/Pass.h"
Reid Spencerd7d83db2007-02-05 23:42:17 +000062#include "llvm/Support/Compiler.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000063#include "llvm/Support/ErrorHandling.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000064#include "llvm/Support/InstIterator.h"
65#include "llvm/Support/InstVisitor.h"
66#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000067#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000068#include "llvm/Support/Debug.h"
Owen Anderson2e693102009-06-24 22:16:52 +000069#include "llvm/System/Atomic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000070#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000071#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000072#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000073#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000074#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000075#include <list>
Dan Gohmanc9235d22008-03-21 23:51:57 +000076#include <map>
Daniel Berlinaad15882007-09-16 21:45:02 +000077#include <stack>
78#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000079#include <queue>
80
81// Determining the actual set of nodes the universal set can consist of is very
82// expensive because it means propagating around very large sets. We rely on
83// other analysis being able to determine which nodes can never be pointed to in
84// order to disambiguate further than "points-to anything".
85#define FULL_UNIVERSAL 0
Chris Lattnere995a2a2004-05-23 21:00:47 +000086
Daniel Berlinaad15882007-09-16 21:45:02 +000087using namespace llvm;
Daniel Dunbare317bcc2009-08-23 10:29:55 +000088#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +000089STATISTIC(NumIters , "Number of iterations to reach convergence");
Daniel Dunbare317bcc2009-08-23 10:29:55 +000090#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +000091STATISTIC(NumConstraints, "Number of constraints");
92STATISTIC(NumNodes , "Number of nodes");
93STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000094STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000095
Dan Gohman844731a2008-05-13 00:00:25 +000096static const unsigned SelfRep = (unsigned)-1;
97static const unsigned Unvisited = (unsigned)-1;
98// Position of the function return node relative to the function node.
99static const unsigned CallReturnPos = 1;
100// Position of the function call node relative to the function node.
101static const unsigned CallFirstArgPos = 2;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000102
Dan Gohman844731a2008-05-13 00:00:25 +0000103namespace {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000104 struct BitmapKeyInfo {
105 static inline SparseBitVector<> *getEmptyKey() {
106 return reinterpret_cast<SparseBitVector<> *>(-1);
107 }
108 static inline SparseBitVector<> *getTombstoneKey() {
109 return reinterpret_cast<SparseBitVector<> *>(-2);
110 }
111 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
112 return bitmap->getHashValue();
113 }
114 static bool isEqual(const SparseBitVector<> *LHS,
115 const SparseBitVector<> *RHS) {
116 if (LHS == RHS)
117 return true;
118 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
119 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
120 return false;
121
122 return *LHS == *RHS;
123 }
124
125 static bool isPod() { return true; }
126 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000127
Reid Spencerd7d83db2007-02-05 23:42:17 +0000128 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
129 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000130 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000131
132 /// Constraint - Objects of this structure are used to represent the various
133 /// constraints identified by the algorithm. The constraints are 'copy',
134 /// for statements like "A = B", 'load' for statements like "A = *B",
135 /// 'store' for statements like "*A = B", and AddressOf for statements like
136 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
137 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000138 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000139 /// resolvable to A = &C where C = B + K)
140
141 struct Constraint {
142 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
143 unsigned Dest;
144 unsigned Src;
145 unsigned Offset;
146
147 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
148 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000149 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000150 "Offset is illegal on addressof constraints");
151 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000152
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000153 bool operator==(const Constraint &RHS) const {
154 return RHS.Type == Type
155 && RHS.Dest == Dest
156 && RHS.Src == Src
157 && RHS.Offset == Offset;
158 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000159
160 bool operator!=(const Constraint &RHS) const {
161 return !(*this == RHS);
162 }
163
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000164 bool operator<(const Constraint &RHS) const {
165 if (RHS.Type != Type)
166 return RHS.Type < Type;
167 else if (RHS.Dest != Dest)
168 return RHS.Dest < Dest;
169 else if (RHS.Src != Src)
170 return RHS.Src < Src;
171 return RHS.Offset < Offset;
172 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000173 };
174
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000175 // Information DenseSet requires implemented in order to be able to do
176 // it's thing
177 struct PairKeyInfo {
178 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000179 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000180 }
181 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000182 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000183 }
184 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
185 return P.first ^ P.second;
186 }
187 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
188 const std::pair<unsigned, unsigned> &RHS) {
189 return LHS == RHS;
190 }
191 };
192
Daniel Berlin336c6c02007-09-29 00:50:40 +0000193 struct ConstraintKeyInfo {
194 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000195 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000196 }
197 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000198 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000199 }
200 static unsigned getHashValue(const Constraint &C) {
201 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
202 }
203 static bool isEqual(const Constraint &LHS,
204 const Constraint &RHS) {
205 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
206 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
207 }
208 };
209
Daniel Berlind81ccc22007-09-24 19:45:49 +0000210 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000211 // graph. Due to various optimizations, it is not always the case that
212 // there is a mapping from a Node to a Value. In particular, we add
213 // artificial Node's that represent the set of pointed-to variables shared
214 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000215 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000216 private:
Owen Anderson5ec56cc2009-06-30 05:33:46 +0000217 static volatile sys::cas_flag Counter;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000218
219 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000220 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000221 SparseBitVector<> *Edges;
222 SparseBitVector<> *PointsTo;
223 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000224 std::list<Constraint> Constraints;
225
Daniel Berlind81ccc22007-09-24 19:45:49 +0000226 // Pointer and location equivalence labels
227 unsigned PointerEquivLabel;
228 unsigned LocationEquivLabel;
229 // Predecessor edges, both real and implicit
230 SparseBitVector<> *PredEdges;
231 SparseBitVector<> *ImplicitPredEdges;
232 // Set of nodes that point to us, only use for location equivalence.
233 SparseBitVector<> *PointedToBy;
234 // Number of incoming edges, used during variable substitution to early
235 // free the points-to sets
236 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000237 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000238 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000239 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000240 bool Direct;
241 // True if the node is address taken, *or* it is part of a group of nodes
242 // that must be kept together. This is set to true for functions and
243 // their arg nodes, which must be kept at the same position relative to
244 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000245 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000246
Daniel Berlind81ccc22007-09-24 19:45:49 +0000247 // Nodes in cycles (or in equivalence classes) are united together using a
248 // standard union-find representation with path compression. NodeRep
249 // gives the index into GraphNodes for the representative Node.
250 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000251
252 // Modification timestamp. Assigned from Counter.
253 // Used for work list prioritization.
254 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000255
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000256 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000257 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000258 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
259 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
260 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000261 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000262
Chris Lattnere995a2a2004-05-23 21:00:47 +0000263 Node *setValue(Value *V) {
264 assert(Val == 0 && "Value already set for this node!");
265 Val = V;
266 return this;
267 }
268
269 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000270 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000271 Value *getValue() const { return Val; }
272
Chris Lattnere995a2a2004-05-23 21:00:47 +0000273 /// addPointerTo - Add a pointer to the list of pointees of this node,
274 /// returning true if this caused a new pointer to be added, or false if
275 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000276 bool addPointerTo(unsigned Node) {
277 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000278 }
279
280 /// intersects - Return true if the points-to set of this node intersects
281 /// with the points-to set of the specified node.
282 bool intersects(Node *N) const;
283
284 /// intersectsIgnoring - Return true if the points-to set of this node
285 /// intersects with the points-to set of the specified node on any nodes
286 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000287 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000288
289 // Timestamp a node (used for work list prioritization)
290 void Stamp() {
Owen Anderson2d7f78e2009-06-25 16:32:45 +0000291 Timestamp = sys::AtomicIncrement(&Counter);
292 --Timestamp;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000293 }
294
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000295 bool isRep() const {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000296 return( (int) NodeRep < 0 );
297 }
298 };
299
300 struct WorkListElement {
301 Node* node;
302 unsigned Timestamp;
303 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
304
305 // Note that we reverse the sense of the comparison because we
306 // actually want to give low timestamps the priority over high,
307 // whereas priority is typically interpreted as a greater value is
308 // given high priority.
309 bool operator<(const WorkListElement& that) const {
310 return( this->Timestamp > that.Timestamp );
311 }
312 };
313
314 // Priority-queue based work list specialized for Nodes.
315 class WorkList {
316 std::priority_queue<WorkListElement> Q;
317
318 public:
319 void insert(Node* n) {
320 Q.push( WorkListElement(n, n->Timestamp) );
321 }
322
323 // We automatically discard non-representative nodes and nodes
324 // that were in the work list twice (we keep a copy of the
325 // timestamp in the work list so we can detect this situation by
326 // comparing against the node's current timestamp).
327 Node* pop() {
328 while( !Q.empty() ) {
329 WorkListElement x = Q.top(); Q.pop();
330 Node* INode = x.node;
331
332 if( INode->isRep() &&
333 INode->Timestamp == x.Timestamp ) {
334 return(x.node);
335 }
336 }
337 return(0);
338 }
339
340 bool empty() {
341 return Q.empty();
342 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000343 };
344
345 /// GraphNodes - This vector is populated as part of the object
346 /// identification stage of the analysis, which populates this vector with a
347 /// node for each memory object and fills in the ValueNodes map.
348 std::vector<Node> GraphNodes;
349
350 /// ValueNodes - This map indicates the Node that a particular Value* is
351 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000352 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000353
354 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000355 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000356 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000357
358 /// ReturnNodes - This map contains an entry for each function in the
359 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000360 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000361
362 /// VarargNodes - This map contains the entry used to represent all pointers
363 /// passed through the varargs portion of a function call for a particular
364 /// function. An entry is not present in this map for functions that do not
365 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000366 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000367
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000368
Chris Lattnere995a2a2004-05-23 21:00:47 +0000369 /// Constraints - This vector contains a list of all of the constraints
370 /// identified by the program.
371 std::vector<Constraint> Constraints;
372
Daniel Berlind81ccc22007-09-24 19:45:49 +0000373 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000374 // this is equivalent to the number of arguments + CallFirstArgPos)
375 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000376
377 /// This enum defines the GraphNodes indices that correspond to important
378 /// fixed sets.
379 enum {
380 UniversalSet = 0,
381 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000382 NullObject = 2,
383 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000384 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000385 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000386 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000387 // Map from Graph Node to DFS number
388 std::vector<unsigned> Node2DFS;
389 // Map from Graph Node to Deleted from graph.
390 std::vector<bool> Node2Deleted;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000391 // Same as Node Maps, but implemented as std::map because it is faster to
392 // clear
393 std::map<unsigned, unsigned> Tarjan2DFS;
394 std::map<unsigned, bool> Tarjan2Deleted;
395 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000396 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000397
398 // Work lists.
399 WorkList w1, w2;
400 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000401
Daniel Berlind81ccc22007-09-24 19:45:49 +0000402 // Offline variable substitution related things
403
404 // Temporary rep storage, used because we can't collapse SCC's in the
405 // predecessor graph by uniting the variables permanently, we can only do so
406 // for the successor graph.
407 std::vector<unsigned> VSSCCRep;
408 // Mapping from node to whether we have visited it during SCC finding yet.
409 std::vector<bool> Node2Visited;
410 // During variable substitution, we create unknowns to represent the unknown
411 // value that is a dereference of a variable. These nodes are known as
412 // "ref" nodes (since they represent the value of dereferences).
413 unsigned FirstRefNode;
414 // During HVN, we create represent address taken nodes as if they were
415 // unknown (since HVN, unlike HU, does not evaluate unions).
416 unsigned FirstAdrNode;
417 // Current pointer equivalence class number
418 unsigned PEClass;
419 // Mapping from points-to sets to equivalence classes
420 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
421 BitVectorMap Set2PEClass;
422 // Mapping from pointer equivalences to the representative node. -1 if we
423 // have no representative node for this pointer equivalence class yet.
424 std::vector<int> PEClass2Node;
425 // Mapping from pointer equivalences to representative node. This includes
426 // pointer equivalent but not location equivalent variables. -1 if we have
427 // no representative node for this pointer equivalence class yet.
428 std::vector<int> PENLEClass2Node;
Daniel Berlinc864edb2008-03-05 19:31:47 +0000429 // Union/Find for HCD
430 std::vector<unsigned> HCDSCCRep;
431 // HCD's offline-detected cycles; "Statically DeTected"
432 // -1 if not part of such a cycle, otherwise a representative node.
433 std::vector<int> SDT;
434 // Whether to use SDT (UniteNodes can use it during solving, but not before)
435 bool SDTActive;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000436
Chris Lattnere995a2a2004-05-23 21:00:47 +0000437 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000438 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000439 Andersens() : ModulePass(&ID) {}
Devang Patel1cee94f2008-03-18 00:39:19 +0000440
Chris Lattnerb12914b2004-09-20 04:48:05 +0000441 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000442 InitializeAliasAnalysis(this);
443 IdentifyObjects(M);
444 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000445#undef DEBUG_TYPE
446#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000447 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000448#undef DEBUG_TYPE
449#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000450 SolveConstraints();
451 DEBUG(PrintPointsToGraph());
452
453 // Free the constraints list, as we don't need it to respond to alias
454 // requests.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000455 std::vector<Constraint>().swap(Constraints);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000456 //These are needed for Print() (-analyze in opt)
457 //ObjectNodes.clear();
458 //ReturnNodes.clear();
459 //VarargNodes.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000460 return false;
461 }
462
463 void releaseMemory() {
464 // FIXME: Until we have transitively required passes working correctly,
465 // this cannot be enabled! Otherwise, using -count-aa with the pass
466 // causes memory to be freed too early. :(
467#if 0
468 // The memory objects and ValueNodes data structures at the only ones that
469 // are still live after construction.
470 std::vector<Node>().swap(GraphNodes);
471 ValueNodes.clear();
472#endif
473 }
474
475 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
476 AliasAnalysis::getAnalysisUsage(AU);
477 AU.setPreservesAll(); // Does not transform code
478 }
479
480 //------------------------------------------------
481 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000482 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000483 AliasResult alias(const Value *V1, unsigned V1Size,
484 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000485 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
486 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000487 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
488 bool pointsToConstantMemory(const Value *P);
489
490 virtual void deleteValue(Value *V) {
491 ValueNodes.erase(V);
492 getAnalysis<AliasAnalysis>().deleteValue(V);
493 }
494
495 virtual void copyValue(Value *From, Value *To) {
496 ValueNodes[To] = ValueNodes[From];
497 getAnalysis<AliasAnalysis>().copyValue(From, To);
498 }
499
500 private:
501 /// getNode - Return the node corresponding to the specified pointer scalar.
502 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000503 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000504 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000505 if (!isa<GlobalValue>(C))
506 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000507
Daniel Berlind81ccc22007-09-24 19:45:49 +0000508 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000509 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000510#ifndef NDEBUG
511 V->dump();
512#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000513 llvm_unreachable("Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000514 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000515 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000516 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000517
Chris Lattnere995a2a2004-05-23 21:00:47 +0000518 /// getObject - Return the node corresponding to the memory object for the
519 /// specified global or allocation instruction.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000520 unsigned getObject(Value *V) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000521 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000522 assert(I != ObjectNodes.end() &&
523 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000524 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000525 }
526
527 /// getReturnNode - Return the node representing the return value for the
528 /// specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000529 unsigned getReturnNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000530 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000531 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000532 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000533 }
534
535 /// getVarargNode - Return the node representing the variable arguments
536 /// formal for the specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000537 unsigned getVarargNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000538 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000539 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000540 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000541 }
542
543 /// getNodeValue - Get the node for the specified LLVM value and set the
544 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000545 unsigned getNodeValue(Value &V) {
546 unsigned Index = getNode(&V);
547 GraphNodes[Index].setValue(&V);
548 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000549 }
550
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000551 unsigned UniteNodes(unsigned First, unsigned Second,
552 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000553 unsigned FindNode(unsigned Node);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000554 unsigned FindNode(unsigned Node) const;
Daniel Berlinaad15882007-09-16 21:45:02 +0000555
Chris Lattnere995a2a2004-05-23 21:00:47 +0000556 void IdentifyObjects(Module &M);
557 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000558 bool AnalyzeUsesOfFunction(Value *);
559 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000560 void OptimizeConstraints();
561 unsigned FindEquivalentNode(unsigned, unsigned);
562 void ClumpAddressTaken();
563 void RewriteConstraints();
564 void HU();
565 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000566 void HCD();
567 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000568 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000569 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000570 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000571 void Condense(unsigned Node);
572 void HUValNum(unsigned Node);
573 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000574 unsigned getNodeForConstantPointer(Constant *C);
575 unsigned getNodeForConstantPointerTarget(Constant *C);
576 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000577
Chris Lattnere995a2a2004-05-23 21:00:47 +0000578 void AddConstraintsForNonInternalLinkage(Function *F);
579 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000580 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000581
582
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000583 void PrintNode(const Node *N) const;
584 void PrintConstraints() const ;
585 void PrintConstraint(const Constraint &) const;
586 void PrintLabels() const;
587 void PrintPointsToGraph() const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000588
589 //===------------------------------------------------------------------===//
590 // Instruction visitation methods for adding constraints
591 //
592 friend class InstVisitor<Andersens>;
593 void visitReturnInst(ReturnInst &RI);
594 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
595 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
596 void visitCallSite(CallSite CS);
597 void visitAllocationInst(AllocationInst &AI);
598 void visitLoadInst(LoadInst &LI);
599 void visitStoreInst(StoreInst &SI);
600 void visitGetElementPtrInst(GetElementPtrInst &GEP);
601 void visitPHINode(PHINode &PN);
602 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000603 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
604 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000605 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000606 void visitVAArg(VAArgInst &I);
607 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000608
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000609 //===------------------------------------------------------------------===//
610 // Implement Analyize interface
611 //
Chris Lattner45cfe542009-08-23 06:03:38 +0000612 void print(raw_ostream &O, const Module*) const {
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000613 PrintPointsToGraph();
614 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000615 };
Chris Lattnere995a2a2004-05-23 21:00:47 +0000616}
617
Dan Gohman844731a2008-05-13 00:00:25 +0000618char Andersens::ID = 0;
619static RegisterPass<Andersens>
620X("anders-aa", "Andersen's Interprocedural Alias Analysis", false, true);
621static RegisterAnalysisGroup<AliasAnalysis> Y(X);
622
623// Initialize Timestamp Counter (static).
Owen Anderson5ec56cc2009-06-30 05:33:46 +0000624volatile llvm::sys::cas_flag Andersens::Node::Counter = 0;
Dan Gohman844731a2008-05-13 00:00:25 +0000625
Jeff Cohen534927d2005-01-08 22:01:16 +0000626ModulePass *llvm::createAndersensPass() { return new Andersens(); }
627
Chris Lattnere995a2a2004-05-23 21:00:47 +0000628//===----------------------------------------------------------------------===//
629// AliasAnalysis Interface Implementation
630//===----------------------------------------------------------------------===//
631
632AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
633 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000634 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
635 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000636
637 // Check to see if the two pointers are known to not alias. They don't alias
638 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000639 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000640 return NoAlias;
641
642 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
643}
644
Chris Lattnerf392c642005-03-28 06:21:17 +0000645AliasAnalysis::ModRefResult
646Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
647 // The only thing useful that we can contribute for mod/ref information is
648 // when calling external function calls: if we know that memory never escapes
649 // from the program, it cannot be modified by an external call.
650 //
651 // NOTE: This is not really safe, at least not when the entire program is not
652 // available. The deal is that the external function could call back into the
653 // program and modify stuff. We ignore this technical niggle for now. This
654 // is, after all, a "research quality" implementation of Andersen's analysis.
655 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000656 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000657 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000658
Daniel Berlinaad15882007-09-16 21:45:02 +0000659 if (N1->PointsTo->empty())
660 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000661#if FULL_UNIVERSAL
662 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
663 return NoModRef; // Universal set does not contain P
664#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000665 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000666 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000667#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000668 }
669
670 return AliasAnalysis::getModRefInfo(CS, P, Size);
671}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000672
Reid Spencer3a9ec242006-08-28 01:02:49 +0000673AliasAnalysis::ModRefResult
674Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
675 return AliasAnalysis::getModRefInfo(CS1,CS2);
676}
677
Chris Lattnere995a2a2004-05-23 21:00:47 +0000678/// getMustAlias - We can provide must alias information if we know that a
679/// pointer can only point to a specific function or the null pointer.
680/// Unfortunately we cannot determine must-alias information for global
681/// variables or any other memory memory objects because we do not track whether
682/// a pointer points to the beginning of an object or a field of it.
683void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000684 Node *N = &GraphNodes[FindNode(getNode(P))];
685 if (N->PointsTo->count() == 1) {
686 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
687 // If a function is the only object in the points-to set, then it must be
688 // the destination. Note that we can't handle global variables here,
689 // because we don't know if the pointer is actually pointing to a field of
690 // the global or to the beginning of it.
691 if (Value *V = Pointee->getValue()) {
692 if (Function *F = dyn_cast<Function>(V))
693 RetVals.push_back(F);
694 } else {
695 // If the object in the points-to set is the null object, then the null
696 // pointer is a must alias.
697 if (Pointee == &GraphNodes[NullObject])
Owen Andersona7235ea2009-07-31 20:28:14 +0000698 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000699 }
700 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000701 AliasAnalysis::getMustAliases(P, RetVals);
702}
703
704/// pointsToConstantMemory - If we can determine that this pointer only points
705/// to constant memory, return true. In practice, this means that if the
706/// pointer can only point to constant globals, functions, or the null pointer,
707/// return true.
708///
709bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000710 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000711 unsigned i;
712
713 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
714 bi != N->PointsTo->end();
715 ++bi) {
716 i = *bi;
717 Node *Pointee = &GraphNodes[i];
718 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000719 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
720 !cast<GlobalVariable>(V)->isConstant()))
721 return AliasAnalysis::pointsToConstantMemory(P);
722 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000723 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000724 return AliasAnalysis::pointsToConstantMemory(P);
725 }
726 }
727
728 return true;
729}
730
731//===----------------------------------------------------------------------===//
732// Object Identification Phase
733//===----------------------------------------------------------------------===//
734
735/// IdentifyObjects - This stage scans the program, adding an entry to the
736/// GraphNodes list for each memory object in the program (global stack or
737/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
738///
739void Andersens::IdentifyObjects(Module &M) {
740 unsigned NumObjects = 0;
741
742 // Object #0 is always the universal set: the object that we don't know
743 // anything about.
744 assert(NumObjects == UniversalSet && "Something changed!");
745 ++NumObjects;
746
747 // Object #1 always represents the null pointer.
748 assert(NumObjects == NullPtr && "Something changed!");
749 ++NumObjects;
750
751 // Object #2 always represents the null object (the object pointed to by null)
752 assert(NumObjects == NullObject && "Something changed!");
753 ++NumObjects;
754
755 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000756 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
757 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000758 ObjectNodes[I] = NumObjects++;
759 ValueNodes[I] = NumObjects++;
760 }
761
762 // Add nodes for all of the functions and the instructions inside of them.
763 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
764 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000765 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000766 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000767 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
768 ReturnNodes[F] = NumObjects++;
769 if (F->getFunctionType()->isVarArg())
770 VarargNodes[F] = NumObjects++;
771
Daniel Berlinaad15882007-09-16 21:45:02 +0000772
Chris Lattnere995a2a2004-05-23 21:00:47 +0000773 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000774 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
775 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000776 {
777 if (isa<PointerType>(I->getType()))
778 ValueNodes[I] = NumObjects++;
779 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000780 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000781
782 // Scan the function body, creating a memory object for each heap/stack
783 // allocation in the body of the function and a node to represent all
784 // pointer values defined by instructions and used as operands.
785 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
786 // If this is an heap or stack allocation, create a node for the memory
787 // object.
788 if (isa<PointerType>(II->getType())) {
789 ValueNodes[&*II] = NumObjects++;
790 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
791 ObjectNodes[AI] = NumObjects++;
792 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000793
794 // Calls to inline asm need to be added as well because the callee isn't
795 // referenced anywhere else.
796 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
797 Value *Callee = CI->getCalledValue();
798 if (isa<InlineAsm>(Callee))
799 ValueNodes[Callee] = NumObjects++;
800 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000801 }
802 }
803
804 // Now that we know how many objects to create, make them all now!
805 GraphNodes.resize(NumObjects);
806 NumNodes += NumObjects;
807}
808
809//===----------------------------------------------------------------------===//
810// Constraint Identification Phase
811//===----------------------------------------------------------------------===//
812
813/// getNodeForConstantPointer - Return the node corresponding to the constant
814/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000815unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000816 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
817
Chris Lattner267a1b02005-03-27 18:58:23 +0000818 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000819 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000820 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
821 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000822 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
823 switch (CE->getOpcode()) {
824 case Instruction::GetElementPtr:
825 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000826 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000827 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000828 case Instruction::BitCast:
829 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000830 default:
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000831 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000832 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000833 }
834 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000835 llvm_unreachable("Unknown constant pointer!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000836 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000837 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000838}
839
840/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
841/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000842unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000843 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
844
845 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000846 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000847 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
848 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000849 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
850 switch (CE->getOpcode()) {
851 case Instruction::GetElementPtr:
852 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000853 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000854 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000855 case Instruction::BitCast:
856 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000857 default:
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000858 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000859 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000860 }
861 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000862 llvm_unreachable("Unknown constant pointer!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000863 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000864 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000865}
866
867/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
868/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000869void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
870 Constant *C) {
Dan Gohmanb64aa112008-05-22 23:43:22 +0000871 if (C->getType()->isSingleValueType()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000872 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000873 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
874 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000875 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000876 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
877 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000878 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000879 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000880 // If this is an array or struct, include constraints for each element.
881 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
882 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000883 AddGlobalInitializerConstraints(NodeIndex,
884 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000885 }
886}
887
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000888/// AddConstraintsForNonInternalLinkage - If this function does not have
889/// internal linkage, realize that we can't trust anything passed into or
890/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000891void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000892 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000893 if (isa<PointerType>(I->getType()))
894 // If this is an argument of an externally accessible function, the
895 // incoming pointer might point to anything.
896 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000897 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000898}
899
Chris Lattner8a446432005-03-29 06:09:07 +0000900/// AddConstraintsForCall - If this is a call to a "known" function, add the
901/// constraints and return true. If this is a call to an unknown function,
902/// return false.
903bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000904 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000905
906 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000907 if (F->getName() == "atoi" || F->getName() == "atof" ||
908 F->getName() == "atol" || F->getName() == "atoll" ||
909 F->getName() == "remove" || F->getName() == "unlink" ||
910 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner824b9582008-11-21 16:42:48 +0000911 F->getName() == "llvm.memset" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000912 F->getName() == "strcmp" || F->getName() == "strncmp" ||
913 F->getName() == "execl" || F->getName() == "execlp" ||
914 F->getName() == "execle" || F->getName() == "execv" ||
915 F->getName() == "execvp" || F->getName() == "chmod" ||
916 F->getName() == "puts" || F->getName() == "write" ||
917 F->getName() == "open" || F->getName() == "create" ||
918 F->getName() == "truncate" || F->getName() == "chdir" ||
919 F->getName() == "mkdir" || F->getName() == "rmdir" ||
920 F->getName() == "read" || F->getName() == "pipe" ||
921 F->getName() == "wait" || F->getName() == "time" ||
922 F->getName() == "stat" || F->getName() == "fstat" ||
923 F->getName() == "lstat" || F->getName() == "strtod" ||
924 F->getName() == "strtof" || F->getName() == "strtold" ||
925 F->getName() == "fopen" || F->getName() == "fdopen" ||
926 F->getName() == "freopen" ||
927 F->getName() == "fflush" || F->getName() == "feof" ||
928 F->getName() == "fileno" || F->getName() == "clearerr" ||
929 F->getName() == "rewind" || F->getName() == "ftell" ||
930 F->getName() == "ferror" || F->getName() == "fgetc" ||
931 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
932 F->getName() == "fwrite" || F->getName() == "fread" ||
933 F->getName() == "fgets" || F->getName() == "ungetc" ||
934 F->getName() == "fputc" ||
935 F->getName() == "fputs" || F->getName() == "putc" ||
936 F->getName() == "ftell" || F->getName() == "rewind" ||
937 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
938 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
939 F->getName() == "printf" || F->getName() == "fprintf" ||
940 F->getName() == "sprintf" || F->getName() == "vprintf" ||
941 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
942 F->getName() == "scanf" || F->getName() == "fscanf" ||
943 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
944 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000945 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000946
Chris Lattner175b9632005-03-29 20:36:05 +0000947
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000948 // These functions do induce points-to edges.
Chris Lattner824b9582008-11-21 16:42:48 +0000949 if (F->getName() == "llvm.memcpy" ||
950 F->getName() == "llvm.memmove" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000951 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000952
Nick Lewycky3037eda2008-12-27 16:20:53 +0000953 const FunctionType *FTy = F->getFunctionType();
954 if (FTy->getNumParams() > 1 &&
955 isa<PointerType>(FTy->getParamType(0)) &&
956 isa<PointerType>(FTy->getParamType(1))) {
957
958 // *Dest = *Src, which requires an artificial graph node to represent the
959 // constraint. It is broken up into *Dest = temp, temp = *Src
960 unsigned FirstArg = getNode(CS.getArgument(0));
961 unsigned SecondArg = getNode(CS.getArgument(1));
962 unsigned TempArg = GraphNodes.size();
963 GraphNodes.push_back(Node());
964 Constraints.push_back(Constraint(Constraint::Store,
965 FirstArg, TempArg));
966 Constraints.push_back(Constraint(Constraint::Load,
967 TempArg, SecondArg));
968 // In addition, Dest = Src
969 Constraints.push_back(Constraint(Constraint::Copy,
970 FirstArg, SecondArg));
971 return true;
972 }
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000973 }
974
Chris Lattner77b50562005-03-29 20:04:24 +0000975 // Result = Arg0
976 if (F->getName() == "realloc" || F->getName() == "strchr" ||
977 F->getName() == "strrchr" || F->getName() == "strstr" ||
978 F->getName() == "strtok") {
Nick Lewycky3037eda2008-12-27 16:20:53 +0000979 const FunctionType *FTy = F->getFunctionType();
980 if (FTy->getNumParams() > 0 &&
981 isa<PointerType>(FTy->getParamType(0))) {
982 Constraints.push_back(Constraint(Constraint::Copy,
983 getNode(CS.getInstruction()),
984 getNode(CS.getArgument(0))));
985 return true;
986 }
Chris Lattner8a446432005-03-29 06:09:07 +0000987 }
988
989 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000990}
991
992
Chris Lattnere995a2a2004-05-23 21:00:47 +0000993
Daniel Berlinaad15882007-09-16 21:45:02 +0000994/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
995/// If this is used by anything complex (i.e., the address escapes), return
996/// true.
997bool Andersens::AnalyzeUsesOfFunction(Value *V) {
998
999 if (!isa<PointerType>(V->getType())) return true;
1000
1001 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Dan Gohman104eac12009-08-11 17:20:16 +00001002 if (isa<LoadInst>(*UI)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001003 return false;
1004 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1005 if (V == SI->getOperand(1)) {
1006 return false;
1007 } else if (SI->getOperand(1)) {
1008 return true; // Storing the pointer
1009 }
1010 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1011 if (AnalyzeUsesOfFunction(GEP)) return true;
1012 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1013 // Make sure that this is just the function being called, not that it is
1014 // passing into the function.
1015 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1016 if (CI->getOperand(i) == V) return true;
1017 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1018 // Make sure that this is just the function being called, not that it is
1019 // passing into the function.
Bill Wendling9a507cd2009-03-13 21:15:59 +00001020 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +00001021 if (II->getOperand(i) == V) return true;
1022 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1023 if (CE->getOpcode() == Instruction::GetElementPtr ||
1024 CE->getOpcode() == Instruction::BitCast) {
1025 if (AnalyzeUsesOfFunction(CE))
1026 return true;
1027 } else {
1028 return true;
1029 }
1030 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1031 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1032 return true; // Allow comparison against null.
Dan Gohman104eac12009-08-11 17:20:16 +00001033 } else if (isa<FreeInst>(*UI)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001034 return false;
1035 } else {
1036 return true;
1037 }
1038 return false;
1039}
1040
Chris Lattnere995a2a2004-05-23 21:00:47 +00001041/// CollectConstraints - This stage scans the program, adding a constraint to
1042/// the Constraints list for each instruction in the program that induces a
1043/// constraint, and setting up the initial points-to graph.
1044///
1045void Andersens::CollectConstraints(Module &M) {
1046 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001047 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1048 UniversalSet));
1049 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1050 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001051
1052 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001053 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001054
1055 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001056 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1057 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001058 // Associate the address of the global object as pointing to the memory for
1059 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001060 unsigned ObjectIndex = getObject(I);
1061 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001062 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001063 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1064 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001065
Dan Gohman82555732009-08-19 18:20:44 +00001066 if (I->hasDefinitiveInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001067 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001068 } else {
1069 // If it doesn't have an initializer (i.e. it's defined in another
1070 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001071 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1072 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001073 }
1074 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001075
Chris Lattnere995a2a2004-05-23 21:00:47 +00001076 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001077 // Set up the return value node.
1078 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001079 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001080 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001081 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001082
1083 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001084 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1085 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001086 if (isa<PointerType>(I->getType()))
1087 getNodeValue(*I);
1088
Daniel Berlinaad15882007-09-16 21:45:02 +00001089 // At some point we should just add constraints for the escaping functions
1090 // at solve time, but this slows down solving. For now, we simply mark
1091 // address taken functions as escaping and treat them as external.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001092 if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001093 AddConstraintsForNonInternalLinkage(F);
1094
Reid Spencer5cbf9852007-01-30 20:08:39 +00001095 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001096 // Scan the function body, creating a memory object for each heap/stack
1097 // allocation in the body of the function and a node to represent all
1098 // pointer values defined by instructions and used as operands.
1099 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001100 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001101 // External functions that return pointers return the universal set.
1102 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1103 Constraints.push_back(Constraint(Constraint::Copy,
1104 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001105 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001106
1107 // Any pointers that are passed into the function have the universal set
1108 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001109 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1110 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001111 if (isa<PointerType>(I->getType())) {
1112 // Pointers passed into external functions could have anything stored
1113 // through them.
1114 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001115 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001116 // Memory objects passed into external function calls can have the
1117 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001118#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001119 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001120 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001121 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001122#else
1123 Constraints.push_back(Constraint(Constraint::Copy,
1124 getNode(I),
1125 UniversalSet));
1126#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001127 }
1128
1129 // If this is an external varargs function, it can also store pointers
1130 // into any pointers passed through the varargs section.
1131 if (F->getFunctionType()->isVarArg())
1132 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001133 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001134 }
1135 }
1136 NumConstraints += Constraints.size();
1137}
1138
1139
1140void Andersens::visitInstruction(Instruction &I) {
1141#ifdef NDEBUG
1142 return; // This function is just a big assert.
1143#endif
1144 if (isa<BinaryOperator>(I))
1145 return;
1146 // Most instructions don't have any effect on pointer values.
1147 switch (I.getOpcode()) {
1148 case Instruction::Br:
1149 case Instruction::Switch:
1150 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001151 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001152 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001153 case Instruction::ICmp:
1154 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001155 return;
1156 default:
1157 // Is this something we aren't handling yet?
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00001158 errs() << "Unknown instruction: " << I;
Torok Edwinc23197a2009-07-14 16:55:14 +00001159 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001160 }
1161}
1162
1163void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001164 unsigned ObjectIndex = getObject(&AI);
1165 GraphNodes[ObjectIndex].setValue(&AI);
1166 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1167 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001168}
1169
1170void Andersens::visitReturnInst(ReturnInst &RI) {
1171 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1172 // return V --> <Copy/retval{F}/v>
1173 Constraints.push_back(Constraint(Constraint::Copy,
1174 getReturnNode(RI.getParent()->getParent()),
1175 getNode(RI.getOperand(0))));
1176}
1177
1178void Andersens::visitLoadInst(LoadInst &LI) {
1179 if (isa<PointerType>(LI.getType()))
1180 // P1 = load P2 --> <Load/P1/P2>
1181 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1182 getNode(LI.getOperand(0))));
1183}
1184
1185void Andersens::visitStoreInst(StoreInst &SI) {
1186 if (isa<PointerType>(SI.getOperand(0)->getType()))
1187 // store P1, P2 --> <Store/P2/P1>
1188 Constraints.push_back(Constraint(Constraint::Store,
1189 getNode(SI.getOperand(1)),
1190 getNode(SI.getOperand(0))));
1191}
1192
1193void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1194 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1195 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1196 getNode(GEP.getOperand(0))));
1197}
1198
1199void Andersens::visitPHINode(PHINode &PN) {
1200 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001201 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001202 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1203 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1204 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1205 getNode(PN.getIncomingValue(i))));
1206 }
1207}
1208
1209void Andersens::visitCastInst(CastInst &CI) {
1210 Value *Op = CI.getOperand(0);
1211 if (isa<PointerType>(CI.getType())) {
1212 if (isa<PointerType>(Op->getType())) {
1213 // P1 = cast P2 --> <Copy/P1/P2>
1214 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1215 getNode(CI.getOperand(0))));
1216 } else {
1217 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001218#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001219 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001220 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001221#else
1222 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001223#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001224 }
1225 } else if (isa<PointerType>(Op->getType())) {
1226 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001227#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001228 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001229 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001230 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001231#else
1232 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001233#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001234 }
1235}
1236
1237void Andersens::visitSelectInst(SelectInst &SI) {
1238 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001239 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001240 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1241 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1242 getNode(SI.getOperand(1))));
1243 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1244 getNode(SI.getOperand(2))));
1245 }
1246}
1247
Chris Lattnere995a2a2004-05-23 21:00:47 +00001248void Andersens::visitVAArg(VAArgInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001249 llvm_unreachable("vaarg not handled yet!");
Chris Lattnere995a2a2004-05-23 21:00:47 +00001250}
1251
1252/// AddConstraintsForCall - Add constraints for a call with actual arguments
1253/// specified by CS to the function specified by F. Note that the types of
1254/// arguments might not match up in the case where this is an indirect call and
1255/// the function pointer has been casted. If this is the case, do something
1256/// reasonable.
1257void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001258 Value *CallValue = CS.getCalledValue();
1259 bool IsDeref = F == NULL;
1260
1261 // If this is a call to an external function, try to handle it directly to get
1262 // some taste of context sensitivity.
1263 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001264 return;
1265
Chris Lattnere995a2a2004-05-23 21:00:47 +00001266 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001267 unsigned CSN = getNode(CS.getInstruction());
1268 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1269 if (IsDeref)
1270 Constraints.push_back(Constraint(Constraint::Load, CSN,
1271 getNode(CallValue), CallReturnPos));
1272 else
1273 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1274 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001275 } else {
1276 // If the function returns a non-pointer value, handle this just like we
1277 // treat a nonpointer cast to pointer.
1278 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001279 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001280 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001281 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001282#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001283 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001284 UniversalSet,
1285 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001286#else
1287 Constraints.push_back(Constraint(Constraint::Copy,
1288 getNode(CallValue) + CallReturnPos,
1289 UniversalSet));
1290#endif
1291
1292
Chris Lattnere995a2a2004-05-23 21:00:47 +00001293 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001294
Chris Lattnere995a2a2004-05-23 21:00:47 +00001295 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001296 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001297 if (F) {
1298 // Direct Call
1299 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001300 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1301 {
1302#if !FULL_UNIVERSAL
1303 if (external && isa<PointerType>((*ArgI)->getType()))
1304 {
1305 // Add constraint that ArgI can now point to anything due to
1306 // escaping, as can everything it points to. The second portion of
1307 // this should be taken care of by universal = *universal
1308 Constraints.push_back(Constraint(Constraint::Copy,
1309 getNode(*ArgI),
1310 UniversalSet));
1311 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001312#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001313 if (isa<PointerType>(AI->getType())) {
1314 if (isa<PointerType>((*ArgI)->getType())) {
1315 // Copy the actual argument into the formal argument.
1316 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1317 getNode(*ArgI)));
1318 } else {
1319 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1320 UniversalSet));
1321 }
1322 } else if (isa<PointerType>((*ArgI)->getType())) {
1323#if FULL_UNIVERSAL
1324 Constraints.push_back(Constraint(Constraint::Copy,
1325 UniversalSet,
1326 getNode(*ArgI)));
1327#else
1328 Constraints.push_back(Constraint(Constraint::Copy,
1329 getNode(*ArgI),
1330 UniversalSet));
1331#endif
1332 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001333 }
1334 } else {
1335 //Indirect Call
1336 unsigned ArgPos = CallFirstArgPos;
1337 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001338 if (isa<PointerType>((*ArgI)->getType())) {
1339 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001340 Constraints.push_back(Constraint(Constraint::Store,
1341 getNode(CallValue),
1342 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001343 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001344 Constraints.push_back(Constraint(Constraint::Store,
1345 getNode (CallValue),
1346 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001347 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001348 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001349 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001350 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001351 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001352 for (; ArgI != ArgE; ++ArgI)
1353 if (isa<PointerType>((*ArgI)->getType()))
1354 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1355 getNode(*ArgI)));
1356 // If more arguments are passed in than we track, just drop them on the floor.
1357}
1358
1359void Andersens::visitCallSite(CallSite CS) {
1360 if (isa<PointerType>(CS.getType()))
1361 getNodeValue(*CS.getInstruction());
1362
1363 if (Function *F = CS.getCalledFunction()) {
1364 AddConstraintsForCall(CS, F);
1365 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001366 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001367 }
1368}
1369
1370//===----------------------------------------------------------------------===//
1371// Constraint Solving Phase
1372//===----------------------------------------------------------------------===//
1373
1374/// intersects - Return true if the points-to set of this node intersects
1375/// with the points-to set of the specified node.
1376bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001377 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001378}
1379
1380/// intersectsIgnoring - Return true if the points-to set of this node
1381/// intersects with the points-to set of the specified node on any nodes
1382/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001383bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1384 // TODO: If we are only going to call this with the same value for Ignoring,
1385 // we should move the special values out of the points-to bitmap.
1386 bool WeHadIt = PointsTo->test(Ignoring);
1387 bool NHadIt = N->PointsTo->test(Ignoring);
1388 bool Result = false;
1389 if (WeHadIt)
1390 PointsTo->reset(Ignoring);
1391 if (NHadIt)
1392 N->PointsTo->reset(Ignoring);
1393 Result = PointsTo->intersects(N->PointsTo);
1394 if (WeHadIt)
1395 PointsTo->set(Ignoring);
1396 if (NHadIt)
1397 N->PointsTo->set(Ignoring);
1398 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001399}
1400
Daniel Berlind81ccc22007-09-24 19:45:49 +00001401
1402/// Clump together address taken variables so that the points-to sets use up
1403/// less space and can be operated on faster.
1404
1405void Andersens::ClumpAddressTaken() {
1406#undef DEBUG_TYPE
1407#define DEBUG_TYPE "anders-aa-renumber"
1408 std::vector<unsigned> Translate;
1409 std::vector<Node> NewGraphNodes;
1410
1411 Translate.resize(GraphNodes.size());
1412 unsigned NewPos = 0;
1413
1414 for (unsigned i = 0; i < Constraints.size(); ++i) {
1415 Constraint &C = Constraints[i];
1416 if (C.Type == Constraint::AddressOf) {
1417 GraphNodes[C.Src].AddressTaken = true;
1418 }
1419 }
1420 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1421 unsigned Pos = NewPos++;
1422 Translate[i] = Pos;
1423 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001424 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001425 }
1426
1427 // I believe this ends up being faster than making two vectors and splicing
1428 // them.
1429 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1430 if (GraphNodes[i].AddressTaken) {
1431 unsigned Pos = NewPos++;
1432 Translate[i] = Pos;
1433 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001434 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001435 }
1436 }
1437
1438 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1439 if (!GraphNodes[i].AddressTaken) {
1440 unsigned Pos = NewPos++;
1441 Translate[i] = Pos;
1442 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001443 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001444 }
1445 }
1446
1447 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1448 Iter != ValueNodes.end();
1449 ++Iter)
1450 Iter->second = Translate[Iter->second];
1451
1452 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1453 Iter != ObjectNodes.end();
1454 ++Iter)
1455 Iter->second = Translate[Iter->second];
1456
1457 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1458 Iter != ReturnNodes.end();
1459 ++Iter)
1460 Iter->second = Translate[Iter->second];
1461
1462 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1463 Iter != VarargNodes.end();
1464 ++Iter)
1465 Iter->second = Translate[Iter->second];
1466
1467 for (unsigned i = 0; i < Constraints.size(); ++i) {
1468 Constraint &C = Constraints[i];
1469 C.Src = Translate[C.Src];
1470 C.Dest = Translate[C.Dest];
1471 }
1472
1473 GraphNodes.swap(NewGraphNodes);
1474#undef DEBUG_TYPE
1475#define DEBUG_TYPE "anders-aa"
1476}
1477
1478/// The technique used here is described in "Exploiting Pointer and Location
1479/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1480/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1481/// and is equivalent to value numbering the collapsed constraint graph without
1482/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1483/// first order pointer dereferences and speed up/reduce memory usage of HU.
1484/// Running both is equivalent to HRU without the iteration
1485/// HVN in more detail:
1486/// Imagine the set of constraints was simply straight line code with no loops
1487/// (we eliminate cycles, so there are no loops), such as:
1488/// E = &D
1489/// E = &C
1490/// E = F
1491/// F = G
1492/// G = F
1493/// Applying value numbering to this code tells us:
1494/// G == F == E
1495///
1496/// For HVN, this is as far as it goes. We assign new value numbers to every
1497/// "address node", and every "reference node".
1498/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1499/// cycle must have the same value number since the = operation is really
1500/// inclusion, not overwrite), and value number nodes we receive points-to sets
1501/// before we value our own node.
1502/// The advantage of HU over HVN is that HU considers the inclusion property, so
1503/// that if you have
1504/// E = &D
1505/// E = &C
1506/// E = F
1507/// F = G
1508/// F = &D
1509/// G = F
1510/// HU will determine that G == F == E. HVN will not, because it cannot prove
1511/// that the points to information ends up being the same because they all
1512/// receive &D from E anyway.
1513
1514void Andersens::HVN() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001515 DEBUG(errs() << "Beginning HVN\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001516 // Build a predecessor graph. This is like our constraint graph with the
1517 // edges going in the opposite direction, and there are edges for all the
1518 // constraints, instead of just copy constraints. We also build implicit
1519 // edges for constraints are implied but not explicit. I.E for the constraint
1520 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1521 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1522 Constraint &C = Constraints[i];
1523 if (C.Type == Constraint::AddressOf) {
1524 GraphNodes[C.Src].AddressTaken = true;
1525 GraphNodes[C.Src].Direct = false;
1526
1527 // Dest = &src edge
1528 unsigned AdrNode = C.Src + FirstAdrNode;
1529 if (!GraphNodes[C.Dest].PredEdges)
1530 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1531 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1532
1533 // *Dest = src edge
1534 unsigned RefNode = C.Dest + FirstRefNode;
1535 if (!GraphNodes[RefNode].ImplicitPredEdges)
1536 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1537 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1538 } else if (C.Type == Constraint::Load) {
1539 if (C.Offset == 0) {
1540 // dest = *src edge
1541 if (!GraphNodes[C.Dest].PredEdges)
1542 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1543 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1544 } else {
1545 GraphNodes[C.Dest].Direct = false;
1546 }
1547 } else if (C.Type == Constraint::Store) {
1548 if (C.Offset == 0) {
1549 // *dest = src edge
1550 unsigned RefNode = C.Dest + FirstRefNode;
1551 if (!GraphNodes[RefNode].PredEdges)
1552 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1553 GraphNodes[RefNode].PredEdges->set(C.Src);
1554 }
1555 } else {
1556 // Dest = Src edge and *Dest = *Src edge
1557 if (!GraphNodes[C.Dest].PredEdges)
1558 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1559 GraphNodes[C.Dest].PredEdges->set(C.Src);
1560 unsigned RefNode = C.Dest + FirstRefNode;
1561 if (!GraphNodes[RefNode].ImplicitPredEdges)
1562 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1563 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1564 }
1565 }
1566 PEClass = 1;
1567 // Do SCC finding first to condense our predecessor graph
1568 DFSNumber = 0;
1569 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1570 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1571 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1572
1573 for (unsigned i = 0; i < FirstRefNode; ++i) {
1574 unsigned Node = VSSCCRep[i];
1575 if (!Node2Visited[Node])
1576 HVNValNum(Node);
1577 }
1578 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1579 Iter != Set2PEClass.end();
1580 ++Iter)
1581 delete Iter->first;
1582 Set2PEClass.clear();
1583 Node2DFS.clear();
1584 Node2Deleted.clear();
1585 Node2Visited.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001586 DEBUG(errs() << "Finished HVN\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001587
1588}
1589
1590/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1591/// same time because it's easy.
1592void Andersens::HVNValNum(unsigned NodeIndex) {
1593 unsigned MyDFS = DFSNumber++;
1594 Node *N = &GraphNodes[NodeIndex];
1595 Node2Visited[NodeIndex] = true;
1596 Node2DFS[NodeIndex] = MyDFS;
1597
1598 // First process all our explicit edges
1599 if (N->PredEdges)
1600 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1601 Iter != N->PredEdges->end();
1602 ++Iter) {
1603 unsigned j = VSSCCRep[*Iter];
1604 if (!Node2Deleted[j]) {
1605 if (!Node2Visited[j])
1606 HVNValNum(j);
1607 if (Node2DFS[NodeIndex] > Node2DFS[j])
1608 Node2DFS[NodeIndex] = Node2DFS[j];
1609 }
1610 }
1611
1612 // Now process all the implicit edges
1613 if (N->ImplicitPredEdges)
1614 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1615 Iter != N->ImplicitPredEdges->end();
1616 ++Iter) {
1617 unsigned j = VSSCCRep[*Iter];
1618 if (!Node2Deleted[j]) {
1619 if (!Node2Visited[j])
1620 HVNValNum(j);
1621 if (Node2DFS[NodeIndex] > Node2DFS[j])
1622 Node2DFS[NodeIndex] = Node2DFS[j];
1623 }
1624 }
1625
1626 // See if we found any cycles
1627 if (MyDFS == Node2DFS[NodeIndex]) {
1628 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1629 unsigned CycleNodeIndex = SCCStack.top();
1630 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1631 VSSCCRep[CycleNodeIndex] = NodeIndex;
1632 // Unify the nodes
1633 N->Direct &= CycleNode->Direct;
1634
1635 if (CycleNode->PredEdges) {
1636 if (!N->PredEdges)
1637 N->PredEdges = new SparseBitVector<>;
1638 *(N->PredEdges) |= CycleNode->PredEdges;
1639 delete CycleNode->PredEdges;
1640 CycleNode->PredEdges = NULL;
1641 }
1642 if (CycleNode->ImplicitPredEdges) {
1643 if (!N->ImplicitPredEdges)
1644 N->ImplicitPredEdges = new SparseBitVector<>;
1645 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1646 delete CycleNode->ImplicitPredEdges;
1647 CycleNode->ImplicitPredEdges = NULL;
1648 }
1649
1650 SCCStack.pop();
1651 }
1652
1653 Node2Deleted[NodeIndex] = true;
1654
1655 if (!N->Direct) {
1656 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1657 return;
1658 }
1659
1660 // Collect labels of successor nodes
1661 bool AllSame = true;
1662 unsigned First = ~0;
1663 SparseBitVector<> *Labels = new SparseBitVector<>;
1664 bool Used = false;
1665
1666 if (N->PredEdges)
1667 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1668 Iter != N->PredEdges->end();
1669 ++Iter) {
1670 unsigned j = VSSCCRep[*Iter];
1671 unsigned Label = GraphNodes[j].PointerEquivLabel;
1672 // Ignore labels that are equal to us or non-pointers
1673 if (j == NodeIndex || Label == 0)
1674 continue;
1675 if (First == (unsigned)~0)
1676 First = Label;
1677 else if (First != Label)
1678 AllSame = false;
1679 Labels->set(Label);
1680 }
1681
1682 // We either have a non-pointer, a copy of an existing node, or a new node.
1683 // Assign the appropriate pointer equivalence label.
1684 if (Labels->empty()) {
1685 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1686 } else if (AllSame) {
1687 GraphNodes[NodeIndex].PointerEquivLabel = First;
1688 } else {
1689 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1690 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1691 unsigned EquivClass = PEClass++;
1692 Set2PEClass[Labels] = EquivClass;
1693 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1694 Used = true;
1695 }
1696 }
1697 if (!Used)
1698 delete Labels;
1699 } else {
1700 SCCStack.push(NodeIndex);
1701 }
1702}
1703
1704/// The technique used here is described in "Exploiting Pointer and Location
1705/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1706/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1707/// and is equivalent to value numbering the collapsed constraint graph
1708/// including evaluating unions.
1709void Andersens::HU() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001710 DEBUG(errs() << "Beginning HU\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001711 // Build a predecessor graph. This is like our constraint graph with the
1712 // edges going in the opposite direction, and there are edges for all the
1713 // constraints, instead of just copy constraints. We also build implicit
1714 // edges for constraints are implied but not explicit. I.E for the constraint
1715 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1716 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1717 Constraint &C = Constraints[i];
1718 if (C.Type == Constraint::AddressOf) {
1719 GraphNodes[C.Src].AddressTaken = true;
1720 GraphNodes[C.Src].Direct = false;
1721
1722 GraphNodes[C.Dest].PointsTo->set(C.Src);
1723 // *Dest = src edge
1724 unsigned RefNode = C.Dest + FirstRefNode;
1725 if (!GraphNodes[RefNode].ImplicitPredEdges)
1726 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1727 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1728 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1729 } else if (C.Type == Constraint::Load) {
1730 if (C.Offset == 0) {
1731 // dest = *src edge
1732 if (!GraphNodes[C.Dest].PredEdges)
1733 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1734 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1735 } else {
1736 GraphNodes[C.Dest].Direct = false;
1737 }
1738 } else if (C.Type == Constraint::Store) {
1739 if (C.Offset == 0) {
1740 // *dest = src edge
1741 unsigned RefNode = C.Dest + FirstRefNode;
1742 if (!GraphNodes[RefNode].PredEdges)
1743 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1744 GraphNodes[RefNode].PredEdges->set(C.Src);
1745 }
1746 } else {
1747 // Dest = Src edge and *Dest = *Src edg
1748 if (!GraphNodes[C.Dest].PredEdges)
1749 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1750 GraphNodes[C.Dest].PredEdges->set(C.Src);
1751 unsigned RefNode = C.Dest + FirstRefNode;
1752 if (!GraphNodes[RefNode].ImplicitPredEdges)
1753 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1754 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1755 }
1756 }
1757 PEClass = 1;
1758 // Do SCC finding first to condense our predecessor graph
1759 DFSNumber = 0;
1760 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1761 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1762 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1763
1764 for (unsigned i = 0; i < FirstRefNode; ++i) {
1765 if (FindNode(i) == i) {
1766 unsigned Node = VSSCCRep[i];
1767 if (!Node2Visited[Node])
1768 Condense(Node);
1769 }
1770 }
1771
1772 // Reset tables for actual labeling
1773 Node2DFS.clear();
1774 Node2Visited.clear();
1775 Node2Deleted.clear();
1776 // Pre-grow our densemap so that we don't get really bad behavior
1777 Set2PEClass.resize(GraphNodes.size());
1778
1779 // Visit the condensed graph and generate pointer equivalence labels.
1780 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1781 for (unsigned i = 0; i < FirstRefNode; ++i) {
1782 if (FindNode(i) == i) {
1783 unsigned Node = VSSCCRep[i];
1784 if (!Node2Visited[Node])
1785 HUValNum(Node);
1786 }
1787 }
1788 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1789 Set2PEClass.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001790 DEBUG(errs() << "Finished HU\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001791}
1792
1793
1794/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1795void Andersens::Condense(unsigned NodeIndex) {
1796 unsigned MyDFS = DFSNumber++;
1797 Node *N = &GraphNodes[NodeIndex];
1798 Node2Visited[NodeIndex] = true;
1799 Node2DFS[NodeIndex] = MyDFS;
1800
1801 // First process all our explicit edges
1802 if (N->PredEdges)
1803 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1804 Iter != N->PredEdges->end();
1805 ++Iter) {
1806 unsigned j = VSSCCRep[*Iter];
1807 if (!Node2Deleted[j]) {
1808 if (!Node2Visited[j])
1809 Condense(j);
1810 if (Node2DFS[NodeIndex] > Node2DFS[j])
1811 Node2DFS[NodeIndex] = Node2DFS[j];
1812 }
1813 }
1814
1815 // Now process all the implicit edges
1816 if (N->ImplicitPredEdges)
1817 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1818 Iter != N->ImplicitPredEdges->end();
1819 ++Iter) {
1820 unsigned j = VSSCCRep[*Iter];
1821 if (!Node2Deleted[j]) {
1822 if (!Node2Visited[j])
1823 Condense(j);
1824 if (Node2DFS[NodeIndex] > Node2DFS[j])
1825 Node2DFS[NodeIndex] = Node2DFS[j];
1826 }
1827 }
1828
1829 // See if we found any cycles
1830 if (MyDFS == Node2DFS[NodeIndex]) {
1831 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1832 unsigned CycleNodeIndex = SCCStack.top();
1833 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1834 VSSCCRep[CycleNodeIndex] = NodeIndex;
1835 // Unify the nodes
1836 N->Direct &= CycleNode->Direct;
1837
1838 *(N->PointsTo) |= CycleNode->PointsTo;
1839 delete CycleNode->PointsTo;
1840 CycleNode->PointsTo = NULL;
1841 if (CycleNode->PredEdges) {
1842 if (!N->PredEdges)
1843 N->PredEdges = new SparseBitVector<>;
1844 *(N->PredEdges) |= CycleNode->PredEdges;
1845 delete CycleNode->PredEdges;
1846 CycleNode->PredEdges = NULL;
1847 }
1848 if (CycleNode->ImplicitPredEdges) {
1849 if (!N->ImplicitPredEdges)
1850 N->ImplicitPredEdges = new SparseBitVector<>;
1851 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1852 delete CycleNode->ImplicitPredEdges;
1853 CycleNode->ImplicitPredEdges = NULL;
1854 }
1855 SCCStack.pop();
1856 }
1857
1858 Node2Deleted[NodeIndex] = true;
1859
1860 // Set up number of incoming edges for other nodes
1861 if (N->PredEdges)
1862 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1863 Iter != N->PredEdges->end();
1864 ++Iter)
1865 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1866 } else {
1867 SCCStack.push(NodeIndex);
1868 }
1869}
1870
1871void Andersens::HUValNum(unsigned NodeIndex) {
1872 Node *N = &GraphNodes[NodeIndex];
1873 Node2Visited[NodeIndex] = true;
1874
1875 // Eliminate dereferences of non-pointers for those non-pointers we have
1876 // already identified. These are ref nodes whose non-ref node:
1877 // 1. Has already been visited determined to point to nothing (and thus, a
1878 // dereference of it must point to nothing)
1879 // 2. Any direct node with no predecessor edges in our graph and with no
1880 // points-to set (since it can't point to anything either, being that it
1881 // receives no points-to sets and has none).
1882 if (NodeIndex >= FirstRefNode) {
1883 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1884 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1885 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1886 && GraphNodes[j].PointsTo->empty())){
1887 return;
1888 }
1889 }
1890 // Process all our explicit edges
1891 if (N->PredEdges)
1892 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1893 Iter != N->PredEdges->end();
1894 ++Iter) {
1895 unsigned j = VSSCCRep[*Iter];
1896 if (!Node2Visited[j])
1897 HUValNum(j);
1898
1899 // If this edge turned out to be the same as us, or got no pointer
1900 // equivalence label (and thus points to nothing) , just decrement our
1901 // incoming edges and continue.
1902 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1903 --GraphNodes[j].NumInEdges;
1904 continue;
1905 }
1906
1907 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1908
1909 // If we didn't end up storing this in the hash, and we're done with all
1910 // the edges, we don't need the points-to set anymore.
1911 --GraphNodes[j].NumInEdges;
1912 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1913 delete GraphNodes[j].PointsTo;
1914 GraphNodes[j].PointsTo = NULL;
1915 }
1916 }
1917 // If this isn't a direct node, generate a fresh variable.
1918 if (!N->Direct) {
1919 N->PointsTo->set(FirstRefNode + NodeIndex);
1920 }
1921
1922 // See If we have something equivalent to us, if not, generate a new
1923 // equivalence class.
1924 if (N->PointsTo->empty()) {
1925 delete N->PointsTo;
1926 N->PointsTo = NULL;
1927 } else {
1928 if (N->Direct) {
1929 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1930 if (N->PointerEquivLabel == 0) {
1931 unsigned EquivClass = PEClass++;
1932 N->StoredInHash = true;
1933 Set2PEClass[N->PointsTo] = EquivClass;
1934 N->PointerEquivLabel = EquivClass;
1935 }
1936 } else {
1937 N->PointerEquivLabel = PEClass++;
1938 }
1939 }
1940}
1941
1942/// Rewrite our list of constraints so that pointer equivalent nodes are
1943/// replaced by their the pointer equivalence class representative.
1944void Andersens::RewriteConstraints() {
1945 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001946 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001947
1948 PEClass2Node.clear();
1949 PENLEClass2Node.clear();
1950
1951 // We may have from 1 to Graphnodes + 1 equivalence classes.
1952 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1953 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1954
1955 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1956 // nodes, and rewriting constraints to use the representative nodes.
1957 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1958 Constraint &C = Constraints[i];
1959 unsigned RHSNode = FindNode(C.Src);
1960 unsigned LHSNode = FindNode(C.Dest);
1961 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1962 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1963
1964 // First we try to eliminate constraints for things we can prove don't point
1965 // to anything.
1966 if (LHSLabel == 0) {
1967 DEBUG(PrintNode(&GraphNodes[LHSNode]));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001968 DEBUG(errs() << " is a non-pointer, ignoring constraint.\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001969 continue;
1970 }
1971 if (RHSLabel == 0) {
1972 DEBUG(PrintNode(&GraphNodes[RHSNode]));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001973 DEBUG(errs() << " is a non-pointer, ignoring constraint.\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001974 continue;
1975 }
1976 // This constraint may be useless, and it may become useless as we translate
1977 // it.
1978 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1979 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001980
Daniel Berlind81ccc22007-09-24 19:45:49 +00001981 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1982 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001983 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001984 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001985 continue;
1986
Chris Lattnerbe207732007-09-30 00:47:20 +00001987 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001988 NewConstraints.push_back(C);
1989 }
1990 Constraints.swap(NewConstraints);
1991 PEClass2Node.clear();
1992}
1993
1994/// See if we have a node that is pointer equivalent to the one being asked
1995/// about, and if so, unite them and return the equivalent node. Otherwise,
1996/// return the original node.
1997unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1998 unsigned NodeLabel) {
1999 if (!GraphNodes[NodeIndex].AddressTaken) {
2000 if (PEClass2Node[NodeLabel] != -1) {
2001 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002002 // We specifically request that Union-By-Rank not be used so that
2003 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
2004 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002005 } else {
2006 PEClass2Node[NodeLabel] = NodeIndex;
2007 PENLEClass2Node[NodeLabel] = NodeIndex;
2008 }
2009 } else if (PENLEClass2Node[NodeLabel] == -1) {
2010 PENLEClass2Node[NodeLabel] = NodeIndex;
2011 }
2012
2013 return NodeIndex;
2014}
2015
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002016void Andersens::PrintLabels() const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002017 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2018 if (i < FirstRefNode) {
2019 PrintNode(&GraphNodes[i]);
2020 } else if (i < FirstAdrNode) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002021 DEBUG(errs() << "REF(");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002022 PrintNode(&GraphNodes[i-FirstRefNode]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002023 DEBUG(errs() <<")");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002024 } else {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002025 DEBUG(errs() << "ADR(");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002026 PrintNode(&GraphNodes[i-FirstAdrNode]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002027 DEBUG(errs() <<")");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002028 }
2029
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002030 DEBUG(errs() << " has pointer label " << GraphNodes[i].PointerEquivLabel
Daniel Berlind81ccc22007-09-24 19:45:49 +00002031 << " and SCC rep " << VSSCCRep[i]
2032 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002033 << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002034 }
2035}
2036
Daniel Berlinc864edb2008-03-05 19:31:47 +00002037/// The technique used here is described in "The Ant and the
2038/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2039/// Lines of Code. In Programming Language Design and Implementation
2040/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2041/// Detection) algorithm. It is called a hybrid because it performs an
2042/// offline analysis and uses its results during the solving (online)
2043/// phase. This is just the offline portion; the results of this
2044/// operation are stored in SDT and are later used in SolveContraints()
2045/// and UniteNodes().
2046void Andersens::HCD() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002047 DEBUG(errs() << "Starting HCD.\n");
Daniel Berlinc864edb2008-03-05 19:31:47 +00002048 HCDSCCRep.resize(GraphNodes.size());
2049
2050 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2051 GraphNodes[i].Edges = new SparseBitVector<>;
2052 HCDSCCRep[i] = i;
2053 }
2054
2055 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2056 Constraint &C = Constraints[i];
2057 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2058 if (C.Type == Constraint::AddressOf) {
2059 continue;
2060 } else if (C.Type == Constraint::Load) {
2061 if( C.Offset == 0 )
2062 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2063 } else if (C.Type == Constraint::Store) {
2064 if( C.Offset == 0 )
2065 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2066 } else {
2067 GraphNodes[C.Dest].Edges->set(C.Src);
2068 }
2069 }
2070
2071 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2072 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2073 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2074 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2075
2076 DFSNumber = 0;
2077 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2078 unsigned Node = HCDSCCRep[i];
2079 if (!Node2Deleted[Node])
2080 Search(Node);
2081 }
2082
2083 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2084 if (GraphNodes[i].Edges != NULL) {
2085 delete GraphNodes[i].Edges;
2086 GraphNodes[i].Edges = NULL;
2087 }
2088
2089 while( !SCCStack.empty() )
2090 SCCStack.pop();
2091
2092 Node2DFS.clear();
2093 Node2Visited.clear();
2094 Node2Deleted.clear();
2095 HCDSCCRep.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002096 DEBUG(errs() << "HCD complete.\n");
Daniel Berlinc864edb2008-03-05 19:31:47 +00002097}
2098
2099// Component of HCD:
2100// Use Nuutila's variant of Tarjan's algorithm to detect
2101// Strongly-Connected Components (SCCs). For non-trivial SCCs
2102// containing ref nodes, insert the appropriate information in SDT.
2103void Andersens::Search(unsigned Node) {
2104 unsigned MyDFS = DFSNumber++;
2105
2106 Node2Visited[Node] = true;
2107 Node2DFS[Node] = MyDFS;
2108
2109 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2110 End = GraphNodes[Node].Edges->end();
2111 Iter != End;
2112 ++Iter) {
2113 unsigned J = HCDSCCRep[*Iter];
2114 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2115 if (!Node2Deleted[J]) {
2116 if (!Node2Visited[J])
2117 Search(J);
2118 if (Node2DFS[Node] > Node2DFS[J])
2119 Node2DFS[Node] = Node2DFS[J];
2120 }
2121 }
2122
2123 if( MyDFS != Node2DFS[Node] ) {
2124 SCCStack.push(Node);
2125 return;
2126 }
2127
2128 // This node is the root of a SCC, so process it.
2129 //
2130 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2131 // node, we place this SCC into SDT. We unite the nodes in any case.
2132 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2133 SparseBitVector<> SCC;
2134
2135 SCC.set(Node);
2136
2137 bool Ref = (Node >= FirstRefNode);
2138
2139 Node2Deleted[Node] = true;
2140
2141 do {
2142 unsigned P = SCCStack.top(); SCCStack.pop();
2143 Ref |= (P >= FirstRefNode);
2144 SCC.set(P);
2145 HCDSCCRep[P] = Node;
2146 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2147
2148 if (Ref) {
2149 unsigned Rep = SCC.find_first();
2150 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2151
2152 SparseBitVector<>::iterator i = SCC.begin();
2153
2154 // Skip over the non-ref nodes
2155 while( *i < FirstRefNode )
2156 ++i;
2157
2158 while( i != SCC.end() )
2159 SDT[ (*i++) - FirstRefNode ] = Rep;
2160 }
2161 }
2162}
2163
2164
Daniel Berlind81ccc22007-09-24 19:45:49 +00002165/// Optimize the constraints by performing offline variable substitution and
2166/// other optimizations.
2167void Andersens::OptimizeConstraints() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002168 DEBUG(errs() << "Beginning constraint optimization\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002169
Daniel Berlinc864edb2008-03-05 19:31:47 +00002170 SDTActive = false;
2171
Daniel Berlind81ccc22007-09-24 19:45:49 +00002172 // Function related nodes need to stay in the same relative position and can't
2173 // be location equivalent.
2174 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2175 Iter != MaxK.end();
2176 ++Iter) {
2177 for (unsigned i = Iter->first;
2178 i != Iter->first + Iter->second;
2179 ++i) {
2180 GraphNodes[i].AddressTaken = true;
2181 GraphNodes[i].Direct = false;
2182 }
2183 }
2184
2185 ClumpAddressTaken();
2186 FirstRefNode = GraphNodes.size();
2187 FirstAdrNode = FirstRefNode + GraphNodes.size();
2188 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2189 Node(false));
2190 VSSCCRep.resize(GraphNodes.size());
2191 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2192 VSSCCRep[i] = i;
2193 }
2194 HVN();
2195 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2196 Node *N = &GraphNodes[i];
2197 delete N->PredEdges;
2198 N->PredEdges = NULL;
2199 delete N->ImplicitPredEdges;
2200 N->ImplicitPredEdges = NULL;
2201 }
2202#undef DEBUG_TYPE
2203#define DEBUG_TYPE "anders-aa-labels"
2204 DEBUG(PrintLabels());
2205#undef DEBUG_TYPE
2206#define DEBUG_TYPE "anders-aa"
2207 RewriteConstraints();
2208 // Delete the adr nodes.
2209 GraphNodes.resize(FirstRefNode * 2);
2210
2211 // Now perform HU
2212 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2213 Node *N = &GraphNodes[i];
2214 if (FindNode(i) == i) {
2215 N->PointsTo = new SparseBitVector<>;
2216 N->PointedToBy = new SparseBitVector<>;
2217 // Reset our labels
2218 }
2219 VSSCCRep[i] = i;
2220 N->PointerEquivLabel = 0;
2221 }
2222 HU();
2223#undef DEBUG_TYPE
2224#define DEBUG_TYPE "anders-aa-labels"
2225 DEBUG(PrintLabels());
2226#undef DEBUG_TYPE
2227#define DEBUG_TYPE "anders-aa"
2228 RewriteConstraints();
2229 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2230 if (FindNode(i) == i) {
2231 Node *N = &GraphNodes[i];
2232 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002233 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002234 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002235 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002236 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002237 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002238 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002239 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002240 }
2241 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002242
2243 // perform Hybrid Cycle Detection (HCD)
2244 HCD();
2245 SDTActive = true;
2246
2247 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002248 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002249
2250 // HCD complete.
2251
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002252 DEBUG(errs() << "Finished constraint optimization\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002253 FirstRefNode = 0;
2254 FirstAdrNode = 0;
2255}
2256
2257/// Unite pointer but not location equivalent variables, now that the constraint
2258/// graph is built.
2259void Andersens::UnitePointerEquivalences() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002260 DEBUG(errs() << "Uniting remaining pointer equivalences\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002261 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002262 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002263 unsigned Label = GraphNodes[i].PointerEquivLabel;
2264
2265 if (Label && PENLEClass2Node[Label] != -1)
2266 UniteNodes(i, PENLEClass2Node[Label]);
2267 }
2268 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002269 DEBUG(errs() << "Finished remaining pointer equivalences\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002270 PENLEClass2Node.clear();
2271}
2272
2273/// Create the constraint graph used for solving points-to analysis.
2274///
Daniel Berlinaad15882007-09-16 21:45:02 +00002275void Andersens::CreateConstraintGraph() {
2276 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2277 Constraint &C = Constraints[i];
2278 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2279 if (C.Type == Constraint::AddressOf)
2280 GraphNodes[C.Dest].PointsTo->set(C.Src);
2281 else if (C.Type == Constraint::Load)
2282 GraphNodes[C.Src].Constraints.push_back(C);
2283 else if (C.Type == Constraint::Store)
2284 GraphNodes[C.Dest].Constraints.push_back(C);
2285 else if (C.Offset != 0)
2286 GraphNodes[C.Src].Constraints.push_back(C);
2287 else
2288 GraphNodes[C.Src].Edges->set(C.Dest);
2289 }
2290}
2291
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002292// Perform DFS and cycle detection.
2293bool Andersens::QueryNode(unsigned Node) {
2294 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002295 unsigned OurDFS = ++DFSNumber;
2296 SparseBitVector<> ToErase;
2297 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002298 Tarjan2DFS[Node] = OurDFS;
2299
2300 // Changed denotes a change from a recursive call that we will bubble up.
2301 // Merged is set if we actually merge a node ourselves.
2302 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002303
2304 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2305 bi != GraphNodes[Node].Edges->end();
2306 ++bi) {
2307 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002308 // If this edge points to a non-representative node but we are
2309 // already planning to add an edge to its representative, we have no
2310 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002311 if (RepNode != *bi && NewEdges.test(RepNode)){
2312 ToErase.set(*bi);
2313 continue;
2314 }
2315
2316 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002317 if (!Tarjan2Deleted[RepNode]){
2318 if (Tarjan2DFS[RepNode] == 0) {
2319 Changed |= QueryNode(RepNode);
2320 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002321 RepNode = FindNode(RepNode);
2322 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002323 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2324 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002325 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002326
2327 // We may have just discovered that this node is part of a cycle, in
2328 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002329 if (RepNode != *bi) {
2330 ToErase.set(*bi);
2331 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002332 }
2333 }
2334
Daniel Berlinaad15882007-09-16 21:45:02 +00002335 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2336 GraphNodes[Node].Edges |= NewEdges;
2337
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002338 // If this node is a root of a non-trivial SCC, place it on our
2339 // worklist to be processed.
2340 if (OurDFS == Tarjan2DFS[Node]) {
2341 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2342 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002343
2344 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002345 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002346 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002347 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002348
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002349 if (Merged)
2350 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002351 } else {
2352 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002353 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002354
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002355 return(Changed | Merged);
2356}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002357
2358/// SolveConstraints - This stage iteratively processes the constraints list
2359/// propagating constraints (adding edges to the Nodes in the points-to graph)
2360/// until a fixed point is reached.
2361///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002362/// We use a variant of the technique called "Lazy Cycle Detection", which is
2363/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2364/// Analysis for Millions of Lines of Code. In Programming Language Design and
2365/// Implementation (PLDI), June 2007."
2366/// The paper describes performing cycle detection one node at a time, which can
2367/// be expensive if there are no cycles, but there are long chains of nodes that
2368/// it heuristically believes are cycles (because it will DFS from each node
2369/// without state from previous nodes).
2370/// Instead, we use the heuristic to build a worklist of nodes to check, then
2371/// cycle detect them all at the same time to do this more cheaply. This
2372/// catches cycles slightly later than the original technique did, but does it
2373/// make significantly cheaper.
2374
Chris Lattnere995a2a2004-05-23 21:00:47 +00002375void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002376 CurrWL = &w1;
2377 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002378
Daniel Berlind81ccc22007-09-24 19:45:49 +00002379 OptimizeConstraints();
2380#undef DEBUG_TYPE
2381#define DEBUG_TYPE "anders-aa-constraints"
2382 DEBUG(PrintConstraints());
2383#undef DEBUG_TYPE
2384#define DEBUG_TYPE "anders-aa"
2385
Daniel Berlinaad15882007-09-16 21:45:02 +00002386 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2387 Node *N = &GraphNodes[i];
2388 N->PointsTo = new SparseBitVector<>;
2389 N->OldPointsTo = new SparseBitVector<>;
2390 N->Edges = new SparseBitVector<>;
2391 }
2392 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002393 UnitePointerEquivalences();
2394 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002395 Node2DFS.clear();
2396 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002397 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2398 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2399 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002400 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2401 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2402
2403 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002404 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002405 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002406
2407 // Add to work list if it's a representative and can contribute to the
2408 // calculation right now.
2409 if (INode->isRep() && !INode->PointsTo->empty()
2410 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2411 INode->Stamp();
2412 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002413 }
2414 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002415 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002416#if !FULL_UNIVERSAL
2417 // "Rep and special variables" - in order for HCD to maintain conservative
2418 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2419 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2420 // the analysis - it's ok to add edges from the special nodes, but never
2421 // *to* the special nodes.
2422 std::vector<unsigned int> RSV;
2423#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002424 while( !CurrWL->empty() ) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002425 DEBUG(errs() << "Starting iteration #" << ++NumIters << "\n");
Daniel Berlinaad15882007-09-16 21:45:02 +00002426
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002427 Node* CurrNode;
2428 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002429
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002430 // Actual cycle checking code. We cycle check all of the lazy cycle
2431 // candidates from the last iteration in one go.
2432 if (!TarjanWL.empty()) {
2433 DFSNumber = 0;
2434
2435 Tarjan2DFS.clear();
2436 Tarjan2Deleted.clear();
2437 while (!TarjanWL.empty()) {
2438 unsigned int ToTarjan = TarjanWL.front();
2439 TarjanWL.pop();
2440 if (!Tarjan2Deleted[ToTarjan]
2441 && GraphNodes[ToTarjan].isRep()
2442 && Tarjan2DFS[ToTarjan] == 0)
2443 QueryNode(ToTarjan);
2444 }
2445 }
2446
2447 // Add to work list if it's a representative and can contribute to the
2448 // calculation right now.
2449 while( (CurrNode = CurrWL->pop()) != NULL ) {
2450 CurrNodeIndex = CurrNode - &GraphNodes[0];
2451 CurrNode->Stamp();
2452
2453
Daniel Berlinaad15882007-09-16 21:45:02 +00002454 // Figure out the changed points to bits
2455 SparseBitVector<> CurrPointsTo;
2456 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2457 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002458 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002459 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002460
Daniel Berlinaad15882007-09-16 21:45:02 +00002461 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002462
2463 // Check the offline-computed equivalencies from HCD.
2464 bool SCC = false;
2465 unsigned Rep;
2466
2467 if (SDT[CurrNodeIndex] >= 0) {
2468 SCC = true;
2469 Rep = FindNode(SDT[CurrNodeIndex]);
2470
2471#if !FULL_UNIVERSAL
2472 RSV.clear();
2473#endif
2474 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2475 bi != CurrPointsTo.end(); ++bi) {
2476 unsigned Node = FindNode(*bi);
2477#if !FULL_UNIVERSAL
2478 if (Node < NumberSpecialNodes) {
2479 RSV.push_back(Node);
2480 continue;
2481 }
2482#endif
2483 Rep = UniteNodes(Rep,Node);
2484 }
2485#if !FULL_UNIVERSAL
2486 RSV.push_back(Rep);
2487#endif
2488
2489 NextWL->insert(&GraphNodes[Rep]);
2490
2491 if ( ! CurrNode->isRep() )
2492 continue;
2493 }
2494
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002495 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002496
Daniel Berlinaad15882007-09-16 21:45:02 +00002497 /* Now process the constraints for this node. */
2498 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2499 li != CurrNode->Constraints.end(); ) {
2500 li->Src = FindNode(li->Src);
2501 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002502
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002503 // Delete redundant constraints
2504 if( Seen.count(*li) ) {
2505 std::list<Constraint>::iterator lk = li; li++;
2506
2507 CurrNode->Constraints.erase(lk);
2508 ++NumErased;
2509 continue;
2510 }
2511 Seen.insert(*li);
2512
Daniel Berlinaad15882007-09-16 21:45:02 +00002513 // Src and Dest will be the vars we are going to process.
2514 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002515 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002516 // Load constraints say that every member of our RHS solution has K
2517 // added to it, and that variable gets an edge to LHS. We also union
2518 // RHS+K's solution into the LHS solution.
2519 // Store constraints say that every member of our LHS solution has K
2520 // added to it, and that variable gets an edge from RHS. We also union
2521 // RHS's solution into the LHS+K solution.
2522 unsigned *Src;
2523 unsigned *Dest;
2524 unsigned K = li->Offset;
2525 unsigned CurrMember;
2526 if (li->Type == Constraint::Load) {
2527 Src = &CurrMember;
2528 Dest = &li->Dest;
2529 } else if (li->Type == Constraint::Store) {
2530 Src = &li->Src;
2531 Dest = &CurrMember;
2532 } else {
2533 // TODO Handle offseted copy constraint
2534 li++;
2535 continue;
2536 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002537
2538 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002539 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002540 // involves pointers; if so, remove the redundant constraints).
2541 if( SCC && K == 0 ) {
2542#if FULL_UNIVERSAL
2543 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002544
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002545 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2546 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2547 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002548#else
2549 for (unsigned i=0; i < RSV.size(); ++i) {
2550 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002551
Daniel Berlinc864edb2008-03-05 19:31:47 +00002552 if (*Dest < NumberSpecialNodes)
2553 continue;
2554 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2555 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2556 NextWL->insert(&GraphNodes[*Dest]);
2557 }
2558#endif
2559 // since all future elements of the points-to set will be
2560 // equivalent to the current ones, the complex constraints
2561 // become redundant.
2562 //
2563 std::list<Constraint>::iterator lk = li; li++;
2564#if !FULL_UNIVERSAL
2565 // In this case, we can still erase the constraints when the
2566 // elements of the points-to sets are referenced by *Dest,
2567 // but not when they are referenced by *Src (i.e. for a Load
2568 // constraint). This is because if another special variable is
2569 // put into the points-to set later, we still need to add the
2570 // new edge from that special variable.
2571 if( lk->Type != Constraint::Load)
2572#endif
2573 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2574 } else {
2575 const SparseBitVector<> &Solution = CurrPointsTo;
2576
2577 for (SparseBitVector<>::iterator bi = Solution.begin();
2578 bi != Solution.end();
2579 ++bi) {
2580 CurrMember = *bi;
2581
2582 // Need to increment the member by K since that is where we are
2583 // supposed to copy to/from. Note that in positive weight cycles,
2584 // which occur in address taking of fields, K can go past
2585 // MaxK[CurrMember] elements, even though that is all it could point
2586 // to.
2587 if (K > 0 && K > MaxK[CurrMember])
2588 continue;
2589 else
2590 CurrMember = FindNode(CurrMember + K);
2591
2592 // Add an edge to the graph, so we can just do regular
2593 // bitmap ior next time. It may also let us notice a cycle.
2594#if !FULL_UNIVERSAL
2595 if (*Dest < NumberSpecialNodes)
2596 continue;
2597#endif
2598 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2599 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2600 NextWL->insert(&GraphNodes[*Dest]);
2601
2602 }
2603 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002604 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002605 }
2606 SparseBitVector<> NewEdges;
2607 SparseBitVector<> ToErase;
2608
2609 // Now all we have left to do is propagate points-to info along the
2610 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002611 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2612 bi != CurrNode->Edges->end();
2613 ++bi) {
2614
2615 unsigned DestVar = *bi;
2616 unsigned Rep = FindNode(DestVar);
2617
Bill Wendlingf059deb2008-02-26 10:51:52 +00002618 // If we ended up with this node as our destination, or we've already
2619 // got an edge for the representative, delete the current edge.
2620 if (Rep == CurrNodeIndex ||
2621 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002622 ToErase.set(DestVar);
2623 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002624 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002625
Bill Wendlingf059deb2008-02-26 10:51:52 +00002626 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002627
2628 // This is where we do lazy cycle detection.
2629 // If this is a cycle candidate (equal points-to sets and this
2630 // particular edge has not been cycle-checked previously), add to the
2631 // list to check for cycles on the next iteration.
2632 if (!EdgesChecked.count(edge) &&
2633 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2634 EdgesChecked.insert(edge);
2635 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002636 }
2637 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002638#if !FULL_UNIVERSAL
2639 if (Rep >= NumberSpecialNodes)
2640#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002641 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002642 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002643 }
2644 // If this edge's destination was collapsed, rewrite the edge.
2645 if (Rep != DestVar) {
2646 ToErase.set(DestVar);
2647 NewEdges.set(Rep);
2648 }
2649 }
2650 CurrNode->Edges->intersectWithComplement(ToErase);
2651 CurrNode->Edges |= NewEdges;
2652 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002653
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002654 // Switch to other work list.
2655 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2656 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002657
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002658
Daniel Berlinaad15882007-09-16 21:45:02 +00002659 Node2DFS.clear();
2660 Node2Deleted.clear();
2661 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2662 Node *N = &GraphNodes[i];
2663 delete N->OldPointsTo;
2664 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002665 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002666 SDTActive = false;
2667 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002668}
2669
Daniel Berlinaad15882007-09-16 21:45:02 +00002670//===----------------------------------------------------------------------===//
2671// Union-Find
2672//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002673
Daniel Berlinaad15882007-09-16 21:45:02 +00002674// Unite nodes First and Second, returning the one which is now the
2675// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002676unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2677 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002678 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2679 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002680
Daniel Berlinaad15882007-09-16 21:45:02 +00002681 Node *FirstNode = &GraphNodes[First];
2682 Node *SecondNode = &GraphNodes[Second];
2683
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002684 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002685 "Trying to unite two non-representative nodes!");
2686 if (First == Second)
2687 return First;
2688
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002689 if (UnionByRank) {
2690 int RankFirst = (int) FirstNode ->NodeRep;
2691 int RankSecond = (int) SecondNode->NodeRep;
2692
2693 // Rank starts at -1 and gets decremented as it increases.
2694 // Translation: higher rank, lower NodeRep value, which is always negative.
2695 if (RankFirst > RankSecond) {
2696 unsigned t = First; First = Second; Second = t;
2697 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2698 } else if (RankFirst == RankSecond) {
2699 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2700 }
2701 }
2702
Daniel Berlinaad15882007-09-16 21:45:02 +00002703 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002704#if !FULL_UNIVERSAL
2705 if (First >= NumberSpecialNodes)
2706#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002707 if (FirstNode->PointsTo && SecondNode->PointsTo)
2708 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2709 if (FirstNode->Edges && SecondNode->Edges)
2710 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002711 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002712 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2713 SecondNode->Constraints);
2714 if (FirstNode->OldPointsTo) {
2715 delete FirstNode->OldPointsTo;
2716 FirstNode->OldPointsTo = new SparseBitVector<>;
2717 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002718
2719 // Destroy interesting parts of the merged-from node.
2720 delete SecondNode->OldPointsTo;
2721 delete SecondNode->Edges;
2722 delete SecondNode->PointsTo;
2723 SecondNode->Edges = NULL;
2724 SecondNode->PointsTo = NULL;
2725 SecondNode->OldPointsTo = NULL;
2726
2727 NumUnified++;
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002728 DEBUG(errs() << "Unified Node ");
Daniel Berlinaad15882007-09-16 21:45:02 +00002729 DEBUG(PrintNode(FirstNode));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002730 DEBUG(errs() << " and Node ");
Daniel Berlinaad15882007-09-16 21:45:02 +00002731 DEBUG(PrintNode(SecondNode));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002732 DEBUG(errs() << "\n");
Daniel Berlinaad15882007-09-16 21:45:02 +00002733
Daniel Berlinc864edb2008-03-05 19:31:47 +00002734 if (SDTActive)
Duncan Sands43e2a032008-05-27 11:50:51 +00002735 if (SDT[Second] >= 0) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002736 if (SDT[First] < 0)
2737 SDT[First] = SDT[Second];
2738 else {
2739 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2740 First = FindNode(First);
2741 }
Duncan Sands43e2a032008-05-27 11:50:51 +00002742 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002743
Daniel Berlinaad15882007-09-16 21:45:02 +00002744 return First;
2745}
2746
2747// Find the index into GraphNodes of the node representing Node, performing
2748// path compression along the way
2749unsigned Andersens::FindNode(unsigned NodeIndex) {
2750 assert (NodeIndex < GraphNodes.size()
2751 && "Attempting to find a node that can't exist");
2752 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002753 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002754 return NodeIndex;
2755 else
2756 return (N->NodeRep = FindNode(N->NodeRep));
2757}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002758
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002759// Find the index into GraphNodes of the node representing Node,
2760// don't perform path compression along the way (for Print)
2761unsigned Andersens::FindNode(unsigned NodeIndex) const {
2762 assert (NodeIndex < GraphNodes.size()
2763 && "Attempting to find a node that can't exist");
2764 const Node *N = &GraphNodes[NodeIndex];
2765 if (N->isRep())
2766 return NodeIndex;
2767 else
2768 return FindNode(N->NodeRep);
2769}
2770
Chris Lattnere995a2a2004-05-23 21:00:47 +00002771//===----------------------------------------------------------------------===//
2772// Debugging Output
2773//===----------------------------------------------------------------------===//
2774
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002775void Andersens::PrintNode(const Node *N) const {
Chris Lattnere995a2a2004-05-23 21:00:47 +00002776 if (N == &GraphNodes[UniversalSet]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002777 errs() << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002778 return;
2779 } else if (N == &GraphNodes[NullPtr]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002780 errs() << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002781 return;
2782 } else if (N == &GraphNodes[NullObject]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002783 errs() << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002784 return;
2785 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002786 if (!N->getValue()) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002787 errs() << "artificial" << (intptr_t) N;
Daniel Berlinaad15882007-09-16 21:45:02 +00002788 return;
2789 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002790
2791 assert(N->getValue() != 0 && "Never set node label!");
2792 Value *V = N->getValue();
2793 if (Function *F = dyn_cast<Function>(V)) {
2794 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002795 N == &GraphNodes[getReturnNode(F)]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002796 errs() << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002797 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002798 } else if (F->getFunctionType()->isVarArg() &&
2799 N == &GraphNodes[getVarargNode(F)]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002800 errs() << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002801 return;
2802 }
2803 }
2804
2805 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002806 errs() << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002807 else if (Argument *Arg = dyn_cast<Argument>(V))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002808 errs() << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002809
2810 if (V->hasName())
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002811 errs() << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002812 else
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002813 errs() << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002814
2815 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002816 if (N == &GraphNodes[getObject(V)])
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002817 errs() << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002818}
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002819void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002820 if (C.Type == Constraint::Store) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002821 errs() << "*";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002822 if (C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002823 errs() << "(";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002824 }
2825 PrintNode(&GraphNodes[C.Dest]);
2826 if (C.Type == Constraint::Store && C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002827 errs() << " + " << C.Offset << ")";
2828 errs() << " = ";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002829 if (C.Type == Constraint::Load) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002830 errs() << "*";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002831 if (C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002832 errs() << "(";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002833 }
2834 else if (C.Type == Constraint::AddressOf)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002835 errs() << "&";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002836 PrintNode(&GraphNodes[C.Src]);
2837 if (C.Offset != 0 && C.Type != Constraint::Store)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002838 errs() << " + " << C.Offset;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002839 if (C.Type == Constraint::Load && C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002840 errs() << ")";
2841 errs() << "\n";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002842}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002843
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002844void Andersens::PrintConstraints() const {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002845 errs() << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002846
Daniel Berlind81ccc22007-09-24 19:45:49 +00002847 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2848 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002849}
2850
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002851void Andersens::PrintPointsToGraph() const {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002852 errs() << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002853 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002854 const Node *N = &GraphNodes[i];
2855 if (FindNode(i) != i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002856 PrintNode(N);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002857 errs() << "\t--> same as ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002858 PrintNode(&GraphNodes[FindNode(i)]);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002859 errs() << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002860 } else {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002861 errs() << "[" << (N->PointsTo->count()) << "] ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002862 PrintNode(N);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002863 errs() << "\t--> ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002864
2865 bool first = true;
2866 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2867 bi != N->PointsTo->end();
2868 ++bi) {
2869 if (!first)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002870 errs() << ", ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002871 PrintNode(&GraphNodes[*bi]);
2872 first = false;
2873 }
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002874 errs() << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002875 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002876 }
2877}