blob: 653ffdded862a784818c4db1483cb1fee4a8c9af [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 Berlind81ccc22007-09-24 19:45:49 +000033// The Offline constraint graph optimization portion includes offline variable
34// substitution algorithms intended to pointer and location equivalences.
35// Pointer equivalences are those pointers that will have the same points-to
36// sets, and location equivalences are those variables that always appear
37// together in points-to sets.
38//
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 }
137 };
138
Daniel Berlind81ccc22007-09-24 19:45:49 +0000139 // Node class - This class is used to represent a node in the constraint
140 // graph. Due to various optimizations, not always the case that there is a
141 // mapping from a Node to a Value. In particular, we add artificial Node's
142 // that represent the set of pointed-to variables shared for each location
143 // equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000144 struct Node {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000145 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000146 SparseBitVector<> *Edges;
147 SparseBitVector<> *PointsTo;
148 SparseBitVector<> *OldPointsTo;
149 bool Changed;
150 std::list<Constraint> Constraints;
151
Daniel Berlind81ccc22007-09-24 19:45:49 +0000152 // Pointer and location equivalence labels
153 unsigned PointerEquivLabel;
154 unsigned LocationEquivLabel;
155 // Predecessor edges, both real and implicit
156 SparseBitVector<> *PredEdges;
157 SparseBitVector<> *ImplicitPredEdges;
158 // Set of nodes that point to us, only use for location equivalence.
159 SparseBitVector<> *PointedToBy;
160 // Number of incoming edges, used during variable substitution to early
161 // free the points-to sets
162 unsigned NumInEdges;
163 // True if our ponits-to set is in the Set2PEClass map
164 bool StoredInHash;
165 // True if our node has no indirect constraints (Complex or otherwise)
166 bool Direct;
167 // True if the node is address taken, *or* it is part of a group of nodes
168 // that must be kept together. This is set to true for functions and
169 // their arg nodes, which must be kept at the same position relative to
170 // their base function node.
171 // kept at the same position relative to their base function node.
172 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000173
Daniel Berlind81ccc22007-09-24 19:45:49 +0000174 // Nodes in cycles (or in equivalence classes) are united together using a
175 // standard union-find representation with path compression. NodeRep
176 // gives the index into GraphNodes for the representative Node.
177 unsigned NodeRep;
178 public:
179
180 Node(bool direct = true) :
181 Val(0), Edges(0), PointsTo(0), OldPointsTo(0), Changed(false),
182 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
183 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
184 StoredInHash(false), Direct(direct), AddressTaken(false),
185 NodeRep(SelfRep) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000186
Chris Lattnere995a2a2004-05-23 21:00:47 +0000187 Node *setValue(Value *V) {
188 assert(Val == 0 && "Value already set for this node!");
189 Val = V;
190 return this;
191 }
192
193 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000194 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000195 Value *getValue() const { return Val; }
196
Chris Lattnere995a2a2004-05-23 21:00:47 +0000197 /// addPointerTo - Add a pointer to the list of pointees of this node,
198 /// returning true if this caused a new pointer to be added, or false if
199 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000200 bool addPointerTo(unsigned Node) {
201 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000202 }
203
204 /// intersects - Return true if the points-to set of this node intersects
205 /// with the points-to set of the specified node.
206 bool intersects(Node *N) const;
207
208 /// intersectsIgnoring - Return true if the points-to set of this node
209 /// intersects with the points-to set of the specified node on any nodes
210 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000211 bool intersectsIgnoring(Node *N, unsigned) const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000212 };
213
214 /// GraphNodes - This vector is populated as part of the object
215 /// identification stage of the analysis, which populates this vector with a
216 /// node for each memory object and fills in the ValueNodes map.
217 std::vector<Node> GraphNodes;
218
219 /// ValueNodes - This map indicates the Node that a particular Value* is
220 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000221 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000222
223 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000224 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000225 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000226
227 /// ReturnNodes - This map contains an entry for each function in the
228 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000229 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000230
231 /// VarargNodes - This map contains the entry used to represent all pointers
232 /// passed through the varargs portion of a function call for a particular
233 /// function. An entry is not present in this map for functions that do not
234 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000235 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000236
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000237
Chris Lattnere995a2a2004-05-23 21:00:47 +0000238 /// Constraints - This vector contains a list of all of the constraints
239 /// identified by the program.
240 std::vector<Constraint> Constraints;
241
Daniel Berlind81ccc22007-09-24 19:45:49 +0000242 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000243 // this is equivalent to the number of arguments + CallFirstArgPos)
244 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000245
246 /// This enum defines the GraphNodes indices that correspond to important
247 /// fixed sets.
248 enum {
249 UniversalSet = 0,
250 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000251 NullObject = 2,
252 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000253 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000254 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000255 std::stack<unsigned> SCCStack;
256 // Topological Index -> Graph node
257 std::vector<unsigned> Topo2Node;
258 // Graph Node -> Topological Index;
259 std::vector<unsigned> Node2Topo;
260 // Map from Graph Node to DFS number
261 std::vector<unsigned> Node2DFS;
262 // Map from Graph Node to Deleted from graph.
263 std::vector<bool> Node2Deleted;
264 // Current DFS and RPO numbers
265 unsigned DFSNumber;
266 unsigned RPONumber;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000267
Daniel Berlind81ccc22007-09-24 19:45:49 +0000268 // Offline variable substitution related things
269
270 // Temporary rep storage, used because we can't collapse SCC's in the
271 // predecessor graph by uniting the variables permanently, we can only do so
272 // for the successor graph.
273 std::vector<unsigned> VSSCCRep;
274 // Mapping from node to whether we have visited it during SCC finding yet.
275 std::vector<bool> Node2Visited;
276 // During variable substitution, we create unknowns to represent the unknown
277 // value that is a dereference of a variable. These nodes are known as
278 // "ref" nodes (since they represent the value of dereferences).
279 unsigned FirstRefNode;
280 // During HVN, we create represent address taken nodes as if they were
281 // unknown (since HVN, unlike HU, does not evaluate unions).
282 unsigned FirstAdrNode;
283 // Current pointer equivalence class number
284 unsigned PEClass;
285 // Mapping from points-to sets to equivalence classes
286 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
287 BitVectorMap Set2PEClass;
288 // Mapping from pointer equivalences to the representative node. -1 if we
289 // have no representative node for this pointer equivalence class yet.
290 std::vector<int> PEClass2Node;
291 // Mapping from pointer equivalences to representative node. This includes
292 // pointer equivalent but not location equivalent variables. -1 if we have
293 // no representative node for this pointer equivalence class yet.
294 std::vector<int> PENLEClass2Node;
295
Chris Lattnere995a2a2004-05-23 21:00:47 +0000296 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000297 static char ID;
298 Andersens() : ModulePass((intptr_t)&ID) {}
299
Chris Lattnerb12914b2004-09-20 04:48:05 +0000300 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000301 InitializeAliasAnalysis(this);
302 IdentifyObjects(M);
303 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000304#undef DEBUG_TYPE
305#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000306 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000307#undef DEBUG_TYPE
308#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000309 SolveConstraints();
310 DEBUG(PrintPointsToGraph());
311
312 // Free the constraints list, as we don't need it to respond to alias
313 // requests.
314 ObjectNodes.clear();
315 ReturnNodes.clear();
316 VarargNodes.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000317 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000318 return false;
319 }
320
321 void releaseMemory() {
322 // FIXME: Until we have transitively required passes working correctly,
323 // this cannot be enabled! Otherwise, using -count-aa with the pass
324 // causes memory to be freed too early. :(
325#if 0
326 // The memory objects and ValueNodes data structures at the only ones that
327 // are still live after construction.
328 std::vector<Node>().swap(GraphNodes);
329 ValueNodes.clear();
330#endif
331 }
332
333 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
334 AliasAnalysis::getAnalysisUsage(AU);
335 AU.setPreservesAll(); // Does not transform code
336 }
337
338 //------------------------------------------------
339 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000340 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000341 AliasResult alias(const Value *V1, unsigned V1Size,
342 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000343 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
344 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000345 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
346 bool pointsToConstantMemory(const Value *P);
347
348 virtual void deleteValue(Value *V) {
349 ValueNodes.erase(V);
350 getAnalysis<AliasAnalysis>().deleteValue(V);
351 }
352
353 virtual void copyValue(Value *From, Value *To) {
354 ValueNodes[To] = ValueNodes[From];
355 getAnalysis<AliasAnalysis>().copyValue(From, To);
356 }
357
358 private:
359 /// getNode - Return the node corresponding to the specified pointer scalar.
360 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000361 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000362 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000363 if (!isa<GlobalValue>(C))
364 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000365
Daniel Berlind81ccc22007-09-24 19:45:49 +0000366 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000367 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000368#ifndef NDEBUG
369 V->dump();
370#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000371 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000372 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000373 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000374 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000375
Chris Lattnere995a2a2004-05-23 21:00:47 +0000376 /// getObject - Return the node corresponding to the memory object for the
377 /// specified global or allocation instruction.
Daniel Berlinaad15882007-09-16 21:45:02 +0000378 unsigned getObject(Value *V) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000379 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000380 assert(I != ObjectNodes.end() &&
381 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000382 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000383 }
384
385 /// getReturnNode - Return the node representing the return value for the
386 /// specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000387 unsigned getReturnNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000388 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000389 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000390 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000391 }
392
393 /// getVarargNode - Return the node representing the variable arguments
394 /// formal for the specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000395 unsigned getVarargNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000396 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000397 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000398 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000399 }
400
401 /// getNodeValue - Get the node for the specified LLVM value and set the
402 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000403 unsigned getNodeValue(Value &V) {
404 unsigned Index = getNode(&V);
405 GraphNodes[Index].setValue(&V);
406 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000407 }
408
Daniel Berlinaad15882007-09-16 21:45:02 +0000409 unsigned UniteNodes(unsigned First, unsigned Second);
410 unsigned FindNode(unsigned Node);
411
Chris Lattnere995a2a2004-05-23 21:00:47 +0000412 void IdentifyObjects(Module &M);
413 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000414 bool AnalyzeUsesOfFunction(Value *);
415 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000416 void OptimizeConstraints();
417 unsigned FindEquivalentNode(unsigned, unsigned);
418 void ClumpAddressTaken();
419 void RewriteConstraints();
420 void HU();
421 void HVN();
422 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000423 void SolveConstraints();
Daniel Berlinaad15882007-09-16 21:45:02 +0000424 void QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000425 void Condense(unsigned Node);
426 void HUValNum(unsigned Node);
427 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000428 unsigned getNodeForConstantPointer(Constant *C);
429 unsigned getNodeForConstantPointerTarget(Constant *C);
430 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000431
Chris Lattnere995a2a2004-05-23 21:00:47 +0000432 void AddConstraintsForNonInternalLinkage(Function *F);
433 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000434 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000435
436
437 void PrintNode(Node *N);
438 void PrintConstraints();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000439 void PrintConstraint(const Constraint &);
440 void PrintLabels();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000441 void PrintPointsToGraph();
442
443 //===------------------------------------------------------------------===//
444 // Instruction visitation methods for adding constraints
445 //
446 friend class InstVisitor<Andersens>;
447 void visitReturnInst(ReturnInst &RI);
448 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
449 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
450 void visitCallSite(CallSite CS);
451 void visitAllocationInst(AllocationInst &AI);
452 void visitLoadInst(LoadInst &LI);
453 void visitStoreInst(StoreInst &SI);
454 void visitGetElementPtrInst(GetElementPtrInst &GEP);
455 void visitPHINode(PHINode &PN);
456 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000457 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
458 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000459 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000460 void visitVAArg(VAArgInst &I);
461 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000462
Chris Lattnere995a2a2004-05-23 21:00:47 +0000463 };
464
Devang Patel19974732007-05-03 01:11:54 +0000465 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000466 RegisterPass<Andersens> X("anders-aa",
467 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000468 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000469}
470
Jeff Cohen534927d2005-01-08 22:01:16 +0000471ModulePass *llvm::createAndersensPass() { return new Andersens(); }
472
Chris Lattnere995a2a2004-05-23 21:00:47 +0000473//===----------------------------------------------------------------------===//
474// AliasAnalysis Interface Implementation
475//===----------------------------------------------------------------------===//
476
477AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
478 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000479 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
480 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000481
482 // Check to see if the two pointers are known to not alias. They don't alias
483 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000484 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000485 return NoAlias;
486
487 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
488}
489
Chris Lattnerf392c642005-03-28 06:21:17 +0000490AliasAnalysis::ModRefResult
491Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
492 // The only thing useful that we can contribute for mod/ref information is
493 // when calling external function calls: if we know that memory never escapes
494 // from the program, it cannot be modified by an external call.
495 //
496 // NOTE: This is not really safe, at least not when the entire program is not
497 // available. The deal is that the external function could call back into the
498 // program and modify stuff. We ignore this technical niggle for now. This
499 // is, after all, a "research quality" implementation of Andersen's analysis.
500 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000501 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000502 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000503
Daniel Berlinaad15882007-09-16 21:45:02 +0000504 if (N1->PointsTo->empty())
505 return NoModRef;
Chris Lattnerf392c642005-03-28 06:21:17 +0000506
Daniel Berlinaad15882007-09-16 21:45:02 +0000507 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000508 return NoModRef; // P doesn't point to the universal set.
509 }
510
511 return AliasAnalysis::getModRefInfo(CS, P, Size);
512}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000513
Reid Spencer3a9ec242006-08-28 01:02:49 +0000514AliasAnalysis::ModRefResult
515Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
516 return AliasAnalysis::getModRefInfo(CS1,CS2);
517}
518
Chris Lattnere995a2a2004-05-23 21:00:47 +0000519/// getMustAlias - We can provide must alias information if we know that a
520/// pointer can only point to a specific function or the null pointer.
521/// Unfortunately we cannot determine must-alias information for global
522/// variables or any other memory memory objects because we do not track whether
523/// a pointer points to the beginning of an object or a field of it.
524void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000525 Node *N = &GraphNodes[FindNode(getNode(P))];
526 if (N->PointsTo->count() == 1) {
527 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
528 // If a function is the only object in the points-to set, then it must be
529 // the destination. Note that we can't handle global variables here,
530 // because we don't know if the pointer is actually pointing to a field of
531 // the global or to the beginning of it.
532 if (Value *V = Pointee->getValue()) {
533 if (Function *F = dyn_cast<Function>(V))
534 RetVals.push_back(F);
535 } else {
536 // If the object in the points-to set is the null object, then the null
537 // pointer is a must alias.
538 if (Pointee == &GraphNodes[NullObject])
539 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000540 }
541 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000542 AliasAnalysis::getMustAliases(P, RetVals);
543}
544
545/// pointsToConstantMemory - If we can determine that this pointer only points
546/// to constant memory, return true. In practice, this means that if the
547/// pointer can only point to constant globals, functions, or the null pointer,
548/// return true.
549///
550bool Andersens::pointsToConstantMemory(const Value *P) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000551 Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
552 unsigned i;
553
554 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
555 bi != N->PointsTo->end();
556 ++bi) {
557 i = *bi;
558 Node *Pointee = &GraphNodes[i];
559 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000560 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
561 !cast<GlobalVariable>(V)->isConstant()))
562 return AliasAnalysis::pointsToConstantMemory(P);
563 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000564 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000565 return AliasAnalysis::pointsToConstantMemory(P);
566 }
567 }
568
569 return true;
570}
571
572//===----------------------------------------------------------------------===//
573// Object Identification Phase
574//===----------------------------------------------------------------------===//
575
576/// IdentifyObjects - This stage scans the program, adding an entry to the
577/// GraphNodes list for each memory object in the program (global stack or
578/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
579///
580void Andersens::IdentifyObjects(Module &M) {
581 unsigned NumObjects = 0;
582
583 // Object #0 is always the universal set: the object that we don't know
584 // anything about.
585 assert(NumObjects == UniversalSet && "Something changed!");
586 ++NumObjects;
587
588 // Object #1 always represents the null pointer.
589 assert(NumObjects == NullPtr && "Something changed!");
590 ++NumObjects;
591
592 // Object #2 always represents the null object (the object pointed to by null)
593 assert(NumObjects == NullObject && "Something changed!");
594 ++NumObjects;
595
596 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000597 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
598 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000599 ObjectNodes[I] = NumObjects++;
600 ValueNodes[I] = NumObjects++;
601 }
602
603 // Add nodes for all of the functions and the instructions inside of them.
604 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
605 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000606 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000607 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000608 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
609 ReturnNodes[F] = NumObjects++;
610 if (F->getFunctionType()->isVarArg())
611 VarargNodes[F] = NumObjects++;
612
Daniel Berlinaad15882007-09-16 21:45:02 +0000613
Chris Lattnere995a2a2004-05-23 21:00:47 +0000614 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000615 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
616 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000617 {
618 if (isa<PointerType>(I->getType()))
619 ValueNodes[I] = NumObjects++;
620 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000621 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000622
623 // Scan the function body, creating a memory object for each heap/stack
624 // allocation in the body of the function and a node to represent all
625 // pointer values defined by instructions and used as operands.
626 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
627 // If this is an heap or stack allocation, create a node for the memory
628 // object.
629 if (isa<PointerType>(II->getType())) {
630 ValueNodes[&*II] = NumObjects++;
631 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
632 ObjectNodes[AI] = NumObjects++;
633 }
634 }
635 }
636
637 // Now that we know how many objects to create, make them all now!
638 GraphNodes.resize(NumObjects);
639 NumNodes += NumObjects;
640}
641
642//===----------------------------------------------------------------------===//
643// Constraint Identification Phase
644//===----------------------------------------------------------------------===//
645
646/// getNodeForConstantPointer - Return the node corresponding to the constant
647/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000648unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000649 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
650
Chris Lattner267a1b02005-03-27 18:58:23 +0000651 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000652 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000653 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
654 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000655 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
656 switch (CE->getOpcode()) {
657 case Instruction::GetElementPtr:
658 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000659 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000660 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000661 case Instruction::BitCast:
662 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000663 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000664 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000665 assert(0);
666 }
667 } else {
668 assert(0 && "Unknown constant pointer!");
669 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000670 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000671}
672
673/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
674/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000675unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000676 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
677
678 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000679 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000680 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
681 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000682 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
683 switch (CE->getOpcode()) {
684 case Instruction::GetElementPtr:
685 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000686 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000687 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000688 case Instruction::BitCast:
689 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000690 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000691 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000692 assert(0);
693 }
694 } else {
695 assert(0 && "Unknown constant pointer!");
696 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000697 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000698}
699
700/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
701/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000702void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
703 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000704 if (C->getType()->isFirstClassType()) {
705 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000706 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
707 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000708 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000709 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
710 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000711 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000712 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000713 // If this is an array or struct, include constraints for each element.
714 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
715 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000716 AddGlobalInitializerConstraints(NodeIndex,
717 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000718 }
719}
720
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000721/// AddConstraintsForNonInternalLinkage - If this function does not have
722/// internal linkage, realize that we can't trust anything passed into or
723/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000724void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000725 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000726 if (isa<PointerType>(I->getType()))
727 // If this is an argument of an externally accessible function, the
728 // incoming pointer might point to anything.
729 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000730 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000731}
732
Chris Lattner8a446432005-03-29 06:09:07 +0000733/// AddConstraintsForCall - If this is a call to a "known" function, add the
734/// constraints and return true. If this is a call to an unknown function,
735/// return false.
736bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000737 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000738
739 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000740 if (F->getName() == "atoi" || F->getName() == "atof" ||
741 F->getName() == "atol" || F->getName() == "atoll" ||
742 F->getName() == "remove" || F->getName() == "unlink" ||
743 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000744 F->getName() == "llvm.memset.i32" ||
745 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000746 F->getName() == "strcmp" || F->getName() == "strncmp" ||
747 F->getName() == "execl" || F->getName() == "execlp" ||
748 F->getName() == "execle" || F->getName() == "execv" ||
749 F->getName() == "execvp" || F->getName() == "chmod" ||
750 F->getName() == "puts" || F->getName() == "write" ||
751 F->getName() == "open" || F->getName() == "create" ||
752 F->getName() == "truncate" || F->getName() == "chdir" ||
753 F->getName() == "mkdir" || F->getName() == "rmdir" ||
754 F->getName() == "read" || F->getName() == "pipe" ||
755 F->getName() == "wait" || F->getName() == "time" ||
756 F->getName() == "stat" || F->getName() == "fstat" ||
757 F->getName() == "lstat" || F->getName() == "strtod" ||
758 F->getName() == "strtof" || F->getName() == "strtold" ||
759 F->getName() == "fopen" || F->getName() == "fdopen" ||
760 F->getName() == "freopen" ||
761 F->getName() == "fflush" || F->getName() == "feof" ||
762 F->getName() == "fileno" || F->getName() == "clearerr" ||
763 F->getName() == "rewind" || F->getName() == "ftell" ||
764 F->getName() == "ferror" || F->getName() == "fgetc" ||
765 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
766 F->getName() == "fwrite" || F->getName() == "fread" ||
767 F->getName() == "fgets" || F->getName() == "ungetc" ||
768 F->getName() == "fputc" ||
769 F->getName() == "fputs" || F->getName() == "putc" ||
770 F->getName() == "ftell" || F->getName() == "rewind" ||
771 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
772 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
773 F->getName() == "printf" || F->getName() == "fprintf" ||
774 F->getName() == "sprintf" || F->getName() == "vprintf" ||
775 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
776 F->getName() == "scanf" || F->getName() == "fscanf" ||
777 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
778 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000779 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000780
Chris Lattner175b9632005-03-29 20:36:05 +0000781
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000782 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000783 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000784 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000785 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000786
787 // *Dest = *Src, which requires an artificial graph node to represent the
788 // constraint. It is broken up into *Dest = temp, temp = *Src
789 unsigned FirstArg = getNode(CS.getArgument(0));
790 unsigned SecondArg = getNode(CS.getArgument(1));
791 unsigned TempArg = GraphNodes.size();
792 GraphNodes.push_back(Node());
793 Constraints.push_back(Constraint(Constraint::Store,
794 FirstArg, TempArg));
795 Constraints.push_back(Constraint(Constraint::Load,
796 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000797 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000798 }
799
Chris Lattner77b50562005-03-29 20:04:24 +0000800 // Result = Arg0
801 if (F->getName() == "realloc" || F->getName() == "strchr" ||
802 F->getName() == "strrchr" || F->getName() == "strstr" ||
803 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000804 Constraints.push_back(Constraint(Constraint::Copy,
805 getNode(CS.getInstruction()),
806 getNode(CS.getArgument(0))));
807 return true;
808 }
809
810 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000811}
812
813
Chris Lattnere995a2a2004-05-23 21:00:47 +0000814
Daniel Berlinaad15882007-09-16 21:45:02 +0000815/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
816/// If this is used by anything complex (i.e., the address escapes), return
817/// true.
818bool Andersens::AnalyzeUsesOfFunction(Value *V) {
819
820 if (!isa<PointerType>(V->getType())) return true;
821
822 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
823 if (dyn_cast<LoadInst>(*UI)) {
824 return false;
825 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
826 if (V == SI->getOperand(1)) {
827 return false;
828 } else if (SI->getOperand(1)) {
829 return true; // Storing the pointer
830 }
831 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
832 if (AnalyzeUsesOfFunction(GEP)) return true;
833 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
834 // Make sure that this is just the function being called, not that it is
835 // passing into the function.
836 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
837 if (CI->getOperand(i) == V) return true;
838 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
839 // Make sure that this is just the function being called, not that it is
840 // passing into the function.
841 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
842 if (II->getOperand(i) == V) return true;
843 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
844 if (CE->getOpcode() == Instruction::GetElementPtr ||
845 CE->getOpcode() == Instruction::BitCast) {
846 if (AnalyzeUsesOfFunction(CE))
847 return true;
848 } else {
849 return true;
850 }
851 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
852 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
853 return true; // Allow comparison against null.
854 } else if (dyn_cast<FreeInst>(*UI)) {
855 return false;
856 } else {
857 return true;
858 }
859 return false;
860}
861
Chris Lattnere995a2a2004-05-23 21:00:47 +0000862/// CollectConstraints - This stage scans the program, adding a constraint to
863/// the Constraints list for each instruction in the program that induces a
864/// constraint, and setting up the initial points-to graph.
865///
866void Andersens::CollectConstraints(Module &M) {
867 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000868 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
869 UniversalSet));
870 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
871 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000872
873 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000874 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000875
876 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000877 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
878 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000879 // Associate the address of the global object as pointing to the memory for
880 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +0000881 unsigned ObjectIndex = getObject(I);
882 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000883 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000884 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
885 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000886
887 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000888 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +0000889 } else {
890 // If it doesn't have an initializer (i.e. it's defined in another
891 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +0000892 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
893 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000894 }
895 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000896
Chris Lattnere995a2a2004-05-23 21:00:47 +0000897 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000898 // Set up the return value node.
899 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000900 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000901 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +0000902 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000903
904 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000905 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
906 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000907 if (isa<PointerType>(I->getType()))
908 getNodeValue(*I);
909
Daniel Berlinaad15882007-09-16 21:45:02 +0000910 // At some point we should just add constraints for the escaping functions
911 // at solve time, but this slows down solving. For now, we simply mark
912 // address taken functions as escaping and treat them as external.
913 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000914 AddConstraintsForNonInternalLinkage(F);
915
Reid Spencer5cbf9852007-01-30 20:08:39 +0000916 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000917 // Scan the function body, creating a memory object for each heap/stack
918 // allocation in the body of the function and a node to represent all
919 // pointer values defined by instructions and used as operands.
920 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000921 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000922 // External functions that return pointers return the universal set.
923 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
924 Constraints.push_back(Constraint(Constraint::Copy,
925 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000926 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000927
928 // Any pointers that are passed into the function have the universal set
929 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000930 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
931 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000932 if (isa<PointerType>(I->getType())) {
933 // Pointers passed into external functions could have anything stored
934 // through them.
935 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000936 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000937 // Memory objects passed into external function calls can have the
938 // universal set point to them.
939 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +0000940 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +0000941 getNode(I)));
942 }
943
944 // If this is an external varargs function, it can also store pointers
945 // into any pointers passed through the varargs section.
946 if (F->getFunctionType()->isVarArg())
947 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000948 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000949 }
950 }
951 NumConstraints += Constraints.size();
952}
953
954
955void Andersens::visitInstruction(Instruction &I) {
956#ifdef NDEBUG
957 return; // This function is just a big assert.
958#endif
959 if (isa<BinaryOperator>(I))
960 return;
961 // Most instructions don't have any effect on pointer values.
962 switch (I.getOpcode()) {
963 case Instruction::Br:
964 case Instruction::Switch:
965 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +0000966 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000967 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000968 case Instruction::ICmp:
969 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000970 return;
971 default:
972 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +0000973 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000974 abort();
975 }
976}
977
978void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000979 unsigned ObjectIndex = getObject(&AI);
980 GraphNodes[ObjectIndex].setValue(&AI);
981 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
982 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000983}
984
985void Andersens::visitReturnInst(ReturnInst &RI) {
986 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
987 // return V --> <Copy/retval{F}/v>
988 Constraints.push_back(Constraint(Constraint::Copy,
989 getReturnNode(RI.getParent()->getParent()),
990 getNode(RI.getOperand(0))));
991}
992
993void Andersens::visitLoadInst(LoadInst &LI) {
994 if (isa<PointerType>(LI.getType()))
995 // P1 = load P2 --> <Load/P1/P2>
996 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
997 getNode(LI.getOperand(0))));
998}
999
1000void Andersens::visitStoreInst(StoreInst &SI) {
1001 if (isa<PointerType>(SI.getOperand(0)->getType()))
1002 // store P1, P2 --> <Store/P2/P1>
1003 Constraints.push_back(Constraint(Constraint::Store,
1004 getNode(SI.getOperand(1)),
1005 getNode(SI.getOperand(0))));
1006}
1007
1008void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1009 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1010 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1011 getNode(GEP.getOperand(0))));
1012}
1013
1014void Andersens::visitPHINode(PHINode &PN) {
1015 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001016 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001017 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1018 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1019 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1020 getNode(PN.getIncomingValue(i))));
1021 }
1022}
1023
1024void Andersens::visitCastInst(CastInst &CI) {
1025 Value *Op = CI.getOperand(0);
1026 if (isa<PointerType>(CI.getType())) {
1027 if (isa<PointerType>(Op->getType())) {
1028 // P1 = cast P2 --> <Copy/P1/P2>
1029 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1030 getNode(CI.getOperand(0))));
1031 } else {
1032 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001033#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001034 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001035 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001036#else
1037 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001038#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001039 }
1040 } else if (isa<PointerType>(Op->getType())) {
1041 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001042#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001043 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001044 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001045 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001046#else
1047 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001048#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001049 }
1050}
1051
1052void Andersens::visitSelectInst(SelectInst &SI) {
1053 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001054 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001055 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1056 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1057 getNode(SI.getOperand(1))));
1058 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1059 getNode(SI.getOperand(2))));
1060 }
1061}
1062
Chris Lattnere995a2a2004-05-23 21:00:47 +00001063void Andersens::visitVAArg(VAArgInst &I) {
1064 assert(0 && "vaarg not handled yet!");
1065}
1066
1067/// AddConstraintsForCall - Add constraints for a call with actual arguments
1068/// specified by CS to the function specified by F. Note that the types of
1069/// arguments might not match up in the case where this is an indirect call and
1070/// the function pointer has been casted. If this is the case, do something
1071/// reasonable.
1072void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001073 Value *CallValue = CS.getCalledValue();
1074 bool IsDeref = F == NULL;
1075
1076 // If this is a call to an external function, try to handle it directly to get
1077 // some taste of context sensitivity.
1078 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001079 return;
1080
Chris Lattnere995a2a2004-05-23 21:00:47 +00001081 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001082 unsigned CSN = getNode(CS.getInstruction());
1083 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1084 if (IsDeref)
1085 Constraints.push_back(Constraint(Constraint::Load, CSN,
1086 getNode(CallValue), CallReturnPos));
1087 else
1088 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1089 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001090 } else {
1091 // If the function returns a non-pointer value, handle this just like we
1092 // treat a nonpointer cast to pointer.
1093 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001094 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001095 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001096 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001097 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001098 UniversalSet,
1099 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001100 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001101
Chris Lattnere995a2a2004-05-23 21:00:47 +00001102 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinaad15882007-09-16 21:45:02 +00001103 if (F) {
1104 // Direct Call
1105 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1106 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1107 if (isa<PointerType>(AI->getType())) {
1108 if (isa<PointerType>((*ArgI)->getType())) {
1109 // Copy the actual argument into the formal argument.
1110 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1111 getNode(*ArgI)));
1112 } else {
1113 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1114 UniversalSet));
1115 }
1116 } else if (isa<PointerType>((*ArgI)->getType())) {
1117 Constraints.push_back(Constraint(Constraint::Copy,
1118 UniversalSet,
1119 getNode(*ArgI)));
1120 }
1121 } else {
1122 //Indirect Call
1123 unsigned ArgPos = CallFirstArgPos;
1124 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001125 if (isa<PointerType>((*ArgI)->getType())) {
1126 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001127 Constraints.push_back(Constraint(Constraint::Store,
1128 getNode(CallValue),
1129 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001130 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001131 Constraints.push_back(Constraint(Constraint::Store,
1132 getNode (CallValue),
1133 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001134 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001135 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001136 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001137 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001138 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001139 for (; ArgI != ArgE; ++ArgI)
1140 if (isa<PointerType>((*ArgI)->getType()))
1141 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1142 getNode(*ArgI)));
1143 // If more arguments are passed in than we track, just drop them on the floor.
1144}
1145
1146void Andersens::visitCallSite(CallSite CS) {
1147 if (isa<PointerType>(CS.getType()))
1148 getNodeValue(*CS.getInstruction());
1149
1150 if (Function *F = CS.getCalledFunction()) {
1151 AddConstraintsForCall(CS, F);
1152 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001153 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001154 }
1155}
1156
1157//===----------------------------------------------------------------------===//
1158// Constraint Solving Phase
1159//===----------------------------------------------------------------------===//
1160
1161/// intersects - Return true if the points-to set of this node intersects
1162/// with the points-to set of the specified node.
1163bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001164 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001165}
1166
1167/// intersectsIgnoring - Return true if the points-to set of this node
1168/// intersects with the points-to set of the specified node on any nodes
1169/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001170bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1171 // TODO: If we are only going to call this with the same value for Ignoring,
1172 // we should move the special values out of the points-to bitmap.
1173 bool WeHadIt = PointsTo->test(Ignoring);
1174 bool NHadIt = N->PointsTo->test(Ignoring);
1175 bool Result = false;
1176 if (WeHadIt)
1177 PointsTo->reset(Ignoring);
1178 if (NHadIt)
1179 N->PointsTo->reset(Ignoring);
1180 Result = PointsTo->intersects(N->PointsTo);
1181 if (WeHadIt)
1182 PointsTo->set(Ignoring);
1183 if (NHadIt)
1184 N->PointsTo->set(Ignoring);
1185 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001186}
1187
Daniel Berlind81ccc22007-09-24 19:45:49 +00001188void dumpToDOUT(SparseBitVector<> *bitmap) {
1189 dump(*bitmap, DOUT);
1190}
1191
1192
1193/// Clump together address taken variables so that the points-to sets use up
1194/// less space and can be operated on faster.
1195
1196void Andersens::ClumpAddressTaken() {
1197#undef DEBUG_TYPE
1198#define DEBUG_TYPE "anders-aa-renumber"
1199 std::vector<unsigned> Translate;
1200 std::vector<Node> NewGraphNodes;
1201
1202 Translate.resize(GraphNodes.size());
1203 unsigned NewPos = 0;
1204
1205 for (unsigned i = 0; i < Constraints.size(); ++i) {
1206 Constraint &C = Constraints[i];
1207 if (C.Type == Constraint::AddressOf) {
1208 GraphNodes[C.Src].AddressTaken = true;
1209 }
1210 }
1211 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1212 unsigned Pos = NewPos++;
1213 Translate[i] = Pos;
1214 NewGraphNodes.push_back(GraphNodes[i]);
1215 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1216 }
1217
1218 // I believe this ends up being faster than making two vectors and splicing
1219 // them.
1220 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1221 if (GraphNodes[i].AddressTaken) {
1222 unsigned Pos = NewPos++;
1223 Translate[i] = Pos;
1224 NewGraphNodes.push_back(GraphNodes[i]);
1225 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1226 }
1227 }
1228
1229 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1230 if (!GraphNodes[i].AddressTaken) {
1231 unsigned Pos = NewPos++;
1232 Translate[i] = Pos;
1233 NewGraphNodes.push_back(GraphNodes[i]);
1234 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1235 }
1236 }
1237
1238 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1239 Iter != ValueNodes.end();
1240 ++Iter)
1241 Iter->second = Translate[Iter->second];
1242
1243 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1244 Iter != ObjectNodes.end();
1245 ++Iter)
1246 Iter->second = Translate[Iter->second];
1247
1248 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1249 Iter != ReturnNodes.end();
1250 ++Iter)
1251 Iter->second = Translate[Iter->second];
1252
1253 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1254 Iter != VarargNodes.end();
1255 ++Iter)
1256 Iter->second = Translate[Iter->second];
1257
1258 for (unsigned i = 0; i < Constraints.size(); ++i) {
1259 Constraint &C = Constraints[i];
1260 C.Src = Translate[C.Src];
1261 C.Dest = Translate[C.Dest];
1262 }
1263
1264 GraphNodes.swap(NewGraphNodes);
1265#undef DEBUG_TYPE
1266#define DEBUG_TYPE "anders-aa"
1267}
1268
1269/// The technique used here is described in "Exploiting Pointer and Location
1270/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1271/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1272/// and is equivalent to value numbering the collapsed constraint graph without
1273/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1274/// first order pointer dereferences and speed up/reduce memory usage of HU.
1275/// Running both is equivalent to HRU without the iteration
1276/// HVN in more detail:
1277/// Imagine the set of constraints was simply straight line code with no loops
1278/// (we eliminate cycles, so there are no loops), such as:
1279/// E = &D
1280/// E = &C
1281/// E = F
1282/// F = G
1283/// G = F
1284/// Applying value numbering to this code tells us:
1285/// G == F == E
1286///
1287/// For HVN, this is as far as it goes. We assign new value numbers to every
1288/// "address node", and every "reference node".
1289/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1290/// cycle must have the same value number since the = operation is really
1291/// inclusion, not overwrite), and value number nodes we receive points-to sets
1292/// before we value our own node.
1293/// The advantage of HU over HVN is that HU considers the inclusion property, so
1294/// that if you have
1295/// E = &D
1296/// E = &C
1297/// E = F
1298/// F = G
1299/// F = &D
1300/// G = F
1301/// HU will determine that G == F == E. HVN will not, because it cannot prove
1302/// that the points to information ends up being the same because they all
1303/// receive &D from E anyway.
1304
1305void Andersens::HVN() {
1306 DOUT << "Beginning HVN\n";
1307 // Build a predecessor graph. This is like our constraint graph with the
1308 // edges going in the opposite direction, and there are edges for all the
1309 // constraints, instead of just copy constraints. We also build implicit
1310 // edges for constraints are implied but not explicit. I.E for the constraint
1311 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1312 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1313 Constraint &C = Constraints[i];
1314 if (C.Type == Constraint::AddressOf) {
1315 GraphNodes[C.Src].AddressTaken = true;
1316 GraphNodes[C.Src].Direct = false;
1317
1318 // Dest = &src edge
1319 unsigned AdrNode = C.Src + FirstAdrNode;
1320 if (!GraphNodes[C.Dest].PredEdges)
1321 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1322 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1323
1324 // *Dest = src edge
1325 unsigned RefNode = C.Dest + FirstRefNode;
1326 if (!GraphNodes[RefNode].ImplicitPredEdges)
1327 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1328 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1329 } else if (C.Type == Constraint::Load) {
1330 if (C.Offset == 0) {
1331 // dest = *src edge
1332 if (!GraphNodes[C.Dest].PredEdges)
1333 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1334 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1335 } else {
1336 GraphNodes[C.Dest].Direct = false;
1337 }
1338 } else if (C.Type == Constraint::Store) {
1339 if (C.Offset == 0) {
1340 // *dest = src edge
1341 unsigned RefNode = C.Dest + FirstRefNode;
1342 if (!GraphNodes[RefNode].PredEdges)
1343 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1344 GraphNodes[RefNode].PredEdges->set(C.Src);
1345 }
1346 } else {
1347 // Dest = Src edge and *Dest = *Src edge
1348 if (!GraphNodes[C.Dest].PredEdges)
1349 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1350 GraphNodes[C.Dest].PredEdges->set(C.Src);
1351 unsigned RefNode = C.Dest + FirstRefNode;
1352 if (!GraphNodes[RefNode].ImplicitPredEdges)
1353 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1354 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1355 }
1356 }
1357 PEClass = 1;
1358 // Do SCC finding first to condense our predecessor graph
1359 DFSNumber = 0;
1360 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1361 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1362 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1363
1364 for (unsigned i = 0; i < FirstRefNode; ++i) {
1365 unsigned Node = VSSCCRep[i];
1366 if (!Node2Visited[Node])
1367 HVNValNum(Node);
1368 }
1369 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1370 Iter != Set2PEClass.end();
1371 ++Iter)
1372 delete Iter->first;
1373 Set2PEClass.clear();
1374 Node2DFS.clear();
1375 Node2Deleted.clear();
1376 Node2Visited.clear();
1377 DOUT << "Finished HVN\n";
1378
1379}
1380
1381/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1382/// same time because it's easy.
1383void Andersens::HVNValNum(unsigned NodeIndex) {
1384 unsigned MyDFS = DFSNumber++;
1385 Node *N = &GraphNodes[NodeIndex];
1386 Node2Visited[NodeIndex] = true;
1387 Node2DFS[NodeIndex] = MyDFS;
1388
1389 // First process all our explicit edges
1390 if (N->PredEdges)
1391 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1392 Iter != N->PredEdges->end();
1393 ++Iter) {
1394 unsigned j = VSSCCRep[*Iter];
1395 if (!Node2Deleted[j]) {
1396 if (!Node2Visited[j])
1397 HVNValNum(j);
1398 if (Node2DFS[NodeIndex] > Node2DFS[j])
1399 Node2DFS[NodeIndex] = Node2DFS[j];
1400 }
1401 }
1402
1403 // Now process all the implicit edges
1404 if (N->ImplicitPredEdges)
1405 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1406 Iter != N->ImplicitPredEdges->end();
1407 ++Iter) {
1408 unsigned j = VSSCCRep[*Iter];
1409 if (!Node2Deleted[j]) {
1410 if (!Node2Visited[j])
1411 HVNValNum(j);
1412 if (Node2DFS[NodeIndex] > Node2DFS[j])
1413 Node2DFS[NodeIndex] = Node2DFS[j];
1414 }
1415 }
1416
1417 // See if we found any cycles
1418 if (MyDFS == Node2DFS[NodeIndex]) {
1419 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1420 unsigned CycleNodeIndex = SCCStack.top();
1421 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1422 VSSCCRep[CycleNodeIndex] = NodeIndex;
1423 // Unify the nodes
1424 N->Direct &= CycleNode->Direct;
1425
1426 if (CycleNode->PredEdges) {
1427 if (!N->PredEdges)
1428 N->PredEdges = new SparseBitVector<>;
1429 *(N->PredEdges) |= CycleNode->PredEdges;
1430 delete CycleNode->PredEdges;
1431 CycleNode->PredEdges = NULL;
1432 }
1433 if (CycleNode->ImplicitPredEdges) {
1434 if (!N->ImplicitPredEdges)
1435 N->ImplicitPredEdges = new SparseBitVector<>;
1436 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1437 delete CycleNode->ImplicitPredEdges;
1438 CycleNode->ImplicitPredEdges = NULL;
1439 }
1440
1441 SCCStack.pop();
1442 }
1443
1444 Node2Deleted[NodeIndex] = true;
1445
1446 if (!N->Direct) {
1447 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1448 return;
1449 }
1450
1451 // Collect labels of successor nodes
1452 bool AllSame = true;
1453 unsigned First = ~0;
1454 SparseBitVector<> *Labels = new SparseBitVector<>;
1455 bool Used = false;
1456
1457 if (N->PredEdges)
1458 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1459 Iter != N->PredEdges->end();
1460 ++Iter) {
1461 unsigned j = VSSCCRep[*Iter];
1462 unsigned Label = GraphNodes[j].PointerEquivLabel;
1463 // Ignore labels that are equal to us or non-pointers
1464 if (j == NodeIndex || Label == 0)
1465 continue;
1466 if (First == (unsigned)~0)
1467 First = Label;
1468 else if (First != Label)
1469 AllSame = false;
1470 Labels->set(Label);
1471 }
1472
1473 // We either have a non-pointer, a copy of an existing node, or a new node.
1474 // Assign the appropriate pointer equivalence label.
1475 if (Labels->empty()) {
1476 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1477 } else if (AllSame) {
1478 GraphNodes[NodeIndex].PointerEquivLabel = First;
1479 } else {
1480 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1481 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1482 unsigned EquivClass = PEClass++;
1483 Set2PEClass[Labels] = EquivClass;
1484 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1485 Used = true;
1486 }
1487 }
1488 if (!Used)
1489 delete Labels;
1490 } else {
1491 SCCStack.push(NodeIndex);
1492 }
1493}
1494
1495/// The technique used here is described in "Exploiting Pointer and Location
1496/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1497/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1498/// and is equivalent to value numbering the collapsed constraint graph
1499/// including evaluating unions.
1500void Andersens::HU() {
1501 DOUT << "Beginning HU\n";
1502 // Build a predecessor graph. This is like our constraint graph with the
1503 // edges going in the opposite direction, and there are edges for all the
1504 // constraints, instead of just copy constraints. We also build implicit
1505 // edges for constraints are implied but not explicit. I.E for the constraint
1506 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1507 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1508 Constraint &C = Constraints[i];
1509 if (C.Type == Constraint::AddressOf) {
1510 GraphNodes[C.Src].AddressTaken = true;
1511 GraphNodes[C.Src].Direct = false;
1512
1513 GraphNodes[C.Dest].PointsTo->set(C.Src);
1514 // *Dest = src edge
1515 unsigned RefNode = C.Dest + FirstRefNode;
1516 if (!GraphNodes[RefNode].ImplicitPredEdges)
1517 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1518 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1519 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1520 } else if (C.Type == Constraint::Load) {
1521 if (C.Offset == 0) {
1522 // dest = *src edge
1523 if (!GraphNodes[C.Dest].PredEdges)
1524 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1525 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1526 } else {
1527 GraphNodes[C.Dest].Direct = false;
1528 }
1529 } else if (C.Type == Constraint::Store) {
1530 if (C.Offset == 0) {
1531 // *dest = src edge
1532 unsigned RefNode = C.Dest + FirstRefNode;
1533 if (!GraphNodes[RefNode].PredEdges)
1534 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1535 GraphNodes[RefNode].PredEdges->set(C.Src);
1536 }
1537 } else {
1538 // Dest = Src edge and *Dest = *Src edg
1539 if (!GraphNodes[C.Dest].PredEdges)
1540 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1541 GraphNodes[C.Dest].PredEdges->set(C.Src);
1542 unsigned RefNode = C.Dest + FirstRefNode;
1543 if (!GraphNodes[RefNode].ImplicitPredEdges)
1544 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1545 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1546 }
1547 }
1548 PEClass = 1;
1549 // Do SCC finding first to condense our predecessor graph
1550 DFSNumber = 0;
1551 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1552 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1553 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1554
1555 for (unsigned i = 0; i < FirstRefNode; ++i) {
1556 if (FindNode(i) == i) {
1557 unsigned Node = VSSCCRep[i];
1558 if (!Node2Visited[Node])
1559 Condense(Node);
1560 }
1561 }
1562
1563 // Reset tables for actual labeling
1564 Node2DFS.clear();
1565 Node2Visited.clear();
1566 Node2Deleted.clear();
1567 // Pre-grow our densemap so that we don't get really bad behavior
1568 Set2PEClass.resize(GraphNodes.size());
1569
1570 // Visit the condensed graph and generate pointer equivalence labels.
1571 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1572 for (unsigned i = 0; i < FirstRefNode; ++i) {
1573 if (FindNode(i) == i) {
1574 unsigned Node = VSSCCRep[i];
1575 if (!Node2Visited[Node])
1576 HUValNum(Node);
1577 }
1578 }
1579 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1580 Set2PEClass.clear();
1581 DOUT << "Finished HU\n";
1582}
1583
1584
1585/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1586void Andersens::Condense(unsigned NodeIndex) {
1587 unsigned MyDFS = DFSNumber++;
1588 Node *N = &GraphNodes[NodeIndex];
1589 Node2Visited[NodeIndex] = true;
1590 Node2DFS[NodeIndex] = MyDFS;
1591
1592 // First process all our explicit edges
1593 if (N->PredEdges)
1594 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1595 Iter != N->PredEdges->end();
1596 ++Iter) {
1597 unsigned j = VSSCCRep[*Iter];
1598 if (!Node2Deleted[j]) {
1599 if (!Node2Visited[j])
1600 Condense(j);
1601 if (Node2DFS[NodeIndex] > Node2DFS[j])
1602 Node2DFS[NodeIndex] = Node2DFS[j];
1603 }
1604 }
1605
1606 // Now process all the implicit edges
1607 if (N->ImplicitPredEdges)
1608 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1609 Iter != N->ImplicitPredEdges->end();
1610 ++Iter) {
1611 unsigned j = VSSCCRep[*Iter];
1612 if (!Node2Deleted[j]) {
1613 if (!Node2Visited[j])
1614 Condense(j);
1615 if (Node2DFS[NodeIndex] > Node2DFS[j])
1616 Node2DFS[NodeIndex] = Node2DFS[j];
1617 }
1618 }
1619
1620 // See if we found any cycles
1621 if (MyDFS == Node2DFS[NodeIndex]) {
1622 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1623 unsigned CycleNodeIndex = SCCStack.top();
1624 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1625 VSSCCRep[CycleNodeIndex] = NodeIndex;
1626 // Unify the nodes
1627 N->Direct &= CycleNode->Direct;
1628
1629 *(N->PointsTo) |= CycleNode->PointsTo;
1630 delete CycleNode->PointsTo;
1631 CycleNode->PointsTo = NULL;
1632 if (CycleNode->PredEdges) {
1633 if (!N->PredEdges)
1634 N->PredEdges = new SparseBitVector<>;
1635 *(N->PredEdges) |= CycleNode->PredEdges;
1636 delete CycleNode->PredEdges;
1637 CycleNode->PredEdges = NULL;
1638 }
1639 if (CycleNode->ImplicitPredEdges) {
1640 if (!N->ImplicitPredEdges)
1641 N->ImplicitPredEdges = new SparseBitVector<>;
1642 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1643 delete CycleNode->ImplicitPredEdges;
1644 CycleNode->ImplicitPredEdges = NULL;
1645 }
1646 SCCStack.pop();
1647 }
1648
1649 Node2Deleted[NodeIndex] = true;
1650
1651 // Set up number of incoming edges for other nodes
1652 if (N->PredEdges)
1653 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1654 Iter != N->PredEdges->end();
1655 ++Iter)
1656 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1657 } else {
1658 SCCStack.push(NodeIndex);
1659 }
1660}
1661
1662void Andersens::HUValNum(unsigned NodeIndex) {
1663 Node *N = &GraphNodes[NodeIndex];
1664 Node2Visited[NodeIndex] = true;
1665
1666 // Eliminate dereferences of non-pointers for those non-pointers we have
1667 // already identified. These are ref nodes whose non-ref node:
1668 // 1. Has already been visited determined to point to nothing (and thus, a
1669 // dereference of it must point to nothing)
1670 // 2. Any direct node with no predecessor edges in our graph and with no
1671 // points-to set (since it can't point to anything either, being that it
1672 // receives no points-to sets and has none).
1673 if (NodeIndex >= FirstRefNode) {
1674 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1675 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1676 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1677 && GraphNodes[j].PointsTo->empty())){
1678 return;
1679 }
1680 }
1681 // Process all our explicit edges
1682 if (N->PredEdges)
1683 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1684 Iter != N->PredEdges->end();
1685 ++Iter) {
1686 unsigned j = VSSCCRep[*Iter];
1687 if (!Node2Visited[j])
1688 HUValNum(j);
1689
1690 // If this edge turned out to be the same as us, or got no pointer
1691 // equivalence label (and thus points to nothing) , just decrement our
1692 // incoming edges and continue.
1693 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1694 --GraphNodes[j].NumInEdges;
1695 continue;
1696 }
1697
1698 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1699
1700 // If we didn't end up storing this in the hash, and we're done with all
1701 // the edges, we don't need the points-to set anymore.
1702 --GraphNodes[j].NumInEdges;
1703 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1704 delete GraphNodes[j].PointsTo;
1705 GraphNodes[j].PointsTo = NULL;
1706 }
1707 }
1708 // If this isn't a direct node, generate a fresh variable.
1709 if (!N->Direct) {
1710 N->PointsTo->set(FirstRefNode + NodeIndex);
1711 }
1712
1713 // See If we have something equivalent to us, if not, generate a new
1714 // equivalence class.
1715 if (N->PointsTo->empty()) {
1716 delete N->PointsTo;
1717 N->PointsTo = NULL;
1718 } else {
1719 if (N->Direct) {
1720 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1721 if (N->PointerEquivLabel == 0) {
1722 unsigned EquivClass = PEClass++;
1723 N->StoredInHash = true;
1724 Set2PEClass[N->PointsTo] = EquivClass;
1725 N->PointerEquivLabel = EquivClass;
1726 }
1727 } else {
1728 N->PointerEquivLabel = PEClass++;
1729 }
1730 }
1731}
1732
1733/// Rewrite our list of constraints so that pointer equivalent nodes are
1734/// replaced by their the pointer equivalence class representative.
1735void Andersens::RewriteConstraints() {
1736 std::vector<Constraint> NewConstraints;
1737
1738 PEClass2Node.clear();
1739 PENLEClass2Node.clear();
1740
1741 // We may have from 1 to Graphnodes + 1 equivalence classes.
1742 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1743 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1744
1745 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1746 // nodes, and rewriting constraints to use the representative nodes.
1747 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1748 Constraint &C = Constraints[i];
1749 unsigned RHSNode = FindNode(C.Src);
1750 unsigned LHSNode = FindNode(C.Dest);
1751 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1752 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1753
1754 // First we try to eliminate constraints for things we can prove don't point
1755 // to anything.
1756 if (LHSLabel == 0) {
1757 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1758 DOUT << " is a non-pointer, ignoring constraint.\n";
1759 continue;
1760 }
1761 if (RHSLabel == 0) {
1762 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1763 DOUT << " is a non-pointer, ignoring constraint.\n";
1764 continue;
1765 }
1766 // This constraint may be useless, and it may become useless as we translate
1767 // it.
1768 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1769 continue;
1770
1771 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1772 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
1773 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1774 continue;
1775
1776 NewConstraints.push_back(C);
1777 }
1778 Constraints.swap(NewConstraints);
1779 PEClass2Node.clear();
1780}
1781
1782/// See if we have a node that is pointer equivalent to the one being asked
1783/// about, and if so, unite them and return the equivalent node. Otherwise,
1784/// return the original node.
1785unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1786 unsigned NodeLabel) {
1787 if (!GraphNodes[NodeIndex].AddressTaken) {
1788 if (PEClass2Node[NodeLabel] != -1) {
1789 // We found an existing node with the same pointer label, so unify them.
1790 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex);
1791 } else {
1792 PEClass2Node[NodeLabel] = NodeIndex;
1793 PENLEClass2Node[NodeLabel] = NodeIndex;
1794 }
1795 } else if (PENLEClass2Node[NodeLabel] == -1) {
1796 PENLEClass2Node[NodeLabel] = NodeIndex;
1797 }
1798
1799 return NodeIndex;
1800}
1801
1802void Andersens::PrintLabels() {
1803 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1804 if (i < FirstRefNode) {
1805 PrintNode(&GraphNodes[i]);
1806 } else if (i < FirstAdrNode) {
1807 DOUT << "REF(";
1808 PrintNode(&GraphNodes[i-FirstRefNode]);
1809 DOUT <<")";
1810 } else {
1811 DOUT << "ADR(";
1812 PrintNode(&GraphNodes[i-FirstAdrNode]);
1813 DOUT <<")";
1814 }
1815
1816 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1817 << " and SCC rep " << VSSCCRep[i]
1818 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1819 << "\n";
1820 }
1821}
1822
1823/// Optimize the constraints by performing offline variable substitution and
1824/// other optimizations.
1825void Andersens::OptimizeConstraints() {
1826 DOUT << "Beginning constraint optimization\n";
1827
1828 // Function related nodes need to stay in the same relative position and can't
1829 // be location equivalent.
1830 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1831 Iter != MaxK.end();
1832 ++Iter) {
1833 for (unsigned i = Iter->first;
1834 i != Iter->first + Iter->second;
1835 ++i) {
1836 GraphNodes[i].AddressTaken = true;
1837 GraphNodes[i].Direct = false;
1838 }
1839 }
1840
1841 ClumpAddressTaken();
1842 FirstRefNode = GraphNodes.size();
1843 FirstAdrNode = FirstRefNode + GraphNodes.size();
1844 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
1845 Node(false));
1846 VSSCCRep.resize(GraphNodes.size());
1847 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1848 VSSCCRep[i] = i;
1849 }
1850 HVN();
1851 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1852 Node *N = &GraphNodes[i];
1853 delete N->PredEdges;
1854 N->PredEdges = NULL;
1855 delete N->ImplicitPredEdges;
1856 N->ImplicitPredEdges = NULL;
1857 }
1858#undef DEBUG_TYPE
1859#define DEBUG_TYPE "anders-aa-labels"
1860 DEBUG(PrintLabels());
1861#undef DEBUG_TYPE
1862#define DEBUG_TYPE "anders-aa"
1863 RewriteConstraints();
1864 // Delete the adr nodes.
1865 GraphNodes.resize(FirstRefNode * 2);
1866
1867 // Now perform HU
1868 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1869 Node *N = &GraphNodes[i];
1870 if (FindNode(i) == i) {
1871 N->PointsTo = new SparseBitVector<>;
1872 N->PointedToBy = new SparseBitVector<>;
1873 // Reset our labels
1874 }
1875 VSSCCRep[i] = i;
1876 N->PointerEquivLabel = 0;
1877 }
1878 HU();
1879#undef DEBUG_TYPE
1880#define DEBUG_TYPE "anders-aa-labels"
1881 DEBUG(PrintLabels());
1882#undef DEBUG_TYPE
1883#define DEBUG_TYPE "anders-aa"
1884 RewriteConstraints();
1885 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1886 if (FindNode(i) == i) {
1887 Node *N = &GraphNodes[i];
1888 delete N->PointsTo;
1889 delete N->PredEdges;
1890 delete N->ImplicitPredEdges;
1891 delete N->PointedToBy;
1892 }
1893 }
1894 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
1895 DOUT << "Finished constraint optimization\n";
1896 FirstRefNode = 0;
1897 FirstAdrNode = 0;
1898}
1899
1900/// Unite pointer but not location equivalent variables, now that the constraint
1901/// graph is built.
1902void Andersens::UnitePointerEquivalences() {
1903 DOUT << "Uniting remaining pointer equivalences\n";
1904 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1905 if (GraphNodes[i].AddressTaken && GraphNodes[i].NodeRep == SelfRep) {
1906 unsigned Label = GraphNodes[i].PointerEquivLabel;
1907
1908 if (Label && PENLEClass2Node[Label] != -1)
1909 UniteNodes(i, PENLEClass2Node[Label]);
1910 }
1911 }
1912 DOUT << "Finished remaining pointer equivalences\n";
1913 PENLEClass2Node.clear();
1914}
1915
1916/// Create the constraint graph used for solving points-to analysis.
1917///
Daniel Berlinaad15882007-09-16 21:45:02 +00001918void Andersens::CreateConstraintGraph() {
1919 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1920 Constraint &C = Constraints[i];
1921 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1922 if (C.Type == Constraint::AddressOf)
1923 GraphNodes[C.Dest].PointsTo->set(C.Src);
1924 else if (C.Type == Constraint::Load)
1925 GraphNodes[C.Src].Constraints.push_back(C);
1926 else if (C.Type == Constraint::Store)
1927 GraphNodes[C.Dest].Constraints.push_back(C);
1928 else if (C.Offset != 0)
1929 GraphNodes[C.Src].Constraints.push_back(C);
1930 else
1931 GraphNodes[C.Src].Edges->set(C.Dest);
1932 }
1933}
1934
1935// Perform cycle detection, DFS, and RPO finding.
1936void Andersens::QueryNode(unsigned Node) {
1937 assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1938 unsigned OurDFS = ++DFSNumber;
1939 SparseBitVector<> ToErase;
1940 SparseBitVector<> NewEdges;
1941 Node2DFS[Node] = OurDFS;
1942
1943 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1944 bi != GraphNodes[Node].Edges->end();
1945 ++bi) {
1946 unsigned RepNode = FindNode(*bi);
1947 // If we are going to add an edge to repnode, we have no need for the edge
1948 // to e anymore.
1949 if (RepNode != *bi && NewEdges.test(RepNode)){
1950 ToErase.set(*bi);
1951 continue;
1952 }
1953
1954 // Continue about our DFS.
1955 if (!Node2Deleted[RepNode]){
1956 if (Node2DFS[RepNode] == 0) {
1957 QueryNode(RepNode);
1958 // May have been changed by query
1959 RepNode = FindNode(RepNode);
1960 }
1961 if (Node2DFS[RepNode] < Node2DFS[Node])
1962 Node2DFS[Node] = Node2DFS[RepNode];
1963 }
1964 // We may have just discovered that e belongs to a cycle, in which case we
1965 // can also erase it.
1966 if (RepNode != *bi) {
1967 ToErase.set(*bi);
1968 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001969 }
1970 }
1971
Daniel Berlinaad15882007-09-16 21:45:02 +00001972 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
1973 GraphNodes[Node].Edges |= NewEdges;
1974
1975 // If this node is a root of a non-trivial SCC, place it on our worklist to be
1976 // processed
1977 if (OurDFS == Node2DFS[Node]) {
1978 bool Changed = false;
1979 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
1980 Node = UniteNodes(Node, FindNode(SCCStack.top()));
1981
1982 SCCStack.pop();
1983 Changed = true;
1984 }
1985 Node2Deleted[Node] = true;
1986 RPONumber++;
1987
1988 Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
1989 Node2Topo[Node] = GraphNodes.size() - RPONumber;
1990 if (Changed)
1991 GraphNodes[Node].Changed = true;
1992 } else {
1993 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001994 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001995}
1996
1997
1998/// SolveConstraints - This stage iteratively processes the constraints list
1999/// propagating constraints (adding edges to the Nodes in the points-to graph)
2000/// until a fixed point is reached.
2001///
2002void Andersens::SolveConstraints() {
2003 bool Changed = true;
2004 unsigned Iteration = 0;
Daniel Berlinaad15882007-09-16 21:45:02 +00002005
Daniel Berlind81ccc22007-09-24 19:45:49 +00002006 OptimizeConstraints();
2007#undef DEBUG_TYPE
2008#define DEBUG_TYPE "anders-aa-constraints"
2009 DEBUG(PrintConstraints());
2010#undef DEBUG_TYPE
2011#define DEBUG_TYPE "anders-aa"
2012
Daniel Berlinaad15882007-09-16 21:45:02 +00002013 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2014 Node *N = &GraphNodes[i];
2015 N->PointsTo = new SparseBitVector<>;
2016 N->OldPointsTo = new SparseBitVector<>;
2017 N->Edges = new SparseBitVector<>;
2018 }
2019 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002020 UnitePointerEquivalences();
2021 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlinaad15882007-09-16 21:45:02 +00002022 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2023 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002024 Node2DFS.clear();
2025 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002026 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2027 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2028 DFSNumber = 0;
2029 RPONumber = 0;
2030 // Order graph and mark starting nodes as changed.
2031 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2032 unsigned N = FindNode(i);
2033 Node *INode = &GraphNodes[i];
2034 if (Node2DFS[N] == 0) {
2035 QueryNode(N);
2036 // Mark as changed if it's a representation and can contribute to the
2037 // calculation right now.
2038 if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
2039 && (!INode->Edges->empty() || !INode->Constraints.empty()))
2040 INode->Changed = true;
2041 }
2042 }
2043
2044 do {
Daniel Berlinc6d93982007-09-16 23:59:53 +00002045 Changed = false;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002046 ++NumIters;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002047 DOUT << "Starting iteration #" << Iteration++ << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002048 // TODO: In the microoptimization category, we could just make Topo2Node
2049 // a fast map and thus only contain the visited nodes.
2050 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2051 unsigned CurrNodeIndex = Topo2Node[i];
2052 Node *CurrNode;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002053
Daniel Berlinaad15882007-09-16 21:45:02 +00002054 // We may not revisit all nodes on every iteration
2055 if (CurrNodeIndex == Unvisited)
2056 continue;
2057 CurrNode = &GraphNodes[CurrNodeIndex];
2058 // See if this is a node we need to process on this iteration
2059 if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
2060 continue;
2061 CurrNode->Changed = false;
2062
2063 // Figure out the changed points to bits
2064 SparseBitVector<> CurrPointsTo;
2065 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2066 CurrNode->OldPointsTo);
2067 if (CurrPointsTo.empty()){
2068 continue;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002069 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002070 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002071
Daniel Berlinaad15882007-09-16 21:45:02 +00002072 /* Now process the constraints for this node. */
2073 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2074 li != CurrNode->Constraints.end(); ) {
2075 li->Src = FindNode(li->Src);
2076 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002077
Daniel Berlinaad15882007-09-16 21:45:02 +00002078 // TODO: We could delete redundant constraints here.
2079 // Src and Dest will be the vars we are going to process.
2080 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002081 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002082 // Load constraints say that every member of our RHS solution has K
2083 // added to it, and that variable gets an edge to LHS. We also union
2084 // RHS+K's solution into the LHS solution.
2085 // Store constraints say that every member of our LHS solution has K
2086 // added to it, and that variable gets an edge from RHS. We also union
2087 // RHS's solution into the LHS+K solution.
2088 unsigned *Src;
2089 unsigned *Dest;
2090 unsigned K = li->Offset;
2091 unsigned CurrMember;
2092 if (li->Type == Constraint::Load) {
2093 Src = &CurrMember;
2094 Dest = &li->Dest;
2095 } else if (li->Type == Constraint::Store) {
2096 Src = &li->Src;
2097 Dest = &CurrMember;
2098 } else {
2099 // TODO Handle offseted copy constraint
2100 li++;
2101 continue;
2102 }
2103 // TODO: hybrid cycle detection would go here, we should check
2104 // if it was a statically detected offline equivalence that
2105 // involves pointers , and if so, remove the redundant constraints.
Chris Lattnere995a2a2004-05-23 21:00:47 +00002106
Daniel Berlinaad15882007-09-16 21:45:02 +00002107 const SparseBitVector<> &Solution = CurrPointsTo;
2108
2109 for (SparseBitVector<>::iterator bi = Solution.begin();
2110 bi != Solution.end();
2111 ++bi) {
2112 CurrMember = *bi;
2113
2114 // Need to increment the member by K since that is where we are
Daniel Berlind81ccc22007-09-24 19:45:49 +00002115 // supposed to copy to/from. Note that in positive weight cycles,
2116 // which occur in address taking of fields, K can go past
2117 // MaxK[CurrMember] elements, even though that is all it could point
2118 // to.
Daniel Berlinaad15882007-09-16 21:45:02 +00002119 if (K > 0 && K > MaxK[CurrMember])
2120 continue;
2121 else
2122 CurrMember = FindNode(CurrMember + K);
2123
2124 // Add an edge to the graph, so we can just do regular bitmap ior next
2125 // time. It may also let us notice a cycle.
Daniel Berlinc6d93982007-09-16 23:59:53 +00002126 if (GraphNodes[*Src].Edges->test_and_set(*Dest)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002127 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
2128 GraphNodes[*Dest].Changed = true;
2129 // If we changed a node we've already processed, we need another
2130 // iteration.
2131 if (Node2Topo[*Dest] <= i)
2132 Changed = true;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002133 }
2134 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002135 }
2136 li++;
2137 }
2138 SparseBitVector<> NewEdges;
2139 SparseBitVector<> ToErase;
2140
2141 // Now all we have left to do is propagate points-to info along the
2142 // edges, erasing the redundant edges.
2143
2144
2145 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2146 bi != CurrNode->Edges->end();
2147 ++bi) {
2148
2149 unsigned DestVar = *bi;
2150 unsigned Rep = FindNode(DestVar);
2151
2152 // If we ended up with this node as our destination, or we've already
2153 // got an edge for the representative, delete the current edge.
2154 if (Rep == CurrNodeIndex ||
2155 (Rep != DestVar && NewEdges.test(Rep))) {
2156 ToErase.set(DestVar);
2157 continue;
2158 }
2159 // Union the points-to sets into the dest
2160 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2161 GraphNodes[Rep].Changed = true;
2162 if (Node2Topo[Rep] <= i)
2163 Changed = true;
2164 }
2165 // If this edge's destination was collapsed, rewrite the edge.
2166 if (Rep != DestVar) {
2167 ToErase.set(DestVar);
2168 NewEdges.set(Rep);
2169 }
2170 }
2171 CurrNode->Edges->intersectWithComplement(ToErase);
2172 CurrNode->Edges |= NewEdges;
2173 }
2174 if (Changed) {
2175 DFSNumber = RPONumber = 0;
2176 Node2Deleted.clear();
2177 Topo2Node.clear();
2178 Node2Topo.clear();
2179 Node2DFS.clear();
2180 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2181 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2182 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2183 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2184 // Rediscover the DFS/Topo ordering, and cycle detect.
2185 for (unsigned j = 0; j < GraphNodes.size(); j++) {
2186 unsigned JRep = FindNode(j);
2187 if (Node2DFS[JRep] == 0)
2188 QueryNode(JRep);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002189 }
2190 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002191
2192 } while (Changed);
2193
2194 Node2Topo.clear();
2195 Topo2Node.clear();
2196 Node2DFS.clear();
2197 Node2Deleted.clear();
2198 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2199 Node *N = &GraphNodes[i];
2200 delete N->OldPointsTo;
2201 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002202 }
2203}
2204
Daniel Berlinaad15882007-09-16 21:45:02 +00002205//===----------------------------------------------------------------------===//
2206// Union-Find
2207//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002208
Daniel Berlinaad15882007-09-16 21:45:02 +00002209// Unite nodes First and Second, returning the one which is now the
2210// representative node. First and Second are indexes into GraphNodes
2211unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
2212 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2213 "Attempting to merge nodes that don't exist");
2214 // TODO: implement union by rank
2215 Node *FirstNode = &GraphNodes[First];
2216 Node *SecondNode = &GraphNodes[Second];
2217
2218 assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
2219 "Trying to unite two non-representative nodes!");
2220 if (First == Second)
2221 return First;
2222
2223 SecondNode->NodeRep = First;
2224 FirstNode->Changed |= SecondNode->Changed;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002225 if (FirstNode->PointsTo && SecondNode->PointsTo)
2226 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2227 if (FirstNode->Edges && SecondNode->Edges)
2228 FirstNode->Edges |= *(SecondNode->Edges);
2229 if (!FirstNode->Constraints.empty() && !SecondNode->Constraints.empty())
2230 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2231 SecondNode->Constraints);
2232 if (FirstNode->OldPointsTo) {
2233 delete FirstNode->OldPointsTo;
2234 FirstNode->OldPointsTo = new SparseBitVector<>;
2235 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002236
2237 // Destroy interesting parts of the merged-from node.
2238 delete SecondNode->OldPointsTo;
2239 delete SecondNode->Edges;
2240 delete SecondNode->PointsTo;
2241 SecondNode->Edges = NULL;
2242 SecondNode->PointsTo = NULL;
2243 SecondNode->OldPointsTo = NULL;
2244
2245 NumUnified++;
2246 DOUT << "Unified Node ";
2247 DEBUG(PrintNode(FirstNode));
2248 DOUT << " and Node ";
2249 DEBUG(PrintNode(SecondNode));
2250 DOUT << "\n";
2251
2252 // TODO: Handle SDT
2253 return First;
2254}
2255
2256// Find the index into GraphNodes of the node representing Node, performing
2257// path compression along the way
2258unsigned Andersens::FindNode(unsigned NodeIndex) {
2259 assert (NodeIndex < GraphNodes.size()
2260 && "Attempting to find a node that can't exist");
2261 Node *N = &GraphNodes[NodeIndex];
2262 if (N->NodeRep == SelfRep)
2263 return NodeIndex;
2264 else
2265 return (N->NodeRep = FindNode(N->NodeRep));
2266}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002267
2268//===----------------------------------------------------------------------===//
2269// Debugging Output
2270//===----------------------------------------------------------------------===//
2271
2272void Andersens::PrintNode(Node *N) {
2273 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002274 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002275 return;
2276 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002277 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002278 return;
2279 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002280 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002281 return;
2282 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002283 if (!N->getValue()) {
2284 cerr << "artificial" << (intptr_t) N;
2285 return;
2286 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002287
2288 assert(N->getValue() != 0 && "Never set node label!");
2289 Value *V = N->getValue();
2290 if (Function *F = dyn_cast<Function>(V)) {
2291 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002292 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002293 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002294 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002295 } else if (F->getFunctionType()->isVarArg() &&
2296 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002297 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002298 return;
2299 }
2300 }
2301
2302 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002303 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002304 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002305 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002306
2307 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002308 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002309 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002310 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002311
2312 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002313 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002314 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002315}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002316void Andersens::PrintConstraint(const Constraint &C) {
2317 if (C.Type == Constraint::Store) {
2318 cerr << "*";
2319 if (C.Offset != 0)
2320 cerr << "(";
2321 }
2322 PrintNode(&GraphNodes[C.Dest]);
2323 if (C.Type == Constraint::Store && C.Offset != 0)
2324 cerr << " + " << C.Offset << ")";
2325 cerr << " = ";
2326 if (C.Type == Constraint::Load) {
2327 cerr << "*";
2328 if (C.Offset != 0)
2329 cerr << "(";
2330 }
2331 else if (C.Type == Constraint::AddressOf)
2332 cerr << "&";
2333 PrintNode(&GraphNodes[C.Src]);
2334 if (C.Offset != 0 && C.Type != Constraint::Store)
2335 cerr << " + " << C.Offset;
2336 if (C.Type == Constraint::Load && C.Offset != 0)
2337 cerr << ")";
2338 cerr << "\n";
2339}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002340
2341void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002342 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002343
Daniel Berlind81ccc22007-09-24 19:45:49 +00002344 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2345 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002346}
2347
2348void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002349 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002350 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2351 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002352 if (FindNode (i) != i) {
2353 PrintNode(N);
2354 cerr << "\t--> same as ";
2355 PrintNode(&GraphNodes[FindNode(i)]);
2356 cerr << "\n";
2357 } else {
2358 cerr << "[" << (N->PointsTo->count()) << "] ";
2359 PrintNode(N);
2360 cerr << "\t--> ";
2361
2362 bool first = true;
2363 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2364 bi != N->PointsTo->end();
2365 ++bi) {
2366 if (!first)
2367 cerr << ", ";
2368 PrintNode(&GraphNodes[*bi]);
2369 first = false;
2370 }
2371 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002372 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002373 }
2374}