blob: 28c66affe119f5ad19e3fae1edcbf4c685ffb837 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
Daniel Berlin385bda62007-09-16 21:45:02 +000010// This file defines an implementation of Andersen's interprocedural alias
11// analysis
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012//
13// In pointer analysis terms, this is a subset-based, flow-insensitive,
Daniel Berlin385bda62007-09-16 21:45:02 +000014// field-sensitive, and context-insensitive algorithm pointer algorithm.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000015//
16// This algorithm is implemented as three stages:
17// 1. Object identification.
18// 2. Inclusion constraint identification.
Daniel Berlinb53270f2007-09-24 19:45:49 +000019// 3. Offline constraint graph optimization
20// 4. Inclusion constraint solving.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Berlin385bda62007-09-16 21:45:02 +000030// B can point to. Constraints can handle copies, loads, and stores, and
31// address taking.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032//
Daniel Berlin122992d2007-09-24 22:20:45 +000033// The offline constraint graph optimization portion includes offline variable
Daniel Berlined95dd02008-03-05 19:31:47 +000034// substitution algorithms intended to compute pointer and location
Daniel Berlin122992d2007-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 Berlined95dd02008-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 Berlinb53270f2007-09-24 19:45:49 +000040//
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Berlin385bda62007-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 Berlinb53270f2007-09-24 19:45:49 +000047// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlin385bda62007-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051//
52// Future Improvements:
Daniel Berlined95dd02008-03-05 19:31:47 +000053// Use of BDD's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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"
Edwin Törökced9ff82009-07-11 13:10:19 +000062#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063#include "llvm/Support/InstIterator.h"
64#include "llvm/Support/InstVisitor.h"
65#include "llvm/Analysis/AliasAnalysis.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000066#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067#include "llvm/Analysis/Passes.h"
68#include "llvm/Support/Debug.h"
Owen Anderson31e671b2009-06-24 22:16:52 +000069#include "llvm/System/Atomic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/ADT/Statistic.h"
Daniel Berlin385bda62007-09-16 21:45:02 +000071#include "llvm/ADT/SparseBitVector.h"
Chris Lattner4cf3c502007-09-30 00:47:20 +000072#include "llvm/ADT/DenseSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include <algorithm>
74#include <set>
Daniel Berlin385bda62007-09-16 21:45:02 +000075#include <list>
Dan Gohman249ddbf2008-03-21 23:51:57 +000076#include <map>
Daniel Berlin385bda62007-09-16 21:45:02 +000077#include <stack>
78#include <vector>
Daniel Berlinc6fd7722007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086
Daniel Berlin385bda62007-09-16 21:45:02 +000087using namespace llvm;
Daniel Dunbar09a0ce92009-08-23 10:29:55 +000088#ifndef NDEBUG
Daniel Berlinb53270f2007-09-24 19:45:49 +000089STATISTIC(NumIters , "Number of iterations to reach convergence");
Daniel Dunbar09a0ce92009-08-23 10:29:55 +000090#endif
Daniel Berlinb53270f2007-09-24 19:45:49 +000091STATISTIC(NumConstraints, "Number of constraints");
92STATISTIC(NumNodes , "Number of nodes");
93STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlinc6fd7722007-12-12 00:37:04 +000094STATISTIC(NumErased , "Number of redundant constraints erased");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095
Dan Gohman089efff2008-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 Berlinb53270f2007-09-24 19:45:49 +0000102
Dan Gohman089efff2008-05-13 00:00:25 +0000103namespace {
Daniel Berlinb53270f2007-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 }
Daniel Berlinb53270f2007-09-24 19:45:49 +0000124 };
Daniel Berlin385bda62007-09-16 21:45:02 +0000125
Nick Lewycky492d06e2009-10-25 06:33:48 +0000126 class Andersens : public ModulePass, public AliasAnalysis,
127 private InstVisitor<Andersens> {
Hartmut Kaiserad654562007-10-25 23:49:14 +0000128 struct Node;
Daniel Berlin385bda62007-09-16 21:45:02 +0000129
130 /// Constraint - Objects of this structure are used to represent the various
131 /// constraints identified by the algorithm. The constraints are 'copy',
132 /// for statements like "A = B", 'load' for statements like "A = *B",
133 /// 'store' for statements like "*A = B", and AddressOf for statements like
134 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
135 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlinb53270f2007-09-24 19:45:49 +0000136 /// illegal on addressof constraints (because it is statically
Daniel Berlin385bda62007-09-16 21:45:02 +0000137 /// resolvable to A = &C where C = B + K)
138
139 struct Constraint {
140 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
141 unsigned Dest;
142 unsigned Src;
143 unsigned Offset;
144
145 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
146 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikov357a27d2008-02-20 11:08:44 +0000147 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlin385bda62007-09-16 21:45:02 +0000148 "Offset is illegal on addressof constraints");
149 }
Daniel Berlin158a3932007-09-29 00:50:40 +0000150
Daniel Berline87fe282007-09-27 15:42:23 +0000151 bool operator==(const Constraint &RHS) const {
152 return RHS.Type == Type
153 && RHS.Dest == Dest
154 && RHS.Src == Src
155 && RHS.Offset == Offset;
156 }
Daniel Berlin158a3932007-09-29 00:50:40 +0000157
158 bool operator!=(const Constraint &RHS) const {
159 return !(*this == RHS);
160 }
161
Daniel Berline87fe282007-09-27 15:42:23 +0000162 bool operator<(const Constraint &RHS) const {
163 if (RHS.Type != Type)
164 return RHS.Type < Type;
165 else if (RHS.Dest != Dest)
166 return RHS.Dest < Dest;
167 else if (RHS.Src != Src)
168 return RHS.Src < Src;
169 return RHS.Offset < Offset;
170 }
Daniel Berlin385bda62007-09-16 21:45:02 +0000171 };
172
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000173 // Information DenseSet requires implemented in order to be able to do
174 // it's thing
175 struct PairKeyInfo {
176 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michel67973e42008-03-18 16:55:06 +0000177 return std::make_pair(~0U, ~0U);
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000178 }
179 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michel67973e42008-03-18 16:55:06 +0000180 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000181 }
182 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
183 return P.first ^ P.second;
184 }
185 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
186 const std::pair<unsigned, unsigned> &RHS) {
187 return LHS == RHS;
188 }
189 };
190
Daniel Berlin158a3932007-09-29 00:50:40 +0000191 struct ConstraintKeyInfo {
192 static inline Constraint getEmptyKey() {
Scott Michel67973e42008-03-18 16:55:06 +0000193 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin158a3932007-09-29 00:50:40 +0000194 }
195 static inline Constraint getTombstoneKey() {
Scott Michel67973e42008-03-18 16:55:06 +0000196 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin158a3932007-09-29 00:50:40 +0000197 }
198 static unsigned getHashValue(const Constraint &C) {
199 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
200 }
201 static bool isEqual(const Constraint &LHS,
202 const Constraint &RHS) {
203 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
204 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
205 }
206 };
207
Daniel Berlinb53270f2007-09-24 19:45:49 +0000208 // Node class - This class is used to represent a node in the constraint
Daniel Berlin122992d2007-09-24 22:20:45 +0000209 // graph. Due to various optimizations, it is not always the case that
210 // there is a mapping from a Node to a Value. In particular, we add
211 // artificial Node's that represent the set of pointed-to variables shared
212 // for each location equivalent Node.
Daniel Berlin385bda62007-09-16 21:45:02 +0000213 struct Node {
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000214 private:
Owen Anderson35c161c2009-06-30 05:33:46 +0000215 static volatile sys::cas_flag Counter;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000216
217 public:
Daniel Berlinb53270f2007-09-24 19:45:49 +0000218 Value *Val;
Daniel Berlin385bda62007-09-16 21:45:02 +0000219 SparseBitVector<> *Edges;
220 SparseBitVector<> *PointsTo;
221 SparseBitVector<> *OldPointsTo;
Daniel Berlin385bda62007-09-16 21:45:02 +0000222 std::list<Constraint> Constraints;
223
Daniel Berlinb53270f2007-09-24 19:45:49 +0000224 // Pointer and location equivalence labels
225 unsigned PointerEquivLabel;
226 unsigned LocationEquivLabel;
227 // Predecessor edges, both real and implicit
228 SparseBitVector<> *PredEdges;
229 SparseBitVector<> *ImplicitPredEdges;
230 // Set of nodes that point to us, only use for location equivalence.
231 SparseBitVector<> *PointedToBy;
232 // Number of incoming edges, used during variable substitution to early
233 // free the points-to sets
234 unsigned NumInEdges;
Daniel Berlin122992d2007-09-24 22:20:45 +0000235 // True if our points-to set is in the Set2PEClass map
Daniel Berlinb53270f2007-09-24 19:45:49 +0000236 bool StoredInHash;
Daniel Berlin122992d2007-09-24 22:20:45 +0000237 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlinb53270f2007-09-24 19:45:49 +0000238 bool Direct;
239 // True if the node is address taken, *or* it is part of a group of nodes
240 // that must be kept together. This is set to true for functions and
241 // their arg nodes, which must be kept at the same position relative to
242 // their base function node.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000243 bool AddressTaken;
Daniel Berlin385bda62007-09-16 21:45:02 +0000244
Daniel Berlinb53270f2007-09-24 19:45:49 +0000245 // Nodes in cycles (or in equivalence classes) are united together using a
246 // standard union-find representation with path compression. NodeRep
247 // gives the index into GraphNodes for the representative Node.
248 unsigned NodeRep;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000249
250 // Modification timestamp. Assigned from Counter.
251 // Used for work list prioritization.
252 unsigned Timestamp;
Daniel Berlinb53270f2007-09-24 19:45:49 +0000253
Dan Gohmanc43c7f42007-12-14 15:41:34 +0000254 explicit Node(bool direct = true) :
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000255 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlinb53270f2007-09-24 19:45:49 +0000256 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
257 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
258 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000259 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlin385bda62007-09-16 21:45:02 +0000260
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 Node *setValue(Value *V) {
262 assert(Val == 0 && "Value already set for this node!");
263 Val = V;
264 return this;
265 }
266
267 /// getValue - Return the LLVM value corresponding to this node.
268 ///
269 Value *getValue() const { return Val; }
270
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 /// addPointerTo - Add a pointer to the list of pointees of this node,
272 /// returning true if this caused a new pointer to be added, or false if
273 /// we already knew about the points-to relation.
Daniel Berlin385bda62007-09-16 21:45:02 +0000274 bool addPointerTo(unsigned Node) {
275 return PointsTo->test_and_set(Node);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 }
277
278 /// intersects - Return true if the points-to set of this node intersects
279 /// with the points-to set of the specified node.
280 bool intersects(Node *N) const;
281
282 /// intersectsIgnoring - Return true if the points-to set of this node
283 /// intersects with the points-to set of the specified node on any nodes
284 /// except for the specified node to ignore.
Daniel Berlin385bda62007-09-16 21:45:02 +0000285 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000286
287 // Timestamp a node (used for work list prioritization)
288 void Stamp() {
Owen Anderson7df5d652009-06-25 16:32:45 +0000289 Timestamp = sys::AtomicIncrement(&Counter);
290 --Timestamp;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000291 }
292
Andrew Lenharthdce39302008-03-20 15:36:44 +0000293 bool isRep() const {
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000294 return( (int) NodeRep < 0 );
295 }
296 };
297
298 struct WorkListElement {
299 Node* node;
300 unsigned Timestamp;
301 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
302
303 // Note that we reverse the sense of the comparison because we
304 // actually want to give low timestamps the priority over high,
305 // whereas priority is typically interpreted as a greater value is
306 // given high priority.
307 bool operator<(const WorkListElement& that) const {
308 return( this->Timestamp > that.Timestamp );
309 }
310 };
311
312 // Priority-queue based work list specialized for Nodes.
313 class WorkList {
314 std::priority_queue<WorkListElement> Q;
315
316 public:
317 void insert(Node* n) {
318 Q.push( WorkListElement(n, n->Timestamp) );
319 }
320
321 // We automatically discard non-representative nodes and nodes
322 // that were in the work list twice (we keep a copy of the
323 // timestamp in the work list so we can detect this situation by
324 // comparing against the node's current timestamp).
325 Node* pop() {
326 while( !Q.empty() ) {
327 WorkListElement x = Q.top(); Q.pop();
328 Node* INode = x.node;
329
330 if( INode->isRep() &&
331 INode->Timestamp == x.Timestamp ) {
332 return(x.node);
333 }
334 }
335 return(0);
336 }
337
338 bool empty() {
339 return Q.empty();
340 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 };
342
343 /// GraphNodes - This vector is populated as part of the object
344 /// identification stage of the analysis, which populates this vector with a
345 /// node for each memory object and fills in the ValueNodes map.
346 std::vector<Node> GraphNodes;
347
348 /// ValueNodes - This map indicates the Node that a particular Value* is
349 /// represented by. This contains entries for all pointers.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000350 DenseMap<Value*, unsigned> ValueNodes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351
352 /// ObjectNodes - This map contains entries for each memory object in the
353 /// program: globals, alloca's and mallocs.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000354 DenseMap<Value*, unsigned> ObjectNodes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355
356 /// ReturnNodes - This map contains an entry for each function in the
357 /// program that returns a value.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000358 DenseMap<Function*, unsigned> ReturnNodes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359
360 /// VarargNodes - This map contains the entry used to represent all pointers
361 /// passed through the varargs portion of a function call for a particular
362 /// function. An entry is not present in this map for functions that do not
363 /// take variable arguments.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000364 DenseMap<Function*, unsigned> VarargNodes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366
367 /// Constraints - This vector contains a list of all of the constraints
368 /// identified by the program.
369 std::vector<Constraint> Constraints;
370
Daniel Berlinb53270f2007-09-24 19:45:49 +0000371 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlin385bda62007-09-16 21:45:02 +0000372 // this is equivalent to the number of arguments + CallFirstArgPos)
373 std::map<unsigned, unsigned> MaxK;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374
375 /// This enum defines the GraphNodes indices that correspond to important
376 /// fixed sets.
377 enum {
378 UniversalSet = 0,
379 NullPtr = 1,
Daniel Berlinb53270f2007-09-24 19:45:49 +0000380 NullObject = 2,
381 NumberSpecialNodes
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 };
Daniel Berlinb53270f2007-09-24 19:45:49 +0000383 // Stack for Tarjan's
Daniel Berlin385bda62007-09-16 21:45:02 +0000384 std::stack<unsigned> SCCStack;
Daniel Berlin385bda62007-09-16 21:45:02 +0000385 // Map from Graph Node to DFS number
386 std::vector<unsigned> Node2DFS;
387 // Map from Graph Node to Deleted from graph.
388 std::vector<bool> Node2Deleted;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000389 // Same as Node Maps, but implemented as std::map because it is faster to
390 // clear
391 std::map<unsigned, unsigned> Tarjan2DFS;
392 std::map<unsigned, bool> Tarjan2Deleted;
393 // Current DFS number
Daniel Berlin385bda62007-09-16 21:45:02 +0000394 unsigned DFSNumber;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000395
396 // Work lists.
397 WorkList w1, w2;
398 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399
Daniel Berlinb53270f2007-09-24 19:45:49 +0000400 // Offline variable substitution related things
401
402 // Temporary rep storage, used because we can't collapse SCC's in the
403 // predecessor graph by uniting the variables permanently, we can only do so
404 // for the successor graph.
405 std::vector<unsigned> VSSCCRep;
406 // Mapping from node to whether we have visited it during SCC finding yet.
407 std::vector<bool> Node2Visited;
408 // During variable substitution, we create unknowns to represent the unknown
409 // value that is a dereference of a variable. These nodes are known as
410 // "ref" nodes (since they represent the value of dereferences).
411 unsigned FirstRefNode;
412 // During HVN, we create represent address taken nodes as if they were
413 // unknown (since HVN, unlike HU, does not evaluate unions).
414 unsigned FirstAdrNode;
415 // Current pointer equivalence class number
416 unsigned PEClass;
417 // Mapping from points-to sets to equivalence classes
418 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
419 BitVectorMap Set2PEClass;
420 // Mapping from pointer equivalences to the representative node. -1 if we
421 // have no representative node for this pointer equivalence class yet.
422 std::vector<int> PEClass2Node;
423 // Mapping from pointer equivalences to representative node. This includes
424 // pointer equivalent but not location equivalent variables. -1 if we have
425 // no representative node for this pointer equivalence class yet.
426 std::vector<int> PENLEClass2Node;
Daniel Berlined95dd02008-03-05 19:31:47 +0000427 // Union/Find for HCD
428 std::vector<unsigned> HCDSCCRep;
429 // HCD's offline-detected cycles; "Statically DeTected"
430 // -1 if not part of such a cycle, otherwise a representative node.
431 std::vector<int> SDT;
432 // Whether to use SDT (UniteNodes can use it during solving, but not before)
433 bool SDTActive;
Daniel Berlinb53270f2007-09-24 19:45:49 +0000434
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 public:
Daniel Berlin385bda62007-09-16 21:45:02 +0000436 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +0000437 Andersens() : ModulePass(&ID) {}
Devang Patel2b4fa682008-03-18 00:39:19 +0000438
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 bool runOnModule(Module &M) {
440 InitializeAliasAnalysis(this);
441 IdentifyObjects(M);
442 CollectConstraints(M);
Daniel Berlinb53270f2007-09-24 19:45:49 +0000443#undef DEBUG_TYPE
444#define DEBUG_TYPE "anders-aa-constraints"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445 DEBUG(PrintConstraints());
Daniel Berlinb53270f2007-09-24 19:45:49 +0000446#undef DEBUG_TYPE
447#define DEBUG_TYPE "anders-aa"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 SolveConstraints();
449 DEBUG(PrintPointsToGraph());
450
451 // Free the constraints list, as we don't need it to respond to alias
452 // requests.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 std::vector<Constraint>().swap(Constraints);
Andrew Lenharthdce39302008-03-20 15:36:44 +0000454 //These are needed for Print() (-analyze in opt)
455 //ObjectNodes.clear();
456 //ReturnNodes.clear();
457 //VarargNodes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 return false;
459 }
460
461 void releaseMemory() {
462 // FIXME: Until we have transitively required passes working correctly,
463 // this cannot be enabled! Otherwise, using -count-aa with the pass
464 // causes memory to be freed too early. :(
465#if 0
466 // The memory objects and ValueNodes data structures at the only ones that
467 // are still live after construction.
468 std::vector<Node>().swap(GraphNodes);
469 ValueNodes.clear();
470#endif
471 }
472
473 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
474 AliasAnalysis::getAnalysisUsage(AU);
475 AU.setPreservesAll(); // Does not transform code
476 }
477
478 //------------------------------------------------
479 // Implement the AliasAnalysis API
480 //
481 AliasResult alias(const Value *V1, unsigned V1Size,
482 const Value *V2, unsigned V2Size);
483 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
484 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485 bool pointsToConstantMemory(const Value *P);
486
487 virtual void deleteValue(Value *V) {
488 ValueNodes.erase(V);
489 getAnalysis<AliasAnalysis>().deleteValue(V);
490 }
491
492 virtual void copyValue(Value *From, Value *To) {
493 ValueNodes[To] = ValueNodes[From];
494 getAnalysis<AliasAnalysis>().copyValue(From, To);
495 }
496
497 private:
498 /// getNode - Return the node corresponding to the specified pointer scalar.
499 ///
Daniel Berlin385bda62007-09-16 21:45:02 +0000500 unsigned getNode(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 if (Constant *C = dyn_cast<Constant>(V))
502 if (!isa<GlobalValue>(C))
503 return getNodeForConstantPointer(C);
504
Daniel Berlinb53270f2007-09-24 19:45:49 +0000505 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 if (I == ValueNodes.end()) {
507#ifndef NDEBUG
508 V->dump();
509#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000510 llvm_unreachable("Value does not have a node in the points-to graph!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 }
Daniel Berlin385bda62007-09-16 21:45:02 +0000512 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 }
514
515 /// getObject - Return the node corresponding to the memory object for the
516 /// specified global or allocation instruction.
Andrew Lenharthdce39302008-03-20 15:36:44 +0000517 unsigned getObject(Value *V) const {
Jeffrey Yasskin8154d2e2009-11-10 01:02:17 +0000518 DenseMap<Value*, unsigned>::const_iterator I = ObjectNodes.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 assert(I != ObjectNodes.end() &&
520 "Value does not have an object in the points-to graph!");
Daniel Berlin385bda62007-09-16 21:45:02 +0000521 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522 }
523
524 /// getReturnNode - Return the node representing the return value for the
525 /// specified function.
Andrew Lenharthdce39302008-03-20 15:36:44 +0000526 unsigned getReturnNode(Function *F) const {
Jeffrey Yasskin8154d2e2009-11-10 01:02:17 +0000527 DenseMap<Function*, unsigned>::const_iterator I = ReturnNodes.find(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlin385bda62007-09-16 21:45:02 +0000529 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 }
531
532 /// getVarargNode - Return the node representing the variable arguments
533 /// formal for the specified function.
Andrew Lenharthdce39302008-03-20 15:36:44 +0000534 unsigned getVarargNode(Function *F) const {
Jeffrey Yasskin8154d2e2009-11-10 01:02:17 +0000535 DenseMap<Function*, unsigned>::const_iterator I = VarargNodes.find(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlin385bda62007-09-16 21:45:02 +0000537 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 }
539
540 /// getNodeValue - Get the node for the specified LLVM value and set the
541 /// value for it to be the specified value.
Daniel Berlin385bda62007-09-16 21:45:02 +0000542 unsigned getNodeValue(Value &V) {
543 unsigned Index = getNode(&V);
544 GraphNodes[Index].setValue(&V);
545 return Index;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 }
547
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000548 unsigned UniteNodes(unsigned First, unsigned Second,
549 bool UnionByRank = true);
Daniel Berlin385bda62007-09-16 21:45:02 +0000550 unsigned FindNode(unsigned Node);
Andrew Lenharthdce39302008-03-20 15:36:44 +0000551 unsigned FindNode(unsigned Node) const;
Daniel Berlin385bda62007-09-16 21:45:02 +0000552
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553 void IdentifyObjects(Module &M);
554 void CollectConstraints(Module &M);
Daniel Berlin385bda62007-09-16 21:45:02 +0000555 bool AnalyzeUsesOfFunction(Value *);
556 void CreateConstraintGraph();
Daniel Berlinb53270f2007-09-24 19:45:49 +0000557 void OptimizeConstraints();
558 unsigned FindEquivalentNode(unsigned, unsigned);
559 void ClumpAddressTaken();
560 void RewriteConstraints();
561 void HU();
562 void HVN();
Daniel Berlined95dd02008-03-05 19:31:47 +0000563 void HCD();
564 void Search(unsigned Node);
Daniel Berlinb53270f2007-09-24 19:45:49 +0000565 void UnitePointerEquivalences();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 void SolveConstraints();
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000567 bool QueryNode(unsigned Node);
Daniel Berlinb53270f2007-09-24 19:45:49 +0000568 void Condense(unsigned Node);
569 void HUValNum(unsigned Node);
570 void HVNValNum(unsigned Node);
Daniel Berlin385bda62007-09-16 21:45:02 +0000571 unsigned getNodeForConstantPointer(Constant *C);
572 unsigned getNodeForConstantPointerTarget(Constant *C);
573 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000574
575 void AddConstraintsForNonInternalLinkage(Function *F);
576 void AddConstraintsForCall(CallSite CS, Function *F);
577 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
578
579
Andrew Lenharthdce39302008-03-20 15:36:44 +0000580 void PrintNode(const Node *N) const;
581 void PrintConstraints() const ;
582 void PrintConstraint(const Constraint &) const;
583 void PrintLabels() const;
584 void PrintPointsToGraph() const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585
586 //===------------------------------------------------------------------===//
587 // Instruction visitation methods for adding constraints
588 //
589 friend class InstVisitor<Andersens>;
590 void visitReturnInst(ReturnInst &RI);
591 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
Victor Hernandez82f0ab62009-09-18 21:34:51 +0000592 void visitCallInst(CallInst &CI) {
Victor Hernandezb1687302009-10-23 21:09:37 +0000593 if (isMalloc(&CI)) visitAlloc(CI);
Victor Hernandez82f0ab62009-09-18 21:34:51 +0000594 else visitCallSite(CallSite(&CI));
595 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 void visitCallSite(CallSite CS);
Victor Hernandezb1687302009-10-23 21:09:37 +0000597 void visitAllocaInst(AllocaInst &I);
598 void visitAlloc(Instruction &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599 void visitLoadInst(LoadInst &LI);
600 void visitStoreInst(StoreInst &SI);
601 void visitGetElementPtrInst(GetElementPtrInst &GEP);
602 void visitPHINode(PHINode &PN);
603 void visitCastInst(CastInst &CI);
604 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
605 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
606 void visitSelectInst(SelectInst &SI);
607 void visitVAArg(VAArgInst &I);
608 void visitInstruction(Instruction &I);
Daniel Berlin385bda62007-09-16 21:45:02 +0000609
Andrew Lenharthdce39302008-03-20 15:36:44 +0000610 //===------------------------------------------------------------------===//
611 // Implement Analyize interface
612 //
Chris Lattner397f4562009-08-23 06:03:38 +0000613 void print(raw_ostream &O, const Module*) const {
Andrew Lenharthdce39302008-03-20 15:36:44 +0000614 PrintPointsToGraph();
615 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617}
618
Dan Gohman089efff2008-05-13 00:00:25 +0000619char Andersens::ID = 0;
620static RegisterPass<Andersens>
Chris Lattnerc4823b92009-08-28 00:45:47 +0000621X("anders-aa", "Andersen's Interprocedural Alias Analysis (experimental)",
622 false, true);
Dan Gohman089efff2008-05-13 00:00:25 +0000623static RegisterAnalysisGroup<AliasAnalysis> Y(X);
624
625// Initialize Timestamp Counter (static).
Owen Anderson35c161c2009-06-30 05:33:46 +0000626volatile llvm::sys::cas_flag Andersens::Node::Counter = 0;
Dan Gohman089efff2008-05-13 00:00:25 +0000627
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628ModulePass *llvm::createAndersensPass() { return new Andersens(); }
629
630//===----------------------------------------------------------------------===//
631// AliasAnalysis Interface Implementation
632//===----------------------------------------------------------------------===//
633
634AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
635 const Value *V2, unsigned V2Size) {
Daniel Berlin385bda62007-09-16 21:45:02 +0000636 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
637 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638
639 // Check to see if the two pointers are known to not alias. They don't alias
640 // if their points-to sets do not intersect.
Daniel Berlin385bda62007-09-16 21:45:02 +0000641 if (!N1->intersectsIgnoring(N2, NullObject))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 return NoAlias;
643
644 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
645}
646
647AliasAnalysis::ModRefResult
648Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
649 // The only thing useful that we can contribute for mod/ref information is
650 // when calling external function calls: if we know that memory never escapes
651 // from the program, it cannot be modified by an external call.
652 //
653 // NOTE: This is not really safe, at least not when the entire program is not
654 // available. The deal is that the external function could call back into the
655 // program and modify stuff. We ignore this technical niggle for now. This
656 // is, after all, a "research quality" implementation of Andersen's analysis.
657 if (Function *F = CS.getCalledFunction())
658 if (F->isDeclaration()) {
Daniel Berlin385bda62007-09-16 21:45:02 +0000659 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660
Daniel Berlin385bda62007-09-16 21:45:02 +0000661 if (N1->PointsTo->empty())
662 return NoModRef;
Daniel Berlinb68539d2008-03-18 22:22:53 +0000663#if FULL_UNIVERSAL
664 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
665 return NoModRef; // Universal set does not contain P
666#else
Daniel Berlin385bda62007-09-16 21:45:02 +0000667 if (!N1->PointsTo->test(UniversalSet))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 return NoModRef; // P doesn't point to the universal set.
Daniel Berlinb68539d2008-03-18 22:22:53 +0000669#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 }
671
672 return AliasAnalysis::getModRefInfo(CS, P, Size);
673}
674
675AliasAnalysis::ModRefResult
676Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
677 return AliasAnalysis::getModRefInfo(CS1,CS2);
678}
679
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680/// pointsToConstantMemory - If we can determine that this pointer only points
681/// to constant memory, return true. In practice, this means that if the
682/// pointer can only point to constant globals, functions, or the null pointer,
683/// return true.
684///
685bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohmandd96f722008-02-21 17:33:24 +0000686 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlin385bda62007-09-16 21:45:02 +0000687 unsigned i;
688
689 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
690 bi != N->PointsTo->end();
691 ++bi) {
692 i = *bi;
693 Node *Pointee = &GraphNodes[i];
694 if (Value *V = Pointee->getValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
696 !cast<GlobalVariable>(V)->isConstant()))
697 return AliasAnalysis::pointsToConstantMemory(P);
698 } else {
Daniel Berlin385bda62007-09-16 21:45:02 +0000699 if (i != NullObject)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 return AliasAnalysis::pointsToConstantMemory(P);
701 }
702 }
703
704 return true;
705}
706
707//===----------------------------------------------------------------------===//
708// Object Identification Phase
709//===----------------------------------------------------------------------===//
710
711/// IdentifyObjects - This stage scans the program, adding an entry to the
712/// GraphNodes list for each memory object in the program (global stack or
713/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
714///
715void Andersens::IdentifyObjects(Module &M) {
716 unsigned NumObjects = 0;
717
718 // Object #0 is always the universal set: the object that we don't know
719 // anything about.
720 assert(NumObjects == UniversalSet && "Something changed!");
721 ++NumObjects;
722
723 // Object #1 always represents the null pointer.
724 assert(NumObjects == NullPtr && "Something changed!");
725 ++NumObjects;
726
727 // Object #2 always represents the null object (the object pointed to by null)
728 assert(NumObjects == NullObject && "Something changed!");
729 ++NumObjects;
730
731 // Add all the globals first.
732 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
733 I != E; ++I) {
734 ObjectNodes[I] = NumObjects++;
735 ValueNodes[I] = NumObjects++;
736 }
737
738 // Add nodes for all of the functions and the instructions inside of them.
739 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
740 // The function itself is a memory object.
Daniel Berlin385bda62007-09-16 21:45:02 +0000741 unsigned First = NumObjects;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742 ValueNodes[F] = NumObjects++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
744 ReturnNodes[F] = NumObjects++;
745 if (F->getFunctionType()->isVarArg())
746 VarargNodes[F] = NumObjects++;
747
Daniel Berlin385bda62007-09-16 21:45:02 +0000748
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 // Add nodes for all of the incoming pointer arguments.
750 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
751 I != E; ++I)
Daniel Berlinb53270f2007-09-24 19:45:49 +0000752 {
753 if (isa<PointerType>(I->getType()))
754 ValueNodes[I] = NumObjects++;
755 }
Daniel Berlin385bda62007-09-16 21:45:02 +0000756 MaxK[First] = NumObjects - First;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757
758 // Scan the function body, creating a memory object for each heap/stack
759 // allocation in the body of the function and a node to represent all
760 // pointer values defined by instructions and used as operands.
761 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
762 // If this is an heap or stack allocation, create a node for the memory
763 // object.
764 if (isa<PointerType>(II->getType())) {
765 ValueNodes[&*II] = NumObjects++;
Victor Hernandezb1687302009-10-23 21:09:37 +0000766 if (AllocaInst *AI = dyn_cast<AllocaInst>(&*II))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 ObjectNodes[AI] = NumObjects++;
Victor Hernandez82f0ab62009-09-18 21:34:51 +0000768 else if (isMalloc(&*II))
769 ObjectNodes[&*II] = NumObjects++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 }
Nick Lewycky6b676da2007-11-22 03:07:37 +0000771
772 // Calls to inline asm need to be added as well because the callee isn't
773 // referenced anywhere else.
774 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
775 Value *Callee = CI->getCalledValue();
776 if (isa<InlineAsm>(Callee))
777 ValueNodes[Callee] = NumObjects++;
778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779 }
780 }
781
782 // Now that we know how many objects to create, make them all now!
783 GraphNodes.resize(NumObjects);
784 NumNodes += NumObjects;
785}
786
787//===----------------------------------------------------------------------===//
788// Constraint Identification Phase
789//===----------------------------------------------------------------------===//
790
791/// getNodeForConstantPointer - Return the node corresponding to the constant
792/// pointer itself.
Daniel Berlin385bda62007-09-16 21:45:02 +0000793unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
795
796 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlin385bda62007-09-16 21:45:02 +0000797 return NullPtr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
799 return getNode(GV);
800 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
801 switch (CE->getOpcode()) {
802 case Instruction::GetElementPtr:
803 return getNodeForConstantPointer(CE->getOperand(0));
804 case Instruction::IntToPtr:
Daniel Berlin385bda62007-09-16 21:45:02 +0000805 return UniversalSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806 case Instruction::BitCast:
807 return getNodeForConstantPointer(CE->getOperand(0));
808 default:
David Greene405d2a12009-12-23 23:14:41 +0000809 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000810 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 }
812 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +0000813 llvm_unreachable("Unknown constant pointer!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 }
815 return 0;
816}
817
818/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
819/// specified constant pointer.
Daniel Berlin385bda62007-09-16 21:45:02 +0000820unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
822
823 if (isa<ConstantPointerNull>(C))
Daniel Berlin385bda62007-09-16 21:45:02 +0000824 return NullObject;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
826 return getObject(GV);
827 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
828 switch (CE->getOpcode()) {
829 case Instruction::GetElementPtr:
830 return getNodeForConstantPointerTarget(CE->getOperand(0));
831 case Instruction::IntToPtr:
Daniel Berlin385bda62007-09-16 21:45:02 +0000832 return UniversalSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 case Instruction::BitCast:
834 return getNodeForConstantPointerTarget(CE->getOperand(0));
835 default:
David Greene405d2a12009-12-23 23:14:41 +0000836 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000837 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 }
839 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +0000840 llvm_unreachable("Unknown constant pointer!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 }
842 return 0;
843}
844
845/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
846/// object N, which contains values indicated by C.
Daniel Berlin385bda62007-09-16 21:45:02 +0000847void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
848 Constant *C) {
Dan Gohman1eb27e52008-05-22 23:43:22 +0000849 if (C->getType()->isSingleValueType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 if (isa<PointerType>(C->getType()))
Daniel Berlin385bda62007-09-16 21:45:02 +0000851 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
852 getNodeForConstantPointer(C)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 } else if (C->isNullValue()) {
Daniel Berlin385bda62007-09-16 21:45:02 +0000854 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
855 NullObject));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 return;
857 } else if (!isa<UndefValue>(C)) {
858 // If this is an array or struct, include constraints for each element.
859 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
860 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlin385bda62007-09-16 21:45:02 +0000861 AddGlobalInitializerConstraints(NodeIndex,
862 cast<Constant>(C->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 }
864}
865
866/// AddConstraintsForNonInternalLinkage - If this function does not have
867/// internal linkage, realize that we can't trust anything passed into or
868/// returned by this function.
869void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
870 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
871 if (isa<PointerType>(I->getType()))
872 // If this is an argument of an externally accessible function, the
873 // incoming pointer might point to anything.
874 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlin385bda62007-09-16 21:45:02 +0000875 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876}
877
878/// AddConstraintsForCall - If this is a call to a "known" function, add the
879/// constraints and return true. If this is a call to an unknown function,
880/// return false.
881bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
882 assert(F->isDeclaration() && "Not an external function!");
883
884 // These functions don't induce any points-to constraints.
885 if (F->getName() == "atoi" || F->getName() == "atof" ||
886 F->getName() == "atol" || F->getName() == "atoll" ||
887 F->getName() == "remove" || F->getName() == "unlink" ||
888 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner82c2e432008-11-21 16:42:48 +0000889 F->getName() == "llvm.memset" ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 F->getName() == "strcmp" || F->getName() == "strncmp" ||
891 F->getName() == "execl" || F->getName() == "execlp" ||
892 F->getName() == "execle" || F->getName() == "execv" ||
893 F->getName() == "execvp" || F->getName() == "chmod" ||
894 F->getName() == "puts" || F->getName() == "write" ||
895 F->getName() == "open" || F->getName() == "create" ||
896 F->getName() == "truncate" || F->getName() == "chdir" ||
897 F->getName() == "mkdir" || F->getName() == "rmdir" ||
898 F->getName() == "read" || F->getName() == "pipe" ||
899 F->getName() == "wait" || F->getName() == "time" ||
900 F->getName() == "stat" || F->getName() == "fstat" ||
901 F->getName() == "lstat" || F->getName() == "strtod" ||
902 F->getName() == "strtof" || F->getName() == "strtold" ||
903 F->getName() == "fopen" || F->getName() == "fdopen" ||
904 F->getName() == "freopen" ||
905 F->getName() == "fflush" || F->getName() == "feof" ||
906 F->getName() == "fileno" || F->getName() == "clearerr" ||
907 F->getName() == "rewind" || F->getName() == "ftell" ||
908 F->getName() == "ferror" || F->getName() == "fgetc" ||
909 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
910 F->getName() == "fwrite" || F->getName() == "fread" ||
911 F->getName() == "fgets" || F->getName() == "ungetc" ||
912 F->getName() == "fputc" ||
913 F->getName() == "fputs" || F->getName() == "putc" ||
914 F->getName() == "ftell" || F->getName() == "rewind" ||
915 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
916 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
917 F->getName() == "printf" || F->getName() == "fprintf" ||
918 F->getName() == "sprintf" || F->getName() == "vprintf" ||
919 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
920 F->getName() == "scanf" || F->getName() == "fscanf" ||
921 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
922 F->getName() == "modf")
923 return true;
924
925
926 // These functions do induce points-to edges.
Chris Lattner82c2e432008-11-21 16:42:48 +0000927 if (F->getName() == "llvm.memcpy" ||
928 F->getName() == "llvm.memmove" ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 F->getName() == "memmove") {
Daniel Berlin385bda62007-09-16 21:45:02 +0000930
Nick Lewycky047a53c2008-12-27 16:20:53 +0000931 const FunctionType *FTy = F->getFunctionType();
932 if (FTy->getNumParams() > 1 &&
933 isa<PointerType>(FTy->getParamType(0)) &&
934 isa<PointerType>(FTy->getParamType(1))) {
935
936 // *Dest = *Src, which requires an artificial graph node to represent the
937 // constraint. It is broken up into *Dest = temp, temp = *Src
938 unsigned FirstArg = getNode(CS.getArgument(0));
939 unsigned SecondArg = getNode(CS.getArgument(1));
940 unsigned TempArg = GraphNodes.size();
941 GraphNodes.push_back(Node());
942 Constraints.push_back(Constraint(Constraint::Store,
943 FirstArg, TempArg));
944 Constraints.push_back(Constraint(Constraint::Load,
945 TempArg, SecondArg));
946 // In addition, Dest = Src
947 Constraints.push_back(Constraint(Constraint::Copy,
948 FirstArg, SecondArg));
949 return true;
950 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 }
952
953 // Result = Arg0
954 if (F->getName() == "realloc" || F->getName() == "strchr" ||
955 F->getName() == "strrchr" || F->getName() == "strstr" ||
956 F->getName() == "strtok") {
Nick Lewycky047a53c2008-12-27 16:20:53 +0000957 const FunctionType *FTy = F->getFunctionType();
958 if (FTy->getNumParams() > 0 &&
959 isa<PointerType>(FTy->getParamType(0))) {
960 Constraints.push_back(Constraint(Constraint::Copy,
961 getNode(CS.getInstruction()),
962 getNode(CS.getArgument(0))));
963 return true;
964 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 }
966
967 return false;
968}
969
970
971
Daniel Berlin385bda62007-09-16 21:45:02 +0000972/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
973/// If this is used by anything complex (i.e., the address escapes), return
974/// true.
975bool Andersens::AnalyzeUsesOfFunction(Value *V) {
976
977 if (!isa<PointerType>(V->getType())) return true;
978
979 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Dan Gohman826edc52009-08-11 17:20:16 +0000980 if (isa<LoadInst>(*UI)) {
Daniel Berlin385bda62007-09-16 21:45:02 +0000981 return false;
982 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
983 if (V == SI->getOperand(1)) {
984 return false;
985 } else if (SI->getOperand(1)) {
986 return true; // Storing the pointer
987 }
988 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
989 if (AnalyzeUsesOfFunction(GEP)) return true;
Victor Hernandezf9a7a332009-10-26 23:43:48 +0000990 } else if (isFreeCall(*UI)) {
Victor Hernandez93946082009-10-24 04:23:03 +0000991 return false;
Daniel Berlin385bda62007-09-16 21:45:02 +0000992 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
993 // Make sure that this is just the function being called, not that it is
994 // passing into the function.
995 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
996 if (CI->getOperand(i) == V) return true;
997 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
998 // Make sure that this is just the function being called, not that it is
999 // passing into the function.
Gabor Greif5a6b6b42009-09-03 02:02:59 +00001000 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
Daniel Berlin385bda62007-09-16 21:45:02 +00001001 if (II->getOperand(i) == V) return true;
1002 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1003 if (CE->getOpcode() == Instruction::GetElementPtr ||
1004 CE->getOpcode() == Instruction::BitCast) {
1005 if (AnalyzeUsesOfFunction(CE))
1006 return true;
1007 } else {
1008 return true;
1009 }
1010 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1011 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1012 return true; // Allow comparison against null.
Daniel Berlin385bda62007-09-16 21:45:02 +00001013 } else {
1014 return true;
1015 }
1016 return false;
1017}
1018
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019/// CollectConstraints - This stage scans the program, adding a constraint to
1020/// the Constraints list for each instruction in the program that induces a
1021/// constraint, and setting up the initial points-to graph.
1022///
1023void Andersens::CollectConstraints(Module &M) {
1024 // First, the universal set points to itself.
Daniel Berlin385bda62007-09-16 21:45:02 +00001025 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1026 UniversalSet));
1027 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1028 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029
1030 // Next, the null pointer points to the null object.
Daniel Berlin385bda62007-09-16 21:45:02 +00001031 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032
1033 // Next, add any constraints on global variables and their initializers.
1034 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1035 I != E; ++I) {
1036 // Associate the address of the global object as pointing to the memory for
1037 // the global: &G = <G memory>
Daniel Berlin385bda62007-09-16 21:45:02 +00001038 unsigned ObjectIndex = getObject(I);
1039 Node *Object = &GraphNodes[ObjectIndex];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 Object->setValue(I);
Daniel Berlin385bda62007-09-16 21:45:02 +00001041 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1042 ObjectIndex));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043
Dan Gohman5e423ed2009-08-19 18:20:44 +00001044 if (I->hasDefinitiveInitializer()) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001045 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046 } else {
1047 // If it doesn't have an initializer (i.e. it's defined in another
1048 // translation unit), it points to the universal set.
Daniel Berlin385bda62007-09-16 21:45:02 +00001049 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1050 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 }
1052 }
1053
1054 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 // Set up the return value node.
1056 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlin385bda62007-09-16 21:45:02 +00001057 GraphNodes[getReturnNode(F)].setValue(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 if (F->getFunctionType()->isVarArg())
Daniel Berlin385bda62007-09-16 21:45:02 +00001059 GraphNodes[getVarargNode(F)].setValue(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060
1061 // Set up incoming argument nodes.
1062 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1063 I != E; ++I)
1064 if (isa<PointerType>(I->getType()))
1065 getNodeValue(*I);
1066
Daniel Berlin385bda62007-09-16 21:45:02 +00001067 // At some point we should just add constraints for the escaping functions
1068 // at solve time, but this slows down solving. For now, we simply mark
1069 // address taken functions as escaping and treat them as external.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001070 if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 AddConstraintsForNonInternalLinkage(F);
1072
1073 if (!F->isDeclaration()) {
1074 // Scan the function body, creating a memory object for each heap/stack
1075 // allocation in the body of the function and a node to represent all
1076 // pointer values defined by instructions and used as operands.
1077 visit(F);
1078 } else {
1079 // External functions that return pointers return the universal set.
1080 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1081 Constraints.push_back(Constraint(Constraint::Copy,
1082 getReturnNode(F),
Daniel Berlin385bda62007-09-16 21:45:02 +00001083 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084
1085 // Any pointers that are passed into the function have the universal set
1086 // stored into them.
1087 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1088 I != E; ++I)
1089 if (isa<PointerType>(I->getType())) {
1090 // Pointers passed into external functions could have anything stored
1091 // through them.
1092 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlin385bda62007-09-16 21:45:02 +00001093 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 // Memory objects passed into external function calls can have the
1095 // universal set point to them.
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001096#if FULL_UNIVERSAL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlin385bda62007-09-16 21:45:02 +00001098 UniversalSet,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 getNode(I)));
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001100#else
1101 Constraints.push_back(Constraint(Constraint::Copy,
1102 getNode(I),
1103 UniversalSet));
1104#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 }
1106
1107 // If this is an external varargs function, it can also store pointers
1108 // into any pointers passed through the varargs section.
1109 if (F->getFunctionType()->isVarArg())
1110 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlin385bda62007-09-16 21:45:02 +00001111 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112 }
1113 }
1114 NumConstraints += Constraints.size();
1115}
1116
1117
1118void Andersens::visitInstruction(Instruction &I) {
1119#ifdef NDEBUG
1120 return; // This function is just a big assert.
1121#endif
1122 if (isa<BinaryOperator>(I))
1123 return;
1124 // Most instructions don't have any effect on pointer values.
1125 switch (I.getOpcode()) {
1126 case Instruction::Br:
1127 case Instruction::Switch:
1128 case Instruction::Unwind:
1129 case Instruction::Unreachable:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 case Instruction::ICmp:
1131 case Instruction::FCmp:
1132 return;
1133 default:
1134 // Is this something we aren't handling yet?
David Greene405d2a12009-12-23 23:14:41 +00001135 errs() << "Unknown instruction: " << I;
Edwin Törökbd448e32009-07-14 16:55:14 +00001136 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 }
1138}
1139
Victor Hernandezb1687302009-10-23 21:09:37 +00001140void Andersens::visitAllocaInst(AllocaInst &I) {
1141 visitAlloc(I);
1142}
1143
1144void Andersens::visitAlloc(Instruction &I) {
Victor Hernandez82f0ab62009-09-18 21:34:51 +00001145 unsigned ObjectIndex = getObject(&I);
1146 GraphNodes[ObjectIndex].setValue(&I);
1147 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(I),
Daniel Berlin385bda62007-09-16 21:45:02 +00001148 ObjectIndex));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149}
1150
1151void Andersens::visitReturnInst(ReturnInst &RI) {
1152 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1153 // return V --> <Copy/retval{F}/v>
1154 Constraints.push_back(Constraint(Constraint::Copy,
1155 getReturnNode(RI.getParent()->getParent()),
1156 getNode(RI.getOperand(0))));
1157}
1158
1159void Andersens::visitLoadInst(LoadInst &LI) {
1160 if (isa<PointerType>(LI.getType()))
1161 // P1 = load P2 --> <Load/P1/P2>
1162 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1163 getNode(LI.getOperand(0))));
1164}
1165
1166void Andersens::visitStoreInst(StoreInst &SI) {
1167 if (isa<PointerType>(SI.getOperand(0)->getType()))
1168 // store P1, P2 --> <Store/P2/P1>
1169 Constraints.push_back(Constraint(Constraint::Store,
1170 getNode(SI.getOperand(1)),
1171 getNode(SI.getOperand(0))));
1172}
1173
1174void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1175 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1176 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1177 getNode(GEP.getOperand(0))));
1178}
1179
1180void Andersens::visitPHINode(PHINode &PN) {
1181 if (isa<PointerType>(PN.getType())) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001182 unsigned PNN = getNodeValue(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1184 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1185 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1186 getNode(PN.getIncomingValue(i))));
1187 }
1188}
1189
1190void Andersens::visitCastInst(CastInst &CI) {
1191 Value *Op = CI.getOperand(0);
1192 if (isa<PointerType>(CI.getType())) {
1193 if (isa<PointerType>(Op->getType())) {
1194 // P1 = cast P2 --> <Copy/P1/P2>
1195 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1196 getNode(CI.getOperand(0))));
1197 } else {
1198 // P1 = cast int --> <Copy/P1/Univ>
1199#if 0
1200 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlin385bda62007-09-16 21:45:02 +00001201 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202#else
1203 getNodeValue(CI);
1204#endif
1205 }
1206 } else if (isa<PointerType>(Op->getType())) {
1207 // int = cast P1 --> <Copy/Univ/P1>
1208#if 0
1209 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlin385bda62007-09-16 21:45:02 +00001210 UniversalSet,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 getNode(CI.getOperand(0))));
1212#else
1213 getNode(CI.getOperand(0));
1214#endif
1215 }
1216}
1217
1218void Andersens::visitSelectInst(SelectInst &SI) {
1219 if (isa<PointerType>(SI.getType())) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001220 unsigned SIN = getNodeValue(SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1222 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1223 getNode(SI.getOperand(1))));
1224 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1225 getNode(SI.getOperand(2))));
1226 }
1227}
1228
1229void Andersens::visitVAArg(VAArgInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001230 llvm_unreachable("vaarg not handled yet!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231}
1232
1233/// AddConstraintsForCall - Add constraints for a call with actual arguments
1234/// specified by CS to the function specified by F. Note that the types of
1235/// arguments might not match up in the case where this is an indirect call and
1236/// the function pointer has been casted. If this is the case, do something
1237/// reasonable.
1238void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001239 Value *CallValue = CS.getCalledValue();
1240 bool IsDeref = F == NULL;
1241
1242 // If this is a call to an external function, try to handle it directly to get
1243 // some taste of context sensitivity.
1244 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 return;
1246
1247 if (isa<PointerType>(CS.getType())) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001248 unsigned CSN = getNode(CS.getInstruction());
1249 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1250 if (IsDeref)
1251 Constraints.push_back(Constraint(Constraint::Load, CSN,
1252 getNode(CallValue), CallReturnPos));
1253 else
1254 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1255 getNode(CallValue) + CallReturnPos));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 } else {
1257 // If the function returns a non-pointer value, handle this just like we
1258 // treat a nonpointer cast to pointer.
1259 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlin385bda62007-09-16 21:45:02 +00001260 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001261 }
Daniel Berlin385bda62007-09-16 21:45:02 +00001262 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001263#if FULL_UNIVERSAL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlin385bda62007-09-16 21:45:02 +00001265 UniversalSet,
1266 getNode(CallValue) + CallReturnPos));
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001267#else
1268 Constraints.push_back(Constraint(Constraint::Copy,
1269 getNode(CallValue) + CallReturnPos,
1270 UniversalSet));
1271#endif
1272
1273
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 }
1275
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinb68539d2008-03-18 22:22:53 +00001277 bool external = !F || F->isDeclaration();
Daniel Berlin385bda62007-09-16 21:45:02 +00001278 if (F) {
1279 // Direct Call
1280 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlinb68539d2008-03-18 22:22:53 +00001281 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1282 {
1283#if !FULL_UNIVERSAL
1284 if (external && isa<PointerType>((*ArgI)->getType()))
1285 {
1286 // Add constraint that ArgI can now point to anything due to
1287 // escaping, as can everything it points to. The second portion of
1288 // this should be taken care of by universal = *universal
1289 Constraints.push_back(Constraint(Constraint::Copy,
1290 getNode(*ArgI),
1291 UniversalSet));
1292 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001293#endif
Daniel Berlinb68539d2008-03-18 22:22:53 +00001294 if (isa<PointerType>(AI->getType())) {
1295 if (isa<PointerType>((*ArgI)->getType())) {
1296 // Copy the actual argument into the formal argument.
1297 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1298 getNode(*ArgI)));
1299 } else {
1300 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1301 UniversalSet));
1302 }
1303 } else if (isa<PointerType>((*ArgI)->getType())) {
1304#if FULL_UNIVERSAL
1305 Constraints.push_back(Constraint(Constraint::Copy,
1306 UniversalSet,
1307 getNode(*ArgI)));
1308#else
1309 Constraints.push_back(Constraint(Constraint::Copy,
1310 getNode(*ArgI),
1311 UniversalSet));
1312#endif
1313 }
Daniel Berlin385bda62007-09-16 21:45:02 +00001314 }
1315 } else {
1316 //Indirect Call
1317 unsigned ArgPos = CallFirstArgPos;
1318 for (; ArgI != ArgE; ++ArgI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 if (isa<PointerType>((*ArgI)->getType())) {
1320 // Copy the actual argument into the formal argument.
Daniel Berlin385bda62007-09-16 21:45:02 +00001321 Constraints.push_back(Constraint(Constraint::Store,
1322 getNode(CallValue),
1323 getNode(*ArgI), ArgPos++));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 } else {
Daniel Berlin385bda62007-09-16 21:45:02 +00001325 Constraints.push_back(Constraint(Constraint::Store,
1326 getNode (CallValue),
1327 UniversalSet, ArgPos++));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 }
Daniel Berlin385bda62007-09-16 21:45:02 +00001330 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlin385bda62007-09-16 21:45:02 +00001332 if (F && F->getFunctionType()->isVarArg())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 for (; ArgI != ArgE; ++ArgI)
1334 if (isa<PointerType>((*ArgI)->getType()))
1335 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1336 getNode(*ArgI)));
1337 // If more arguments are passed in than we track, just drop them on the floor.
1338}
1339
1340void Andersens::visitCallSite(CallSite CS) {
1341 if (isa<PointerType>(CS.getType()))
1342 getNodeValue(*CS.getInstruction());
1343
1344 if (Function *F = CS.getCalledFunction()) {
1345 AddConstraintsForCall(CS, F);
1346 } else {
Daniel Berlin385bda62007-09-16 21:45:02 +00001347 AddConstraintsForCall(CS, NULL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001348 }
1349}
1350
1351//===----------------------------------------------------------------------===//
1352// Constraint Solving Phase
1353//===----------------------------------------------------------------------===//
1354
1355/// intersects - Return true if the points-to set of this node intersects
1356/// with the points-to set of the specified node.
1357bool Andersens::Node::intersects(Node *N) const {
Daniel Berlin385bda62007-09-16 21:45:02 +00001358 return PointsTo->intersects(N->PointsTo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359}
1360
1361/// intersectsIgnoring - Return true if the points-to set of this node
1362/// intersects with the points-to set of the specified node on any nodes
1363/// except for the specified node to ignore.
Daniel Berlin385bda62007-09-16 21:45:02 +00001364bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1365 // TODO: If we are only going to call this with the same value for Ignoring,
1366 // we should move the special values out of the points-to bitmap.
1367 bool WeHadIt = PointsTo->test(Ignoring);
1368 bool NHadIt = N->PointsTo->test(Ignoring);
1369 bool Result = false;
1370 if (WeHadIt)
1371 PointsTo->reset(Ignoring);
1372 if (NHadIt)
1373 N->PointsTo->reset(Ignoring);
1374 Result = PointsTo->intersects(N->PointsTo);
1375 if (WeHadIt)
1376 PointsTo->set(Ignoring);
1377 if (NHadIt)
1378 N->PointsTo->set(Ignoring);
1379 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380}
1381
Daniel Berlinb53270f2007-09-24 19:45:49 +00001382
1383/// Clump together address taken variables so that the points-to sets use up
1384/// less space and can be operated on faster.
1385
1386void Andersens::ClumpAddressTaken() {
1387#undef DEBUG_TYPE
1388#define DEBUG_TYPE "anders-aa-renumber"
1389 std::vector<unsigned> Translate;
1390 std::vector<Node> NewGraphNodes;
1391
1392 Translate.resize(GraphNodes.size());
1393 unsigned NewPos = 0;
1394
1395 for (unsigned i = 0; i < Constraints.size(); ++i) {
1396 Constraint &C = Constraints[i];
1397 if (C.Type == Constraint::AddressOf) {
1398 GraphNodes[C.Src].AddressTaken = true;
1399 }
1400 }
1401 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1402 unsigned Pos = NewPos++;
1403 Translate[i] = Pos;
1404 NewGraphNodes.push_back(GraphNodes[i]);
David Greene7c553e02009-12-23 19:51:44 +00001405 DEBUG(dbgs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001406 }
1407
1408 // I believe this ends up being faster than making two vectors and splicing
1409 // them.
1410 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1411 if (GraphNodes[i].AddressTaken) {
1412 unsigned Pos = NewPos++;
1413 Translate[i] = Pos;
1414 NewGraphNodes.push_back(GraphNodes[i]);
David Greene7c553e02009-12-23 19:51:44 +00001415 DEBUG(dbgs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001416 }
1417 }
1418
1419 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1420 if (!GraphNodes[i].AddressTaken) {
1421 unsigned Pos = NewPos++;
1422 Translate[i] = Pos;
1423 NewGraphNodes.push_back(GraphNodes[i]);
David Greene7c553e02009-12-23 19:51:44 +00001424 DEBUG(dbgs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001425 }
1426 }
1427
1428 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1429 Iter != ValueNodes.end();
1430 ++Iter)
1431 Iter->second = Translate[Iter->second];
1432
1433 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1434 Iter != ObjectNodes.end();
1435 ++Iter)
1436 Iter->second = Translate[Iter->second];
1437
1438 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1439 Iter != ReturnNodes.end();
1440 ++Iter)
1441 Iter->second = Translate[Iter->second];
1442
1443 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1444 Iter != VarargNodes.end();
1445 ++Iter)
1446 Iter->second = Translate[Iter->second];
1447
1448 for (unsigned i = 0; i < Constraints.size(); ++i) {
1449 Constraint &C = Constraints[i];
1450 C.Src = Translate[C.Src];
1451 C.Dest = Translate[C.Dest];
1452 }
1453
1454 GraphNodes.swap(NewGraphNodes);
1455#undef DEBUG_TYPE
1456#define DEBUG_TYPE "anders-aa"
1457}
1458
1459/// The technique used here is described in "Exploiting Pointer and Location
1460/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1461/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1462/// and is equivalent to value numbering the collapsed constraint graph without
1463/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1464/// first order pointer dereferences and speed up/reduce memory usage of HU.
1465/// Running both is equivalent to HRU without the iteration
1466/// HVN in more detail:
1467/// Imagine the set of constraints was simply straight line code with no loops
1468/// (we eliminate cycles, so there are no loops), such as:
1469/// E = &D
1470/// E = &C
1471/// E = F
1472/// F = G
1473/// G = F
1474/// Applying value numbering to this code tells us:
1475/// G == F == E
1476///
1477/// For HVN, this is as far as it goes. We assign new value numbers to every
1478/// "address node", and every "reference node".
1479/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1480/// cycle must have the same value number since the = operation is really
1481/// inclusion, not overwrite), and value number nodes we receive points-to sets
1482/// before we value our own node.
1483/// The advantage of HU over HVN is that HU considers the inclusion property, so
1484/// that if you have
1485/// E = &D
1486/// E = &C
1487/// E = F
1488/// F = G
1489/// F = &D
1490/// G = F
1491/// HU will determine that G == F == E. HVN will not, because it cannot prove
1492/// that the points to information ends up being the same because they all
1493/// receive &D from E anyway.
1494
1495void Andersens::HVN() {
David Greene7c553e02009-12-23 19:51:44 +00001496 DEBUG(dbgs() << "Beginning HVN\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001497 // Build a predecessor graph. This is like our constraint graph with the
1498 // edges going in the opposite direction, and there are edges for all the
1499 // constraints, instead of just copy constraints. We also build implicit
1500 // edges for constraints are implied but not explicit. I.E for the constraint
1501 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1502 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1503 Constraint &C = Constraints[i];
1504 if (C.Type == Constraint::AddressOf) {
1505 GraphNodes[C.Src].AddressTaken = true;
1506 GraphNodes[C.Src].Direct = false;
1507
1508 // Dest = &src edge
1509 unsigned AdrNode = C.Src + FirstAdrNode;
1510 if (!GraphNodes[C.Dest].PredEdges)
1511 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1512 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1513
1514 // *Dest = src edge
1515 unsigned RefNode = C.Dest + FirstRefNode;
1516 if (!GraphNodes[RefNode].ImplicitPredEdges)
1517 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1518 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1519 } else if (C.Type == Constraint::Load) {
1520 if (C.Offset == 0) {
1521 // dest = *src edge
1522 if (!GraphNodes[C.Dest].PredEdges)
1523 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1524 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1525 } else {
1526 GraphNodes[C.Dest].Direct = false;
1527 }
1528 } else if (C.Type == Constraint::Store) {
1529 if (C.Offset == 0) {
1530 // *dest = src edge
1531 unsigned RefNode = C.Dest + FirstRefNode;
1532 if (!GraphNodes[RefNode].PredEdges)
1533 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1534 GraphNodes[RefNode].PredEdges->set(C.Src);
1535 }
1536 } else {
1537 // Dest = Src edge and *Dest = *Src edge
1538 if (!GraphNodes[C.Dest].PredEdges)
1539 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1540 GraphNodes[C.Dest].PredEdges->set(C.Src);
1541 unsigned RefNode = C.Dest + FirstRefNode;
1542 if (!GraphNodes[RefNode].ImplicitPredEdges)
1543 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1544 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1545 }
1546 }
1547 PEClass = 1;
1548 // Do SCC finding first to condense our predecessor graph
1549 DFSNumber = 0;
1550 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1551 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1552 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1553
1554 for (unsigned i = 0; i < FirstRefNode; ++i) {
1555 unsigned Node = VSSCCRep[i];
1556 if (!Node2Visited[Node])
1557 HVNValNum(Node);
1558 }
1559 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1560 Iter != Set2PEClass.end();
1561 ++Iter)
1562 delete Iter->first;
1563 Set2PEClass.clear();
1564 Node2DFS.clear();
1565 Node2Deleted.clear();
1566 Node2Visited.clear();
David Greene7c553e02009-12-23 19:51:44 +00001567 DEBUG(dbgs() << "Finished HVN\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001568
1569}
1570
1571/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1572/// same time because it's easy.
1573void Andersens::HVNValNum(unsigned NodeIndex) {
1574 unsigned MyDFS = DFSNumber++;
1575 Node *N = &GraphNodes[NodeIndex];
1576 Node2Visited[NodeIndex] = true;
1577 Node2DFS[NodeIndex] = MyDFS;
1578
1579 // First process all our explicit edges
1580 if (N->PredEdges)
1581 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1582 Iter != N->PredEdges->end();
1583 ++Iter) {
1584 unsigned j = VSSCCRep[*Iter];
1585 if (!Node2Deleted[j]) {
1586 if (!Node2Visited[j])
1587 HVNValNum(j);
1588 if (Node2DFS[NodeIndex] > Node2DFS[j])
1589 Node2DFS[NodeIndex] = Node2DFS[j];
1590 }
1591 }
1592
1593 // Now process all the implicit edges
1594 if (N->ImplicitPredEdges)
1595 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1596 Iter != N->ImplicitPredEdges->end();
1597 ++Iter) {
1598 unsigned j = VSSCCRep[*Iter];
1599 if (!Node2Deleted[j]) {
1600 if (!Node2Visited[j])
1601 HVNValNum(j);
1602 if (Node2DFS[NodeIndex] > Node2DFS[j])
1603 Node2DFS[NodeIndex] = Node2DFS[j];
1604 }
1605 }
1606
1607 // See if we found any cycles
1608 if (MyDFS == Node2DFS[NodeIndex]) {
1609 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1610 unsigned CycleNodeIndex = SCCStack.top();
1611 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1612 VSSCCRep[CycleNodeIndex] = NodeIndex;
1613 // Unify the nodes
1614 N->Direct &= CycleNode->Direct;
1615
1616 if (CycleNode->PredEdges) {
1617 if (!N->PredEdges)
1618 N->PredEdges = new SparseBitVector<>;
1619 *(N->PredEdges) |= CycleNode->PredEdges;
1620 delete CycleNode->PredEdges;
1621 CycleNode->PredEdges = NULL;
1622 }
1623 if (CycleNode->ImplicitPredEdges) {
1624 if (!N->ImplicitPredEdges)
1625 N->ImplicitPredEdges = new SparseBitVector<>;
1626 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1627 delete CycleNode->ImplicitPredEdges;
1628 CycleNode->ImplicitPredEdges = NULL;
1629 }
1630
1631 SCCStack.pop();
1632 }
1633
1634 Node2Deleted[NodeIndex] = true;
1635
1636 if (!N->Direct) {
1637 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1638 return;
1639 }
1640
1641 // Collect labels of successor nodes
1642 bool AllSame = true;
1643 unsigned First = ~0;
1644 SparseBitVector<> *Labels = new SparseBitVector<>;
1645 bool Used = false;
1646
1647 if (N->PredEdges)
1648 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1649 Iter != N->PredEdges->end();
1650 ++Iter) {
1651 unsigned j = VSSCCRep[*Iter];
1652 unsigned Label = GraphNodes[j].PointerEquivLabel;
1653 // Ignore labels that are equal to us or non-pointers
1654 if (j == NodeIndex || Label == 0)
1655 continue;
1656 if (First == (unsigned)~0)
1657 First = Label;
1658 else if (First != Label)
1659 AllSame = false;
1660 Labels->set(Label);
1661 }
1662
1663 // We either have a non-pointer, a copy of an existing node, or a new node.
1664 // Assign the appropriate pointer equivalence label.
1665 if (Labels->empty()) {
1666 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1667 } else if (AllSame) {
1668 GraphNodes[NodeIndex].PointerEquivLabel = First;
1669 } else {
1670 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1671 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1672 unsigned EquivClass = PEClass++;
1673 Set2PEClass[Labels] = EquivClass;
1674 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1675 Used = true;
1676 }
1677 }
1678 if (!Used)
1679 delete Labels;
1680 } else {
1681 SCCStack.push(NodeIndex);
1682 }
1683}
1684
1685/// The technique used here is described in "Exploiting Pointer and Location
1686/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1687/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1688/// and is equivalent to value numbering the collapsed constraint graph
1689/// including evaluating unions.
1690void Andersens::HU() {
David Greene7c553e02009-12-23 19:51:44 +00001691 DEBUG(dbgs() << "Beginning HU\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001692 // Build a predecessor graph. This is like our constraint graph with the
1693 // edges going in the opposite direction, and there are edges for all the
1694 // constraints, instead of just copy constraints. We also build implicit
1695 // edges for constraints are implied but not explicit. I.E for the constraint
1696 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1697 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1698 Constraint &C = Constraints[i];
1699 if (C.Type == Constraint::AddressOf) {
1700 GraphNodes[C.Src].AddressTaken = true;
1701 GraphNodes[C.Src].Direct = false;
1702
1703 GraphNodes[C.Dest].PointsTo->set(C.Src);
1704 // *Dest = src edge
1705 unsigned RefNode = C.Dest + FirstRefNode;
1706 if (!GraphNodes[RefNode].ImplicitPredEdges)
1707 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1708 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1709 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1710 } else if (C.Type == Constraint::Load) {
1711 if (C.Offset == 0) {
1712 // dest = *src edge
1713 if (!GraphNodes[C.Dest].PredEdges)
1714 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1715 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1716 } else {
1717 GraphNodes[C.Dest].Direct = false;
1718 }
1719 } else if (C.Type == Constraint::Store) {
1720 if (C.Offset == 0) {
1721 // *dest = src edge
1722 unsigned RefNode = C.Dest + FirstRefNode;
1723 if (!GraphNodes[RefNode].PredEdges)
1724 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1725 GraphNodes[RefNode].PredEdges->set(C.Src);
1726 }
1727 } else {
1728 // Dest = Src edge and *Dest = *Src edg
1729 if (!GraphNodes[C.Dest].PredEdges)
1730 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1731 GraphNodes[C.Dest].PredEdges->set(C.Src);
1732 unsigned RefNode = C.Dest + FirstRefNode;
1733 if (!GraphNodes[RefNode].ImplicitPredEdges)
1734 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1735 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1736 }
1737 }
1738 PEClass = 1;
1739 // Do SCC finding first to condense our predecessor graph
1740 DFSNumber = 0;
1741 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1742 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1743 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1744
1745 for (unsigned i = 0; i < FirstRefNode; ++i) {
1746 if (FindNode(i) == i) {
1747 unsigned Node = VSSCCRep[i];
1748 if (!Node2Visited[Node])
1749 Condense(Node);
1750 }
1751 }
1752
1753 // Reset tables for actual labeling
1754 Node2DFS.clear();
1755 Node2Visited.clear();
1756 Node2Deleted.clear();
1757 // Pre-grow our densemap so that we don't get really bad behavior
1758 Set2PEClass.resize(GraphNodes.size());
1759
1760 // Visit the condensed graph and generate pointer equivalence labels.
1761 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1762 for (unsigned i = 0; i < FirstRefNode; ++i) {
1763 if (FindNode(i) == i) {
1764 unsigned Node = VSSCCRep[i];
1765 if (!Node2Visited[Node])
1766 HUValNum(Node);
1767 }
1768 }
1769 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1770 Set2PEClass.clear();
David Greene7c553e02009-12-23 19:51:44 +00001771 DEBUG(dbgs() << "Finished HU\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001772}
1773
1774
1775/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1776void Andersens::Condense(unsigned NodeIndex) {
1777 unsigned MyDFS = DFSNumber++;
1778 Node *N = &GraphNodes[NodeIndex];
1779 Node2Visited[NodeIndex] = true;
1780 Node2DFS[NodeIndex] = MyDFS;
1781
1782 // First process all our explicit edges
1783 if (N->PredEdges)
1784 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1785 Iter != N->PredEdges->end();
1786 ++Iter) {
1787 unsigned j = VSSCCRep[*Iter];
1788 if (!Node2Deleted[j]) {
1789 if (!Node2Visited[j])
1790 Condense(j);
1791 if (Node2DFS[NodeIndex] > Node2DFS[j])
1792 Node2DFS[NodeIndex] = Node2DFS[j];
1793 }
1794 }
1795
1796 // Now process all the implicit edges
1797 if (N->ImplicitPredEdges)
1798 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1799 Iter != N->ImplicitPredEdges->end();
1800 ++Iter) {
1801 unsigned j = VSSCCRep[*Iter];
1802 if (!Node2Deleted[j]) {
1803 if (!Node2Visited[j])
1804 Condense(j);
1805 if (Node2DFS[NodeIndex] > Node2DFS[j])
1806 Node2DFS[NodeIndex] = Node2DFS[j];
1807 }
1808 }
1809
1810 // See if we found any cycles
1811 if (MyDFS == Node2DFS[NodeIndex]) {
1812 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1813 unsigned CycleNodeIndex = SCCStack.top();
1814 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1815 VSSCCRep[CycleNodeIndex] = NodeIndex;
1816 // Unify the nodes
1817 N->Direct &= CycleNode->Direct;
1818
1819 *(N->PointsTo) |= CycleNode->PointsTo;
1820 delete CycleNode->PointsTo;
1821 CycleNode->PointsTo = NULL;
1822 if (CycleNode->PredEdges) {
1823 if (!N->PredEdges)
1824 N->PredEdges = new SparseBitVector<>;
1825 *(N->PredEdges) |= CycleNode->PredEdges;
1826 delete CycleNode->PredEdges;
1827 CycleNode->PredEdges = NULL;
1828 }
1829 if (CycleNode->ImplicitPredEdges) {
1830 if (!N->ImplicitPredEdges)
1831 N->ImplicitPredEdges = new SparseBitVector<>;
1832 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1833 delete CycleNode->ImplicitPredEdges;
1834 CycleNode->ImplicitPredEdges = NULL;
1835 }
1836 SCCStack.pop();
1837 }
1838
1839 Node2Deleted[NodeIndex] = true;
1840
1841 // Set up number of incoming edges for other nodes
1842 if (N->PredEdges)
1843 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1844 Iter != N->PredEdges->end();
1845 ++Iter)
1846 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1847 } else {
1848 SCCStack.push(NodeIndex);
1849 }
1850}
1851
1852void Andersens::HUValNum(unsigned NodeIndex) {
1853 Node *N = &GraphNodes[NodeIndex];
1854 Node2Visited[NodeIndex] = true;
1855
1856 // Eliminate dereferences of non-pointers for those non-pointers we have
1857 // already identified. These are ref nodes whose non-ref node:
1858 // 1. Has already been visited determined to point to nothing (and thus, a
1859 // dereference of it must point to nothing)
1860 // 2. Any direct node with no predecessor edges in our graph and with no
1861 // points-to set (since it can't point to anything either, being that it
1862 // receives no points-to sets and has none).
1863 if (NodeIndex >= FirstRefNode) {
1864 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1865 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1866 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1867 && GraphNodes[j].PointsTo->empty())){
1868 return;
1869 }
1870 }
1871 // Process all our explicit edges
1872 if (N->PredEdges)
1873 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1874 Iter != N->PredEdges->end();
1875 ++Iter) {
1876 unsigned j = VSSCCRep[*Iter];
1877 if (!Node2Visited[j])
1878 HUValNum(j);
1879
1880 // If this edge turned out to be the same as us, or got no pointer
1881 // equivalence label (and thus points to nothing) , just decrement our
1882 // incoming edges and continue.
1883 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1884 --GraphNodes[j].NumInEdges;
1885 continue;
1886 }
1887
1888 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1889
1890 // If we didn't end up storing this in the hash, and we're done with all
1891 // the edges, we don't need the points-to set anymore.
1892 --GraphNodes[j].NumInEdges;
1893 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1894 delete GraphNodes[j].PointsTo;
1895 GraphNodes[j].PointsTo = NULL;
1896 }
1897 }
1898 // If this isn't a direct node, generate a fresh variable.
1899 if (!N->Direct) {
1900 N->PointsTo->set(FirstRefNode + NodeIndex);
1901 }
1902
1903 // See If we have something equivalent to us, if not, generate a new
1904 // equivalence class.
1905 if (N->PointsTo->empty()) {
1906 delete N->PointsTo;
1907 N->PointsTo = NULL;
1908 } else {
1909 if (N->Direct) {
1910 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1911 if (N->PointerEquivLabel == 0) {
1912 unsigned EquivClass = PEClass++;
1913 N->StoredInHash = true;
1914 Set2PEClass[N->PointsTo] = EquivClass;
1915 N->PointerEquivLabel = EquivClass;
1916 }
1917 } else {
1918 N->PointerEquivLabel = PEClass++;
1919 }
1920 }
1921}
1922
1923/// Rewrite our list of constraints so that pointer equivalent nodes are
1924/// replaced by their the pointer equivalence class representative.
1925void Andersens::RewriteConstraints() {
1926 std::vector<Constraint> NewConstraints;
Chris Lattner4cf3c502007-09-30 00:47:20 +00001927 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlinb53270f2007-09-24 19:45:49 +00001928
1929 PEClass2Node.clear();
1930 PENLEClass2Node.clear();
1931
1932 // We may have from 1 to Graphnodes + 1 equivalence classes.
1933 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1934 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1935
1936 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1937 // nodes, and rewriting constraints to use the representative nodes.
1938 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1939 Constraint &C = Constraints[i];
1940 unsigned RHSNode = FindNode(C.Src);
1941 unsigned LHSNode = FindNode(C.Dest);
1942 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1943 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1944
1945 // First we try to eliminate constraints for things we can prove don't point
1946 // to anything.
1947 if (LHSLabel == 0) {
1948 DEBUG(PrintNode(&GraphNodes[LHSNode]));
David Greene7c553e02009-12-23 19:51:44 +00001949 DEBUG(dbgs() << " is a non-pointer, ignoring constraint.\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001950 continue;
1951 }
1952 if (RHSLabel == 0) {
1953 DEBUG(PrintNode(&GraphNodes[RHSNode]));
David Greene7c553e02009-12-23 19:51:44 +00001954 DEBUG(dbgs() << " is a non-pointer, ignoring constraint.\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00001955 continue;
1956 }
1957 // This constraint may be useless, and it may become useless as we translate
1958 // it.
1959 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1960 continue;
Daniel Berline87fe282007-09-27 15:42:23 +00001961
Daniel Berlinb53270f2007-09-24 19:45:49 +00001962 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1963 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00001964 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattner4cf3c502007-09-30 00:47:20 +00001965 || Seen.count(C))
Daniel Berlinb53270f2007-09-24 19:45:49 +00001966 continue;
1967
Chris Lattner4cf3c502007-09-30 00:47:20 +00001968 Seen.insert(C);
Daniel Berlinb53270f2007-09-24 19:45:49 +00001969 NewConstraints.push_back(C);
1970 }
1971 Constraints.swap(NewConstraints);
1972 PEClass2Node.clear();
1973}
1974
1975/// See if we have a node that is pointer equivalent to the one being asked
1976/// about, and if so, unite them and return the equivalent node. Otherwise,
1977/// return the original node.
1978unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1979 unsigned NodeLabel) {
1980 if (!GraphNodes[NodeIndex].AddressTaken) {
1981 if (PEClass2Node[NodeLabel] != -1) {
1982 // We found an existing node with the same pointer label, so unify them.
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001983 // We specifically request that Union-By-Rank not be used so that
1984 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1985 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlinb53270f2007-09-24 19:45:49 +00001986 } else {
1987 PEClass2Node[NodeLabel] = NodeIndex;
1988 PENLEClass2Node[NodeLabel] = NodeIndex;
1989 }
1990 } else if (PENLEClass2Node[NodeLabel] == -1) {
1991 PENLEClass2Node[NodeLabel] = NodeIndex;
1992 }
1993
1994 return NodeIndex;
1995}
1996
Andrew Lenharthdce39302008-03-20 15:36:44 +00001997void Andersens::PrintLabels() const {
Daniel Berlinb53270f2007-09-24 19:45:49 +00001998 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1999 if (i < FirstRefNode) {
2000 PrintNode(&GraphNodes[i]);
2001 } else if (i < FirstAdrNode) {
David Greene7c553e02009-12-23 19:51:44 +00002002 DEBUG(dbgs() << "REF(");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002003 PrintNode(&GraphNodes[i-FirstRefNode]);
David Greene7c553e02009-12-23 19:51:44 +00002004 DEBUG(dbgs() <<")");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002005 } else {
David Greene7c553e02009-12-23 19:51:44 +00002006 DEBUG(dbgs() << "ADR(");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002007 PrintNode(&GraphNodes[i-FirstAdrNode]);
David Greene7c553e02009-12-23 19:51:44 +00002008 DEBUG(dbgs() <<")");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002009 }
2010
David Greene7c553e02009-12-23 19:51:44 +00002011 DEBUG(dbgs() << " has pointer label " << GraphNodes[i].PointerEquivLabel
Daniel Berlinb53270f2007-09-24 19:45:49 +00002012 << " and SCC rep " << VSSCCRep[i]
2013 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
Chris Lattner2b40c562009-08-23 06:35:02 +00002014 << "\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002015 }
2016}
2017
Daniel Berlined95dd02008-03-05 19:31:47 +00002018/// The technique used here is described in "The Ant and the
2019/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2020/// Lines of Code. In Programming Language Design and Implementation
2021/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2022/// Detection) algorithm. It is called a hybrid because it performs an
2023/// offline analysis and uses its results during the solving (online)
2024/// phase. This is just the offline portion; the results of this
2025/// operation are stored in SDT and are later used in SolveContraints()
2026/// and UniteNodes().
2027void Andersens::HCD() {
David Greene7c553e02009-12-23 19:51:44 +00002028 DEBUG(dbgs() << "Starting HCD.\n");
Daniel Berlined95dd02008-03-05 19:31:47 +00002029 HCDSCCRep.resize(GraphNodes.size());
2030
2031 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2032 GraphNodes[i].Edges = new SparseBitVector<>;
2033 HCDSCCRep[i] = i;
2034 }
2035
2036 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2037 Constraint &C = Constraints[i];
2038 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2039 if (C.Type == Constraint::AddressOf) {
2040 continue;
2041 } else if (C.Type == Constraint::Load) {
2042 if( C.Offset == 0 )
2043 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2044 } else if (C.Type == Constraint::Store) {
2045 if( C.Offset == 0 )
2046 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2047 } else {
2048 GraphNodes[C.Dest].Edges->set(C.Src);
2049 }
2050 }
2051
2052 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2053 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2054 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2055 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2056
2057 DFSNumber = 0;
2058 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2059 unsigned Node = HCDSCCRep[i];
2060 if (!Node2Deleted[Node])
2061 Search(Node);
2062 }
2063
2064 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2065 if (GraphNodes[i].Edges != NULL) {
2066 delete GraphNodes[i].Edges;
2067 GraphNodes[i].Edges = NULL;
2068 }
2069
2070 while( !SCCStack.empty() )
2071 SCCStack.pop();
2072
2073 Node2DFS.clear();
2074 Node2Visited.clear();
2075 Node2Deleted.clear();
2076 HCDSCCRep.clear();
David Greene7c553e02009-12-23 19:51:44 +00002077 DEBUG(dbgs() << "HCD complete.\n");
Daniel Berlined95dd02008-03-05 19:31:47 +00002078}
2079
2080// Component of HCD:
2081// Use Nuutila's variant of Tarjan's algorithm to detect
2082// Strongly-Connected Components (SCCs). For non-trivial SCCs
2083// containing ref nodes, insert the appropriate information in SDT.
2084void Andersens::Search(unsigned Node) {
2085 unsigned MyDFS = DFSNumber++;
2086
2087 Node2Visited[Node] = true;
2088 Node2DFS[Node] = MyDFS;
2089
2090 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2091 End = GraphNodes[Node].Edges->end();
2092 Iter != End;
2093 ++Iter) {
2094 unsigned J = HCDSCCRep[*Iter];
2095 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2096 if (!Node2Deleted[J]) {
2097 if (!Node2Visited[J])
2098 Search(J);
2099 if (Node2DFS[Node] > Node2DFS[J])
2100 Node2DFS[Node] = Node2DFS[J];
2101 }
2102 }
2103
2104 if( MyDFS != Node2DFS[Node] ) {
2105 SCCStack.push(Node);
2106 return;
2107 }
2108
2109 // This node is the root of a SCC, so process it.
2110 //
2111 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2112 // node, we place this SCC into SDT. We unite the nodes in any case.
2113 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2114 SparseBitVector<> SCC;
2115
2116 SCC.set(Node);
2117
2118 bool Ref = (Node >= FirstRefNode);
2119
2120 Node2Deleted[Node] = true;
2121
2122 do {
2123 unsigned P = SCCStack.top(); SCCStack.pop();
2124 Ref |= (P >= FirstRefNode);
2125 SCC.set(P);
2126 HCDSCCRep[P] = Node;
2127 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2128
2129 if (Ref) {
2130 unsigned Rep = SCC.find_first();
2131 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2132
2133 SparseBitVector<>::iterator i = SCC.begin();
2134
2135 // Skip over the non-ref nodes
2136 while( *i < FirstRefNode )
2137 ++i;
2138
2139 while( i != SCC.end() )
2140 SDT[ (*i++) - FirstRefNode ] = Rep;
2141 }
2142 }
2143}
2144
2145
Daniel Berlinb53270f2007-09-24 19:45:49 +00002146/// Optimize the constraints by performing offline variable substitution and
2147/// other optimizations.
2148void Andersens::OptimizeConstraints() {
David Greene7c553e02009-12-23 19:51:44 +00002149 DEBUG(dbgs() << "Beginning constraint optimization\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002150
Daniel Berlined95dd02008-03-05 19:31:47 +00002151 SDTActive = false;
2152
Daniel Berlinb53270f2007-09-24 19:45:49 +00002153 // Function related nodes need to stay in the same relative position and can't
2154 // be location equivalent.
2155 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2156 Iter != MaxK.end();
2157 ++Iter) {
2158 for (unsigned i = Iter->first;
2159 i != Iter->first + Iter->second;
2160 ++i) {
2161 GraphNodes[i].AddressTaken = true;
2162 GraphNodes[i].Direct = false;
2163 }
2164 }
2165
2166 ClumpAddressTaken();
2167 FirstRefNode = GraphNodes.size();
2168 FirstAdrNode = FirstRefNode + GraphNodes.size();
2169 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2170 Node(false));
2171 VSSCCRep.resize(GraphNodes.size());
2172 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2173 VSSCCRep[i] = i;
2174 }
2175 HVN();
2176 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2177 Node *N = &GraphNodes[i];
2178 delete N->PredEdges;
2179 N->PredEdges = NULL;
2180 delete N->ImplicitPredEdges;
2181 N->ImplicitPredEdges = NULL;
2182 }
2183#undef DEBUG_TYPE
2184#define DEBUG_TYPE "anders-aa-labels"
2185 DEBUG(PrintLabels());
2186#undef DEBUG_TYPE
2187#define DEBUG_TYPE "anders-aa"
2188 RewriteConstraints();
2189 // Delete the adr nodes.
2190 GraphNodes.resize(FirstRefNode * 2);
2191
2192 // Now perform HU
2193 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2194 Node *N = &GraphNodes[i];
2195 if (FindNode(i) == i) {
2196 N->PointsTo = new SparseBitVector<>;
2197 N->PointedToBy = new SparseBitVector<>;
2198 // Reset our labels
2199 }
2200 VSSCCRep[i] = i;
2201 N->PointerEquivLabel = 0;
2202 }
2203 HU();
2204#undef DEBUG_TYPE
2205#define DEBUG_TYPE "anders-aa-labels"
2206 DEBUG(PrintLabels());
2207#undef DEBUG_TYPE
2208#define DEBUG_TYPE "anders-aa"
2209 RewriteConstraints();
2210 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2211 if (FindNode(i) == i) {
2212 Node *N = &GraphNodes[i];
2213 delete N->PointsTo;
Daniel Berlined95dd02008-03-05 19:31:47 +00002214 N->PointsTo = NULL;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002215 delete N->PredEdges;
Daniel Berlined95dd02008-03-05 19:31:47 +00002216 N->PredEdges = NULL;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002217 delete N->ImplicitPredEdges;
Daniel Berlined95dd02008-03-05 19:31:47 +00002218 N->ImplicitPredEdges = NULL;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002219 delete N->PointedToBy;
Daniel Berlined95dd02008-03-05 19:31:47 +00002220 N->PointedToBy = NULL;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002221 }
2222 }
Daniel Berlined95dd02008-03-05 19:31:47 +00002223
2224 // perform Hybrid Cycle Detection (HCD)
2225 HCD();
2226 SDTActive = true;
2227
2228 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlinb53270f2007-09-24 19:45:49 +00002229 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlined95dd02008-03-05 19:31:47 +00002230
2231 // HCD complete.
2232
David Greene7c553e02009-12-23 19:51:44 +00002233 DEBUG(dbgs() << "Finished constraint optimization\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002234 FirstRefNode = 0;
2235 FirstAdrNode = 0;
2236}
2237
2238/// Unite pointer but not location equivalent variables, now that the constraint
2239/// graph is built.
2240void Andersens::UnitePointerEquivalences() {
David Greene7c553e02009-12-23 19:51:44 +00002241 DEBUG(dbgs() << "Uniting remaining pointer equivalences\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002242 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002243 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlinb53270f2007-09-24 19:45:49 +00002244 unsigned Label = GraphNodes[i].PointerEquivLabel;
2245
2246 if (Label && PENLEClass2Node[Label] != -1)
2247 UniteNodes(i, PENLEClass2Node[Label]);
2248 }
2249 }
David Greene7c553e02009-12-23 19:51:44 +00002250 DEBUG(dbgs() << "Finished remaining pointer equivalences\n");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002251 PENLEClass2Node.clear();
2252}
2253
2254/// Create the constraint graph used for solving points-to analysis.
2255///
Daniel Berlin385bda62007-09-16 21:45:02 +00002256void Andersens::CreateConstraintGraph() {
2257 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2258 Constraint &C = Constraints[i];
2259 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2260 if (C.Type == Constraint::AddressOf)
2261 GraphNodes[C.Dest].PointsTo->set(C.Src);
2262 else if (C.Type == Constraint::Load)
2263 GraphNodes[C.Src].Constraints.push_back(C);
2264 else if (C.Type == Constraint::Store)
2265 GraphNodes[C.Dest].Constraints.push_back(C);
2266 else if (C.Offset != 0)
2267 GraphNodes[C.Src].Constraints.push_back(C);
2268 else
2269 GraphNodes[C.Src].Edges->set(C.Dest);
2270 }
2271}
2272
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002273// Perform DFS and cycle detection.
2274bool Andersens::QueryNode(unsigned Node) {
2275 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlin385bda62007-09-16 21:45:02 +00002276 unsigned OurDFS = ++DFSNumber;
2277 SparseBitVector<> ToErase;
2278 SparseBitVector<> NewEdges;
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002279 Tarjan2DFS[Node] = OurDFS;
2280
2281 // Changed denotes a change from a recursive call that we will bubble up.
2282 // Merged is set if we actually merge a node ourselves.
2283 bool Changed = false, Merged = false;
Daniel Berlin385bda62007-09-16 21:45:02 +00002284
2285 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2286 bi != GraphNodes[Node].Edges->end();
2287 ++bi) {
2288 unsigned RepNode = FindNode(*bi);
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002289 // If this edge points to a non-representative node but we are
2290 // already planning to add an edge to its representative, we have no
2291 // need for this edge anymore.
Daniel Berlin385bda62007-09-16 21:45:02 +00002292 if (RepNode != *bi && NewEdges.test(RepNode)){
2293 ToErase.set(*bi);
2294 continue;
2295 }
2296
2297 // Continue about our DFS.
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002298 if (!Tarjan2Deleted[RepNode]){
2299 if (Tarjan2DFS[RepNode] == 0) {
2300 Changed |= QueryNode(RepNode);
2301 // May have been changed by QueryNode
Daniel Berlin385bda62007-09-16 21:45:02 +00002302 RepNode = FindNode(RepNode);
2303 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002304 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2305 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlin385bda62007-09-16 21:45:02 +00002306 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002307
2308 // We may have just discovered that this node is part of a cycle, in
2309 // which case we can also erase it.
Daniel Berlin385bda62007-09-16 21:45:02 +00002310 if (RepNode != *bi) {
2311 ToErase.set(*bi);
2312 NewEdges.set(RepNode);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 }
2314 }
2315
Daniel Berlin385bda62007-09-16 21:45:02 +00002316 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2317 GraphNodes[Node].Edges |= NewEdges;
2318
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002319 // If this node is a root of a non-trivial SCC, place it on our
2320 // worklist to be processed.
2321 if (OurDFS == Tarjan2DFS[Node]) {
2322 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2323 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlin385bda62007-09-16 21:45:02 +00002324
2325 SCCStack.pop();
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002326 Merged = true;
Daniel Berlin385bda62007-09-16 21:45:02 +00002327 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002328 Tarjan2Deleted[Node] = true;
Daniel Berlin385bda62007-09-16 21:45:02 +00002329
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002330 if (Merged)
2331 NextWL->insert(&GraphNodes[Node]);
Daniel Berlin385bda62007-09-16 21:45:02 +00002332 } else {
2333 SCCStack.push(Node);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002334 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002335
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002336 return(Changed | Merged);
2337}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338
2339/// SolveConstraints - This stage iteratively processes the constraints list
2340/// propagating constraints (adding edges to the Nodes in the points-to graph)
2341/// until a fixed point is reached.
2342///
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002343/// We use a variant of the technique called "Lazy Cycle Detection", which is
2344/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2345/// Analysis for Millions of Lines of Code. In Programming Language Design and
2346/// Implementation (PLDI), June 2007."
2347/// The paper describes performing cycle detection one node at a time, which can
2348/// be expensive if there are no cycles, but there are long chains of nodes that
2349/// it heuristically believes are cycles (because it will DFS from each node
2350/// without state from previous nodes).
2351/// Instead, we use the heuristic to build a worklist of nodes to check, then
2352/// cycle detect them all at the same time to do this more cheaply. This
2353/// catches cycles slightly later than the original technique did, but does it
2354/// make significantly cheaper.
2355
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002356void Andersens::SolveConstraints() {
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002357 CurrWL = &w1;
2358 NextWL = &w2;
Daniel Berlin385bda62007-09-16 21:45:02 +00002359
Daniel Berlinb53270f2007-09-24 19:45:49 +00002360 OptimizeConstraints();
2361#undef DEBUG_TYPE
2362#define DEBUG_TYPE "anders-aa-constraints"
2363 DEBUG(PrintConstraints());
2364#undef DEBUG_TYPE
2365#define DEBUG_TYPE "anders-aa"
2366
Daniel Berlin385bda62007-09-16 21:45:02 +00002367 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2368 Node *N = &GraphNodes[i];
2369 N->PointsTo = new SparseBitVector<>;
2370 N->OldPointsTo = new SparseBitVector<>;
2371 N->Edges = new SparseBitVector<>;
2372 }
2373 CreateConstraintGraph();
Daniel Berlinb53270f2007-09-24 19:45:49 +00002374 UnitePointerEquivalences();
2375 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002376 Node2DFS.clear();
2377 Node2Deleted.clear();
Daniel Berlin385bda62007-09-16 21:45:02 +00002378 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2379 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2380 DFSNumber = 0;
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002381 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2382 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2383
2384 // Order graph and add initial nodes to work list.
Daniel Berlin385bda62007-09-16 21:45:02 +00002385 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin385bda62007-09-16 21:45:02 +00002386 Node *INode = &GraphNodes[i];
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002387
2388 // Add to work list if it's a representative and can contribute to the
2389 // calculation right now.
2390 if (INode->isRep() && !INode->PointsTo->empty()
2391 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2392 INode->Stamp();
2393 CurrWL->insert(INode);
Daniel Berlin385bda62007-09-16 21:45:02 +00002394 }
2395 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002396 std::queue<unsigned int> TarjanWL;
Daniel Berlined95dd02008-03-05 19:31:47 +00002397#if !FULL_UNIVERSAL
2398 // "Rep and special variables" - in order for HCD to maintain conservative
2399 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2400 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2401 // the analysis - it's ok to add edges from the special nodes, but never
2402 // *to* the special nodes.
2403 std::vector<unsigned int> RSV;
2404#endif
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002405 while( !CurrWL->empty() ) {
David Greene7c553e02009-12-23 19:51:44 +00002406 DEBUG(dbgs() << "Starting iteration #" << ++NumIters << "\n");
Daniel Berlin385bda62007-09-16 21:45:02 +00002407
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002408 Node* CurrNode;
2409 unsigned CurrNodeIndex;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002410
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002411 // Actual cycle checking code. We cycle check all of the lazy cycle
2412 // candidates from the last iteration in one go.
2413 if (!TarjanWL.empty()) {
2414 DFSNumber = 0;
2415
2416 Tarjan2DFS.clear();
2417 Tarjan2Deleted.clear();
2418 while (!TarjanWL.empty()) {
2419 unsigned int ToTarjan = TarjanWL.front();
2420 TarjanWL.pop();
2421 if (!Tarjan2Deleted[ToTarjan]
2422 && GraphNodes[ToTarjan].isRep()
2423 && Tarjan2DFS[ToTarjan] == 0)
2424 QueryNode(ToTarjan);
2425 }
2426 }
2427
2428 // Add to work list if it's a representative and can contribute to the
2429 // calculation right now.
2430 while( (CurrNode = CurrWL->pop()) != NULL ) {
2431 CurrNodeIndex = CurrNode - &GraphNodes[0];
2432 CurrNode->Stamp();
2433
2434
Daniel Berlin385bda62007-09-16 21:45:02 +00002435 // Figure out the changed points to bits
2436 SparseBitVector<> CurrPointsTo;
2437 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2438 CurrNode->OldPointsTo);
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002439 if (CurrPointsTo.empty())
Daniel Berlin385bda62007-09-16 21:45:02 +00002440 continue;
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002441
Daniel Berlin385bda62007-09-16 21:45:02 +00002442 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlined95dd02008-03-05 19:31:47 +00002443
2444 // Check the offline-computed equivalencies from HCD.
2445 bool SCC = false;
2446 unsigned Rep;
2447
2448 if (SDT[CurrNodeIndex] >= 0) {
2449 SCC = true;
2450 Rep = FindNode(SDT[CurrNodeIndex]);
2451
2452#if !FULL_UNIVERSAL
2453 RSV.clear();
2454#endif
2455 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2456 bi != CurrPointsTo.end(); ++bi) {
2457 unsigned Node = FindNode(*bi);
2458#if !FULL_UNIVERSAL
2459 if (Node < NumberSpecialNodes) {
2460 RSV.push_back(Node);
2461 continue;
2462 }
2463#endif
2464 Rep = UniteNodes(Rep,Node);
2465 }
2466#if !FULL_UNIVERSAL
2467 RSV.push_back(Rep);
2468#endif
2469
2470 NextWL->insert(&GraphNodes[Rep]);
2471
2472 if ( ! CurrNode->isRep() )
2473 continue;
2474 }
2475
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002476 Seen.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002477
Daniel Berlin385bda62007-09-16 21:45:02 +00002478 /* Now process the constraints for this node. */
2479 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2480 li != CurrNode->Constraints.end(); ) {
2481 li->Src = FindNode(li->Src);
2482 li->Dest = FindNode(li->Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002484 // Delete redundant constraints
2485 if( Seen.count(*li) ) {
2486 std::list<Constraint>::iterator lk = li; li++;
2487
2488 CurrNode->Constraints.erase(lk);
2489 ++NumErased;
2490 continue;
2491 }
2492 Seen.insert(*li);
2493
Daniel Berlin385bda62007-09-16 21:45:02 +00002494 // Src and Dest will be the vars we are going to process.
2495 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlinb53270f2007-09-24 19:45:49 +00002496 // both store and load constraints with the same code.
Daniel Berlin385bda62007-09-16 21:45:02 +00002497 // Load constraints say that every member of our RHS solution has K
2498 // added to it, and that variable gets an edge to LHS. We also union
2499 // RHS+K's solution into the LHS solution.
2500 // Store constraints say that every member of our LHS solution has K
2501 // added to it, and that variable gets an edge from RHS. We also union
2502 // RHS's solution into the LHS+K solution.
2503 unsigned *Src;
2504 unsigned *Dest;
2505 unsigned K = li->Offset;
2506 unsigned CurrMember;
2507 if (li->Type == Constraint::Load) {
2508 Src = &CurrMember;
2509 Dest = &li->Dest;
2510 } else if (li->Type == Constraint::Store) {
2511 Src = &li->Src;
2512 Dest = &CurrMember;
2513 } else {
2514 // TODO Handle offseted copy constraint
2515 li++;
2516 continue;
2517 }
Daniel Berlined95dd02008-03-05 19:31:47 +00002518
2519 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlin385bda62007-09-16 21:45:02 +00002520 // if it was a statically detected offline equivalence that
Daniel Berlined95dd02008-03-05 19:31:47 +00002521 // involves pointers; if so, remove the redundant constraints).
2522 if( SCC && K == 0 ) {
2523#if FULL_UNIVERSAL
2524 CurrMember = Rep;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002526 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2527 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2528 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlined95dd02008-03-05 19:31:47 +00002529#else
2530 for (unsigned i=0; i < RSV.size(); ++i) {
2531 CurrMember = RSV[i];
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002532
Daniel Berlined95dd02008-03-05 19:31:47 +00002533 if (*Dest < NumberSpecialNodes)
2534 continue;
2535 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2536 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2537 NextWL->insert(&GraphNodes[*Dest]);
2538 }
2539#endif
2540 // since all future elements of the points-to set will be
2541 // equivalent to the current ones, the complex constraints
2542 // become redundant.
2543 //
2544 std::list<Constraint>::iterator lk = li; li++;
2545#if !FULL_UNIVERSAL
2546 // In this case, we can still erase the constraints when the
2547 // elements of the points-to sets are referenced by *Dest,
2548 // but not when they are referenced by *Src (i.e. for a Load
2549 // constraint). This is because if another special variable is
2550 // put into the points-to set later, we still need to add the
2551 // new edge from that special variable.
2552 if( lk->Type != Constraint::Load)
2553#endif
2554 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2555 } else {
2556 const SparseBitVector<> &Solution = CurrPointsTo;
2557
2558 for (SparseBitVector<>::iterator bi = Solution.begin();
2559 bi != Solution.end();
2560 ++bi) {
2561 CurrMember = *bi;
2562
2563 // Need to increment the member by K since that is where we are
2564 // supposed to copy to/from. Note that in positive weight cycles,
2565 // which occur in address taking of fields, K can go past
2566 // MaxK[CurrMember] elements, even though that is all it could point
2567 // to.
2568 if (K > 0 && K > MaxK[CurrMember])
2569 continue;
2570 else
2571 CurrMember = FindNode(CurrMember + K);
2572
2573 // Add an edge to the graph, so we can just do regular
2574 // bitmap ior next time. It may also let us notice a cycle.
2575#if !FULL_UNIVERSAL
2576 if (*Dest < NumberSpecialNodes)
2577 continue;
2578#endif
2579 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2580 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2581 NextWL->insert(&GraphNodes[*Dest]);
2582
2583 }
2584 li++;
Daniel Berlin385bda62007-09-16 21:45:02 +00002585 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002586 }
2587 SparseBitVector<> NewEdges;
2588 SparseBitVector<> ToErase;
2589
2590 // Now all we have left to do is propagate points-to info along the
2591 // edges, erasing the redundant edges.
Daniel Berlin385bda62007-09-16 21:45:02 +00002592 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2593 bi != CurrNode->Edges->end();
2594 ++bi) {
2595
2596 unsigned DestVar = *bi;
2597 unsigned Rep = FindNode(DestVar);
2598
Bill Wendling059e62c2008-02-26 10:51:52 +00002599 // If we ended up with this node as our destination, or we've already
2600 // got an edge for the representative, delete the current edge.
2601 if (Rep == CurrNodeIndex ||
2602 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlined95dd02008-03-05 19:31:47 +00002603 ToErase.set(DestVar);
2604 continue;
Bill Wendling059e62c2008-02-26 10:51:52 +00002605 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002606
Bill Wendling059e62c2008-02-26 10:51:52 +00002607 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002608
2609 // This is where we do lazy cycle detection.
2610 // If this is a cycle candidate (equal points-to sets and this
2611 // particular edge has not been cycle-checked previously), add to the
2612 // list to check for cycles on the next iteration.
2613 if (!EdgesChecked.count(edge) &&
2614 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2615 EdgesChecked.insert(edge);
2616 TarjanWL.push(Rep);
Daniel Berlin385bda62007-09-16 21:45:02 +00002617 }
2618 // Union the points-to sets into the dest
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002619#if !FULL_UNIVERSAL
2620 if (Rep >= NumberSpecialNodes)
2621#endif
Daniel Berlin385bda62007-09-16 21:45:02 +00002622 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002623 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlin385bda62007-09-16 21:45:02 +00002624 }
2625 // If this edge's destination was collapsed, rewrite the edge.
2626 if (Rep != DestVar) {
2627 ToErase.set(DestVar);
2628 NewEdges.set(Rep);
2629 }
2630 }
2631 CurrNode->Edges->intersectWithComplement(ToErase);
2632 CurrNode->Edges |= NewEdges;
2633 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002634
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002635 // Switch to other work list.
2636 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2637 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002638
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002639
Daniel Berlin385bda62007-09-16 21:45:02 +00002640 Node2DFS.clear();
2641 Node2Deleted.clear();
2642 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2643 Node *N = &GraphNodes[i];
2644 delete N->OldPointsTo;
2645 delete N->Edges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002646 }
Daniel Berlined95dd02008-03-05 19:31:47 +00002647 SDTActive = false;
2648 SDT.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002649}
2650
Daniel Berlin385bda62007-09-16 21:45:02 +00002651//===----------------------------------------------------------------------===//
2652// Union-Find
2653//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002654
Daniel Berlin385bda62007-09-16 21:45:02 +00002655// Unite nodes First and Second, returning the one which is now the
2656// representative node. First and Second are indexes into GraphNodes
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002657unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2658 bool UnionByRank) {
Daniel Berlin385bda62007-09-16 21:45:02 +00002659 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2660 "Attempting to merge nodes that don't exist");
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002661
Daniel Berlin385bda62007-09-16 21:45:02 +00002662 Node *FirstNode = &GraphNodes[First];
2663 Node *SecondNode = &GraphNodes[Second];
2664
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002665 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlin385bda62007-09-16 21:45:02 +00002666 "Trying to unite two non-representative nodes!");
2667 if (First == Second)
2668 return First;
2669
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002670 if (UnionByRank) {
2671 int RankFirst = (int) FirstNode ->NodeRep;
2672 int RankSecond = (int) SecondNode->NodeRep;
2673
2674 // Rank starts at -1 and gets decremented as it increases.
2675 // Translation: higher rank, lower NodeRep value, which is always negative.
2676 if (RankFirst > RankSecond) {
2677 unsigned t = First; First = Second; Second = t;
2678 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2679 } else if (RankFirst == RankSecond) {
2680 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2681 }
2682 }
2683
Daniel Berlin385bda62007-09-16 21:45:02 +00002684 SecondNode->NodeRep = First;
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002685#if !FULL_UNIVERSAL
2686 if (First >= NumberSpecialNodes)
2687#endif
Daniel Berlinb53270f2007-09-24 19:45:49 +00002688 if (FirstNode->PointsTo && SecondNode->PointsTo)
2689 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2690 if (FirstNode->Edges && SecondNode->Edges)
2691 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002692 if (!SecondNode->Constraints.empty())
Daniel Berlinb53270f2007-09-24 19:45:49 +00002693 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2694 SecondNode->Constraints);
2695 if (FirstNode->OldPointsTo) {
2696 delete FirstNode->OldPointsTo;
2697 FirstNode->OldPointsTo = new SparseBitVector<>;
2698 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002699
2700 // Destroy interesting parts of the merged-from node.
2701 delete SecondNode->OldPointsTo;
2702 delete SecondNode->Edges;
2703 delete SecondNode->PointsTo;
2704 SecondNode->Edges = NULL;
2705 SecondNode->PointsTo = NULL;
2706 SecondNode->OldPointsTo = NULL;
2707
2708 NumUnified++;
David Greene7c553e02009-12-23 19:51:44 +00002709 DEBUG(dbgs() << "Unified Node ");
Daniel Berlin385bda62007-09-16 21:45:02 +00002710 DEBUG(PrintNode(FirstNode));
David Greene7c553e02009-12-23 19:51:44 +00002711 DEBUG(dbgs() << " and Node ");
Daniel Berlin385bda62007-09-16 21:45:02 +00002712 DEBUG(PrintNode(SecondNode));
David Greene7c553e02009-12-23 19:51:44 +00002713 DEBUG(dbgs() << "\n");
Daniel Berlin385bda62007-09-16 21:45:02 +00002714
Daniel Berlined95dd02008-03-05 19:31:47 +00002715 if (SDTActive)
Duncan Sandsf6890712008-05-27 11:50:51 +00002716 if (SDT[Second] >= 0) {
Daniel Berlined95dd02008-03-05 19:31:47 +00002717 if (SDT[First] < 0)
2718 SDT[First] = SDT[Second];
2719 else {
2720 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2721 First = FindNode(First);
2722 }
Duncan Sandsf6890712008-05-27 11:50:51 +00002723 }
Daniel Berlined95dd02008-03-05 19:31:47 +00002724
Daniel Berlin385bda62007-09-16 21:45:02 +00002725 return First;
2726}
2727
2728// Find the index into GraphNodes of the node representing Node, performing
2729// path compression along the way
2730unsigned Andersens::FindNode(unsigned NodeIndex) {
2731 assert (NodeIndex < GraphNodes.size()
2732 && "Attempting to find a node that can't exist");
2733 Node *N = &GraphNodes[NodeIndex];
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002734 if (N->isRep())
Daniel Berlin385bda62007-09-16 21:45:02 +00002735 return NodeIndex;
2736 else
2737 return (N->NodeRep = FindNode(N->NodeRep));
2738}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739
Andrew Lenharthdce39302008-03-20 15:36:44 +00002740// Find the index into GraphNodes of the node representing Node,
2741// don't perform path compression along the way (for Print)
2742unsigned Andersens::FindNode(unsigned NodeIndex) const {
2743 assert (NodeIndex < GraphNodes.size()
2744 && "Attempting to find a node that can't exist");
2745 const Node *N = &GraphNodes[NodeIndex];
2746 if (N->isRep())
2747 return NodeIndex;
2748 else
2749 return FindNode(N->NodeRep);
2750}
2751
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752//===----------------------------------------------------------------------===//
2753// Debugging Output
2754//===----------------------------------------------------------------------===//
2755
Andrew Lenharthdce39302008-03-20 15:36:44 +00002756void Andersens::PrintNode(const Node *N) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002757 if (N == &GraphNodes[UniversalSet]) {
David Greene7c553e02009-12-23 19:51:44 +00002758 dbgs() << "<universal>";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002759 return;
2760 } else if (N == &GraphNodes[NullPtr]) {
David Greene7c553e02009-12-23 19:51:44 +00002761 dbgs() << "<nullptr>";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002762 return;
2763 } else if (N == &GraphNodes[NullObject]) {
David Greene7c553e02009-12-23 19:51:44 +00002764 dbgs() << "<null>";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 return;
2766 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002767 if (!N->getValue()) {
David Greene7c553e02009-12-23 19:51:44 +00002768 dbgs() << "artificial" << (intptr_t) N;
Daniel Berlin385bda62007-09-16 21:45:02 +00002769 return;
2770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771
2772 assert(N->getValue() != 0 && "Never set node label!");
2773 Value *V = N->getValue();
2774 if (Function *F = dyn_cast<Function>(V)) {
2775 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlin385bda62007-09-16 21:45:02 +00002776 N == &GraphNodes[getReturnNode(F)]) {
David Greene7c553e02009-12-23 19:51:44 +00002777 dbgs() << F->getName() << ":retval";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002778 return;
Daniel Berlin385bda62007-09-16 21:45:02 +00002779 } else if (F->getFunctionType()->isVarArg() &&
2780 N == &GraphNodes[getVarargNode(F)]) {
David Greene7c553e02009-12-23 19:51:44 +00002781 dbgs() << F->getName() << ":vararg";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 return;
2783 }
2784 }
2785
2786 if (Instruction *I = dyn_cast<Instruction>(V))
David Greene7c553e02009-12-23 19:51:44 +00002787 dbgs() << I->getParent()->getParent()->getName() << ":";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002788 else if (Argument *Arg = dyn_cast<Argument>(V))
David Greene7c553e02009-12-23 19:51:44 +00002789 dbgs() << Arg->getParent()->getName() << ":";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002790
2791 if (V->hasName())
David Greene7c553e02009-12-23 19:51:44 +00002792 dbgs() << V->getName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002793 else
David Greene7c553e02009-12-23 19:51:44 +00002794 dbgs() << "(unnamed)";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795
Victor Hernandezb1687302009-10-23 21:09:37 +00002796 if (isa<GlobalValue>(V) || isa<AllocaInst>(V) || isMalloc(V))
Daniel Berlin385bda62007-09-16 21:45:02 +00002797 if (N == &GraphNodes[getObject(V)])
David Greene7c553e02009-12-23 19:51:44 +00002798 dbgs() << "<mem>";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799}
Andrew Lenharthdce39302008-03-20 15:36:44 +00002800void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlinb53270f2007-09-24 19:45:49 +00002801 if (C.Type == Constraint::Store) {
David Greene7c553e02009-12-23 19:51:44 +00002802 dbgs() << "*";
Daniel Berlinb53270f2007-09-24 19:45:49 +00002803 if (C.Offset != 0)
David Greene7c553e02009-12-23 19:51:44 +00002804 dbgs() << "(";
Daniel Berlinb53270f2007-09-24 19:45:49 +00002805 }
2806 PrintNode(&GraphNodes[C.Dest]);
2807 if (C.Type == Constraint::Store && C.Offset != 0)
David Greene7c553e02009-12-23 19:51:44 +00002808 dbgs() << " + " << C.Offset << ")";
2809 dbgs() << " = ";
Daniel Berlinb53270f2007-09-24 19:45:49 +00002810 if (C.Type == Constraint::Load) {
David Greene7c553e02009-12-23 19:51:44 +00002811 dbgs() << "*";
Daniel Berlinb53270f2007-09-24 19:45:49 +00002812 if (C.Offset != 0)
David Greene7c553e02009-12-23 19:51:44 +00002813 dbgs() << "(";
Daniel Berlinb53270f2007-09-24 19:45:49 +00002814 }
2815 else if (C.Type == Constraint::AddressOf)
David Greene7c553e02009-12-23 19:51:44 +00002816 dbgs() << "&";
Daniel Berlinb53270f2007-09-24 19:45:49 +00002817 PrintNode(&GraphNodes[C.Src]);
2818 if (C.Offset != 0 && C.Type != Constraint::Store)
David Greene7c553e02009-12-23 19:51:44 +00002819 dbgs() << " + " << C.Offset;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002820 if (C.Type == Constraint::Load && C.Offset != 0)
David Greene7c553e02009-12-23 19:51:44 +00002821 dbgs() << ")";
2822 dbgs() << "\n";
Daniel Berlinb53270f2007-09-24 19:45:49 +00002823}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002824
Andrew Lenharthdce39302008-03-20 15:36:44 +00002825void Andersens::PrintConstraints() const {
David Greene7c553e02009-12-23 19:51:44 +00002826 dbgs() << "Constraints:\n";
Daniel Berlin385bda62007-09-16 21:45:02 +00002827
Daniel Berlinb53270f2007-09-24 19:45:49 +00002828 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2829 PrintConstraint(Constraints[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830}
2831
Andrew Lenharthdce39302008-03-20 15:36:44 +00002832void Andersens::PrintPointsToGraph() const {
David Greene7c553e02009-12-23 19:51:44 +00002833 dbgs() << "Points-to graph:\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002834 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharthdce39302008-03-20 15:36:44 +00002835 const Node *N = &GraphNodes[i];
2836 if (FindNode(i) != i) {
Daniel Berlin385bda62007-09-16 21:45:02 +00002837 PrintNode(N);
David Greene7c553e02009-12-23 19:51:44 +00002838 dbgs() << "\t--> same as ";
Daniel Berlin385bda62007-09-16 21:45:02 +00002839 PrintNode(&GraphNodes[FindNode(i)]);
David Greene7c553e02009-12-23 19:51:44 +00002840 dbgs() << "\n";
Daniel Berlin385bda62007-09-16 21:45:02 +00002841 } else {
David Greene7c553e02009-12-23 19:51:44 +00002842 dbgs() << "[" << (N->PointsTo->count()) << "] ";
Daniel Berlin385bda62007-09-16 21:45:02 +00002843 PrintNode(N);
David Greene7c553e02009-12-23 19:51:44 +00002844 dbgs() << "\t--> ";
Daniel Berlin385bda62007-09-16 21:45:02 +00002845
2846 bool first = true;
2847 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2848 bi != N->PointsTo->end();
2849 ++bi) {
2850 if (!first)
David Greene7c553e02009-12-23 19:51:44 +00002851 dbgs() << ", ";
Daniel Berlin385bda62007-09-16 21:45:02 +00002852 PrintNode(&GraphNodes[*bi]);
2853 first = false;
2854 }
David Greene7c553e02009-12-23 19:51:44 +00002855 dbgs() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002856 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002857 }
2858}