blob: 146c88aaebd1f464d121113bab7ec24ea52c8813 [file] [log] [blame]
Chris Lattnerd28b0d72004-06-25 04:24:22 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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
46// scale reasonably well, the inclusion constraints could be sorted (easy),
47// offline variable substitution would be a huge win (straight-forward), and
48// 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 {
68 Statistic<>
69 NumIters("anders-aa", "Number of iterations to reach convergence");
70 Statistic<>
71 NumConstraints("anders-aa", "Number of constraints");
72 Statistic<>
73 NumNodes("anders-aa", "Number of nodes");
74 Statistic<>
75 NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
76 Statistic<>
77 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
140 /// program: globals, alloca's and mallocs.
141 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 };
164
165 /// 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,
194 NullObject = 2,
195 };
196
197 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();
212 std::vector<Constraint>().swap(Constraints);
213 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
235 //
236 AliasResult alias(const Value *V1, unsigned V1Size,
237 const Value *V2, unsigned V2Size);
Chris Lattnerf392c642005-03-28 06:21:17 +0000238 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000239 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
240 bool pointsToConstantMemory(const Value *P);
241
242 virtual void deleteValue(Value *V) {
243 ValueNodes.erase(V);
244 getAnalysis<AliasAnalysis>().deleteValue(V);
245 }
246
247 virtual void copyValue(Value *From, Value *To) {
248 ValueNodes[To] = ValueNodes[From];
249 getAnalysis<AliasAnalysis>().copyValue(From, To);
250 }
251
252 private:
253 /// getNode - Return the node corresponding to the specified pointer scalar.
254 ///
255 Node *getNode(Value *V) {
256 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000257 if (!isa<GlobalValue>(C))
258 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000259
260 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
261 if (I == ValueNodes.end()) {
262 V->dump();
263 assert(I != ValueNodes.end() &&
264 "Value does not have a node in the points-to graph!");
265 }
266 return &GraphNodes[I->second];
267 }
268
269 /// getObject - Return the node corresponding to the memory object for the
270 /// specified global or allocation instruction.
271 Node *getObject(Value *V) {
272 std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
273 assert(I != ObjectNodes.end() &&
274 "Value does not have an object in the points-to graph!");
275 return &GraphNodes[I->second];
276 }
277
278 /// getReturnNode - Return the node representing the return value for the
279 /// specified function.
280 Node *getReturnNode(Function *F) {
281 std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
282 assert(I != ReturnNodes.end() && "Function does not return a value!");
283 return &GraphNodes[I->second];
284 }
285
286 /// getVarargNode - Return the node representing the variable arguments
287 /// formal for the specified function.
288 Node *getVarargNode(Function *F) {
289 std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
290 assert(I != VarargNodes.end() && "Function does not take var args!");
291 return &GraphNodes[I->second];
292 }
293
294 /// getNodeValue - Get the node for the specified LLVM value and set the
295 /// value for it to be the specified value.
296 Node *getNodeValue(Value &V) {
297 return getNode(&V)->setValue(&V);
298 }
299
300 void IdentifyObjects(Module &M);
301 void CollectConstraints(Module &M);
302 void SolveConstraints();
303
304 Node *getNodeForConstantPointer(Constant *C);
305 Node *getNodeForConstantPointerTarget(Constant *C);
306 void AddGlobalInitializerConstraints(Node *N, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000307
Chris Lattnere995a2a2004-05-23 21:00:47 +0000308 void AddConstraintsForNonInternalLinkage(Function *F);
309 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000310 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000311
312
313 void PrintNode(Node *N);
314 void PrintConstraints();
315 void PrintPointsToGraph();
316
317 //===------------------------------------------------------------------===//
318 // Instruction visitation methods for adding constraints
319 //
320 friend class InstVisitor<Andersens>;
321 void visitReturnInst(ReturnInst &RI);
322 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
323 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
324 void visitCallSite(CallSite CS);
325 void visitAllocationInst(AllocationInst &AI);
326 void visitLoadInst(LoadInst &LI);
327 void visitStoreInst(StoreInst &SI);
328 void visitGetElementPtrInst(GetElementPtrInst &GEP);
329 void visitPHINode(PHINode &PN);
330 void visitCastInst(CastInst &CI);
Chris Lattner4de57fd2005-03-29 06:52:20 +0000331 void visitSetCondInst(SetCondInst &SCI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000332 void visitSelectInst(SelectInst &SI);
333 void visitVANext(VANextInst &I);
334 void visitVAArg(VAArgInst &I);
335 void visitInstruction(Instruction &I);
336 };
337
338 RegisterOpt<Andersens> X("anders-aa",
339 "Andersen's Interprocedural Alias Analysis");
340 RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
341}
342
Jeff Cohen534927d2005-01-08 22:01:16 +0000343ModulePass *llvm::createAndersensPass() { return new Andersens(); }
344
Chris Lattnere995a2a2004-05-23 21:00:47 +0000345//===----------------------------------------------------------------------===//
346// AliasAnalysis Interface Implementation
347//===----------------------------------------------------------------------===//
348
349AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
350 const Value *V2, unsigned V2Size) {
Chris Lattnerf392c642005-03-28 06:21:17 +0000351 Node *N1 = getNode(const_cast<Value*>(V1));
352 Node *N2 = getNode(const_cast<Value*>(V2));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000353
354 // Check to see if the two pointers are known to not alias. They don't alias
355 // if their points-to sets do not intersect.
356 if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
357 return NoAlias;
358
359 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
360}
361
Chris Lattnerf392c642005-03-28 06:21:17 +0000362AliasAnalysis::ModRefResult
363Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
364 // The only thing useful that we can contribute for mod/ref information is
365 // when calling external function calls: if we know that memory never escapes
366 // from the program, it cannot be modified by an external call.
367 //
368 // NOTE: This is not really safe, at least not when the entire program is not
369 // available. The deal is that the external function could call back into the
370 // program and modify stuff. We ignore this technical niggle for now. This
371 // is, after all, a "research quality" implementation of Andersen's analysis.
372 if (Function *F = CS.getCalledFunction())
373 if (F->isExternal()) {
374 Node *N1 = getNode(P);
375 bool PointsToUniversalSet = false;
376
377 for (Node::iterator NI = N1->begin(), E = N1->end(); NI != E; ++NI) {
378 Node *PN = *NI;
379 if (PN->begin() == PN->end())
380 continue; // P doesn't point to anything.
381 // Get the first pointee.
382 Node *FirstPointee = *PN->begin();
383 if (FirstPointee == &GraphNodes[UniversalSet]) {
384 PointsToUniversalSet = true;
385 break;
386 }
387 }
388
389 if (!PointsToUniversalSet)
390 return NoModRef; // P doesn't point to the universal set.
391 }
392
393 return AliasAnalysis::getModRefInfo(CS, P, Size);
394}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000395
Chris Lattnere995a2a2004-05-23 21:00:47 +0000396/// getMustAlias - We can provide must alias information if we know that a
397/// pointer can only point to a specific function or the null pointer.
398/// Unfortunately we cannot determine must-alias information for global
399/// variables or any other memory memory objects because we do not track whether
400/// a pointer points to the beginning of an object or a field of it.
401void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
402 Node *N = getNode(P);
403 Node::iterator I = N->begin();
404 if (I != N->end()) {
405 // If there is exactly one element in the points-to set for the object...
406 ++I;
407 if (I == N->end()) {
408 Node *Pointee = *N->begin();
409
410 // If a function is the only object in the points-to set, then it must be
411 // the destination. Note that we can't handle global variables here,
412 // because we don't know if the pointer is actually pointing to a field of
413 // the global or to the beginning of it.
414 if (Value *V = Pointee->getValue()) {
415 if (Function *F = dyn_cast<Function>(V))
416 RetVals.push_back(F);
417 } else {
418 // If the object in the points-to set is the null object, then the null
419 // pointer is a must alias.
420 if (Pointee == &GraphNodes[NullObject])
421 RetVals.push_back(Constant::getNullValue(P->getType()));
422 }
423 }
424 }
425
426 AliasAnalysis::getMustAliases(P, RetVals);
427}
428
429/// pointsToConstantMemory - If we can determine that this pointer only points
430/// to constant memory, return true. In practice, this means that if the
431/// pointer can only point to constant globals, functions, or the null pointer,
432/// return true.
433///
434bool Andersens::pointsToConstantMemory(const Value *P) {
435 Node *N = getNode((Value*)P);
436 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
437 if (Value *V = (*I)->getValue()) {
438 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
439 !cast<GlobalVariable>(V)->isConstant()))
440 return AliasAnalysis::pointsToConstantMemory(P);
441 } else {
442 if (*I != &GraphNodes[NullObject])
443 return AliasAnalysis::pointsToConstantMemory(P);
444 }
445 }
446
447 return true;
448}
449
450//===----------------------------------------------------------------------===//
451// Object Identification Phase
452//===----------------------------------------------------------------------===//
453
454/// IdentifyObjects - This stage scans the program, adding an entry to the
455/// GraphNodes list for each memory object in the program (global stack or
456/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
457///
458void Andersens::IdentifyObjects(Module &M) {
459 unsigned NumObjects = 0;
460
461 // Object #0 is always the universal set: the object that we don't know
462 // anything about.
463 assert(NumObjects == UniversalSet && "Something changed!");
464 ++NumObjects;
465
466 // Object #1 always represents the null pointer.
467 assert(NumObjects == NullPtr && "Something changed!");
468 ++NumObjects;
469
470 // Object #2 always represents the null object (the object pointed to by null)
471 assert(NumObjects == NullObject && "Something changed!");
472 ++NumObjects;
473
474 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000475 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
476 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000477 ObjectNodes[I] = NumObjects++;
478 ValueNodes[I] = NumObjects++;
479 }
480
481 // Add nodes for all of the functions and the instructions inside of them.
482 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
483 // The function itself is a memory object.
484 ValueNodes[F] = NumObjects++;
485 ObjectNodes[F] = NumObjects++;
486 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
487 ReturnNodes[F] = NumObjects++;
488 if (F->getFunctionType()->isVarArg())
489 VarargNodes[F] = NumObjects++;
490
491 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000492 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
493 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000494 if (isa<PointerType>(I->getType()))
495 ValueNodes[I] = NumObjects++;
496
497 // Scan the function body, creating a memory object for each heap/stack
498 // allocation in the body of the function and a node to represent all
499 // pointer values defined by instructions and used as operands.
500 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
501 // If this is an heap or stack allocation, create a node for the memory
502 // object.
503 if (isa<PointerType>(II->getType())) {
504 ValueNodes[&*II] = NumObjects++;
505 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
506 ObjectNodes[AI] = NumObjects++;
507 }
508 }
509 }
510
511 // Now that we know how many objects to create, make them all now!
512 GraphNodes.resize(NumObjects);
513 NumNodes += NumObjects;
514}
515
516//===----------------------------------------------------------------------===//
517// Constraint Identification Phase
518//===----------------------------------------------------------------------===//
519
520/// getNodeForConstantPointer - Return the node corresponding to the constant
521/// pointer itself.
522Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
523 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
524
Chris Lattner267a1b02005-03-27 18:58:23 +0000525 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000526 return &GraphNodes[NullPtr];
Reid Spencere8404342004-07-18 00:18:30 +0000527 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
528 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000529 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
530 switch (CE->getOpcode()) {
531 case Instruction::GetElementPtr:
532 return getNodeForConstantPointer(CE->getOperand(0));
533 case Instruction::Cast:
534 if (isa<PointerType>(CE->getOperand(0)->getType()))
535 return getNodeForConstantPointer(CE->getOperand(0));
536 else
537 return &GraphNodes[UniversalSet];
538 default:
539 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
540 assert(0);
541 }
542 } else {
543 assert(0 && "Unknown constant pointer!");
544 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000545 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000546}
547
548/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
549/// specified constant pointer.
550Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
551 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
552
553 if (isa<ConstantPointerNull>(C))
554 return &GraphNodes[NullObject];
Reid Spencere8404342004-07-18 00:18:30 +0000555 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
556 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000557 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
558 switch (CE->getOpcode()) {
559 case Instruction::GetElementPtr:
560 return getNodeForConstantPointerTarget(CE->getOperand(0));
561 case Instruction::Cast:
562 if (isa<PointerType>(CE->getOperand(0)->getType()))
563 return getNodeForConstantPointerTarget(CE->getOperand(0));
564 else
565 return &GraphNodes[UniversalSet];
566 default:
567 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
568 assert(0);
569 }
570 } else {
571 assert(0 && "Unknown constant pointer!");
572 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000573 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000574}
575
576/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
577/// object N, which contains values indicated by C.
578void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
579 if (C->getType()->isFirstClassType()) {
580 if (isa<PointerType>(C->getType()))
Chris Lattner76bc5ce2005-03-29 17:21:53 +0000581 N->copyFrom(getNodeForConstantPointer(C));
582
Chris Lattnere995a2a2004-05-23 21:00:47 +0000583 } else if (C->isNullValue()) {
584 N->addPointerTo(&GraphNodes[NullObject]);
585 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000586 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000587 // If this is an array or struct, include constraints for each element.
588 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
589 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
590 AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
591 }
592}
593
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000594/// AddConstraintsForNonInternalLinkage - If this function does not have
595/// internal linkage, realize that we can't trust anything passed into or
596/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000597void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000598 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000599 if (isa<PointerType>(I->getType()))
600 // If this is an argument of an externally accessible function, the
601 // incoming pointer might point to anything.
602 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
603 &GraphNodes[UniversalSet]));
604}
605
Chris Lattner8a446432005-03-29 06:09:07 +0000606/// AddConstraintsForCall - If this is a call to a "known" function, add the
607/// constraints and return true. If this is a call to an unknown function,
608/// return false.
609bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000610 assert(F->isExternal() && "Not an external function!");
611
612 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000613 if (F->getName() == "atoi" || F->getName() == "atof" ||
614 F->getName() == "atol" || F->getName() == "atoll" ||
615 F->getName() == "remove" || F->getName() == "unlink" ||
616 F->getName() == "rename" || F->getName() == "memcmp" ||
617 F->getName() == "llvm.memset" ||
618 F->getName() == "strcmp" || F->getName() == "strncmp" ||
619 F->getName() == "execl" || F->getName() == "execlp" ||
620 F->getName() == "execle" || F->getName() == "execv" ||
621 F->getName() == "execvp" || F->getName() == "chmod" ||
622 F->getName() == "puts" || F->getName() == "write" ||
623 F->getName() == "open" || F->getName() == "create" ||
624 F->getName() == "truncate" || F->getName() == "chdir" ||
625 F->getName() == "mkdir" || F->getName() == "rmdir" ||
626 F->getName() == "read" || F->getName() == "pipe" ||
627 F->getName() == "wait" || F->getName() == "time" ||
628 F->getName() == "stat" || F->getName() == "fstat" ||
629 F->getName() == "lstat" || F->getName() == "strtod" ||
630 F->getName() == "strtof" || F->getName() == "strtold" ||
631 F->getName() == "fopen" || F->getName() == "fdopen" ||
632 F->getName() == "freopen" ||
633 F->getName() == "fflush" || F->getName() == "feof" ||
634 F->getName() == "fileno" || F->getName() == "clearerr" ||
635 F->getName() == "rewind" || F->getName() == "ftell" ||
636 F->getName() == "ferror" || F->getName() == "fgetc" ||
637 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
638 F->getName() == "fwrite" || F->getName() == "fread" ||
639 F->getName() == "fgets" || F->getName() == "ungetc" ||
640 F->getName() == "fputc" ||
641 F->getName() == "fputs" || F->getName() == "putc" ||
642 F->getName() == "ftell" || F->getName() == "rewind" ||
643 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
644 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
645 F->getName() == "printf" || F->getName() == "fprintf" ||
646 F->getName() == "sprintf" || F->getName() == "vprintf" ||
647 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
648 F->getName() == "scanf" || F->getName() == "fscanf" ||
649 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
650 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000651 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000652
Chris Lattner175b9632005-03-29 20:36:05 +0000653
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000654 // These functions do induce points-to edges.
Chris Lattner4de57fd2005-03-29 06:52:20 +0000655 if (F->getName() == "llvm.memcpy" || F->getName() == "llvm.memmove" ||
656 F->getName() == "memmove") {
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000657 // Note: this is a poor approximation, this says Dest = Src, instead of
658 // *Dest = *Src.
Chris Lattner8a446432005-03-29 06:09:07 +0000659 Constraints.push_back(Constraint(Constraint::Copy,
660 getNode(CS.getArgument(0)),
661 getNode(CS.getArgument(1))));
662 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000663 }
664
Chris Lattner77b50562005-03-29 20:04:24 +0000665 // Result = Arg0
666 if (F->getName() == "realloc" || F->getName() == "strchr" ||
667 F->getName() == "strrchr" || F->getName() == "strstr" ||
668 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000669 Constraints.push_back(Constraint(Constraint::Copy,
670 getNode(CS.getInstruction()),
671 getNode(CS.getArgument(0))));
672 return true;
673 }
674
675 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000676}
677
678
Chris Lattnere995a2a2004-05-23 21:00:47 +0000679
680/// CollectConstraints - This stage scans the program, adding a constraint to
681/// the Constraints list for each instruction in the program that induces a
682/// constraint, and setting up the initial points-to graph.
683///
684void Andersens::CollectConstraints(Module &M) {
685 // First, the universal set points to itself.
686 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
Chris Lattner4de57fd2005-03-29 06:52:20 +0000687 //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
688 // &GraphNodes[UniversalSet]));
Chris Lattnerf392c642005-03-28 06:21:17 +0000689 Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
690 &GraphNodes[UniversalSet]));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000691
692 // Next, the null pointer points to the null object.
693 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
694
695 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000696 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
697 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000698 // Associate the address of the global object as pointing to the memory for
699 // the global: &G = <G memory>
700 Node *Object = getObject(I);
701 Object->setValue(I);
702 getNodeValue(*I)->addPointerTo(Object);
703
704 if (I->hasInitializer()) {
705 AddGlobalInitializerConstraints(Object, I->getInitializer());
706 } else {
707 // If it doesn't have an initializer (i.e. it's defined in another
708 // translation unit), it points to the universal set.
709 Constraints.push_back(Constraint(Constraint::Copy, Object,
710 &GraphNodes[UniversalSet]));
711 }
712 }
713
714 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
715 // Make the function address point to the function object.
716 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
717
718 // Set up the return value node.
719 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
720 getReturnNode(F)->setValue(F);
721 if (F->getFunctionType()->isVarArg())
722 getVarargNode(F)->setValue(F);
723
724 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000725 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
726 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000727 if (isa<PointerType>(I->getType()))
728 getNodeValue(*I);
729
730 if (!F->hasInternalLinkage())
731 AddConstraintsForNonInternalLinkage(F);
732
733 if (!F->isExternal()) {
734 // Scan the function body, creating a memory object for each heap/stack
735 // allocation in the body of the function and a node to represent all
736 // pointer values defined by instructions and used as operands.
737 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000738 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000739 // External functions that return pointers return the universal set.
740 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
741 Constraints.push_back(Constraint(Constraint::Copy,
742 getReturnNode(F),
743 &GraphNodes[UniversalSet]));
744
745 // Any pointers that are passed into the function have the universal set
746 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000747 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
748 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000749 if (isa<PointerType>(I->getType())) {
750 // Pointers passed into external functions could have anything stored
751 // through them.
752 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
753 &GraphNodes[UniversalSet]));
754 // Memory objects passed into external function calls can have the
755 // universal set point to them.
756 Constraints.push_back(Constraint(Constraint::Copy,
757 &GraphNodes[UniversalSet],
758 getNode(I)));
759 }
760
761 // If this is an external varargs function, it can also store pointers
762 // into any pointers passed through the varargs section.
763 if (F->getFunctionType()->isVarArg())
764 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
765 &GraphNodes[UniversalSet]));
766 }
767 }
768 NumConstraints += Constraints.size();
769}
770
771
772void Andersens::visitInstruction(Instruction &I) {
773#ifdef NDEBUG
774 return; // This function is just a big assert.
775#endif
776 if (isa<BinaryOperator>(I))
777 return;
778 // Most instructions don't have any effect on pointer values.
779 switch (I.getOpcode()) {
780 case Instruction::Br:
781 case Instruction::Switch:
782 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +0000783 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000784 case Instruction::Free:
785 case Instruction::Shl:
786 case Instruction::Shr:
787 return;
788 default:
789 // Is this something we aren't handling yet?
790 std::cerr << "Unknown instruction: " << I;
791 abort();
792 }
793}
794
795void Andersens::visitAllocationInst(AllocationInst &AI) {
796 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
797}
798
799void Andersens::visitReturnInst(ReturnInst &RI) {
800 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
801 // return V --> <Copy/retval{F}/v>
802 Constraints.push_back(Constraint(Constraint::Copy,
803 getReturnNode(RI.getParent()->getParent()),
804 getNode(RI.getOperand(0))));
805}
806
807void Andersens::visitLoadInst(LoadInst &LI) {
808 if (isa<PointerType>(LI.getType()))
809 // P1 = load P2 --> <Load/P1/P2>
810 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
811 getNode(LI.getOperand(0))));
812}
813
814void Andersens::visitStoreInst(StoreInst &SI) {
815 if (isa<PointerType>(SI.getOperand(0)->getType()))
816 // store P1, P2 --> <Store/P2/P1>
817 Constraints.push_back(Constraint(Constraint::Store,
818 getNode(SI.getOperand(1)),
819 getNode(SI.getOperand(0))));
820}
821
822void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
823 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
824 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
825 getNode(GEP.getOperand(0))));
826}
827
828void Andersens::visitPHINode(PHINode &PN) {
829 if (isa<PointerType>(PN.getType())) {
830 Node *PNN = getNodeValue(PN);
831 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
832 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
833 Constraints.push_back(Constraint(Constraint::Copy, PNN,
834 getNode(PN.getIncomingValue(i))));
835 }
836}
837
838void Andersens::visitCastInst(CastInst &CI) {
839 Value *Op = CI.getOperand(0);
840 if (isa<PointerType>(CI.getType())) {
841 if (isa<PointerType>(Op->getType())) {
842 // P1 = cast P2 --> <Copy/P1/P2>
843 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
844 getNode(CI.getOperand(0))));
845 } else {
846 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +0000847#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000848 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
849 &GraphNodes[UniversalSet]));
Chris Lattner175b9632005-03-29 20:36:05 +0000850#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000851 }
852 } else if (isa<PointerType>(Op->getType())) {
853 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +0000854#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000855 Constraints.push_back(Constraint(Constraint::Copy,
856 &GraphNodes[UniversalSet],
857 getNode(CI.getOperand(0))));
Chris Lattner175b9632005-03-29 20:36:05 +0000858#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000859 }
860}
861
862void Andersens::visitSelectInst(SelectInst &SI) {
863 if (isa<PointerType>(SI.getType())) {
864 Node *SIN = getNodeValue(SI);
865 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
866 Constraints.push_back(Constraint(Constraint::Copy, SIN,
867 getNode(SI.getOperand(1))));
868 Constraints.push_back(Constraint(Constraint::Copy, SIN,
869 getNode(SI.getOperand(2))));
870 }
871}
872
873void Andersens::visitVANext(VANextInst &I) {
874 // FIXME: Implement
875 assert(0 && "vanext not handled yet!");
876}
877void Andersens::visitVAArg(VAArgInst &I) {
878 assert(0 && "vaarg not handled yet!");
879}
880
881/// AddConstraintsForCall - Add constraints for a call with actual arguments
882/// specified by CS to the function specified by F. Note that the types of
883/// arguments might not match up in the case where this is an indirect call and
884/// the function pointer has been casted. If this is the case, do something
885/// reasonable.
886void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Chris Lattner8a446432005-03-29 06:09:07 +0000887 // If this is a call to an external function, handle it directly to get some
888 // taste of context sensitivity.
889 if (F->isExternal() && AddConstraintsForExternalCall(CS, F))
890 return;
891
Chris Lattnere995a2a2004-05-23 21:00:47 +0000892 if (isa<PointerType>(CS.getType())) {
893 Node *CSN = getNode(CS.getInstruction());
894 if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
895 Constraints.push_back(Constraint(Constraint::Copy, CSN,
896 getReturnNode(F)));
897 } else {
898 // If the function returns a non-pointer value, handle this just like we
899 // treat a nonpointer cast to pointer.
900 Constraints.push_back(Constraint(Constraint::Copy, CSN,
901 &GraphNodes[UniversalSet]));
902 }
903 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
904 Constraints.push_back(Constraint(Constraint::Copy,
905 &GraphNodes[UniversalSet],
906 getReturnNode(F)));
907 }
908
Chris Lattnere4d5c442005-03-15 04:54:21 +0000909 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000910 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
911 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
912 if (isa<PointerType>(AI->getType())) {
913 if (isa<PointerType>((*ArgI)->getType())) {
914 // Copy the actual argument into the formal argument.
915 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
916 getNode(*ArgI)));
917 } else {
918 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
919 &GraphNodes[UniversalSet]));
920 }
921 } else if (isa<PointerType>((*ArgI)->getType())) {
922 Constraints.push_back(Constraint(Constraint::Copy,
923 &GraphNodes[UniversalSet],
924 getNode(*ArgI)));
925 }
926
927 // Copy all pointers passed through the varargs section to the varargs node.
928 if (F->getFunctionType()->isVarArg())
929 for (; ArgI != ArgE; ++ArgI)
930 if (isa<PointerType>((*ArgI)->getType()))
931 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
932 getNode(*ArgI)));
933 // If more arguments are passed in than we track, just drop them on the floor.
934}
935
936void Andersens::visitCallSite(CallSite CS) {
937 if (isa<PointerType>(CS.getType()))
938 getNodeValue(*CS.getInstruction());
939
940 if (Function *F = CS.getCalledFunction()) {
941 AddConstraintsForCall(CS, F);
942 } else {
943 // We don't handle indirect call sites yet. Keep track of them for when we
944 // discover the call graph incrementally.
945 IndirectCalls.push_back(CS);
946 }
947}
948
949//===----------------------------------------------------------------------===//
950// Constraint Solving Phase
951//===----------------------------------------------------------------------===//
952
953/// intersects - Return true if the points-to set of this node intersects
954/// with the points-to set of the specified node.
955bool Andersens::Node::intersects(Node *N) const {
956 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
957 while (I1 != E1 && I2 != E2) {
958 if (*I1 == *I2) return true;
959 if (*I1 < *I2)
960 ++I1;
961 else
962 ++I2;
963 }
964 return false;
965}
966
967/// intersectsIgnoring - Return true if the points-to set of this node
968/// intersects with the points-to set of the specified node on any nodes
969/// except for the specified node to ignore.
970bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
971 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
972 while (I1 != E1 && I2 != E2) {
973 if (*I1 == *I2) {
974 if (*I1 != Ignoring) return true;
975 ++I1; ++I2;
976 } else if (*I1 < *I2)
977 ++I1;
978 else
979 ++I2;
980 }
981 return false;
982}
983
984// Copy constraint: all edges out of the source node get copied to the
985// destination node. This returns true if a change is made.
986bool Andersens::Node::copyFrom(Node *N) {
987 // Use a mostly linear-time merge since both of the lists are sorted.
988 bool Changed = false;
989 iterator I = N->begin(), E = N->end();
990 unsigned i = 0;
991 while (I != E && i != Pointees.size()) {
992 if (Pointees[i] < *I) {
993 ++i;
994 } else if (Pointees[i] == *I) {
995 ++i; ++I;
996 } else {
997 // We found a new element to copy over.
998 Changed = true;
999 Pointees.insert(Pointees.begin()+i, *I);
1000 ++i; ++I;
1001 }
1002 }
1003
1004 if (I != E) {
1005 Pointees.insert(Pointees.end(), I, E);
1006 Changed = true;
1007 }
1008
1009 return Changed;
1010}
1011
1012bool Andersens::Node::loadFrom(Node *N) {
1013 bool Changed = false;
1014 for (iterator I = N->begin(), E = N->end(); I != E; ++I)
1015 Changed |= copyFrom(*I);
1016 return Changed;
1017}
1018
1019bool Andersens::Node::storeThrough(Node *N) {
1020 bool Changed = false;
1021 for (iterator I = begin(), E = end(); I != E; ++I)
1022 Changed |= (*I)->copyFrom(N);
1023 return Changed;
1024}
1025
1026
1027/// SolveConstraints - This stage iteratively processes the constraints list
1028/// propagating constraints (adding edges to the Nodes in the points-to graph)
1029/// until a fixed point is reached.
1030///
1031void Andersens::SolveConstraints() {
1032 bool Changed = true;
1033 unsigned Iteration = 0;
1034 while (Changed) {
1035 Changed = false;
1036 ++NumIters;
1037 DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
1038
1039 // Loop over all of the constraints, applying them in turn.
1040 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1041 Constraint &C = Constraints[i];
1042 switch (C.Type) {
1043 case Constraint::Copy:
1044 Changed |= C.Dest->copyFrom(C.Src);
1045 break;
1046 case Constraint::Load:
1047 Changed |= C.Dest->loadFrom(C.Src);
1048 break;
1049 case Constraint::Store:
1050 Changed |= C.Dest->storeThrough(C.Src);
1051 break;
1052 default:
1053 assert(0 && "Unknown constraint!");
1054 }
1055 }
1056
1057 if (Changed) {
1058 // Check to see if any internal function's addresses have been passed to
1059 // external functions. If so, we have to assume that their incoming
1060 // arguments could be anything. If there are any internal functions in
1061 // the universal node that we don't know about, we must iterate.
1062 for (Node::iterator I = GraphNodes[UniversalSet].begin(),
1063 E = GraphNodes[UniversalSet].end(); I != E; ++I)
1064 if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
1065 if (F->hasInternalLinkage() &&
1066 EscapingInternalFunctions.insert(F).second) {
1067 // We found a function that is just now escaping. Mark it as if it
1068 // didn't have internal linkage.
1069 AddConstraintsForNonInternalLinkage(F);
1070 DEBUG(std::cerr << "Found escaping internal function: "
1071 << F->getName() << "\n");
1072 ++NumEscapingFunctions;
1073 }
1074
1075 // Check to see if we have discovered any new callees of the indirect call
1076 // sites. If so, add constraints to the analysis.
1077 for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1078 CallSite CS = IndirectCalls[i];
1079 std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1080 Node *CN = getNode(CS.getCalledValue());
1081
1082 for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1083 if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1084 std::vector<Function*>::iterator IP =
1085 std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1086 if (IP == KnownCallees.end() || *IP != F) {
1087 // Add the constraints for the call now.
1088 AddConstraintsForCall(CS, F);
1089 DEBUG(std::cerr << "Found actual callee '"
1090 << F->getName() << "' for call: "
1091 << *CS.getInstruction() << "\n");
1092 ++NumIndirectCallees;
1093 KnownCallees.insert(IP, F);
1094 }
1095 }
1096 }
1097 }
1098 }
1099}
1100
1101
1102
1103//===----------------------------------------------------------------------===//
1104// Debugging Output
1105//===----------------------------------------------------------------------===//
1106
1107void Andersens::PrintNode(Node *N) {
1108 if (N == &GraphNodes[UniversalSet]) {
1109 std::cerr << "<universal>";
1110 return;
1111 } else if (N == &GraphNodes[NullPtr]) {
1112 std::cerr << "<nullptr>";
1113 return;
1114 } else if (N == &GraphNodes[NullObject]) {
1115 std::cerr << "<null>";
1116 return;
1117 }
1118
1119 assert(N->getValue() != 0 && "Never set node label!");
1120 Value *V = N->getValue();
1121 if (Function *F = dyn_cast<Function>(V)) {
1122 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1123 N == getReturnNode(F)) {
1124 std::cerr << F->getName() << ":retval";
1125 return;
1126 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
1127 std::cerr << F->getName() << ":vararg";
1128 return;
1129 }
1130 }
1131
1132 if (Instruction *I = dyn_cast<Instruction>(V))
1133 std::cerr << I->getParent()->getParent()->getName() << ":";
1134 else if (Argument *Arg = dyn_cast<Argument>(V))
1135 std::cerr << Arg->getParent()->getName() << ":";
1136
1137 if (V->hasName())
1138 std::cerr << V->getName();
1139 else
1140 std::cerr << "(unnamed)";
1141
1142 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1143 if (N == getObject(V))
1144 std::cerr << "<mem>";
1145}
1146
1147void Andersens::PrintConstraints() {
1148 std::cerr << "Constraints:\n";
1149 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1150 std::cerr << " #" << i << ": ";
1151 Constraint &C = Constraints[i];
1152 if (C.Type == Constraint::Store)
1153 std::cerr << "*";
1154 PrintNode(C.Dest);
1155 std::cerr << " = ";
1156 if (C.Type == Constraint::Load)
1157 std::cerr << "*";
1158 PrintNode(C.Src);
1159 std::cerr << "\n";
1160 }
1161}
1162
1163void Andersens::PrintPointsToGraph() {
1164 std::cerr << "Points-to graph:\n";
1165 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1166 Node *N = &GraphNodes[i];
1167 std::cerr << "[" << (N->end() - N->begin()) << "] ";
1168 PrintNode(N);
1169 std::cerr << "\t--> ";
1170 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1171 if (I != N->begin()) std::cerr << ", ";
1172 PrintNode(*I);
1173 }
1174 std::cerr << "\n";
1175 }
1176}