blob: b6855f650302fb82dc7e47fcc52438e99a488242 [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
Chris Lattner3b27d682006-12-19 22:30:33 +000067STATISTIC(NumIters , "Number of iterations to reach convergence");
68STATISTIC(NumConstraints , "Number of constraints");
69STATISTIC(NumNodes , "Number of nodes");
70STATISTIC(NumEscapingFunctions, "Number of internal functions that escape");
71STATISTIC(NumIndirectCallees , "Number of indirect callees found");
Chris Lattnere995a2a2004-05-23 21:00:47 +000072
Chris Lattner3b27d682006-12-19 22:30:33 +000073namespace {
Chris Lattnerb12914b2004-09-20 04:48:05 +000074 class Andersens : public ModulePass, public AliasAnalysis,
Chris Lattnere995a2a2004-05-23 21:00:47 +000075 private InstVisitor<Andersens> {
76 /// Node class - This class is used to represent a memory object in the
77 /// program, and is the primitive used to build the points-to graph.
78 class Node {
79 std::vector<Node*> Pointees;
80 Value *Val;
81 public:
82 Node() : Val(0) {}
83 Node *setValue(Value *V) {
84 assert(Val == 0 && "Value already set for this node!");
85 Val = V;
86 return this;
87 }
88
89 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +000090 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +000091 Value *getValue() const { return Val; }
92
93 typedef std::vector<Node*>::const_iterator iterator;
94 iterator begin() const { return Pointees.begin(); }
95 iterator end() const { return Pointees.end(); }
96
97 /// addPointerTo - Add a pointer to the list of pointees of this node,
98 /// returning true if this caused a new pointer to be added, or false if
99 /// we already knew about the points-to relation.
100 bool addPointerTo(Node *N) {
101 std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
102 Pointees.end(),
103 N);
104 if (I != Pointees.end() && *I == N)
105 return false;
106 Pointees.insert(I, N);
107 return true;
108 }
109
110 /// intersects - Return true if the points-to set of this node intersects
111 /// with the points-to set of the specified node.
112 bool intersects(Node *N) const;
113
114 /// intersectsIgnoring - Return true if the points-to set of this node
115 /// intersects with the points-to set of the specified node on any nodes
116 /// except for the specified node to ignore.
117 bool intersectsIgnoring(Node *N, Node *Ignoring) const;
118
119 // Constraint application methods.
120 bool copyFrom(Node *N);
121 bool loadFrom(Node *N);
122 bool storeThrough(Node *N);
123 };
124
125 /// GraphNodes - This vector is populated as part of the object
126 /// identification stage of the analysis, which populates this vector with a
127 /// node for each memory object and fills in the ValueNodes map.
128 std::vector<Node> GraphNodes;
129
130 /// ValueNodes - This map indicates the Node that a particular Value* is
131 /// represented by. This contains entries for all pointers.
132 std::map<Value*, unsigned> ValueNodes;
133
134 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000135 /// program: globals, alloca's and mallocs.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000136 std::map<Value*, unsigned> ObjectNodes;
137
138 /// ReturnNodes - This map contains an entry for each function in the
139 /// program that returns a value.
140 std::map<Function*, unsigned> ReturnNodes;
141
142 /// VarargNodes - This map contains the entry used to represent all pointers
143 /// passed through the varargs portion of a function call for a particular
144 /// function. An entry is not present in this map for functions that do not
145 /// take variable arguments.
146 std::map<Function*, unsigned> VarargNodes;
147
148 /// Constraint - Objects of this structure are used to represent the various
149 /// constraints identified by the algorithm. The constraints are 'copy',
150 /// for statements like "A = B", 'load' for statements like "A = *B", and
151 /// 'store' for statements like "*A = B".
152 struct Constraint {
153 enum ConstraintType { Copy, Load, Store } Type;
154 Node *Dest, *Src;
155
156 Constraint(ConstraintType Ty, Node *D, Node *S)
157 : Type(Ty), Dest(D), Src(S) {}
158 };
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000159
Chris Lattnere995a2a2004-05-23 21:00:47 +0000160 /// Constraints - This vector contains a list of all of the constraints
161 /// identified by the program.
162 std::vector<Constraint> Constraints;
163
164 /// EscapingInternalFunctions - This set contains all of the internal
165 /// functions that are found to escape from the program. If the address of
166 /// an internal function is passed to an external function or otherwise
167 /// escapes from the analyzed portion of the program, we must assume that
168 /// any pointer arguments can alias the universal node. This set keeps
169 /// track of those functions we are assuming to escape so far.
170 std::set<Function*> EscapingInternalFunctions;
171
172 /// IndirectCalls - This contains a list of all of the indirect call sites
173 /// in the program. Since the call graph is iteratively discovered, we may
174 /// need to add constraints to our graph as we find new targets of function
175 /// pointers.
176 std::vector<CallSite> IndirectCalls;
177
178 /// IndirectCallees - For each call site in the indirect calls list, keep
179 /// track of the callees that we have discovered so far. As the analysis
180 /// proceeds, more callees are discovered, until the call graph finally
181 /// stabilizes.
182 std::map<CallSite, std::vector<Function*> > IndirectCallees;
183
184 /// This enum defines the GraphNodes indices that correspond to important
185 /// fixed sets.
186 enum {
187 UniversalSet = 0,
188 NullPtr = 1,
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000189 NullObject = 2
Chris Lattnere995a2a2004-05-23 21:00:47 +0000190 };
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000191
Chris Lattnere995a2a2004-05-23 21:00:47 +0000192 public:
Chris Lattnerb12914b2004-09-20 04:48:05 +0000193 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000194 InitializeAliasAnalysis(this);
195 IdentifyObjects(M);
196 CollectConstraints(M);
197 DEBUG(PrintConstraints());
198 SolveConstraints();
199 DEBUG(PrintPointsToGraph());
200
201 // Free the constraints list, as we don't need it to respond to alias
202 // requests.
203 ObjectNodes.clear();
204 ReturnNodes.clear();
205 VarargNodes.clear();
206 EscapingInternalFunctions.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000207 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000208 return false;
209 }
210
211 void releaseMemory() {
212 // FIXME: Until we have transitively required passes working correctly,
213 // this cannot be enabled! Otherwise, using -count-aa with the pass
214 // causes memory to be freed too early. :(
215#if 0
216 // The memory objects and ValueNodes data structures at the only ones that
217 // are still live after construction.
218 std::vector<Node>().swap(GraphNodes);
219 ValueNodes.clear();
220#endif
221 }
222
223 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
224 AliasAnalysis::getAnalysisUsage(AU);
225 AU.setPreservesAll(); // Does not transform code
226 }
227
228 //------------------------------------------------
229 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000230 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000231 AliasResult alias(const Value *V1, unsigned V1Size,
232 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000233 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
234 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000235 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
236 bool pointsToConstantMemory(const Value *P);
237
238 virtual void deleteValue(Value *V) {
239 ValueNodes.erase(V);
240 getAnalysis<AliasAnalysis>().deleteValue(V);
241 }
242
243 virtual void copyValue(Value *From, Value *To) {
244 ValueNodes[To] = ValueNodes[From];
245 getAnalysis<AliasAnalysis>().copyValue(From, To);
246 }
247
248 private:
249 /// getNode - Return the node corresponding to the specified pointer scalar.
250 ///
251 Node *getNode(Value *V) {
252 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000253 if (!isa<GlobalValue>(C))
254 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000255
256 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
257 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000258#ifndef NDEBUG
259 V->dump();
260#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000261 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000262 }
263 return &GraphNodes[I->second];
264 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000265
Chris Lattnere995a2a2004-05-23 21:00:47 +0000266 /// getObject - Return the node corresponding to the memory object for the
267 /// specified global or allocation instruction.
268 Node *getObject(Value *V) {
269 std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
270 assert(I != ObjectNodes.end() &&
271 "Value does not have an object in the points-to graph!");
272 return &GraphNodes[I->second];
273 }
274
275 /// getReturnNode - Return the node representing the return value for the
276 /// specified function.
277 Node *getReturnNode(Function *F) {
278 std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
279 assert(I != ReturnNodes.end() && "Function does not return a value!");
280 return &GraphNodes[I->second];
281 }
282
283 /// getVarargNode - Return the node representing the variable arguments
284 /// formal for the specified function.
285 Node *getVarargNode(Function *F) {
286 std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
287 assert(I != VarargNodes.end() && "Function does not take var args!");
288 return &GraphNodes[I->second];
289 }
290
291 /// getNodeValue - Get the node for the specified LLVM value and set the
292 /// value for it to be the specified value.
293 Node *getNodeValue(Value &V) {
294 return getNode(&V)->setValue(&V);
295 }
296
297 void IdentifyObjects(Module &M);
298 void CollectConstraints(Module &M);
299 void SolveConstraints();
300
301 Node *getNodeForConstantPointer(Constant *C);
302 Node *getNodeForConstantPointerTarget(Constant *C);
303 void AddGlobalInitializerConstraints(Node *N, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000304
Chris Lattnere995a2a2004-05-23 21:00:47 +0000305 void AddConstraintsForNonInternalLinkage(Function *F);
306 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000307 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000308
309
310 void PrintNode(Node *N);
311 void PrintConstraints();
312 void PrintPointsToGraph();
313
314 //===------------------------------------------------------------------===//
315 // Instruction visitation methods for adding constraints
316 //
317 friend class InstVisitor<Andersens>;
318 void visitReturnInst(ReturnInst &RI);
319 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
320 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
321 void visitCallSite(CallSite CS);
322 void visitAllocationInst(AllocationInst &AI);
323 void visitLoadInst(LoadInst &LI);
324 void visitStoreInst(StoreInst &SI);
325 void visitGetElementPtrInst(GetElementPtrInst &GEP);
326 void visitPHINode(PHINode &PN);
327 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000328 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
329 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000330 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000331 void visitVAArg(VAArgInst &I);
332 void visitInstruction(Instruction &I);
333 };
334
Chris Lattner7f8897f2006-08-27 22:42:52 +0000335 RegisterPass<Andersens> X("anders-aa",
336 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000337 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000338}
339
Jeff Cohen534927d2005-01-08 22:01:16 +0000340ModulePass *llvm::createAndersensPass() { return new Andersens(); }
341
Chris Lattnere995a2a2004-05-23 21:00:47 +0000342//===----------------------------------------------------------------------===//
343// AliasAnalysis Interface Implementation
344//===----------------------------------------------------------------------===//
345
346AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
347 const Value *V2, unsigned V2Size) {
Chris Lattnerf392c642005-03-28 06:21:17 +0000348 Node *N1 = getNode(const_cast<Value*>(V1));
349 Node *N2 = getNode(const_cast<Value*>(V2));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000350
351 // Check to see if the two pointers are known to not alias. They don't alias
352 // if their points-to sets do not intersect.
353 if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
354 return NoAlias;
355
356 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
357}
358
Chris Lattnerf392c642005-03-28 06:21:17 +0000359AliasAnalysis::ModRefResult
360Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
361 // The only thing useful that we can contribute for mod/ref information is
362 // when calling external function calls: if we know that memory never escapes
363 // from the program, it cannot be modified by an external call.
364 //
365 // NOTE: This is not really safe, at least not when the entire program is not
366 // available. The deal is that the external function could call back into the
367 // program and modify stuff. We ignore this technical niggle for now. This
368 // is, after all, a "research quality" implementation of Andersen's analysis.
369 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000370 if (F->isDeclaration()) {
Chris Lattnerf392c642005-03-28 06:21:17 +0000371 Node *N1 = getNode(P);
Chris Lattnerf392c642005-03-28 06:21:17 +0000372
Chris Lattner8a9763c2005-04-04 22:23:21 +0000373 if (N1->begin() == N1->end())
374 return NoModRef; // P doesn't point to anything.
Chris Lattnerf392c642005-03-28 06:21:17 +0000375
Chris Lattner8a9763c2005-04-04 22:23:21 +0000376 // Get the first pointee.
377 Node *FirstPointee = *N1->begin();
378 if (FirstPointee != &GraphNodes[UniversalSet])
Chris Lattnerf392c642005-03-28 06:21:17 +0000379 return NoModRef; // P doesn't point to the universal set.
380 }
381
382 return AliasAnalysis::getModRefInfo(CS, P, Size);
383}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000384
Reid Spencer3a9ec242006-08-28 01:02:49 +0000385AliasAnalysis::ModRefResult
386Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
387 return AliasAnalysis::getModRefInfo(CS1,CS2);
388}
389
Chris Lattnere995a2a2004-05-23 21:00:47 +0000390/// getMustAlias - We can provide must alias information if we know that a
391/// pointer can only point to a specific function or the null pointer.
392/// Unfortunately we cannot determine must-alias information for global
393/// variables or any other memory memory objects because we do not track whether
394/// a pointer points to the beginning of an object or a field of it.
395void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
396 Node *N = getNode(P);
397 Node::iterator I = N->begin();
398 if (I != N->end()) {
399 // If there is exactly one element in the points-to set for the object...
400 ++I;
401 if (I == N->end()) {
402 Node *Pointee = *N->begin();
403
404 // If a function is the only object in the points-to set, then it must be
405 // the destination. Note that we can't handle global variables here,
406 // because we don't know if the pointer is actually pointing to a field of
407 // the global or to the beginning of it.
408 if (Value *V = Pointee->getValue()) {
409 if (Function *F = dyn_cast<Function>(V))
410 RetVals.push_back(F);
411 } else {
412 // If the object in the points-to set is the null object, then the null
413 // pointer is a must alias.
414 if (Pointee == &GraphNodes[NullObject])
415 RetVals.push_back(Constant::getNullValue(P->getType()));
416 }
417 }
418 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000419
Chris Lattnere995a2a2004-05-23 21:00:47 +0000420 AliasAnalysis::getMustAliases(P, RetVals);
421}
422
423/// pointsToConstantMemory - If we can determine that this pointer only points
424/// to constant memory, return true. In practice, this means that if the
425/// pointer can only point to constant globals, functions, or the null pointer,
426/// return true.
427///
428bool Andersens::pointsToConstantMemory(const Value *P) {
429 Node *N = getNode((Value*)P);
430 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
431 if (Value *V = (*I)->getValue()) {
432 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
433 !cast<GlobalVariable>(V)->isConstant()))
434 return AliasAnalysis::pointsToConstantMemory(P);
435 } else {
436 if (*I != &GraphNodes[NullObject])
437 return AliasAnalysis::pointsToConstantMemory(P);
438 }
439 }
440
441 return true;
442}
443
444//===----------------------------------------------------------------------===//
445// Object Identification Phase
446//===----------------------------------------------------------------------===//
447
448/// IdentifyObjects - This stage scans the program, adding an entry to the
449/// GraphNodes list for each memory object in the program (global stack or
450/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
451///
452void Andersens::IdentifyObjects(Module &M) {
453 unsigned NumObjects = 0;
454
455 // Object #0 is always the universal set: the object that we don't know
456 // anything about.
457 assert(NumObjects == UniversalSet && "Something changed!");
458 ++NumObjects;
459
460 // Object #1 always represents the null pointer.
461 assert(NumObjects == NullPtr && "Something changed!");
462 ++NumObjects;
463
464 // Object #2 always represents the null object (the object pointed to by null)
465 assert(NumObjects == NullObject && "Something changed!");
466 ++NumObjects;
467
468 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000469 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
470 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000471 ObjectNodes[I] = NumObjects++;
472 ValueNodes[I] = NumObjects++;
473 }
474
475 // Add nodes for all of the functions and the instructions inside of them.
476 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
477 // The function itself is a memory object.
478 ValueNodes[F] = NumObjects++;
479 ObjectNodes[F] = NumObjects++;
480 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
481 ReturnNodes[F] = NumObjects++;
482 if (F->getFunctionType()->isVarArg())
483 VarargNodes[F] = NumObjects++;
484
485 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000486 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
487 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000488 if (isa<PointerType>(I->getType()))
489 ValueNodes[I] = NumObjects++;
490
491 // Scan the function body, creating a memory object for each heap/stack
492 // allocation in the body of the function and a node to represent all
493 // pointer values defined by instructions and used as operands.
494 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
495 // If this is an heap or stack allocation, create a node for the memory
496 // object.
497 if (isa<PointerType>(II->getType())) {
498 ValueNodes[&*II] = NumObjects++;
499 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
500 ObjectNodes[AI] = NumObjects++;
501 }
502 }
503 }
504
505 // Now that we know how many objects to create, make them all now!
506 GraphNodes.resize(NumObjects);
507 NumNodes += NumObjects;
508}
509
510//===----------------------------------------------------------------------===//
511// Constraint Identification Phase
512//===----------------------------------------------------------------------===//
513
514/// getNodeForConstantPointer - Return the node corresponding to the constant
515/// pointer itself.
516Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
517 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
518
Chris Lattner267a1b02005-03-27 18:58:23 +0000519 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000520 return &GraphNodes[NullPtr];
Reid Spencere8404342004-07-18 00:18:30 +0000521 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
522 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000523 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
524 switch (CE->getOpcode()) {
525 case Instruction::GetElementPtr:
526 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000527 case Instruction::IntToPtr:
528 return &GraphNodes[UniversalSet];
529 case Instruction::BitCast:
530 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000531 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000532 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000533 assert(0);
534 }
535 } else {
536 assert(0 && "Unknown constant pointer!");
537 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000538 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000539}
540
541/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
542/// specified constant pointer.
543Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
544 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
545
546 if (isa<ConstantPointerNull>(C))
547 return &GraphNodes[NullObject];
Reid Spencere8404342004-07-18 00:18:30 +0000548 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
549 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000550 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
551 switch (CE->getOpcode()) {
552 case Instruction::GetElementPtr:
553 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000554 case Instruction::IntToPtr:
555 return &GraphNodes[UniversalSet];
556 case Instruction::BitCast:
557 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000558 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000559 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000560 assert(0);
561 }
562 } else {
563 assert(0 && "Unknown constant pointer!");
564 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000565 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000566}
567
568/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
569/// object N, which contains values indicated by C.
570void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
571 if (C->getType()->isFirstClassType()) {
572 if (isa<PointerType>(C->getType()))
Chris Lattner76bc5ce2005-03-29 17:21:53 +0000573 N->copyFrom(getNodeForConstantPointer(C));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000574
Chris Lattnere995a2a2004-05-23 21:00:47 +0000575 } else if (C->isNullValue()) {
576 N->addPointerTo(&GraphNodes[NullObject]);
577 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000578 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000579 // If this is an array or struct, include constraints for each element.
580 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
581 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
582 AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
583 }
584}
585
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000586/// AddConstraintsForNonInternalLinkage - If this function does not have
587/// internal linkage, realize that we can't trust anything passed into or
588/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000589void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000590 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000591 if (isa<PointerType>(I->getType()))
592 // If this is an argument of an externally accessible function, the
593 // incoming pointer might point to anything.
594 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
595 &GraphNodes[UniversalSet]));
596}
597
Chris Lattner8a446432005-03-29 06:09:07 +0000598/// AddConstraintsForCall - If this is a call to a "known" function, add the
599/// constraints and return true. If this is a call to an unknown function,
600/// return false.
601bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000602 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000603
604 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000605 if (F->getName() == "atoi" || F->getName() == "atof" ||
606 F->getName() == "atol" || F->getName() == "atoll" ||
607 F->getName() == "remove" || F->getName() == "unlink" ||
608 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000609 F->getName() == "llvm.memset.i32" ||
610 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000611 F->getName() == "strcmp" || F->getName() == "strncmp" ||
612 F->getName() == "execl" || F->getName() == "execlp" ||
613 F->getName() == "execle" || F->getName() == "execv" ||
614 F->getName() == "execvp" || F->getName() == "chmod" ||
615 F->getName() == "puts" || F->getName() == "write" ||
616 F->getName() == "open" || F->getName() == "create" ||
617 F->getName() == "truncate" || F->getName() == "chdir" ||
618 F->getName() == "mkdir" || F->getName() == "rmdir" ||
619 F->getName() == "read" || F->getName() == "pipe" ||
620 F->getName() == "wait" || F->getName() == "time" ||
621 F->getName() == "stat" || F->getName() == "fstat" ||
622 F->getName() == "lstat" || F->getName() == "strtod" ||
623 F->getName() == "strtof" || F->getName() == "strtold" ||
624 F->getName() == "fopen" || F->getName() == "fdopen" ||
625 F->getName() == "freopen" ||
626 F->getName() == "fflush" || F->getName() == "feof" ||
627 F->getName() == "fileno" || F->getName() == "clearerr" ||
628 F->getName() == "rewind" || F->getName() == "ftell" ||
629 F->getName() == "ferror" || F->getName() == "fgetc" ||
630 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
631 F->getName() == "fwrite" || F->getName() == "fread" ||
632 F->getName() == "fgets" || F->getName() == "ungetc" ||
633 F->getName() == "fputc" ||
634 F->getName() == "fputs" || F->getName() == "putc" ||
635 F->getName() == "ftell" || F->getName() == "rewind" ||
636 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
637 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
638 F->getName() == "printf" || F->getName() == "fprintf" ||
639 F->getName() == "sprintf" || F->getName() == "vprintf" ||
640 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
641 F->getName() == "scanf" || F->getName() == "fscanf" ||
642 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
643 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000644 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000645
Chris Lattner175b9632005-03-29 20:36:05 +0000646
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000647 // These functions do induce points-to edges.
Chris Lattner01ac91e2006-03-03 01:21:36 +0000648 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
649 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000650 F->getName() == "memmove") {
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000651 // Note: this is a poor approximation, this says Dest = Src, instead of
652 // *Dest = *Src.
Chris Lattner8a446432005-03-29 06:09:07 +0000653 Constraints.push_back(Constraint(Constraint::Copy,
654 getNode(CS.getArgument(0)),
655 getNode(CS.getArgument(1))));
656 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000657 }
658
Chris Lattner77b50562005-03-29 20:04:24 +0000659 // Result = Arg0
660 if (F->getName() == "realloc" || F->getName() == "strchr" ||
661 F->getName() == "strrchr" || F->getName() == "strstr" ||
662 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000663 Constraints.push_back(Constraint(Constraint::Copy,
664 getNode(CS.getInstruction()),
665 getNode(CS.getArgument(0))));
666 return true;
667 }
668
669 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000670}
671
672
Chris Lattnere995a2a2004-05-23 21:00:47 +0000673
674/// CollectConstraints - This stage scans the program, adding a constraint to
675/// the Constraints list for each instruction in the program that induces a
676/// constraint, and setting up the initial points-to graph.
677///
678void Andersens::CollectConstraints(Module &M) {
679 // First, the universal set points to itself.
680 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
Chris Lattner4de57fd2005-03-29 06:52:20 +0000681 //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
682 // &GraphNodes[UniversalSet]));
Chris Lattnerf392c642005-03-28 06:21:17 +0000683 Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
684 &GraphNodes[UniversalSet]));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000685
686 // Next, the null pointer points to the null object.
687 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
688
689 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000690 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
691 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000692 // Associate the address of the global object as pointing to the memory for
693 // the global: &G = <G memory>
694 Node *Object = getObject(I);
695 Object->setValue(I);
696 getNodeValue(*I)->addPointerTo(Object);
697
698 if (I->hasInitializer()) {
699 AddGlobalInitializerConstraints(Object, I->getInitializer());
700 } else {
701 // If it doesn't have an initializer (i.e. it's defined in another
702 // translation unit), it points to the universal set.
703 Constraints.push_back(Constraint(Constraint::Copy, Object,
704 &GraphNodes[UniversalSet]));
705 }
706 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000707
Chris Lattnere995a2a2004-05-23 21:00:47 +0000708 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
709 // Make the function address point to the function object.
710 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
711
712 // Set up the return value node.
713 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
714 getReturnNode(F)->setValue(F);
715 if (F->getFunctionType()->isVarArg())
716 getVarargNode(F)->setValue(F);
717
718 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000719 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
720 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000721 if (isa<PointerType>(I->getType()))
722 getNodeValue(*I);
723
724 if (!F->hasInternalLinkage())
725 AddConstraintsForNonInternalLinkage(F);
726
Reid Spencer5cbf9852007-01-30 20:08:39 +0000727 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000728 // Scan the function body, creating a memory object for each heap/stack
729 // allocation in the body of the function and a node to represent all
730 // pointer values defined by instructions and used as operands.
731 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000732 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000733 // External functions that return pointers return the universal set.
734 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
735 Constraints.push_back(Constraint(Constraint::Copy,
736 getReturnNode(F),
737 &GraphNodes[UniversalSet]));
738
739 // Any pointers that are passed into the function have the universal set
740 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000741 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
742 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000743 if (isa<PointerType>(I->getType())) {
744 // Pointers passed into external functions could have anything stored
745 // through them.
746 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
747 &GraphNodes[UniversalSet]));
748 // Memory objects passed into external function calls can have the
749 // universal set point to them.
750 Constraints.push_back(Constraint(Constraint::Copy,
751 &GraphNodes[UniversalSet],
752 getNode(I)));
753 }
754
755 // If this is an external varargs function, it can also store pointers
756 // into any pointers passed through the varargs section.
757 if (F->getFunctionType()->isVarArg())
758 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
759 &GraphNodes[UniversalSet]));
760 }
761 }
762 NumConstraints += Constraints.size();
763}
764
765
766void Andersens::visitInstruction(Instruction &I) {
767#ifdef NDEBUG
768 return; // This function is just a big assert.
769#endif
770 if (isa<BinaryOperator>(I))
771 return;
772 // Most instructions don't have any effect on pointer values.
773 switch (I.getOpcode()) {
774 case Instruction::Br:
775 case Instruction::Switch:
776 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +0000777 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000778 case Instruction::Free:
779 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000780 case Instruction::LShr:
781 case Instruction::AShr:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000782 case Instruction::ICmp:
783 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000784 return;
785 default:
786 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +0000787 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000788 abort();
789 }
790}
791
792void Andersens::visitAllocationInst(AllocationInst &AI) {
793 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
794}
795
796void Andersens::visitReturnInst(ReturnInst &RI) {
797 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
798 // return V --> <Copy/retval{F}/v>
799 Constraints.push_back(Constraint(Constraint::Copy,
800 getReturnNode(RI.getParent()->getParent()),
801 getNode(RI.getOperand(0))));
802}
803
804void Andersens::visitLoadInst(LoadInst &LI) {
805 if (isa<PointerType>(LI.getType()))
806 // P1 = load P2 --> <Load/P1/P2>
807 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
808 getNode(LI.getOperand(0))));
809}
810
811void Andersens::visitStoreInst(StoreInst &SI) {
812 if (isa<PointerType>(SI.getOperand(0)->getType()))
813 // store P1, P2 --> <Store/P2/P1>
814 Constraints.push_back(Constraint(Constraint::Store,
815 getNode(SI.getOperand(1)),
816 getNode(SI.getOperand(0))));
817}
818
819void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
820 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
821 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
822 getNode(GEP.getOperand(0))));
823}
824
825void Andersens::visitPHINode(PHINode &PN) {
826 if (isa<PointerType>(PN.getType())) {
827 Node *PNN = getNodeValue(PN);
828 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
829 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
830 Constraints.push_back(Constraint(Constraint::Copy, PNN,
831 getNode(PN.getIncomingValue(i))));
832 }
833}
834
835void Andersens::visitCastInst(CastInst &CI) {
836 Value *Op = CI.getOperand(0);
837 if (isa<PointerType>(CI.getType())) {
838 if (isa<PointerType>(Op->getType())) {
839 // P1 = cast P2 --> <Copy/P1/P2>
840 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
841 getNode(CI.getOperand(0))));
842 } else {
843 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +0000844#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000845 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
846 &GraphNodes[UniversalSet]));
Chris Lattnerbd135c72005-04-05 01:12:03 +0000847#else
848 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +0000849#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000850 }
851 } else if (isa<PointerType>(Op->getType())) {
852 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +0000853#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000854 Constraints.push_back(Constraint(Constraint::Copy,
855 &GraphNodes[UniversalSet],
856 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +0000857#else
858 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +0000859#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000860 }
861}
862
863void Andersens::visitSelectInst(SelectInst &SI) {
864 if (isa<PointerType>(SI.getType())) {
865 Node *SIN = getNodeValue(SI);
866 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
867 Constraints.push_back(Constraint(Constraint::Copy, SIN,
868 getNode(SI.getOperand(1))));
869 Constraints.push_back(Constraint(Constraint::Copy, SIN,
870 getNode(SI.getOperand(2))));
871 }
872}
873
Chris Lattnere995a2a2004-05-23 21:00:47 +0000874void Andersens::visitVAArg(VAArgInst &I) {
875 assert(0 && "vaarg not handled yet!");
876}
877
878/// AddConstraintsForCall - Add constraints for a call with actual arguments
879/// specified by CS to the function specified by F. Note that the types of
880/// arguments might not match up in the case where this is an indirect call and
881/// the function pointer has been casted. If this is the case, do something
882/// reasonable.
883void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Chris Lattner8a446432005-03-29 06:09:07 +0000884 // If this is a call to an external function, handle it directly to get some
885 // taste of context sensitivity.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000886 if (F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +0000887 return;
888
Chris Lattnere995a2a2004-05-23 21:00:47 +0000889 if (isa<PointerType>(CS.getType())) {
890 Node *CSN = getNode(CS.getInstruction());
891 if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
892 Constraints.push_back(Constraint(Constraint::Copy, CSN,
893 getReturnNode(F)));
894 } else {
895 // If the function returns a non-pointer value, handle this just like we
896 // treat a nonpointer cast to pointer.
897 Constraints.push_back(Constraint(Constraint::Copy, CSN,
898 &GraphNodes[UniversalSet]));
899 }
900 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
901 Constraints.push_back(Constraint(Constraint::Copy,
902 &GraphNodes[UniversalSet],
903 getReturnNode(F)));
904 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000905
Chris Lattnere4d5c442005-03-15 04:54:21 +0000906 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000907 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
908 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
909 if (isa<PointerType>(AI->getType())) {
910 if (isa<PointerType>((*ArgI)->getType())) {
911 // Copy the actual argument into the formal argument.
912 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
913 getNode(*ArgI)));
914 } else {
915 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
916 &GraphNodes[UniversalSet]));
917 }
918 } else if (isa<PointerType>((*ArgI)->getType())) {
919 Constraints.push_back(Constraint(Constraint::Copy,
920 &GraphNodes[UniversalSet],
921 getNode(*ArgI)));
922 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000923
Chris Lattnere995a2a2004-05-23 21:00:47 +0000924 // Copy all pointers passed through the varargs section to the varargs node.
925 if (F->getFunctionType()->isVarArg())
926 for (; ArgI != ArgE; ++ArgI)
927 if (isa<PointerType>((*ArgI)->getType()))
928 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
929 getNode(*ArgI)));
930 // If more arguments are passed in than we track, just drop them on the floor.
931}
932
933void Andersens::visitCallSite(CallSite CS) {
934 if (isa<PointerType>(CS.getType()))
935 getNodeValue(*CS.getInstruction());
936
937 if (Function *F = CS.getCalledFunction()) {
938 AddConstraintsForCall(CS, F);
939 } else {
940 // We don't handle indirect call sites yet. Keep track of them for when we
941 // discover the call graph incrementally.
942 IndirectCalls.push_back(CS);
943 }
944}
945
946//===----------------------------------------------------------------------===//
947// Constraint Solving Phase
948//===----------------------------------------------------------------------===//
949
950/// intersects - Return true if the points-to set of this node intersects
951/// with the points-to set of the specified node.
952bool Andersens::Node::intersects(Node *N) const {
953 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
954 while (I1 != E1 && I2 != E2) {
955 if (*I1 == *I2) return true;
956 if (*I1 < *I2)
957 ++I1;
958 else
959 ++I2;
960 }
961 return false;
962}
963
964/// intersectsIgnoring - Return true if the points-to set of this node
965/// intersects with the points-to set of the specified node on any nodes
966/// except for the specified node to ignore.
967bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
968 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
969 while (I1 != E1 && I2 != E2) {
970 if (*I1 == *I2) {
971 if (*I1 != Ignoring) return true;
972 ++I1; ++I2;
973 } else if (*I1 < *I2)
974 ++I1;
975 else
976 ++I2;
977 }
978 return false;
979}
980
981// Copy constraint: all edges out of the source node get copied to the
982// destination node. This returns true if a change is made.
983bool Andersens::Node::copyFrom(Node *N) {
984 // Use a mostly linear-time merge since both of the lists are sorted.
985 bool Changed = false;
986 iterator I = N->begin(), E = N->end();
987 unsigned i = 0;
988 while (I != E && i != Pointees.size()) {
989 if (Pointees[i] < *I) {
990 ++i;
991 } else if (Pointees[i] == *I) {
992 ++i; ++I;
993 } else {
994 // We found a new element to copy over.
995 Changed = true;
996 Pointees.insert(Pointees.begin()+i, *I);
997 ++i; ++I;
998 }
999 }
1000
1001 if (I != E) {
1002 Pointees.insert(Pointees.end(), I, E);
1003 Changed = true;
1004 }
1005
1006 return Changed;
1007}
1008
1009bool Andersens::Node::loadFrom(Node *N) {
1010 bool Changed = false;
1011 for (iterator I = N->begin(), E = N->end(); I != E; ++I)
1012 Changed |= copyFrom(*I);
1013 return Changed;
1014}
1015
1016bool Andersens::Node::storeThrough(Node *N) {
1017 bool Changed = false;
1018 for (iterator I = begin(), E = end(); I != E; ++I)
1019 Changed |= (*I)->copyFrom(N);
1020 return Changed;
1021}
1022
1023
1024/// SolveConstraints - This stage iteratively processes the constraints list
1025/// propagating constraints (adding edges to the Nodes in the points-to graph)
1026/// until a fixed point is reached.
1027///
1028void Andersens::SolveConstraints() {
1029 bool Changed = true;
1030 unsigned Iteration = 0;
1031 while (Changed) {
1032 Changed = false;
1033 ++NumIters;
Bill Wendling9be7ac12006-11-17 07:36:54 +00001034 DOUT << "Starting iteration #" << Iteration++ << "!\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001035
1036 // Loop over all of the constraints, applying them in turn.
1037 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1038 Constraint &C = Constraints[i];
1039 switch (C.Type) {
1040 case Constraint::Copy:
1041 Changed |= C.Dest->copyFrom(C.Src);
1042 break;
1043 case Constraint::Load:
1044 Changed |= C.Dest->loadFrom(C.Src);
1045 break;
1046 case Constraint::Store:
1047 Changed |= C.Dest->storeThrough(C.Src);
1048 break;
1049 default:
1050 assert(0 && "Unknown constraint!");
1051 }
1052 }
1053
1054 if (Changed) {
1055 // Check to see if any internal function's addresses have been passed to
1056 // external functions. If so, we have to assume that their incoming
1057 // arguments could be anything. If there are any internal functions in
1058 // the universal node that we don't know about, we must iterate.
1059 for (Node::iterator I = GraphNodes[UniversalSet].begin(),
1060 E = GraphNodes[UniversalSet].end(); I != E; ++I)
1061 if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
1062 if (F->hasInternalLinkage() &&
1063 EscapingInternalFunctions.insert(F).second) {
1064 // We found a function that is just now escaping. Mark it as if it
1065 // didn't have internal linkage.
1066 AddConstraintsForNonInternalLinkage(F);
Bill Wendling9be7ac12006-11-17 07:36:54 +00001067 DOUT << "Found escaping internal function: " << F->getName() <<"\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001068 ++NumEscapingFunctions;
1069 }
1070
1071 // Check to see if we have discovered any new callees of the indirect call
1072 // sites. If so, add constraints to the analysis.
1073 for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1074 CallSite CS = IndirectCalls[i];
1075 std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1076 Node *CN = getNode(CS.getCalledValue());
1077
1078 for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1079 if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1080 std::vector<Function*>::iterator IP =
1081 std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1082 if (IP == KnownCallees.end() || *IP != F) {
1083 // Add the constraints for the call now.
1084 AddConstraintsForCall(CS, F);
Bill Wendling9be7ac12006-11-17 07:36:54 +00001085 DOUT << "Found actual callee '"
1086 << F->getName() << "' for call: "
1087 << *CS.getInstruction() << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001088 ++NumIndirectCallees;
1089 KnownCallees.insert(IP, F);
1090 }
1091 }
1092 }
1093 }
1094 }
1095}
1096
1097
1098
1099//===----------------------------------------------------------------------===//
1100// Debugging Output
1101//===----------------------------------------------------------------------===//
1102
1103void Andersens::PrintNode(Node *N) {
1104 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001105 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001106 return;
1107 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001108 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001109 return;
1110 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001111 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001112 return;
1113 }
1114
1115 assert(N->getValue() != 0 && "Never set node label!");
1116 Value *V = N->getValue();
1117 if (Function *F = dyn_cast<Function>(V)) {
1118 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1119 N == getReturnNode(F)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001120 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001121 return;
1122 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001123 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001124 return;
1125 }
1126 }
1127
1128 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001129 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001130 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001131 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001132
1133 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00001134 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00001135 else
Bill Wendlinge8156192006-12-07 01:30:32 +00001136 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001137
1138 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1139 if (N == getObject(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001140 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001141}
1142
1143void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001144 cerr << "Constraints:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001145 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001146 cerr << " #" << i << ": ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001147 Constraint &C = Constraints[i];
1148 if (C.Type == Constraint::Store)
Bill Wendlinge8156192006-12-07 01:30:32 +00001149 cerr << "*";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001150 PrintNode(C.Dest);
Bill Wendlinge8156192006-12-07 01:30:32 +00001151 cerr << " = ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001152 if (C.Type == Constraint::Load)
Bill Wendlinge8156192006-12-07 01:30:32 +00001153 cerr << "*";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001154 PrintNode(C.Src);
Bill Wendlinge8156192006-12-07 01:30:32 +00001155 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001156 }
1157}
1158
1159void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001160 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001161 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1162 Node *N = &GraphNodes[i];
Bill Wendlinge8156192006-12-07 01:30:32 +00001163 cerr << "[" << (N->end() - N->begin()) << "] ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001164 PrintNode(N);
Bill Wendlinge8156192006-12-07 01:30:32 +00001165 cerr << "\t--> ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001166 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001167 if (I != N->begin()) cerr << ", ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001168 PrintNode(*I);
1169 }
Bill Wendlinge8156192006-12-07 01:30:32 +00001170 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001171 }
1172}