bug 122:
[oota-llvm.git] / lib / Analysis / IPA / Andersens.cpp
1 //===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
2 // 
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 //
44 // 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 //
50 //===----------------------------------------------------------------------===//
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"
61 #include "Support/Debug.h"
62 #include "Support/Statistic.h"
63 #include <set>
64 using namespace llvm;
65
66 namespace {
67   Statistic<>
68   NumIters("anders-aa", "Number of iterations to reach convergence");
69   Statistic<>
70   NumConstraints("anders-aa", "Number of constraints");
71   Statistic<>
72   NumNodes("anders-aa", "Number of nodes");
73   Statistic<>
74   NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
75   Statistic<>
76   NumIndirectCallees("anders-aa", "Number of indirect callees found");
77
78   class Andersens : public Pass, public AliasAnalysis,
79                     private InstVisitor<Andersens> {
80     /// Node class - This class is used to represent a memory object in the
81     /// program, and is the primitive used to build the points-to graph.
82     class Node {
83       std::vector<Node*> Pointees;
84       Value *Val;
85     public:
86       Node() : Val(0) {}
87       Node *setValue(Value *V) {
88         assert(Val == 0 && "Value already set for this node!");
89         Val = V;
90         return this;
91       }
92
93       /// getValue - Return the LLVM value corresponding to this node.
94       Value *getValue() const { return Val; }
95
96       typedef std::vector<Node*>::const_iterator iterator;
97       iterator begin() const { return Pointees.begin(); }
98       iterator end() const { return Pointees.end(); }
99
100       /// addPointerTo - Add a pointer to the list of pointees of this node,
101       /// returning true if this caused a new pointer to be added, or false if
102       /// we already knew about the points-to relation.
103       bool addPointerTo(Node *N) {
104         std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
105                                                           Pointees.end(),
106                                                           N);
107         if (I != Pointees.end() && *I == N)
108           return false;
109         Pointees.insert(I, N);
110         return true;
111       }
112
113       /// intersects - Return true if the points-to set of this node intersects
114       /// with the points-to set of the specified node.
115       bool intersects(Node *N) const;
116
117       /// intersectsIgnoring - Return true if the points-to set of this node
118       /// intersects with the points-to set of the specified node on any nodes
119       /// except for the specified node to ignore.
120       bool intersectsIgnoring(Node *N, Node *Ignoring) const;
121
122       // Constraint application methods.
123       bool copyFrom(Node *N);
124       bool loadFrom(Node *N);
125       bool storeThrough(Node *N);
126     };
127
128     /// GraphNodes - This vector is populated as part of the object
129     /// identification stage of the analysis, which populates this vector with a
130     /// node for each memory object and fills in the ValueNodes map.
131     std::vector<Node> GraphNodes;
132
133     /// ValueNodes - This map indicates the Node that a particular Value* is
134     /// represented by.  This contains entries for all pointers.
135     std::map<Value*, unsigned> ValueNodes;
136
137     /// ObjectNodes - This map contains entries for each memory object in the
138     /// program: globals, alloca's and mallocs.  
139     std::map<Value*, unsigned> ObjectNodes;
140
141     /// ReturnNodes - This map contains an entry for each function in the
142     /// program that returns a value.
143     std::map<Function*, unsigned> ReturnNodes;
144
145     /// VarargNodes - This map contains the entry used to represent all pointers
146     /// passed through the varargs portion of a function call for a particular
147     /// function.  An entry is not present in this map for functions that do not
148     /// take variable arguments.
149     std::map<Function*, unsigned> VarargNodes;
150
151     /// Constraint - Objects of this structure are used to represent the various
152     /// constraints identified by the algorithm.  The constraints are 'copy',
153     /// for statements like "A = B", 'load' for statements like "A = *B", and
154     /// 'store' for statements like "*A = B".
155     struct Constraint {
156       enum ConstraintType { Copy, Load, Store } Type;
157       Node *Dest, *Src;
158
159       Constraint(ConstraintType Ty, Node *D, Node *S)
160         : Type(Ty), Dest(D), Src(S) {}
161     };
162     
163     /// Constraints - This vector contains a list of all of the constraints
164     /// identified by the program.
165     std::vector<Constraint> Constraints;
166
167     /// EscapingInternalFunctions - This set contains all of the internal
168     /// functions that are found to escape from the program.  If the address of
169     /// an internal function is passed to an external function or otherwise
170     /// escapes from the analyzed portion of the program, we must assume that
171     /// any pointer arguments can alias the universal node.  This set keeps
172     /// track of those functions we are assuming to escape so far.
173     std::set<Function*> EscapingInternalFunctions;
174
175     /// IndirectCalls - This contains a list of all of the indirect call sites
176     /// in the program.  Since the call graph is iteratively discovered, we may
177     /// need to add constraints to our graph as we find new targets of function
178     /// pointers.
179     std::vector<CallSite> IndirectCalls;
180
181     /// IndirectCallees - For each call site in the indirect calls list, keep
182     /// track of the callees that we have discovered so far.  As the analysis
183     /// proceeds, more callees are discovered, until the call graph finally
184     /// stabilizes.
185     std::map<CallSite, std::vector<Function*> > IndirectCallees;
186
187     /// This enum defines the GraphNodes indices that correspond to important
188     /// fixed sets.
189     enum {
190       UniversalSet = 0,
191       NullPtr      = 1,
192       NullObject   = 2,
193     };
194     
195   public:
196     bool run(Module &M) {
197       InitializeAliasAnalysis(this);
198       IdentifyObjects(M);
199       CollectConstraints(M);
200       DEBUG(PrintConstraints());
201       SolveConstraints();
202       DEBUG(PrintPointsToGraph());
203
204       // Free the constraints list, as we don't need it to respond to alias
205       // requests.
206       ObjectNodes.clear();
207       ReturnNodes.clear();
208       VarargNodes.clear();
209       EscapingInternalFunctions.clear();
210       std::vector<Constraint>().swap(Constraints);      
211       return false;
212     }
213
214     void releaseMemory() {
215       // FIXME: Until we have transitively required passes working correctly,
216       // this cannot be enabled!  Otherwise, using -count-aa with the pass
217       // causes memory to be freed too early. :(
218 #if 0
219       // The memory objects and ValueNodes data structures at the only ones that
220       // are still live after construction.
221       std::vector<Node>().swap(GraphNodes);
222       ValueNodes.clear();
223 #endif
224     }
225
226     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
227       AliasAnalysis::getAnalysisUsage(AU);
228       AU.setPreservesAll();                         // Does not transform code
229     }
230
231     //------------------------------------------------
232     // Implement the AliasAnalysis API
233     //  
234     AliasResult alias(const Value *V1, unsigned V1Size,
235                       const Value *V2, unsigned V2Size);
236     void getMustAliases(Value *P, std::vector<Value*> &RetVals);
237     bool pointsToConstantMemory(const Value *P);
238
239     virtual void deleteValue(Value *V) {
240       ValueNodes.erase(V);
241       getAnalysis<AliasAnalysis>().deleteValue(V);
242     }
243
244     virtual void copyValue(Value *From, Value *To) {
245       ValueNodes[To] = ValueNodes[From];
246       getAnalysis<AliasAnalysis>().copyValue(From, To);
247     }
248
249   private:
250     /// getNode - Return the node corresponding to the specified pointer scalar.
251     ///
252     Node *getNode(Value *V) {
253       if (Constant *C = dyn_cast<Constant>(V))
254         return getNodeForConstantPointer(C);
255
256       std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
257       if (I == ValueNodes.end()) {
258         V->dump();
259         assert(I != ValueNodes.end() &&
260                "Value does not have a node in the points-to graph!");
261       }
262       return &GraphNodes[I->second];
263     }
264     
265     /// getObject - Return the node corresponding to the memory object for the
266     /// specified global or allocation instruction.
267     Node *getObject(Value *V) {
268       std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
269       assert(I != ObjectNodes.end() &&
270              "Value does not have an object in the points-to graph!");
271       return &GraphNodes[I->second];
272     }
273
274     /// getReturnNode - Return the node representing the return value for the
275     /// specified function.
276     Node *getReturnNode(Function *F) {
277       std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
278       assert(I != ReturnNodes.end() && "Function does not return a value!");
279       return &GraphNodes[I->second];
280     }
281
282     /// getVarargNode - Return the node representing the variable arguments
283     /// formal for the specified function.
284     Node *getVarargNode(Function *F) {
285       std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
286       assert(I != VarargNodes.end() && "Function does not take var args!");
287       return &GraphNodes[I->second];
288     }
289
290     /// getNodeValue - Get the node for the specified LLVM value and set the
291     /// value for it to be the specified value.
292     Node *getNodeValue(Value &V) {
293       return getNode(&V)->setValue(&V);
294     }
295
296     void IdentifyObjects(Module &M);
297     void CollectConstraints(Module &M);
298     void SolveConstraints();
299
300     Node *getNodeForConstantPointer(Constant *C);
301     Node *getNodeForConstantPointerTarget(Constant *C);
302     void AddGlobalInitializerConstraints(Node *N, Constant *C);
303     void AddConstraintsForNonInternalLinkage(Function *F);
304     void AddConstraintsForCall(CallSite CS, Function *F);
305
306
307     void PrintNode(Node *N);
308     void PrintConstraints();
309     void PrintPointsToGraph();
310
311     //===------------------------------------------------------------------===//
312     // Instruction visitation methods for adding constraints
313     //
314     friend class InstVisitor<Andersens>;
315     void visitReturnInst(ReturnInst &RI);
316     void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
317     void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
318     void visitCallSite(CallSite CS);
319     void visitAllocationInst(AllocationInst &AI);
320     void visitLoadInst(LoadInst &LI);
321     void visitStoreInst(StoreInst &SI);
322     void visitGetElementPtrInst(GetElementPtrInst &GEP);
323     void visitPHINode(PHINode &PN);
324     void visitCastInst(CastInst &CI);
325     void visitSelectInst(SelectInst &SI);
326     void visitVANext(VANextInst &I);
327     void visitVAArg(VAArgInst &I);
328     void visitInstruction(Instruction &I);
329   };
330
331   RegisterOpt<Andersens> X("anders-aa",
332                            "Andersen's Interprocedural Alias Analysis");
333   RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
334 }
335
336 //===----------------------------------------------------------------------===//
337 //                  AliasAnalysis Interface Implementation
338 //===----------------------------------------------------------------------===//
339
340 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
341                                             const Value *V2, unsigned V2Size) {
342   Node *N1 = getNode((Value*)V1);
343   Node *N2 = getNode((Value*)V2);
344
345   // Check to see if the two pointers are known to not alias.  They don't alias
346   // if their points-to sets do not intersect.
347   if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
348     return NoAlias;
349
350   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
351 }
352
353 /// getMustAlias - We can provide must alias information if we know that a
354 /// pointer can only point to a specific function or the null pointer.
355 /// Unfortunately we cannot determine must-alias information for global
356 /// variables or any other memory memory objects because we do not track whether
357 /// a pointer points to the beginning of an object or a field of it.
358 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
359   Node *N = getNode(P);
360   Node::iterator I = N->begin();
361   if (I != N->end()) {
362     // If there is exactly one element in the points-to set for the object...
363     ++I;
364     if (I == N->end()) {
365       Node *Pointee = *N->begin();
366
367       // If a function is the only object in the points-to set, then it must be
368       // the destination.  Note that we can't handle global variables here,
369       // because we don't know if the pointer is actually pointing to a field of
370       // the global or to the beginning of it.
371       if (Value *V = Pointee->getValue()) {
372         if (Function *F = dyn_cast<Function>(V))
373           RetVals.push_back(F);
374       } else {
375         // If the object in the points-to set is the null object, then the null
376         // pointer is a must alias.
377         if (Pointee == &GraphNodes[NullObject])
378           RetVals.push_back(Constant::getNullValue(P->getType()));
379       }
380     }
381   }
382   
383   AliasAnalysis::getMustAliases(P, RetVals);
384 }
385
386 /// pointsToConstantMemory - If we can determine that this pointer only points
387 /// to constant memory, return true.  In practice, this means that if the
388 /// pointer can only point to constant globals, functions, or the null pointer,
389 /// return true.
390 ///
391 bool Andersens::pointsToConstantMemory(const Value *P) {
392   Node *N = getNode((Value*)P);
393   for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
394     if (Value *V = (*I)->getValue()) {
395       if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
396                                    !cast<GlobalVariable>(V)->isConstant()))
397         return AliasAnalysis::pointsToConstantMemory(P);
398     } else {
399       if (*I != &GraphNodes[NullObject])
400         return AliasAnalysis::pointsToConstantMemory(P);
401     }
402   }
403
404   return true;
405 }
406
407 //===----------------------------------------------------------------------===//
408 //                       Object Identification Phase
409 //===----------------------------------------------------------------------===//
410
411 /// IdentifyObjects - This stage scans the program, adding an entry to the
412 /// GraphNodes list for each memory object in the program (global stack or
413 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
414 ///
415 void Andersens::IdentifyObjects(Module &M) {
416   unsigned NumObjects = 0;
417
418   // Object #0 is always the universal set: the object that we don't know
419   // anything about.
420   assert(NumObjects == UniversalSet && "Something changed!");
421   ++NumObjects;
422
423   // Object #1 always represents the null pointer.
424   assert(NumObjects == NullPtr && "Something changed!");
425   ++NumObjects;
426
427   // Object #2 always represents the null object (the object pointed to by null)
428   assert(NumObjects == NullObject && "Something changed!");
429   ++NumObjects;
430
431   // Add all the globals first.
432   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
433     ObjectNodes[I] = NumObjects++;
434     ValueNodes[I] = NumObjects++;
435   }
436
437   // Add nodes for all of the functions and the instructions inside of them.
438   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
439     // The function itself is a memory object.
440     ValueNodes[F] = NumObjects++;
441     ObjectNodes[F] = NumObjects++;
442     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
443       ReturnNodes[F] = NumObjects++;
444     if (F->getFunctionType()->isVarArg())
445       VarargNodes[F] = NumObjects++;
446
447     // Add nodes for all of the incoming pointer arguments.
448     for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
449       if (isa<PointerType>(I->getType()))
450         ValueNodes[I] = NumObjects++;
451
452     // Scan the function body, creating a memory object for each heap/stack
453     // allocation in the body of the function and a node to represent all
454     // pointer values defined by instructions and used as operands.
455     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
456       // If this is an heap or stack allocation, create a node for the memory
457       // object.
458       if (isa<PointerType>(II->getType())) {
459         ValueNodes[&*II] = NumObjects++;
460         if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
461           ObjectNodes[AI] = NumObjects++;
462       }
463     }
464   }
465
466   // Now that we know how many objects to create, make them all now!
467   GraphNodes.resize(NumObjects);
468   NumNodes += NumObjects;
469 }
470
471 //===----------------------------------------------------------------------===//
472 //                     Constraint Identification Phase
473 //===----------------------------------------------------------------------===//
474
475 /// getNodeForConstantPointer - Return the node corresponding to the constant
476 /// pointer itself.
477 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
478   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
479
480   if (isa<ConstantPointerNull>(C))
481     return &GraphNodes[NullPtr];
482   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
483     return getNode(GV);
484   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
485     switch (CE->getOpcode()) {
486     case Instruction::GetElementPtr:
487       return getNodeForConstantPointer(CE->getOperand(0));
488     case Instruction::Cast:
489       if (isa<PointerType>(CE->getOperand(0)->getType()))
490         return getNodeForConstantPointer(CE->getOperand(0));
491       else
492         return &GraphNodes[UniversalSet];
493     default:
494       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
495       assert(0);
496     }
497   } else {
498     assert(0 && "Unknown constant pointer!");
499   }
500   return 0;
501 }
502
503 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
504 /// specified constant pointer.
505 Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
506   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
507
508   if (isa<ConstantPointerNull>(C))
509     return &GraphNodes[NullObject];
510   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
511     return getObject(GV);
512   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
513     switch (CE->getOpcode()) {
514     case Instruction::GetElementPtr:
515       return getNodeForConstantPointerTarget(CE->getOperand(0));
516     case Instruction::Cast:
517       if (isa<PointerType>(CE->getOperand(0)->getType()))
518         return getNodeForConstantPointerTarget(CE->getOperand(0));
519       else
520         return &GraphNodes[UniversalSet];
521     default:
522       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
523       assert(0);
524     }
525   } else {
526     assert(0 && "Unknown constant pointer!");
527   }
528   return 0;
529 }
530
531 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
532 /// object N, which contains values indicated by C.
533 void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
534   if (C->getType()->isFirstClassType()) {
535     if (isa<PointerType>(C->getType()))
536       N->addPointerTo(getNodeForConstantPointer(C));
537   } else if (C->isNullValue()) {
538     N->addPointerTo(&GraphNodes[NullObject]);
539     return;
540   } else {
541     // If this is an array or struct, include constraints for each element.
542     assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
543     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
544       AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
545   }
546 }
547
548 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
549   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
550     if (isa<PointerType>(I->getType()))
551       // If this is an argument of an externally accessible function, the
552       // incoming pointer might point to anything.
553       Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
554                                        &GraphNodes[UniversalSet]));
555 }
556
557
558 /// CollectConstraints - This stage scans the program, adding a constraint to
559 /// the Constraints list for each instruction in the program that induces a
560 /// constraint, and setting up the initial points-to graph.
561 ///
562 void Andersens::CollectConstraints(Module &M) {
563   // First, the universal set points to itself.
564   GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
565
566   // Next, the null pointer points to the null object.
567   GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
568
569   // Next, add any constraints on global variables and their initializers.
570   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
571     // Associate the address of the global object as pointing to the memory for
572     // the global: &G = <G memory>
573     Node *Object = getObject(I);
574     Object->setValue(I);
575     getNodeValue(*I)->addPointerTo(Object);
576
577     if (I->hasInitializer()) {
578       AddGlobalInitializerConstraints(Object, I->getInitializer());
579     } else {
580       // If it doesn't have an initializer (i.e. it's defined in another
581       // translation unit), it points to the universal set.
582       Constraints.push_back(Constraint(Constraint::Copy, Object,
583                                        &GraphNodes[UniversalSet]));
584     }
585   }
586   
587   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
588     // Make the function address point to the function object.
589     getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
590
591     // Set up the return value node.
592     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
593       getReturnNode(F)->setValue(F);
594     if (F->getFunctionType()->isVarArg())
595       getVarargNode(F)->setValue(F);
596
597     // Set up incoming argument nodes.
598     for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
599       if (isa<PointerType>(I->getType()))
600         getNodeValue(*I);
601
602     if (!F->hasInternalLinkage())
603       AddConstraintsForNonInternalLinkage(F);
604
605     if (!F->isExternal()) {
606       // Scan the function body, creating a memory object for each heap/stack
607       // allocation in the body of the function and a node to represent all
608       // pointer values defined by instructions and used as operands.
609       visit(F);
610     } else {
611       // External functions that return pointers return the universal set.
612       if (isa<PointerType>(F->getFunctionType()->getReturnType()))
613         Constraints.push_back(Constraint(Constraint::Copy,
614                                          getReturnNode(F),
615                                          &GraphNodes[UniversalSet]));
616
617       // Any pointers that are passed into the function have the universal set
618       // stored into them.
619       for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
620         if (isa<PointerType>(I->getType())) {
621           // Pointers passed into external functions could have anything stored
622           // through them.
623           Constraints.push_back(Constraint(Constraint::Store, getNode(I),
624                                            &GraphNodes[UniversalSet]));
625           // Memory objects passed into external function calls can have the
626           // universal set point to them.
627           Constraints.push_back(Constraint(Constraint::Copy,
628                                            &GraphNodes[UniversalSet],
629                                            getNode(I)));
630         }
631
632       // If this is an external varargs function, it can also store pointers
633       // into any pointers passed through the varargs section.
634       if (F->getFunctionType()->isVarArg())
635         Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
636                                          &GraphNodes[UniversalSet]));
637     }
638   }
639   NumConstraints += Constraints.size();
640 }
641
642
643 void Andersens::visitInstruction(Instruction &I) {
644 #ifdef NDEBUG
645   return;          // This function is just a big assert.
646 #endif
647   if (isa<BinaryOperator>(I))
648     return;
649   // Most instructions don't have any effect on pointer values.
650   switch (I.getOpcode()) {
651   case Instruction::Br:
652   case Instruction::Switch:
653   case Instruction::Unwind:
654   case Instruction::Free:
655   case Instruction::Shl:
656   case Instruction::Shr:
657     return;
658   default:
659     // Is this something we aren't handling yet?
660     std::cerr << "Unknown instruction: " << I;
661     abort();
662   }
663 }
664
665 void Andersens::visitAllocationInst(AllocationInst &AI) {
666   getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
667 }
668
669 void Andersens::visitReturnInst(ReturnInst &RI) {
670   if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
671     // return V   -->   <Copy/retval{F}/v>
672     Constraints.push_back(Constraint(Constraint::Copy,
673                                      getReturnNode(RI.getParent()->getParent()),
674                                      getNode(RI.getOperand(0))));
675 }
676
677 void Andersens::visitLoadInst(LoadInst &LI) {
678   if (isa<PointerType>(LI.getType()))
679     // P1 = load P2  -->  <Load/P1/P2>
680     Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
681                                      getNode(LI.getOperand(0))));
682 }
683
684 void Andersens::visitStoreInst(StoreInst &SI) {
685   if (isa<PointerType>(SI.getOperand(0)->getType()))
686     // store P1, P2  -->  <Store/P2/P1>
687     Constraints.push_back(Constraint(Constraint::Store,
688                                      getNode(SI.getOperand(1)),
689                                      getNode(SI.getOperand(0))));
690 }
691
692 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
693   // P1 = getelementptr P2, ... --> <Copy/P1/P2>
694   Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
695                                    getNode(GEP.getOperand(0))));
696 }
697
698 void Andersens::visitPHINode(PHINode &PN) {
699   if (isa<PointerType>(PN.getType())) {
700     Node *PNN = getNodeValue(PN);
701     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
702       // P1 = phi P2, P3  -->  <Copy/P1/P2>, <Copy/P1/P3>, ...
703       Constraints.push_back(Constraint(Constraint::Copy, PNN,
704                                        getNode(PN.getIncomingValue(i))));
705   }
706 }
707
708 void Andersens::visitCastInst(CastInst &CI) {
709   Value *Op = CI.getOperand(0);
710   if (isa<PointerType>(CI.getType())) {
711     if (isa<PointerType>(Op->getType())) {
712       // P1 = cast P2  --> <Copy/P1/P2>
713       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
714                                        getNode(CI.getOperand(0))));
715     } else {
716       // P1 = cast int --> <Copy/P1/Univ>
717       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
718                                        &GraphNodes[UniversalSet]));
719     }
720   } else if (isa<PointerType>(Op->getType())) {
721     // int = cast P1 --> <Copy/Univ/P1>
722     Constraints.push_back(Constraint(Constraint::Copy,
723                                      &GraphNodes[UniversalSet],
724                                      getNode(CI.getOperand(0))));
725   }
726 }
727
728 void Andersens::visitSelectInst(SelectInst &SI) {
729   if (isa<PointerType>(SI.getType())) {
730     Node *SIN = getNodeValue(SI);
731     // P1 = select C, P2, P3   ---> <Copy/P1/P2>, <Copy/P1/P3>
732     Constraints.push_back(Constraint(Constraint::Copy, SIN,
733                                      getNode(SI.getOperand(1))));
734     Constraints.push_back(Constraint(Constraint::Copy, SIN,
735                                      getNode(SI.getOperand(2))));
736   }
737 }
738
739 void Andersens::visitVANext(VANextInst &I) {
740   // FIXME: Implement
741   assert(0 && "vanext not handled yet!");
742 }
743 void Andersens::visitVAArg(VAArgInst &I) {
744   assert(0 && "vaarg not handled yet!");
745 }
746
747 /// AddConstraintsForCall - Add constraints for a call with actual arguments
748 /// specified by CS to the function specified by F.  Note that the types of
749 /// arguments might not match up in the case where this is an indirect call and
750 /// the function pointer has been casted.  If this is the case, do something
751 /// reasonable.
752 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
753   if (isa<PointerType>(CS.getType())) {
754     Node *CSN = getNode(CS.getInstruction());
755     if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
756       Constraints.push_back(Constraint(Constraint::Copy, CSN,
757                                        getReturnNode(F)));
758     } else {
759       // If the function returns a non-pointer value, handle this just like we
760       // treat a nonpointer cast to pointer.
761       Constraints.push_back(Constraint(Constraint::Copy, CSN,
762                                        &GraphNodes[UniversalSet]));
763     }
764   } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
765     Constraints.push_back(Constraint(Constraint::Copy,
766                                      &GraphNodes[UniversalSet],
767                                      getReturnNode(F)));
768   }
769   
770   Function::aiterator AI = F->abegin(), AE = F->aend();
771   CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
772   for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
773     if (isa<PointerType>(AI->getType())) {
774       if (isa<PointerType>((*ArgI)->getType())) {
775         // Copy the actual argument into the formal argument.
776         Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
777                                          getNode(*ArgI)));
778       } else {
779         Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
780                                          &GraphNodes[UniversalSet]));
781       }
782     } else if (isa<PointerType>((*ArgI)->getType())) {
783       Constraints.push_back(Constraint(Constraint::Copy,
784                                        &GraphNodes[UniversalSet],
785                                        getNode(*ArgI)));
786     }
787   
788   // Copy all pointers passed through the varargs section to the varargs node.
789   if (F->getFunctionType()->isVarArg())
790     for (; ArgI != ArgE; ++ArgI)
791       if (isa<PointerType>((*ArgI)->getType()))
792         Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
793                                          getNode(*ArgI)));
794   // If more arguments are passed in than we track, just drop them on the floor.
795 }
796
797 void Andersens::visitCallSite(CallSite CS) {
798   if (isa<PointerType>(CS.getType()))
799     getNodeValue(*CS.getInstruction());
800
801   if (Function *F = CS.getCalledFunction()) {
802     AddConstraintsForCall(CS, F);
803   } else {
804     // We don't handle indirect call sites yet.  Keep track of them for when we
805     // discover the call graph incrementally.
806     IndirectCalls.push_back(CS);
807   }
808 }
809
810 //===----------------------------------------------------------------------===//
811 //                         Constraint Solving Phase
812 //===----------------------------------------------------------------------===//
813
814 /// intersects - Return true if the points-to set of this node intersects
815 /// with the points-to set of the specified node.
816 bool Andersens::Node::intersects(Node *N) const {
817   iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
818   while (I1 != E1 && I2 != E2) {
819     if (*I1 == *I2) return true;
820     if (*I1 < *I2)
821       ++I1;
822     else
823       ++I2;
824   }
825   return false;
826 }
827
828 /// intersectsIgnoring - Return true if the points-to set of this node
829 /// intersects with the points-to set of the specified node on any nodes
830 /// except for the specified node to ignore.
831 bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
832   iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
833   while (I1 != E1 && I2 != E2) {
834     if (*I1 == *I2) {
835       if (*I1 != Ignoring) return true;
836       ++I1; ++I2;
837     } else if (*I1 < *I2)
838       ++I1;
839     else
840       ++I2;
841   }
842   return false;
843 }
844
845 // Copy constraint: all edges out of the source node get copied to the
846 // destination node.  This returns true if a change is made.
847 bool Andersens::Node::copyFrom(Node *N) {
848   // Use a mostly linear-time merge since both of the lists are sorted.
849   bool Changed = false;
850   iterator I = N->begin(), E = N->end();
851   unsigned i = 0;
852   while (I != E && i != Pointees.size()) {
853     if (Pointees[i] < *I) {
854       ++i;
855     } else if (Pointees[i] == *I) {
856       ++i; ++I;
857     } else {
858       // We found a new element to copy over.
859       Changed = true;
860       Pointees.insert(Pointees.begin()+i, *I);
861        ++i; ++I;
862     }
863   }
864
865   if (I != E) {
866     Pointees.insert(Pointees.end(), I, E);
867     Changed = true;
868   }
869
870   return Changed;
871 }
872
873 bool Andersens::Node::loadFrom(Node *N) {
874   bool Changed = false;
875   for (iterator I = N->begin(), E = N->end(); I != E; ++I)
876     Changed |= copyFrom(*I);
877   return Changed;
878 }
879
880 bool Andersens::Node::storeThrough(Node *N) {
881   bool Changed = false;
882   for (iterator I = begin(), E = end(); I != E; ++I)
883     Changed |= (*I)->copyFrom(N);
884   return Changed;
885 }
886
887
888 /// SolveConstraints - This stage iteratively processes the constraints list
889 /// propagating constraints (adding edges to the Nodes in the points-to graph)
890 /// until a fixed point is reached.
891 ///
892 void Andersens::SolveConstraints() {
893   bool Changed = true;
894   unsigned Iteration = 0;
895   while (Changed) {
896     Changed = false;
897     ++NumIters;
898     DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
899
900     // Loop over all of the constraints, applying them in turn.
901     for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
902       Constraint &C = Constraints[i];
903       switch (C.Type) {
904       case Constraint::Copy:
905         Changed |= C.Dest->copyFrom(C.Src);
906         break;
907       case Constraint::Load:
908         Changed |= C.Dest->loadFrom(C.Src);
909         break;
910       case Constraint::Store:
911         Changed |= C.Dest->storeThrough(C.Src);
912         break;
913       default:
914         assert(0 && "Unknown constraint!");
915       }
916     }
917
918     if (Changed) {
919       // Check to see if any internal function's addresses have been passed to
920       // external functions.  If so, we have to assume that their incoming
921       // arguments could be anything.  If there are any internal functions in
922       // the universal node that we don't know about, we must iterate.
923       for (Node::iterator I = GraphNodes[UniversalSet].begin(),
924              E = GraphNodes[UniversalSet].end(); I != E; ++I)
925         if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
926           if (F->hasInternalLinkage() &&
927               EscapingInternalFunctions.insert(F).second) {
928             // We found a function that is just now escaping.  Mark it as if it
929             // didn't have internal linkage.
930             AddConstraintsForNonInternalLinkage(F);
931             DEBUG(std::cerr << "Found escaping internal function: "
932                             << F->getName() << "\n");
933             ++NumEscapingFunctions;
934           }
935
936       // Check to see if we have discovered any new callees of the indirect call
937       // sites.  If so, add constraints to the analysis.
938       for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
939         CallSite CS = IndirectCalls[i];
940         std::vector<Function*> &KnownCallees = IndirectCallees[CS];
941         Node *CN = getNode(CS.getCalledValue());
942
943         for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
944           if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
945             std::vector<Function*>::iterator IP =
946               std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
947             if (IP == KnownCallees.end() || *IP != F) {
948               // Add the constraints for the call now.
949               AddConstraintsForCall(CS, F);
950               DEBUG(std::cerr << "Found actual callee '"
951                               << F->getName() << "' for call: "
952                               << *CS.getInstruction() << "\n");
953               ++NumIndirectCallees;
954               KnownCallees.insert(IP, F);
955             }
956           }
957       }
958     }
959   }
960 }
961
962
963
964 //===----------------------------------------------------------------------===//
965 //                               Debugging Output
966 //===----------------------------------------------------------------------===//
967
968 void Andersens::PrintNode(Node *N) {
969   if (N == &GraphNodes[UniversalSet]) {
970     std::cerr << "<universal>";
971     return;
972   } else if (N == &GraphNodes[NullPtr]) {
973     std::cerr << "<nullptr>";
974     return;
975   } else if (N == &GraphNodes[NullObject]) {
976     std::cerr << "<null>";
977     return;
978   }
979
980   assert(N->getValue() != 0 && "Never set node label!");
981   Value *V = N->getValue();
982   if (Function *F = dyn_cast<Function>(V)) {
983     if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
984         N == getReturnNode(F)) {
985       std::cerr << F->getName() << ":retval";
986       return;
987     } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
988       std::cerr << F->getName() << ":vararg";
989       return;
990     }
991   }
992
993   if (Instruction *I = dyn_cast<Instruction>(V))
994     std::cerr << I->getParent()->getParent()->getName() << ":";
995   else if (Argument *Arg = dyn_cast<Argument>(V))
996     std::cerr << Arg->getParent()->getName() << ":";
997
998   if (V->hasName())
999     std::cerr << V->getName();
1000   else
1001     std::cerr << "(unnamed)";
1002
1003   if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1004     if (N == getObject(V))
1005       std::cerr << "<mem>";
1006 }
1007
1008 void Andersens::PrintConstraints() {
1009   std::cerr << "Constraints:\n";
1010   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1011     std::cerr << "  #" << i << ":  ";
1012     Constraint &C = Constraints[i];
1013     if (C.Type == Constraint::Store)
1014       std::cerr << "*";
1015     PrintNode(C.Dest);
1016     std::cerr << " = ";
1017     if (C.Type == Constraint::Load)
1018       std::cerr << "*";
1019     PrintNode(C.Src);
1020     std::cerr << "\n";
1021   }
1022 }
1023
1024 void Andersens::PrintPointsToGraph() {
1025   std::cerr << "Points-to graph:\n";
1026   for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1027     Node *N = &GraphNodes[i];
1028     std::cerr << "[" << (N->end() - N->begin()) << "] ";
1029     PrintNode(N);
1030     std::cerr << "\t--> ";
1031     for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1032       if (I != N->begin()) std::cerr << ", ";
1033       PrintNode(*I);
1034     }
1035     std::cerr << "\n";
1036   }
1037 }