blob: b6cb8f8f15bb9d72306978636265091434409d93 [file] [log] [blame]
Chris Lattnerd28b0d72004-06-25 04:24:22 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattnere995a2a2004-05-23 21:00:47 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattnere995a2a2004-05-23 21:00:47 +00008//===----------------------------------------------------------------------===//
9//
Daniel Berlinaad15882007-09-16 21:45:02 +000010// This file defines an implementation of Andersen's interprocedural alias
11// analysis
Chris Lattnere995a2a2004-05-23 21:00:47 +000012//
13// In pointer analysis terms, this is a subset-based, flow-insensitive,
Daniel Berlinaad15882007-09-16 21:45:02 +000014// field-sensitive, and context-insensitive algorithm pointer algorithm.
Chris Lattnere995a2a2004-05-23 21:00:47 +000015//
16// This algorithm is implemented as three stages:
17// 1. Object identification.
18// 2. Inclusion constraint identification.
Daniel Berlind81ccc22007-09-24 19:45:49 +000019// 3. Offline constraint graph optimization
20// 4. Inclusion constraint solving.
Chris Lattnere995a2a2004-05-23 21:00:47 +000021//
22// The object identification stage identifies all of the memory objects in the
23// program, which includes globals, heap allocated objects, and stack allocated
24// objects.
25//
26// The inclusion constraint identification stage finds all inclusion constraints
27// in the program by scanning the program, looking for pointer assignments and
28// other statements that effect the points-to graph. For a statement like "A =
29// B", this statement is processed to indicate that A can point to anything that
Daniel Berlinaad15882007-09-16 21:45:02 +000030// B can point to. Constraints can handle copies, loads, and stores, and
31// address taking.
Chris Lattnere995a2a2004-05-23 21:00:47 +000032//
Daniel Berline6f04792007-09-24 22:20:45 +000033// The offline constraint graph optimization portion includes offline variable
34// substitution algorithms intended to computer pointer and location
35// equivalences. Pointer equivalences are those pointers that will have the
36// same points-to sets, and location equivalences are those variables that
37// always appear together in points-to sets.
Daniel Berlind81ccc22007-09-24 19:45:49 +000038//
Chris Lattnere995a2a2004-05-23 21:00:47 +000039// The inclusion constraint solving phase iteratively propagates the inclusion
40// constraints until a fixed point is reached. This is an O(N^3) algorithm.
41//
Daniel Berlinaad15882007-09-16 21:45:02 +000042// Function constraints are handled as if they were structs with X fields.
43// Thus, an access to argument X of function Y is an access to node index
44// getNode(Y) + X. This representation allows handling of indirect calls
Daniel Berlind81ccc22007-09-24 19:45:49 +000045// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlinaad15882007-09-16 21:45:02 +000046// *(Y + 1) = a, *(Y + 2) = b.
47// The return node for a function is always located at getNode(F) +
48// CallReturnPos. The arguments start at getNode(F) + CallArgPos.
Chris Lattnere995a2a2004-05-23 21:00:47 +000049//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000050// Future Improvements:
Daniel Berlind81ccc22007-09-24 19:45:49 +000051// Offline detection of online cycles. Use of BDD's.
Chris Lattnere995a2a2004-05-23 21:00:47 +000052//===----------------------------------------------------------------------===//
53
54#define DEBUG_TYPE "anders-aa"
55#include "llvm/Constants.h"
56#include "llvm/DerivedTypes.h"
57#include "llvm/Instructions.h"
58#include "llvm/Module.h"
59#include "llvm/Pass.h"
Reid Spencerd7d83db2007-02-05 23:42:17 +000060#include "llvm/Support/Compiler.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000061#include "llvm/Support/InstIterator.h"
62#include "llvm/Support/InstVisitor.h"
63#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000064#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/Support/Debug.h"
66#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000067#include "llvm/ADT/SparseBitVector.h"
Daniel Berlind81ccc22007-09-24 19:45:49 +000068#include "llvm/ADT/DenseMap.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000069#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000070#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000071#include <list>
72#include <stack>
73#include <vector>
Chris Lattnere995a2a2004-05-23 21:00:47 +000074
Daniel Berlinaad15882007-09-16 21:45:02 +000075using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000076STATISTIC(NumIters , "Number of iterations to reach convergence");
77STATISTIC(NumConstraints, "Number of constraints");
78STATISTIC(NumNodes , "Number of nodes");
79STATISTIC(NumUnified , "Number of variables unified");
Chris Lattnere995a2a2004-05-23 21:00:47 +000080
Chris Lattner3b27d682006-12-19 22:30:33 +000081namespace {
Daniel Berlinaad15882007-09-16 21:45:02 +000082 const unsigned SelfRep = (unsigned)-1;
83 const unsigned Unvisited = (unsigned)-1;
84 // Position of the function return node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000085 const unsigned CallReturnPos = 1;
Daniel Berlinaad15882007-09-16 21:45:02 +000086 // Position of the function call node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000087 const unsigned CallFirstArgPos = 2;
88
89 struct BitmapKeyInfo {
90 static inline SparseBitVector<> *getEmptyKey() {
91 return reinterpret_cast<SparseBitVector<> *>(-1);
92 }
93 static inline SparseBitVector<> *getTombstoneKey() {
94 return reinterpret_cast<SparseBitVector<> *>(-2);
95 }
96 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
97 return bitmap->getHashValue();
98 }
99 static bool isEqual(const SparseBitVector<> *LHS,
100 const SparseBitVector<> *RHS) {
101 if (LHS == RHS)
102 return true;
103 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
104 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
105 return false;
106
107 return *LHS == *RHS;
108 }
109
110 static bool isPod() { return true; }
111 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000112
Reid Spencerd7d83db2007-02-05 23:42:17 +0000113 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
114 private InstVisitor<Andersens> {
Daniel Berlinaad15882007-09-16 21:45:02 +0000115 class Node;
116
117 /// Constraint - Objects of this structure are used to represent the various
118 /// constraints identified by the algorithm. The constraints are 'copy',
119 /// for statements like "A = B", 'load' for statements like "A = *B",
120 /// 'store' for statements like "*A = B", and AddressOf for statements like
121 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
122 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000123 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000124 /// resolvable to A = &C where C = B + K)
125
126 struct Constraint {
127 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
128 unsigned Dest;
129 unsigned Src;
130 unsigned Offset;
131
132 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
133 : Type(Ty), Dest(D), Src(S), Offset(O) {
134 assert(Offset == 0 || Ty != AddressOf &&
135 "Offset is illegal on addressof constraints");
136 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000137
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000138 bool operator==(const Constraint &RHS) const {
139 return RHS.Type == Type
140 && RHS.Dest == Dest
141 && RHS.Src == Src
142 && RHS.Offset == Offset;
143 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000144
145 bool operator!=(const Constraint &RHS) const {
146 return !(*this == RHS);
147 }
148
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000149 bool operator<(const Constraint &RHS) const {
150 if (RHS.Type != Type)
151 return RHS.Type < Type;
152 else if (RHS.Dest != Dest)
153 return RHS.Dest < Dest;
154 else if (RHS.Src != Src)
155 return RHS.Src < Src;
156 return RHS.Offset < Offset;
157 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000158 };
159
Daniel Berlin336c6c02007-09-29 00:50:40 +0000160 struct ConstraintKeyInfo {
161 static inline Constraint getEmptyKey() {
162 return Constraint(Constraint::Copy, ~0UL, ~0UL, ~0UL);
163 }
164 static inline Constraint getTombstoneKey() {
165 return Constraint(Constraint::Copy, ~0UL - 1, ~0UL - 1, ~0UL - 1);
166 }
167 static unsigned getHashValue(const Constraint &C) {
168 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
169 }
170 static bool isEqual(const Constraint &LHS,
171 const Constraint &RHS) {
172 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
173 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
174 }
175 };
176
Daniel Berlind81ccc22007-09-24 19:45:49 +0000177 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000178 // graph. Due to various optimizations, it is not always the case that
179 // there is a mapping from a Node to a Value. In particular, we add
180 // artificial Node's that represent the set of pointed-to variables shared
181 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000182 struct Node {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000183 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000184 SparseBitVector<> *Edges;
185 SparseBitVector<> *PointsTo;
186 SparseBitVector<> *OldPointsTo;
187 bool Changed;
188 std::list<Constraint> Constraints;
189
Daniel Berlind81ccc22007-09-24 19:45:49 +0000190 // Pointer and location equivalence labels
191 unsigned PointerEquivLabel;
192 unsigned LocationEquivLabel;
193 // Predecessor edges, both real and implicit
194 SparseBitVector<> *PredEdges;
195 SparseBitVector<> *ImplicitPredEdges;
196 // Set of nodes that point to us, only use for location equivalence.
197 SparseBitVector<> *PointedToBy;
198 // Number of incoming edges, used during variable substitution to early
199 // free the points-to sets
200 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000201 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000202 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000203 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000204 bool Direct;
205 // True if the node is address taken, *or* it is part of a group of nodes
206 // that must be kept together. This is set to true for functions and
207 // their arg nodes, which must be kept at the same position relative to
208 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000209 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000210
Daniel Berlind81ccc22007-09-24 19:45:49 +0000211 // Nodes in cycles (or in equivalence classes) are united together using a
212 // standard union-find representation with path compression. NodeRep
213 // gives the index into GraphNodes for the representative Node.
214 unsigned NodeRep;
215 public:
216
217 Node(bool direct = true) :
218 Val(0), Edges(0), PointsTo(0), OldPointsTo(0), Changed(false),
219 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
220 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
221 StoredInHash(false), Direct(direct), AddressTaken(false),
222 NodeRep(SelfRep) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000223
Chris Lattnere995a2a2004-05-23 21:00:47 +0000224 Node *setValue(Value *V) {
225 assert(Val == 0 && "Value already set for this node!");
226 Val = V;
227 return this;
228 }
229
230 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000231 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000232 Value *getValue() const { return Val; }
233
Chris Lattnere995a2a2004-05-23 21:00:47 +0000234 /// addPointerTo - Add a pointer to the list of pointees of this node,
235 /// returning true if this caused a new pointer to be added, or false if
236 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000237 bool addPointerTo(unsigned Node) {
238 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000239 }
240
241 /// intersects - Return true if the points-to set of this node intersects
242 /// with the points-to set of the specified node.
243 bool intersects(Node *N) const;
244
245 /// intersectsIgnoring - Return true if the points-to set of this node
246 /// intersects with the points-to set of the specified node on any nodes
247 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000248 bool intersectsIgnoring(Node *N, unsigned) const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000249 };
250
251 /// GraphNodes - This vector is populated as part of the object
252 /// identification stage of the analysis, which populates this vector with a
253 /// node for each memory object and fills in the ValueNodes map.
254 std::vector<Node> GraphNodes;
255
256 /// ValueNodes - This map indicates the Node that a particular Value* is
257 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000258 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000259
260 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000261 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000262 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000263
264 /// ReturnNodes - This map contains an entry for each function in the
265 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000266 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000267
268 /// VarargNodes - This map contains the entry used to represent all pointers
269 /// passed through the varargs portion of a function call for a particular
270 /// function. An entry is not present in this map for functions that do not
271 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000272 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000273
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000274
Chris Lattnere995a2a2004-05-23 21:00:47 +0000275 /// Constraints - This vector contains a list of all of the constraints
276 /// identified by the program.
277 std::vector<Constraint> Constraints;
278
Daniel Berlind81ccc22007-09-24 19:45:49 +0000279 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000280 // this is equivalent to the number of arguments + CallFirstArgPos)
281 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000282
283 /// This enum defines the GraphNodes indices that correspond to important
284 /// fixed sets.
285 enum {
286 UniversalSet = 0,
287 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000288 NullObject = 2,
289 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000290 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000291 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000292 std::stack<unsigned> SCCStack;
293 // Topological Index -> Graph node
294 std::vector<unsigned> Topo2Node;
295 // Graph Node -> Topological Index;
296 std::vector<unsigned> Node2Topo;
297 // Map from Graph Node to DFS number
298 std::vector<unsigned> Node2DFS;
299 // Map from Graph Node to Deleted from graph.
300 std::vector<bool> Node2Deleted;
301 // Current DFS and RPO numbers
302 unsigned DFSNumber;
303 unsigned RPONumber;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000304
Daniel Berlind81ccc22007-09-24 19:45:49 +0000305 // Offline variable substitution related things
306
307 // Temporary rep storage, used because we can't collapse SCC's in the
308 // predecessor graph by uniting the variables permanently, we can only do so
309 // for the successor graph.
310 std::vector<unsigned> VSSCCRep;
311 // Mapping from node to whether we have visited it during SCC finding yet.
312 std::vector<bool> Node2Visited;
313 // During variable substitution, we create unknowns to represent the unknown
314 // value that is a dereference of a variable. These nodes are known as
315 // "ref" nodes (since they represent the value of dereferences).
316 unsigned FirstRefNode;
317 // During HVN, we create represent address taken nodes as if they were
318 // unknown (since HVN, unlike HU, does not evaluate unions).
319 unsigned FirstAdrNode;
320 // Current pointer equivalence class number
321 unsigned PEClass;
322 // Mapping from points-to sets to equivalence classes
323 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
324 BitVectorMap Set2PEClass;
325 // Mapping from pointer equivalences to the representative node. -1 if we
326 // have no representative node for this pointer equivalence class yet.
327 std::vector<int> PEClass2Node;
328 // Mapping from pointer equivalences to representative node. This includes
329 // pointer equivalent but not location equivalent variables. -1 if we have
330 // no representative node for this pointer equivalence class yet.
331 std::vector<int> PENLEClass2Node;
332
Chris Lattnere995a2a2004-05-23 21:00:47 +0000333 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000334 static char ID;
335 Andersens() : ModulePass((intptr_t)&ID) {}
336
Chris Lattnerb12914b2004-09-20 04:48:05 +0000337 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000338 InitializeAliasAnalysis(this);
339 IdentifyObjects(M);
340 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000341#undef DEBUG_TYPE
342#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000343 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000344#undef DEBUG_TYPE
345#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000346 SolveConstraints();
347 DEBUG(PrintPointsToGraph());
348
349 // Free the constraints list, as we don't need it to respond to alias
350 // requests.
351 ObjectNodes.clear();
352 ReturnNodes.clear();
353 VarargNodes.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000354 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000355 return false;
356 }
357
358 void releaseMemory() {
359 // FIXME: Until we have transitively required passes working correctly,
360 // this cannot be enabled! Otherwise, using -count-aa with the pass
361 // causes memory to be freed too early. :(
362#if 0
363 // The memory objects and ValueNodes data structures at the only ones that
364 // are still live after construction.
365 std::vector<Node>().swap(GraphNodes);
366 ValueNodes.clear();
367#endif
368 }
369
370 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
371 AliasAnalysis::getAnalysisUsage(AU);
372 AU.setPreservesAll(); // Does not transform code
373 }
374
375 //------------------------------------------------
376 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000377 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000378 AliasResult alias(const Value *V1, unsigned V1Size,
379 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000380 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
381 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000382 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
383 bool pointsToConstantMemory(const Value *P);
384
385 virtual void deleteValue(Value *V) {
386 ValueNodes.erase(V);
387 getAnalysis<AliasAnalysis>().deleteValue(V);
388 }
389
390 virtual void copyValue(Value *From, Value *To) {
391 ValueNodes[To] = ValueNodes[From];
392 getAnalysis<AliasAnalysis>().copyValue(From, To);
393 }
394
395 private:
396 /// getNode - Return the node corresponding to the specified pointer scalar.
397 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000398 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000399 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000400 if (!isa<GlobalValue>(C))
401 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000402
Daniel Berlind81ccc22007-09-24 19:45:49 +0000403 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000404 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000405#ifndef NDEBUG
406 V->dump();
407#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000408 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000409 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000410 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000411 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000412
Chris Lattnere995a2a2004-05-23 21:00:47 +0000413 /// getObject - Return the node corresponding to the memory object for the
414 /// specified global or allocation instruction.
Daniel Berlinaad15882007-09-16 21:45:02 +0000415 unsigned getObject(Value *V) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000416 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000417 assert(I != ObjectNodes.end() &&
418 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000419 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000420 }
421
422 /// getReturnNode - Return the node representing the return value for the
423 /// specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000424 unsigned getReturnNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000425 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000426 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000427 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000428 }
429
430 /// getVarargNode - Return the node representing the variable arguments
431 /// formal for the specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000432 unsigned getVarargNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000433 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000434 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000435 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000436 }
437
438 /// getNodeValue - Get the node for the specified LLVM value and set the
439 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000440 unsigned getNodeValue(Value &V) {
441 unsigned Index = getNode(&V);
442 GraphNodes[Index].setValue(&V);
443 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000444 }
445
Daniel Berlinaad15882007-09-16 21:45:02 +0000446 unsigned UniteNodes(unsigned First, unsigned Second);
447 unsigned FindNode(unsigned Node);
448
Chris Lattnere995a2a2004-05-23 21:00:47 +0000449 void IdentifyObjects(Module &M);
450 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000451 bool AnalyzeUsesOfFunction(Value *);
452 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000453 void OptimizeConstraints();
454 unsigned FindEquivalentNode(unsigned, unsigned);
455 void ClumpAddressTaken();
456 void RewriteConstraints();
457 void HU();
458 void HVN();
459 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000460 void SolveConstraints();
Daniel Berlinaad15882007-09-16 21:45:02 +0000461 void QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000462 void Condense(unsigned Node);
463 void HUValNum(unsigned Node);
464 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000465 unsigned getNodeForConstantPointer(Constant *C);
466 unsigned getNodeForConstantPointerTarget(Constant *C);
467 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000468
Chris Lattnere995a2a2004-05-23 21:00:47 +0000469 void AddConstraintsForNonInternalLinkage(Function *F);
470 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000471 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000472
473
474 void PrintNode(Node *N);
475 void PrintConstraints();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000476 void PrintConstraint(const Constraint &);
477 void PrintLabels();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000478 void PrintPointsToGraph();
479
480 //===------------------------------------------------------------------===//
481 // Instruction visitation methods for adding constraints
482 //
483 friend class InstVisitor<Andersens>;
484 void visitReturnInst(ReturnInst &RI);
485 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
486 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
487 void visitCallSite(CallSite CS);
488 void visitAllocationInst(AllocationInst &AI);
489 void visitLoadInst(LoadInst &LI);
490 void visitStoreInst(StoreInst &SI);
491 void visitGetElementPtrInst(GetElementPtrInst &GEP);
492 void visitPHINode(PHINode &PN);
493 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000494 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
495 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000496 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000497 void visitVAArg(VAArgInst &I);
498 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000499
Chris Lattnere995a2a2004-05-23 21:00:47 +0000500 };
501
Devang Patel19974732007-05-03 01:11:54 +0000502 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000503 RegisterPass<Andersens> X("anders-aa",
504 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000505 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000506}
507
Jeff Cohen534927d2005-01-08 22:01:16 +0000508ModulePass *llvm::createAndersensPass() { return new Andersens(); }
509
Chris Lattnere995a2a2004-05-23 21:00:47 +0000510//===----------------------------------------------------------------------===//
511// AliasAnalysis Interface Implementation
512//===----------------------------------------------------------------------===//
513
514AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
515 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000516 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
517 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000518
519 // Check to see if the two pointers are known to not alias. They don't alias
520 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000521 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000522 return NoAlias;
523
524 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
525}
526
Chris Lattnerf392c642005-03-28 06:21:17 +0000527AliasAnalysis::ModRefResult
528Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
529 // The only thing useful that we can contribute for mod/ref information is
530 // when calling external function calls: if we know that memory never escapes
531 // from the program, it cannot be modified by an external call.
532 //
533 // NOTE: This is not really safe, at least not when the entire program is not
534 // available. The deal is that the external function could call back into the
535 // program and modify stuff. We ignore this technical niggle for now. This
536 // is, after all, a "research quality" implementation of Andersen's analysis.
537 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000538 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000539 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000540
Daniel Berlinaad15882007-09-16 21:45:02 +0000541 if (N1->PointsTo->empty())
542 return NoModRef;
Chris Lattnerf392c642005-03-28 06:21:17 +0000543
Daniel Berlinaad15882007-09-16 21:45:02 +0000544 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000545 return NoModRef; // P doesn't point to the universal set.
546 }
547
548 return AliasAnalysis::getModRefInfo(CS, P, Size);
549}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000550
Reid Spencer3a9ec242006-08-28 01:02:49 +0000551AliasAnalysis::ModRefResult
552Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
553 return AliasAnalysis::getModRefInfo(CS1,CS2);
554}
555
Chris Lattnere995a2a2004-05-23 21:00:47 +0000556/// getMustAlias - We can provide must alias information if we know that a
557/// pointer can only point to a specific function or the null pointer.
558/// Unfortunately we cannot determine must-alias information for global
559/// variables or any other memory memory objects because we do not track whether
560/// a pointer points to the beginning of an object or a field of it.
561void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000562 Node *N = &GraphNodes[FindNode(getNode(P))];
563 if (N->PointsTo->count() == 1) {
564 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
565 // If a function is the only object in the points-to set, then it must be
566 // the destination. Note that we can't handle global variables here,
567 // because we don't know if the pointer is actually pointing to a field of
568 // the global or to the beginning of it.
569 if (Value *V = Pointee->getValue()) {
570 if (Function *F = dyn_cast<Function>(V))
571 RetVals.push_back(F);
572 } else {
573 // If the object in the points-to set is the null object, then the null
574 // pointer is a must alias.
575 if (Pointee == &GraphNodes[NullObject])
576 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000577 }
578 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000579 AliasAnalysis::getMustAliases(P, RetVals);
580}
581
582/// pointsToConstantMemory - If we can determine that this pointer only points
583/// to constant memory, return true. In practice, this means that if the
584/// pointer can only point to constant globals, functions, or the null pointer,
585/// return true.
586///
587bool Andersens::pointsToConstantMemory(const Value *P) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000588 Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
589 unsigned i;
590
591 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
592 bi != N->PointsTo->end();
593 ++bi) {
594 i = *bi;
595 Node *Pointee = &GraphNodes[i];
596 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000597 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
598 !cast<GlobalVariable>(V)->isConstant()))
599 return AliasAnalysis::pointsToConstantMemory(P);
600 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000601 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000602 return AliasAnalysis::pointsToConstantMemory(P);
603 }
604 }
605
606 return true;
607}
608
609//===----------------------------------------------------------------------===//
610// Object Identification Phase
611//===----------------------------------------------------------------------===//
612
613/// IdentifyObjects - This stage scans the program, adding an entry to the
614/// GraphNodes list for each memory object in the program (global stack or
615/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
616///
617void Andersens::IdentifyObjects(Module &M) {
618 unsigned NumObjects = 0;
619
620 // Object #0 is always the universal set: the object that we don't know
621 // anything about.
622 assert(NumObjects == UniversalSet && "Something changed!");
623 ++NumObjects;
624
625 // Object #1 always represents the null pointer.
626 assert(NumObjects == NullPtr && "Something changed!");
627 ++NumObjects;
628
629 // Object #2 always represents the null object (the object pointed to by null)
630 assert(NumObjects == NullObject && "Something changed!");
631 ++NumObjects;
632
633 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000634 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
635 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000636 ObjectNodes[I] = NumObjects++;
637 ValueNodes[I] = NumObjects++;
638 }
639
640 // Add nodes for all of the functions and the instructions inside of them.
641 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
642 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000643 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000644 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000645 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
646 ReturnNodes[F] = NumObjects++;
647 if (F->getFunctionType()->isVarArg())
648 VarargNodes[F] = NumObjects++;
649
Daniel Berlinaad15882007-09-16 21:45:02 +0000650
Chris Lattnere995a2a2004-05-23 21:00:47 +0000651 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000652 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
653 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000654 {
655 if (isa<PointerType>(I->getType()))
656 ValueNodes[I] = NumObjects++;
657 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000658 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000659
660 // Scan the function body, creating a memory object for each heap/stack
661 // allocation in the body of the function and a node to represent all
662 // pointer values defined by instructions and used as operands.
663 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
664 // If this is an heap or stack allocation, create a node for the memory
665 // object.
666 if (isa<PointerType>(II->getType())) {
667 ValueNodes[&*II] = NumObjects++;
668 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
669 ObjectNodes[AI] = NumObjects++;
670 }
671 }
672 }
673
674 // Now that we know how many objects to create, make them all now!
675 GraphNodes.resize(NumObjects);
676 NumNodes += NumObjects;
677}
678
679//===----------------------------------------------------------------------===//
680// Constraint Identification Phase
681//===----------------------------------------------------------------------===//
682
683/// getNodeForConstantPointer - Return the node corresponding to the constant
684/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000685unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000686 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
687
Chris Lattner267a1b02005-03-27 18:58:23 +0000688 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000689 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000690 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
691 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000692 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
693 switch (CE->getOpcode()) {
694 case Instruction::GetElementPtr:
695 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000696 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000697 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000698 case Instruction::BitCast:
699 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000700 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000701 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000702 assert(0);
703 }
704 } else {
705 assert(0 && "Unknown constant pointer!");
706 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000707 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000708}
709
710/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
711/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000712unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000713 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
714
715 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000716 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000717 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
718 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000719 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
720 switch (CE->getOpcode()) {
721 case Instruction::GetElementPtr:
722 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000723 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000724 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000725 case Instruction::BitCast:
726 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000727 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000728 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000729 assert(0);
730 }
731 } else {
732 assert(0 && "Unknown constant pointer!");
733 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000734 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000735}
736
737/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
738/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000739void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
740 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000741 if (C->getType()->isFirstClassType()) {
742 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000743 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
744 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000745 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000746 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
747 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000748 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000749 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000750 // If this is an array or struct, include constraints for each element.
751 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
752 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000753 AddGlobalInitializerConstraints(NodeIndex,
754 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000755 }
756}
757
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000758/// AddConstraintsForNonInternalLinkage - If this function does not have
759/// internal linkage, realize that we can't trust anything passed into or
760/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000761void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000762 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000763 if (isa<PointerType>(I->getType()))
764 // If this is an argument of an externally accessible function, the
765 // incoming pointer might point to anything.
766 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000767 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000768}
769
Chris Lattner8a446432005-03-29 06:09:07 +0000770/// AddConstraintsForCall - If this is a call to a "known" function, add the
771/// constraints and return true. If this is a call to an unknown function,
772/// return false.
773bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000774 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000775
776 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000777 if (F->getName() == "atoi" || F->getName() == "atof" ||
778 F->getName() == "atol" || F->getName() == "atoll" ||
779 F->getName() == "remove" || F->getName() == "unlink" ||
780 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000781 F->getName() == "llvm.memset.i32" ||
782 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000783 F->getName() == "strcmp" || F->getName() == "strncmp" ||
784 F->getName() == "execl" || F->getName() == "execlp" ||
785 F->getName() == "execle" || F->getName() == "execv" ||
786 F->getName() == "execvp" || F->getName() == "chmod" ||
787 F->getName() == "puts" || F->getName() == "write" ||
788 F->getName() == "open" || F->getName() == "create" ||
789 F->getName() == "truncate" || F->getName() == "chdir" ||
790 F->getName() == "mkdir" || F->getName() == "rmdir" ||
791 F->getName() == "read" || F->getName() == "pipe" ||
792 F->getName() == "wait" || F->getName() == "time" ||
793 F->getName() == "stat" || F->getName() == "fstat" ||
794 F->getName() == "lstat" || F->getName() == "strtod" ||
795 F->getName() == "strtof" || F->getName() == "strtold" ||
796 F->getName() == "fopen" || F->getName() == "fdopen" ||
797 F->getName() == "freopen" ||
798 F->getName() == "fflush" || F->getName() == "feof" ||
799 F->getName() == "fileno" || F->getName() == "clearerr" ||
800 F->getName() == "rewind" || F->getName() == "ftell" ||
801 F->getName() == "ferror" || F->getName() == "fgetc" ||
802 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
803 F->getName() == "fwrite" || F->getName() == "fread" ||
804 F->getName() == "fgets" || F->getName() == "ungetc" ||
805 F->getName() == "fputc" ||
806 F->getName() == "fputs" || F->getName() == "putc" ||
807 F->getName() == "ftell" || F->getName() == "rewind" ||
808 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
809 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
810 F->getName() == "printf" || F->getName() == "fprintf" ||
811 F->getName() == "sprintf" || F->getName() == "vprintf" ||
812 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
813 F->getName() == "scanf" || F->getName() == "fscanf" ||
814 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
815 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000816 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000817
Chris Lattner175b9632005-03-29 20:36:05 +0000818
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000819 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000820 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000821 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000822 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000823
824 // *Dest = *Src, which requires an artificial graph node to represent the
825 // constraint. It is broken up into *Dest = temp, temp = *Src
826 unsigned FirstArg = getNode(CS.getArgument(0));
827 unsigned SecondArg = getNode(CS.getArgument(1));
828 unsigned TempArg = GraphNodes.size();
829 GraphNodes.push_back(Node());
830 Constraints.push_back(Constraint(Constraint::Store,
831 FirstArg, TempArg));
832 Constraints.push_back(Constraint(Constraint::Load,
833 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000834 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000835 }
836
Chris Lattner77b50562005-03-29 20:04:24 +0000837 // Result = Arg0
838 if (F->getName() == "realloc" || F->getName() == "strchr" ||
839 F->getName() == "strrchr" || F->getName() == "strstr" ||
840 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000841 Constraints.push_back(Constraint(Constraint::Copy,
842 getNode(CS.getInstruction()),
843 getNode(CS.getArgument(0))));
844 return true;
845 }
846
847 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000848}
849
850
Chris Lattnere995a2a2004-05-23 21:00:47 +0000851
Daniel Berlinaad15882007-09-16 21:45:02 +0000852/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
853/// If this is used by anything complex (i.e., the address escapes), return
854/// true.
855bool Andersens::AnalyzeUsesOfFunction(Value *V) {
856
857 if (!isa<PointerType>(V->getType())) return true;
858
859 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
860 if (dyn_cast<LoadInst>(*UI)) {
861 return false;
862 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
863 if (V == SI->getOperand(1)) {
864 return false;
865 } else if (SI->getOperand(1)) {
866 return true; // Storing the pointer
867 }
868 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
869 if (AnalyzeUsesOfFunction(GEP)) return true;
870 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
871 // Make sure that this is just the function being called, not that it is
872 // passing into the function.
873 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
874 if (CI->getOperand(i) == V) return true;
875 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
876 // Make sure that this is just the function being called, not that it is
877 // passing into the function.
878 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
879 if (II->getOperand(i) == V) return true;
880 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
881 if (CE->getOpcode() == Instruction::GetElementPtr ||
882 CE->getOpcode() == Instruction::BitCast) {
883 if (AnalyzeUsesOfFunction(CE))
884 return true;
885 } else {
886 return true;
887 }
888 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
889 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
890 return true; // Allow comparison against null.
891 } else if (dyn_cast<FreeInst>(*UI)) {
892 return false;
893 } else {
894 return true;
895 }
896 return false;
897}
898
Chris Lattnere995a2a2004-05-23 21:00:47 +0000899/// CollectConstraints - This stage scans the program, adding a constraint to
900/// the Constraints list for each instruction in the program that induces a
901/// constraint, and setting up the initial points-to graph.
902///
903void Andersens::CollectConstraints(Module &M) {
904 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000905 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
906 UniversalSet));
907 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
908 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000909
910 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000911 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000912
913 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000914 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
915 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000916 // Associate the address of the global object as pointing to the memory for
917 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +0000918 unsigned ObjectIndex = getObject(I);
919 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000920 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000921 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
922 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000923
924 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000925 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +0000926 } else {
927 // If it doesn't have an initializer (i.e. it's defined in another
928 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +0000929 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
930 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000931 }
932 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000933
Chris Lattnere995a2a2004-05-23 21:00:47 +0000934 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000935 // Set up the return value node.
936 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000937 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000938 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +0000939 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000940
941 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000942 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
943 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000944 if (isa<PointerType>(I->getType()))
945 getNodeValue(*I);
946
Daniel Berlinaad15882007-09-16 21:45:02 +0000947 // At some point we should just add constraints for the escaping functions
948 // at solve time, but this slows down solving. For now, we simply mark
949 // address taken functions as escaping and treat them as external.
950 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000951 AddConstraintsForNonInternalLinkage(F);
952
Reid Spencer5cbf9852007-01-30 20:08:39 +0000953 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000954 // Scan the function body, creating a memory object for each heap/stack
955 // allocation in the body of the function and a node to represent all
956 // pointer values defined by instructions and used as operands.
957 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000958 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000959 // External functions that return pointers return the universal set.
960 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
961 Constraints.push_back(Constraint(Constraint::Copy,
962 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000963 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000964
965 // Any pointers that are passed into the function have the universal set
966 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000967 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
968 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000969 if (isa<PointerType>(I->getType())) {
970 // Pointers passed into external functions could have anything stored
971 // through them.
972 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000973 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000974 // Memory objects passed into external function calls can have the
975 // universal set point to them.
976 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +0000977 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +0000978 getNode(I)));
979 }
980
981 // If this is an external varargs function, it can also store pointers
982 // into any pointers passed through the varargs section.
983 if (F->getFunctionType()->isVarArg())
984 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000985 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000986 }
987 }
988 NumConstraints += Constraints.size();
989}
990
991
992void Andersens::visitInstruction(Instruction &I) {
993#ifdef NDEBUG
994 return; // This function is just a big assert.
995#endif
996 if (isa<BinaryOperator>(I))
997 return;
998 // Most instructions don't have any effect on pointer values.
999 switch (I.getOpcode()) {
1000 case Instruction::Br:
1001 case Instruction::Switch:
1002 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001003 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001004 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001005 case Instruction::ICmp:
1006 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001007 return;
1008 default:
1009 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001010 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001011 abort();
1012 }
1013}
1014
1015void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001016 unsigned ObjectIndex = getObject(&AI);
1017 GraphNodes[ObjectIndex].setValue(&AI);
1018 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1019 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001020}
1021
1022void Andersens::visitReturnInst(ReturnInst &RI) {
1023 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1024 // return V --> <Copy/retval{F}/v>
1025 Constraints.push_back(Constraint(Constraint::Copy,
1026 getReturnNode(RI.getParent()->getParent()),
1027 getNode(RI.getOperand(0))));
1028}
1029
1030void Andersens::visitLoadInst(LoadInst &LI) {
1031 if (isa<PointerType>(LI.getType()))
1032 // P1 = load P2 --> <Load/P1/P2>
1033 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1034 getNode(LI.getOperand(0))));
1035}
1036
1037void Andersens::visitStoreInst(StoreInst &SI) {
1038 if (isa<PointerType>(SI.getOperand(0)->getType()))
1039 // store P1, P2 --> <Store/P2/P1>
1040 Constraints.push_back(Constraint(Constraint::Store,
1041 getNode(SI.getOperand(1)),
1042 getNode(SI.getOperand(0))));
1043}
1044
1045void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1046 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1047 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1048 getNode(GEP.getOperand(0))));
1049}
1050
1051void Andersens::visitPHINode(PHINode &PN) {
1052 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001053 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001054 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1055 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1056 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1057 getNode(PN.getIncomingValue(i))));
1058 }
1059}
1060
1061void Andersens::visitCastInst(CastInst &CI) {
1062 Value *Op = CI.getOperand(0);
1063 if (isa<PointerType>(CI.getType())) {
1064 if (isa<PointerType>(Op->getType())) {
1065 // P1 = cast P2 --> <Copy/P1/P2>
1066 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1067 getNode(CI.getOperand(0))));
1068 } else {
1069 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001070#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001071 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001072 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001073#else
1074 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001075#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001076 }
1077 } else if (isa<PointerType>(Op->getType())) {
1078 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001079#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001080 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001081 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001082 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001083#else
1084 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001085#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001086 }
1087}
1088
1089void Andersens::visitSelectInst(SelectInst &SI) {
1090 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001091 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001092 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1093 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1094 getNode(SI.getOperand(1))));
1095 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1096 getNode(SI.getOperand(2))));
1097 }
1098}
1099
Chris Lattnere995a2a2004-05-23 21:00:47 +00001100void Andersens::visitVAArg(VAArgInst &I) {
1101 assert(0 && "vaarg not handled yet!");
1102}
1103
1104/// AddConstraintsForCall - Add constraints for a call with actual arguments
1105/// specified by CS to the function specified by F. Note that the types of
1106/// arguments might not match up in the case where this is an indirect call and
1107/// the function pointer has been casted. If this is the case, do something
1108/// reasonable.
1109void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001110 Value *CallValue = CS.getCalledValue();
1111 bool IsDeref = F == NULL;
1112
1113 // If this is a call to an external function, try to handle it directly to get
1114 // some taste of context sensitivity.
1115 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001116 return;
1117
Chris Lattnere995a2a2004-05-23 21:00:47 +00001118 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001119 unsigned CSN = getNode(CS.getInstruction());
1120 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1121 if (IsDeref)
1122 Constraints.push_back(Constraint(Constraint::Load, CSN,
1123 getNode(CallValue), CallReturnPos));
1124 else
1125 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1126 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001127 } else {
1128 // If the function returns a non-pointer value, handle this just like we
1129 // treat a nonpointer cast to pointer.
1130 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001131 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001132 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001133 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001134 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001135 UniversalSet,
1136 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001137 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001138
Chris Lattnere995a2a2004-05-23 21:00:47 +00001139 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinaad15882007-09-16 21:45:02 +00001140 if (F) {
1141 // Direct Call
1142 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1143 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1144 if (isa<PointerType>(AI->getType())) {
1145 if (isa<PointerType>((*ArgI)->getType())) {
1146 // Copy the actual argument into the formal argument.
1147 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1148 getNode(*ArgI)));
1149 } else {
1150 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1151 UniversalSet));
1152 }
1153 } else if (isa<PointerType>((*ArgI)->getType())) {
1154 Constraints.push_back(Constraint(Constraint::Copy,
1155 UniversalSet,
1156 getNode(*ArgI)));
1157 }
1158 } else {
1159 //Indirect Call
1160 unsigned ArgPos = CallFirstArgPos;
1161 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001162 if (isa<PointerType>((*ArgI)->getType())) {
1163 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001164 Constraints.push_back(Constraint(Constraint::Store,
1165 getNode(CallValue),
1166 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001167 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001168 Constraints.push_back(Constraint(Constraint::Store,
1169 getNode (CallValue),
1170 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001171 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001172 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001173 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001174 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001175 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001176 for (; ArgI != ArgE; ++ArgI)
1177 if (isa<PointerType>((*ArgI)->getType()))
1178 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1179 getNode(*ArgI)));
1180 // If more arguments are passed in than we track, just drop them on the floor.
1181}
1182
1183void Andersens::visitCallSite(CallSite CS) {
1184 if (isa<PointerType>(CS.getType()))
1185 getNodeValue(*CS.getInstruction());
1186
1187 if (Function *F = CS.getCalledFunction()) {
1188 AddConstraintsForCall(CS, F);
1189 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001190 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001191 }
1192}
1193
1194//===----------------------------------------------------------------------===//
1195// Constraint Solving Phase
1196//===----------------------------------------------------------------------===//
1197
1198/// intersects - Return true if the points-to set of this node intersects
1199/// with the points-to set of the specified node.
1200bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001201 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001202}
1203
1204/// intersectsIgnoring - Return true if the points-to set of this node
1205/// intersects with the points-to set of the specified node on any nodes
1206/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001207bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1208 // TODO: If we are only going to call this with the same value for Ignoring,
1209 // we should move the special values out of the points-to bitmap.
1210 bool WeHadIt = PointsTo->test(Ignoring);
1211 bool NHadIt = N->PointsTo->test(Ignoring);
1212 bool Result = false;
1213 if (WeHadIt)
1214 PointsTo->reset(Ignoring);
1215 if (NHadIt)
1216 N->PointsTo->reset(Ignoring);
1217 Result = PointsTo->intersects(N->PointsTo);
1218 if (WeHadIt)
1219 PointsTo->set(Ignoring);
1220 if (NHadIt)
1221 N->PointsTo->set(Ignoring);
1222 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001223}
1224
Daniel Berlind81ccc22007-09-24 19:45:49 +00001225void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001226#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001227 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001228#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001229}
1230
1231
1232/// Clump together address taken variables so that the points-to sets use up
1233/// less space and can be operated on faster.
1234
1235void Andersens::ClumpAddressTaken() {
1236#undef DEBUG_TYPE
1237#define DEBUG_TYPE "anders-aa-renumber"
1238 std::vector<unsigned> Translate;
1239 std::vector<Node> NewGraphNodes;
1240
1241 Translate.resize(GraphNodes.size());
1242 unsigned NewPos = 0;
1243
1244 for (unsigned i = 0; i < Constraints.size(); ++i) {
1245 Constraint &C = Constraints[i];
1246 if (C.Type == Constraint::AddressOf) {
1247 GraphNodes[C.Src].AddressTaken = true;
1248 }
1249 }
1250 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1251 unsigned Pos = NewPos++;
1252 Translate[i] = Pos;
1253 NewGraphNodes.push_back(GraphNodes[i]);
1254 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1255 }
1256
1257 // I believe this ends up being faster than making two vectors and splicing
1258 // them.
1259 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1260 if (GraphNodes[i].AddressTaken) {
1261 unsigned Pos = NewPos++;
1262 Translate[i] = Pos;
1263 NewGraphNodes.push_back(GraphNodes[i]);
1264 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1265 }
1266 }
1267
1268 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1269 if (!GraphNodes[i].AddressTaken) {
1270 unsigned Pos = NewPos++;
1271 Translate[i] = Pos;
1272 NewGraphNodes.push_back(GraphNodes[i]);
1273 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1274 }
1275 }
1276
1277 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1278 Iter != ValueNodes.end();
1279 ++Iter)
1280 Iter->second = Translate[Iter->second];
1281
1282 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1283 Iter != ObjectNodes.end();
1284 ++Iter)
1285 Iter->second = Translate[Iter->second];
1286
1287 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1288 Iter != ReturnNodes.end();
1289 ++Iter)
1290 Iter->second = Translate[Iter->second];
1291
1292 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1293 Iter != VarargNodes.end();
1294 ++Iter)
1295 Iter->second = Translate[Iter->second];
1296
1297 for (unsigned i = 0; i < Constraints.size(); ++i) {
1298 Constraint &C = Constraints[i];
1299 C.Src = Translate[C.Src];
1300 C.Dest = Translate[C.Dest];
1301 }
1302
1303 GraphNodes.swap(NewGraphNodes);
1304#undef DEBUG_TYPE
1305#define DEBUG_TYPE "anders-aa"
1306}
1307
1308/// The technique used here is described in "Exploiting Pointer and Location
1309/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1310/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1311/// and is equivalent to value numbering the collapsed constraint graph without
1312/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1313/// first order pointer dereferences and speed up/reduce memory usage of HU.
1314/// Running both is equivalent to HRU without the iteration
1315/// HVN in more detail:
1316/// Imagine the set of constraints was simply straight line code with no loops
1317/// (we eliminate cycles, so there are no loops), such as:
1318/// E = &D
1319/// E = &C
1320/// E = F
1321/// F = G
1322/// G = F
1323/// Applying value numbering to this code tells us:
1324/// G == F == E
1325///
1326/// For HVN, this is as far as it goes. We assign new value numbers to every
1327/// "address node", and every "reference node".
1328/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1329/// cycle must have the same value number since the = operation is really
1330/// inclusion, not overwrite), and value number nodes we receive points-to sets
1331/// before we value our own node.
1332/// The advantage of HU over HVN is that HU considers the inclusion property, so
1333/// that if you have
1334/// E = &D
1335/// E = &C
1336/// E = F
1337/// F = G
1338/// F = &D
1339/// G = F
1340/// HU will determine that G == F == E. HVN will not, because it cannot prove
1341/// that the points to information ends up being the same because they all
1342/// receive &D from E anyway.
1343
1344void Andersens::HVN() {
1345 DOUT << "Beginning HVN\n";
1346 // Build a predecessor graph. This is like our constraint graph with the
1347 // edges going in the opposite direction, and there are edges for all the
1348 // constraints, instead of just copy constraints. We also build implicit
1349 // edges for constraints are implied but not explicit. I.E for the constraint
1350 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1351 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1352 Constraint &C = Constraints[i];
1353 if (C.Type == Constraint::AddressOf) {
1354 GraphNodes[C.Src].AddressTaken = true;
1355 GraphNodes[C.Src].Direct = false;
1356
1357 // Dest = &src edge
1358 unsigned AdrNode = C.Src + FirstAdrNode;
1359 if (!GraphNodes[C.Dest].PredEdges)
1360 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1361 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1362
1363 // *Dest = src edge
1364 unsigned RefNode = C.Dest + FirstRefNode;
1365 if (!GraphNodes[RefNode].ImplicitPredEdges)
1366 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1367 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1368 } else if (C.Type == Constraint::Load) {
1369 if (C.Offset == 0) {
1370 // dest = *src edge
1371 if (!GraphNodes[C.Dest].PredEdges)
1372 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1373 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1374 } else {
1375 GraphNodes[C.Dest].Direct = false;
1376 }
1377 } else if (C.Type == Constraint::Store) {
1378 if (C.Offset == 0) {
1379 // *dest = src edge
1380 unsigned RefNode = C.Dest + FirstRefNode;
1381 if (!GraphNodes[RefNode].PredEdges)
1382 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1383 GraphNodes[RefNode].PredEdges->set(C.Src);
1384 }
1385 } else {
1386 // Dest = Src edge and *Dest = *Src edge
1387 if (!GraphNodes[C.Dest].PredEdges)
1388 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1389 GraphNodes[C.Dest].PredEdges->set(C.Src);
1390 unsigned RefNode = C.Dest + FirstRefNode;
1391 if (!GraphNodes[RefNode].ImplicitPredEdges)
1392 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1393 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1394 }
1395 }
1396 PEClass = 1;
1397 // Do SCC finding first to condense our predecessor graph
1398 DFSNumber = 0;
1399 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1400 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1401 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1402
1403 for (unsigned i = 0; i < FirstRefNode; ++i) {
1404 unsigned Node = VSSCCRep[i];
1405 if (!Node2Visited[Node])
1406 HVNValNum(Node);
1407 }
1408 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1409 Iter != Set2PEClass.end();
1410 ++Iter)
1411 delete Iter->first;
1412 Set2PEClass.clear();
1413 Node2DFS.clear();
1414 Node2Deleted.clear();
1415 Node2Visited.clear();
1416 DOUT << "Finished HVN\n";
1417
1418}
1419
1420/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1421/// same time because it's easy.
1422void Andersens::HVNValNum(unsigned NodeIndex) {
1423 unsigned MyDFS = DFSNumber++;
1424 Node *N = &GraphNodes[NodeIndex];
1425 Node2Visited[NodeIndex] = true;
1426 Node2DFS[NodeIndex] = MyDFS;
1427
1428 // First process all our explicit edges
1429 if (N->PredEdges)
1430 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1431 Iter != N->PredEdges->end();
1432 ++Iter) {
1433 unsigned j = VSSCCRep[*Iter];
1434 if (!Node2Deleted[j]) {
1435 if (!Node2Visited[j])
1436 HVNValNum(j);
1437 if (Node2DFS[NodeIndex] > Node2DFS[j])
1438 Node2DFS[NodeIndex] = Node2DFS[j];
1439 }
1440 }
1441
1442 // Now process all the implicit edges
1443 if (N->ImplicitPredEdges)
1444 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1445 Iter != N->ImplicitPredEdges->end();
1446 ++Iter) {
1447 unsigned j = VSSCCRep[*Iter];
1448 if (!Node2Deleted[j]) {
1449 if (!Node2Visited[j])
1450 HVNValNum(j);
1451 if (Node2DFS[NodeIndex] > Node2DFS[j])
1452 Node2DFS[NodeIndex] = Node2DFS[j];
1453 }
1454 }
1455
1456 // See if we found any cycles
1457 if (MyDFS == Node2DFS[NodeIndex]) {
1458 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1459 unsigned CycleNodeIndex = SCCStack.top();
1460 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1461 VSSCCRep[CycleNodeIndex] = NodeIndex;
1462 // Unify the nodes
1463 N->Direct &= CycleNode->Direct;
1464
1465 if (CycleNode->PredEdges) {
1466 if (!N->PredEdges)
1467 N->PredEdges = new SparseBitVector<>;
1468 *(N->PredEdges) |= CycleNode->PredEdges;
1469 delete CycleNode->PredEdges;
1470 CycleNode->PredEdges = NULL;
1471 }
1472 if (CycleNode->ImplicitPredEdges) {
1473 if (!N->ImplicitPredEdges)
1474 N->ImplicitPredEdges = new SparseBitVector<>;
1475 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1476 delete CycleNode->ImplicitPredEdges;
1477 CycleNode->ImplicitPredEdges = NULL;
1478 }
1479
1480 SCCStack.pop();
1481 }
1482
1483 Node2Deleted[NodeIndex] = true;
1484
1485 if (!N->Direct) {
1486 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1487 return;
1488 }
1489
1490 // Collect labels of successor nodes
1491 bool AllSame = true;
1492 unsigned First = ~0;
1493 SparseBitVector<> *Labels = new SparseBitVector<>;
1494 bool Used = false;
1495
1496 if (N->PredEdges)
1497 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1498 Iter != N->PredEdges->end();
1499 ++Iter) {
1500 unsigned j = VSSCCRep[*Iter];
1501 unsigned Label = GraphNodes[j].PointerEquivLabel;
1502 // Ignore labels that are equal to us or non-pointers
1503 if (j == NodeIndex || Label == 0)
1504 continue;
1505 if (First == (unsigned)~0)
1506 First = Label;
1507 else if (First != Label)
1508 AllSame = false;
1509 Labels->set(Label);
1510 }
1511
1512 // We either have a non-pointer, a copy of an existing node, or a new node.
1513 // Assign the appropriate pointer equivalence label.
1514 if (Labels->empty()) {
1515 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1516 } else if (AllSame) {
1517 GraphNodes[NodeIndex].PointerEquivLabel = First;
1518 } else {
1519 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1520 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1521 unsigned EquivClass = PEClass++;
1522 Set2PEClass[Labels] = EquivClass;
1523 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1524 Used = true;
1525 }
1526 }
1527 if (!Used)
1528 delete Labels;
1529 } else {
1530 SCCStack.push(NodeIndex);
1531 }
1532}
1533
1534/// The technique used here is described in "Exploiting Pointer and Location
1535/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1536/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1537/// and is equivalent to value numbering the collapsed constraint graph
1538/// including evaluating unions.
1539void Andersens::HU() {
1540 DOUT << "Beginning HU\n";
1541 // Build a predecessor graph. This is like our constraint graph with the
1542 // edges going in the opposite direction, and there are edges for all the
1543 // constraints, instead of just copy constraints. We also build implicit
1544 // edges for constraints are implied but not explicit. I.E for the constraint
1545 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1546 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1547 Constraint &C = Constraints[i];
1548 if (C.Type == Constraint::AddressOf) {
1549 GraphNodes[C.Src].AddressTaken = true;
1550 GraphNodes[C.Src].Direct = false;
1551
1552 GraphNodes[C.Dest].PointsTo->set(C.Src);
1553 // *Dest = src edge
1554 unsigned RefNode = C.Dest + FirstRefNode;
1555 if (!GraphNodes[RefNode].ImplicitPredEdges)
1556 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1557 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1558 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1559 } else if (C.Type == Constraint::Load) {
1560 if (C.Offset == 0) {
1561 // dest = *src edge
1562 if (!GraphNodes[C.Dest].PredEdges)
1563 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1564 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1565 } else {
1566 GraphNodes[C.Dest].Direct = false;
1567 }
1568 } else if (C.Type == Constraint::Store) {
1569 if (C.Offset == 0) {
1570 // *dest = src edge
1571 unsigned RefNode = C.Dest + FirstRefNode;
1572 if (!GraphNodes[RefNode].PredEdges)
1573 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1574 GraphNodes[RefNode].PredEdges->set(C.Src);
1575 }
1576 } else {
1577 // Dest = Src edge and *Dest = *Src edg
1578 if (!GraphNodes[C.Dest].PredEdges)
1579 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1580 GraphNodes[C.Dest].PredEdges->set(C.Src);
1581 unsigned RefNode = C.Dest + FirstRefNode;
1582 if (!GraphNodes[RefNode].ImplicitPredEdges)
1583 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1584 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1585 }
1586 }
1587 PEClass = 1;
1588 // Do SCC finding first to condense our predecessor graph
1589 DFSNumber = 0;
1590 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1591 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1592 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1593
1594 for (unsigned i = 0; i < FirstRefNode; ++i) {
1595 if (FindNode(i) == i) {
1596 unsigned Node = VSSCCRep[i];
1597 if (!Node2Visited[Node])
1598 Condense(Node);
1599 }
1600 }
1601
1602 // Reset tables for actual labeling
1603 Node2DFS.clear();
1604 Node2Visited.clear();
1605 Node2Deleted.clear();
1606 // Pre-grow our densemap so that we don't get really bad behavior
1607 Set2PEClass.resize(GraphNodes.size());
1608
1609 // Visit the condensed graph and generate pointer equivalence labels.
1610 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1611 for (unsigned i = 0; i < FirstRefNode; ++i) {
1612 if (FindNode(i) == i) {
1613 unsigned Node = VSSCCRep[i];
1614 if (!Node2Visited[Node])
1615 HUValNum(Node);
1616 }
1617 }
1618 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1619 Set2PEClass.clear();
1620 DOUT << "Finished HU\n";
1621}
1622
1623
1624/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1625void Andersens::Condense(unsigned NodeIndex) {
1626 unsigned MyDFS = DFSNumber++;
1627 Node *N = &GraphNodes[NodeIndex];
1628 Node2Visited[NodeIndex] = true;
1629 Node2DFS[NodeIndex] = MyDFS;
1630
1631 // First process all our explicit edges
1632 if (N->PredEdges)
1633 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1634 Iter != N->PredEdges->end();
1635 ++Iter) {
1636 unsigned j = VSSCCRep[*Iter];
1637 if (!Node2Deleted[j]) {
1638 if (!Node2Visited[j])
1639 Condense(j);
1640 if (Node2DFS[NodeIndex] > Node2DFS[j])
1641 Node2DFS[NodeIndex] = Node2DFS[j];
1642 }
1643 }
1644
1645 // Now process all the implicit edges
1646 if (N->ImplicitPredEdges)
1647 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1648 Iter != N->ImplicitPredEdges->end();
1649 ++Iter) {
1650 unsigned j = VSSCCRep[*Iter];
1651 if (!Node2Deleted[j]) {
1652 if (!Node2Visited[j])
1653 Condense(j);
1654 if (Node2DFS[NodeIndex] > Node2DFS[j])
1655 Node2DFS[NodeIndex] = Node2DFS[j];
1656 }
1657 }
1658
1659 // See if we found any cycles
1660 if (MyDFS == Node2DFS[NodeIndex]) {
1661 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1662 unsigned CycleNodeIndex = SCCStack.top();
1663 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1664 VSSCCRep[CycleNodeIndex] = NodeIndex;
1665 // Unify the nodes
1666 N->Direct &= CycleNode->Direct;
1667
1668 *(N->PointsTo) |= CycleNode->PointsTo;
1669 delete CycleNode->PointsTo;
1670 CycleNode->PointsTo = NULL;
1671 if (CycleNode->PredEdges) {
1672 if (!N->PredEdges)
1673 N->PredEdges = new SparseBitVector<>;
1674 *(N->PredEdges) |= CycleNode->PredEdges;
1675 delete CycleNode->PredEdges;
1676 CycleNode->PredEdges = NULL;
1677 }
1678 if (CycleNode->ImplicitPredEdges) {
1679 if (!N->ImplicitPredEdges)
1680 N->ImplicitPredEdges = new SparseBitVector<>;
1681 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1682 delete CycleNode->ImplicitPredEdges;
1683 CycleNode->ImplicitPredEdges = NULL;
1684 }
1685 SCCStack.pop();
1686 }
1687
1688 Node2Deleted[NodeIndex] = true;
1689
1690 // Set up number of incoming edges for other nodes
1691 if (N->PredEdges)
1692 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1693 Iter != N->PredEdges->end();
1694 ++Iter)
1695 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1696 } else {
1697 SCCStack.push(NodeIndex);
1698 }
1699}
1700
1701void Andersens::HUValNum(unsigned NodeIndex) {
1702 Node *N = &GraphNodes[NodeIndex];
1703 Node2Visited[NodeIndex] = true;
1704
1705 // Eliminate dereferences of non-pointers for those non-pointers we have
1706 // already identified. These are ref nodes whose non-ref node:
1707 // 1. Has already been visited determined to point to nothing (and thus, a
1708 // dereference of it must point to nothing)
1709 // 2. Any direct node with no predecessor edges in our graph and with no
1710 // points-to set (since it can't point to anything either, being that it
1711 // receives no points-to sets and has none).
1712 if (NodeIndex >= FirstRefNode) {
1713 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1714 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1715 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1716 && GraphNodes[j].PointsTo->empty())){
1717 return;
1718 }
1719 }
1720 // Process all our explicit edges
1721 if (N->PredEdges)
1722 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1723 Iter != N->PredEdges->end();
1724 ++Iter) {
1725 unsigned j = VSSCCRep[*Iter];
1726 if (!Node2Visited[j])
1727 HUValNum(j);
1728
1729 // If this edge turned out to be the same as us, or got no pointer
1730 // equivalence label (and thus points to nothing) , just decrement our
1731 // incoming edges and continue.
1732 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1733 --GraphNodes[j].NumInEdges;
1734 continue;
1735 }
1736
1737 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1738
1739 // If we didn't end up storing this in the hash, and we're done with all
1740 // the edges, we don't need the points-to set anymore.
1741 --GraphNodes[j].NumInEdges;
1742 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1743 delete GraphNodes[j].PointsTo;
1744 GraphNodes[j].PointsTo = NULL;
1745 }
1746 }
1747 // If this isn't a direct node, generate a fresh variable.
1748 if (!N->Direct) {
1749 N->PointsTo->set(FirstRefNode + NodeIndex);
1750 }
1751
1752 // See If we have something equivalent to us, if not, generate a new
1753 // equivalence class.
1754 if (N->PointsTo->empty()) {
1755 delete N->PointsTo;
1756 N->PointsTo = NULL;
1757 } else {
1758 if (N->Direct) {
1759 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1760 if (N->PointerEquivLabel == 0) {
1761 unsigned EquivClass = PEClass++;
1762 N->StoredInHash = true;
1763 Set2PEClass[N->PointsTo] = EquivClass;
1764 N->PointerEquivLabel = EquivClass;
1765 }
1766 } else {
1767 N->PointerEquivLabel = PEClass++;
1768 }
1769 }
1770}
1771
1772/// Rewrite our list of constraints so that pointer equivalent nodes are
1773/// replaced by their the pointer equivalence class representative.
1774void Andersens::RewriteConstraints() {
1775 std::vector<Constraint> NewConstraints;
Daniel Berlin336c6c02007-09-29 00:50:40 +00001776 DenseMap<Constraint, bool, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001777
1778 PEClass2Node.clear();
1779 PENLEClass2Node.clear();
1780
1781 // We may have from 1 to Graphnodes + 1 equivalence classes.
1782 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1783 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1784
1785 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1786 // nodes, and rewriting constraints to use the representative nodes.
1787 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1788 Constraint &C = Constraints[i];
1789 unsigned RHSNode = FindNode(C.Src);
1790 unsigned LHSNode = FindNode(C.Dest);
1791 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1792 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1793
1794 // First we try to eliminate constraints for things we can prove don't point
1795 // to anything.
1796 if (LHSLabel == 0) {
1797 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1798 DOUT << " is a non-pointer, ignoring constraint.\n";
1799 continue;
1800 }
1801 if (RHSLabel == 0) {
1802 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1803 DOUT << " is a non-pointer, ignoring constraint.\n";
1804 continue;
1805 }
1806 // This constraint may be useless, and it may become useless as we translate
1807 // it.
1808 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1809 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001810
Daniel Berlind81ccc22007-09-24 19:45:49 +00001811 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1812 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001813 if (C.Src == C.Dest && C.Type == Constraint::Copy
Daniel Berlin336c6c02007-09-29 00:50:40 +00001814 || Seen[C] == true)
Daniel Berlind81ccc22007-09-24 19:45:49 +00001815 continue;
1816
Daniel Berlin336c6c02007-09-29 00:50:40 +00001817 Seen[C] = true;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001818 NewConstraints.push_back(C);
1819 }
1820 Constraints.swap(NewConstraints);
1821 PEClass2Node.clear();
1822}
1823
1824/// See if we have a node that is pointer equivalent to the one being asked
1825/// about, and if so, unite them and return the equivalent node. Otherwise,
1826/// return the original node.
1827unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1828 unsigned NodeLabel) {
1829 if (!GraphNodes[NodeIndex].AddressTaken) {
1830 if (PEClass2Node[NodeLabel] != -1) {
1831 // We found an existing node with the same pointer label, so unify them.
1832 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex);
1833 } else {
1834 PEClass2Node[NodeLabel] = NodeIndex;
1835 PENLEClass2Node[NodeLabel] = NodeIndex;
1836 }
1837 } else if (PENLEClass2Node[NodeLabel] == -1) {
1838 PENLEClass2Node[NodeLabel] = NodeIndex;
1839 }
1840
1841 return NodeIndex;
1842}
1843
1844void Andersens::PrintLabels() {
1845 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1846 if (i < FirstRefNode) {
1847 PrintNode(&GraphNodes[i]);
1848 } else if (i < FirstAdrNode) {
1849 DOUT << "REF(";
1850 PrintNode(&GraphNodes[i-FirstRefNode]);
1851 DOUT <<")";
1852 } else {
1853 DOUT << "ADR(";
1854 PrintNode(&GraphNodes[i-FirstAdrNode]);
1855 DOUT <<")";
1856 }
1857
1858 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1859 << " and SCC rep " << VSSCCRep[i]
1860 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1861 << "\n";
1862 }
1863}
1864
1865/// Optimize the constraints by performing offline variable substitution and
1866/// other optimizations.
1867void Andersens::OptimizeConstraints() {
1868 DOUT << "Beginning constraint optimization\n";
1869
1870 // Function related nodes need to stay in the same relative position and can't
1871 // be location equivalent.
1872 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1873 Iter != MaxK.end();
1874 ++Iter) {
1875 for (unsigned i = Iter->first;
1876 i != Iter->first + Iter->second;
1877 ++i) {
1878 GraphNodes[i].AddressTaken = true;
1879 GraphNodes[i].Direct = false;
1880 }
1881 }
1882
1883 ClumpAddressTaken();
1884 FirstRefNode = GraphNodes.size();
1885 FirstAdrNode = FirstRefNode + GraphNodes.size();
1886 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
1887 Node(false));
1888 VSSCCRep.resize(GraphNodes.size());
1889 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1890 VSSCCRep[i] = i;
1891 }
1892 HVN();
1893 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1894 Node *N = &GraphNodes[i];
1895 delete N->PredEdges;
1896 N->PredEdges = NULL;
1897 delete N->ImplicitPredEdges;
1898 N->ImplicitPredEdges = NULL;
1899 }
1900#undef DEBUG_TYPE
1901#define DEBUG_TYPE "anders-aa-labels"
1902 DEBUG(PrintLabels());
1903#undef DEBUG_TYPE
1904#define DEBUG_TYPE "anders-aa"
1905 RewriteConstraints();
1906 // Delete the adr nodes.
1907 GraphNodes.resize(FirstRefNode * 2);
1908
1909 // Now perform HU
1910 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1911 Node *N = &GraphNodes[i];
1912 if (FindNode(i) == i) {
1913 N->PointsTo = new SparseBitVector<>;
1914 N->PointedToBy = new SparseBitVector<>;
1915 // Reset our labels
1916 }
1917 VSSCCRep[i] = i;
1918 N->PointerEquivLabel = 0;
1919 }
1920 HU();
1921#undef DEBUG_TYPE
1922#define DEBUG_TYPE "anders-aa-labels"
1923 DEBUG(PrintLabels());
1924#undef DEBUG_TYPE
1925#define DEBUG_TYPE "anders-aa"
1926 RewriteConstraints();
1927 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1928 if (FindNode(i) == i) {
1929 Node *N = &GraphNodes[i];
1930 delete N->PointsTo;
1931 delete N->PredEdges;
1932 delete N->ImplicitPredEdges;
1933 delete N->PointedToBy;
1934 }
1935 }
1936 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
1937 DOUT << "Finished constraint optimization\n";
1938 FirstRefNode = 0;
1939 FirstAdrNode = 0;
1940}
1941
1942/// Unite pointer but not location equivalent variables, now that the constraint
1943/// graph is built.
1944void Andersens::UnitePointerEquivalences() {
1945 DOUT << "Uniting remaining pointer equivalences\n";
1946 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1947 if (GraphNodes[i].AddressTaken && GraphNodes[i].NodeRep == SelfRep) {
1948 unsigned Label = GraphNodes[i].PointerEquivLabel;
1949
1950 if (Label && PENLEClass2Node[Label] != -1)
1951 UniteNodes(i, PENLEClass2Node[Label]);
1952 }
1953 }
1954 DOUT << "Finished remaining pointer equivalences\n";
1955 PENLEClass2Node.clear();
1956}
1957
1958/// Create the constraint graph used for solving points-to analysis.
1959///
Daniel Berlinaad15882007-09-16 21:45:02 +00001960void Andersens::CreateConstraintGraph() {
1961 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1962 Constraint &C = Constraints[i];
1963 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1964 if (C.Type == Constraint::AddressOf)
1965 GraphNodes[C.Dest].PointsTo->set(C.Src);
1966 else if (C.Type == Constraint::Load)
1967 GraphNodes[C.Src].Constraints.push_back(C);
1968 else if (C.Type == Constraint::Store)
1969 GraphNodes[C.Dest].Constraints.push_back(C);
1970 else if (C.Offset != 0)
1971 GraphNodes[C.Src].Constraints.push_back(C);
1972 else
1973 GraphNodes[C.Src].Edges->set(C.Dest);
1974 }
1975}
1976
1977// Perform cycle detection, DFS, and RPO finding.
1978void Andersens::QueryNode(unsigned Node) {
1979 assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1980 unsigned OurDFS = ++DFSNumber;
1981 SparseBitVector<> ToErase;
1982 SparseBitVector<> NewEdges;
1983 Node2DFS[Node] = OurDFS;
1984
1985 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1986 bi != GraphNodes[Node].Edges->end();
1987 ++bi) {
1988 unsigned RepNode = FindNode(*bi);
1989 // If we are going to add an edge to repnode, we have no need for the edge
1990 // to e anymore.
1991 if (RepNode != *bi && NewEdges.test(RepNode)){
1992 ToErase.set(*bi);
1993 continue;
1994 }
1995
1996 // Continue about our DFS.
1997 if (!Node2Deleted[RepNode]){
1998 if (Node2DFS[RepNode] == 0) {
1999 QueryNode(RepNode);
2000 // May have been changed by query
2001 RepNode = FindNode(RepNode);
2002 }
2003 if (Node2DFS[RepNode] < Node2DFS[Node])
2004 Node2DFS[Node] = Node2DFS[RepNode];
2005 }
2006 // We may have just discovered that e belongs to a cycle, in which case we
2007 // can also erase it.
2008 if (RepNode != *bi) {
2009 ToErase.set(*bi);
2010 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002011 }
2012 }
2013
Daniel Berlinaad15882007-09-16 21:45:02 +00002014 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2015 GraphNodes[Node].Edges |= NewEdges;
2016
2017 // If this node is a root of a non-trivial SCC, place it on our worklist to be
2018 // processed
2019 if (OurDFS == Node2DFS[Node]) {
2020 bool Changed = false;
2021 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
2022 Node = UniteNodes(Node, FindNode(SCCStack.top()));
2023
2024 SCCStack.pop();
2025 Changed = true;
2026 }
2027 Node2Deleted[Node] = true;
2028 RPONumber++;
2029
2030 Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
2031 Node2Topo[Node] = GraphNodes.size() - RPONumber;
2032 if (Changed)
2033 GraphNodes[Node].Changed = true;
2034 } else {
2035 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002036 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002037}
2038
2039
2040/// SolveConstraints - This stage iteratively processes the constraints list
2041/// propagating constraints (adding edges to the Nodes in the points-to graph)
2042/// until a fixed point is reached.
2043///
2044void Andersens::SolveConstraints() {
2045 bool Changed = true;
2046 unsigned Iteration = 0;
Daniel Berlinaad15882007-09-16 21:45:02 +00002047
Daniel Berlind81ccc22007-09-24 19:45:49 +00002048 OptimizeConstraints();
2049#undef DEBUG_TYPE
2050#define DEBUG_TYPE "anders-aa-constraints"
2051 DEBUG(PrintConstraints());
2052#undef DEBUG_TYPE
2053#define DEBUG_TYPE "anders-aa"
2054
Daniel Berlinaad15882007-09-16 21:45:02 +00002055 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2056 Node *N = &GraphNodes[i];
2057 N->PointsTo = new SparseBitVector<>;
2058 N->OldPointsTo = new SparseBitVector<>;
2059 N->Edges = new SparseBitVector<>;
2060 }
2061 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002062 UnitePointerEquivalences();
2063 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlinaad15882007-09-16 21:45:02 +00002064 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2065 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002066 Node2DFS.clear();
2067 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002068 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2069 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2070 DFSNumber = 0;
2071 RPONumber = 0;
2072 // Order graph and mark starting nodes as changed.
2073 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2074 unsigned N = FindNode(i);
2075 Node *INode = &GraphNodes[i];
2076 if (Node2DFS[N] == 0) {
2077 QueryNode(N);
2078 // Mark as changed if it's a representation and can contribute to the
2079 // calculation right now.
2080 if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
2081 && (!INode->Edges->empty() || !INode->Constraints.empty()))
2082 INode->Changed = true;
2083 }
2084 }
2085
2086 do {
Daniel Berlinc6d93982007-09-16 23:59:53 +00002087 Changed = false;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002088 ++NumIters;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002089 DOUT << "Starting iteration #" << Iteration++ << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002090 // TODO: In the microoptimization category, we could just make Topo2Node
2091 // a fast map and thus only contain the visited nodes.
2092 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2093 unsigned CurrNodeIndex = Topo2Node[i];
2094 Node *CurrNode;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002095
Daniel Berlinaad15882007-09-16 21:45:02 +00002096 // We may not revisit all nodes on every iteration
2097 if (CurrNodeIndex == Unvisited)
2098 continue;
2099 CurrNode = &GraphNodes[CurrNodeIndex];
2100 // See if this is a node we need to process on this iteration
2101 if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
2102 continue;
2103 CurrNode->Changed = false;
2104
2105 // Figure out the changed points to bits
2106 SparseBitVector<> CurrPointsTo;
2107 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2108 CurrNode->OldPointsTo);
2109 if (CurrPointsTo.empty()){
2110 continue;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002111 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002112 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002113
Daniel Berlinaad15882007-09-16 21:45:02 +00002114 /* Now process the constraints for this node. */
2115 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2116 li != CurrNode->Constraints.end(); ) {
2117 li->Src = FindNode(li->Src);
2118 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002119
Daniel Berlinaad15882007-09-16 21:45:02 +00002120 // TODO: We could delete redundant constraints here.
2121 // Src and Dest will be the vars we are going to process.
2122 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002123 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002124 // Load constraints say that every member of our RHS solution has K
2125 // added to it, and that variable gets an edge to LHS. We also union
2126 // RHS+K's solution into the LHS solution.
2127 // Store constraints say that every member of our LHS solution has K
2128 // added to it, and that variable gets an edge from RHS. We also union
2129 // RHS's solution into the LHS+K solution.
2130 unsigned *Src;
2131 unsigned *Dest;
2132 unsigned K = li->Offset;
2133 unsigned CurrMember;
2134 if (li->Type == Constraint::Load) {
2135 Src = &CurrMember;
2136 Dest = &li->Dest;
2137 } else if (li->Type == Constraint::Store) {
2138 Src = &li->Src;
2139 Dest = &CurrMember;
2140 } else {
2141 // TODO Handle offseted copy constraint
2142 li++;
2143 continue;
2144 }
2145 // TODO: hybrid cycle detection would go here, we should check
2146 // if it was a statically detected offline equivalence that
2147 // involves pointers , and if so, remove the redundant constraints.
Chris Lattnere995a2a2004-05-23 21:00:47 +00002148
Daniel Berlinaad15882007-09-16 21:45:02 +00002149 const SparseBitVector<> &Solution = CurrPointsTo;
2150
2151 for (SparseBitVector<>::iterator bi = Solution.begin();
2152 bi != Solution.end();
2153 ++bi) {
2154 CurrMember = *bi;
2155
2156 // Need to increment the member by K since that is where we are
Daniel Berlind81ccc22007-09-24 19:45:49 +00002157 // supposed to copy to/from. Note that in positive weight cycles,
2158 // which occur in address taking of fields, K can go past
2159 // MaxK[CurrMember] elements, even though that is all it could point
2160 // to.
Daniel Berlinaad15882007-09-16 21:45:02 +00002161 if (K > 0 && K > MaxK[CurrMember])
2162 continue;
2163 else
2164 CurrMember = FindNode(CurrMember + K);
2165
2166 // Add an edge to the graph, so we can just do regular bitmap ior next
2167 // time. It may also let us notice a cycle.
Daniel Berlinc6d93982007-09-16 23:59:53 +00002168 if (GraphNodes[*Src].Edges->test_and_set(*Dest)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002169 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
2170 GraphNodes[*Dest].Changed = true;
2171 // If we changed a node we've already processed, we need another
2172 // iteration.
2173 if (Node2Topo[*Dest] <= i)
2174 Changed = true;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002175 }
2176 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002177 }
2178 li++;
2179 }
2180 SparseBitVector<> NewEdges;
2181 SparseBitVector<> ToErase;
2182
2183 // Now all we have left to do is propagate points-to info along the
2184 // edges, erasing the redundant edges.
2185
2186
2187 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2188 bi != CurrNode->Edges->end();
2189 ++bi) {
2190
2191 unsigned DestVar = *bi;
2192 unsigned Rep = FindNode(DestVar);
2193
2194 // If we ended up with this node as our destination, or we've already
2195 // got an edge for the representative, delete the current edge.
2196 if (Rep == CurrNodeIndex ||
2197 (Rep != DestVar && NewEdges.test(Rep))) {
2198 ToErase.set(DestVar);
2199 continue;
2200 }
2201 // Union the points-to sets into the dest
2202 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2203 GraphNodes[Rep].Changed = true;
2204 if (Node2Topo[Rep] <= i)
2205 Changed = true;
2206 }
2207 // If this edge's destination was collapsed, rewrite the edge.
2208 if (Rep != DestVar) {
2209 ToErase.set(DestVar);
2210 NewEdges.set(Rep);
2211 }
2212 }
2213 CurrNode->Edges->intersectWithComplement(ToErase);
2214 CurrNode->Edges |= NewEdges;
2215 }
2216 if (Changed) {
2217 DFSNumber = RPONumber = 0;
2218 Node2Deleted.clear();
2219 Topo2Node.clear();
2220 Node2Topo.clear();
2221 Node2DFS.clear();
2222 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2223 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2224 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2225 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2226 // Rediscover the DFS/Topo ordering, and cycle detect.
2227 for (unsigned j = 0; j < GraphNodes.size(); j++) {
2228 unsigned JRep = FindNode(j);
2229 if (Node2DFS[JRep] == 0)
2230 QueryNode(JRep);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002231 }
2232 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002233
2234 } while (Changed);
2235
2236 Node2Topo.clear();
2237 Topo2Node.clear();
2238 Node2DFS.clear();
2239 Node2Deleted.clear();
2240 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2241 Node *N = &GraphNodes[i];
2242 delete N->OldPointsTo;
2243 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002244 }
2245}
2246
Daniel Berlinaad15882007-09-16 21:45:02 +00002247//===----------------------------------------------------------------------===//
2248// Union-Find
2249//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002250
Daniel Berlinaad15882007-09-16 21:45:02 +00002251// Unite nodes First and Second, returning the one which is now the
2252// representative node. First and Second are indexes into GraphNodes
2253unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
2254 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2255 "Attempting to merge nodes that don't exist");
2256 // TODO: implement union by rank
2257 Node *FirstNode = &GraphNodes[First];
2258 Node *SecondNode = &GraphNodes[Second];
2259
2260 assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
2261 "Trying to unite two non-representative nodes!");
2262 if (First == Second)
2263 return First;
2264
2265 SecondNode->NodeRep = First;
2266 FirstNode->Changed |= SecondNode->Changed;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002267 if (FirstNode->PointsTo && SecondNode->PointsTo)
2268 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2269 if (FirstNode->Edges && SecondNode->Edges)
2270 FirstNode->Edges |= *(SecondNode->Edges);
2271 if (!FirstNode->Constraints.empty() && !SecondNode->Constraints.empty())
2272 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2273 SecondNode->Constraints);
2274 if (FirstNode->OldPointsTo) {
2275 delete FirstNode->OldPointsTo;
2276 FirstNode->OldPointsTo = new SparseBitVector<>;
2277 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002278
2279 // Destroy interesting parts of the merged-from node.
2280 delete SecondNode->OldPointsTo;
2281 delete SecondNode->Edges;
2282 delete SecondNode->PointsTo;
2283 SecondNode->Edges = NULL;
2284 SecondNode->PointsTo = NULL;
2285 SecondNode->OldPointsTo = NULL;
2286
2287 NumUnified++;
2288 DOUT << "Unified Node ";
2289 DEBUG(PrintNode(FirstNode));
2290 DOUT << " and Node ";
2291 DEBUG(PrintNode(SecondNode));
2292 DOUT << "\n";
2293
2294 // TODO: Handle SDT
2295 return First;
2296}
2297
2298// Find the index into GraphNodes of the node representing Node, performing
2299// path compression along the way
2300unsigned Andersens::FindNode(unsigned NodeIndex) {
2301 assert (NodeIndex < GraphNodes.size()
2302 && "Attempting to find a node that can't exist");
2303 Node *N = &GraphNodes[NodeIndex];
2304 if (N->NodeRep == SelfRep)
2305 return NodeIndex;
2306 else
2307 return (N->NodeRep = FindNode(N->NodeRep));
2308}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002309
2310//===----------------------------------------------------------------------===//
2311// Debugging Output
2312//===----------------------------------------------------------------------===//
2313
2314void Andersens::PrintNode(Node *N) {
2315 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002316 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002317 return;
2318 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002319 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002320 return;
2321 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002322 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002323 return;
2324 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002325 if (!N->getValue()) {
2326 cerr << "artificial" << (intptr_t) N;
2327 return;
2328 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002329
2330 assert(N->getValue() != 0 && "Never set node label!");
2331 Value *V = N->getValue();
2332 if (Function *F = dyn_cast<Function>(V)) {
2333 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002334 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002335 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002336 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002337 } else if (F->getFunctionType()->isVarArg() &&
2338 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002339 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002340 return;
2341 }
2342 }
2343
2344 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002345 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002346 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002347 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002348
2349 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002350 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002351 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002352 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002353
2354 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002355 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002356 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002357}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002358void Andersens::PrintConstraint(const Constraint &C) {
2359 if (C.Type == Constraint::Store) {
2360 cerr << "*";
2361 if (C.Offset != 0)
2362 cerr << "(";
2363 }
2364 PrintNode(&GraphNodes[C.Dest]);
2365 if (C.Type == Constraint::Store && C.Offset != 0)
2366 cerr << " + " << C.Offset << ")";
2367 cerr << " = ";
2368 if (C.Type == Constraint::Load) {
2369 cerr << "*";
2370 if (C.Offset != 0)
2371 cerr << "(";
2372 }
2373 else if (C.Type == Constraint::AddressOf)
2374 cerr << "&";
2375 PrintNode(&GraphNodes[C.Src]);
2376 if (C.Offset != 0 && C.Type != Constraint::Store)
2377 cerr << " + " << C.Offset;
2378 if (C.Type == Constraint::Load && C.Offset != 0)
2379 cerr << ")";
2380 cerr << "\n";
2381}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002382
2383void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002384 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002385
Daniel Berlind81ccc22007-09-24 19:45:49 +00002386 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2387 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002388}
2389
2390void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002391 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002392 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2393 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002394 if (FindNode (i) != i) {
2395 PrintNode(N);
2396 cerr << "\t--> same as ";
2397 PrintNode(&GraphNodes[FindNode(i)]);
2398 cerr << "\n";
2399 } else {
2400 cerr << "[" << (N->PointsTo->count()) << "] ";
2401 PrintNode(N);
2402 cerr << "\t--> ";
2403
2404 bool first = true;
2405 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2406 bi != N->PointsTo->end();
2407 ++bi) {
2408 if (!first)
2409 cerr << ", ";
2410 PrintNode(&GraphNodes[*bi]);
2411 first = false;
2412 }
2413 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002414 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002415 }
2416}