1 //===- Andersens.cpp - Andersen's Interprocedural Alias Analysis -----------==//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
16 // In pointer analysis terms, this is a subset-based, flow-insensitive,
17 // field-insensitive, and context-insensitive algorithm pointer algorithm.
19 // This algorithm is implemented as three stages:
20 // 1. Object identification.
21 // 2. Inclusion constraint identification.
22 // 3. Inclusion constraint solving.
24 // The object identification stage identifies all of the memory objects in the
25 // program, which includes globals, heap allocated objects, and stack allocated
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.
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.
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.
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.
50 //===----------------------------------------------------------------------===//
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"
68 NumIters("anders-aa", "Number of iterations to reach convergence");
70 NumConstraints("anders-aa", "Number of constraints");
72 NumNodes("anders-aa", "Number of nodes");
74 NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
76 NumIndirectCallees("anders-aa", "Number of indirect callees found");
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.
83 std::vector<Node*> Pointees;
87 Node *setValue(Value *V) {
88 assert(Val == 0 && "Value already set for this node!");
93 /// getValue - Return the LLVM value corresponding to this node.
94 Value *getValue() const { return Val; }
96 typedef std::vector<Node*>::const_iterator iterator;
97 iterator begin() const { return Pointees.begin(); }
98 iterator end() const { return Pointees.end(); }
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(),
107 if (I != Pointees.end() && *I == N)
109 Pointees.insert(I, N);
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;
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;
122 // Constraint application methods.
123 bool copyFrom(Node *N);
124 bool loadFrom(Node *N);
125 bool storeThrough(Node *N);
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;
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;
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;
141 /// ReturnNodes - This map contains an entry for each function in the
142 /// program that returns a value.
143 std::map<Function*, unsigned> ReturnNodes;
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;
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".
156 enum ConstraintType { Copy, Load, Store } Type;
159 Constraint(ConstraintType Ty, Node *D, Node *S)
160 : Type(Ty), Dest(D), Src(S) {}
163 /// Constraints - This vector contains a list of all of the constraints
164 /// identified by the program.
165 std::vector<Constraint> Constraints;
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;
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
179 std::vector<CallSite> IndirectCalls;
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
185 std::map<CallSite, std::vector<Function*> > IndirectCallees;
187 /// This enum defines the GraphNodes indices that correspond to important
196 bool run(Module &M) {
197 InitializeAliasAnalysis(this);
199 CollectConstraints(M);
200 DEBUG(PrintConstraints());
202 DEBUG(PrintPointsToGraph());
204 // Free the constraints list, as we don't need it to respond to alias
209 EscapingInternalFunctions.clear();
210 std::vector<Constraint>().swap(Constraints);
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. :(
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);
226 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
227 AliasAnalysis::getAnalysisUsage(AU);
228 AU.setPreservesAll(); // Does not transform code
231 //------------------------------------------------
232 // Implement the AliasAnalysis API
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);
239 virtual void deleteValue(Value *V) {
241 getAnalysis<AliasAnalysis>().deleteValue(V);
244 virtual void copyValue(Value *From, Value *To) {
245 ValueNodes[To] = ValueNodes[From];
246 getAnalysis<AliasAnalysis>().copyValue(From, To);
250 /// getNode - Return the node corresponding to the specified pointer scalar.
252 Node *getNode(Value *V) {
253 if (Constant *C = dyn_cast<Constant>(V))
254 return getNodeForConstantPointer(C);
256 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
257 if (I == ValueNodes.end()) {
259 assert(I != ValueNodes.end() &&
260 "Value does not have a node in the points-to graph!");
262 return &GraphNodes[I->second];
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];
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];
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];
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);
296 void IdentifyObjects(Module &M);
297 void CollectConstraints(Module &M);
298 void SolveConstraints();
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);
307 void PrintNode(Node *N);
308 void PrintConstraints();
309 void PrintPointsToGraph();
311 //===------------------------------------------------------------------===//
312 // Instruction visitation methods for adding constraints
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);
331 RegisterOpt<Andersens> X("anders-aa",
332 "Andersen's Interprocedural Alias Analysis");
333 RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
336 //===----------------------------------------------------------------------===//
337 // AliasAnalysis Interface Implementation
338 //===----------------------------------------------------------------------===//
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);
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]))
350 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
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();
362 // If there is exactly one element in the points-to set for the object...
365 Node *Pointee = *N->begin();
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);
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()));
383 AliasAnalysis::getMustAliases(P, RetVals);
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,
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);
399 if (*I != &GraphNodes[NullObject])
400 return AliasAnalysis::pointsToConstantMemory(P);
407 //===----------------------------------------------------------------------===//
408 // Object Identification Phase
409 //===----------------------------------------------------------------------===//
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.
415 void Andersens::IdentifyObjects(Module &M) {
416 unsigned NumObjects = 0;
418 // Object #0 is always the universal set: the object that we don't know
420 assert(NumObjects == UniversalSet && "Something changed!");
423 // Object #1 always represents the null pointer.
424 assert(NumObjects == NullPtr && "Something changed!");
427 // Object #2 always represents the null object (the object pointed to by null)
428 assert(NumObjects == NullObject && "Something changed!");
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++;
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++;
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++;
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
458 if (isa<PointerType>(II->getType())) {
459 ValueNodes[&*II] = NumObjects++;
460 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
461 ObjectNodes[AI] = NumObjects++;
466 // Now that we know how many objects to create, make them all now!
467 GraphNodes.resize(NumObjects);
468 NumNodes += NumObjects;
471 //===----------------------------------------------------------------------===//
472 // Constraint Identification Phase
473 //===----------------------------------------------------------------------===//
475 /// getNodeForConstantPointer - Return the node corresponding to the constant
477 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
478 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
480 if (isa<ConstantPointerNull>(C))
481 return &GraphNodes[NullPtr];
482 else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C))
483 return getNode(CPR->getValue());
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));
492 return &GraphNodes[UniversalSet];
494 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
498 assert(0 && "Unknown constant pointer!");
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!");
508 if (isa<ConstantPointerNull>(C))
509 return &GraphNodes[NullObject];
510 else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C))
511 return getObject(CPR->getValue());
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));
520 return &GraphNodes[UniversalSet];
522 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
526 assert(0 && "Unknown constant pointer!");
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]);
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)));
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]));
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.
562 void Andersens::CollectConstraints(Module &M) {
563 // First, the universal set points to itself.
564 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
566 // Next, the null pointer points to the null object.
567 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
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);
575 getNodeValue(*I)->addPointerTo(Object);
577 if (I->hasInitializer()) {
578 AddGlobalInitializerConstraints(Object, I->getInitializer());
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]));
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));
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);
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()))
602 if (!F->hasInternalLinkage())
603 AddConstraintsForNonInternalLinkage(F);
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.
611 // External functions that return pointers return the universal set.
612 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
613 Constraints.push_back(Constraint(Constraint::Copy,
615 &GraphNodes[UniversalSet]));
617 // Any pointers that are passed into the function have the universal set
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
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],
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]));
639 NumConstraints += Constraints.size();
643 void Andersens::visitInstruction(Instruction &I) {
645 return; // This function is just a big assert.
647 if (isa<BinaryOperator>(I))
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:
659 // Is this something we aren't handling yet?
660 std::cerr << "Unknown instruction: " << I;
665 void Andersens::visitAllocationInst(AllocationInst &AI) {
666 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
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))));
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))));
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))));
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))));
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))));
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))));
716 // P1 = cast int --> <Copy/P1/Univ>
717 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
718 &GraphNodes[UniversalSet]));
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))));
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))));
739 void Andersens::visitVANext(VANextInst &I) {
741 assert(0 && "vanext not handled yet!");
743 void Andersens::visitVAArg(VAArgInst &I) {
744 assert(0 && "vaarg not handled yet!");
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
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,
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]));
764 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
765 Constraints.push_back(Constraint(Constraint::Copy,
766 &GraphNodes[UniversalSet],
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),
779 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
780 &GraphNodes[UniversalSet]));
782 } else if (isa<PointerType>((*ArgI)->getType())) {
783 Constraints.push_back(Constraint(Constraint::Copy,
784 &GraphNodes[UniversalSet],
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),
794 // If more arguments are passed in than we track, just drop them on the floor.
797 void Andersens::visitCallSite(CallSite CS) {
798 if (isa<PointerType>(CS.getType()))
799 getNodeValue(*CS.getInstruction());
801 if (Function *F = CS.getCalledFunction()) {
802 AddConstraintsForCall(CS, F);
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);
810 //===----------------------------------------------------------------------===//
811 // Constraint Solving Phase
812 //===----------------------------------------------------------------------===//
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;
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) {
835 if (*I1 != Ignoring) return true;
837 } else if (*I1 < *I2)
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();
852 while (I != E && i != Pointees.size()) {
853 if (Pointees[i] < *I) {
855 } else if (Pointees[i] == *I) {
858 // We found a new element to copy over.
860 Pointees.insert(Pointees.begin()+i, *I);
866 Pointees.insert(Pointees.end(), I, E);
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);
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);
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.
892 void Andersens::SolveConstraints() {
894 unsigned Iteration = 0;
898 DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
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];
904 case Constraint::Copy:
905 Changed |= C.Dest->copyFrom(C.Src);
907 case Constraint::Load:
908 Changed |= C.Dest->loadFrom(C.Src);
910 case Constraint::Store:
911 Changed |= C.Dest->storeThrough(C.Src);
914 assert(0 && "Unknown constraint!");
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;
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());
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);
964 //===----------------------------------------------------------------------===//
966 //===----------------------------------------------------------------------===//
968 void Andersens::PrintNode(Node *N) {
969 if (N == &GraphNodes[UniversalSet]) {
970 std::cerr << "<universal>";
972 } else if (N == &GraphNodes[NullPtr]) {
973 std::cerr << "<nullptr>";
975 } else if (N == &GraphNodes[NullObject]) {
976 std::cerr << "<null>";
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";
987 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
988 std::cerr << F->getName() << ":vararg";
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() << ":";
999 std::cerr << V->getName();
1001 std::cerr << "(unnamed)";
1003 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1004 if (N == getObject(V))
1005 std::cerr << "<mem>";
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)
1017 if (C.Type == Constraint::Load)
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()) << "] ";
1030 std::cerr << "\t--> ";
1031 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1032 if (I != N->begin()) std::cerr << ", ";