blob: da4fa82f06a2d0437c364214603a9b3deb8b10a6 [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"
Chris Lattnerbe207732007-09-30 00:47:20 +000068#include "llvm/ADT/DenseSet.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> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000115 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000116
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 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000671
672 // Calls to inline asm need to be added as well because the callee isn't
673 // referenced anywhere else.
674 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
675 Value *Callee = CI->getCalledValue();
676 if (isa<InlineAsm>(Callee))
677 ValueNodes[Callee] = NumObjects++;
678 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000679 }
680 }
681
682 // Now that we know how many objects to create, make them all now!
683 GraphNodes.resize(NumObjects);
684 NumNodes += NumObjects;
685}
686
687//===----------------------------------------------------------------------===//
688// Constraint Identification Phase
689//===----------------------------------------------------------------------===//
690
691/// getNodeForConstantPointer - Return the node corresponding to the constant
692/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000693unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000694 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
695
Chris Lattner267a1b02005-03-27 18:58:23 +0000696 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000697 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000698 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
699 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000700 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
701 switch (CE->getOpcode()) {
702 case Instruction::GetElementPtr:
703 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000704 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000705 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000706 case Instruction::BitCast:
707 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000708 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000709 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000710 assert(0);
711 }
712 } else {
713 assert(0 && "Unknown constant pointer!");
714 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000715 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000716}
717
718/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
719/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000720unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000721 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
722
723 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000724 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000725 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
726 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000727 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
728 switch (CE->getOpcode()) {
729 case Instruction::GetElementPtr:
730 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000731 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000732 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000733 case Instruction::BitCast:
734 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000735 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000736 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000737 assert(0);
738 }
739 } else {
740 assert(0 && "Unknown constant pointer!");
741 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000742 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000743}
744
745/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
746/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000747void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
748 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000749 if (C->getType()->isFirstClassType()) {
750 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000751 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
752 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000753 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000754 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
755 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000756 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000757 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000758 // If this is an array or struct, include constraints for each element.
759 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
760 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000761 AddGlobalInitializerConstraints(NodeIndex,
762 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000763 }
764}
765
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000766/// AddConstraintsForNonInternalLinkage - If this function does not have
767/// internal linkage, realize that we can't trust anything passed into or
768/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000769void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000770 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000771 if (isa<PointerType>(I->getType()))
772 // If this is an argument of an externally accessible function, the
773 // incoming pointer might point to anything.
774 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000775 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000776}
777
Chris Lattner8a446432005-03-29 06:09:07 +0000778/// AddConstraintsForCall - If this is a call to a "known" function, add the
779/// constraints and return true. If this is a call to an unknown function,
780/// return false.
781bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000782 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000783
784 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000785 if (F->getName() == "atoi" || F->getName() == "atof" ||
786 F->getName() == "atol" || F->getName() == "atoll" ||
787 F->getName() == "remove" || F->getName() == "unlink" ||
788 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000789 F->getName() == "llvm.memset.i32" ||
790 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000791 F->getName() == "strcmp" || F->getName() == "strncmp" ||
792 F->getName() == "execl" || F->getName() == "execlp" ||
793 F->getName() == "execle" || F->getName() == "execv" ||
794 F->getName() == "execvp" || F->getName() == "chmod" ||
795 F->getName() == "puts" || F->getName() == "write" ||
796 F->getName() == "open" || F->getName() == "create" ||
797 F->getName() == "truncate" || F->getName() == "chdir" ||
798 F->getName() == "mkdir" || F->getName() == "rmdir" ||
799 F->getName() == "read" || F->getName() == "pipe" ||
800 F->getName() == "wait" || F->getName() == "time" ||
801 F->getName() == "stat" || F->getName() == "fstat" ||
802 F->getName() == "lstat" || F->getName() == "strtod" ||
803 F->getName() == "strtof" || F->getName() == "strtold" ||
804 F->getName() == "fopen" || F->getName() == "fdopen" ||
805 F->getName() == "freopen" ||
806 F->getName() == "fflush" || F->getName() == "feof" ||
807 F->getName() == "fileno" || F->getName() == "clearerr" ||
808 F->getName() == "rewind" || F->getName() == "ftell" ||
809 F->getName() == "ferror" || F->getName() == "fgetc" ||
810 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
811 F->getName() == "fwrite" || F->getName() == "fread" ||
812 F->getName() == "fgets" || F->getName() == "ungetc" ||
813 F->getName() == "fputc" ||
814 F->getName() == "fputs" || F->getName() == "putc" ||
815 F->getName() == "ftell" || F->getName() == "rewind" ||
816 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
817 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
818 F->getName() == "printf" || F->getName() == "fprintf" ||
819 F->getName() == "sprintf" || F->getName() == "vprintf" ||
820 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
821 F->getName() == "scanf" || F->getName() == "fscanf" ||
822 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
823 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000824 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000825
Chris Lattner175b9632005-03-29 20:36:05 +0000826
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000827 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000828 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000829 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000830 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000831
832 // *Dest = *Src, which requires an artificial graph node to represent the
833 // constraint. It is broken up into *Dest = temp, temp = *Src
834 unsigned FirstArg = getNode(CS.getArgument(0));
835 unsigned SecondArg = getNode(CS.getArgument(1));
836 unsigned TempArg = GraphNodes.size();
837 GraphNodes.push_back(Node());
838 Constraints.push_back(Constraint(Constraint::Store,
839 FirstArg, TempArg));
840 Constraints.push_back(Constraint(Constraint::Load,
841 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000842 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000843 }
844
Chris Lattner77b50562005-03-29 20:04:24 +0000845 // Result = Arg0
846 if (F->getName() == "realloc" || F->getName() == "strchr" ||
847 F->getName() == "strrchr" || F->getName() == "strstr" ||
848 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000849 Constraints.push_back(Constraint(Constraint::Copy,
850 getNode(CS.getInstruction()),
851 getNode(CS.getArgument(0))));
852 return true;
853 }
854
855 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000856}
857
858
Chris Lattnere995a2a2004-05-23 21:00:47 +0000859
Daniel Berlinaad15882007-09-16 21:45:02 +0000860/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
861/// If this is used by anything complex (i.e., the address escapes), return
862/// true.
863bool Andersens::AnalyzeUsesOfFunction(Value *V) {
864
865 if (!isa<PointerType>(V->getType())) return true;
866
867 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
868 if (dyn_cast<LoadInst>(*UI)) {
869 return false;
870 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
871 if (V == SI->getOperand(1)) {
872 return false;
873 } else if (SI->getOperand(1)) {
874 return true; // Storing the pointer
875 }
876 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
877 if (AnalyzeUsesOfFunction(GEP)) return true;
878 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
879 // Make sure that this is just the function being called, not that it is
880 // passing into the function.
881 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
882 if (CI->getOperand(i) == V) return true;
883 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
884 // Make sure that this is just the function being called, not that it is
885 // passing into the function.
886 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
887 if (II->getOperand(i) == V) return true;
888 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
889 if (CE->getOpcode() == Instruction::GetElementPtr ||
890 CE->getOpcode() == Instruction::BitCast) {
891 if (AnalyzeUsesOfFunction(CE))
892 return true;
893 } else {
894 return true;
895 }
896 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
897 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
898 return true; // Allow comparison against null.
899 } else if (dyn_cast<FreeInst>(*UI)) {
900 return false;
901 } else {
902 return true;
903 }
904 return false;
905}
906
Chris Lattnere995a2a2004-05-23 21:00:47 +0000907/// CollectConstraints - This stage scans the program, adding a constraint to
908/// the Constraints list for each instruction in the program that induces a
909/// constraint, and setting up the initial points-to graph.
910///
911void Andersens::CollectConstraints(Module &M) {
912 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000913 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
914 UniversalSet));
915 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
916 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000917
918 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000919 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000920
921 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000922 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
923 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000924 // Associate the address of the global object as pointing to the memory for
925 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +0000926 unsigned ObjectIndex = getObject(I);
927 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000928 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000929 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
930 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000931
932 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000933 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +0000934 } else {
935 // If it doesn't have an initializer (i.e. it's defined in another
936 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +0000937 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
938 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000939 }
940 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000941
Chris Lattnere995a2a2004-05-23 21:00:47 +0000942 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000943 // Set up the return value node.
944 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000945 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000946 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +0000947 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000948
949 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000950 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
951 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000952 if (isa<PointerType>(I->getType()))
953 getNodeValue(*I);
954
Daniel Berlinaad15882007-09-16 21:45:02 +0000955 // At some point we should just add constraints for the escaping functions
956 // at solve time, but this slows down solving. For now, we simply mark
957 // address taken functions as escaping and treat them as external.
958 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000959 AddConstraintsForNonInternalLinkage(F);
960
Reid Spencer5cbf9852007-01-30 20:08:39 +0000961 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000962 // Scan the function body, creating a memory object for each heap/stack
963 // allocation in the body of the function and a node to represent all
964 // pointer values defined by instructions and used as operands.
965 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000966 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000967 // External functions that return pointers return the universal set.
968 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
969 Constraints.push_back(Constraint(Constraint::Copy,
970 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000971 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000972
973 // Any pointers that are passed into the function have the universal set
974 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000975 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
976 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000977 if (isa<PointerType>(I->getType())) {
978 // Pointers passed into external functions could have anything stored
979 // through them.
980 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000981 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000982 // Memory objects passed into external function calls can have the
983 // universal set point to them.
984 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +0000985 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +0000986 getNode(I)));
987 }
988
989 // If this is an external varargs function, it can also store pointers
990 // into any pointers passed through the varargs section.
991 if (F->getFunctionType()->isVarArg())
992 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000993 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000994 }
995 }
996 NumConstraints += Constraints.size();
997}
998
999
1000void Andersens::visitInstruction(Instruction &I) {
1001#ifdef NDEBUG
1002 return; // This function is just a big assert.
1003#endif
1004 if (isa<BinaryOperator>(I))
1005 return;
1006 // Most instructions don't have any effect on pointer values.
1007 switch (I.getOpcode()) {
1008 case Instruction::Br:
1009 case Instruction::Switch:
1010 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001011 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001012 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001013 case Instruction::ICmp:
1014 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001015 return;
1016 default:
1017 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001018 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001019 abort();
1020 }
1021}
1022
1023void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001024 unsigned ObjectIndex = getObject(&AI);
1025 GraphNodes[ObjectIndex].setValue(&AI);
1026 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1027 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001028}
1029
1030void Andersens::visitReturnInst(ReturnInst &RI) {
1031 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1032 // return V --> <Copy/retval{F}/v>
1033 Constraints.push_back(Constraint(Constraint::Copy,
1034 getReturnNode(RI.getParent()->getParent()),
1035 getNode(RI.getOperand(0))));
1036}
1037
1038void Andersens::visitLoadInst(LoadInst &LI) {
1039 if (isa<PointerType>(LI.getType()))
1040 // P1 = load P2 --> <Load/P1/P2>
1041 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1042 getNode(LI.getOperand(0))));
1043}
1044
1045void Andersens::visitStoreInst(StoreInst &SI) {
1046 if (isa<PointerType>(SI.getOperand(0)->getType()))
1047 // store P1, P2 --> <Store/P2/P1>
1048 Constraints.push_back(Constraint(Constraint::Store,
1049 getNode(SI.getOperand(1)),
1050 getNode(SI.getOperand(0))));
1051}
1052
1053void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1054 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1055 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1056 getNode(GEP.getOperand(0))));
1057}
1058
1059void Andersens::visitPHINode(PHINode &PN) {
1060 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001061 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001062 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1063 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1064 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1065 getNode(PN.getIncomingValue(i))));
1066 }
1067}
1068
1069void Andersens::visitCastInst(CastInst &CI) {
1070 Value *Op = CI.getOperand(0);
1071 if (isa<PointerType>(CI.getType())) {
1072 if (isa<PointerType>(Op->getType())) {
1073 // P1 = cast P2 --> <Copy/P1/P2>
1074 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1075 getNode(CI.getOperand(0))));
1076 } else {
1077 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001078#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001079 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001080 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001081#else
1082 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001083#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001084 }
1085 } else if (isa<PointerType>(Op->getType())) {
1086 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001087#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001088 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001089 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001090 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001091#else
1092 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001093#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001094 }
1095}
1096
1097void Andersens::visitSelectInst(SelectInst &SI) {
1098 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001099 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001100 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1101 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1102 getNode(SI.getOperand(1))));
1103 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1104 getNode(SI.getOperand(2))));
1105 }
1106}
1107
Chris Lattnere995a2a2004-05-23 21:00:47 +00001108void Andersens::visitVAArg(VAArgInst &I) {
1109 assert(0 && "vaarg not handled yet!");
1110}
1111
1112/// AddConstraintsForCall - Add constraints for a call with actual arguments
1113/// specified by CS to the function specified by F. Note that the types of
1114/// arguments might not match up in the case where this is an indirect call and
1115/// the function pointer has been casted. If this is the case, do something
1116/// reasonable.
1117void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001118 Value *CallValue = CS.getCalledValue();
1119 bool IsDeref = F == NULL;
1120
1121 // If this is a call to an external function, try to handle it directly to get
1122 // some taste of context sensitivity.
1123 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001124 return;
1125
Chris Lattnere995a2a2004-05-23 21:00:47 +00001126 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001127 unsigned CSN = getNode(CS.getInstruction());
1128 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1129 if (IsDeref)
1130 Constraints.push_back(Constraint(Constraint::Load, CSN,
1131 getNode(CallValue), CallReturnPos));
1132 else
1133 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1134 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001135 } else {
1136 // If the function returns a non-pointer value, handle this just like we
1137 // treat a nonpointer cast to pointer.
1138 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001139 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001140 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001141 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001142 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001143 UniversalSet,
1144 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001145 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001146
Chris Lattnere995a2a2004-05-23 21:00:47 +00001147 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinaad15882007-09-16 21:45:02 +00001148 if (F) {
1149 // Direct Call
1150 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1151 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1152 if (isa<PointerType>(AI->getType())) {
1153 if (isa<PointerType>((*ArgI)->getType())) {
1154 // Copy the actual argument into the formal argument.
1155 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1156 getNode(*ArgI)));
1157 } else {
1158 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1159 UniversalSet));
1160 }
1161 } else if (isa<PointerType>((*ArgI)->getType())) {
1162 Constraints.push_back(Constraint(Constraint::Copy,
1163 UniversalSet,
1164 getNode(*ArgI)));
1165 }
1166 } else {
1167 //Indirect Call
1168 unsigned ArgPos = CallFirstArgPos;
1169 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001170 if (isa<PointerType>((*ArgI)->getType())) {
1171 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001172 Constraints.push_back(Constraint(Constraint::Store,
1173 getNode(CallValue),
1174 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001175 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001176 Constraints.push_back(Constraint(Constraint::Store,
1177 getNode (CallValue),
1178 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001179 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001180 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001181 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001182 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001183 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001184 for (; ArgI != ArgE; ++ArgI)
1185 if (isa<PointerType>((*ArgI)->getType()))
1186 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1187 getNode(*ArgI)));
1188 // If more arguments are passed in than we track, just drop them on the floor.
1189}
1190
1191void Andersens::visitCallSite(CallSite CS) {
1192 if (isa<PointerType>(CS.getType()))
1193 getNodeValue(*CS.getInstruction());
1194
1195 if (Function *F = CS.getCalledFunction()) {
1196 AddConstraintsForCall(CS, F);
1197 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001198 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001199 }
1200}
1201
1202//===----------------------------------------------------------------------===//
1203// Constraint Solving Phase
1204//===----------------------------------------------------------------------===//
1205
1206/// intersects - Return true if the points-to set of this node intersects
1207/// with the points-to set of the specified node.
1208bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001209 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001210}
1211
1212/// intersectsIgnoring - Return true if the points-to set of this node
1213/// intersects with the points-to set of the specified node on any nodes
1214/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001215bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1216 // TODO: If we are only going to call this with the same value for Ignoring,
1217 // we should move the special values out of the points-to bitmap.
1218 bool WeHadIt = PointsTo->test(Ignoring);
1219 bool NHadIt = N->PointsTo->test(Ignoring);
1220 bool Result = false;
1221 if (WeHadIt)
1222 PointsTo->reset(Ignoring);
1223 if (NHadIt)
1224 N->PointsTo->reset(Ignoring);
1225 Result = PointsTo->intersects(N->PointsTo);
1226 if (WeHadIt)
1227 PointsTo->set(Ignoring);
1228 if (NHadIt)
1229 N->PointsTo->set(Ignoring);
1230 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001231}
1232
Daniel Berlind81ccc22007-09-24 19:45:49 +00001233void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001234#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001235 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001236#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001237}
1238
1239
1240/// Clump together address taken variables so that the points-to sets use up
1241/// less space and can be operated on faster.
1242
1243void Andersens::ClumpAddressTaken() {
1244#undef DEBUG_TYPE
1245#define DEBUG_TYPE "anders-aa-renumber"
1246 std::vector<unsigned> Translate;
1247 std::vector<Node> NewGraphNodes;
1248
1249 Translate.resize(GraphNodes.size());
1250 unsigned NewPos = 0;
1251
1252 for (unsigned i = 0; i < Constraints.size(); ++i) {
1253 Constraint &C = Constraints[i];
1254 if (C.Type == Constraint::AddressOf) {
1255 GraphNodes[C.Src].AddressTaken = true;
1256 }
1257 }
1258 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1259 unsigned Pos = NewPos++;
1260 Translate[i] = Pos;
1261 NewGraphNodes.push_back(GraphNodes[i]);
1262 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1263 }
1264
1265 // I believe this ends up being faster than making two vectors and splicing
1266 // them.
1267 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1268 if (GraphNodes[i].AddressTaken) {
1269 unsigned Pos = NewPos++;
1270 Translate[i] = Pos;
1271 NewGraphNodes.push_back(GraphNodes[i]);
1272 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1273 }
1274 }
1275
1276 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1277 if (!GraphNodes[i].AddressTaken) {
1278 unsigned Pos = NewPos++;
1279 Translate[i] = Pos;
1280 NewGraphNodes.push_back(GraphNodes[i]);
1281 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1282 }
1283 }
1284
1285 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1286 Iter != ValueNodes.end();
1287 ++Iter)
1288 Iter->second = Translate[Iter->second];
1289
1290 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1291 Iter != ObjectNodes.end();
1292 ++Iter)
1293 Iter->second = Translate[Iter->second];
1294
1295 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1296 Iter != ReturnNodes.end();
1297 ++Iter)
1298 Iter->second = Translate[Iter->second];
1299
1300 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1301 Iter != VarargNodes.end();
1302 ++Iter)
1303 Iter->second = Translate[Iter->second];
1304
1305 for (unsigned i = 0; i < Constraints.size(); ++i) {
1306 Constraint &C = Constraints[i];
1307 C.Src = Translate[C.Src];
1308 C.Dest = Translate[C.Dest];
1309 }
1310
1311 GraphNodes.swap(NewGraphNodes);
1312#undef DEBUG_TYPE
1313#define DEBUG_TYPE "anders-aa"
1314}
1315
1316/// The technique used here is described in "Exploiting Pointer and Location
1317/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1318/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1319/// and is equivalent to value numbering the collapsed constraint graph without
1320/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1321/// first order pointer dereferences and speed up/reduce memory usage of HU.
1322/// Running both is equivalent to HRU without the iteration
1323/// HVN in more detail:
1324/// Imagine the set of constraints was simply straight line code with no loops
1325/// (we eliminate cycles, so there are no loops), such as:
1326/// E = &D
1327/// E = &C
1328/// E = F
1329/// F = G
1330/// G = F
1331/// Applying value numbering to this code tells us:
1332/// G == F == E
1333///
1334/// For HVN, this is as far as it goes. We assign new value numbers to every
1335/// "address node", and every "reference node".
1336/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1337/// cycle must have the same value number since the = operation is really
1338/// inclusion, not overwrite), and value number nodes we receive points-to sets
1339/// before we value our own node.
1340/// The advantage of HU over HVN is that HU considers the inclusion property, so
1341/// that if you have
1342/// E = &D
1343/// E = &C
1344/// E = F
1345/// F = G
1346/// F = &D
1347/// G = F
1348/// HU will determine that G == F == E. HVN will not, because it cannot prove
1349/// that the points to information ends up being the same because they all
1350/// receive &D from E anyway.
1351
1352void Andersens::HVN() {
1353 DOUT << "Beginning HVN\n";
1354 // Build a predecessor graph. This is like our constraint graph with the
1355 // edges going in the opposite direction, and there are edges for all the
1356 // constraints, instead of just copy constraints. We also build implicit
1357 // edges for constraints are implied but not explicit. I.E for the constraint
1358 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1359 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1360 Constraint &C = Constraints[i];
1361 if (C.Type == Constraint::AddressOf) {
1362 GraphNodes[C.Src].AddressTaken = true;
1363 GraphNodes[C.Src].Direct = false;
1364
1365 // Dest = &src edge
1366 unsigned AdrNode = C.Src + FirstAdrNode;
1367 if (!GraphNodes[C.Dest].PredEdges)
1368 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1369 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1370
1371 // *Dest = src edge
1372 unsigned RefNode = C.Dest + FirstRefNode;
1373 if (!GraphNodes[RefNode].ImplicitPredEdges)
1374 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1375 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1376 } else if (C.Type == Constraint::Load) {
1377 if (C.Offset == 0) {
1378 // dest = *src edge
1379 if (!GraphNodes[C.Dest].PredEdges)
1380 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1381 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1382 } else {
1383 GraphNodes[C.Dest].Direct = false;
1384 }
1385 } else if (C.Type == Constraint::Store) {
1386 if (C.Offset == 0) {
1387 // *dest = src edge
1388 unsigned RefNode = C.Dest + FirstRefNode;
1389 if (!GraphNodes[RefNode].PredEdges)
1390 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1391 GraphNodes[RefNode].PredEdges->set(C.Src);
1392 }
1393 } else {
1394 // Dest = Src edge and *Dest = *Src edge
1395 if (!GraphNodes[C.Dest].PredEdges)
1396 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1397 GraphNodes[C.Dest].PredEdges->set(C.Src);
1398 unsigned RefNode = C.Dest + FirstRefNode;
1399 if (!GraphNodes[RefNode].ImplicitPredEdges)
1400 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1401 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1402 }
1403 }
1404 PEClass = 1;
1405 // Do SCC finding first to condense our predecessor graph
1406 DFSNumber = 0;
1407 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1408 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1409 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1410
1411 for (unsigned i = 0; i < FirstRefNode; ++i) {
1412 unsigned Node = VSSCCRep[i];
1413 if (!Node2Visited[Node])
1414 HVNValNum(Node);
1415 }
1416 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1417 Iter != Set2PEClass.end();
1418 ++Iter)
1419 delete Iter->first;
1420 Set2PEClass.clear();
1421 Node2DFS.clear();
1422 Node2Deleted.clear();
1423 Node2Visited.clear();
1424 DOUT << "Finished HVN\n";
1425
1426}
1427
1428/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1429/// same time because it's easy.
1430void Andersens::HVNValNum(unsigned NodeIndex) {
1431 unsigned MyDFS = DFSNumber++;
1432 Node *N = &GraphNodes[NodeIndex];
1433 Node2Visited[NodeIndex] = true;
1434 Node2DFS[NodeIndex] = MyDFS;
1435
1436 // First process all our explicit edges
1437 if (N->PredEdges)
1438 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1439 Iter != N->PredEdges->end();
1440 ++Iter) {
1441 unsigned j = VSSCCRep[*Iter];
1442 if (!Node2Deleted[j]) {
1443 if (!Node2Visited[j])
1444 HVNValNum(j);
1445 if (Node2DFS[NodeIndex] > Node2DFS[j])
1446 Node2DFS[NodeIndex] = Node2DFS[j];
1447 }
1448 }
1449
1450 // Now process all the implicit edges
1451 if (N->ImplicitPredEdges)
1452 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1453 Iter != N->ImplicitPredEdges->end();
1454 ++Iter) {
1455 unsigned j = VSSCCRep[*Iter];
1456 if (!Node2Deleted[j]) {
1457 if (!Node2Visited[j])
1458 HVNValNum(j);
1459 if (Node2DFS[NodeIndex] > Node2DFS[j])
1460 Node2DFS[NodeIndex] = Node2DFS[j];
1461 }
1462 }
1463
1464 // See if we found any cycles
1465 if (MyDFS == Node2DFS[NodeIndex]) {
1466 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1467 unsigned CycleNodeIndex = SCCStack.top();
1468 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1469 VSSCCRep[CycleNodeIndex] = NodeIndex;
1470 // Unify the nodes
1471 N->Direct &= CycleNode->Direct;
1472
1473 if (CycleNode->PredEdges) {
1474 if (!N->PredEdges)
1475 N->PredEdges = new SparseBitVector<>;
1476 *(N->PredEdges) |= CycleNode->PredEdges;
1477 delete CycleNode->PredEdges;
1478 CycleNode->PredEdges = NULL;
1479 }
1480 if (CycleNode->ImplicitPredEdges) {
1481 if (!N->ImplicitPredEdges)
1482 N->ImplicitPredEdges = new SparseBitVector<>;
1483 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1484 delete CycleNode->ImplicitPredEdges;
1485 CycleNode->ImplicitPredEdges = NULL;
1486 }
1487
1488 SCCStack.pop();
1489 }
1490
1491 Node2Deleted[NodeIndex] = true;
1492
1493 if (!N->Direct) {
1494 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1495 return;
1496 }
1497
1498 // Collect labels of successor nodes
1499 bool AllSame = true;
1500 unsigned First = ~0;
1501 SparseBitVector<> *Labels = new SparseBitVector<>;
1502 bool Used = false;
1503
1504 if (N->PredEdges)
1505 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1506 Iter != N->PredEdges->end();
1507 ++Iter) {
1508 unsigned j = VSSCCRep[*Iter];
1509 unsigned Label = GraphNodes[j].PointerEquivLabel;
1510 // Ignore labels that are equal to us or non-pointers
1511 if (j == NodeIndex || Label == 0)
1512 continue;
1513 if (First == (unsigned)~0)
1514 First = Label;
1515 else if (First != Label)
1516 AllSame = false;
1517 Labels->set(Label);
1518 }
1519
1520 // We either have a non-pointer, a copy of an existing node, or a new node.
1521 // Assign the appropriate pointer equivalence label.
1522 if (Labels->empty()) {
1523 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1524 } else if (AllSame) {
1525 GraphNodes[NodeIndex].PointerEquivLabel = First;
1526 } else {
1527 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1528 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1529 unsigned EquivClass = PEClass++;
1530 Set2PEClass[Labels] = EquivClass;
1531 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1532 Used = true;
1533 }
1534 }
1535 if (!Used)
1536 delete Labels;
1537 } else {
1538 SCCStack.push(NodeIndex);
1539 }
1540}
1541
1542/// The technique used here is described in "Exploiting Pointer and Location
1543/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1544/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1545/// and is equivalent to value numbering the collapsed constraint graph
1546/// including evaluating unions.
1547void Andersens::HU() {
1548 DOUT << "Beginning HU\n";
1549 // Build a predecessor graph. This is like our constraint graph with the
1550 // edges going in the opposite direction, and there are edges for all the
1551 // constraints, instead of just copy constraints. We also build implicit
1552 // edges for constraints are implied but not explicit. I.E for the constraint
1553 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1554 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1555 Constraint &C = Constraints[i];
1556 if (C.Type == Constraint::AddressOf) {
1557 GraphNodes[C.Src].AddressTaken = true;
1558 GraphNodes[C.Src].Direct = false;
1559
1560 GraphNodes[C.Dest].PointsTo->set(C.Src);
1561 // *Dest = src edge
1562 unsigned RefNode = C.Dest + FirstRefNode;
1563 if (!GraphNodes[RefNode].ImplicitPredEdges)
1564 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1565 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1566 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1567 } else if (C.Type == Constraint::Load) {
1568 if (C.Offset == 0) {
1569 // dest = *src edge
1570 if (!GraphNodes[C.Dest].PredEdges)
1571 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1572 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1573 } else {
1574 GraphNodes[C.Dest].Direct = false;
1575 }
1576 } else if (C.Type == Constraint::Store) {
1577 if (C.Offset == 0) {
1578 // *dest = src edge
1579 unsigned RefNode = C.Dest + FirstRefNode;
1580 if (!GraphNodes[RefNode].PredEdges)
1581 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1582 GraphNodes[RefNode].PredEdges->set(C.Src);
1583 }
1584 } else {
1585 // Dest = Src edge and *Dest = *Src edg
1586 if (!GraphNodes[C.Dest].PredEdges)
1587 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1588 GraphNodes[C.Dest].PredEdges->set(C.Src);
1589 unsigned RefNode = C.Dest + FirstRefNode;
1590 if (!GraphNodes[RefNode].ImplicitPredEdges)
1591 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1592 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1593 }
1594 }
1595 PEClass = 1;
1596 // Do SCC finding first to condense our predecessor graph
1597 DFSNumber = 0;
1598 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1599 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1600 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1601
1602 for (unsigned i = 0; i < FirstRefNode; ++i) {
1603 if (FindNode(i) == i) {
1604 unsigned Node = VSSCCRep[i];
1605 if (!Node2Visited[Node])
1606 Condense(Node);
1607 }
1608 }
1609
1610 // Reset tables for actual labeling
1611 Node2DFS.clear();
1612 Node2Visited.clear();
1613 Node2Deleted.clear();
1614 // Pre-grow our densemap so that we don't get really bad behavior
1615 Set2PEClass.resize(GraphNodes.size());
1616
1617 // Visit the condensed graph and generate pointer equivalence labels.
1618 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1619 for (unsigned i = 0; i < FirstRefNode; ++i) {
1620 if (FindNode(i) == i) {
1621 unsigned Node = VSSCCRep[i];
1622 if (!Node2Visited[Node])
1623 HUValNum(Node);
1624 }
1625 }
1626 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1627 Set2PEClass.clear();
1628 DOUT << "Finished HU\n";
1629}
1630
1631
1632/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1633void Andersens::Condense(unsigned NodeIndex) {
1634 unsigned MyDFS = DFSNumber++;
1635 Node *N = &GraphNodes[NodeIndex];
1636 Node2Visited[NodeIndex] = true;
1637 Node2DFS[NodeIndex] = MyDFS;
1638
1639 // First process all our explicit edges
1640 if (N->PredEdges)
1641 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1642 Iter != N->PredEdges->end();
1643 ++Iter) {
1644 unsigned j = VSSCCRep[*Iter];
1645 if (!Node2Deleted[j]) {
1646 if (!Node2Visited[j])
1647 Condense(j);
1648 if (Node2DFS[NodeIndex] > Node2DFS[j])
1649 Node2DFS[NodeIndex] = Node2DFS[j];
1650 }
1651 }
1652
1653 // Now process all the implicit edges
1654 if (N->ImplicitPredEdges)
1655 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1656 Iter != N->ImplicitPredEdges->end();
1657 ++Iter) {
1658 unsigned j = VSSCCRep[*Iter];
1659 if (!Node2Deleted[j]) {
1660 if (!Node2Visited[j])
1661 Condense(j);
1662 if (Node2DFS[NodeIndex] > Node2DFS[j])
1663 Node2DFS[NodeIndex] = Node2DFS[j];
1664 }
1665 }
1666
1667 // See if we found any cycles
1668 if (MyDFS == Node2DFS[NodeIndex]) {
1669 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1670 unsigned CycleNodeIndex = SCCStack.top();
1671 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1672 VSSCCRep[CycleNodeIndex] = NodeIndex;
1673 // Unify the nodes
1674 N->Direct &= CycleNode->Direct;
1675
1676 *(N->PointsTo) |= CycleNode->PointsTo;
1677 delete CycleNode->PointsTo;
1678 CycleNode->PointsTo = NULL;
1679 if (CycleNode->PredEdges) {
1680 if (!N->PredEdges)
1681 N->PredEdges = new SparseBitVector<>;
1682 *(N->PredEdges) |= CycleNode->PredEdges;
1683 delete CycleNode->PredEdges;
1684 CycleNode->PredEdges = NULL;
1685 }
1686 if (CycleNode->ImplicitPredEdges) {
1687 if (!N->ImplicitPredEdges)
1688 N->ImplicitPredEdges = new SparseBitVector<>;
1689 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1690 delete CycleNode->ImplicitPredEdges;
1691 CycleNode->ImplicitPredEdges = NULL;
1692 }
1693 SCCStack.pop();
1694 }
1695
1696 Node2Deleted[NodeIndex] = true;
1697
1698 // Set up number of incoming edges for other nodes
1699 if (N->PredEdges)
1700 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1701 Iter != N->PredEdges->end();
1702 ++Iter)
1703 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1704 } else {
1705 SCCStack.push(NodeIndex);
1706 }
1707}
1708
1709void Andersens::HUValNum(unsigned NodeIndex) {
1710 Node *N = &GraphNodes[NodeIndex];
1711 Node2Visited[NodeIndex] = true;
1712
1713 // Eliminate dereferences of non-pointers for those non-pointers we have
1714 // already identified. These are ref nodes whose non-ref node:
1715 // 1. Has already been visited determined to point to nothing (and thus, a
1716 // dereference of it must point to nothing)
1717 // 2. Any direct node with no predecessor edges in our graph and with no
1718 // points-to set (since it can't point to anything either, being that it
1719 // receives no points-to sets and has none).
1720 if (NodeIndex >= FirstRefNode) {
1721 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1722 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1723 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1724 && GraphNodes[j].PointsTo->empty())){
1725 return;
1726 }
1727 }
1728 // Process all our explicit edges
1729 if (N->PredEdges)
1730 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1731 Iter != N->PredEdges->end();
1732 ++Iter) {
1733 unsigned j = VSSCCRep[*Iter];
1734 if (!Node2Visited[j])
1735 HUValNum(j);
1736
1737 // If this edge turned out to be the same as us, or got no pointer
1738 // equivalence label (and thus points to nothing) , just decrement our
1739 // incoming edges and continue.
1740 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1741 --GraphNodes[j].NumInEdges;
1742 continue;
1743 }
1744
1745 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1746
1747 // If we didn't end up storing this in the hash, and we're done with all
1748 // the edges, we don't need the points-to set anymore.
1749 --GraphNodes[j].NumInEdges;
1750 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1751 delete GraphNodes[j].PointsTo;
1752 GraphNodes[j].PointsTo = NULL;
1753 }
1754 }
1755 // If this isn't a direct node, generate a fresh variable.
1756 if (!N->Direct) {
1757 N->PointsTo->set(FirstRefNode + NodeIndex);
1758 }
1759
1760 // See If we have something equivalent to us, if not, generate a new
1761 // equivalence class.
1762 if (N->PointsTo->empty()) {
1763 delete N->PointsTo;
1764 N->PointsTo = NULL;
1765 } else {
1766 if (N->Direct) {
1767 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1768 if (N->PointerEquivLabel == 0) {
1769 unsigned EquivClass = PEClass++;
1770 N->StoredInHash = true;
1771 Set2PEClass[N->PointsTo] = EquivClass;
1772 N->PointerEquivLabel = EquivClass;
1773 }
1774 } else {
1775 N->PointerEquivLabel = PEClass++;
1776 }
1777 }
1778}
1779
1780/// Rewrite our list of constraints so that pointer equivalent nodes are
1781/// replaced by their the pointer equivalence class representative.
1782void Andersens::RewriteConstraints() {
1783 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001784 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001785
1786 PEClass2Node.clear();
1787 PENLEClass2Node.clear();
1788
1789 // We may have from 1 to Graphnodes + 1 equivalence classes.
1790 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1791 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1792
1793 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1794 // nodes, and rewriting constraints to use the representative nodes.
1795 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1796 Constraint &C = Constraints[i];
1797 unsigned RHSNode = FindNode(C.Src);
1798 unsigned LHSNode = FindNode(C.Dest);
1799 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1800 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1801
1802 // First we try to eliminate constraints for things we can prove don't point
1803 // to anything.
1804 if (LHSLabel == 0) {
1805 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1806 DOUT << " is a non-pointer, ignoring constraint.\n";
1807 continue;
1808 }
1809 if (RHSLabel == 0) {
1810 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1811 DOUT << " is a non-pointer, ignoring constraint.\n";
1812 continue;
1813 }
1814 // This constraint may be useless, and it may become useless as we translate
1815 // it.
1816 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1817 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001818
Daniel Berlind81ccc22007-09-24 19:45:49 +00001819 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1820 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001821 if (C.Src == C.Dest && C.Type == Constraint::Copy
Chris Lattnerbe207732007-09-30 00:47:20 +00001822 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001823 continue;
1824
Chris Lattnerbe207732007-09-30 00:47:20 +00001825 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001826 NewConstraints.push_back(C);
1827 }
1828 Constraints.swap(NewConstraints);
1829 PEClass2Node.clear();
1830}
1831
1832/// See if we have a node that is pointer equivalent to the one being asked
1833/// about, and if so, unite them and return the equivalent node. Otherwise,
1834/// return the original node.
1835unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1836 unsigned NodeLabel) {
1837 if (!GraphNodes[NodeIndex].AddressTaken) {
1838 if (PEClass2Node[NodeLabel] != -1) {
1839 // We found an existing node with the same pointer label, so unify them.
1840 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex);
1841 } else {
1842 PEClass2Node[NodeLabel] = NodeIndex;
1843 PENLEClass2Node[NodeLabel] = NodeIndex;
1844 }
1845 } else if (PENLEClass2Node[NodeLabel] == -1) {
1846 PENLEClass2Node[NodeLabel] = NodeIndex;
1847 }
1848
1849 return NodeIndex;
1850}
1851
1852void Andersens::PrintLabels() {
1853 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1854 if (i < FirstRefNode) {
1855 PrintNode(&GraphNodes[i]);
1856 } else if (i < FirstAdrNode) {
1857 DOUT << "REF(";
1858 PrintNode(&GraphNodes[i-FirstRefNode]);
1859 DOUT <<")";
1860 } else {
1861 DOUT << "ADR(";
1862 PrintNode(&GraphNodes[i-FirstAdrNode]);
1863 DOUT <<")";
1864 }
1865
1866 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1867 << " and SCC rep " << VSSCCRep[i]
1868 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1869 << "\n";
1870 }
1871}
1872
1873/// Optimize the constraints by performing offline variable substitution and
1874/// other optimizations.
1875void Andersens::OptimizeConstraints() {
1876 DOUT << "Beginning constraint optimization\n";
1877
1878 // Function related nodes need to stay in the same relative position and can't
1879 // be location equivalent.
1880 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1881 Iter != MaxK.end();
1882 ++Iter) {
1883 for (unsigned i = Iter->first;
1884 i != Iter->first + Iter->second;
1885 ++i) {
1886 GraphNodes[i].AddressTaken = true;
1887 GraphNodes[i].Direct = false;
1888 }
1889 }
1890
1891 ClumpAddressTaken();
1892 FirstRefNode = GraphNodes.size();
1893 FirstAdrNode = FirstRefNode + GraphNodes.size();
1894 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
1895 Node(false));
1896 VSSCCRep.resize(GraphNodes.size());
1897 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1898 VSSCCRep[i] = i;
1899 }
1900 HVN();
1901 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1902 Node *N = &GraphNodes[i];
1903 delete N->PredEdges;
1904 N->PredEdges = NULL;
1905 delete N->ImplicitPredEdges;
1906 N->ImplicitPredEdges = NULL;
1907 }
1908#undef DEBUG_TYPE
1909#define DEBUG_TYPE "anders-aa-labels"
1910 DEBUG(PrintLabels());
1911#undef DEBUG_TYPE
1912#define DEBUG_TYPE "anders-aa"
1913 RewriteConstraints();
1914 // Delete the adr nodes.
1915 GraphNodes.resize(FirstRefNode * 2);
1916
1917 // Now perform HU
1918 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1919 Node *N = &GraphNodes[i];
1920 if (FindNode(i) == i) {
1921 N->PointsTo = new SparseBitVector<>;
1922 N->PointedToBy = new SparseBitVector<>;
1923 // Reset our labels
1924 }
1925 VSSCCRep[i] = i;
1926 N->PointerEquivLabel = 0;
1927 }
1928 HU();
1929#undef DEBUG_TYPE
1930#define DEBUG_TYPE "anders-aa-labels"
1931 DEBUG(PrintLabels());
1932#undef DEBUG_TYPE
1933#define DEBUG_TYPE "anders-aa"
1934 RewriteConstraints();
1935 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1936 if (FindNode(i) == i) {
1937 Node *N = &GraphNodes[i];
1938 delete N->PointsTo;
1939 delete N->PredEdges;
1940 delete N->ImplicitPredEdges;
1941 delete N->PointedToBy;
1942 }
1943 }
1944 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
1945 DOUT << "Finished constraint optimization\n";
1946 FirstRefNode = 0;
1947 FirstAdrNode = 0;
1948}
1949
1950/// Unite pointer but not location equivalent variables, now that the constraint
1951/// graph is built.
1952void Andersens::UnitePointerEquivalences() {
1953 DOUT << "Uniting remaining pointer equivalences\n";
1954 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1955 if (GraphNodes[i].AddressTaken && GraphNodes[i].NodeRep == SelfRep) {
1956 unsigned Label = GraphNodes[i].PointerEquivLabel;
1957
1958 if (Label && PENLEClass2Node[Label] != -1)
1959 UniteNodes(i, PENLEClass2Node[Label]);
1960 }
1961 }
1962 DOUT << "Finished remaining pointer equivalences\n";
1963 PENLEClass2Node.clear();
1964}
1965
1966/// Create the constraint graph used for solving points-to analysis.
1967///
Daniel Berlinaad15882007-09-16 21:45:02 +00001968void Andersens::CreateConstraintGraph() {
1969 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1970 Constraint &C = Constraints[i];
1971 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1972 if (C.Type == Constraint::AddressOf)
1973 GraphNodes[C.Dest].PointsTo->set(C.Src);
1974 else if (C.Type == Constraint::Load)
1975 GraphNodes[C.Src].Constraints.push_back(C);
1976 else if (C.Type == Constraint::Store)
1977 GraphNodes[C.Dest].Constraints.push_back(C);
1978 else if (C.Offset != 0)
1979 GraphNodes[C.Src].Constraints.push_back(C);
1980 else
1981 GraphNodes[C.Src].Edges->set(C.Dest);
1982 }
1983}
1984
1985// Perform cycle detection, DFS, and RPO finding.
1986void Andersens::QueryNode(unsigned Node) {
1987 assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1988 unsigned OurDFS = ++DFSNumber;
1989 SparseBitVector<> ToErase;
1990 SparseBitVector<> NewEdges;
1991 Node2DFS[Node] = OurDFS;
1992
1993 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1994 bi != GraphNodes[Node].Edges->end();
1995 ++bi) {
1996 unsigned RepNode = FindNode(*bi);
1997 // If we are going to add an edge to repnode, we have no need for the edge
1998 // to e anymore.
1999 if (RepNode != *bi && NewEdges.test(RepNode)){
2000 ToErase.set(*bi);
2001 continue;
2002 }
2003
2004 // Continue about our DFS.
2005 if (!Node2Deleted[RepNode]){
2006 if (Node2DFS[RepNode] == 0) {
2007 QueryNode(RepNode);
2008 // May have been changed by query
2009 RepNode = FindNode(RepNode);
2010 }
2011 if (Node2DFS[RepNode] < Node2DFS[Node])
2012 Node2DFS[Node] = Node2DFS[RepNode];
2013 }
2014 // We may have just discovered that e belongs to a cycle, in which case we
2015 // can also erase it.
2016 if (RepNode != *bi) {
2017 ToErase.set(*bi);
2018 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002019 }
2020 }
2021
Daniel Berlinaad15882007-09-16 21:45:02 +00002022 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2023 GraphNodes[Node].Edges |= NewEdges;
2024
2025 // If this node is a root of a non-trivial SCC, place it on our worklist to be
2026 // processed
2027 if (OurDFS == Node2DFS[Node]) {
2028 bool Changed = false;
2029 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
2030 Node = UniteNodes(Node, FindNode(SCCStack.top()));
2031
2032 SCCStack.pop();
2033 Changed = true;
2034 }
2035 Node2Deleted[Node] = true;
2036 RPONumber++;
2037
2038 Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
2039 Node2Topo[Node] = GraphNodes.size() - RPONumber;
2040 if (Changed)
2041 GraphNodes[Node].Changed = true;
2042 } else {
2043 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002044 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002045}
2046
2047
2048/// SolveConstraints - This stage iteratively processes the constraints list
2049/// propagating constraints (adding edges to the Nodes in the points-to graph)
2050/// until a fixed point is reached.
2051///
2052void Andersens::SolveConstraints() {
2053 bool Changed = true;
2054 unsigned Iteration = 0;
Daniel Berlinaad15882007-09-16 21:45:02 +00002055
Daniel Berlind81ccc22007-09-24 19:45:49 +00002056 OptimizeConstraints();
2057#undef DEBUG_TYPE
2058#define DEBUG_TYPE "anders-aa-constraints"
2059 DEBUG(PrintConstraints());
2060#undef DEBUG_TYPE
2061#define DEBUG_TYPE "anders-aa"
2062
Daniel Berlinaad15882007-09-16 21:45:02 +00002063 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2064 Node *N = &GraphNodes[i];
2065 N->PointsTo = new SparseBitVector<>;
2066 N->OldPointsTo = new SparseBitVector<>;
2067 N->Edges = new SparseBitVector<>;
2068 }
2069 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002070 UnitePointerEquivalences();
2071 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlinaad15882007-09-16 21:45:02 +00002072 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2073 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002074 Node2DFS.clear();
2075 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002076 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2077 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2078 DFSNumber = 0;
2079 RPONumber = 0;
2080 // Order graph and mark starting nodes as changed.
2081 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2082 unsigned N = FindNode(i);
2083 Node *INode = &GraphNodes[i];
2084 if (Node2DFS[N] == 0) {
2085 QueryNode(N);
2086 // Mark as changed if it's a representation and can contribute to the
2087 // calculation right now.
2088 if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
2089 && (!INode->Edges->empty() || !INode->Constraints.empty()))
2090 INode->Changed = true;
2091 }
2092 }
2093
2094 do {
Daniel Berlinc6d93982007-09-16 23:59:53 +00002095 Changed = false;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002096 ++NumIters;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002097 DOUT << "Starting iteration #" << Iteration++ << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002098 // TODO: In the microoptimization category, we could just make Topo2Node
2099 // a fast map and thus only contain the visited nodes.
2100 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2101 unsigned CurrNodeIndex = Topo2Node[i];
2102 Node *CurrNode;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002103
Daniel Berlinaad15882007-09-16 21:45:02 +00002104 // We may not revisit all nodes on every iteration
2105 if (CurrNodeIndex == Unvisited)
2106 continue;
2107 CurrNode = &GraphNodes[CurrNodeIndex];
2108 // See if this is a node we need to process on this iteration
2109 if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
2110 continue;
2111 CurrNode->Changed = false;
2112
2113 // Figure out the changed points to bits
2114 SparseBitVector<> CurrPointsTo;
2115 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2116 CurrNode->OldPointsTo);
2117 if (CurrPointsTo.empty()){
2118 continue;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002119 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002120 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002121
Daniel Berlinaad15882007-09-16 21:45:02 +00002122 /* Now process the constraints for this node. */
2123 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2124 li != CurrNode->Constraints.end(); ) {
2125 li->Src = FindNode(li->Src);
2126 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002127
Daniel Berlinaad15882007-09-16 21:45:02 +00002128 // TODO: We could delete redundant constraints here.
2129 // Src and Dest will be the vars we are going to process.
2130 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002131 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002132 // Load constraints say that every member of our RHS solution has K
2133 // added to it, and that variable gets an edge to LHS. We also union
2134 // RHS+K's solution into the LHS solution.
2135 // Store constraints say that every member of our LHS solution has K
2136 // added to it, and that variable gets an edge from RHS. We also union
2137 // RHS's solution into the LHS+K solution.
2138 unsigned *Src;
2139 unsigned *Dest;
2140 unsigned K = li->Offset;
2141 unsigned CurrMember;
2142 if (li->Type == Constraint::Load) {
2143 Src = &CurrMember;
2144 Dest = &li->Dest;
2145 } else if (li->Type == Constraint::Store) {
2146 Src = &li->Src;
2147 Dest = &CurrMember;
2148 } else {
2149 // TODO Handle offseted copy constraint
2150 li++;
2151 continue;
2152 }
2153 // TODO: hybrid cycle detection would go here, we should check
2154 // if it was a statically detected offline equivalence that
2155 // involves pointers , and if so, remove the redundant constraints.
Chris Lattnere995a2a2004-05-23 21:00:47 +00002156
Daniel Berlinaad15882007-09-16 21:45:02 +00002157 const SparseBitVector<> &Solution = CurrPointsTo;
2158
2159 for (SparseBitVector<>::iterator bi = Solution.begin();
2160 bi != Solution.end();
2161 ++bi) {
2162 CurrMember = *bi;
2163
2164 // Need to increment the member by K since that is where we are
Daniel Berlind81ccc22007-09-24 19:45:49 +00002165 // supposed to copy to/from. Note that in positive weight cycles,
2166 // which occur in address taking of fields, K can go past
2167 // MaxK[CurrMember] elements, even though that is all it could point
2168 // to.
Daniel Berlinaad15882007-09-16 21:45:02 +00002169 if (K > 0 && K > MaxK[CurrMember])
2170 continue;
2171 else
2172 CurrMember = FindNode(CurrMember + K);
2173
2174 // Add an edge to the graph, so we can just do regular bitmap ior next
2175 // time. It may also let us notice a cycle.
Daniel Berlinc6d93982007-09-16 23:59:53 +00002176 if (GraphNodes[*Src].Edges->test_and_set(*Dest)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002177 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
2178 GraphNodes[*Dest].Changed = true;
2179 // If we changed a node we've already processed, we need another
2180 // iteration.
2181 if (Node2Topo[*Dest] <= i)
2182 Changed = true;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002183 }
2184 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002185 }
2186 li++;
2187 }
2188 SparseBitVector<> NewEdges;
2189 SparseBitVector<> ToErase;
2190
2191 // Now all we have left to do is propagate points-to info along the
2192 // edges, erasing the redundant edges.
2193
2194
2195 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2196 bi != CurrNode->Edges->end();
2197 ++bi) {
2198
2199 unsigned DestVar = *bi;
2200 unsigned Rep = FindNode(DestVar);
2201
2202 // If we ended up with this node as our destination, or we've already
2203 // got an edge for the representative, delete the current edge.
2204 if (Rep == CurrNodeIndex ||
2205 (Rep != DestVar && NewEdges.test(Rep))) {
2206 ToErase.set(DestVar);
2207 continue;
2208 }
2209 // Union the points-to sets into the dest
2210 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2211 GraphNodes[Rep].Changed = true;
2212 if (Node2Topo[Rep] <= i)
2213 Changed = true;
2214 }
2215 // If this edge's destination was collapsed, rewrite the edge.
2216 if (Rep != DestVar) {
2217 ToErase.set(DestVar);
2218 NewEdges.set(Rep);
2219 }
2220 }
2221 CurrNode->Edges->intersectWithComplement(ToErase);
2222 CurrNode->Edges |= NewEdges;
2223 }
2224 if (Changed) {
2225 DFSNumber = RPONumber = 0;
2226 Node2Deleted.clear();
2227 Topo2Node.clear();
2228 Node2Topo.clear();
2229 Node2DFS.clear();
2230 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2231 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2232 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2233 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2234 // Rediscover the DFS/Topo ordering, and cycle detect.
2235 for (unsigned j = 0; j < GraphNodes.size(); j++) {
2236 unsigned JRep = FindNode(j);
2237 if (Node2DFS[JRep] == 0)
2238 QueryNode(JRep);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002239 }
2240 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002241
2242 } while (Changed);
2243
2244 Node2Topo.clear();
2245 Topo2Node.clear();
2246 Node2DFS.clear();
2247 Node2Deleted.clear();
2248 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2249 Node *N = &GraphNodes[i];
2250 delete N->OldPointsTo;
2251 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002252 }
2253}
2254
Daniel Berlinaad15882007-09-16 21:45:02 +00002255//===----------------------------------------------------------------------===//
2256// Union-Find
2257//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002258
Daniel Berlinaad15882007-09-16 21:45:02 +00002259// Unite nodes First and Second, returning the one which is now the
2260// representative node. First and Second are indexes into GraphNodes
2261unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
2262 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2263 "Attempting to merge nodes that don't exist");
2264 // TODO: implement union by rank
2265 Node *FirstNode = &GraphNodes[First];
2266 Node *SecondNode = &GraphNodes[Second];
2267
2268 assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
2269 "Trying to unite two non-representative nodes!");
2270 if (First == Second)
2271 return First;
2272
2273 SecondNode->NodeRep = First;
2274 FirstNode->Changed |= SecondNode->Changed;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002275 if (FirstNode->PointsTo && SecondNode->PointsTo)
2276 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2277 if (FirstNode->Edges && SecondNode->Edges)
2278 FirstNode->Edges |= *(SecondNode->Edges);
2279 if (!FirstNode->Constraints.empty() && !SecondNode->Constraints.empty())
2280 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2281 SecondNode->Constraints);
2282 if (FirstNode->OldPointsTo) {
2283 delete FirstNode->OldPointsTo;
2284 FirstNode->OldPointsTo = new SparseBitVector<>;
2285 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002286
2287 // Destroy interesting parts of the merged-from node.
2288 delete SecondNode->OldPointsTo;
2289 delete SecondNode->Edges;
2290 delete SecondNode->PointsTo;
2291 SecondNode->Edges = NULL;
2292 SecondNode->PointsTo = NULL;
2293 SecondNode->OldPointsTo = NULL;
2294
2295 NumUnified++;
2296 DOUT << "Unified Node ";
2297 DEBUG(PrintNode(FirstNode));
2298 DOUT << " and Node ";
2299 DEBUG(PrintNode(SecondNode));
2300 DOUT << "\n";
2301
2302 // TODO: Handle SDT
2303 return First;
2304}
2305
2306// Find the index into GraphNodes of the node representing Node, performing
2307// path compression along the way
2308unsigned Andersens::FindNode(unsigned NodeIndex) {
2309 assert (NodeIndex < GraphNodes.size()
2310 && "Attempting to find a node that can't exist");
2311 Node *N = &GraphNodes[NodeIndex];
2312 if (N->NodeRep == SelfRep)
2313 return NodeIndex;
2314 else
2315 return (N->NodeRep = FindNode(N->NodeRep));
2316}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002317
2318//===----------------------------------------------------------------------===//
2319// Debugging Output
2320//===----------------------------------------------------------------------===//
2321
2322void Andersens::PrintNode(Node *N) {
2323 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002324 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002325 return;
2326 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002327 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002328 return;
2329 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002330 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002331 return;
2332 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002333 if (!N->getValue()) {
2334 cerr << "artificial" << (intptr_t) N;
2335 return;
2336 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002337
2338 assert(N->getValue() != 0 && "Never set node label!");
2339 Value *V = N->getValue();
2340 if (Function *F = dyn_cast<Function>(V)) {
2341 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002342 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002343 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002344 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002345 } else if (F->getFunctionType()->isVarArg() &&
2346 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002347 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002348 return;
2349 }
2350 }
2351
2352 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002353 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002354 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002355 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002356
2357 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002358 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002359 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002360 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002361
2362 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002363 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002364 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002365}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002366void Andersens::PrintConstraint(const Constraint &C) {
2367 if (C.Type == Constraint::Store) {
2368 cerr << "*";
2369 if (C.Offset != 0)
2370 cerr << "(";
2371 }
2372 PrintNode(&GraphNodes[C.Dest]);
2373 if (C.Type == Constraint::Store && C.Offset != 0)
2374 cerr << " + " << C.Offset << ")";
2375 cerr << " = ";
2376 if (C.Type == Constraint::Load) {
2377 cerr << "*";
2378 if (C.Offset != 0)
2379 cerr << "(";
2380 }
2381 else if (C.Type == Constraint::AddressOf)
2382 cerr << "&";
2383 PrintNode(&GraphNodes[C.Src]);
2384 if (C.Offset != 0 && C.Type != Constraint::Store)
2385 cerr << " + " << C.Offset;
2386 if (C.Type == Constraint::Load && C.Offset != 0)
2387 cerr << ")";
2388 cerr << "\n";
2389}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002390
2391void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002392 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002393
Daniel Berlind81ccc22007-09-24 19:45:49 +00002394 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2395 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002396}
2397
2398void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002399 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002400 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2401 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002402 if (FindNode (i) != i) {
2403 PrintNode(N);
2404 cerr << "\t--> same as ";
2405 PrintNode(&GraphNodes[FindNode(i)]);
2406 cerr << "\n";
2407 } else {
2408 cerr << "[" << (N->PointsTo->count()) << "] ";
2409 PrintNode(N);
2410 cerr << "\t--> ";
2411
2412 bool first = true;
2413 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2414 bi != N->PointsTo->end();
2415 ++bi) {
2416 if (!first)
2417 cerr << ", ";
2418 PrintNode(&GraphNodes[*bi]);
2419 first = false;
2420 }
2421 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002422 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002423 }
2424}