blob: 69462279a9a486399d64cb5779d88c5b0343a5ed [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//
10// This file defines a very simple implementation of Andersen's interprocedural
11// alias analysis. This implementation does not include any of the fancy
12// features that make Andersen's reasonably efficient (like cycle elimination or
13// variable substitution), but it should be useful for getting precision
14// numbers and can be extended in the future.
15//
16// In pointer analysis terms, this is a subset-based, flow-insensitive,
17// field-insensitive, and context-insensitive algorithm pointer algorithm.
18//
19// This algorithm is implemented as three stages:
20// 1. Object identification.
21// 2. Inclusion constraint identification.
22// 3. Inclusion constraint solving.
23//
24// The object identification stage identifies all of the memory objects in the
25// program, which includes globals, heap allocated objects, and stack allocated
26// objects.
27//
28// The inclusion constraint identification stage finds all inclusion constraints
29// in the program by scanning the program, looking for pointer assignments and
30// other statements that effect the points-to graph. For a statement like "A =
31// B", this statement is processed to indicate that A can point to anything that
32// B can point to. Constraints can handle copies, loads, and stores.
33//
34// The inclusion constraint solving phase iteratively propagates the inclusion
35// constraints until a fixed point is reached. This is an O(N^3) algorithm.
36//
37// In the initial pass, all indirect function calls are completely ignored. As
38// the analysis discovers new targets of function pointers, it iteratively
39// resolves a precise (and conservative) call graph. Also related, this
40// analysis initially assumes that all internal functions have known incoming
41// pointers. If we find that an internal function's address escapes outside of
42// the program, we update this assumption.
43//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000044// Future Improvements:
45// This implementation of Andersen's algorithm is extremely slow. To make it
Misha Brukman2b37d7c2005-04-21 21:13:18 +000046// scale reasonably well, the inclusion constraints could be sorted (easy),
47// offline variable substitution would be a huge win (straight-forward), and
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000048// online cycle elimination (trickier) might help as well.
49//
Chris Lattnere995a2a2004-05-23 21:00:47 +000050//===----------------------------------------------------------------------===//
51
52#define DEBUG_TYPE "anders-aa"
53#include "llvm/Constants.h"
54#include "llvm/DerivedTypes.h"
55#include "llvm/Instructions.h"
56#include "llvm/Module.h"
57#include "llvm/Pass.h"
58#include "llvm/Support/InstIterator.h"
59#include "llvm/Support/InstVisitor.h"
60#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000061#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000062#include "llvm/Support/Debug.h"
63#include "llvm/ADT/Statistic.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000064#include <set>
65using namespace llvm;
66
67namespace {
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000068 Statistic
Chris Lattnere995a2a2004-05-23 21:00:47 +000069 NumIters("anders-aa", "Number of iterations to reach convergence");
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000070 Statistic
Chris Lattnere995a2a2004-05-23 21:00:47 +000071 NumConstraints("anders-aa", "Number of constraints");
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000072 Statistic
Chris Lattnere995a2a2004-05-23 21:00:47 +000073 NumNodes("anders-aa", "Number of nodes");
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000074 Statistic
Chris Lattnere995a2a2004-05-23 21:00:47 +000075 NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000076 Statistic
Chris Lattnere995a2a2004-05-23 21:00:47 +000077 NumIndirectCallees("anders-aa", "Number of indirect callees found");
78
Chris Lattnerb12914b2004-09-20 04:48:05 +000079 class Andersens : public ModulePass, public AliasAnalysis,
Chris Lattnere995a2a2004-05-23 21:00:47 +000080 private InstVisitor<Andersens> {
81 /// Node class - This class is used to represent a memory object in the
82 /// program, and is the primitive used to build the points-to graph.
83 class Node {
84 std::vector<Node*> Pointees;
85 Value *Val;
86 public:
87 Node() : Val(0) {}
88 Node *setValue(Value *V) {
89 assert(Val == 0 && "Value already set for this node!");
90 Val = V;
91 return this;
92 }
93
94 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +000095 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +000096 Value *getValue() const { return Val; }
97
98 typedef std::vector<Node*>::const_iterator iterator;
99 iterator begin() const { return Pointees.begin(); }
100 iterator end() const { return Pointees.end(); }
101
102 /// addPointerTo - Add a pointer to the list of pointees of this node,
103 /// returning true if this caused a new pointer to be added, or false if
104 /// we already knew about the points-to relation.
105 bool addPointerTo(Node *N) {
106 std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
107 Pointees.end(),
108 N);
109 if (I != Pointees.end() && *I == N)
110 return false;
111 Pointees.insert(I, N);
112 return true;
113 }
114
115 /// intersects - Return true if the points-to set of this node intersects
116 /// with the points-to set of the specified node.
117 bool intersects(Node *N) const;
118
119 /// intersectsIgnoring - Return true if the points-to set of this node
120 /// intersects with the points-to set of the specified node on any nodes
121 /// except for the specified node to ignore.
122 bool intersectsIgnoring(Node *N, Node *Ignoring) const;
123
124 // Constraint application methods.
125 bool copyFrom(Node *N);
126 bool loadFrom(Node *N);
127 bool storeThrough(Node *N);
128 };
129
130 /// GraphNodes - This vector is populated as part of the object
131 /// identification stage of the analysis, which populates this vector with a
132 /// node for each memory object and fills in the ValueNodes map.
133 std::vector<Node> GraphNodes;
134
135 /// ValueNodes - This map indicates the Node that a particular Value* is
136 /// represented by. This contains entries for all pointers.
137 std::map<Value*, unsigned> ValueNodes;
138
139 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000140 /// program: globals, alloca's and mallocs.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000141 std::map<Value*, unsigned> ObjectNodes;
142
143 /// ReturnNodes - This map contains an entry for each function in the
144 /// program that returns a value.
145 std::map<Function*, unsigned> ReturnNodes;
146
147 /// VarargNodes - This map contains the entry used to represent all pointers
148 /// passed through the varargs portion of a function call for a particular
149 /// function. An entry is not present in this map for functions that do not
150 /// take variable arguments.
151 std::map<Function*, unsigned> VarargNodes;
152
153 /// Constraint - Objects of this structure are used to represent the various
154 /// constraints identified by the algorithm. The constraints are 'copy',
155 /// for statements like "A = B", 'load' for statements like "A = *B", and
156 /// 'store' for statements like "*A = B".
157 struct Constraint {
158 enum ConstraintType { Copy, Load, Store } Type;
159 Node *Dest, *Src;
160
161 Constraint(ConstraintType Ty, Node *D, Node *S)
162 : Type(Ty), Dest(D), Src(S) {}
163 };
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000164
Chris Lattnere995a2a2004-05-23 21:00:47 +0000165 /// Constraints - This vector contains a list of all of the constraints
166 /// identified by the program.
167 std::vector<Constraint> Constraints;
168
169 /// EscapingInternalFunctions - This set contains all of the internal
170 /// functions that are found to escape from the program. If the address of
171 /// an internal function is passed to an external function or otherwise
172 /// escapes from the analyzed portion of the program, we must assume that
173 /// any pointer arguments can alias the universal node. This set keeps
174 /// track of those functions we are assuming to escape so far.
175 std::set<Function*> EscapingInternalFunctions;
176
177 /// IndirectCalls - This contains a list of all of the indirect call sites
178 /// in the program. Since the call graph is iteratively discovered, we may
179 /// need to add constraints to our graph as we find new targets of function
180 /// pointers.
181 std::vector<CallSite> IndirectCalls;
182
183 /// IndirectCallees - For each call site in the indirect calls list, keep
184 /// track of the callees that we have discovered so far. As the analysis
185 /// proceeds, more callees are discovered, until the call graph finally
186 /// stabilizes.
187 std::map<CallSite, std::vector<Function*> > IndirectCallees;
188
189 /// This enum defines the GraphNodes indices that correspond to important
190 /// fixed sets.
191 enum {
192 UniversalSet = 0,
193 NullPtr = 1,
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000194 NullObject = 2
Chris Lattnere995a2a2004-05-23 21:00:47 +0000195 };
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000196
Chris Lattnere995a2a2004-05-23 21:00:47 +0000197 public:
Chris Lattnerb12914b2004-09-20 04:48:05 +0000198 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000199 InitializeAliasAnalysis(this);
200 IdentifyObjects(M);
201 CollectConstraints(M);
202 DEBUG(PrintConstraints());
203 SolveConstraints();
204 DEBUG(PrintPointsToGraph());
205
206 // Free the constraints list, as we don't need it to respond to alias
207 // requests.
208 ObjectNodes.clear();
209 ReturnNodes.clear();
210 VarargNodes.clear();
211 EscapingInternalFunctions.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000212 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000213 return false;
214 }
215
216 void releaseMemory() {
217 // FIXME: Until we have transitively required passes working correctly,
218 // this cannot be enabled! Otherwise, using -count-aa with the pass
219 // causes memory to be freed too early. :(
220#if 0
221 // The memory objects and ValueNodes data structures at the only ones that
222 // are still live after construction.
223 std::vector<Node>().swap(GraphNodes);
224 ValueNodes.clear();
225#endif
226 }
227
228 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
229 AliasAnalysis::getAnalysisUsage(AU);
230 AU.setPreservesAll(); // Does not transform code
231 }
232
233 //------------------------------------------------
234 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000235 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000236 AliasResult alias(const Value *V1, unsigned V1Size,
237 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000238 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
239 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000240 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
241 bool pointsToConstantMemory(const Value *P);
242
243 virtual void deleteValue(Value *V) {
244 ValueNodes.erase(V);
245 getAnalysis<AliasAnalysis>().deleteValue(V);
246 }
247
248 virtual void copyValue(Value *From, Value *To) {
249 ValueNodes[To] = ValueNodes[From];
250 getAnalysis<AliasAnalysis>().copyValue(From, To);
251 }
252
253 private:
254 /// getNode - Return the node corresponding to the specified pointer scalar.
255 ///
256 Node *getNode(Value *V) {
257 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000258 if (!isa<GlobalValue>(C))
259 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000260
261 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
262 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000263#ifndef NDEBUG
264 V->dump();
265#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000266 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000267 }
268 return &GraphNodes[I->second];
269 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000270
Chris Lattnere995a2a2004-05-23 21:00:47 +0000271 /// getObject - Return the node corresponding to the memory object for the
272 /// specified global or allocation instruction.
273 Node *getObject(Value *V) {
274 std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
275 assert(I != ObjectNodes.end() &&
276 "Value does not have an object in the points-to graph!");
277 return &GraphNodes[I->second];
278 }
279
280 /// getReturnNode - Return the node representing the return value for the
281 /// specified function.
282 Node *getReturnNode(Function *F) {
283 std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
284 assert(I != ReturnNodes.end() && "Function does not return a value!");
285 return &GraphNodes[I->second];
286 }
287
288 /// getVarargNode - Return the node representing the variable arguments
289 /// formal for the specified function.
290 Node *getVarargNode(Function *F) {
291 std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
292 assert(I != VarargNodes.end() && "Function does not take var args!");
293 return &GraphNodes[I->second];
294 }
295
296 /// getNodeValue - Get the node for the specified LLVM value and set the
297 /// value for it to be the specified value.
298 Node *getNodeValue(Value &V) {
299 return getNode(&V)->setValue(&V);
300 }
301
302 void IdentifyObjects(Module &M);
303 void CollectConstraints(Module &M);
304 void SolveConstraints();
305
306 Node *getNodeForConstantPointer(Constant *C);
307 Node *getNodeForConstantPointerTarget(Constant *C);
308 void AddGlobalInitializerConstraints(Node *N, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000309
Chris Lattnere995a2a2004-05-23 21:00:47 +0000310 void AddConstraintsForNonInternalLinkage(Function *F);
311 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000312 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000313
314
315 void PrintNode(Node *N);
316 void PrintConstraints();
317 void PrintPointsToGraph();
318
319 //===------------------------------------------------------------------===//
320 // Instruction visitation methods for adding constraints
321 //
322 friend class InstVisitor<Andersens>;
323 void visitReturnInst(ReturnInst &RI);
324 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
325 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
326 void visitCallSite(CallSite CS);
327 void visitAllocationInst(AllocationInst &AI);
328 void visitLoadInst(LoadInst &LI);
329 void visitStoreInst(StoreInst &SI);
330 void visitGetElementPtrInst(GetElementPtrInst &GEP);
331 void visitPHINode(PHINode &PN);
332 void visitCastInst(CastInst &CI);
Chris Lattner4de57fd2005-03-29 06:52:20 +0000333 void visitSetCondInst(SetCondInst &SCI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000334 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000335 void visitVAArg(VAArgInst &I);
336 void visitInstruction(Instruction &I);
337 };
338
Chris Lattner7f8897f2006-08-27 22:42:52 +0000339 RegisterPass<Andersens> X("anders-aa",
340 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000341 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000342}
343
Jeff Cohen534927d2005-01-08 22:01:16 +0000344ModulePass *llvm::createAndersensPass() { return new Andersens(); }
345
Chris Lattnere995a2a2004-05-23 21:00:47 +0000346//===----------------------------------------------------------------------===//
347// AliasAnalysis Interface Implementation
348//===----------------------------------------------------------------------===//
349
350AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
351 const Value *V2, unsigned V2Size) {
Chris Lattnerf392c642005-03-28 06:21:17 +0000352 Node *N1 = getNode(const_cast<Value*>(V1));
353 Node *N2 = getNode(const_cast<Value*>(V2));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000354
355 // Check to see if the two pointers are known to not alias. They don't alias
356 // if their points-to sets do not intersect.
357 if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
358 return NoAlias;
359
360 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
361}
362
Chris Lattnerf392c642005-03-28 06:21:17 +0000363AliasAnalysis::ModRefResult
364Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
365 // The only thing useful that we can contribute for mod/ref information is
366 // when calling external function calls: if we know that memory never escapes
367 // from the program, it cannot be modified by an external call.
368 //
369 // NOTE: This is not really safe, at least not when the entire program is not
370 // available. The deal is that the external function could call back into the
371 // program and modify stuff. We ignore this technical niggle for now. This
372 // is, after all, a "research quality" implementation of Andersen's analysis.
373 if (Function *F = CS.getCalledFunction())
374 if (F->isExternal()) {
375 Node *N1 = getNode(P);
Chris Lattnerf392c642005-03-28 06:21:17 +0000376
Chris Lattner8a9763c2005-04-04 22:23:21 +0000377 if (N1->begin() == N1->end())
378 return NoModRef; // P doesn't point to anything.
Chris Lattnerf392c642005-03-28 06:21:17 +0000379
Chris Lattner8a9763c2005-04-04 22:23:21 +0000380 // Get the first pointee.
381 Node *FirstPointee = *N1->begin();
382 if (FirstPointee != &GraphNodes[UniversalSet])
Chris Lattnerf392c642005-03-28 06:21:17 +0000383 return NoModRef; // P doesn't point to the universal set.
384 }
385
386 return AliasAnalysis::getModRefInfo(CS, P, Size);
387}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000388
Reid Spencer3a9ec242006-08-28 01:02:49 +0000389AliasAnalysis::ModRefResult
390Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
391 return AliasAnalysis::getModRefInfo(CS1,CS2);
392}
393
Chris Lattnere995a2a2004-05-23 21:00:47 +0000394/// getMustAlias - We can provide must alias information if we know that a
395/// pointer can only point to a specific function or the null pointer.
396/// Unfortunately we cannot determine must-alias information for global
397/// variables or any other memory memory objects because we do not track whether
398/// a pointer points to the beginning of an object or a field of it.
399void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
400 Node *N = getNode(P);
401 Node::iterator I = N->begin();
402 if (I != N->end()) {
403 // If there is exactly one element in the points-to set for the object...
404 ++I;
405 if (I == N->end()) {
406 Node *Pointee = *N->begin();
407
408 // If a function is the only object in the points-to set, then it must be
409 // the destination. Note that we can't handle global variables here,
410 // because we don't know if the pointer is actually pointing to a field of
411 // the global or to the beginning of it.
412 if (Value *V = Pointee->getValue()) {
413 if (Function *F = dyn_cast<Function>(V))
414 RetVals.push_back(F);
415 } else {
416 // If the object in the points-to set is the null object, then the null
417 // pointer is a must alias.
418 if (Pointee == &GraphNodes[NullObject])
419 RetVals.push_back(Constant::getNullValue(P->getType()));
420 }
421 }
422 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000423
Chris Lattnere995a2a2004-05-23 21:00:47 +0000424 AliasAnalysis::getMustAliases(P, RetVals);
425}
426
427/// pointsToConstantMemory - If we can determine that this pointer only points
428/// to constant memory, return true. In practice, this means that if the
429/// pointer can only point to constant globals, functions, or the null pointer,
430/// return true.
431///
432bool Andersens::pointsToConstantMemory(const Value *P) {
433 Node *N = getNode((Value*)P);
434 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
435 if (Value *V = (*I)->getValue()) {
436 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
437 !cast<GlobalVariable>(V)->isConstant()))
438 return AliasAnalysis::pointsToConstantMemory(P);
439 } else {
440 if (*I != &GraphNodes[NullObject])
441 return AliasAnalysis::pointsToConstantMemory(P);
442 }
443 }
444
445 return true;
446}
447
448//===----------------------------------------------------------------------===//
449// Object Identification Phase
450//===----------------------------------------------------------------------===//
451
452/// IdentifyObjects - This stage scans the program, adding an entry to the
453/// GraphNodes list for each memory object in the program (global stack or
454/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
455///
456void Andersens::IdentifyObjects(Module &M) {
457 unsigned NumObjects = 0;
458
459 // Object #0 is always the universal set: the object that we don't know
460 // anything about.
461 assert(NumObjects == UniversalSet && "Something changed!");
462 ++NumObjects;
463
464 // Object #1 always represents the null pointer.
465 assert(NumObjects == NullPtr && "Something changed!");
466 ++NumObjects;
467
468 // Object #2 always represents the null object (the object pointed to by null)
469 assert(NumObjects == NullObject && "Something changed!");
470 ++NumObjects;
471
472 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000473 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
474 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000475 ObjectNodes[I] = NumObjects++;
476 ValueNodes[I] = NumObjects++;
477 }
478
479 // Add nodes for all of the functions and the instructions inside of them.
480 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
481 // The function itself is a memory object.
482 ValueNodes[F] = NumObjects++;
483 ObjectNodes[F] = NumObjects++;
484 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
485 ReturnNodes[F] = NumObjects++;
486 if (F->getFunctionType()->isVarArg())
487 VarargNodes[F] = NumObjects++;
488
489 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000490 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
491 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000492 if (isa<PointerType>(I->getType()))
493 ValueNodes[I] = NumObjects++;
494
495 // Scan the function body, creating a memory object for each heap/stack
496 // allocation in the body of the function and a node to represent all
497 // pointer values defined by instructions and used as operands.
498 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
499 // If this is an heap or stack allocation, create a node for the memory
500 // object.
501 if (isa<PointerType>(II->getType())) {
502 ValueNodes[&*II] = NumObjects++;
503 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
504 ObjectNodes[AI] = NumObjects++;
505 }
506 }
507 }
508
509 // Now that we know how many objects to create, make them all now!
510 GraphNodes.resize(NumObjects);
511 NumNodes += NumObjects;
512}
513
514//===----------------------------------------------------------------------===//
515// Constraint Identification Phase
516//===----------------------------------------------------------------------===//
517
518/// getNodeForConstantPointer - Return the node corresponding to the constant
519/// pointer itself.
520Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
521 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
522
Chris Lattner267a1b02005-03-27 18:58:23 +0000523 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000524 return &GraphNodes[NullPtr];
Reid Spencere8404342004-07-18 00:18:30 +0000525 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
526 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000527 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
528 switch (CE->getOpcode()) {
529 case Instruction::GetElementPtr:
530 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000531 case Instruction::IntToPtr:
532 return &GraphNodes[UniversalSet];
533 case Instruction::BitCast:
534 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000535 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000536 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000537 assert(0);
538 }
539 } else {
540 assert(0 && "Unknown constant pointer!");
541 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000542 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000543}
544
545/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
546/// specified constant pointer.
547Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
548 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
549
550 if (isa<ConstantPointerNull>(C))
551 return &GraphNodes[NullObject];
Reid Spencere8404342004-07-18 00:18:30 +0000552 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
553 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000554 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
555 switch (CE->getOpcode()) {
556 case Instruction::GetElementPtr:
557 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000558 case Instruction::IntToPtr:
559 return &GraphNodes[UniversalSet];
560 case Instruction::BitCast:
561 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000562 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000563 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000564 assert(0);
565 }
566 } else {
567 assert(0 && "Unknown constant pointer!");
568 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000569 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000570}
571
572/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
573/// object N, which contains values indicated by C.
574void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
575 if (C->getType()->isFirstClassType()) {
576 if (isa<PointerType>(C->getType()))
Chris Lattner76bc5ce2005-03-29 17:21:53 +0000577 N->copyFrom(getNodeForConstantPointer(C));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000578
Chris Lattnere995a2a2004-05-23 21:00:47 +0000579 } else if (C->isNullValue()) {
580 N->addPointerTo(&GraphNodes[NullObject]);
581 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000582 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000583 // If this is an array or struct, include constraints for each element.
584 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
585 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
586 AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
587 }
588}
589
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000590/// AddConstraintsForNonInternalLinkage - If this function does not have
591/// internal linkage, realize that we can't trust anything passed into or
592/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000593void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000594 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000595 if (isa<PointerType>(I->getType()))
596 // If this is an argument of an externally accessible function, the
597 // incoming pointer might point to anything.
598 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
599 &GraphNodes[UniversalSet]));
600}
601
Chris Lattner8a446432005-03-29 06:09:07 +0000602/// AddConstraintsForCall - If this is a call to a "known" function, add the
603/// constraints and return true. If this is a call to an unknown function,
604/// return false.
605bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000606 assert(F->isExternal() && "Not an external function!");
607
608 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000609 if (F->getName() == "atoi" || F->getName() == "atof" ||
610 F->getName() == "atol" || F->getName() == "atoll" ||
611 F->getName() == "remove" || F->getName() == "unlink" ||
612 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000613 F->getName() == "llvm.memset.i32" ||
614 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000615 F->getName() == "strcmp" || F->getName() == "strncmp" ||
616 F->getName() == "execl" || F->getName() == "execlp" ||
617 F->getName() == "execle" || F->getName() == "execv" ||
618 F->getName() == "execvp" || F->getName() == "chmod" ||
619 F->getName() == "puts" || F->getName() == "write" ||
620 F->getName() == "open" || F->getName() == "create" ||
621 F->getName() == "truncate" || F->getName() == "chdir" ||
622 F->getName() == "mkdir" || F->getName() == "rmdir" ||
623 F->getName() == "read" || F->getName() == "pipe" ||
624 F->getName() == "wait" || F->getName() == "time" ||
625 F->getName() == "stat" || F->getName() == "fstat" ||
626 F->getName() == "lstat" || F->getName() == "strtod" ||
627 F->getName() == "strtof" || F->getName() == "strtold" ||
628 F->getName() == "fopen" || F->getName() == "fdopen" ||
629 F->getName() == "freopen" ||
630 F->getName() == "fflush" || F->getName() == "feof" ||
631 F->getName() == "fileno" || F->getName() == "clearerr" ||
632 F->getName() == "rewind" || F->getName() == "ftell" ||
633 F->getName() == "ferror" || F->getName() == "fgetc" ||
634 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
635 F->getName() == "fwrite" || F->getName() == "fread" ||
636 F->getName() == "fgets" || F->getName() == "ungetc" ||
637 F->getName() == "fputc" ||
638 F->getName() == "fputs" || F->getName() == "putc" ||
639 F->getName() == "ftell" || F->getName() == "rewind" ||
640 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
641 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
642 F->getName() == "printf" || F->getName() == "fprintf" ||
643 F->getName() == "sprintf" || F->getName() == "vprintf" ||
644 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
645 F->getName() == "scanf" || F->getName() == "fscanf" ||
646 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
647 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000648 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000649
Chris Lattner175b9632005-03-29 20:36:05 +0000650
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000651 // These functions do induce points-to edges.
Chris Lattner01ac91e2006-03-03 01:21:36 +0000652 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
653 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000654 F->getName() == "memmove") {
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000655 // Note: this is a poor approximation, this says Dest = Src, instead of
656 // *Dest = *Src.
Chris Lattner8a446432005-03-29 06:09:07 +0000657 Constraints.push_back(Constraint(Constraint::Copy,
658 getNode(CS.getArgument(0)),
659 getNode(CS.getArgument(1))));
660 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000661 }
662
Chris Lattner77b50562005-03-29 20:04:24 +0000663 // Result = Arg0
664 if (F->getName() == "realloc" || F->getName() == "strchr" ||
665 F->getName() == "strrchr" || F->getName() == "strstr" ||
666 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000667 Constraints.push_back(Constraint(Constraint::Copy,
668 getNode(CS.getInstruction()),
669 getNode(CS.getArgument(0))));
670 return true;
671 }
672
673 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000674}
675
676
Chris Lattnere995a2a2004-05-23 21:00:47 +0000677
678/// CollectConstraints - This stage scans the program, adding a constraint to
679/// the Constraints list for each instruction in the program that induces a
680/// constraint, and setting up the initial points-to graph.
681///
682void Andersens::CollectConstraints(Module &M) {
683 // First, the universal set points to itself.
684 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
Chris Lattner4de57fd2005-03-29 06:52:20 +0000685 //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
686 // &GraphNodes[UniversalSet]));
Chris Lattnerf392c642005-03-28 06:21:17 +0000687 Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
688 &GraphNodes[UniversalSet]));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000689
690 // Next, the null pointer points to the null object.
691 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
692
693 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000694 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
695 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000696 // Associate the address of the global object as pointing to the memory for
697 // the global: &G = <G memory>
698 Node *Object = getObject(I);
699 Object->setValue(I);
700 getNodeValue(*I)->addPointerTo(Object);
701
702 if (I->hasInitializer()) {
703 AddGlobalInitializerConstraints(Object, I->getInitializer());
704 } else {
705 // If it doesn't have an initializer (i.e. it's defined in another
706 // translation unit), it points to the universal set.
707 Constraints.push_back(Constraint(Constraint::Copy, Object,
708 &GraphNodes[UniversalSet]));
709 }
710 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000711
Chris Lattnere995a2a2004-05-23 21:00:47 +0000712 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
713 // Make the function address point to the function object.
714 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
715
716 // Set up the return value node.
717 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
718 getReturnNode(F)->setValue(F);
719 if (F->getFunctionType()->isVarArg())
720 getVarargNode(F)->setValue(F);
721
722 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000723 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
724 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000725 if (isa<PointerType>(I->getType()))
726 getNodeValue(*I);
727
728 if (!F->hasInternalLinkage())
729 AddConstraintsForNonInternalLinkage(F);
730
731 if (!F->isExternal()) {
732 // Scan the function body, creating a memory object for each heap/stack
733 // allocation in the body of the function and a node to represent all
734 // pointer values defined by instructions and used as operands.
735 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000736 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000737 // External functions that return pointers return the universal set.
738 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
739 Constraints.push_back(Constraint(Constraint::Copy,
740 getReturnNode(F),
741 &GraphNodes[UniversalSet]));
742
743 // Any pointers that are passed into the function have the universal set
744 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000745 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
746 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000747 if (isa<PointerType>(I->getType())) {
748 // Pointers passed into external functions could have anything stored
749 // through them.
750 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
751 &GraphNodes[UniversalSet]));
752 // Memory objects passed into external function calls can have the
753 // universal set point to them.
754 Constraints.push_back(Constraint(Constraint::Copy,
755 &GraphNodes[UniversalSet],
756 getNode(I)));
757 }
758
759 // If this is an external varargs function, it can also store pointers
760 // into any pointers passed through the varargs section.
761 if (F->getFunctionType()->isVarArg())
762 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
763 &GraphNodes[UniversalSet]));
764 }
765 }
766 NumConstraints += Constraints.size();
767}
768
769
770void Andersens::visitInstruction(Instruction &I) {
771#ifdef NDEBUG
772 return; // This function is just a big assert.
773#endif
774 if (isa<BinaryOperator>(I))
775 return;
776 // Most instructions don't have any effect on pointer values.
777 switch (I.getOpcode()) {
778 case Instruction::Br:
779 case Instruction::Switch:
780 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +0000781 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000782 case Instruction::Free:
783 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000784 case Instruction::LShr:
785 case Instruction::AShr:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000786 return;
787 default:
788 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +0000789 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000790 abort();
791 }
792}
793
794void Andersens::visitAllocationInst(AllocationInst &AI) {
795 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
796}
797
798void Andersens::visitReturnInst(ReturnInst &RI) {
799 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
800 // return V --> <Copy/retval{F}/v>
801 Constraints.push_back(Constraint(Constraint::Copy,
802 getReturnNode(RI.getParent()->getParent()),
803 getNode(RI.getOperand(0))));
804}
805
806void Andersens::visitLoadInst(LoadInst &LI) {
807 if (isa<PointerType>(LI.getType()))
808 // P1 = load P2 --> <Load/P1/P2>
809 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
810 getNode(LI.getOperand(0))));
811}
812
813void Andersens::visitStoreInst(StoreInst &SI) {
814 if (isa<PointerType>(SI.getOperand(0)->getType()))
815 // store P1, P2 --> <Store/P2/P1>
816 Constraints.push_back(Constraint(Constraint::Store,
817 getNode(SI.getOperand(1)),
818 getNode(SI.getOperand(0))));
819}
820
821void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
822 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
823 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
824 getNode(GEP.getOperand(0))));
825}
826
827void Andersens::visitPHINode(PHINode &PN) {
828 if (isa<PointerType>(PN.getType())) {
829 Node *PNN = getNodeValue(PN);
830 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
831 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
832 Constraints.push_back(Constraint(Constraint::Copy, PNN,
833 getNode(PN.getIncomingValue(i))));
834 }
835}
836
837void Andersens::visitCastInst(CastInst &CI) {
838 Value *Op = CI.getOperand(0);
839 if (isa<PointerType>(CI.getType())) {
840 if (isa<PointerType>(Op->getType())) {
841 // P1 = cast P2 --> <Copy/P1/P2>
842 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
843 getNode(CI.getOperand(0))));
844 } else {
845 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +0000846#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000847 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
848 &GraphNodes[UniversalSet]));
Chris Lattnerbd135c72005-04-05 01:12:03 +0000849#else
850 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +0000851#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000852 }
853 } else if (isa<PointerType>(Op->getType())) {
854 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +0000855#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000856 Constraints.push_back(Constraint(Constraint::Copy,
857 &GraphNodes[UniversalSet],
858 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +0000859#else
860 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +0000861#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000862 }
863}
864
865void Andersens::visitSelectInst(SelectInst &SI) {
866 if (isa<PointerType>(SI.getType())) {
867 Node *SIN = getNodeValue(SI);
868 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
869 Constraints.push_back(Constraint(Constraint::Copy, SIN,
870 getNode(SI.getOperand(1))));
871 Constraints.push_back(Constraint(Constraint::Copy, SIN,
872 getNode(SI.getOperand(2))));
873 }
874}
875
Chris Lattnere995a2a2004-05-23 21:00:47 +0000876void Andersens::visitVAArg(VAArgInst &I) {
877 assert(0 && "vaarg not handled yet!");
878}
879
880/// AddConstraintsForCall - Add constraints for a call with actual arguments
881/// specified by CS to the function specified by F. Note that the types of
882/// arguments might not match up in the case where this is an indirect call and
883/// the function pointer has been casted. If this is the case, do something
884/// reasonable.
885void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Chris Lattner8a446432005-03-29 06:09:07 +0000886 // If this is a call to an external function, handle it directly to get some
887 // taste of context sensitivity.
888 if (F->isExternal() && AddConstraintsForExternalCall(CS, F))
889 return;
890
Chris Lattnere995a2a2004-05-23 21:00:47 +0000891 if (isa<PointerType>(CS.getType())) {
892 Node *CSN = getNode(CS.getInstruction());
893 if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
894 Constraints.push_back(Constraint(Constraint::Copy, CSN,
895 getReturnNode(F)));
896 } else {
897 // If the function returns a non-pointer value, handle this just like we
898 // treat a nonpointer cast to pointer.
899 Constraints.push_back(Constraint(Constraint::Copy, CSN,
900 &GraphNodes[UniversalSet]));
901 }
902 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
903 Constraints.push_back(Constraint(Constraint::Copy,
904 &GraphNodes[UniversalSet],
905 getReturnNode(F)));
906 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000907
Chris Lattnere4d5c442005-03-15 04:54:21 +0000908 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000909 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
910 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
911 if (isa<PointerType>(AI->getType())) {
912 if (isa<PointerType>((*ArgI)->getType())) {
913 // Copy the actual argument into the formal argument.
914 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
915 getNode(*ArgI)));
916 } else {
917 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
918 &GraphNodes[UniversalSet]));
919 }
920 } else if (isa<PointerType>((*ArgI)->getType())) {
921 Constraints.push_back(Constraint(Constraint::Copy,
922 &GraphNodes[UniversalSet],
923 getNode(*ArgI)));
924 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000925
Chris Lattnere995a2a2004-05-23 21:00:47 +0000926 // Copy all pointers passed through the varargs section to the varargs node.
927 if (F->getFunctionType()->isVarArg())
928 for (; ArgI != ArgE; ++ArgI)
929 if (isa<PointerType>((*ArgI)->getType()))
930 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
931 getNode(*ArgI)));
932 // If more arguments are passed in than we track, just drop them on the floor.
933}
934
935void Andersens::visitCallSite(CallSite CS) {
936 if (isa<PointerType>(CS.getType()))
937 getNodeValue(*CS.getInstruction());
938
939 if (Function *F = CS.getCalledFunction()) {
940 AddConstraintsForCall(CS, F);
941 } else {
942 // We don't handle indirect call sites yet. Keep track of them for when we
943 // discover the call graph incrementally.
944 IndirectCalls.push_back(CS);
945 }
946}
947
948//===----------------------------------------------------------------------===//
949// Constraint Solving Phase
950//===----------------------------------------------------------------------===//
951
952/// intersects - Return true if the points-to set of this node intersects
953/// with the points-to set of the specified node.
954bool Andersens::Node::intersects(Node *N) const {
955 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
956 while (I1 != E1 && I2 != E2) {
957 if (*I1 == *I2) return true;
958 if (*I1 < *I2)
959 ++I1;
960 else
961 ++I2;
962 }
963 return false;
964}
965
966/// intersectsIgnoring - Return true if the points-to set of this node
967/// intersects with the points-to set of the specified node on any nodes
968/// except for the specified node to ignore.
969bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
970 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
971 while (I1 != E1 && I2 != E2) {
972 if (*I1 == *I2) {
973 if (*I1 != Ignoring) return true;
974 ++I1; ++I2;
975 } else if (*I1 < *I2)
976 ++I1;
977 else
978 ++I2;
979 }
980 return false;
981}
982
983// Copy constraint: all edges out of the source node get copied to the
984// destination node. This returns true if a change is made.
985bool Andersens::Node::copyFrom(Node *N) {
986 // Use a mostly linear-time merge since both of the lists are sorted.
987 bool Changed = false;
988 iterator I = N->begin(), E = N->end();
989 unsigned i = 0;
990 while (I != E && i != Pointees.size()) {
991 if (Pointees[i] < *I) {
992 ++i;
993 } else if (Pointees[i] == *I) {
994 ++i; ++I;
995 } else {
996 // We found a new element to copy over.
997 Changed = true;
998 Pointees.insert(Pointees.begin()+i, *I);
999 ++i; ++I;
1000 }
1001 }
1002
1003 if (I != E) {
1004 Pointees.insert(Pointees.end(), I, E);
1005 Changed = true;
1006 }
1007
1008 return Changed;
1009}
1010
1011bool Andersens::Node::loadFrom(Node *N) {
1012 bool Changed = false;
1013 for (iterator I = N->begin(), E = N->end(); I != E; ++I)
1014 Changed |= copyFrom(*I);
1015 return Changed;
1016}
1017
1018bool Andersens::Node::storeThrough(Node *N) {
1019 bool Changed = false;
1020 for (iterator I = begin(), E = end(); I != E; ++I)
1021 Changed |= (*I)->copyFrom(N);
1022 return Changed;
1023}
1024
1025
1026/// SolveConstraints - This stage iteratively processes the constraints list
1027/// propagating constraints (adding edges to the Nodes in the points-to graph)
1028/// until a fixed point is reached.
1029///
1030void Andersens::SolveConstraints() {
1031 bool Changed = true;
1032 unsigned Iteration = 0;
1033 while (Changed) {
1034 Changed = false;
1035 ++NumIters;
Bill Wendling9be7ac12006-11-17 07:36:54 +00001036 DOUT << "Starting iteration #" << Iteration++ << "!\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001037
1038 // Loop over all of the constraints, applying them in turn.
1039 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1040 Constraint &C = Constraints[i];
1041 switch (C.Type) {
1042 case Constraint::Copy:
1043 Changed |= C.Dest->copyFrom(C.Src);
1044 break;
1045 case Constraint::Load:
1046 Changed |= C.Dest->loadFrom(C.Src);
1047 break;
1048 case Constraint::Store:
1049 Changed |= C.Dest->storeThrough(C.Src);
1050 break;
1051 default:
1052 assert(0 && "Unknown constraint!");
1053 }
1054 }
1055
1056 if (Changed) {
1057 // Check to see if any internal function's addresses have been passed to
1058 // external functions. If so, we have to assume that their incoming
1059 // arguments could be anything. If there are any internal functions in
1060 // the universal node that we don't know about, we must iterate.
1061 for (Node::iterator I = GraphNodes[UniversalSet].begin(),
1062 E = GraphNodes[UniversalSet].end(); I != E; ++I)
1063 if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
1064 if (F->hasInternalLinkage() &&
1065 EscapingInternalFunctions.insert(F).second) {
1066 // We found a function that is just now escaping. Mark it as if it
1067 // didn't have internal linkage.
1068 AddConstraintsForNonInternalLinkage(F);
Bill Wendling9be7ac12006-11-17 07:36:54 +00001069 DOUT << "Found escaping internal function: " << F->getName() <<"\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001070 ++NumEscapingFunctions;
1071 }
1072
1073 // Check to see if we have discovered any new callees of the indirect call
1074 // sites. If so, add constraints to the analysis.
1075 for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1076 CallSite CS = IndirectCalls[i];
1077 std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1078 Node *CN = getNode(CS.getCalledValue());
1079
1080 for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1081 if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1082 std::vector<Function*>::iterator IP =
1083 std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1084 if (IP == KnownCallees.end() || *IP != F) {
1085 // Add the constraints for the call now.
1086 AddConstraintsForCall(CS, F);
Bill Wendling9be7ac12006-11-17 07:36:54 +00001087 DOUT << "Found actual callee '"
1088 << F->getName() << "' for call: "
1089 << *CS.getInstruction() << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001090 ++NumIndirectCallees;
1091 KnownCallees.insert(IP, F);
1092 }
1093 }
1094 }
1095 }
1096 }
1097}
1098
1099
1100
1101//===----------------------------------------------------------------------===//
1102// Debugging Output
1103//===----------------------------------------------------------------------===//
1104
1105void Andersens::PrintNode(Node *N) {
1106 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001107 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001108 return;
1109 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001110 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001111 return;
1112 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001113 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001114 return;
1115 }
1116
1117 assert(N->getValue() != 0 && "Never set node label!");
1118 Value *V = N->getValue();
1119 if (Function *F = dyn_cast<Function>(V)) {
1120 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1121 N == getReturnNode(F)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001122 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001123 return;
1124 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001125 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001126 return;
1127 }
1128 }
1129
1130 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001131 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001132 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001133 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001134
1135 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00001136 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00001137 else
Bill Wendlinge8156192006-12-07 01:30:32 +00001138 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001139
1140 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1141 if (N == getObject(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001142 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001143}
1144
1145void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001146 cerr << "Constraints:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001147 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001148 cerr << " #" << i << ": ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001149 Constraint &C = Constraints[i];
1150 if (C.Type == Constraint::Store)
Bill Wendlinge8156192006-12-07 01:30:32 +00001151 cerr << "*";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001152 PrintNode(C.Dest);
Bill Wendlinge8156192006-12-07 01:30:32 +00001153 cerr << " = ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001154 if (C.Type == Constraint::Load)
Bill Wendlinge8156192006-12-07 01:30:32 +00001155 cerr << "*";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001156 PrintNode(C.Src);
Bill Wendlinge8156192006-12-07 01:30:32 +00001157 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001158 }
1159}
1160
1161void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001162 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001163 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1164 Node *N = &GraphNodes[i];
Bill Wendlinge8156192006-12-07 01:30:32 +00001165 cerr << "[" << (N->end() - N->begin()) << "] ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001166 PrintNode(N);
Bill Wendlinge8156192006-12-07 01:30:32 +00001167 cerr << "\t--> ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001168 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001169 if (I != N->begin()) cerr << ", ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001170 PrintNode(*I);
1171 }
Bill Wendlinge8156192006-12-07 01:30:32 +00001172 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001173 }
1174}