blob: 63a6cb553e02e8f2fa9536105fe84f7fd7c4551a [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
34// substitution algorithms intended to computer pointer and location
35// equivalences. Pointer equivalences are those pointers that will have the
36// same points-to sets, and location equivalences are those variables that
37// always appear together in points-to sets.
Daniel Berlind81ccc22007-09-24 19:45:49 +000038//
Chris Lattnere995a2a2004-05-23 21:00:47 +000039// The inclusion constraint solving phase iteratively propagates the inclusion
40// constraints until a fixed point is reached. This is an O(N^3) algorithm.
41//
Daniel Berlinaad15882007-09-16 21:45:02 +000042// Function constraints are handled as if they were structs with X fields.
43// Thus, an access to argument X of function Y is an access to node index
44// getNode(Y) + X. This representation allows handling of indirect calls
Daniel Berlind81ccc22007-09-24 19:45:49 +000045// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlinaad15882007-09-16 21:45:02 +000046// *(Y + 1) = a, *(Y + 2) = b.
47// The return node for a function is always located at getNode(F) +
48// CallReturnPos. The arguments start at getNode(F) + CallArgPos.
Chris Lattnere995a2a2004-05-23 21:00:47 +000049//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000050// Future Improvements:
Daniel Berlind81ccc22007-09-24 19:45:49 +000051// Offline detection of online cycles. Use of BDD's.
Chris Lattnere995a2a2004-05-23 21:00:47 +000052//===----------------------------------------------------------------------===//
53
54#define DEBUG_TYPE "anders-aa"
55#include "llvm/Constants.h"
56#include "llvm/DerivedTypes.h"
57#include "llvm/Instructions.h"
58#include "llvm/Module.h"
59#include "llvm/Pass.h"
Reid Spencerd7d83db2007-02-05 23:42:17 +000060#include "llvm/Support/Compiler.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000061#include "llvm/Support/InstIterator.h"
62#include "llvm/Support/InstVisitor.h"
63#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000064#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/Support/Debug.h"
66#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000067#include "llvm/ADT/SparseBitVector.h"
Daniel Berlind81ccc22007-09-24 19:45:49 +000068#include "llvm/ADT/DenseMap.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000069#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000070#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000071#include <list>
72#include <stack>
73#include <vector>
Chris Lattnere995a2a2004-05-23 21:00:47 +000074
Daniel Berlinaad15882007-09-16 21:45:02 +000075using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000076STATISTIC(NumIters , "Number of iterations to reach convergence");
77STATISTIC(NumConstraints, "Number of constraints");
78STATISTIC(NumNodes , "Number of nodes");
79STATISTIC(NumUnified , "Number of variables unified");
Chris Lattnere995a2a2004-05-23 21:00:47 +000080
Chris Lattner3b27d682006-12-19 22:30:33 +000081namespace {
Daniel Berlinaad15882007-09-16 21:45:02 +000082 const unsigned SelfRep = (unsigned)-1;
83 const unsigned Unvisited = (unsigned)-1;
84 // Position of the function return node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000085 const unsigned CallReturnPos = 1;
Daniel Berlinaad15882007-09-16 21:45:02 +000086 // Position of the function call node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000087 const unsigned CallFirstArgPos = 2;
88
89 struct BitmapKeyInfo {
90 static inline SparseBitVector<> *getEmptyKey() {
91 return reinterpret_cast<SparseBitVector<> *>(-1);
92 }
93 static inline SparseBitVector<> *getTombstoneKey() {
94 return reinterpret_cast<SparseBitVector<> *>(-2);
95 }
96 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
97 return bitmap->getHashValue();
98 }
99 static bool isEqual(const SparseBitVector<> *LHS,
100 const SparseBitVector<> *RHS) {
101 if (LHS == RHS)
102 return true;
103 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
104 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
105 return false;
106
107 return *LHS == *RHS;
108 }
109
110 static bool isPod() { return true; }
111 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000112
Reid Spencerd7d83db2007-02-05 23:42:17 +0000113 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
114 private InstVisitor<Andersens> {
Daniel Berlinaad15882007-09-16 21:45:02 +0000115 class Node;
116
117 /// Constraint - Objects of this structure are used to represent the various
118 /// constraints identified by the algorithm. The constraints are 'copy',
119 /// for statements like "A = B", 'load' for statements like "A = *B",
120 /// 'store' for statements like "*A = B", and AddressOf for statements like
121 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
122 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000123 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000124 /// resolvable to A = &C where C = B + K)
125
126 struct Constraint {
127 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
128 unsigned Dest;
129 unsigned Src;
130 unsigned Offset;
131
132 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
133 : Type(Ty), Dest(D), Src(S), Offset(O) {
134 assert(Offset == 0 || Ty != AddressOf &&
135 "Offset is illegal on addressof constraints");
136 }
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000137 bool operator==(const Constraint &RHS) const {
138 return RHS.Type == Type
139 && RHS.Dest == Dest
140 && RHS.Src == Src
141 && RHS.Offset == Offset;
142 }
143 bool operator<(const Constraint &RHS) const {
144 if (RHS.Type != Type)
145 return RHS.Type < Type;
146 else if (RHS.Dest != Dest)
147 return RHS.Dest < Dest;
148 else if (RHS.Src != Src)
149 return RHS.Src < Src;
150 return RHS.Offset < Offset;
151 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000152 };
153
Daniel Berlind81ccc22007-09-24 19:45:49 +0000154 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000155 // graph. Due to various optimizations, it is not always the case that
156 // there is a mapping from a Node to a Value. In particular, we add
157 // artificial Node's that represent the set of pointed-to variables shared
158 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000159 struct Node {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000160 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000161 SparseBitVector<> *Edges;
162 SparseBitVector<> *PointsTo;
163 SparseBitVector<> *OldPointsTo;
164 bool Changed;
165 std::list<Constraint> Constraints;
166
Daniel Berlind81ccc22007-09-24 19:45:49 +0000167 // Pointer and location equivalence labels
168 unsigned PointerEquivLabel;
169 unsigned LocationEquivLabel;
170 // Predecessor edges, both real and implicit
171 SparseBitVector<> *PredEdges;
172 SparseBitVector<> *ImplicitPredEdges;
173 // Set of nodes that point to us, only use for location equivalence.
174 SparseBitVector<> *PointedToBy;
175 // Number of incoming edges, used during variable substitution to early
176 // free the points-to sets
177 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000178 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000179 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000180 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000181 bool Direct;
182 // True if the node is address taken, *or* it is part of a group of nodes
183 // that must be kept together. This is set to true for functions and
184 // their arg nodes, which must be kept at the same position relative to
185 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000186 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000187
Daniel Berlind81ccc22007-09-24 19:45:49 +0000188 // Nodes in cycles (or in equivalence classes) are united together using a
189 // standard union-find representation with path compression. NodeRep
190 // gives the index into GraphNodes for the representative Node.
191 unsigned NodeRep;
192 public:
193
194 Node(bool direct = true) :
195 Val(0), Edges(0), PointsTo(0), OldPointsTo(0), Changed(false),
196 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
197 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
198 StoredInHash(false), Direct(direct), AddressTaken(false),
199 NodeRep(SelfRep) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000200
Chris Lattnere995a2a2004-05-23 21:00:47 +0000201 Node *setValue(Value *V) {
202 assert(Val == 0 && "Value already set for this node!");
203 Val = V;
204 return this;
205 }
206
207 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000208 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000209 Value *getValue() const { return Val; }
210
Chris Lattnere995a2a2004-05-23 21:00:47 +0000211 /// addPointerTo - Add a pointer to the list of pointees of this node,
212 /// returning true if this caused a new pointer to be added, or false if
213 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000214 bool addPointerTo(unsigned Node) {
215 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000216 }
217
218 /// intersects - Return true if the points-to set of this node intersects
219 /// with the points-to set of the specified node.
220 bool intersects(Node *N) const;
221
222 /// intersectsIgnoring - Return true if the points-to set of this node
223 /// intersects with the points-to set of the specified node on any nodes
224 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000225 bool intersectsIgnoring(Node *N, unsigned) const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000226 };
227
228 /// GraphNodes - This vector is populated as part of the object
229 /// identification stage of the analysis, which populates this vector with a
230 /// node for each memory object and fills in the ValueNodes map.
231 std::vector<Node> GraphNodes;
232
233 /// ValueNodes - This map indicates the Node that a particular Value* is
234 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000235 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000236
237 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000238 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000239 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000240
241 /// ReturnNodes - This map contains an entry for each function in the
242 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000243 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000244
245 /// VarargNodes - This map contains the entry used to represent all pointers
246 /// passed through the varargs portion of a function call for a particular
247 /// function. An entry is not present in this map for functions that do not
248 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000249 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000250
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000251
Chris Lattnere995a2a2004-05-23 21:00:47 +0000252 /// Constraints - This vector contains a list of all of the constraints
253 /// identified by the program.
254 std::vector<Constraint> Constraints;
255
Daniel Berlind81ccc22007-09-24 19:45:49 +0000256 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000257 // this is equivalent to the number of arguments + CallFirstArgPos)
258 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000259
260 /// This enum defines the GraphNodes indices that correspond to important
261 /// fixed sets.
262 enum {
263 UniversalSet = 0,
264 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000265 NullObject = 2,
266 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000267 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000268 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000269 std::stack<unsigned> SCCStack;
270 // Topological Index -> Graph node
271 std::vector<unsigned> Topo2Node;
272 // Graph Node -> Topological Index;
273 std::vector<unsigned> Node2Topo;
274 // Map from Graph Node to DFS number
275 std::vector<unsigned> Node2DFS;
276 // Map from Graph Node to Deleted from graph.
277 std::vector<bool> Node2Deleted;
278 // Current DFS and RPO numbers
279 unsigned DFSNumber;
280 unsigned RPONumber;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000281
Daniel Berlind81ccc22007-09-24 19:45:49 +0000282 // Offline variable substitution related things
283
284 // Temporary rep storage, used because we can't collapse SCC's in the
285 // predecessor graph by uniting the variables permanently, we can only do so
286 // for the successor graph.
287 std::vector<unsigned> VSSCCRep;
288 // Mapping from node to whether we have visited it during SCC finding yet.
289 std::vector<bool> Node2Visited;
290 // During variable substitution, we create unknowns to represent the unknown
291 // value that is a dereference of a variable. These nodes are known as
292 // "ref" nodes (since they represent the value of dereferences).
293 unsigned FirstRefNode;
294 // During HVN, we create represent address taken nodes as if they were
295 // unknown (since HVN, unlike HU, does not evaluate unions).
296 unsigned FirstAdrNode;
297 // Current pointer equivalence class number
298 unsigned PEClass;
299 // Mapping from points-to sets to equivalence classes
300 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
301 BitVectorMap Set2PEClass;
302 // Mapping from pointer equivalences to the representative node. -1 if we
303 // have no representative node for this pointer equivalence class yet.
304 std::vector<int> PEClass2Node;
305 // Mapping from pointer equivalences to representative node. This includes
306 // pointer equivalent but not location equivalent variables. -1 if we have
307 // no representative node for this pointer equivalence class yet.
308 std::vector<int> PENLEClass2Node;
309
Chris Lattnere995a2a2004-05-23 21:00:47 +0000310 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000311 static char ID;
312 Andersens() : ModulePass((intptr_t)&ID) {}
313
Chris Lattnerb12914b2004-09-20 04:48:05 +0000314 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000315 InitializeAliasAnalysis(this);
316 IdentifyObjects(M);
317 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000318#undef DEBUG_TYPE
319#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000320 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000321#undef DEBUG_TYPE
322#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000323 SolveConstraints();
324 DEBUG(PrintPointsToGraph());
325
326 // Free the constraints list, as we don't need it to respond to alias
327 // requests.
328 ObjectNodes.clear();
329 ReturnNodes.clear();
330 VarargNodes.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000331 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000332 return false;
333 }
334
335 void releaseMemory() {
336 // FIXME: Until we have transitively required passes working correctly,
337 // this cannot be enabled! Otherwise, using -count-aa with the pass
338 // causes memory to be freed too early. :(
339#if 0
340 // The memory objects and ValueNodes data structures at the only ones that
341 // are still live after construction.
342 std::vector<Node>().swap(GraphNodes);
343 ValueNodes.clear();
344#endif
345 }
346
347 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
348 AliasAnalysis::getAnalysisUsage(AU);
349 AU.setPreservesAll(); // Does not transform code
350 }
351
352 //------------------------------------------------
353 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000354 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000355 AliasResult alias(const Value *V1, unsigned V1Size,
356 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000357 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
358 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000359 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
360 bool pointsToConstantMemory(const Value *P);
361
362 virtual void deleteValue(Value *V) {
363 ValueNodes.erase(V);
364 getAnalysis<AliasAnalysis>().deleteValue(V);
365 }
366
367 virtual void copyValue(Value *From, Value *To) {
368 ValueNodes[To] = ValueNodes[From];
369 getAnalysis<AliasAnalysis>().copyValue(From, To);
370 }
371
372 private:
373 /// getNode - Return the node corresponding to the specified pointer scalar.
374 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000375 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000376 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000377 if (!isa<GlobalValue>(C))
378 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000379
Daniel Berlind81ccc22007-09-24 19:45:49 +0000380 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000381 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000382#ifndef NDEBUG
383 V->dump();
384#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000385 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000386 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000387 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000388 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000389
Chris Lattnere995a2a2004-05-23 21:00:47 +0000390 /// getObject - Return the node corresponding to the memory object for the
391 /// specified global or allocation instruction.
Daniel Berlinaad15882007-09-16 21:45:02 +0000392 unsigned getObject(Value *V) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000393 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000394 assert(I != ObjectNodes.end() &&
395 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000396 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000397 }
398
399 /// getReturnNode - Return the node representing the return value for the
400 /// specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000401 unsigned getReturnNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000402 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000403 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000404 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000405 }
406
407 /// getVarargNode - Return the node representing the variable arguments
408 /// formal for the specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000409 unsigned getVarargNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000410 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000411 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000412 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000413 }
414
415 /// getNodeValue - Get the node for the specified LLVM value and set the
416 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000417 unsigned getNodeValue(Value &V) {
418 unsigned Index = getNode(&V);
419 GraphNodes[Index].setValue(&V);
420 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000421 }
422
Daniel Berlinaad15882007-09-16 21:45:02 +0000423 unsigned UniteNodes(unsigned First, unsigned Second);
424 unsigned FindNode(unsigned Node);
425
Chris Lattnere995a2a2004-05-23 21:00:47 +0000426 void IdentifyObjects(Module &M);
427 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000428 bool AnalyzeUsesOfFunction(Value *);
429 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000430 void OptimizeConstraints();
431 unsigned FindEquivalentNode(unsigned, unsigned);
432 void ClumpAddressTaken();
433 void RewriteConstraints();
434 void HU();
435 void HVN();
436 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000437 void SolveConstraints();
Daniel Berlinaad15882007-09-16 21:45:02 +0000438 void QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000439 void Condense(unsigned Node);
440 void HUValNum(unsigned Node);
441 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000442 unsigned getNodeForConstantPointer(Constant *C);
443 unsigned getNodeForConstantPointerTarget(Constant *C);
444 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000445
Chris Lattnere995a2a2004-05-23 21:00:47 +0000446 void AddConstraintsForNonInternalLinkage(Function *F);
447 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000448 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000449
450
451 void PrintNode(Node *N);
452 void PrintConstraints();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000453 void PrintConstraint(const Constraint &);
454 void PrintLabels();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000455 void PrintPointsToGraph();
456
457 //===------------------------------------------------------------------===//
458 // Instruction visitation methods for adding constraints
459 //
460 friend class InstVisitor<Andersens>;
461 void visitReturnInst(ReturnInst &RI);
462 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
463 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
464 void visitCallSite(CallSite CS);
465 void visitAllocationInst(AllocationInst &AI);
466 void visitLoadInst(LoadInst &LI);
467 void visitStoreInst(StoreInst &SI);
468 void visitGetElementPtrInst(GetElementPtrInst &GEP);
469 void visitPHINode(PHINode &PN);
470 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000471 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
472 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000473 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000474 void visitVAArg(VAArgInst &I);
475 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000476
Chris Lattnere995a2a2004-05-23 21:00:47 +0000477 };
478
Devang Patel19974732007-05-03 01:11:54 +0000479 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000480 RegisterPass<Andersens> X("anders-aa",
481 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000482 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000483}
484
Jeff Cohen534927d2005-01-08 22:01:16 +0000485ModulePass *llvm::createAndersensPass() { return new Andersens(); }
486
Chris Lattnere995a2a2004-05-23 21:00:47 +0000487//===----------------------------------------------------------------------===//
488// AliasAnalysis Interface Implementation
489//===----------------------------------------------------------------------===//
490
491AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
492 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000493 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
494 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000495
496 // Check to see if the two pointers are known to not alias. They don't alias
497 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000498 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000499 return NoAlias;
500
501 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
502}
503
Chris Lattnerf392c642005-03-28 06:21:17 +0000504AliasAnalysis::ModRefResult
505Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
506 // The only thing useful that we can contribute for mod/ref information is
507 // when calling external function calls: if we know that memory never escapes
508 // from the program, it cannot be modified by an external call.
509 //
510 // NOTE: This is not really safe, at least not when the entire program is not
511 // available. The deal is that the external function could call back into the
512 // program and modify stuff. We ignore this technical niggle for now. This
513 // is, after all, a "research quality" implementation of Andersen's analysis.
514 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000515 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000516 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000517
Daniel Berlinaad15882007-09-16 21:45:02 +0000518 if (N1->PointsTo->empty())
519 return NoModRef;
Chris Lattnerf392c642005-03-28 06:21:17 +0000520
Daniel Berlinaad15882007-09-16 21:45:02 +0000521 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000522 return NoModRef; // P doesn't point to the universal set.
523 }
524
525 return AliasAnalysis::getModRefInfo(CS, P, Size);
526}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000527
Reid Spencer3a9ec242006-08-28 01:02:49 +0000528AliasAnalysis::ModRefResult
529Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
530 return AliasAnalysis::getModRefInfo(CS1,CS2);
531}
532
Chris Lattnere995a2a2004-05-23 21:00:47 +0000533/// getMustAlias - We can provide must alias information if we know that a
534/// pointer can only point to a specific function or the null pointer.
535/// Unfortunately we cannot determine must-alias information for global
536/// variables or any other memory memory objects because we do not track whether
537/// a pointer points to the beginning of an object or a field of it.
538void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000539 Node *N = &GraphNodes[FindNode(getNode(P))];
540 if (N->PointsTo->count() == 1) {
541 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
542 // If a function is the only object in the points-to set, then it must be
543 // the destination. Note that we can't handle global variables here,
544 // because we don't know if the pointer is actually pointing to a field of
545 // the global or to the beginning of it.
546 if (Value *V = Pointee->getValue()) {
547 if (Function *F = dyn_cast<Function>(V))
548 RetVals.push_back(F);
549 } else {
550 // If the object in the points-to set is the null object, then the null
551 // pointer is a must alias.
552 if (Pointee == &GraphNodes[NullObject])
553 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000554 }
555 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000556 AliasAnalysis::getMustAliases(P, RetVals);
557}
558
559/// pointsToConstantMemory - If we can determine that this pointer only points
560/// to constant memory, return true. In practice, this means that if the
561/// pointer can only point to constant globals, functions, or the null pointer,
562/// return true.
563///
564bool Andersens::pointsToConstantMemory(const Value *P) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000565 Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
566 unsigned i;
567
568 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
569 bi != N->PointsTo->end();
570 ++bi) {
571 i = *bi;
572 Node *Pointee = &GraphNodes[i];
573 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000574 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
575 !cast<GlobalVariable>(V)->isConstant()))
576 return AliasAnalysis::pointsToConstantMemory(P);
577 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000578 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000579 return AliasAnalysis::pointsToConstantMemory(P);
580 }
581 }
582
583 return true;
584}
585
586//===----------------------------------------------------------------------===//
587// Object Identification Phase
588//===----------------------------------------------------------------------===//
589
590/// IdentifyObjects - This stage scans the program, adding an entry to the
591/// GraphNodes list for each memory object in the program (global stack or
592/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
593///
594void Andersens::IdentifyObjects(Module &M) {
595 unsigned NumObjects = 0;
596
597 // Object #0 is always the universal set: the object that we don't know
598 // anything about.
599 assert(NumObjects == UniversalSet && "Something changed!");
600 ++NumObjects;
601
602 // Object #1 always represents the null pointer.
603 assert(NumObjects == NullPtr && "Something changed!");
604 ++NumObjects;
605
606 // Object #2 always represents the null object (the object pointed to by null)
607 assert(NumObjects == NullObject && "Something changed!");
608 ++NumObjects;
609
610 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000611 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
612 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000613 ObjectNodes[I] = NumObjects++;
614 ValueNodes[I] = NumObjects++;
615 }
616
617 // Add nodes for all of the functions and the instructions inside of them.
618 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
619 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000620 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000621 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000622 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
623 ReturnNodes[F] = NumObjects++;
624 if (F->getFunctionType()->isVarArg())
625 VarargNodes[F] = NumObjects++;
626
Daniel Berlinaad15882007-09-16 21:45:02 +0000627
Chris Lattnere995a2a2004-05-23 21:00:47 +0000628 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000629 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
630 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000631 {
632 if (isa<PointerType>(I->getType()))
633 ValueNodes[I] = NumObjects++;
634 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000635 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000636
637 // Scan the function body, creating a memory object for each heap/stack
638 // allocation in the body of the function and a node to represent all
639 // pointer values defined by instructions and used as operands.
640 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
641 // If this is an heap or stack allocation, create a node for the memory
642 // object.
643 if (isa<PointerType>(II->getType())) {
644 ValueNodes[&*II] = NumObjects++;
645 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
646 ObjectNodes[AI] = NumObjects++;
647 }
648 }
649 }
650
651 // Now that we know how many objects to create, make them all now!
652 GraphNodes.resize(NumObjects);
653 NumNodes += NumObjects;
654}
655
656//===----------------------------------------------------------------------===//
657// Constraint Identification Phase
658//===----------------------------------------------------------------------===//
659
660/// getNodeForConstantPointer - Return the node corresponding to the constant
661/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000662unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000663 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
664
Chris Lattner267a1b02005-03-27 18:58:23 +0000665 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000666 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000667 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
668 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000669 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
670 switch (CE->getOpcode()) {
671 case Instruction::GetElementPtr:
672 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000673 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000674 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000675 case Instruction::BitCast:
676 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000677 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000678 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000679 assert(0);
680 }
681 } else {
682 assert(0 && "Unknown constant pointer!");
683 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000684 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000685}
686
687/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
688/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000689unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000690 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
691
692 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000693 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000694 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
695 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000696 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
697 switch (CE->getOpcode()) {
698 case Instruction::GetElementPtr:
699 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000700 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000701 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000702 case Instruction::BitCast:
703 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000704 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000705 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000706 assert(0);
707 }
708 } else {
709 assert(0 && "Unknown constant pointer!");
710 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000711 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000712}
713
714/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
715/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000716void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
717 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000718 if (C->getType()->isFirstClassType()) {
719 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000720 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
721 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000722 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000723 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
724 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000725 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000726 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000727 // If this is an array or struct, include constraints for each element.
728 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
729 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000730 AddGlobalInitializerConstraints(NodeIndex,
731 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000732 }
733}
734
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000735/// AddConstraintsForNonInternalLinkage - If this function does not have
736/// internal linkage, realize that we can't trust anything passed into or
737/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000738void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000739 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000740 if (isa<PointerType>(I->getType()))
741 // If this is an argument of an externally accessible function, the
742 // incoming pointer might point to anything.
743 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000744 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000745}
746
Chris Lattner8a446432005-03-29 06:09:07 +0000747/// AddConstraintsForCall - If this is a call to a "known" function, add the
748/// constraints and return true. If this is a call to an unknown function,
749/// return false.
750bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000751 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000752
753 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000754 if (F->getName() == "atoi" || F->getName() == "atof" ||
755 F->getName() == "atol" || F->getName() == "atoll" ||
756 F->getName() == "remove" || F->getName() == "unlink" ||
757 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000758 F->getName() == "llvm.memset.i32" ||
759 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000760 F->getName() == "strcmp" || F->getName() == "strncmp" ||
761 F->getName() == "execl" || F->getName() == "execlp" ||
762 F->getName() == "execle" || F->getName() == "execv" ||
763 F->getName() == "execvp" || F->getName() == "chmod" ||
764 F->getName() == "puts" || F->getName() == "write" ||
765 F->getName() == "open" || F->getName() == "create" ||
766 F->getName() == "truncate" || F->getName() == "chdir" ||
767 F->getName() == "mkdir" || F->getName() == "rmdir" ||
768 F->getName() == "read" || F->getName() == "pipe" ||
769 F->getName() == "wait" || F->getName() == "time" ||
770 F->getName() == "stat" || F->getName() == "fstat" ||
771 F->getName() == "lstat" || F->getName() == "strtod" ||
772 F->getName() == "strtof" || F->getName() == "strtold" ||
773 F->getName() == "fopen" || F->getName() == "fdopen" ||
774 F->getName() == "freopen" ||
775 F->getName() == "fflush" || F->getName() == "feof" ||
776 F->getName() == "fileno" || F->getName() == "clearerr" ||
777 F->getName() == "rewind" || F->getName() == "ftell" ||
778 F->getName() == "ferror" || F->getName() == "fgetc" ||
779 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
780 F->getName() == "fwrite" || F->getName() == "fread" ||
781 F->getName() == "fgets" || F->getName() == "ungetc" ||
782 F->getName() == "fputc" ||
783 F->getName() == "fputs" || F->getName() == "putc" ||
784 F->getName() == "ftell" || F->getName() == "rewind" ||
785 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
786 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
787 F->getName() == "printf" || F->getName() == "fprintf" ||
788 F->getName() == "sprintf" || F->getName() == "vprintf" ||
789 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
790 F->getName() == "scanf" || F->getName() == "fscanf" ||
791 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
792 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000793 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000794
Chris Lattner175b9632005-03-29 20:36:05 +0000795
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000796 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000797 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000798 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000799 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000800
801 // *Dest = *Src, which requires an artificial graph node to represent the
802 // constraint. It is broken up into *Dest = temp, temp = *Src
803 unsigned FirstArg = getNode(CS.getArgument(0));
804 unsigned SecondArg = getNode(CS.getArgument(1));
805 unsigned TempArg = GraphNodes.size();
806 GraphNodes.push_back(Node());
807 Constraints.push_back(Constraint(Constraint::Store,
808 FirstArg, TempArg));
809 Constraints.push_back(Constraint(Constraint::Load,
810 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000811 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000812 }
813
Chris Lattner77b50562005-03-29 20:04:24 +0000814 // Result = Arg0
815 if (F->getName() == "realloc" || F->getName() == "strchr" ||
816 F->getName() == "strrchr" || F->getName() == "strstr" ||
817 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000818 Constraints.push_back(Constraint(Constraint::Copy,
819 getNode(CS.getInstruction()),
820 getNode(CS.getArgument(0))));
821 return true;
822 }
823
824 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000825}
826
827
Chris Lattnere995a2a2004-05-23 21:00:47 +0000828
Daniel Berlinaad15882007-09-16 21:45:02 +0000829/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
830/// If this is used by anything complex (i.e., the address escapes), return
831/// true.
832bool Andersens::AnalyzeUsesOfFunction(Value *V) {
833
834 if (!isa<PointerType>(V->getType())) return true;
835
836 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
837 if (dyn_cast<LoadInst>(*UI)) {
838 return false;
839 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
840 if (V == SI->getOperand(1)) {
841 return false;
842 } else if (SI->getOperand(1)) {
843 return true; // Storing the pointer
844 }
845 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
846 if (AnalyzeUsesOfFunction(GEP)) return true;
847 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
848 // Make sure that this is just the function being called, not that it is
849 // passing into the function.
850 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
851 if (CI->getOperand(i) == V) return true;
852 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
853 // Make sure that this is just the function being called, not that it is
854 // passing into the function.
855 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
856 if (II->getOperand(i) == V) return true;
857 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
858 if (CE->getOpcode() == Instruction::GetElementPtr ||
859 CE->getOpcode() == Instruction::BitCast) {
860 if (AnalyzeUsesOfFunction(CE))
861 return true;
862 } else {
863 return true;
864 }
865 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
866 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
867 return true; // Allow comparison against null.
868 } else if (dyn_cast<FreeInst>(*UI)) {
869 return false;
870 } else {
871 return true;
872 }
873 return false;
874}
875
Chris Lattnere995a2a2004-05-23 21:00:47 +0000876/// CollectConstraints - This stage scans the program, adding a constraint to
877/// the Constraints list for each instruction in the program that induces a
878/// constraint, and setting up the initial points-to graph.
879///
880void Andersens::CollectConstraints(Module &M) {
881 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000882 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
883 UniversalSet));
884 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
885 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000886
887 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000888 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000889
890 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000891 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
892 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000893 // Associate the address of the global object as pointing to the memory for
894 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +0000895 unsigned ObjectIndex = getObject(I);
896 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000897 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000898 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
899 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000900
901 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000902 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +0000903 } else {
904 // If it doesn't have an initializer (i.e. it's defined in another
905 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +0000906 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
907 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000908 }
909 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000910
Chris Lattnere995a2a2004-05-23 21:00:47 +0000911 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000912 // Set up the return value node.
913 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000914 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000915 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +0000916 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000917
918 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000919 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
920 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000921 if (isa<PointerType>(I->getType()))
922 getNodeValue(*I);
923
Daniel Berlinaad15882007-09-16 21:45:02 +0000924 // At some point we should just add constraints for the escaping functions
925 // at solve time, but this slows down solving. For now, we simply mark
926 // address taken functions as escaping and treat them as external.
927 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000928 AddConstraintsForNonInternalLinkage(F);
929
Reid Spencer5cbf9852007-01-30 20:08:39 +0000930 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000931 // Scan the function body, creating a memory object for each heap/stack
932 // allocation in the body of the function and a node to represent all
933 // pointer values defined by instructions and used as operands.
934 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000935 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000936 // External functions that return pointers return the universal set.
937 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
938 Constraints.push_back(Constraint(Constraint::Copy,
939 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000940 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000941
942 // Any pointers that are passed into the function have the universal set
943 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000944 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
945 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000946 if (isa<PointerType>(I->getType())) {
947 // Pointers passed into external functions could have anything stored
948 // through them.
949 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000950 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000951 // Memory objects passed into external function calls can have the
952 // universal set point to them.
953 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +0000954 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +0000955 getNode(I)));
956 }
957
958 // If this is an external varargs function, it can also store pointers
959 // into any pointers passed through the varargs section.
960 if (F->getFunctionType()->isVarArg())
961 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000962 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000963 }
964 }
965 NumConstraints += Constraints.size();
966}
967
968
969void Andersens::visitInstruction(Instruction &I) {
970#ifdef NDEBUG
971 return; // This function is just a big assert.
972#endif
973 if (isa<BinaryOperator>(I))
974 return;
975 // Most instructions don't have any effect on pointer values.
976 switch (I.getOpcode()) {
977 case Instruction::Br:
978 case Instruction::Switch:
979 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +0000980 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000981 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000982 case Instruction::ICmp:
983 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000984 return;
985 default:
986 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +0000987 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000988 abort();
989 }
990}
991
992void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000993 unsigned ObjectIndex = getObject(&AI);
994 GraphNodes[ObjectIndex].setValue(&AI);
995 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
996 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000997}
998
999void Andersens::visitReturnInst(ReturnInst &RI) {
1000 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1001 // return V --> <Copy/retval{F}/v>
1002 Constraints.push_back(Constraint(Constraint::Copy,
1003 getReturnNode(RI.getParent()->getParent()),
1004 getNode(RI.getOperand(0))));
1005}
1006
1007void Andersens::visitLoadInst(LoadInst &LI) {
1008 if (isa<PointerType>(LI.getType()))
1009 // P1 = load P2 --> <Load/P1/P2>
1010 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1011 getNode(LI.getOperand(0))));
1012}
1013
1014void Andersens::visitStoreInst(StoreInst &SI) {
1015 if (isa<PointerType>(SI.getOperand(0)->getType()))
1016 // store P1, P2 --> <Store/P2/P1>
1017 Constraints.push_back(Constraint(Constraint::Store,
1018 getNode(SI.getOperand(1)),
1019 getNode(SI.getOperand(0))));
1020}
1021
1022void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1023 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1024 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1025 getNode(GEP.getOperand(0))));
1026}
1027
1028void Andersens::visitPHINode(PHINode &PN) {
1029 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001030 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001031 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1032 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1033 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1034 getNode(PN.getIncomingValue(i))));
1035 }
1036}
1037
1038void Andersens::visitCastInst(CastInst &CI) {
1039 Value *Op = CI.getOperand(0);
1040 if (isa<PointerType>(CI.getType())) {
1041 if (isa<PointerType>(Op->getType())) {
1042 // P1 = cast P2 --> <Copy/P1/P2>
1043 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1044 getNode(CI.getOperand(0))));
1045 } else {
1046 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001047#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001048 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001049 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001050#else
1051 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001052#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001053 }
1054 } else if (isa<PointerType>(Op->getType())) {
1055 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001056#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001057 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001058 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001059 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001060#else
1061 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001062#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001063 }
1064}
1065
1066void Andersens::visitSelectInst(SelectInst &SI) {
1067 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001068 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001069 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1070 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1071 getNode(SI.getOperand(1))));
1072 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1073 getNode(SI.getOperand(2))));
1074 }
1075}
1076
Chris Lattnere995a2a2004-05-23 21:00:47 +00001077void Andersens::visitVAArg(VAArgInst &I) {
1078 assert(0 && "vaarg not handled yet!");
1079}
1080
1081/// AddConstraintsForCall - Add constraints for a call with actual arguments
1082/// specified by CS to the function specified by F. Note that the types of
1083/// arguments might not match up in the case where this is an indirect call and
1084/// the function pointer has been casted. If this is the case, do something
1085/// reasonable.
1086void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001087 Value *CallValue = CS.getCalledValue();
1088 bool IsDeref = F == NULL;
1089
1090 // If this is a call to an external function, try to handle it directly to get
1091 // some taste of context sensitivity.
1092 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001093 return;
1094
Chris Lattnere995a2a2004-05-23 21:00:47 +00001095 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001096 unsigned CSN = getNode(CS.getInstruction());
1097 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1098 if (IsDeref)
1099 Constraints.push_back(Constraint(Constraint::Load, CSN,
1100 getNode(CallValue), CallReturnPos));
1101 else
1102 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1103 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001104 } else {
1105 // If the function returns a non-pointer value, handle this just like we
1106 // treat a nonpointer cast to pointer.
1107 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001108 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001109 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001110 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001111 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001112 UniversalSet,
1113 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001114 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001115
Chris Lattnere995a2a2004-05-23 21:00:47 +00001116 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinaad15882007-09-16 21:45:02 +00001117 if (F) {
1118 // Direct Call
1119 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1120 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1121 if (isa<PointerType>(AI->getType())) {
1122 if (isa<PointerType>((*ArgI)->getType())) {
1123 // Copy the actual argument into the formal argument.
1124 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1125 getNode(*ArgI)));
1126 } else {
1127 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1128 UniversalSet));
1129 }
1130 } else if (isa<PointerType>((*ArgI)->getType())) {
1131 Constraints.push_back(Constraint(Constraint::Copy,
1132 UniversalSet,
1133 getNode(*ArgI)));
1134 }
1135 } else {
1136 //Indirect Call
1137 unsigned ArgPos = CallFirstArgPos;
1138 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001139 if (isa<PointerType>((*ArgI)->getType())) {
1140 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001141 Constraints.push_back(Constraint(Constraint::Store,
1142 getNode(CallValue),
1143 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001144 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001145 Constraints.push_back(Constraint(Constraint::Store,
1146 getNode (CallValue),
1147 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001148 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001149 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001150 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001151 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001152 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001153 for (; ArgI != ArgE; ++ArgI)
1154 if (isa<PointerType>((*ArgI)->getType()))
1155 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1156 getNode(*ArgI)));
1157 // If more arguments are passed in than we track, just drop them on the floor.
1158}
1159
1160void Andersens::visitCallSite(CallSite CS) {
1161 if (isa<PointerType>(CS.getType()))
1162 getNodeValue(*CS.getInstruction());
1163
1164 if (Function *F = CS.getCalledFunction()) {
1165 AddConstraintsForCall(CS, F);
1166 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001167 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001168 }
1169}
1170
1171//===----------------------------------------------------------------------===//
1172// Constraint Solving Phase
1173//===----------------------------------------------------------------------===//
1174
1175/// intersects - Return true if the points-to set of this node intersects
1176/// with the points-to set of the specified node.
1177bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001178 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001179}
1180
1181/// intersectsIgnoring - Return true if the points-to set of this node
1182/// intersects with the points-to set of the specified node on any nodes
1183/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001184bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1185 // TODO: If we are only going to call this with the same value for Ignoring,
1186 // we should move the special values out of the points-to bitmap.
1187 bool WeHadIt = PointsTo->test(Ignoring);
1188 bool NHadIt = N->PointsTo->test(Ignoring);
1189 bool Result = false;
1190 if (WeHadIt)
1191 PointsTo->reset(Ignoring);
1192 if (NHadIt)
1193 N->PointsTo->reset(Ignoring);
1194 Result = PointsTo->intersects(N->PointsTo);
1195 if (WeHadIt)
1196 PointsTo->set(Ignoring);
1197 if (NHadIt)
1198 N->PointsTo->set(Ignoring);
1199 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001200}
1201
Daniel Berlind81ccc22007-09-24 19:45:49 +00001202void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001203#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001204 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001205#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001206}
1207
1208
1209/// Clump together address taken variables so that the points-to sets use up
1210/// less space and can be operated on faster.
1211
1212void Andersens::ClumpAddressTaken() {
1213#undef DEBUG_TYPE
1214#define DEBUG_TYPE "anders-aa-renumber"
1215 std::vector<unsigned> Translate;
1216 std::vector<Node> NewGraphNodes;
1217
1218 Translate.resize(GraphNodes.size());
1219 unsigned NewPos = 0;
1220
1221 for (unsigned i = 0; i < Constraints.size(); ++i) {
1222 Constraint &C = Constraints[i];
1223 if (C.Type == Constraint::AddressOf) {
1224 GraphNodes[C.Src].AddressTaken = true;
1225 }
1226 }
1227 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1228 unsigned Pos = NewPos++;
1229 Translate[i] = Pos;
1230 NewGraphNodes.push_back(GraphNodes[i]);
1231 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1232 }
1233
1234 // I believe this ends up being faster than making two vectors and splicing
1235 // them.
1236 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1237 if (GraphNodes[i].AddressTaken) {
1238 unsigned Pos = NewPos++;
1239 Translate[i] = Pos;
1240 NewGraphNodes.push_back(GraphNodes[i]);
1241 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1242 }
1243 }
1244
1245 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1246 if (!GraphNodes[i].AddressTaken) {
1247 unsigned Pos = NewPos++;
1248 Translate[i] = Pos;
1249 NewGraphNodes.push_back(GraphNodes[i]);
1250 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1251 }
1252 }
1253
1254 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1255 Iter != ValueNodes.end();
1256 ++Iter)
1257 Iter->second = Translate[Iter->second];
1258
1259 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1260 Iter != ObjectNodes.end();
1261 ++Iter)
1262 Iter->second = Translate[Iter->second];
1263
1264 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1265 Iter != ReturnNodes.end();
1266 ++Iter)
1267 Iter->second = Translate[Iter->second];
1268
1269 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1270 Iter != VarargNodes.end();
1271 ++Iter)
1272 Iter->second = Translate[Iter->second];
1273
1274 for (unsigned i = 0; i < Constraints.size(); ++i) {
1275 Constraint &C = Constraints[i];
1276 C.Src = Translate[C.Src];
1277 C.Dest = Translate[C.Dest];
1278 }
1279
1280 GraphNodes.swap(NewGraphNodes);
1281#undef DEBUG_TYPE
1282#define DEBUG_TYPE "anders-aa"
1283}
1284
1285/// The technique used here is described in "Exploiting Pointer and Location
1286/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1287/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1288/// and is equivalent to value numbering the collapsed constraint graph without
1289/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1290/// first order pointer dereferences and speed up/reduce memory usage of HU.
1291/// Running both is equivalent to HRU without the iteration
1292/// HVN in more detail:
1293/// Imagine the set of constraints was simply straight line code with no loops
1294/// (we eliminate cycles, so there are no loops), such as:
1295/// E = &D
1296/// E = &C
1297/// E = F
1298/// F = G
1299/// G = F
1300/// Applying value numbering to this code tells us:
1301/// G == F == E
1302///
1303/// For HVN, this is as far as it goes. We assign new value numbers to every
1304/// "address node", and every "reference node".
1305/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1306/// cycle must have the same value number since the = operation is really
1307/// inclusion, not overwrite), and value number nodes we receive points-to sets
1308/// before we value our own node.
1309/// The advantage of HU over HVN is that HU considers the inclusion property, so
1310/// that if you have
1311/// E = &D
1312/// E = &C
1313/// E = F
1314/// F = G
1315/// F = &D
1316/// G = F
1317/// HU will determine that G == F == E. HVN will not, because it cannot prove
1318/// that the points to information ends up being the same because they all
1319/// receive &D from E anyway.
1320
1321void Andersens::HVN() {
1322 DOUT << "Beginning HVN\n";
1323 // Build a predecessor graph. This is like our constraint graph with the
1324 // edges going in the opposite direction, and there are edges for all the
1325 // constraints, instead of just copy constraints. We also build implicit
1326 // edges for constraints are implied but not explicit. I.E for the constraint
1327 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1328 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1329 Constraint &C = Constraints[i];
1330 if (C.Type == Constraint::AddressOf) {
1331 GraphNodes[C.Src].AddressTaken = true;
1332 GraphNodes[C.Src].Direct = false;
1333
1334 // Dest = &src edge
1335 unsigned AdrNode = C.Src + FirstAdrNode;
1336 if (!GraphNodes[C.Dest].PredEdges)
1337 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1338 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1339
1340 // *Dest = src edge
1341 unsigned RefNode = C.Dest + FirstRefNode;
1342 if (!GraphNodes[RefNode].ImplicitPredEdges)
1343 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1344 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1345 } else if (C.Type == Constraint::Load) {
1346 if (C.Offset == 0) {
1347 // dest = *src edge
1348 if (!GraphNodes[C.Dest].PredEdges)
1349 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1350 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1351 } else {
1352 GraphNodes[C.Dest].Direct = false;
1353 }
1354 } else if (C.Type == Constraint::Store) {
1355 if (C.Offset == 0) {
1356 // *dest = src edge
1357 unsigned RefNode = C.Dest + FirstRefNode;
1358 if (!GraphNodes[RefNode].PredEdges)
1359 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1360 GraphNodes[RefNode].PredEdges->set(C.Src);
1361 }
1362 } else {
1363 // Dest = Src edge and *Dest = *Src edge
1364 if (!GraphNodes[C.Dest].PredEdges)
1365 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1366 GraphNodes[C.Dest].PredEdges->set(C.Src);
1367 unsigned RefNode = C.Dest + FirstRefNode;
1368 if (!GraphNodes[RefNode].ImplicitPredEdges)
1369 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1370 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1371 }
1372 }
1373 PEClass = 1;
1374 // Do SCC finding first to condense our predecessor graph
1375 DFSNumber = 0;
1376 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1377 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1378 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1379
1380 for (unsigned i = 0; i < FirstRefNode; ++i) {
1381 unsigned Node = VSSCCRep[i];
1382 if (!Node2Visited[Node])
1383 HVNValNum(Node);
1384 }
1385 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1386 Iter != Set2PEClass.end();
1387 ++Iter)
1388 delete Iter->first;
1389 Set2PEClass.clear();
1390 Node2DFS.clear();
1391 Node2Deleted.clear();
1392 Node2Visited.clear();
1393 DOUT << "Finished HVN\n";
1394
1395}
1396
1397/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1398/// same time because it's easy.
1399void Andersens::HVNValNum(unsigned NodeIndex) {
1400 unsigned MyDFS = DFSNumber++;
1401 Node *N = &GraphNodes[NodeIndex];
1402 Node2Visited[NodeIndex] = true;
1403 Node2DFS[NodeIndex] = MyDFS;
1404
1405 // First process all our explicit edges
1406 if (N->PredEdges)
1407 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1408 Iter != N->PredEdges->end();
1409 ++Iter) {
1410 unsigned j = VSSCCRep[*Iter];
1411 if (!Node2Deleted[j]) {
1412 if (!Node2Visited[j])
1413 HVNValNum(j);
1414 if (Node2DFS[NodeIndex] > Node2DFS[j])
1415 Node2DFS[NodeIndex] = Node2DFS[j];
1416 }
1417 }
1418
1419 // Now process all the implicit edges
1420 if (N->ImplicitPredEdges)
1421 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1422 Iter != N->ImplicitPredEdges->end();
1423 ++Iter) {
1424 unsigned j = VSSCCRep[*Iter];
1425 if (!Node2Deleted[j]) {
1426 if (!Node2Visited[j])
1427 HVNValNum(j);
1428 if (Node2DFS[NodeIndex] > Node2DFS[j])
1429 Node2DFS[NodeIndex] = Node2DFS[j];
1430 }
1431 }
1432
1433 // See if we found any cycles
1434 if (MyDFS == Node2DFS[NodeIndex]) {
1435 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1436 unsigned CycleNodeIndex = SCCStack.top();
1437 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1438 VSSCCRep[CycleNodeIndex] = NodeIndex;
1439 // Unify the nodes
1440 N->Direct &= CycleNode->Direct;
1441
1442 if (CycleNode->PredEdges) {
1443 if (!N->PredEdges)
1444 N->PredEdges = new SparseBitVector<>;
1445 *(N->PredEdges) |= CycleNode->PredEdges;
1446 delete CycleNode->PredEdges;
1447 CycleNode->PredEdges = NULL;
1448 }
1449 if (CycleNode->ImplicitPredEdges) {
1450 if (!N->ImplicitPredEdges)
1451 N->ImplicitPredEdges = new SparseBitVector<>;
1452 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1453 delete CycleNode->ImplicitPredEdges;
1454 CycleNode->ImplicitPredEdges = NULL;
1455 }
1456
1457 SCCStack.pop();
1458 }
1459
1460 Node2Deleted[NodeIndex] = true;
1461
1462 if (!N->Direct) {
1463 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1464 return;
1465 }
1466
1467 // Collect labels of successor nodes
1468 bool AllSame = true;
1469 unsigned First = ~0;
1470 SparseBitVector<> *Labels = new SparseBitVector<>;
1471 bool Used = false;
1472
1473 if (N->PredEdges)
1474 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1475 Iter != N->PredEdges->end();
1476 ++Iter) {
1477 unsigned j = VSSCCRep[*Iter];
1478 unsigned Label = GraphNodes[j].PointerEquivLabel;
1479 // Ignore labels that are equal to us or non-pointers
1480 if (j == NodeIndex || Label == 0)
1481 continue;
1482 if (First == (unsigned)~0)
1483 First = Label;
1484 else if (First != Label)
1485 AllSame = false;
1486 Labels->set(Label);
1487 }
1488
1489 // We either have a non-pointer, a copy of an existing node, or a new node.
1490 // Assign the appropriate pointer equivalence label.
1491 if (Labels->empty()) {
1492 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1493 } else if (AllSame) {
1494 GraphNodes[NodeIndex].PointerEquivLabel = First;
1495 } else {
1496 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1497 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1498 unsigned EquivClass = PEClass++;
1499 Set2PEClass[Labels] = EquivClass;
1500 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1501 Used = true;
1502 }
1503 }
1504 if (!Used)
1505 delete Labels;
1506 } else {
1507 SCCStack.push(NodeIndex);
1508 }
1509}
1510
1511/// The technique used here is described in "Exploiting Pointer and Location
1512/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1513/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1514/// and is equivalent to value numbering the collapsed constraint graph
1515/// including evaluating unions.
1516void Andersens::HU() {
1517 DOUT << "Beginning HU\n";
1518 // Build a predecessor graph. This is like our constraint graph with the
1519 // edges going in the opposite direction, and there are edges for all the
1520 // constraints, instead of just copy constraints. We also build implicit
1521 // edges for constraints are implied but not explicit. I.E for the constraint
1522 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1523 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1524 Constraint &C = Constraints[i];
1525 if (C.Type == Constraint::AddressOf) {
1526 GraphNodes[C.Src].AddressTaken = true;
1527 GraphNodes[C.Src].Direct = false;
1528
1529 GraphNodes[C.Dest].PointsTo->set(C.Src);
1530 // *Dest = src edge
1531 unsigned RefNode = C.Dest + FirstRefNode;
1532 if (!GraphNodes[RefNode].ImplicitPredEdges)
1533 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1534 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1535 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1536 } else if (C.Type == Constraint::Load) {
1537 if (C.Offset == 0) {
1538 // dest = *src edge
1539 if (!GraphNodes[C.Dest].PredEdges)
1540 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1541 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1542 } else {
1543 GraphNodes[C.Dest].Direct = false;
1544 }
1545 } else if (C.Type == Constraint::Store) {
1546 if (C.Offset == 0) {
1547 // *dest = src edge
1548 unsigned RefNode = C.Dest + FirstRefNode;
1549 if (!GraphNodes[RefNode].PredEdges)
1550 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1551 GraphNodes[RefNode].PredEdges->set(C.Src);
1552 }
1553 } else {
1554 // Dest = Src edge and *Dest = *Src edg
1555 if (!GraphNodes[C.Dest].PredEdges)
1556 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1557 GraphNodes[C.Dest].PredEdges->set(C.Src);
1558 unsigned RefNode = C.Dest + FirstRefNode;
1559 if (!GraphNodes[RefNode].ImplicitPredEdges)
1560 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1561 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1562 }
1563 }
1564 PEClass = 1;
1565 // Do SCC finding first to condense our predecessor graph
1566 DFSNumber = 0;
1567 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1568 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1569 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1570
1571 for (unsigned i = 0; i < FirstRefNode; ++i) {
1572 if (FindNode(i) == i) {
1573 unsigned Node = VSSCCRep[i];
1574 if (!Node2Visited[Node])
1575 Condense(Node);
1576 }
1577 }
1578
1579 // Reset tables for actual labeling
1580 Node2DFS.clear();
1581 Node2Visited.clear();
1582 Node2Deleted.clear();
1583 // Pre-grow our densemap so that we don't get really bad behavior
1584 Set2PEClass.resize(GraphNodes.size());
1585
1586 // Visit the condensed graph and generate pointer equivalence labels.
1587 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1588 for (unsigned i = 0; i < FirstRefNode; ++i) {
1589 if (FindNode(i) == i) {
1590 unsigned Node = VSSCCRep[i];
1591 if (!Node2Visited[Node])
1592 HUValNum(Node);
1593 }
1594 }
1595 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1596 Set2PEClass.clear();
1597 DOUT << "Finished HU\n";
1598}
1599
1600
1601/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1602void Andersens::Condense(unsigned NodeIndex) {
1603 unsigned MyDFS = DFSNumber++;
1604 Node *N = &GraphNodes[NodeIndex];
1605 Node2Visited[NodeIndex] = true;
1606 Node2DFS[NodeIndex] = MyDFS;
1607
1608 // First process all our explicit edges
1609 if (N->PredEdges)
1610 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1611 Iter != N->PredEdges->end();
1612 ++Iter) {
1613 unsigned j = VSSCCRep[*Iter];
1614 if (!Node2Deleted[j]) {
1615 if (!Node2Visited[j])
1616 Condense(j);
1617 if (Node2DFS[NodeIndex] > Node2DFS[j])
1618 Node2DFS[NodeIndex] = Node2DFS[j];
1619 }
1620 }
1621
1622 // Now process all the implicit edges
1623 if (N->ImplicitPredEdges)
1624 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1625 Iter != N->ImplicitPredEdges->end();
1626 ++Iter) {
1627 unsigned j = VSSCCRep[*Iter];
1628 if (!Node2Deleted[j]) {
1629 if (!Node2Visited[j])
1630 Condense(j);
1631 if (Node2DFS[NodeIndex] > Node2DFS[j])
1632 Node2DFS[NodeIndex] = Node2DFS[j];
1633 }
1634 }
1635
1636 // See if we found any cycles
1637 if (MyDFS == Node2DFS[NodeIndex]) {
1638 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1639 unsigned CycleNodeIndex = SCCStack.top();
1640 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1641 VSSCCRep[CycleNodeIndex] = NodeIndex;
1642 // Unify the nodes
1643 N->Direct &= CycleNode->Direct;
1644
1645 *(N->PointsTo) |= CycleNode->PointsTo;
1646 delete CycleNode->PointsTo;
1647 CycleNode->PointsTo = NULL;
1648 if (CycleNode->PredEdges) {
1649 if (!N->PredEdges)
1650 N->PredEdges = new SparseBitVector<>;
1651 *(N->PredEdges) |= CycleNode->PredEdges;
1652 delete CycleNode->PredEdges;
1653 CycleNode->PredEdges = NULL;
1654 }
1655 if (CycleNode->ImplicitPredEdges) {
1656 if (!N->ImplicitPredEdges)
1657 N->ImplicitPredEdges = new SparseBitVector<>;
1658 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1659 delete CycleNode->ImplicitPredEdges;
1660 CycleNode->ImplicitPredEdges = NULL;
1661 }
1662 SCCStack.pop();
1663 }
1664
1665 Node2Deleted[NodeIndex] = true;
1666
1667 // Set up number of incoming edges for other nodes
1668 if (N->PredEdges)
1669 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1670 Iter != N->PredEdges->end();
1671 ++Iter)
1672 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1673 } else {
1674 SCCStack.push(NodeIndex);
1675 }
1676}
1677
1678void Andersens::HUValNum(unsigned NodeIndex) {
1679 Node *N = &GraphNodes[NodeIndex];
1680 Node2Visited[NodeIndex] = true;
1681
1682 // Eliminate dereferences of non-pointers for those non-pointers we have
1683 // already identified. These are ref nodes whose non-ref node:
1684 // 1. Has already been visited determined to point to nothing (and thus, a
1685 // dereference of it must point to nothing)
1686 // 2. Any direct node with no predecessor edges in our graph and with no
1687 // points-to set (since it can't point to anything either, being that it
1688 // receives no points-to sets and has none).
1689 if (NodeIndex >= FirstRefNode) {
1690 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1691 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1692 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1693 && GraphNodes[j].PointsTo->empty())){
1694 return;
1695 }
1696 }
1697 // Process all our explicit edges
1698 if (N->PredEdges)
1699 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1700 Iter != N->PredEdges->end();
1701 ++Iter) {
1702 unsigned j = VSSCCRep[*Iter];
1703 if (!Node2Visited[j])
1704 HUValNum(j);
1705
1706 // If this edge turned out to be the same as us, or got no pointer
1707 // equivalence label (and thus points to nothing) , just decrement our
1708 // incoming edges and continue.
1709 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1710 --GraphNodes[j].NumInEdges;
1711 continue;
1712 }
1713
1714 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1715
1716 // If we didn't end up storing this in the hash, and we're done with all
1717 // the edges, we don't need the points-to set anymore.
1718 --GraphNodes[j].NumInEdges;
1719 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1720 delete GraphNodes[j].PointsTo;
1721 GraphNodes[j].PointsTo = NULL;
1722 }
1723 }
1724 // If this isn't a direct node, generate a fresh variable.
1725 if (!N->Direct) {
1726 N->PointsTo->set(FirstRefNode + NodeIndex);
1727 }
1728
1729 // See If we have something equivalent to us, if not, generate a new
1730 // equivalence class.
1731 if (N->PointsTo->empty()) {
1732 delete N->PointsTo;
1733 N->PointsTo = NULL;
1734 } else {
1735 if (N->Direct) {
1736 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1737 if (N->PointerEquivLabel == 0) {
1738 unsigned EquivClass = PEClass++;
1739 N->StoredInHash = true;
1740 Set2PEClass[N->PointsTo] = EquivClass;
1741 N->PointerEquivLabel = EquivClass;
1742 }
1743 } else {
1744 N->PointerEquivLabel = PEClass++;
1745 }
1746 }
1747}
1748
1749/// Rewrite our list of constraints so that pointer equivalent nodes are
1750/// replaced by their the pointer equivalence class representative.
1751void Andersens::RewriteConstraints() {
1752 std::vector<Constraint> NewConstraints;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001753 std::set<Constraint> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001754
1755 PEClass2Node.clear();
1756 PENLEClass2Node.clear();
1757
1758 // We may have from 1 to Graphnodes + 1 equivalence classes.
1759 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1760 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1761
1762 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1763 // nodes, and rewriting constraints to use the representative nodes.
1764 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1765 Constraint &C = Constraints[i];
1766 unsigned RHSNode = FindNode(C.Src);
1767 unsigned LHSNode = FindNode(C.Dest);
1768 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1769 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1770
1771 // First we try to eliminate constraints for things we can prove don't point
1772 // to anything.
1773 if (LHSLabel == 0) {
1774 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1775 DOUT << " is a non-pointer, ignoring constraint.\n";
1776 continue;
1777 }
1778 if (RHSLabel == 0) {
1779 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1780 DOUT << " is a non-pointer, ignoring constraint.\n";
1781 continue;
1782 }
1783 // This constraint may be useless, and it may become useless as we translate
1784 // it.
1785 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1786 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001787
Daniel Berlind81ccc22007-09-24 19:45:49 +00001788 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1789 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001790 if (C.Src == C.Dest && C.Type == Constraint::Copy
1791 || Seen.count(C) != 0)
Daniel Berlind81ccc22007-09-24 19:45:49 +00001792 continue;
1793
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001794 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001795 NewConstraints.push_back(C);
1796 }
1797 Constraints.swap(NewConstraints);
1798 PEClass2Node.clear();
1799}
1800
1801/// See if we have a node that is pointer equivalent to the one being asked
1802/// about, and if so, unite them and return the equivalent node. Otherwise,
1803/// return the original node.
1804unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1805 unsigned NodeLabel) {
1806 if (!GraphNodes[NodeIndex].AddressTaken) {
1807 if (PEClass2Node[NodeLabel] != -1) {
1808 // We found an existing node with the same pointer label, so unify them.
1809 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex);
1810 } else {
1811 PEClass2Node[NodeLabel] = NodeIndex;
1812 PENLEClass2Node[NodeLabel] = NodeIndex;
1813 }
1814 } else if (PENLEClass2Node[NodeLabel] == -1) {
1815 PENLEClass2Node[NodeLabel] = NodeIndex;
1816 }
1817
1818 return NodeIndex;
1819}
1820
1821void Andersens::PrintLabels() {
1822 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1823 if (i < FirstRefNode) {
1824 PrintNode(&GraphNodes[i]);
1825 } else if (i < FirstAdrNode) {
1826 DOUT << "REF(";
1827 PrintNode(&GraphNodes[i-FirstRefNode]);
1828 DOUT <<")";
1829 } else {
1830 DOUT << "ADR(";
1831 PrintNode(&GraphNodes[i-FirstAdrNode]);
1832 DOUT <<")";
1833 }
1834
1835 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1836 << " and SCC rep " << VSSCCRep[i]
1837 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1838 << "\n";
1839 }
1840}
1841
1842/// Optimize the constraints by performing offline variable substitution and
1843/// other optimizations.
1844void Andersens::OptimizeConstraints() {
1845 DOUT << "Beginning constraint optimization\n";
1846
1847 // Function related nodes need to stay in the same relative position and can't
1848 // be location equivalent.
1849 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1850 Iter != MaxK.end();
1851 ++Iter) {
1852 for (unsigned i = Iter->first;
1853 i != Iter->first + Iter->second;
1854 ++i) {
1855 GraphNodes[i].AddressTaken = true;
1856 GraphNodes[i].Direct = false;
1857 }
1858 }
1859
1860 ClumpAddressTaken();
1861 FirstRefNode = GraphNodes.size();
1862 FirstAdrNode = FirstRefNode + GraphNodes.size();
1863 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
1864 Node(false));
1865 VSSCCRep.resize(GraphNodes.size());
1866 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1867 VSSCCRep[i] = i;
1868 }
1869 HVN();
1870 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1871 Node *N = &GraphNodes[i];
1872 delete N->PredEdges;
1873 N->PredEdges = NULL;
1874 delete N->ImplicitPredEdges;
1875 N->ImplicitPredEdges = NULL;
1876 }
1877#undef DEBUG_TYPE
1878#define DEBUG_TYPE "anders-aa-labels"
1879 DEBUG(PrintLabels());
1880#undef DEBUG_TYPE
1881#define DEBUG_TYPE "anders-aa"
1882 RewriteConstraints();
1883 // Delete the adr nodes.
1884 GraphNodes.resize(FirstRefNode * 2);
1885
1886 // Now perform HU
1887 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1888 Node *N = &GraphNodes[i];
1889 if (FindNode(i) == i) {
1890 N->PointsTo = new SparseBitVector<>;
1891 N->PointedToBy = new SparseBitVector<>;
1892 // Reset our labels
1893 }
1894 VSSCCRep[i] = i;
1895 N->PointerEquivLabel = 0;
1896 }
1897 HU();
1898#undef DEBUG_TYPE
1899#define DEBUG_TYPE "anders-aa-labels"
1900 DEBUG(PrintLabels());
1901#undef DEBUG_TYPE
1902#define DEBUG_TYPE "anders-aa"
1903 RewriteConstraints();
1904 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1905 if (FindNode(i) == i) {
1906 Node *N = &GraphNodes[i];
1907 delete N->PointsTo;
1908 delete N->PredEdges;
1909 delete N->ImplicitPredEdges;
1910 delete N->PointedToBy;
1911 }
1912 }
1913 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
1914 DOUT << "Finished constraint optimization\n";
1915 FirstRefNode = 0;
1916 FirstAdrNode = 0;
1917}
1918
1919/// Unite pointer but not location equivalent variables, now that the constraint
1920/// graph is built.
1921void Andersens::UnitePointerEquivalences() {
1922 DOUT << "Uniting remaining pointer equivalences\n";
1923 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1924 if (GraphNodes[i].AddressTaken && GraphNodes[i].NodeRep == SelfRep) {
1925 unsigned Label = GraphNodes[i].PointerEquivLabel;
1926
1927 if (Label && PENLEClass2Node[Label] != -1)
1928 UniteNodes(i, PENLEClass2Node[Label]);
1929 }
1930 }
1931 DOUT << "Finished remaining pointer equivalences\n";
1932 PENLEClass2Node.clear();
1933}
1934
1935/// Create the constraint graph used for solving points-to analysis.
1936///
Daniel Berlinaad15882007-09-16 21:45:02 +00001937void Andersens::CreateConstraintGraph() {
1938 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1939 Constraint &C = Constraints[i];
1940 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1941 if (C.Type == Constraint::AddressOf)
1942 GraphNodes[C.Dest].PointsTo->set(C.Src);
1943 else if (C.Type == Constraint::Load)
1944 GraphNodes[C.Src].Constraints.push_back(C);
1945 else if (C.Type == Constraint::Store)
1946 GraphNodes[C.Dest].Constraints.push_back(C);
1947 else if (C.Offset != 0)
1948 GraphNodes[C.Src].Constraints.push_back(C);
1949 else
1950 GraphNodes[C.Src].Edges->set(C.Dest);
1951 }
1952}
1953
1954// Perform cycle detection, DFS, and RPO finding.
1955void Andersens::QueryNode(unsigned Node) {
1956 assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1957 unsigned OurDFS = ++DFSNumber;
1958 SparseBitVector<> ToErase;
1959 SparseBitVector<> NewEdges;
1960 Node2DFS[Node] = OurDFS;
1961
1962 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1963 bi != GraphNodes[Node].Edges->end();
1964 ++bi) {
1965 unsigned RepNode = FindNode(*bi);
1966 // If we are going to add an edge to repnode, we have no need for the edge
1967 // to e anymore.
1968 if (RepNode != *bi && NewEdges.test(RepNode)){
1969 ToErase.set(*bi);
1970 continue;
1971 }
1972
1973 // Continue about our DFS.
1974 if (!Node2Deleted[RepNode]){
1975 if (Node2DFS[RepNode] == 0) {
1976 QueryNode(RepNode);
1977 // May have been changed by query
1978 RepNode = FindNode(RepNode);
1979 }
1980 if (Node2DFS[RepNode] < Node2DFS[Node])
1981 Node2DFS[Node] = Node2DFS[RepNode];
1982 }
1983 // We may have just discovered that e belongs to a cycle, in which case we
1984 // can also erase it.
1985 if (RepNode != *bi) {
1986 ToErase.set(*bi);
1987 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001988 }
1989 }
1990
Daniel Berlinaad15882007-09-16 21:45:02 +00001991 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
1992 GraphNodes[Node].Edges |= NewEdges;
1993
1994 // If this node is a root of a non-trivial SCC, place it on our worklist to be
1995 // processed
1996 if (OurDFS == Node2DFS[Node]) {
1997 bool Changed = false;
1998 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
1999 Node = UniteNodes(Node, FindNode(SCCStack.top()));
2000
2001 SCCStack.pop();
2002 Changed = true;
2003 }
2004 Node2Deleted[Node] = true;
2005 RPONumber++;
2006
2007 Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
2008 Node2Topo[Node] = GraphNodes.size() - RPONumber;
2009 if (Changed)
2010 GraphNodes[Node].Changed = true;
2011 } else {
2012 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002013 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002014}
2015
2016
2017/// SolveConstraints - This stage iteratively processes the constraints list
2018/// propagating constraints (adding edges to the Nodes in the points-to graph)
2019/// until a fixed point is reached.
2020///
2021void Andersens::SolveConstraints() {
2022 bool Changed = true;
2023 unsigned Iteration = 0;
Daniel Berlinaad15882007-09-16 21:45:02 +00002024
Daniel Berlind81ccc22007-09-24 19:45:49 +00002025 OptimizeConstraints();
2026#undef DEBUG_TYPE
2027#define DEBUG_TYPE "anders-aa-constraints"
2028 DEBUG(PrintConstraints());
2029#undef DEBUG_TYPE
2030#define DEBUG_TYPE "anders-aa"
2031
Daniel Berlinaad15882007-09-16 21:45:02 +00002032 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2033 Node *N = &GraphNodes[i];
2034 N->PointsTo = new SparseBitVector<>;
2035 N->OldPointsTo = new SparseBitVector<>;
2036 N->Edges = new SparseBitVector<>;
2037 }
2038 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002039 UnitePointerEquivalences();
2040 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlinaad15882007-09-16 21:45:02 +00002041 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2042 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002043 Node2DFS.clear();
2044 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002045 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2046 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2047 DFSNumber = 0;
2048 RPONumber = 0;
2049 // Order graph and mark starting nodes as changed.
2050 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2051 unsigned N = FindNode(i);
2052 Node *INode = &GraphNodes[i];
2053 if (Node2DFS[N] == 0) {
2054 QueryNode(N);
2055 // Mark as changed if it's a representation and can contribute to the
2056 // calculation right now.
2057 if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
2058 && (!INode->Edges->empty() || !INode->Constraints.empty()))
2059 INode->Changed = true;
2060 }
2061 }
2062
2063 do {
Daniel Berlinc6d93982007-09-16 23:59:53 +00002064 Changed = false;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002065 ++NumIters;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002066 DOUT << "Starting iteration #" << Iteration++ << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002067 // TODO: In the microoptimization category, we could just make Topo2Node
2068 // a fast map and thus only contain the visited nodes.
2069 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2070 unsigned CurrNodeIndex = Topo2Node[i];
2071 Node *CurrNode;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002072
Daniel Berlinaad15882007-09-16 21:45:02 +00002073 // We may not revisit all nodes on every iteration
2074 if (CurrNodeIndex == Unvisited)
2075 continue;
2076 CurrNode = &GraphNodes[CurrNodeIndex];
2077 // See if this is a node we need to process on this iteration
2078 if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
2079 continue;
2080 CurrNode->Changed = false;
2081
2082 // Figure out the changed points to bits
2083 SparseBitVector<> CurrPointsTo;
2084 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2085 CurrNode->OldPointsTo);
2086 if (CurrPointsTo.empty()){
2087 continue;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002088 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002089 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002090
Daniel Berlinaad15882007-09-16 21:45:02 +00002091 /* Now process the constraints for this node. */
2092 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2093 li != CurrNode->Constraints.end(); ) {
2094 li->Src = FindNode(li->Src);
2095 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002096
Daniel Berlinaad15882007-09-16 21:45:02 +00002097 // TODO: We could delete redundant constraints here.
2098 // Src and Dest will be the vars we are going to process.
2099 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002100 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002101 // Load constraints say that every member of our RHS solution has K
2102 // added to it, and that variable gets an edge to LHS. We also union
2103 // RHS+K's solution into the LHS solution.
2104 // Store constraints say that every member of our LHS solution has K
2105 // added to it, and that variable gets an edge from RHS. We also union
2106 // RHS's solution into the LHS+K solution.
2107 unsigned *Src;
2108 unsigned *Dest;
2109 unsigned K = li->Offset;
2110 unsigned CurrMember;
2111 if (li->Type == Constraint::Load) {
2112 Src = &CurrMember;
2113 Dest = &li->Dest;
2114 } else if (li->Type == Constraint::Store) {
2115 Src = &li->Src;
2116 Dest = &CurrMember;
2117 } else {
2118 // TODO Handle offseted copy constraint
2119 li++;
2120 continue;
2121 }
2122 // TODO: hybrid cycle detection would go here, we should check
2123 // if it was a statically detected offline equivalence that
2124 // involves pointers , and if so, remove the redundant constraints.
Chris Lattnere995a2a2004-05-23 21:00:47 +00002125
Daniel Berlinaad15882007-09-16 21:45:02 +00002126 const SparseBitVector<> &Solution = CurrPointsTo;
2127
2128 for (SparseBitVector<>::iterator bi = Solution.begin();
2129 bi != Solution.end();
2130 ++bi) {
2131 CurrMember = *bi;
2132
2133 // Need to increment the member by K since that is where we are
Daniel Berlind81ccc22007-09-24 19:45:49 +00002134 // supposed to copy to/from. Note that in positive weight cycles,
2135 // which occur in address taking of fields, K can go past
2136 // MaxK[CurrMember] elements, even though that is all it could point
2137 // to.
Daniel Berlinaad15882007-09-16 21:45:02 +00002138 if (K > 0 && K > MaxK[CurrMember])
2139 continue;
2140 else
2141 CurrMember = FindNode(CurrMember + K);
2142
2143 // Add an edge to the graph, so we can just do regular bitmap ior next
2144 // time. It may also let us notice a cycle.
Daniel Berlinc6d93982007-09-16 23:59:53 +00002145 if (GraphNodes[*Src].Edges->test_and_set(*Dest)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002146 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
2147 GraphNodes[*Dest].Changed = true;
2148 // If we changed a node we've already processed, we need another
2149 // iteration.
2150 if (Node2Topo[*Dest] <= i)
2151 Changed = true;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002152 }
2153 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002154 }
2155 li++;
2156 }
2157 SparseBitVector<> NewEdges;
2158 SparseBitVector<> ToErase;
2159
2160 // Now all we have left to do is propagate points-to info along the
2161 // edges, erasing the redundant edges.
2162
2163
2164 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2165 bi != CurrNode->Edges->end();
2166 ++bi) {
2167
2168 unsigned DestVar = *bi;
2169 unsigned Rep = FindNode(DestVar);
2170
2171 // If we ended up with this node as our destination, or we've already
2172 // got an edge for the representative, delete the current edge.
2173 if (Rep == CurrNodeIndex ||
2174 (Rep != DestVar && NewEdges.test(Rep))) {
2175 ToErase.set(DestVar);
2176 continue;
2177 }
2178 // Union the points-to sets into the dest
2179 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2180 GraphNodes[Rep].Changed = true;
2181 if (Node2Topo[Rep] <= i)
2182 Changed = true;
2183 }
2184 // If this edge's destination was collapsed, rewrite the edge.
2185 if (Rep != DestVar) {
2186 ToErase.set(DestVar);
2187 NewEdges.set(Rep);
2188 }
2189 }
2190 CurrNode->Edges->intersectWithComplement(ToErase);
2191 CurrNode->Edges |= NewEdges;
2192 }
2193 if (Changed) {
2194 DFSNumber = RPONumber = 0;
2195 Node2Deleted.clear();
2196 Topo2Node.clear();
2197 Node2Topo.clear();
2198 Node2DFS.clear();
2199 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2200 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2201 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2202 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2203 // Rediscover the DFS/Topo ordering, and cycle detect.
2204 for (unsigned j = 0; j < GraphNodes.size(); j++) {
2205 unsigned JRep = FindNode(j);
2206 if (Node2DFS[JRep] == 0)
2207 QueryNode(JRep);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002208 }
2209 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002210
2211 } while (Changed);
2212
2213 Node2Topo.clear();
2214 Topo2Node.clear();
2215 Node2DFS.clear();
2216 Node2Deleted.clear();
2217 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2218 Node *N = &GraphNodes[i];
2219 delete N->OldPointsTo;
2220 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002221 }
2222}
2223
Daniel Berlinaad15882007-09-16 21:45:02 +00002224//===----------------------------------------------------------------------===//
2225// Union-Find
2226//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002227
Daniel Berlinaad15882007-09-16 21:45:02 +00002228// Unite nodes First and Second, returning the one which is now the
2229// representative node. First and Second are indexes into GraphNodes
2230unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
2231 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2232 "Attempting to merge nodes that don't exist");
2233 // TODO: implement union by rank
2234 Node *FirstNode = &GraphNodes[First];
2235 Node *SecondNode = &GraphNodes[Second];
2236
2237 assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
2238 "Trying to unite two non-representative nodes!");
2239 if (First == Second)
2240 return First;
2241
2242 SecondNode->NodeRep = First;
2243 FirstNode->Changed |= SecondNode->Changed;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002244 if (FirstNode->PointsTo && SecondNode->PointsTo)
2245 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2246 if (FirstNode->Edges && SecondNode->Edges)
2247 FirstNode->Edges |= *(SecondNode->Edges);
2248 if (!FirstNode->Constraints.empty() && !SecondNode->Constraints.empty())
2249 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2250 SecondNode->Constraints);
2251 if (FirstNode->OldPointsTo) {
2252 delete FirstNode->OldPointsTo;
2253 FirstNode->OldPointsTo = new SparseBitVector<>;
2254 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002255
2256 // Destroy interesting parts of the merged-from node.
2257 delete SecondNode->OldPointsTo;
2258 delete SecondNode->Edges;
2259 delete SecondNode->PointsTo;
2260 SecondNode->Edges = NULL;
2261 SecondNode->PointsTo = NULL;
2262 SecondNode->OldPointsTo = NULL;
2263
2264 NumUnified++;
2265 DOUT << "Unified Node ";
2266 DEBUG(PrintNode(FirstNode));
2267 DOUT << " and Node ";
2268 DEBUG(PrintNode(SecondNode));
2269 DOUT << "\n";
2270
2271 // TODO: Handle SDT
2272 return First;
2273}
2274
2275// Find the index into GraphNodes of the node representing Node, performing
2276// path compression along the way
2277unsigned Andersens::FindNode(unsigned NodeIndex) {
2278 assert (NodeIndex < GraphNodes.size()
2279 && "Attempting to find a node that can't exist");
2280 Node *N = &GraphNodes[NodeIndex];
2281 if (N->NodeRep == SelfRep)
2282 return NodeIndex;
2283 else
2284 return (N->NodeRep = FindNode(N->NodeRep));
2285}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002286
2287//===----------------------------------------------------------------------===//
2288// Debugging Output
2289//===----------------------------------------------------------------------===//
2290
2291void Andersens::PrintNode(Node *N) {
2292 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002293 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002294 return;
2295 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002296 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002297 return;
2298 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002299 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002300 return;
2301 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002302 if (!N->getValue()) {
2303 cerr << "artificial" << (intptr_t) N;
2304 return;
2305 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002306
2307 assert(N->getValue() != 0 && "Never set node label!");
2308 Value *V = N->getValue();
2309 if (Function *F = dyn_cast<Function>(V)) {
2310 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002311 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002312 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002313 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002314 } else if (F->getFunctionType()->isVarArg() &&
2315 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002316 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002317 return;
2318 }
2319 }
2320
2321 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002322 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002323 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002324 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002325
2326 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002327 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002328 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002329 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002330
2331 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002332 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002333 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002334}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002335void Andersens::PrintConstraint(const Constraint &C) {
2336 if (C.Type == Constraint::Store) {
2337 cerr << "*";
2338 if (C.Offset != 0)
2339 cerr << "(";
2340 }
2341 PrintNode(&GraphNodes[C.Dest]);
2342 if (C.Type == Constraint::Store && C.Offset != 0)
2343 cerr << " + " << C.Offset << ")";
2344 cerr << " = ";
2345 if (C.Type == Constraint::Load) {
2346 cerr << "*";
2347 if (C.Offset != 0)
2348 cerr << "(";
2349 }
2350 else if (C.Type == Constraint::AddressOf)
2351 cerr << "&";
2352 PrintNode(&GraphNodes[C.Src]);
2353 if (C.Offset != 0 && C.Type != Constraint::Store)
2354 cerr << " + " << C.Offset;
2355 if (C.Type == Constraint::Load && C.Offset != 0)
2356 cerr << ")";
2357 cerr << "\n";
2358}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002359
2360void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002361 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002362
Daniel Berlind81ccc22007-09-24 19:45:49 +00002363 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2364 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002365}
2366
2367void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002368 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002369 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2370 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002371 if (FindNode (i) != i) {
2372 PrintNode(N);
2373 cerr << "\t--> same as ";
2374 PrintNode(&GraphNodes[FindNode(i)]);
2375 cerr << "\n";
2376 } else {
2377 cerr << "[" << (N->PointsTo->count()) << "] ";
2378 PrintNode(N);
2379 cerr << "\t--> ";
2380
2381 bool first = true;
2382 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2383 bi != N->PointsTo->end();
2384 ++bi) {
2385 if (!first)
2386 cerr << ", ";
2387 PrintNode(&GraphNodes[*bi]);
2388 first = false;
2389 }
2390 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002391 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002392 }
2393}