blob: 49c6edd6207fcc91f6cb1fc47fd1b0eb622183dd [file] [log] [blame]
Chris Lattnerd28b0d72004-06-25 04:24:22 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattnere995a2a2004-05-23 21:00:47 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattnere995a2a2004-05-23 21:00:47 +00008//===----------------------------------------------------------------------===//
9//
Daniel Berlinaad15882007-09-16 21:45:02 +000010// This file defines an implementation of Andersen's interprocedural alias
11// analysis
Chris Lattnere995a2a2004-05-23 21:00:47 +000012//
13// In pointer analysis terms, this is a subset-based, flow-insensitive,
Daniel Berlinaad15882007-09-16 21:45:02 +000014// field-sensitive, and context-insensitive algorithm pointer algorithm.
Chris Lattnere995a2a2004-05-23 21:00:47 +000015//
16// This algorithm is implemented as three stages:
17// 1. Object identification.
18// 2. Inclusion constraint identification.
Daniel Berlind81ccc22007-09-24 19:45:49 +000019// 3. Offline constraint graph optimization
20// 4. Inclusion constraint solving.
Chris Lattnere995a2a2004-05-23 21:00:47 +000021//
22// The object identification stage identifies all of the memory objects in the
23// program, which includes globals, heap allocated objects, and stack allocated
24// objects.
25//
26// The inclusion constraint identification stage finds all inclusion constraints
27// in the program by scanning the program, looking for pointer assignments and
28// other statements that effect the points-to graph. For a statement like "A =
29// B", this statement is processed to indicate that A can point to anything that
Daniel Berlinaad15882007-09-16 21:45:02 +000030// B can point to. Constraints can handle copies, loads, and stores, and
31// address taking.
Chris Lattnere995a2a2004-05-23 21:00:47 +000032//
Daniel Berline6f04792007-09-24 22:20:45 +000033// The offline constraint graph optimization portion includes offline variable
Daniel Berlinc864edb2008-03-05 19:31:47 +000034// substitution algorithms intended to compute pointer and location
Daniel Berline6f04792007-09-24 22:20:45 +000035// equivalences. Pointer equivalences are those pointers that will have the
36// same points-to sets, and location equivalences are those variables that
Daniel Berlinc864edb2008-03-05 19:31:47 +000037// always appear together in points-to sets. It also includes an offline
38// cycle detection algorithm that allows cycles to be collapsed sooner
39// during solving.
Daniel Berlind81ccc22007-09-24 19:45:49 +000040//
Chris Lattnere995a2a2004-05-23 21:00:47 +000041// The inclusion constraint solving phase iteratively propagates the inclusion
42// constraints until a fixed point is reached. This is an O(N^3) algorithm.
43//
Daniel Berlinaad15882007-09-16 21:45:02 +000044// Function constraints are handled as if they were structs with X fields.
45// Thus, an access to argument X of function Y is an access to node index
46// getNode(Y) + X. This representation allows handling of indirect calls
Daniel Berlind81ccc22007-09-24 19:45:49 +000047// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlinaad15882007-09-16 21:45:02 +000048// *(Y + 1) = a, *(Y + 2) = b.
49// The return node for a function is always located at getNode(F) +
50// CallReturnPos. The arguments start at getNode(F) + CallArgPos.
Chris Lattnere995a2a2004-05-23 21:00:47 +000051//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000052// Future Improvements:
Daniel Berlinc864edb2008-03-05 19:31:47 +000053// Use of BDD's.
Chris Lattnere995a2a2004-05-23 21:00:47 +000054//===----------------------------------------------------------------------===//
55
56#define DEBUG_TYPE "anders-aa"
57#include "llvm/Constants.h"
58#include "llvm/DerivedTypes.h"
59#include "llvm/Instructions.h"
60#include "llvm/Module.h"
61#include "llvm/Pass.h"
Reid Spencerd7d83db2007-02-05 23:42:17 +000062#include "llvm/Support/Compiler.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000063#include "llvm/Support/InstIterator.h"
64#include "llvm/Support/InstVisitor.h"
65#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000066#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000067#include "llvm/Support/Debug.h"
68#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000069#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000070#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000071#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000072#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000073#include <list>
74#include <stack>
75#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000076#include <queue>
77
78// Determining the actual set of nodes the universal set can consist of is very
79// expensive because it means propagating around very large sets. We rely on
80// other analysis being able to determine which nodes can never be pointed to in
81// order to disambiguate further than "points-to anything".
82#define FULL_UNIVERSAL 0
Chris Lattnere995a2a2004-05-23 21:00:47 +000083
Daniel Berlinaad15882007-09-16 21:45:02 +000084using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000085STATISTIC(NumIters , "Number of iterations to reach convergence");
86STATISTIC(NumConstraints, "Number of constraints");
87STATISTIC(NumNodes , "Number of nodes");
88STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000089STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000090
Chris Lattner3b27d682006-12-19 22:30:33 +000091namespace {
Daniel Berlinaad15882007-09-16 21:45:02 +000092 const unsigned SelfRep = (unsigned)-1;
93 const unsigned Unvisited = (unsigned)-1;
94 // Position of the function return node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000095 const unsigned CallReturnPos = 1;
Daniel Berlinaad15882007-09-16 21:45:02 +000096 // Position of the function call node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000097 const unsigned CallFirstArgPos = 2;
98
99 struct BitmapKeyInfo {
100 static inline SparseBitVector<> *getEmptyKey() {
101 return reinterpret_cast<SparseBitVector<> *>(-1);
102 }
103 static inline SparseBitVector<> *getTombstoneKey() {
104 return reinterpret_cast<SparseBitVector<> *>(-2);
105 }
106 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
107 return bitmap->getHashValue();
108 }
109 static bool isEqual(const SparseBitVector<> *LHS,
110 const SparseBitVector<> *RHS) {
111 if (LHS == RHS)
112 return true;
113 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
114 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
115 return false;
116
117 return *LHS == *RHS;
118 }
119
120 static bool isPod() { return true; }
121 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000122
Reid Spencerd7d83db2007-02-05 23:42:17 +0000123 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
124 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000125 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000126
127 /// Constraint - Objects of this structure are used to represent the various
128 /// constraints identified by the algorithm. The constraints are 'copy',
129 /// for statements like "A = B", 'load' for statements like "A = *B",
130 /// 'store' for statements like "*A = B", and AddressOf for statements like
131 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
132 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000133 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000134 /// resolvable to A = &C where C = B + K)
135
136 struct Constraint {
137 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
138 unsigned Dest;
139 unsigned Src;
140 unsigned Offset;
141
142 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
143 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000144 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000145 "Offset is illegal on addressof constraints");
146 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000147
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000148 bool operator==(const Constraint &RHS) const {
149 return RHS.Type == Type
150 && RHS.Dest == Dest
151 && RHS.Src == Src
152 && RHS.Offset == Offset;
153 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000154
155 bool operator!=(const Constraint &RHS) const {
156 return !(*this == RHS);
157 }
158
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000159 bool operator<(const Constraint &RHS) const {
160 if (RHS.Type != Type)
161 return RHS.Type < Type;
162 else if (RHS.Dest != Dest)
163 return RHS.Dest < Dest;
164 else if (RHS.Src != Src)
165 return RHS.Src < Src;
166 return RHS.Offset < Offset;
167 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000168 };
169
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000170 // Information DenseSet requires implemented in order to be able to do
171 // it's thing
172 struct PairKeyInfo {
173 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000174 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000175 }
176 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000177 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000178 }
179 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
180 return P.first ^ P.second;
181 }
182 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
183 const std::pair<unsigned, unsigned> &RHS) {
184 return LHS == RHS;
185 }
186 };
187
Daniel Berlin336c6c02007-09-29 00:50:40 +0000188 struct ConstraintKeyInfo {
189 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000190 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000191 }
192 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000193 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000194 }
195 static unsigned getHashValue(const Constraint &C) {
196 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
197 }
198 static bool isEqual(const Constraint &LHS,
199 const Constraint &RHS) {
200 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
201 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
202 }
203 };
204
Daniel Berlind81ccc22007-09-24 19:45:49 +0000205 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000206 // graph. Due to various optimizations, it is not always the case that
207 // there is a mapping from a Node to a Value. In particular, we add
208 // artificial Node's that represent the set of pointed-to variables shared
209 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000210 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000211 private:
212 static unsigned Counter;
213
214 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000215 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000216 SparseBitVector<> *Edges;
217 SparseBitVector<> *PointsTo;
218 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000219 std::list<Constraint> Constraints;
220
Daniel Berlind81ccc22007-09-24 19:45:49 +0000221 // Pointer and location equivalence labels
222 unsigned PointerEquivLabel;
223 unsigned LocationEquivLabel;
224 // Predecessor edges, both real and implicit
225 SparseBitVector<> *PredEdges;
226 SparseBitVector<> *ImplicitPredEdges;
227 // Set of nodes that point to us, only use for location equivalence.
228 SparseBitVector<> *PointedToBy;
229 // Number of incoming edges, used during variable substitution to early
230 // free the points-to sets
231 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000232 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000233 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000234 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000235 bool Direct;
236 // True if the node is address taken, *or* it is part of a group of nodes
237 // that must be kept together. This is set to true for functions and
238 // their arg nodes, which must be kept at the same position relative to
239 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000240 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000241
Daniel Berlind81ccc22007-09-24 19:45:49 +0000242 // Nodes in cycles (or in equivalence classes) are united together using a
243 // standard union-find representation with path compression. NodeRep
244 // gives the index into GraphNodes for the representative Node.
245 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000246
247 // Modification timestamp. Assigned from Counter.
248 // Used for work list prioritization.
249 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000250
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000251 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000252 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000253 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
254 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
255 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000256 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000257
Chris Lattnere995a2a2004-05-23 21:00:47 +0000258 Node *setValue(Value *V) {
259 assert(Val == 0 && "Value already set for this node!");
260 Val = V;
261 return this;
262 }
263
264 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000265 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000266 Value *getValue() const { return Val; }
267
Chris Lattnere995a2a2004-05-23 21:00:47 +0000268 /// addPointerTo - Add a pointer to the list of pointees of this node,
269 /// returning true if this caused a new pointer to be added, or false if
270 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000271 bool addPointerTo(unsigned Node) {
272 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000273 }
274
275 /// intersects - Return true if the points-to set of this node intersects
276 /// with the points-to set of the specified node.
277 bool intersects(Node *N) const;
278
279 /// intersectsIgnoring - Return true if the points-to set of this node
280 /// intersects with the points-to set of the specified node on any nodes
281 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000282 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000283
284 // Timestamp a node (used for work list prioritization)
285 void Stamp() {
286 Timestamp = Counter++;
287 }
288
289 bool isRep() {
290 return( (int) NodeRep < 0 );
291 }
292 };
293
294 struct WorkListElement {
295 Node* node;
296 unsigned Timestamp;
297 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
298
299 // Note that we reverse the sense of the comparison because we
300 // actually want to give low timestamps the priority over high,
301 // whereas priority is typically interpreted as a greater value is
302 // given high priority.
303 bool operator<(const WorkListElement& that) const {
304 return( this->Timestamp > that.Timestamp );
305 }
306 };
307
308 // Priority-queue based work list specialized for Nodes.
309 class WorkList {
310 std::priority_queue<WorkListElement> Q;
311
312 public:
313 void insert(Node* n) {
314 Q.push( WorkListElement(n, n->Timestamp) );
315 }
316
317 // We automatically discard non-representative nodes and nodes
318 // that were in the work list twice (we keep a copy of the
319 // timestamp in the work list so we can detect this situation by
320 // comparing against the node's current timestamp).
321 Node* pop() {
322 while( !Q.empty() ) {
323 WorkListElement x = Q.top(); Q.pop();
324 Node* INode = x.node;
325
326 if( INode->isRep() &&
327 INode->Timestamp == x.Timestamp ) {
328 return(x.node);
329 }
330 }
331 return(0);
332 }
333
334 bool empty() {
335 return Q.empty();
336 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000337 };
338
339 /// GraphNodes - This vector is populated as part of the object
340 /// identification stage of the analysis, which populates this vector with a
341 /// node for each memory object and fills in the ValueNodes map.
342 std::vector<Node> GraphNodes;
343
344 /// ValueNodes - This map indicates the Node that a particular Value* is
345 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000346 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000347
348 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000349 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000350 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000351
352 /// ReturnNodes - This map contains an entry for each function in the
353 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000354 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000355
356 /// VarargNodes - This map contains the entry used to represent all pointers
357 /// passed through the varargs portion of a function call for a particular
358 /// function. An entry is not present in this map for functions that do not
359 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000360 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000361
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000362
Chris Lattnere995a2a2004-05-23 21:00:47 +0000363 /// Constraints - This vector contains a list of all of the constraints
364 /// identified by the program.
365 std::vector<Constraint> Constraints;
366
Daniel Berlind81ccc22007-09-24 19:45:49 +0000367 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000368 // this is equivalent to the number of arguments + CallFirstArgPos)
369 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000370
371 /// This enum defines the GraphNodes indices that correspond to important
372 /// fixed sets.
373 enum {
374 UniversalSet = 0,
375 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000376 NullObject = 2,
377 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000378 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000379 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000380 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000381 // Map from Graph Node to DFS number
382 std::vector<unsigned> Node2DFS;
383 // Map from Graph Node to Deleted from graph.
384 std::vector<bool> Node2Deleted;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000385 // Same as Node Maps, but implemented as std::map because it is faster to
386 // clear
387 std::map<unsigned, unsigned> Tarjan2DFS;
388 std::map<unsigned, bool> Tarjan2Deleted;
389 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000390 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000391
392 // Work lists.
393 WorkList w1, w2;
394 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000395
Daniel Berlind81ccc22007-09-24 19:45:49 +0000396 // Offline variable substitution related things
397
398 // Temporary rep storage, used because we can't collapse SCC's in the
399 // predecessor graph by uniting the variables permanently, we can only do so
400 // for the successor graph.
401 std::vector<unsigned> VSSCCRep;
402 // Mapping from node to whether we have visited it during SCC finding yet.
403 std::vector<bool> Node2Visited;
404 // During variable substitution, we create unknowns to represent the unknown
405 // value that is a dereference of a variable. These nodes are known as
406 // "ref" nodes (since they represent the value of dereferences).
407 unsigned FirstRefNode;
408 // During HVN, we create represent address taken nodes as if they were
409 // unknown (since HVN, unlike HU, does not evaluate unions).
410 unsigned FirstAdrNode;
411 // Current pointer equivalence class number
412 unsigned PEClass;
413 // Mapping from points-to sets to equivalence classes
414 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
415 BitVectorMap Set2PEClass;
416 // Mapping from pointer equivalences to the representative node. -1 if we
417 // have no representative node for this pointer equivalence class yet.
418 std::vector<int> PEClass2Node;
419 // Mapping from pointer equivalences to representative node. This includes
420 // pointer equivalent but not location equivalent variables. -1 if we have
421 // no representative node for this pointer equivalence class yet.
422 std::vector<int> PENLEClass2Node;
Daniel Berlinc864edb2008-03-05 19:31:47 +0000423 // Union/Find for HCD
424 std::vector<unsigned> HCDSCCRep;
425 // HCD's offline-detected cycles; "Statically DeTected"
426 // -1 if not part of such a cycle, otherwise a representative node.
427 std::vector<int> SDT;
428 // Whether to use SDT (UniteNodes can use it during solving, but not before)
429 bool SDTActive;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000430
Chris Lattnere995a2a2004-05-23 21:00:47 +0000431 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000432 static char ID;
433 Andersens() : ModulePass((intptr_t)&ID) {}
434
Devang Patel1cee94f2008-03-18 00:39:19 +0000435 /// isAnalysis - Return true if this pass is implementing an analysis pass.
436 virtual bool isAnalysis() const { return true; }
437
Chris Lattnerb12914b2004-09-20 04:48:05 +0000438 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000439 InitializeAliasAnalysis(this);
440 IdentifyObjects(M);
441 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000442#undef DEBUG_TYPE
443#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000444 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000445#undef DEBUG_TYPE
446#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000447 SolveConstraints();
448 DEBUG(PrintPointsToGraph());
449
450 // Free the constraints list, as we don't need it to respond to alias
451 // requests.
452 ObjectNodes.clear();
453 ReturnNodes.clear();
454 VarargNodes.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000455 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000456 return false;
457 }
458
459 void releaseMemory() {
460 // FIXME: Until we have transitively required passes working correctly,
461 // this cannot be enabled! Otherwise, using -count-aa with the pass
462 // causes memory to be freed too early. :(
463#if 0
464 // The memory objects and ValueNodes data structures at the only ones that
465 // are still live after construction.
466 std::vector<Node>().swap(GraphNodes);
467 ValueNodes.clear();
468#endif
469 }
470
471 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
472 AliasAnalysis::getAnalysisUsage(AU);
473 AU.setPreservesAll(); // Does not transform code
474 }
475
476 //------------------------------------------------
477 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000478 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000479 AliasResult alias(const Value *V1, unsigned V1Size,
480 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000481 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
482 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000483 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
484 bool pointsToConstantMemory(const Value *P);
485
486 virtual void deleteValue(Value *V) {
487 ValueNodes.erase(V);
488 getAnalysis<AliasAnalysis>().deleteValue(V);
489 }
490
491 virtual void copyValue(Value *From, Value *To) {
492 ValueNodes[To] = ValueNodes[From];
493 getAnalysis<AliasAnalysis>().copyValue(From, To);
494 }
495
496 private:
497 /// getNode - Return the node corresponding to the specified pointer scalar.
498 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000499 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000500 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000501 if (!isa<GlobalValue>(C))
502 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000503
Daniel Berlind81ccc22007-09-24 19:45:49 +0000504 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000505 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000506#ifndef NDEBUG
507 V->dump();
508#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000509 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000510 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000511 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000512 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000513
Chris Lattnere995a2a2004-05-23 21:00:47 +0000514 /// getObject - Return the node corresponding to the memory object for the
515 /// specified global or allocation instruction.
Daniel Berlinaad15882007-09-16 21:45:02 +0000516 unsigned getObject(Value *V) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000517 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000518 assert(I != ObjectNodes.end() &&
519 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000520 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000521 }
522
523 /// getReturnNode - Return the node representing the return value for the
524 /// specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000525 unsigned getReturnNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000526 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000527 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000528 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000529 }
530
531 /// getVarargNode - Return the node representing the variable arguments
532 /// formal for the specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000533 unsigned getVarargNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000534 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000535 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000536 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000537 }
538
539 /// getNodeValue - Get the node for the specified LLVM value and set the
540 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000541 unsigned getNodeValue(Value &V) {
542 unsigned Index = getNode(&V);
543 GraphNodes[Index].setValue(&V);
544 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000545 }
546
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000547 unsigned UniteNodes(unsigned First, unsigned Second,
548 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000549 unsigned FindNode(unsigned Node);
550
Chris Lattnere995a2a2004-05-23 21:00:47 +0000551 void IdentifyObjects(Module &M);
552 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000553 bool AnalyzeUsesOfFunction(Value *);
554 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000555 void OptimizeConstraints();
556 unsigned FindEquivalentNode(unsigned, unsigned);
557 void ClumpAddressTaken();
558 void RewriteConstraints();
559 void HU();
560 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000561 void HCD();
562 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000563 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000564 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000565 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000566 void Condense(unsigned Node);
567 void HUValNum(unsigned Node);
568 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000569 unsigned getNodeForConstantPointer(Constant *C);
570 unsigned getNodeForConstantPointerTarget(Constant *C);
571 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000572
Chris Lattnere995a2a2004-05-23 21:00:47 +0000573 void AddConstraintsForNonInternalLinkage(Function *F);
574 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000575 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000576
577
578 void PrintNode(Node *N);
579 void PrintConstraints();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000580 void PrintConstraint(const Constraint &);
581 void PrintLabels();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000582 void PrintPointsToGraph();
583
584 //===------------------------------------------------------------------===//
585 // Instruction visitation methods for adding constraints
586 //
587 friend class InstVisitor<Andersens>;
588 void visitReturnInst(ReturnInst &RI);
589 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
590 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
591 void visitCallSite(CallSite CS);
592 void visitAllocationInst(AllocationInst &AI);
593 void visitLoadInst(LoadInst &LI);
594 void visitStoreInst(StoreInst &SI);
595 void visitGetElementPtrInst(GetElementPtrInst &GEP);
596 void visitPHINode(PHINode &PN);
597 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000598 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
599 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000600 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000601 void visitVAArg(VAArgInst &I);
602 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000603
Chris Lattnere995a2a2004-05-23 21:00:47 +0000604 };
605
Devang Patel19974732007-05-03 01:11:54 +0000606 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000607 RegisterPass<Andersens> X("anders-aa",
608 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000609 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000610
611 // Initialize Timestamp Counter (static).
612 unsigned Andersens::Node::Counter = 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000613}
614
Jeff Cohen534927d2005-01-08 22:01:16 +0000615ModulePass *llvm::createAndersensPass() { return new Andersens(); }
616
Chris Lattnere995a2a2004-05-23 21:00:47 +0000617//===----------------------------------------------------------------------===//
618// AliasAnalysis Interface Implementation
619//===----------------------------------------------------------------------===//
620
621AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
622 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000623 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
624 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000625
626 // Check to see if the two pointers are known to not alias. They don't alias
627 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000628 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000629 return NoAlias;
630
631 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
632}
633
Chris Lattnerf392c642005-03-28 06:21:17 +0000634AliasAnalysis::ModRefResult
635Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
636 // The only thing useful that we can contribute for mod/ref information is
637 // when calling external function calls: if we know that memory never escapes
638 // from the program, it cannot be modified by an external call.
639 //
640 // NOTE: This is not really safe, at least not when the entire program is not
641 // available. The deal is that the external function could call back into the
642 // program and modify stuff. We ignore this technical niggle for now. This
643 // is, after all, a "research quality" implementation of Andersen's analysis.
644 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000645 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000646 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000647
Daniel Berlinaad15882007-09-16 21:45:02 +0000648 if (N1->PointsTo->empty())
649 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000650#if FULL_UNIVERSAL
651 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
652 return NoModRef; // Universal set does not contain P
653#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000654 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000655 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000656#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000657 }
658
659 return AliasAnalysis::getModRefInfo(CS, P, Size);
660}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000661
Reid Spencer3a9ec242006-08-28 01:02:49 +0000662AliasAnalysis::ModRefResult
663Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
664 return AliasAnalysis::getModRefInfo(CS1,CS2);
665}
666
Chris Lattnere995a2a2004-05-23 21:00:47 +0000667/// getMustAlias - We can provide must alias information if we know that a
668/// pointer can only point to a specific function or the null pointer.
669/// Unfortunately we cannot determine must-alias information for global
670/// variables or any other memory memory objects because we do not track whether
671/// a pointer points to the beginning of an object or a field of it.
672void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000673 Node *N = &GraphNodes[FindNode(getNode(P))];
674 if (N->PointsTo->count() == 1) {
675 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
676 // If a function is the only object in the points-to set, then it must be
677 // the destination. Note that we can't handle global variables here,
678 // because we don't know if the pointer is actually pointing to a field of
679 // the global or to the beginning of it.
680 if (Value *V = Pointee->getValue()) {
681 if (Function *F = dyn_cast<Function>(V))
682 RetVals.push_back(F);
683 } else {
684 // If the object in the points-to set is the null object, then the null
685 // pointer is a must alias.
686 if (Pointee == &GraphNodes[NullObject])
687 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000688 }
689 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000690 AliasAnalysis::getMustAliases(P, RetVals);
691}
692
693/// pointsToConstantMemory - If we can determine that this pointer only points
694/// to constant memory, return true. In practice, this means that if the
695/// pointer can only point to constant globals, functions, or the null pointer,
696/// return true.
697///
698bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000699 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000700 unsigned i;
701
702 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
703 bi != N->PointsTo->end();
704 ++bi) {
705 i = *bi;
706 Node *Pointee = &GraphNodes[i];
707 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000708 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
709 !cast<GlobalVariable>(V)->isConstant()))
710 return AliasAnalysis::pointsToConstantMemory(P);
711 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000712 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000713 return AliasAnalysis::pointsToConstantMemory(P);
714 }
715 }
716
717 return true;
718}
719
720//===----------------------------------------------------------------------===//
721// Object Identification Phase
722//===----------------------------------------------------------------------===//
723
724/// IdentifyObjects - This stage scans the program, adding an entry to the
725/// GraphNodes list for each memory object in the program (global stack or
726/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
727///
728void Andersens::IdentifyObjects(Module &M) {
729 unsigned NumObjects = 0;
730
731 // Object #0 is always the universal set: the object that we don't know
732 // anything about.
733 assert(NumObjects == UniversalSet && "Something changed!");
734 ++NumObjects;
735
736 // Object #1 always represents the null pointer.
737 assert(NumObjects == NullPtr && "Something changed!");
738 ++NumObjects;
739
740 // Object #2 always represents the null object (the object pointed to by null)
741 assert(NumObjects == NullObject && "Something changed!");
742 ++NumObjects;
743
744 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000745 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
746 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000747 ObjectNodes[I] = NumObjects++;
748 ValueNodes[I] = NumObjects++;
749 }
750
751 // Add nodes for all of the functions and the instructions inside of them.
752 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
753 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000754 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000755 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000756 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
757 ReturnNodes[F] = NumObjects++;
758 if (F->getFunctionType()->isVarArg())
759 VarargNodes[F] = NumObjects++;
760
Daniel Berlinaad15882007-09-16 21:45:02 +0000761
Chris Lattnere995a2a2004-05-23 21:00:47 +0000762 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000763 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
764 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000765 {
766 if (isa<PointerType>(I->getType()))
767 ValueNodes[I] = NumObjects++;
768 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000769 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000770
771 // Scan the function body, creating a memory object for each heap/stack
772 // allocation in the body of the function and a node to represent all
773 // pointer values defined by instructions and used as operands.
774 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
775 // If this is an heap or stack allocation, create a node for the memory
776 // object.
777 if (isa<PointerType>(II->getType())) {
778 ValueNodes[&*II] = NumObjects++;
779 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
780 ObjectNodes[AI] = NumObjects++;
781 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000782
783 // Calls to inline asm need to be added as well because the callee isn't
784 // referenced anywhere else.
785 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
786 Value *Callee = CI->getCalledValue();
787 if (isa<InlineAsm>(Callee))
788 ValueNodes[Callee] = NumObjects++;
789 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000790 }
791 }
792
793 // Now that we know how many objects to create, make them all now!
794 GraphNodes.resize(NumObjects);
795 NumNodes += NumObjects;
796}
797
798//===----------------------------------------------------------------------===//
799// Constraint Identification Phase
800//===----------------------------------------------------------------------===//
801
802/// getNodeForConstantPointer - Return the node corresponding to the constant
803/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000804unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000805 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
806
Chris Lattner267a1b02005-03-27 18:58:23 +0000807 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000808 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000809 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
810 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000811 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
812 switch (CE->getOpcode()) {
813 case Instruction::GetElementPtr:
814 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000815 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000816 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000817 case Instruction::BitCast:
818 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000819 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000820 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000821 assert(0);
822 }
823 } else {
824 assert(0 && "Unknown constant pointer!");
825 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000826 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000827}
828
829/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
830/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000831unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000832 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
833
834 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000835 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000836 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
837 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000838 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
839 switch (CE->getOpcode()) {
840 case Instruction::GetElementPtr:
841 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000842 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000843 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000844 case Instruction::BitCast:
845 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000846 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000847 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000848 assert(0);
849 }
850 } else {
851 assert(0 && "Unknown constant pointer!");
852 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000853 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000854}
855
856/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
857/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000858void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
859 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000860 if (C->getType()->isFirstClassType()) {
861 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000862 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
863 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000864 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000865 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
866 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000867 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000868 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000869 // If this is an array or struct, include constraints for each element.
870 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
871 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000872 AddGlobalInitializerConstraints(NodeIndex,
873 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000874 }
875}
876
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000877/// AddConstraintsForNonInternalLinkage - If this function does not have
878/// internal linkage, realize that we can't trust anything passed into or
879/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000880void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000881 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000882 if (isa<PointerType>(I->getType()))
883 // If this is an argument of an externally accessible function, the
884 // incoming pointer might point to anything.
885 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000886 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000887}
888
Chris Lattner8a446432005-03-29 06:09:07 +0000889/// AddConstraintsForCall - If this is a call to a "known" function, add the
890/// constraints and return true. If this is a call to an unknown function,
891/// return false.
892bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000893 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000894
895 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000896 if (F->getName() == "atoi" || F->getName() == "atof" ||
897 F->getName() == "atol" || F->getName() == "atoll" ||
898 F->getName() == "remove" || F->getName() == "unlink" ||
899 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000900 F->getName() == "llvm.memset.i32" ||
901 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000902 F->getName() == "strcmp" || F->getName() == "strncmp" ||
903 F->getName() == "execl" || F->getName() == "execlp" ||
904 F->getName() == "execle" || F->getName() == "execv" ||
905 F->getName() == "execvp" || F->getName() == "chmod" ||
906 F->getName() == "puts" || F->getName() == "write" ||
907 F->getName() == "open" || F->getName() == "create" ||
908 F->getName() == "truncate" || F->getName() == "chdir" ||
909 F->getName() == "mkdir" || F->getName() == "rmdir" ||
910 F->getName() == "read" || F->getName() == "pipe" ||
911 F->getName() == "wait" || F->getName() == "time" ||
912 F->getName() == "stat" || F->getName() == "fstat" ||
913 F->getName() == "lstat" || F->getName() == "strtod" ||
914 F->getName() == "strtof" || F->getName() == "strtold" ||
915 F->getName() == "fopen" || F->getName() == "fdopen" ||
916 F->getName() == "freopen" ||
917 F->getName() == "fflush" || F->getName() == "feof" ||
918 F->getName() == "fileno" || F->getName() == "clearerr" ||
919 F->getName() == "rewind" || F->getName() == "ftell" ||
920 F->getName() == "ferror" || F->getName() == "fgetc" ||
921 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
922 F->getName() == "fwrite" || F->getName() == "fread" ||
923 F->getName() == "fgets" || F->getName() == "ungetc" ||
924 F->getName() == "fputc" ||
925 F->getName() == "fputs" || F->getName() == "putc" ||
926 F->getName() == "ftell" || F->getName() == "rewind" ||
927 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
928 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
929 F->getName() == "printf" || F->getName() == "fprintf" ||
930 F->getName() == "sprintf" || F->getName() == "vprintf" ||
931 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
932 F->getName() == "scanf" || F->getName() == "fscanf" ||
933 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
934 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000935 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000936
Chris Lattner175b9632005-03-29 20:36:05 +0000937
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000938 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000939 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000940 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000941 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000942
943 // *Dest = *Src, which requires an artificial graph node to represent the
944 // constraint. It is broken up into *Dest = temp, temp = *Src
945 unsigned FirstArg = getNode(CS.getArgument(0));
946 unsigned SecondArg = getNode(CS.getArgument(1));
947 unsigned TempArg = GraphNodes.size();
948 GraphNodes.push_back(Node());
949 Constraints.push_back(Constraint(Constraint::Store,
950 FirstArg, TempArg));
951 Constraints.push_back(Constraint(Constraint::Load,
952 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000953 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000954 }
955
Chris Lattner77b50562005-03-29 20:04:24 +0000956 // Result = Arg0
957 if (F->getName() == "realloc" || F->getName() == "strchr" ||
958 F->getName() == "strrchr" || F->getName() == "strstr" ||
959 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000960 Constraints.push_back(Constraint(Constraint::Copy,
961 getNode(CS.getInstruction()),
962 getNode(CS.getArgument(0))));
963 return true;
964 }
965
966 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000967}
968
969
Chris Lattnere995a2a2004-05-23 21:00:47 +0000970
Daniel Berlinaad15882007-09-16 21:45:02 +0000971/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
972/// If this is used by anything complex (i.e., the address escapes), return
973/// true.
974bool Andersens::AnalyzeUsesOfFunction(Value *V) {
975
976 if (!isa<PointerType>(V->getType())) return true;
977
978 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
979 if (dyn_cast<LoadInst>(*UI)) {
980 return false;
981 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
982 if (V == SI->getOperand(1)) {
983 return false;
984 } else if (SI->getOperand(1)) {
985 return true; // Storing the pointer
986 }
987 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
988 if (AnalyzeUsesOfFunction(GEP)) return true;
989 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
990 // Make sure that this is just the function being called, not that it is
991 // passing into the function.
992 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
993 if (CI->getOperand(i) == V) return true;
994 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
995 // Make sure that this is just the function being called, not that it is
996 // passing into the function.
997 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
998 if (II->getOperand(i) == V) return true;
999 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1000 if (CE->getOpcode() == Instruction::GetElementPtr ||
1001 CE->getOpcode() == Instruction::BitCast) {
1002 if (AnalyzeUsesOfFunction(CE))
1003 return true;
1004 } else {
1005 return true;
1006 }
1007 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1008 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1009 return true; // Allow comparison against null.
1010 } else if (dyn_cast<FreeInst>(*UI)) {
1011 return false;
1012 } else {
1013 return true;
1014 }
1015 return false;
1016}
1017
Chris Lattnere995a2a2004-05-23 21:00:47 +00001018/// CollectConstraints - This stage scans the program, adding a constraint to
1019/// the Constraints list for each instruction in the program that induces a
1020/// constraint, and setting up the initial points-to graph.
1021///
1022void Andersens::CollectConstraints(Module &M) {
1023 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001024 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1025 UniversalSet));
1026 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1027 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001028
1029 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001030 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001031
1032 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001033 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1034 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001035 // Associate the address of the global object as pointing to the memory for
1036 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001037 unsigned ObjectIndex = getObject(I);
1038 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001039 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001040 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1041 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001042
1043 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001044 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001045 } else {
1046 // If it doesn't have an initializer (i.e. it's defined in another
1047 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001048 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1049 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001050 }
1051 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001052
Chris Lattnere995a2a2004-05-23 21:00:47 +00001053 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001054 // Set up the return value node.
1055 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001056 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001057 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001058 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001059
1060 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001061 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1062 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001063 if (isa<PointerType>(I->getType()))
1064 getNodeValue(*I);
1065
Daniel Berlinaad15882007-09-16 21:45:02 +00001066 // At some point we should just add constraints for the escaping functions
1067 // at solve time, but this slows down solving. For now, we simply mark
1068 // address taken functions as escaping and treat them as external.
1069 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001070 AddConstraintsForNonInternalLinkage(F);
1071
Reid Spencer5cbf9852007-01-30 20:08:39 +00001072 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001073 // Scan the function body, creating a memory object for each heap/stack
1074 // allocation in the body of the function and a node to represent all
1075 // pointer values defined by instructions and used as operands.
1076 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001077 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001078 // External functions that return pointers return the universal set.
1079 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1080 Constraints.push_back(Constraint(Constraint::Copy,
1081 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001082 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001083
1084 // Any pointers that are passed into the function have the universal set
1085 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001086 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1087 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001088 if (isa<PointerType>(I->getType())) {
1089 // Pointers passed into external functions could have anything stored
1090 // through them.
1091 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001092 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001093 // Memory objects passed into external function calls can have the
1094 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001095#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001096 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001097 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001098 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001099#else
1100 Constraints.push_back(Constraint(Constraint::Copy,
1101 getNode(I),
1102 UniversalSet));
1103#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001104 }
1105
1106 // If this is an external varargs function, it can also store pointers
1107 // into any pointers passed through the varargs section.
1108 if (F->getFunctionType()->isVarArg())
1109 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001110 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001111 }
1112 }
1113 NumConstraints += Constraints.size();
1114}
1115
1116
1117void Andersens::visitInstruction(Instruction &I) {
1118#ifdef NDEBUG
1119 return; // This function is just a big assert.
1120#endif
1121 if (isa<BinaryOperator>(I))
1122 return;
1123 // Most instructions don't have any effect on pointer values.
1124 switch (I.getOpcode()) {
1125 case Instruction::Br:
1126 case Instruction::Switch:
1127 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001128 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001129 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001130 case Instruction::ICmp:
1131 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001132 return;
1133 default:
1134 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001135 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001136 abort();
1137 }
1138}
1139
1140void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001141 unsigned ObjectIndex = getObject(&AI);
1142 GraphNodes[ObjectIndex].setValue(&AI);
1143 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1144 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001145}
1146
1147void Andersens::visitReturnInst(ReturnInst &RI) {
1148 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1149 // return V --> <Copy/retval{F}/v>
1150 Constraints.push_back(Constraint(Constraint::Copy,
1151 getReturnNode(RI.getParent()->getParent()),
1152 getNode(RI.getOperand(0))));
1153}
1154
1155void Andersens::visitLoadInst(LoadInst &LI) {
1156 if (isa<PointerType>(LI.getType()))
1157 // P1 = load P2 --> <Load/P1/P2>
1158 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1159 getNode(LI.getOperand(0))));
1160}
1161
1162void Andersens::visitStoreInst(StoreInst &SI) {
1163 if (isa<PointerType>(SI.getOperand(0)->getType()))
1164 // store P1, P2 --> <Store/P2/P1>
1165 Constraints.push_back(Constraint(Constraint::Store,
1166 getNode(SI.getOperand(1)),
1167 getNode(SI.getOperand(0))));
1168}
1169
1170void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1171 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1172 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1173 getNode(GEP.getOperand(0))));
1174}
1175
1176void Andersens::visitPHINode(PHINode &PN) {
1177 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001178 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001179 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1180 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1181 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1182 getNode(PN.getIncomingValue(i))));
1183 }
1184}
1185
1186void Andersens::visitCastInst(CastInst &CI) {
1187 Value *Op = CI.getOperand(0);
1188 if (isa<PointerType>(CI.getType())) {
1189 if (isa<PointerType>(Op->getType())) {
1190 // P1 = cast P2 --> <Copy/P1/P2>
1191 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1192 getNode(CI.getOperand(0))));
1193 } else {
1194 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001195#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001196 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001197 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001198#else
1199 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001200#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001201 }
1202 } else if (isa<PointerType>(Op->getType())) {
1203 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001204#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001205 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001206 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001207 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001208#else
1209 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001210#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001211 }
1212}
1213
1214void Andersens::visitSelectInst(SelectInst &SI) {
1215 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001216 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001217 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1218 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1219 getNode(SI.getOperand(1))));
1220 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1221 getNode(SI.getOperand(2))));
1222 }
1223}
1224
Chris Lattnere995a2a2004-05-23 21:00:47 +00001225void Andersens::visitVAArg(VAArgInst &I) {
1226 assert(0 && "vaarg not handled yet!");
1227}
1228
1229/// AddConstraintsForCall - Add constraints for a call with actual arguments
1230/// specified by CS to the function specified by F. Note that the types of
1231/// arguments might not match up in the case where this is an indirect call and
1232/// the function pointer has been casted. If this is the case, do something
1233/// reasonable.
1234void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001235 Value *CallValue = CS.getCalledValue();
1236 bool IsDeref = F == NULL;
1237
1238 // If this is a call to an external function, try to handle it directly to get
1239 // some taste of context sensitivity.
1240 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001241 return;
1242
Chris Lattnere995a2a2004-05-23 21:00:47 +00001243 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001244 unsigned CSN = getNode(CS.getInstruction());
1245 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1246 if (IsDeref)
1247 Constraints.push_back(Constraint(Constraint::Load, CSN,
1248 getNode(CallValue), CallReturnPos));
1249 else
1250 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1251 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001252 } else {
1253 // If the function returns a non-pointer value, handle this just like we
1254 // treat a nonpointer cast to pointer.
1255 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001256 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001257 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001258 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001259#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001260 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001261 UniversalSet,
1262 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001263#else
1264 Constraints.push_back(Constraint(Constraint::Copy,
1265 getNode(CallValue) + CallReturnPos,
1266 UniversalSet));
1267#endif
1268
1269
Chris Lattnere995a2a2004-05-23 21:00:47 +00001270 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001271
Chris Lattnere995a2a2004-05-23 21:00:47 +00001272 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001273 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001274 if (F) {
1275 // Direct Call
1276 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001277 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1278 {
1279#if !FULL_UNIVERSAL
1280 if (external && isa<PointerType>((*ArgI)->getType()))
1281 {
1282 // Add constraint that ArgI can now point to anything due to
1283 // escaping, as can everything it points to. The second portion of
1284 // this should be taken care of by universal = *universal
1285 Constraints.push_back(Constraint(Constraint::Copy,
1286 getNode(*ArgI),
1287 UniversalSet));
1288 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001289#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001290 if (isa<PointerType>(AI->getType())) {
1291 if (isa<PointerType>((*ArgI)->getType())) {
1292 // Copy the actual argument into the formal argument.
1293 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1294 getNode(*ArgI)));
1295 } else {
1296 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1297 UniversalSet));
1298 }
1299 } else if (isa<PointerType>((*ArgI)->getType())) {
1300#if FULL_UNIVERSAL
1301 Constraints.push_back(Constraint(Constraint::Copy,
1302 UniversalSet,
1303 getNode(*ArgI)));
1304#else
1305 Constraints.push_back(Constraint(Constraint::Copy,
1306 getNode(*ArgI),
1307 UniversalSet));
1308#endif
1309 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001310 }
1311 } else {
1312 //Indirect Call
1313 unsigned ArgPos = CallFirstArgPos;
1314 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001315 if (isa<PointerType>((*ArgI)->getType())) {
1316 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001317 Constraints.push_back(Constraint(Constraint::Store,
1318 getNode(CallValue),
1319 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001320 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001321 Constraints.push_back(Constraint(Constraint::Store,
1322 getNode (CallValue),
1323 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001324 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001325 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001326 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001327 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001328 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001329 for (; ArgI != ArgE; ++ArgI)
1330 if (isa<PointerType>((*ArgI)->getType()))
1331 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1332 getNode(*ArgI)));
1333 // If more arguments are passed in than we track, just drop them on the floor.
1334}
1335
1336void Andersens::visitCallSite(CallSite CS) {
1337 if (isa<PointerType>(CS.getType()))
1338 getNodeValue(*CS.getInstruction());
1339
1340 if (Function *F = CS.getCalledFunction()) {
1341 AddConstraintsForCall(CS, F);
1342 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001343 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001344 }
1345}
1346
1347//===----------------------------------------------------------------------===//
1348// Constraint Solving Phase
1349//===----------------------------------------------------------------------===//
1350
1351/// intersects - Return true if the points-to set of this node intersects
1352/// with the points-to set of the specified node.
1353bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001354 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001355}
1356
1357/// intersectsIgnoring - Return true if the points-to set of this node
1358/// intersects with the points-to set of the specified node on any nodes
1359/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001360bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1361 // TODO: If we are only going to call this with the same value for Ignoring,
1362 // we should move the special values out of the points-to bitmap.
1363 bool WeHadIt = PointsTo->test(Ignoring);
1364 bool NHadIt = N->PointsTo->test(Ignoring);
1365 bool Result = false;
1366 if (WeHadIt)
1367 PointsTo->reset(Ignoring);
1368 if (NHadIt)
1369 N->PointsTo->reset(Ignoring);
1370 Result = PointsTo->intersects(N->PointsTo);
1371 if (WeHadIt)
1372 PointsTo->set(Ignoring);
1373 if (NHadIt)
1374 N->PointsTo->set(Ignoring);
1375 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001376}
1377
Daniel Berlind81ccc22007-09-24 19:45:49 +00001378void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001379#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001380 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001381#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001382}
1383
1384
1385/// Clump together address taken variables so that the points-to sets use up
1386/// less space and can be operated on faster.
1387
1388void Andersens::ClumpAddressTaken() {
1389#undef DEBUG_TYPE
1390#define DEBUG_TYPE "anders-aa-renumber"
1391 std::vector<unsigned> Translate;
1392 std::vector<Node> NewGraphNodes;
1393
1394 Translate.resize(GraphNodes.size());
1395 unsigned NewPos = 0;
1396
1397 for (unsigned i = 0; i < Constraints.size(); ++i) {
1398 Constraint &C = Constraints[i];
1399 if (C.Type == Constraint::AddressOf) {
1400 GraphNodes[C.Src].AddressTaken = true;
1401 }
1402 }
1403 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1404 unsigned Pos = NewPos++;
1405 Translate[i] = Pos;
1406 NewGraphNodes.push_back(GraphNodes[i]);
1407 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1408 }
1409
1410 // I believe this ends up being faster than making two vectors and splicing
1411 // them.
1412 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1413 if (GraphNodes[i].AddressTaken) {
1414 unsigned Pos = NewPos++;
1415 Translate[i] = Pos;
1416 NewGraphNodes.push_back(GraphNodes[i]);
1417 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1418 }
1419 }
1420
1421 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1422 if (!GraphNodes[i].AddressTaken) {
1423 unsigned Pos = NewPos++;
1424 Translate[i] = Pos;
1425 NewGraphNodes.push_back(GraphNodes[i]);
1426 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1427 }
1428 }
1429
1430 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1431 Iter != ValueNodes.end();
1432 ++Iter)
1433 Iter->second = Translate[Iter->second];
1434
1435 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1436 Iter != ObjectNodes.end();
1437 ++Iter)
1438 Iter->second = Translate[Iter->second];
1439
1440 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1441 Iter != ReturnNodes.end();
1442 ++Iter)
1443 Iter->second = Translate[Iter->second];
1444
1445 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1446 Iter != VarargNodes.end();
1447 ++Iter)
1448 Iter->second = Translate[Iter->second];
1449
1450 for (unsigned i = 0; i < Constraints.size(); ++i) {
1451 Constraint &C = Constraints[i];
1452 C.Src = Translate[C.Src];
1453 C.Dest = Translate[C.Dest];
1454 }
1455
1456 GraphNodes.swap(NewGraphNodes);
1457#undef DEBUG_TYPE
1458#define DEBUG_TYPE "anders-aa"
1459}
1460
1461/// The technique used here is described in "Exploiting Pointer and Location
1462/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1463/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1464/// and is equivalent to value numbering the collapsed constraint graph without
1465/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1466/// first order pointer dereferences and speed up/reduce memory usage of HU.
1467/// Running both is equivalent to HRU without the iteration
1468/// HVN in more detail:
1469/// Imagine the set of constraints was simply straight line code with no loops
1470/// (we eliminate cycles, so there are no loops), such as:
1471/// E = &D
1472/// E = &C
1473/// E = F
1474/// F = G
1475/// G = F
1476/// Applying value numbering to this code tells us:
1477/// G == F == E
1478///
1479/// For HVN, this is as far as it goes. We assign new value numbers to every
1480/// "address node", and every "reference node".
1481/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1482/// cycle must have the same value number since the = operation is really
1483/// inclusion, not overwrite), and value number nodes we receive points-to sets
1484/// before we value our own node.
1485/// The advantage of HU over HVN is that HU considers the inclusion property, so
1486/// that if you have
1487/// E = &D
1488/// E = &C
1489/// E = F
1490/// F = G
1491/// F = &D
1492/// G = F
1493/// HU will determine that G == F == E. HVN will not, because it cannot prove
1494/// that the points to information ends up being the same because they all
1495/// receive &D from E anyway.
1496
1497void Andersens::HVN() {
1498 DOUT << "Beginning HVN\n";
1499 // Build a predecessor graph. This is like our constraint graph with the
1500 // edges going in the opposite direction, and there are edges for all the
1501 // constraints, instead of just copy constraints. We also build implicit
1502 // edges for constraints are implied but not explicit. I.E for the constraint
1503 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1504 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1505 Constraint &C = Constraints[i];
1506 if (C.Type == Constraint::AddressOf) {
1507 GraphNodes[C.Src].AddressTaken = true;
1508 GraphNodes[C.Src].Direct = false;
1509
1510 // Dest = &src edge
1511 unsigned AdrNode = C.Src + FirstAdrNode;
1512 if (!GraphNodes[C.Dest].PredEdges)
1513 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1514 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1515
1516 // *Dest = src edge
1517 unsigned RefNode = C.Dest + FirstRefNode;
1518 if (!GraphNodes[RefNode].ImplicitPredEdges)
1519 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1520 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1521 } else if (C.Type == Constraint::Load) {
1522 if (C.Offset == 0) {
1523 // dest = *src edge
1524 if (!GraphNodes[C.Dest].PredEdges)
1525 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1526 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1527 } else {
1528 GraphNodes[C.Dest].Direct = false;
1529 }
1530 } else if (C.Type == Constraint::Store) {
1531 if (C.Offset == 0) {
1532 // *dest = src edge
1533 unsigned RefNode = C.Dest + FirstRefNode;
1534 if (!GraphNodes[RefNode].PredEdges)
1535 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1536 GraphNodes[RefNode].PredEdges->set(C.Src);
1537 }
1538 } else {
1539 // Dest = Src edge and *Dest = *Src edge
1540 if (!GraphNodes[C.Dest].PredEdges)
1541 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1542 GraphNodes[C.Dest].PredEdges->set(C.Src);
1543 unsigned RefNode = C.Dest + FirstRefNode;
1544 if (!GraphNodes[RefNode].ImplicitPredEdges)
1545 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1546 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1547 }
1548 }
1549 PEClass = 1;
1550 // Do SCC finding first to condense our predecessor graph
1551 DFSNumber = 0;
1552 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1553 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1554 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1555
1556 for (unsigned i = 0; i < FirstRefNode; ++i) {
1557 unsigned Node = VSSCCRep[i];
1558 if (!Node2Visited[Node])
1559 HVNValNum(Node);
1560 }
1561 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1562 Iter != Set2PEClass.end();
1563 ++Iter)
1564 delete Iter->first;
1565 Set2PEClass.clear();
1566 Node2DFS.clear();
1567 Node2Deleted.clear();
1568 Node2Visited.clear();
1569 DOUT << "Finished HVN\n";
1570
1571}
1572
1573/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1574/// same time because it's easy.
1575void Andersens::HVNValNum(unsigned NodeIndex) {
1576 unsigned MyDFS = DFSNumber++;
1577 Node *N = &GraphNodes[NodeIndex];
1578 Node2Visited[NodeIndex] = true;
1579 Node2DFS[NodeIndex] = MyDFS;
1580
1581 // First process all our explicit edges
1582 if (N->PredEdges)
1583 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1584 Iter != N->PredEdges->end();
1585 ++Iter) {
1586 unsigned j = VSSCCRep[*Iter];
1587 if (!Node2Deleted[j]) {
1588 if (!Node2Visited[j])
1589 HVNValNum(j);
1590 if (Node2DFS[NodeIndex] > Node2DFS[j])
1591 Node2DFS[NodeIndex] = Node2DFS[j];
1592 }
1593 }
1594
1595 // Now process all the implicit edges
1596 if (N->ImplicitPredEdges)
1597 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1598 Iter != N->ImplicitPredEdges->end();
1599 ++Iter) {
1600 unsigned j = VSSCCRep[*Iter];
1601 if (!Node2Deleted[j]) {
1602 if (!Node2Visited[j])
1603 HVNValNum(j);
1604 if (Node2DFS[NodeIndex] > Node2DFS[j])
1605 Node2DFS[NodeIndex] = Node2DFS[j];
1606 }
1607 }
1608
1609 // See if we found any cycles
1610 if (MyDFS == Node2DFS[NodeIndex]) {
1611 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1612 unsigned CycleNodeIndex = SCCStack.top();
1613 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1614 VSSCCRep[CycleNodeIndex] = NodeIndex;
1615 // Unify the nodes
1616 N->Direct &= CycleNode->Direct;
1617
1618 if (CycleNode->PredEdges) {
1619 if (!N->PredEdges)
1620 N->PredEdges = new SparseBitVector<>;
1621 *(N->PredEdges) |= CycleNode->PredEdges;
1622 delete CycleNode->PredEdges;
1623 CycleNode->PredEdges = NULL;
1624 }
1625 if (CycleNode->ImplicitPredEdges) {
1626 if (!N->ImplicitPredEdges)
1627 N->ImplicitPredEdges = new SparseBitVector<>;
1628 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1629 delete CycleNode->ImplicitPredEdges;
1630 CycleNode->ImplicitPredEdges = NULL;
1631 }
1632
1633 SCCStack.pop();
1634 }
1635
1636 Node2Deleted[NodeIndex] = true;
1637
1638 if (!N->Direct) {
1639 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1640 return;
1641 }
1642
1643 // Collect labels of successor nodes
1644 bool AllSame = true;
1645 unsigned First = ~0;
1646 SparseBitVector<> *Labels = new SparseBitVector<>;
1647 bool Used = false;
1648
1649 if (N->PredEdges)
1650 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1651 Iter != N->PredEdges->end();
1652 ++Iter) {
1653 unsigned j = VSSCCRep[*Iter];
1654 unsigned Label = GraphNodes[j].PointerEquivLabel;
1655 // Ignore labels that are equal to us or non-pointers
1656 if (j == NodeIndex || Label == 0)
1657 continue;
1658 if (First == (unsigned)~0)
1659 First = Label;
1660 else if (First != Label)
1661 AllSame = false;
1662 Labels->set(Label);
1663 }
1664
1665 // We either have a non-pointer, a copy of an existing node, or a new node.
1666 // Assign the appropriate pointer equivalence label.
1667 if (Labels->empty()) {
1668 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1669 } else if (AllSame) {
1670 GraphNodes[NodeIndex].PointerEquivLabel = First;
1671 } else {
1672 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1673 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1674 unsigned EquivClass = PEClass++;
1675 Set2PEClass[Labels] = EquivClass;
1676 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1677 Used = true;
1678 }
1679 }
1680 if (!Used)
1681 delete Labels;
1682 } else {
1683 SCCStack.push(NodeIndex);
1684 }
1685}
1686
1687/// The technique used here is described in "Exploiting Pointer and Location
1688/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1689/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1690/// and is equivalent to value numbering the collapsed constraint graph
1691/// including evaluating unions.
1692void Andersens::HU() {
1693 DOUT << "Beginning HU\n";
1694 // Build a predecessor graph. This is like our constraint graph with the
1695 // edges going in the opposite direction, and there are edges for all the
1696 // constraints, instead of just copy constraints. We also build implicit
1697 // edges for constraints are implied but not explicit. I.E for the constraint
1698 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1699 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1700 Constraint &C = Constraints[i];
1701 if (C.Type == Constraint::AddressOf) {
1702 GraphNodes[C.Src].AddressTaken = true;
1703 GraphNodes[C.Src].Direct = false;
1704
1705 GraphNodes[C.Dest].PointsTo->set(C.Src);
1706 // *Dest = src edge
1707 unsigned RefNode = C.Dest + FirstRefNode;
1708 if (!GraphNodes[RefNode].ImplicitPredEdges)
1709 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1710 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1711 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1712 } else if (C.Type == Constraint::Load) {
1713 if (C.Offset == 0) {
1714 // dest = *src edge
1715 if (!GraphNodes[C.Dest].PredEdges)
1716 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1717 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1718 } else {
1719 GraphNodes[C.Dest].Direct = false;
1720 }
1721 } else if (C.Type == Constraint::Store) {
1722 if (C.Offset == 0) {
1723 // *dest = src edge
1724 unsigned RefNode = C.Dest + FirstRefNode;
1725 if (!GraphNodes[RefNode].PredEdges)
1726 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1727 GraphNodes[RefNode].PredEdges->set(C.Src);
1728 }
1729 } else {
1730 // Dest = Src edge and *Dest = *Src edg
1731 if (!GraphNodes[C.Dest].PredEdges)
1732 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1733 GraphNodes[C.Dest].PredEdges->set(C.Src);
1734 unsigned RefNode = C.Dest + FirstRefNode;
1735 if (!GraphNodes[RefNode].ImplicitPredEdges)
1736 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1737 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1738 }
1739 }
1740 PEClass = 1;
1741 // Do SCC finding first to condense our predecessor graph
1742 DFSNumber = 0;
1743 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1744 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1745 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1746
1747 for (unsigned i = 0; i < FirstRefNode; ++i) {
1748 if (FindNode(i) == i) {
1749 unsigned Node = VSSCCRep[i];
1750 if (!Node2Visited[Node])
1751 Condense(Node);
1752 }
1753 }
1754
1755 // Reset tables for actual labeling
1756 Node2DFS.clear();
1757 Node2Visited.clear();
1758 Node2Deleted.clear();
1759 // Pre-grow our densemap so that we don't get really bad behavior
1760 Set2PEClass.resize(GraphNodes.size());
1761
1762 // Visit the condensed graph and generate pointer equivalence labels.
1763 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1764 for (unsigned i = 0; i < FirstRefNode; ++i) {
1765 if (FindNode(i) == i) {
1766 unsigned Node = VSSCCRep[i];
1767 if (!Node2Visited[Node])
1768 HUValNum(Node);
1769 }
1770 }
1771 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1772 Set2PEClass.clear();
1773 DOUT << "Finished HU\n";
1774}
1775
1776
1777/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1778void Andersens::Condense(unsigned NodeIndex) {
1779 unsigned MyDFS = DFSNumber++;
1780 Node *N = &GraphNodes[NodeIndex];
1781 Node2Visited[NodeIndex] = true;
1782 Node2DFS[NodeIndex] = MyDFS;
1783
1784 // First process all our explicit edges
1785 if (N->PredEdges)
1786 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1787 Iter != N->PredEdges->end();
1788 ++Iter) {
1789 unsigned j = VSSCCRep[*Iter];
1790 if (!Node2Deleted[j]) {
1791 if (!Node2Visited[j])
1792 Condense(j);
1793 if (Node2DFS[NodeIndex] > Node2DFS[j])
1794 Node2DFS[NodeIndex] = Node2DFS[j];
1795 }
1796 }
1797
1798 // Now process all the implicit edges
1799 if (N->ImplicitPredEdges)
1800 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1801 Iter != N->ImplicitPredEdges->end();
1802 ++Iter) {
1803 unsigned j = VSSCCRep[*Iter];
1804 if (!Node2Deleted[j]) {
1805 if (!Node2Visited[j])
1806 Condense(j);
1807 if (Node2DFS[NodeIndex] > Node2DFS[j])
1808 Node2DFS[NodeIndex] = Node2DFS[j];
1809 }
1810 }
1811
1812 // See if we found any cycles
1813 if (MyDFS == Node2DFS[NodeIndex]) {
1814 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1815 unsigned CycleNodeIndex = SCCStack.top();
1816 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1817 VSSCCRep[CycleNodeIndex] = NodeIndex;
1818 // Unify the nodes
1819 N->Direct &= CycleNode->Direct;
1820
1821 *(N->PointsTo) |= CycleNode->PointsTo;
1822 delete CycleNode->PointsTo;
1823 CycleNode->PointsTo = NULL;
1824 if (CycleNode->PredEdges) {
1825 if (!N->PredEdges)
1826 N->PredEdges = new SparseBitVector<>;
1827 *(N->PredEdges) |= CycleNode->PredEdges;
1828 delete CycleNode->PredEdges;
1829 CycleNode->PredEdges = NULL;
1830 }
1831 if (CycleNode->ImplicitPredEdges) {
1832 if (!N->ImplicitPredEdges)
1833 N->ImplicitPredEdges = new SparseBitVector<>;
1834 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1835 delete CycleNode->ImplicitPredEdges;
1836 CycleNode->ImplicitPredEdges = NULL;
1837 }
1838 SCCStack.pop();
1839 }
1840
1841 Node2Deleted[NodeIndex] = true;
1842
1843 // Set up number of incoming edges for other nodes
1844 if (N->PredEdges)
1845 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1846 Iter != N->PredEdges->end();
1847 ++Iter)
1848 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1849 } else {
1850 SCCStack.push(NodeIndex);
1851 }
1852}
1853
1854void Andersens::HUValNum(unsigned NodeIndex) {
1855 Node *N = &GraphNodes[NodeIndex];
1856 Node2Visited[NodeIndex] = true;
1857
1858 // Eliminate dereferences of non-pointers for those non-pointers we have
1859 // already identified. These are ref nodes whose non-ref node:
1860 // 1. Has already been visited determined to point to nothing (and thus, a
1861 // dereference of it must point to nothing)
1862 // 2. Any direct node with no predecessor edges in our graph and with no
1863 // points-to set (since it can't point to anything either, being that it
1864 // receives no points-to sets and has none).
1865 if (NodeIndex >= FirstRefNode) {
1866 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1867 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1868 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1869 && GraphNodes[j].PointsTo->empty())){
1870 return;
1871 }
1872 }
1873 // Process all our explicit edges
1874 if (N->PredEdges)
1875 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1876 Iter != N->PredEdges->end();
1877 ++Iter) {
1878 unsigned j = VSSCCRep[*Iter];
1879 if (!Node2Visited[j])
1880 HUValNum(j);
1881
1882 // If this edge turned out to be the same as us, or got no pointer
1883 // equivalence label (and thus points to nothing) , just decrement our
1884 // incoming edges and continue.
1885 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1886 --GraphNodes[j].NumInEdges;
1887 continue;
1888 }
1889
1890 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1891
1892 // If we didn't end up storing this in the hash, and we're done with all
1893 // the edges, we don't need the points-to set anymore.
1894 --GraphNodes[j].NumInEdges;
1895 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1896 delete GraphNodes[j].PointsTo;
1897 GraphNodes[j].PointsTo = NULL;
1898 }
1899 }
1900 // If this isn't a direct node, generate a fresh variable.
1901 if (!N->Direct) {
1902 N->PointsTo->set(FirstRefNode + NodeIndex);
1903 }
1904
1905 // See If we have something equivalent to us, if not, generate a new
1906 // equivalence class.
1907 if (N->PointsTo->empty()) {
1908 delete N->PointsTo;
1909 N->PointsTo = NULL;
1910 } else {
1911 if (N->Direct) {
1912 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1913 if (N->PointerEquivLabel == 0) {
1914 unsigned EquivClass = PEClass++;
1915 N->StoredInHash = true;
1916 Set2PEClass[N->PointsTo] = EquivClass;
1917 N->PointerEquivLabel = EquivClass;
1918 }
1919 } else {
1920 N->PointerEquivLabel = PEClass++;
1921 }
1922 }
1923}
1924
1925/// Rewrite our list of constraints so that pointer equivalent nodes are
1926/// replaced by their the pointer equivalence class representative.
1927void Andersens::RewriteConstraints() {
1928 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001929 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001930
1931 PEClass2Node.clear();
1932 PENLEClass2Node.clear();
1933
1934 // We may have from 1 to Graphnodes + 1 equivalence classes.
1935 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1936 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1937
1938 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1939 // nodes, and rewriting constraints to use the representative nodes.
1940 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1941 Constraint &C = Constraints[i];
1942 unsigned RHSNode = FindNode(C.Src);
1943 unsigned LHSNode = FindNode(C.Dest);
1944 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1945 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1946
1947 // First we try to eliminate constraints for things we can prove don't point
1948 // to anything.
1949 if (LHSLabel == 0) {
1950 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1951 DOUT << " is a non-pointer, ignoring constraint.\n";
1952 continue;
1953 }
1954 if (RHSLabel == 0) {
1955 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1956 DOUT << " is a non-pointer, ignoring constraint.\n";
1957 continue;
1958 }
1959 // This constraint may be useless, and it may become useless as we translate
1960 // it.
1961 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1962 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001963
Daniel Berlind81ccc22007-09-24 19:45:49 +00001964 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1965 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001966 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001967 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001968 continue;
1969
Chris Lattnerbe207732007-09-30 00:47:20 +00001970 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001971 NewConstraints.push_back(C);
1972 }
1973 Constraints.swap(NewConstraints);
1974 PEClass2Node.clear();
1975}
1976
1977/// See if we have a node that is pointer equivalent to the one being asked
1978/// about, and if so, unite them and return the equivalent node. Otherwise,
1979/// return the original node.
1980unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1981 unsigned NodeLabel) {
1982 if (!GraphNodes[NodeIndex].AddressTaken) {
1983 if (PEClass2Node[NodeLabel] != -1) {
1984 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001985 // We specifically request that Union-By-Rank not be used so that
1986 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1987 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001988 } else {
1989 PEClass2Node[NodeLabel] = NodeIndex;
1990 PENLEClass2Node[NodeLabel] = NodeIndex;
1991 }
1992 } else if (PENLEClass2Node[NodeLabel] == -1) {
1993 PENLEClass2Node[NodeLabel] = NodeIndex;
1994 }
1995
1996 return NodeIndex;
1997}
1998
1999void Andersens::PrintLabels() {
2000 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2001 if (i < FirstRefNode) {
2002 PrintNode(&GraphNodes[i]);
2003 } else if (i < FirstAdrNode) {
2004 DOUT << "REF(";
2005 PrintNode(&GraphNodes[i-FirstRefNode]);
2006 DOUT <<")";
2007 } else {
2008 DOUT << "ADR(";
2009 PrintNode(&GraphNodes[i-FirstAdrNode]);
2010 DOUT <<")";
2011 }
2012
2013 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2014 << " and SCC rep " << VSSCCRep[i]
2015 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2016 << "\n";
2017 }
2018}
2019
Daniel Berlinc864edb2008-03-05 19:31:47 +00002020/// The technique used here is described in "The Ant and the
2021/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2022/// Lines of Code. In Programming Language Design and Implementation
2023/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2024/// Detection) algorithm. It is called a hybrid because it performs an
2025/// offline analysis and uses its results during the solving (online)
2026/// phase. This is just the offline portion; the results of this
2027/// operation are stored in SDT and are later used in SolveContraints()
2028/// and UniteNodes().
2029void Andersens::HCD() {
2030 DOUT << "Starting HCD.\n";
2031 HCDSCCRep.resize(GraphNodes.size());
2032
2033 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2034 GraphNodes[i].Edges = new SparseBitVector<>;
2035 HCDSCCRep[i] = i;
2036 }
2037
2038 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2039 Constraint &C = Constraints[i];
2040 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2041 if (C.Type == Constraint::AddressOf) {
2042 continue;
2043 } else if (C.Type == Constraint::Load) {
2044 if( C.Offset == 0 )
2045 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2046 } else if (C.Type == Constraint::Store) {
2047 if( C.Offset == 0 )
2048 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2049 } else {
2050 GraphNodes[C.Dest].Edges->set(C.Src);
2051 }
2052 }
2053
2054 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2055 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2056 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2057 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2058
2059 DFSNumber = 0;
2060 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2061 unsigned Node = HCDSCCRep[i];
2062 if (!Node2Deleted[Node])
2063 Search(Node);
2064 }
2065
2066 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2067 if (GraphNodes[i].Edges != NULL) {
2068 delete GraphNodes[i].Edges;
2069 GraphNodes[i].Edges = NULL;
2070 }
2071
2072 while( !SCCStack.empty() )
2073 SCCStack.pop();
2074
2075 Node2DFS.clear();
2076 Node2Visited.clear();
2077 Node2Deleted.clear();
2078 HCDSCCRep.clear();
2079 DOUT << "HCD complete.\n";
2080}
2081
2082// Component of HCD:
2083// Use Nuutila's variant of Tarjan's algorithm to detect
2084// Strongly-Connected Components (SCCs). For non-trivial SCCs
2085// containing ref nodes, insert the appropriate information in SDT.
2086void Andersens::Search(unsigned Node) {
2087 unsigned MyDFS = DFSNumber++;
2088
2089 Node2Visited[Node] = true;
2090 Node2DFS[Node] = MyDFS;
2091
2092 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2093 End = GraphNodes[Node].Edges->end();
2094 Iter != End;
2095 ++Iter) {
2096 unsigned J = HCDSCCRep[*Iter];
2097 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2098 if (!Node2Deleted[J]) {
2099 if (!Node2Visited[J])
2100 Search(J);
2101 if (Node2DFS[Node] > Node2DFS[J])
2102 Node2DFS[Node] = Node2DFS[J];
2103 }
2104 }
2105
2106 if( MyDFS != Node2DFS[Node] ) {
2107 SCCStack.push(Node);
2108 return;
2109 }
2110
2111 // This node is the root of a SCC, so process it.
2112 //
2113 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2114 // node, we place this SCC into SDT. We unite the nodes in any case.
2115 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2116 SparseBitVector<> SCC;
2117
2118 SCC.set(Node);
2119
2120 bool Ref = (Node >= FirstRefNode);
2121
2122 Node2Deleted[Node] = true;
2123
2124 do {
2125 unsigned P = SCCStack.top(); SCCStack.pop();
2126 Ref |= (P >= FirstRefNode);
2127 SCC.set(P);
2128 HCDSCCRep[P] = Node;
2129 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2130
2131 if (Ref) {
2132 unsigned Rep = SCC.find_first();
2133 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2134
2135 SparseBitVector<>::iterator i = SCC.begin();
2136
2137 // Skip over the non-ref nodes
2138 while( *i < FirstRefNode )
2139 ++i;
2140
2141 while( i != SCC.end() )
2142 SDT[ (*i++) - FirstRefNode ] = Rep;
2143 }
2144 }
2145}
2146
2147
Daniel Berlind81ccc22007-09-24 19:45:49 +00002148/// Optimize the constraints by performing offline variable substitution and
2149/// other optimizations.
2150void Andersens::OptimizeConstraints() {
2151 DOUT << "Beginning constraint optimization\n";
2152
Daniel Berlinc864edb2008-03-05 19:31:47 +00002153 SDTActive = false;
2154
Daniel Berlind81ccc22007-09-24 19:45:49 +00002155 // Function related nodes need to stay in the same relative position and can't
2156 // be location equivalent.
2157 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2158 Iter != MaxK.end();
2159 ++Iter) {
2160 for (unsigned i = Iter->first;
2161 i != Iter->first + Iter->second;
2162 ++i) {
2163 GraphNodes[i].AddressTaken = true;
2164 GraphNodes[i].Direct = false;
2165 }
2166 }
2167
2168 ClumpAddressTaken();
2169 FirstRefNode = GraphNodes.size();
2170 FirstAdrNode = FirstRefNode + GraphNodes.size();
2171 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2172 Node(false));
2173 VSSCCRep.resize(GraphNodes.size());
2174 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2175 VSSCCRep[i] = i;
2176 }
2177 HVN();
2178 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2179 Node *N = &GraphNodes[i];
2180 delete N->PredEdges;
2181 N->PredEdges = NULL;
2182 delete N->ImplicitPredEdges;
2183 N->ImplicitPredEdges = NULL;
2184 }
2185#undef DEBUG_TYPE
2186#define DEBUG_TYPE "anders-aa-labels"
2187 DEBUG(PrintLabels());
2188#undef DEBUG_TYPE
2189#define DEBUG_TYPE "anders-aa"
2190 RewriteConstraints();
2191 // Delete the adr nodes.
2192 GraphNodes.resize(FirstRefNode * 2);
2193
2194 // Now perform HU
2195 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2196 Node *N = &GraphNodes[i];
2197 if (FindNode(i) == i) {
2198 N->PointsTo = new SparseBitVector<>;
2199 N->PointedToBy = new SparseBitVector<>;
2200 // Reset our labels
2201 }
2202 VSSCCRep[i] = i;
2203 N->PointerEquivLabel = 0;
2204 }
2205 HU();
2206#undef DEBUG_TYPE
2207#define DEBUG_TYPE "anders-aa-labels"
2208 DEBUG(PrintLabels());
2209#undef DEBUG_TYPE
2210#define DEBUG_TYPE "anders-aa"
2211 RewriteConstraints();
2212 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2213 if (FindNode(i) == i) {
2214 Node *N = &GraphNodes[i];
2215 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002216 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002217 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002218 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002219 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002220 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002221 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002222 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002223 }
2224 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002225
2226 // perform Hybrid Cycle Detection (HCD)
2227 HCD();
2228 SDTActive = true;
2229
2230 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002231 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002232
2233 // HCD complete.
2234
Daniel Berlind81ccc22007-09-24 19:45:49 +00002235 DOUT << "Finished constraint optimization\n";
2236 FirstRefNode = 0;
2237 FirstAdrNode = 0;
2238}
2239
2240/// Unite pointer but not location equivalent variables, now that the constraint
2241/// graph is built.
2242void Andersens::UnitePointerEquivalences() {
2243 DOUT << "Uniting remaining pointer equivalences\n";
2244 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002245 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002246 unsigned Label = GraphNodes[i].PointerEquivLabel;
2247
2248 if (Label && PENLEClass2Node[Label] != -1)
2249 UniteNodes(i, PENLEClass2Node[Label]);
2250 }
2251 }
2252 DOUT << "Finished remaining pointer equivalences\n";
2253 PENLEClass2Node.clear();
2254}
2255
2256/// Create the constraint graph used for solving points-to analysis.
2257///
Daniel Berlinaad15882007-09-16 21:45:02 +00002258void Andersens::CreateConstraintGraph() {
2259 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2260 Constraint &C = Constraints[i];
2261 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2262 if (C.Type == Constraint::AddressOf)
2263 GraphNodes[C.Dest].PointsTo->set(C.Src);
2264 else if (C.Type == Constraint::Load)
2265 GraphNodes[C.Src].Constraints.push_back(C);
2266 else if (C.Type == Constraint::Store)
2267 GraphNodes[C.Dest].Constraints.push_back(C);
2268 else if (C.Offset != 0)
2269 GraphNodes[C.Src].Constraints.push_back(C);
2270 else
2271 GraphNodes[C.Src].Edges->set(C.Dest);
2272 }
2273}
2274
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002275// Perform DFS and cycle detection.
2276bool Andersens::QueryNode(unsigned Node) {
2277 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002278 unsigned OurDFS = ++DFSNumber;
2279 SparseBitVector<> ToErase;
2280 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002281 Tarjan2DFS[Node] = OurDFS;
2282
2283 // Changed denotes a change from a recursive call that we will bubble up.
2284 // Merged is set if we actually merge a node ourselves.
2285 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002286
2287 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2288 bi != GraphNodes[Node].Edges->end();
2289 ++bi) {
2290 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002291 // If this edge points to a non-representative node but we are
2292 // already planning to add an edge to its representative, we have no
2293 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002294 if (RepNode != *bi && NewEdges.test(RepNode)){
2295 ToErase.set(*bi);
2296 continue;
2297 }
2298
2299 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002300 if (!Tarjan2Deleted[RepNode]){
2301 if (Tarjan2DFS[RepNode] == 0) {
2302 Changed |= QueryNode(RepNode);
2303 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002304 RepNode = FindNode(RepNode);
2305 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002306 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2307 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002308 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002309
2310 // We may have just discovered that this node is part of a cycle, in
2311 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002312 if (RepNode != *bi) {
2313 ToErase.set(*bi);
2314 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002315 }
2316 }
2317
Daniel Berlinaad15882007-09-16 21:45:02 +00002318 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2319 GraphNodes[Node].Edges |= NewEdges;
2320
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002321 // If this node is a root of a non-trivial SCC, place it on our
2322 // worklist to be processed.
2323 if (OurDFS == Tarjan2DFS[Node]) {
2324 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2325 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002326
2327 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002328 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002329 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002330 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002331
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002332 if (Merged)
2333 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002334 } else {
2335 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002336 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002337
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002338 return(Changed | Merged);
2339}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002340
2341/// SolveConstraints - This stage iteratively processes the constraints list
2342/// propagating constraints (adding edges to the Nodes in the points-to graph)
2343/// until a fixed point is reached.
2344///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002345/// We use a variant of the technique called "Lazy Cycle Detection", which is
2346/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2347/// Analysis for Millions of Lines of Code. In Programming Language Design and
2348/// Implementation (PLDI), June 2007."
2349/// The paper describes performing cycle detection one node at a time, which can
2350/// be expensive if there are no cycles, but there are long chains of nodes that
2351/// it heuristically believes are cycles (because it will DFS from each node
2352/// without state from previous nodes).
2353/// Instead, we use the heuristic to build a worklist of nodes to check, then
2354/// cycle detect them all at the same time to do this more cheaply. This
2355/// catches cycles slightly later than the original technique did, but does it
2356/// make significantly cheaper.
2357
Chris Lattnere995a2a2004-05-23 21:00:47 +00002358void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002359 CurrWL = &w1;
2360 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002361
Daniel Berlind81ccc22007-09-24 19:45:49 +00002362 OptimizeConstraints();
2363#undef DEBUG_TYPE
2364#define DEBUG_TYPE "anders-aa-constraints"
2365 DEBUG(PrintConstraints());
2366#undef DEBUG_TYPE
2367#define DEBUG_TYPE "anders-aa"
2368
Daniel Berlinaad15882007-09-16 21:45:02 +00002369 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2370 Node *N = &GraphNodes[i];
2371 N->PointsTo = new SparseBitVector<>;
2372 N->OldPointsTo = new SparseBitVector<>;
2373 N->Edges = new SparseBitVector<>;
2374 }
2375 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002376 UnitePointerEquivalences();
2377 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002378 Node2DFS.clear();
2379 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002380 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2381 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2382 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002383 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2384 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2385
2386 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002387 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002388 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002389
2390 // Add to work list if it's a representative and can contribute to the
2391 // calculation right now.
2392 if (INode->isRep() && !INode->PointsTo->empty()
2393 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2394 INode->Stamp();
2395 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002396 }
2397 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002398 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002399#if !FULL_UNIVERSAL
2400 // "Rep and special variables" - in order for HCD to maintain conservative
2401 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2402 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2403 // the analysis - it's ok to add edges from the special nodes, but never
2404 // *to* the special nodes.
2405 std::vector<unsigned int> RSV;
2406#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002407 while( !CurrWL->empty() ) {
2408 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002409
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002410 Node* CurrNode;
2411 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002412
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002413 // Actual cycle checking code. We cycle check all of the lazy cycle
2414 // candidates from the last iteration in one go.
2415 if (!TarjanWL.empty()) {
2416 DFSNumber = 0;
2417
2418 Tarjan2DFS.clear();
2419 Tarjan2Deleted.clear();
2420 while (!TarjanWL.empty()) {
2421 unsigned int ToTarjan = TarjanWL.front();
2422 TarjanWL.pop();
2423 if (!Tarjan2Deleted[ToTarjan]
2424 && GraphNodes[ToTarjan].isRep()
2425 && Tarjan2DFS[ToTarjan] == 0)
2426 QueryNode(ToTarjan);
2427 }
2428 }
2429
2430 // Add to work list if it's a representative and can contribute to the
2431 // calculation right now.
2432 while( (CurrNode = CurrWL->pop()) != NULL ) {
2433 CurrNodeIndex = CurrNode - &GraphNodes[0];
2434 CurrNode->Stamp();
2435
2436
Daniel Berlinaad15882007-09-16 21:45:02 +00002437 // Figure out the changed points to bits
2438 SparseBitVector<> CurrPointsTo;
2439 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2440 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002441 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002442 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002443
Daniel Berlinaad15882007-09-16 21:45:02 +00002444 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002445
2446 // Check the offline-computed equivalencies from HCD.
2447 bool SCC = false;
2448 unsigned Rep;
2449
2450 if (SDT[CurrNodeIndex] >= 0) {
2451 SCC = true;
2452 Rep = FindNode(SDT[CurrNodeIndex]);
2453
2454#if !FULL_UNIVERSAL
2455 RSV.clear();
2456#endif
2457 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2458 bi != CurrPointsTo.end(); ++bi) {
2459 unsigned Node = FindNode(*bi);
2460#if !FULL_UNIVERSAL
2461 if (Node < NumberSpecialNodes) {
2462 RSV.push_back(Node);
2463 continue;
2464 }
2465#endif
2466 Rep = UniteNodes(Rep,Node);
2467 }
2468#if !FULL_UNIVERSAL
2469 RSV.push_back(Rep);
2470#endif
2471
2472 NextWL->insert(&GraphNodes[Rep]);
2473
2474 if ( ! CurrNode->isRep() )
2475 continue;
2476 }
2477
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002478 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002479
Daniel Berlinaad15882007-09-16 21:45:02 +00002480 /* Now process the constraints for this node. */
2481 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2482 li != CurrNode->Constraints.end(); ) {
2483 li->Src = FindNode(li->Src);
2484 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002485
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002486 // Delete redundant constraints
2487 if( Seen.count(*li) ) {
2488 std::list<Constraint>::iterator lk = li; li++;
2489
2490 CurrNode->Constraints.erase(lk);
2491 ++NumErased;
2492 continue;
2493 }
2494 Seen.insert(*li);
2495
Daniel Berlinaad15882007-09-16 21:45:02 +00002496 // Src and Dest will be the vars we are going to process.
2497 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002498 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002499 // Load constraints say that every member of our RHS solution has K
2500 // added to it, and that variable gets an edge to LHS. We also union
2501 // RHS+K's solution into the LHS solution.
2502 // Store constraints say that every member of our LHS solution has K
2503 // added to it, and that variable gets an edge from RHS. We also union
2504 // RHS's solution into the LHS+K solution.
2505 unsigned *Src;
2506 unsigned *Dest;
2507 unsigned K = li->Offset;
2508 unsigned CurrMember;
2509 if (li->Type == Constraint::Load) {
2510 Src = &CurrMember;
2511 Dest = &li->Dest;
2512 } else if (li->Type == Constraint::Store) {
2513 Src = &li->Src;
2514 Dest = &CurrMember;
2515 } else {
2516 // TODO Handle offseted copy constraint
2517 li++;
2518 continue;
2519 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002520
2521 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002522 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002523 // involves pointers; if so, remove the redundant constraints).
2524 if( SCC && K == 0 ) {
2525#if FULL_UNIVERSAL
2526 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002527
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002528 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2529 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2530 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002531#else
2532 for (unsigned i=0; i < RSV.size(); ++i) {
2533 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002534
Daniel Berlinc864edb2008-03-05 19:31:47 +00002535 if (*Dest < NumberSpecialNodes)
2536 continue;
2537 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2538 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2539 NextWL->insert(&GraphNodes[*Dest]);
2540 }
2541#endif
2542 // since all future elements of the points-to set will be
2543 // equivalent to the current ones, the complex constraints
2544 // become redundant.
2545 //
2546 std::list<Constraint>::iterator lk = li; li++;
2547#if !FULL_UNIVERSAL
2548 // In this case, we can still erase the constraints when the
2549 // elements of the points-to sets are referenced by *Dest,
2550 // but not when they are referenced by *Src (i.e. for a Load
2551 // constraint). This is because if another special variable is
2552 // put into the points-to set later, we still need to add the
2553 // new edge from that special variable.
2554 if( lk->Type != Constraint::Load)
2555#endif
2556 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2557 } else {
2558 const SparseBitVector<> &Solution = CurrPointsTo;
2559
2560 for (SparseBitVector<>::iterator bi = Solution.begin();
2561 bi != Solution.end();
2562 ++bi) {
2563 CurrMember = *bi;
2564
2565 // Need to increment the member by K since that is where we are
2566 // supposed to copy to/from. Note that in positive weight cycles,
2567 // which occur in address taking of fields, K can go past
2568 // MaxK[CurrMember] elements, even though that is all it could point
2569 // to.
2570 if (K > 0 && K > MaxK[CurrMember])
2571 continue;
2572 else
2573 CurrMember = FindNode(CurrMember + K);
2574
2575 // Add an edge to the graph, so we can just do regular
2576 // bitmap ior next time. It may also let us notice a cycle.
2577#if !FULL_UNIVERSAL
2578 if (*Dest < NumberSpecialNodes)
2579 continue;
2580#endif
2581 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2582 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2583 NextWL->insert(&GraphNodes[*Dest]);
2584
2585 }
2586 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002587 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002588 }
2589 SparseBitVector<> NewEdges;
2590 SparseBitVector<> ToErase;
2591
2592 // Now all we have left to do is propagate points-to info along the
2593 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002594 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2595 bi != CurrNode->Edges->end();
2596 ++bi) {
2597
2598 unsigned DestVar = *bi;
2599 unsigned Rep = FindNode(DestVar);
2600
Bill Wendlingf059deb2008-02-26 10:51:52 +00002601 // If we ended up with this node as our destination, or we've already
2602 // got an edge for the representative, delete the current edge.
2603 if (Rep == CurrNodeIndex ||
2604 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002605 ToErase.set(DestVar);
2606 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002607 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002608
Bill Wendlingf059deb2008-02-26 10:51:52 +00002609 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002610
2611 // This is where we do lazy cycle detection.
2612 // If this is a cycle candidate (equal points-to sets and this
2613 // particular edge has not been cycle-checked previously), add to the
2614 // list to check for cycles on the next iteration.
2615 if (!EdgesChecked.count(edge) &&
2616 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2617 EdgesChecked.insert(edge);
2618 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002619 }
2620 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002621#if !FULL_UNIVERSAL
2622 if (Rep >= NumberSpecialNodes)
2623#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002624 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002625 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002626 }
2627 // If this edge's destination was collapsed, rewrite the edge.
2628 if (Rep != DestVar) {
2629 ToErase.set(DestVar);
2630 NewEdges.set(Rep);
2631 }
2632 }
2633 CurrNode->Edges->intersectWithComplement(ToErase);
2634 CurrNode->Edges |= NewEdges;
2635 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002636
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002637 // Switch to other work list.
2638 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2639 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002640
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002641
Daniel Berlinaad15882007-09-16 21:45:02 +00002642 Node2DFS.clear();
2643 Node2Deleted.clear();
2644 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2645 Node *N = &GraphNodes[i];
2646 delete N->OldPointsTo;
2647 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002648 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002649 SDTActive = false;
2650 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002651}
2652
Daniel Berlinaad15882007-09-16 21:45:02 +00002653//===----------------------------------------------------------------------===//
2654// Union-Find
2655//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002656
Daniel Berlinaad15882007-09-16 21:45:02 +00002657// Unite nodes First and Second, returning the one which is now the
2658// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002659unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2660 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002661 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2662 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002663
Daniel Berlinaad15882007-09-16 21:45:02 +00002664 Node *FirstNode = &GraphNodes[First];
2665 Node *SecondNode = &GraphNodes[Second];
2666
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002667 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002668 "Trying to unite two non-representative nodes!");
2669 if (First == Second)
2670 return First;
2671
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002672 if (UnionByRank) {
2673 int RankFirst = (int) FirstNode ->NodeRep;
2674 int RankSecond = (int) SecondNode->NodeRep;
2675
2676 // Rank starts at -1 and gets decremented as it increases.
2677 // Translation: higher rank, lower NodeRep value, which is always negative.
2678 if (RankFirst > RankSecond) {
2679 unsigned t = First; First = Second; Second = t;
2680 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2681 } else if (RankFirst == RankSecond) {
2682 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2683 }
2684 }
2685
Daniel Berlinaad15882007-09-16 21:45:02 +00002686 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002687#if !FULL_UNIVERSAL
2688 if (First >= NumberSpecialNodes)
2689#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002690 if (FirstNode->PointsTo && SecondNode->PointsTo)
2691 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2692 if (FirstNode->Edges && SecondNode->Edges)
2693 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002694 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002695 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2696 SecondNode->Constraints);
2697 if (FirstNode->OldPointsTo) {
2698 delete FirstNode->OldPointsTo;
2699 FirstNode->OldPointsTo = new SparseBitVector<>;
2700 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002701
2702 // Destroy interesting parts of the merged-from node.
2703 delete SecondNode->OldPointsTo;
2704 delete SecondNode->Edges;
2705 delete SecondNode->PointsTo;
2706 SecondNode->Edges = NULL;
2707 SecondNode->PointsTo = NULL;
2708 SecondNode->OldPointsTo = NULL;
2709
2710 NumUnified++;
2711 DOUT << "Unified Node ";
2712 DEBUG(PrintNode(FirstNode));
2713 DOUT << " and Node ";
2714 DEBUG(PrintNode(SecondNode));
2715 DOUT << "\n";
2716
Daniel Berlinc864edb2008-03-05 19:31:47 +00002717 if (SDTActive)
2718 if (SDT[Second] >= 0)
2719 if (SDT[First] < 0)
2720 SDT[First] = SDT[Second];
2721 else {
2722 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2723 First = FindNode(First);
2724 }
2725
Daniel Berlinaad15882007-09-16 21:45:02 +00002726 return First;
2727}
2728
2729// Find the index into GraphNodes of the node representing Node, performing
2730// path compression along the way
2731unsigned Andersens::FindNode(unsigned NodeIndex) {
2732 assert (NodeIndex < GraphNodes.size()
2733 && "Attempting to find a node that can't exist");
2734 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002735 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002736 return NodeIndex;
2737 else
2738 return (N->NodeRep = FindNode(N->NodeRep));
2739}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002740
2741//===----------------------------------------------------------------------===//
2742// Debugging Output
2743//===----------------------------------------------------------------------===//
2744
2745void Andersens::PrintNode(Node *N) {
2746 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002747 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002748 return;
2749 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002750 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002751 return;
2752 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002753 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002754 return;
2755 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002756 if (!N->getValue()) {
2757 cerr << "artificial" << (intptr_t) N;
2758 return;
2759 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002760
2761 assert(N->getValue() != 0 && "Never set node label!");
2762 Value *V = N->getValue();
2763 if (Function *F = dyn_cast<Function>(V)) {
2764 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002765 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002766 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002767 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002768 } else if (F->getFunctionType()->isVarArg() &&
2769 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002770 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002771 return;
2772 }
2773 }
2774
2775 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002776 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002777 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002778 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002779
2780 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002781 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002782 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002783 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002784
2785 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002786 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002787 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002788}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002789void Andersens::PrintConstraint(const Constraint &C) {
2790 if (C.Type == Constraint::Store) {
2791 cerr << "*";
2792 if (C.Offset != 0)
2793 cerr << "(";
2794 }
2795 PrintNode(&GraphNodes[C.Dest]);
2796 if (C.Type == Constraint::Store && C.Offset != 0)
2797 cerr << " + " << C.Offset << ")";
2798 cerr << " = ";
2799 if (C.Type == Constraint::Load) {
2800 cerr << "*";
2801 if (C.Offset != 0)
2802 cerr << "(";
2803 }
2804 else if (C.Type == Constraint::AddressOf)
2805 cerr << "&";
2806 PrintNode(&GraphNodes[C.Src]);
2807 if (C.Offset != 0 && C.Type != Constraint::Store)
2808 cerr << " + " << C.Offset;
2809 if (C.Type == Constraint::Load && C.Offset != 0)
2810 cerr << ")";
2811 cerr << "\n";
2812}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002813
2814void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002815 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002816
Daniel Berlind81ccc22007-09-24 19:45:49 +00002817 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2818 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002819}
2820
2821void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002822 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002823 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2824 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002825 if (FindNode (i) != i) {
2826 PrintNode(N);
2827 cerr << "\t--> same as ";
2828 PrintNode(&GraphNodes[FindNode(i)]);
2829 cerr << "\n";
2830 } else {
2831 cerr << "[" << (N->PointsTo->count()) << "] ";
2832 PrintNode(N);
2833 cerr << "\t--> ";
2834
2835 bool first = true;
2836 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2837 bi != N->PointsTo->end();
2838 ++bi) {
2839 if (!first)
2840 cerr << ", ";
2841 PrintNode(&GraphNodes[*bi]);
2842 first = false;
2843 }
2844 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002845 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002846 }
2847}