For PR950:
[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 "llvm/Analysis/Passes.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/ADT/Statistic.h"
64 #include <set>
65 #include <iostream>
66 using namespace llvm;
67
68 namespace {
69   Statistic<>
70   NumIters("anders-aa", "Number of iterations to reach convergence");
71   Statistic<>
72   NumConstraints("anders-aa", "Number of constraints");
73   Statistic<>
74   NumNodes("anders-aa", "Number of nodes");
75   Statistic<>
76   NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
77   Statistic<>
78   NumIndirectCallees("anders-aa", "Number of indirect callees found");
79
80   class Andersens : public ModulePass, public AliasAnalysis,
81                     private InstVisitor<Andersens> {
82     /// Node class - This class is used to represent a memory object in the
83     /// program, and is the primitive used to build the points-to graph.
84     class Node {
85       std::vector<Node*> Pointees;
86       Value *Val;
87     public:
88       Node() : Val(0) {}
89       Node *setValue(Value *V) {
90         assert(Val == 0 && "Value already set for this node!");
91         Val = V;
92         return this;
93       }
94
95       /// getValue - Return the LLVM value corresponding to this node.
96       ///
97       Value *getValue() const { return Val; }
98
99       typedef std::vector<Node*>::const_iterator iterator;
100       iterator begin() const { return Pointees.begin(); }
101       iterator end() const { return Pointees.end(); }
102
103       /// addPointerTo - Add a pointer to the list of pointees of this node,
104       /// returning true if this caused a new pointer to be added, or false if
105       /// we already knew about the points-to relation.
106       bool addPointerTo(Node *N) {
107         std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
108                                                           Pointees.end(),
109                                                           N);
110         if (I != Pointees.end() && *I == N)
111           return false;
112         Pointees.insert(I, N);
113         return true;
114       }
115
116       /// intersects - Return true if the points-to set of this node intersects
117       /// with the points-to set of the specified node.
118       bool intersects(Node *N) const;
119
120       /// intersectsIgnoring - Return true if the points-to set of this node
121       /// intersects with the points-to set of the specified node on any nodes
122       /// except for the specified node to ignore.
123       bool intersectsIgnoring(Node *N, Node *Ignoring) const;
124
125       // Constraint application methods.
126       bool copyFrom(Node *N);
127       bool loadFrom(Node *N);
128       bool storeThrough(Node *N);
129     };
130
131     /// GraphNodes - This vector is populated as part of the object
132     /// identification stage of the analysis, which populates this vector with a
133     /// node for each memory object and fills in the ValueNodes map.
134     std::vector<Node> GraphNodes;
135
136     /// ValueNodes - This map indicates the Node that a particular Value* is
137     /// represented by.  This contains entries for all pointers.
138     std::map<Value*, unsigned> ValueNodes;
139
140     /// ObjectNodes - This map contains entries for each memory object in the
141     /// program: globals, alloca's and mallocs.
142     std::map<Value*, unsigned> ObjectNodes;
143
144     /// ReturnNodes - This map contains an entry for each function in the
145     /// program that returns a value.
146     std::map<Function*, unsigned> ReturnNodes;
147
148     /// VarargNodes - This map contains the entry used to represent all pointers
149     /// passed through the varargs portion of a function call for a particular
150     /// function.  An entry is not present in this map for functions that do not
151     /// take variable arguments.
152     std::map<Function*, unsigned> VarargNodes;
153
154     /// Constraint - Objects of this structure are used to represent the various
155     /// constraints identified by the algorithm.  The constraints are 'copy',
156     /// for statements like "A = B", 'load' for statements like "A = *B", and
157     /// 'store' for statements like "*A = B".
158     struct Constraint {
159       enum ConstraintType { Copy, Load, Store } Type;
160       Node *Dest, *Src;
161
162       Constraint(ConstraintType Ty, Node *D, Node *S)
163         : Type(Ty), Dest(D), Src(S) {}
164     };
165
166     /// Constraints - This vector contains a list of all of the constraints
167     /// identified by the program.
168     std::vector<Constraint> Constraints;
169
170     /// EscapingInternalFunctions - This set contains all of the internal
171     /// functions that are found to escape from the program.  If the address of
172     /// an internal function is passed to an external function or otherwise
173     /// escapes from the analyzed portion of the program, we must assume that
174     /// any pointer arguments can alias the universal node.  This set keeps
175     /// track of those functions we are assuming to escape so far.
176     std::set<Function*> EscapingInternalFunctions;
177
178     /// IndirectCalls - This contains a list of all of the indirect call sites
179     /// in the program.  Since the call graph is iteratively discovered, we may
180     /// need to add constraints to our graph as we find new targets of function
181     /// pointers.
182     std::vector<CallSite> IndirectCalls;
183
184     /// IndirectCallees - For each call site in the indirect calls list, keep
185     /// track of the callees that we have discovered so far.  As the analysis
186     /// proceeds, more callees are discovered, until the call graph finally
187     /// stabilizes.
188     std::map<CallSite, std::vector<Function*> > IndirectCallees;
189
190     /// This enum defines the GraphNodes indices that correspond to important
191     /// fixed sets.
192     enum {
193       UniversalSet = 0,
194       NullPtr      = 1,
195       NullObject   = 2
196     };
197
198   public:
199     bool runOnModule(Module &M) {
200       InitializeAliasAnalysis(this);
201       IdentifyObjects(M);
202       CollectConstraints(M);
203       DEBUG(PrintConstraints());
204       SolveConstraints();
205       DEBUG(PrintPointsToGraph());
206
207       // Free the constraints list, as we don't need it to respond to alias
208       // requests.
209       ObjectNodes.clear();
210       ReturnNodes.clear();
211       VarargNodes.clear();
212       EscapingInternalFunctions.clear();
213       std::vector<Constraint>().swap(Constraints);
214       return false;
215     }
216
217     void releaseMemory() {
218       // FIXME: Until we have transitively required passes working correctly,
219       // this cannot be enabled!  Otherwise, using -count-aa with the pass
220       // causes memory to be freed too early. :(
221 #if 0
222       // The memory objects and ValueNodes data structures at the only ones that
223       // are still live after construction.
224       std::vector<Node>().swap(GraphNodes);
225       ValueNodes.clear();
226 #endif
227     }
228
229     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
230       AliasAnalysis::getAnalysisUsage(AU);
231       AU.setPreservesAll();                         // Does not transform code
232     }
233
234     //------------------------------------------------
235     // Implement the AliasAnalysis API
236     //
237     AliasResult alias(const Value *V1, unsigned V1Size,
238                       const Value *V2, unsigned V2Size);
239     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
240     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
241     void getMustAliases(Value *P, std::vector<Value*> &RetVals);
242     bool pointsToConstantMemory(const Value *P);
243
244     virtual void deleteValue(Value *V) {
245       ValueNodes.erase(V);
246       getAnalysis<AliasAnalysis>().deleteValue(V);
247     }
248
249     virtual void copyValue(Value *From, Value *To) {
250       ValueNodes[To] = ValueNodes[From];
251       getAnalysis<AliasAnalysis>().copyValue(From, To);
252     }
253
254   private:
255     /// getNode - Return the node corresponding to the specified pointer scalar.
256     ///
257     Node *getNode(Value *V) {
258       if (Constant *C = dyn_cast<Constant>(V))
259         if (!isa<GlobalValue>(C))
260           return getNodeForConstantPointer(C);
261
262       std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
263       if (I == ValueNodes.end()) {
264 #ifndef NDEBUG
265         V->dump();
266 #endif
267         assert(0 && "Value does not have a node in the points-to graph!");
268       }
269       return &GraphNodes[I->second];
270     }
271
272     /// getObject - Return the node corresponding to the memory object for the
273     /// specified global or allocation instruction.
274     Node *getObject(Value *V) {
275       std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
276       assert(I != ObjectNodes.end() &&
277              "Value does not have an object in the points-to graph!");
278       return &GraphNodes[I->second];
279     }
280
281     /// getReturnNode - Return the node representing the return value for the
282     /// specified function.
283     Node *getReturnNode(Function *F) {
284       std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
285       assert(I != ReturnNodes.end() && "Function does not return a value!");
286       return &GraphNodes[I->second];
287     }
288
289     /// getVarargNode - Return the node representing the variable arguments
290     /// formal for the specified function.
291     Node *getVarargNode(Function *F) {
292       std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
293       assert(I != VarargNodes.end() && "Function does not take var args!");
294       return &GraphNodes[I->second];
295     }
296
297     /// getNodeValue - Get the node for the specified LLVM value and set the
298     /// value for it to be the specified value.
299     Node *getNodeValue(Value &V) {
300       return getNode(&V)->setValue(&V);
301     }
302
303     void IdentifyObjects(Module &M);
304     void CollectConstraints(Module &M);
305     void SolveConstraints();
306
307     Node *getNodeForConstantPointer(Constant *C);
308     Node *getNodeForConstantPointerTarget(Constant *C);
309     void AddGlobalInitializerConstraints(Node *N, Constant *C);
310
311     void AddConstraintsForNonInternalLinkage(Function *F);
312     void AddConstraintsForCall(CallSite CS, Function *F);
313     bool AddConstraintsForExternalCall(CallSite CS, Function *F);
314
315
316     void PrintNode(Node *N);
317     void PrintConstraints();
318     void PrintPointsToGraph();
319
320     //===------------------------------------------------------------------===//
321     // Instruction visitation methods for adding constraints
322     //
323     friend class InstVisitor<Andersens>;
324     void visitReturnInst(ReturnInst &RI);
325     void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
326     void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
327     void visitCallSite(CallSite CS);
328     void visitAllocationInst(AllocationInst &AI);
329     void visitLoadInst(LoadInst &LI);
330     void visitStoreInst(StoreInst &SI);
331     void visitGetElementPtrInst(GetElementPtrInst &GEP);
332     void visitPHINode(PHINode &PN);
333     void visitCastInst(CastInst &CI);
334     void visitSetCondInst(SetCondInst &SCI) {} // NOOP!
335     void visitSelectInst(SelectInst &SI);
336     void visitVAArg(VAArgInst &I);
337     void visitInstruction(Instruction &I);
338   };
339
340   RegisterPass<Andersens> X("anders-aa",
341                             "Andersen's Interprocedural Alias Analysis");
342   RegisterAnalysisGroup<AliasAnalysis> Y(X);
343 }
344
345 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
346
347 //===----------------------------------------------------------------------===//
348 //                  AliasAnalysis Interface Implementation
349 //===----------------------------------------------------------------------===//
350
351 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
352                                             const Value *V2, unsigned V2Size) {
353   Node *N1 = getNode(const_cast<Value*>(V1));
354   Node *N2 = getNode(const_cast<Value*>(V2));
355
356   // Check to see if the two pointers are known to not alias.  They don't alias
357   // if their points-to sets do not intersect.
358   if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
359     return NoAlias;
360
361   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
362 }
363
364 AliasAnalysis::ModRefResult
365 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
366   // The only thing useful that we can contribute for mod/ref information is
367   // when calling external function calls: if we know that memory never escapes
368   // from the program, it cannot be modified by an external call.
369   //
370   // NOTE: This is not really safe, at least not when the entire program is not
371   // available.  The deal is that the external function could call back into the
372   // program and modify stuff.  We ignore this technical niggle for now.  This
373   // is, after all, a "research quality" implementation of Andersen's analysis.
374   if (Function *F = CS.getCalledFunction())
375     if (F->isExternal()) {
376       Node *N1 = getNode(P);
377
378       if (N1->begin() == N1->end())
379         return NoModRef;  // P doesn't point to anything.
380
381       // Get the first pointee.
382       Node *FirstPointee = *N1->begin();
383       if (FirstPointee != &GraphNodes[UniversalSet])
384         return NoModRef;  // P doesn't point to the universal set.
385     }
386
387   return AliasAnalysis::getModRefInfo(CS, P, Size);
388 }
389
390 AliasAnalysis::ModRefResult
391 Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
392   return AliasAnalysis::getModRefInfo(CS1,CS2);
393 }
394
395 /// getMustAlias - We can provide must alias information if we know that a
396 /// pointer can only point to a specific function or the null pointer.
397 /// Unfortunately we cannot determine must-alias information for global
398 /// variables or any other memory memory objects because we do not track whether
399 /// a pointer points to the beginning of an object or a field of it.
400 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
401   Node *N = getNode(P);
402   Node::iterator I = N->begin();
403   if (I != N->end()) {
404     // If there is exactly one element in the points-to set for the object...
405     ++I;
406     if (I == N->end()) {
407       Node *Pointee = *N->begin();
408
409       // If a function is the only object in the points-to set, then it must be
410       // the destination.  Note that we can't handle global variables here,
411       // because we don't know if the pointer is actually pointing to a field of
412       // the global or to the beginning of it.
413       if (Value *V = Pointee->getValue()) {
414         if (Function *F = dyn_cast<Function>(V))
415           RetVals.push_back(F);
416       } else {
417         // If the object in the points-to set is the null object, then the null
418         // pointer is a must alias.
419         if (Pointee == &GraphNodes[NullObject])
420           RetVals.push_back(Constant::getNullValue(P->getType()));
421       }
422     }
423   }
424
425   AliasAnalysis::getMustAliases(P, RetVals);
426 }
427
428 /// pointsToConstantMemory - If we can determine that this pointer only points
429 /// to constant memory, return true.  In practice, this means that if the
430 /// pointer can only point to constant globals, functions, or the null pointer,
431 /// return true.
432 ///
433 bool Andersens::pointsToConstantMemory(const Value *P) {
434   Node *N = getNode((Value*)P);
435   for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
436     if (Value *V = (*I)->getValue()) {
437       if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
438                                    !cast<GlobalVariable>(V)->isConstant()))
439         return AliasAnalysis::pointsToConstantMemory(P);
440     } else {
441       if (*I != &GraphNodes[NullObject])
442         return AliasAnalysis::pointsToConstantMemory(P);
443     }
444   }
445
446   return true;
447 }
448
449 //===----------------------------------------------------------------------===//
450 //                       Object Identification Phase
451 //===----------------------------------------------------------------------===//
452
453 /// IdentifyObjects - This stage scans the program, adding an entry to the
454 /// GraphNodes list for each memory object in the program (global stack or
455 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
456 ///
457 void Andersens::IdentifyObjects(Module &M) {
458   unsigned NumObjects = 0;
459
460   // Object #0 is always the universal set: the object that we don't know
461   // anything about.
462   assert(NumObjects == UniversalSet && "Something changed!");
463   ++NumObjects;
464
465   // Object #1 always represents the null pointer.
466   assert(NumObjects == NullPtr && "Something changed!");
467   ++NumObjects;
468
469   // Object #2 always represents the null object (the object pointed to by null)
470   assert(NumObjects == NullObject && "Something changed!");
471   ++NumObjects;
472
473   // Add all the globals first.
474   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
475        I != E; ++I) {
476     ObjectNodes[I] = NumObjects++;
477     ValueNodes[I] = NumObjects++;
478   }
479
480   // Add nodes for all of the functions and the instructions inside of them.
481   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
482     // The function itself is a memory object.
483     ValueNodes[F] = NumObjects++;
484     ObjectNodes[F] = NumObjects++;
485     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
486       ReturnNodes[F] = NumObjects++;
487     if (F->getFunctionType()->isVarArg())
488       VarargNodes[F] = NumObjects++;
489
490     // Add nodes for all of the incoming pointer arguments.
491     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
492          I != E; ++I)
493       if (isa<PointerType>(I->getType()))
494         ValueNodes[I] = NumObjects++;
495
496     // Scan the function body, creating a memory object for each heap/stack
497     // allocation in the body of the function and a node to represent all
498     // pointer values defined by instructions and used as operands.
499     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
500       // If this is an heap or stack allocation, create a node for the memory
501       // object.
502       if (isa<PointerType>(II->getType())) {
503         ValueNodes[&*II] = NumObjects++;
504         if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
505           ObjectNodes[AI] = NumObjects++;
506       }
507     }
508   }
509
510   // Now that we know how many objects to create, make them all now!
511   GraphNodes.resize(NumObjects);
512   NumNodes += NumObjects;
513 }
514
515 //===----------------------------------------------------------------------===//
516 //                     Constraint Identification Phase
517 //===----------------------------------------------------------------------===//
518
519 /// getNodeForConstantPointer - Return the node corresponding to the constant
520 /// pointer itself.
521 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
522   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
523
524   if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
525     return &GraphNodes[NullPtr];
526   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
527     return getNode(GV);
528   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
529     switch (CE->getOpcode()) {
530     case Instruction::GetElementPtr:
531       return getNodeForConstantPointer(CE->getOperand(0));
532     case Instruction::IntToPtr:
533       return &GraphNodes[UniversalSet];
534     case Instruction::BitCast:
535       return getNodeForConstantPointer(CE->getOperand(0));
536     default:
537       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
538       assert(0);
539     }
540   } else {
541     assert(0 && "Unknown constant pointer!");
542   }
543   return 0;
544 }
545
546 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
547 /// specified constant pointer.
548 Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
549   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
550
551   if (isa<ConstantPointerNull>(C))
552     return &GraphNodes[NullObject];
553   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
554     return getObject(GV);
555   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
556     switch (CE->getOpcode()) {
557     case Instruction::GetElementPtr:
558       return getNodeForConstantPointerTarget(CE->getOperand(0));
559     case Instruction::IntToPtr:
560       return &GraphNodes[UniversalSet];
561     case Instruction::BitCast:
562       return getNodeForConstantPointerTarget(CE->getOperand(0));
563     default:
564       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
565       assert(0);
566     }
567   } else {
568     assert(0 && "Unknown constant pointer!");
569   }
570   return 0;
571 }
572
573 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
574 /// object N, which contains values indicated by C.
575 void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
576   if (C->getType()->isFirstClassType()) {
577     if (isa<PointerType>(C->getType()))
578       N->copyFrom(getNodeForConstantPointer(C));
579
580   } else if (C->isNullValue()) {
581     N->addPointerTo(&GraphNodes[NullObject]);
582     return;
583   } else if (!isa<UndefValue>(C)) {
584     // If this is an array or struct, include constraints for each element.
585     assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
586     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
587       AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
588   }
589 }
590
591 /// AddConstraintsForNonInternalLinkage - If this function does not have
592 /// internal linkage, realize that we can't trust anything passed into or
593 /// returned by this function.
594 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
595   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
596     if (isa<PointerType>(I->getType()))
597       // If this is an argument of an externally accessible function, the
598       // incoming pointer might point to anything.
599       Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
600                                        &GraphNodes[UniversalSet]));
601 }
602
603 /// AddConstraintsForCall - If this is a call to a "known" function, add the
604 /// constraints and return true.  If this is a call to an unknown function,
605 /// return false.
606 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
607   assert(F->isExternal() && "Not an external function!");
608
609   // These functions don't induce any points-to constraints.
610   if (F->getName() == "atoi" || F->getName() == "atof" ||
611       F->getName() == "atol" || F->getName() == "atoll" ||
612       F->getName() == "remove" || F->getName() == "unlink" ||
613       F->getName() == "rename" || F->getName() == "memcmp" ||
614       F->getName() == "llvm.memset.i32" ||
615       F->getName() == "llvm.memset.i64" ||
616       F->getName() == "strcmp" || F->getName() == "strncmp" ||
617       F->getName() == "execl" || F->getName() == "execlp" ||
618       F->getName() == "execle" || F->getName() == "execv" ||
619       F->getName() == "execvp" || F->getName() == "chmod" ||
620       F->getName() == "puts" || F->getName() == "write" ||
621       F->getName() == "open" || F->getName() == "create" ||
622       F->getName() == "truncate" || F->getName() == "chdir" ||
623       F->getName() == "mkdir" || F->getName() == "rmdir" ||
624       F->getName() == "read" || F->getName() == "pipe" ||
625       F->getName() == "wait" || F->getName() == "time" ||
626       F->getName() == "stat" || F->getName() == "fstat" ||
627       F->getName() == "lstat" || F->getName() == "strtod" ||
628       F->getName() == "strtof" || F->getName() == "strtold" ||
629       F->getName() == "fopen" || F->getName() == "fdopen" ||
630       F->getName() == "freopen" ||
631       F->getName() == "fflush" || F->getName() == "feof" ||
632       F->getName() == "fileno" || F->getName() == "clearerr" ||
633       F->getName() == "rewind" || F->getName() == "ftell" ||
634       F->getName() == "ferror" || F->getName() == "fgetc" ||
635       F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
636       F->getName() == "fwrite" || F->getName() == "fread" ||
637       F->getName() == "fgets" || F->getName() == "ungetc" ||
638       F->getName() == "fputc" ||
639       F->getName() == "fputs" || F->getName() == "putc" ||
640       F->getName() == "ftell" || F->getName() == "rewind" ||
641       F->getName() == "_IO_putc" || F->getName() == "fseek" ||
642       F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
643       F->getName() == "printf" || F->getName() == "fprintf" ||
644       F->getName() == "sprintf" || F->getName() == "vprintf" ||
645       F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
646       F->getName() == "scanf" || F->getName() == "fscanf" ||
647       F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
648       F->getName() == "modf")
649     return true;
650
651
652   // These functions do induce points-to edges.
653   if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" || 
654       F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
655       F->getName() == "memmove") {
656     // Note: this is a poor approximation, this says Dest = Src, instead of
657     // *Dest = *Src.
658     Constraints.push_back(Constraint(Constraint::Copy,
659                                      getNode(CS.getArgument(0)),
660                                      getNode(CS.getArgument(1))));
661     return true;
662   }
663
664   // Result = Arg0
665   if (F->getName() == "realloc" || F->getName() == "strchr" ||
666       F->getName() == "strrchr" || F->getName() == "strstr" ||
667       F->getName() == "strtok") {
668     Constraints.push_back(Constraint(Constraint::Copy,
669                                      getNode(CS.getInstruction()),
670                                      getNode(CS.getArgument(0))));
671     return true;
672   }
673
674   return false;
675 }
676
677
678
679 /// CollectConstraints - This stage scans the program, adding a constraint to
680 /// the Constraints list for each instruction in the program that induces a
681 /// constraint, and setting up the initial points-to graph.
682 ///
683 void Andersens::CollectConstraints(Module &M) {
684   // First, the universal set points to itself.
685   GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
686   //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
687   //                                 &GraphNodes[UniversalSet]));
688   Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
689                                    &GraphNodes[UniversalSet]));
690
691   // Next, the null pointer points to the null object.
692   GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
693
694   // Next, add any constraints on global variables and their initializers.
695   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
696        I != E; ++I) {
697     // Associate the address of the global object as pointing to the memory for
698     // the global: &G = <G memory>
699     Node *Object = getObject(I);
700     Object->setValue(I);
701     getNodeValue(*I)->addPointerTo(Object);
702
703     if (I->hasInitializer()) {
704       AddGlobalInitializerConstraints(Object, I->getInitializer());
705     } else {
706       // If it doesn't have an initializer (i.e. it's defined in another
707       // translation unit), it points to the universal set.
708       Constraints.push_back(Constraint(Constraint::Copy, Object,
709                                        &GraphNodes[UniversalSet]));
710     }
711   }
712
713   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
714     // Make the function address point to the function object.
715     getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
716
717     // Set up the return value node.
718     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
719       getReturnNode(F)->setValue(F);
720     if (F->getFunctionType()->isVarArg())
721       getVarargNode(F)->setValue(F);
722
723     // Set up incoming argument nodes.
724     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
725          I != E; ++I)
726       if (isa<PointerType>(I->getType()))
727         getNodeValue(*I);
728
729     if (!F->hasInternalLinkage())
730       AddConstraintsForNonInternalLinkage(F);
731
732     if (!F->isExternal()) {
733       // Scan the function body, creating a memory object for each heap/stack
734       // allocation in the body of the function and a node to represent all
735       // pointer values defined by instructions and used as operands.
736       visit(F);
737     } else {
738       // External functions that return pointers return the universal set.
739       if (isa<PointerType>(F->getFunctionType()->getReturnType()))
740         Constraints.push_back(Constraint(Constraint::Copy,
741                                          getReturnNode(F),
742                                          &GraphNodes[UniversalSet]));
743
744       // Any pointers that are passed into the function have the universal set
745       // stored into them.
746       for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
747            I != E; ++I)
748         if (isa<PointerType>(I->getType())) {
749           // Pointers passed into external functions could have anything stored
750           // through them.
751           Constraints.push_back(Constraint(Constraint::Store, getNode(I),
752                                            &GraphNodes[UniversalSet]));
753           // Memory objects passed into external function calls can have the
754           // universal set point to them.
755           Constraints.push_back(Constraint(Constraint::Copy,
756                                            &GraphNodes[UniversalSet],
757                                            getNode(I)));
758         }
759
760       // If this is an external varargs function, it can also store pointers
761       // into any pointers passed through the varargs section.
762       if (F->getFunctionType()->isVarArg())
763         Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
764                                          &GraphNodes[UniversalSet]));
765     }
766   }
767   NumConstraints += Constraints.size();
768 }
769
770
771 void Andersens::visitInstruction(Instruction &I) {
772 #ifdef NDEBUG
773   return;          // This function is just a big assert.
774 #endif
775   if (isa<BinaryOperator>(I))
776     return;
777   // Most instructions don't have any effect on pointer values.
778   switch (I.getOpcode()) {
779   case Instruction::Br:
780   case Instruction::Switch:
781   case Instruction::Unwind:
782   case Instruction::Unreachable:
783   case Instruction::Free:
784   case Instruction::Shl:
785   case Instruction::LShr:
786   case Instruction::AShr:
787     return;
788   default:
789     // Is this something we aren't handling yet?
790     std::cerr << "Unknown instruction: " << I;
791     abort();
792   }
793 }
794
795 void Andersens::visitAllocationInst(AllocationInst &AI) {
796   getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
797 }
798
799 void 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
807 void 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
814 void 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
822 void 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
828 void 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
838 void 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>
847 #if 0
848       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
849                                        &GraphNodes[UniversalSet]));
850 #else
851       getNodeValue(CI);
852 #endif
853     }
854   } else if (isa<PointerType>(Op->getType())) {
855     // int = cast P1 --> <Copy/Univ/P1>
856 #if 0
857     Constraints.push_back(Constraint(Constraint::Copy,
858                                      &GraphNodes[UniversalSet],
859                                      getNode(CI.getOperand(0))));
860 #else
861     getNode(CI.getOperand(0));
862 #endif
863   }
864 }
865
866 void Andersens::visitSelectInst(SelectInst &SI) {
867   if (isa<PointerType>(SI.getType())) {
868     Node *SIN = getNodeValue(SI);
869     // P1 = select C, P2, P3   ---> <Copy/P1/P2>, <Copy/P1/P3>
870     Constraints.push_back(Constraint(Constraint::Copy, SIN,
871                                      getNode(SI.getOperand(1))));
872     Constraints.push_back(Constraint(Constraint::Copy, SIN,
873                                      getNode(SI.getOperand(2))));
874   }
875 }
876
877 void 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.
886 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
887   // 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
892   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
909   Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
910   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
936 void 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.
955 bool 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.
970 bool 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.
986 bool 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
1012 bool 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
1019 bool 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 ///
1031 void Andersens::SolveConstraints() {
1032   bool Changed = true;
1033   unsigned Iteration = 0;
1034   while (Changed) {
1035     Changed = false;
1036     ++NumIters;
1037     DOUT << "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             DOUT << "Found escaping internal function: " << F->getName() <<"\n";
1071             ++NumEscapingFunctions;
1072           }
1073
1074       // Check to see if we have discovered any new callees of the indirect call
1075       // sites.  If so, add constraints to the analysis.
1076       for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1077         CallSite CS = IndirectCalls[i];
1078         std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1079         Node *CN = getNode(CS.getCalledValue());
1080
1081         for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1082           if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1083             std::vector<Function*>::iterator IP =
1084               std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1085             if (IP == KnownCallees.end() || *IP != F) {
1086               // Add the constraints for the call now.
1087               AddConstraintsForCall(CS, F);
1088               DOUT << "Found actual callee '"
1089                    << F->getName() << "' for call: "
1090                    << *CS.getInstruction() << "\n";
1091               ++NumIndirectCallees;
1092               KnownCallees.insert(IP, F);
1093             }
1094           }
1095       }
1096     }
1097   }
1098 }
1099
1100
1101
1102 //===----------------------------------------------------------------------===//
1103 //                               Debugging Output
1104 //===----------------------------------------------------------------------===//
1105
1106 void Andersens::PrintNode(Node *N) {
1107   if (N == &GraphNodes[UniversalSet]) {
1108     std::cerr << "<universal>";
1109     return;
1110   } else if (N == &GraphNodes[NullPtr]) {
1111     std::cerr << "<nullptr>";
1112     return;
1113   } else if (N == &GraphNodes[NullObject]) {
1114     std::cerr << "<null>";
1115     return;
1116   }
1117
1118   assert(N->getValue() != 0 && "Never set node label!");
1119   Value *V = N->getValue();
1120   if (Function *F = dyn_cast<Function>(V)) {
1121     if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1122         N == getReturnNode(F)) {
1123       std::cerr << F->getName() << ":retval";
1124       return;
1125     } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
1126       std::cerr << F->getName() << ":vararg";
1127       return;
1128     }
1129   }
1130
1131   if (Instruction *I = dyn_cast<Instruction>(V))
1132     std::cerr << I->getParent()->getParent()->getName() << ":";
1133   else if (Argument *Arg = dyn_cast<Argument>(V))
1134     std::cerr << Arg->getParent()->getName() << ":";
1135
1136   if (V->hasName())
1137     std::cerr << V->getName();
1138   else
1139     std::cerr << "(unnamed)";
1140
1141   if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1142     if (N == getObject(V))
1143       std::cerr << "<mem>";
1144 }
1145
1146 void Andersens::PrintConstraints() {
1147   std::cerr << "Constraints:\n";
1148   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1149     std::cerr << "  #" << i << ":  ";
1150     Constraint &C = Constraints[i];
1151     if (C.Type == Constraint::Store)
1152       std::cerr << "*";
1153     PrintNode(C.Dest);
1154     std::cerr << " = ";
1155     if (C.Type == Constraint::Load)
1156       std::cerr << "*";
1157     PrintNode(C.Src);
1158     std::cerr << "\n";
1159   }
1160 }
1161
1162 void Andersens::PrintPointsToGraph() {
1163   std::cerr << "Points-to graph:\n";
1164   for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1165     Node *N = &GraphNodes[i];
1166     std::cerr << "[" << (N->end() - N->begin()) << "] ";
1167     PrintNode(N);
1168     std::cerr << "\t--> ";
1169     for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1170       if (I != N->begin()) std::cerr << ", ";
1171       PrintNode(*I);
1172     }
1173     std::cerr << "\n";
1174   }
1175 }