Get rid of idefs for arguments
[oota-llvm.git] / lib / Analysis / IPA / Andersens.cpp
index 12f0fc30065d8f39dce6ee03e01a003d03e32cf9..50ee474339325674d6e203bc95b04bcff6eae709 100644 (file)
@@ -58,8 +58,9 @@
 #include "llvm/Support/InstIterator.h"
 #include "llvm/Support/InstVisitor.h"
 #include "llvm/Analysis/AliasAnalysis.h"
-#include "Support/Debug.h"
-#include "Support/Statistic.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/ADT/Statistic.h"
 #include <set>
 using namespace llvm;
 
@@ -75,7 +76,7 @@ namespace {
   Statistic<>
   NumIndirectCallees("anders-aa", "Number of indirect callees found");
 
-  class Andersens : public Pass, public AliasAnalysis,
+  class Andersens : public ModulePass, public AliasAnalysis,
                     private InstVisitor<Andersens> {
     /// Node class - This class is used to represent a memory object in the
     /// program, and is the primitive used to build the points-to graph.
@@ -91,6 +92,7 @@ namespace {
       }
 
       /// getValue - Return the LLVM value corresponding to this node.
+      ///
       Value *getValue() const { return Val; }
 
       typedef std::vector<Node*>::const_iterator iterator;
@@ -193,7 +195,7 @@ namespace {
     };
     
   public:
-    bool run(Module &M) {
+    bool runOnModule(Module &M) {
       InitializeAliasAnalysis(this);
       IdentifyObjects(M);
       CollectConstraints(M);
@@ -233,6 +235,7 @@ namespace {
     //  
     AliasResult alias(const Value *V1, unsigned V1Size,
                       const Value *V2, unsigned V2Size);
+    ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
     void getMustAliases(Value *P, std::vector<Value*> &RetVals);
     bool pointsToConstantMemory(const Value *P);
 
@@ -251,7 +254,8 @@ namespace {
     ///
     Node *getNode(Value *V) {
       if (Constant *C = dyn_cast<Constant>(V))
-        return getNodeForConstantPointer(C);
+        if (!isa<GlobalValue>(C))
+          return getNodeForConstantPointer(C);
 
       std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
       if (I == ValueNodes.end()) {
@@ -300,8 +304,10 @@ namespace {
     Node *getNodeForConstantPointer(Constant *C);
     Node *getNodeForConstantPointerTarget(Constant *C);
     void AddGlobalInitializerConstraints(Node *N, Constant *C);
+
     void AddConstraintsForNonInternalLinkage(Function *F);
     void AddConstraintsForCall(CallSite CS, Function *F);
+    bool AddConstraintsForExternalCall(CallSite CS, Function *F);
 
 
     void PrintNode(Node *N);
@@ -322,6 +328,7 @@ namespace {
     void visitGetElementPtrInst(GetElementPtrInst &GEP);
     void visitPHINode(PHINode &PN);
     void visitCastInst(CastInst &CI);
+    void visitSetCondInst(SetCondInst &SCI) {} // NOOP!
     void visitSelectInst(SelectInst &SI);
     void visitVANext(VANextInst &I);
     void visitVAArg(VAArgInst &I);
@@ -333,14 +340,16 @@ namespace {
   RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
 }
 
+ModulePass *llvm::createAndersensPass() { return new Andersens(); }
+
 //===----------------------------------------------------------------------===//
 //                  AliasAnalysis Interface Implementation
 //===----------------------------------------------------------------------===//
 
 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
                                             const Value *V2, unsigned V2Size) {
-  Node *N1 = getNode((Value*)V1);
-  Node *N2 = getNode((Value*)V2);
+  Node *N1 = getNode(const_cast<Value*>(V1));
+  Node *N2 = getNode(const_cast<Value*>(V2));
 
   // Check to see if the two pointers are known to not alias.  They don't alias
   // if their points-to sets do not intersect.
@@ -350,6 +359,33 @@ AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
 }
 
+AliasAnalysis::ModRefResult
+Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
+  // The only thing useful that we can contribute for mod/ref information is
+  // when calling external function calls: if we know that memory never escapes
+  // from the program, it cannot be modified by an external call.
+  //
+  // NOTE: This is not really safe, at least not when the entire program is not
+  // available.  The deal is that the external function could call back into the
+  // program and modify stuff.  We ignore this technical niggle for now.  This
+  // is, after all, a "research quality" implementation of Andersen's analysis.
+  if (Function *F = CS.getCalledFunction())
+    if (F->isExternal()) {
+      Node *N1 = getNode(P);
+      bool PointsToUniversalSet = false;
+
+      if (N1->begin() == N1->end())
+        return NoModRef;  // P doesn't point to anything.
+
+      // Get the first pointee.
+      Node *FirstPointee = *N1->begin();
+      if (FirstPointee != &GraphNodes[UniversalSet])
+        return NoModRef;  // P doesn't point to the universal set.
+    }
+
+  return AliasAnalysis::getModRefInfo(CS, P, Size);
+}
+
 /// getMustAlias - We can provide must alias information if we know that a
 /// pointer can only point to a specific function or the null pointer.
 /// Unfortunately we cannot determine must-alias information for global
@@ -429,7 +465,8 @@ void Andersens::IdentifyObjects(Module &M) {
   ++NumObjects;
 
   // Add all the globals first.
-  for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
+  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+       I != E; ++I) {
     ObjectNodes[I] = NumObjects++;
     ValueNodes[I] = NumObjects++;
   }
@@ -445,7 +482,8 @@ void Andersens::IdentifyObjects(Module &M) {
       VarargNodes[F] = NumObjects++;
 
     // Add nodes for all of the incoming pointer arguments.
-    for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
+    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
+         I != E; ++I)
       if (isa<PointerType>(I->getType()))
         ValueNodes[I] = NumObjects++;
 
@@ -477,7 +515,7 @@ void Andersens::IdentifyObjects(Module &M) {
 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
 
-  if (isa<ConstantPointerNull>(C))
+  if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
     return &GraphNodes[NullPtr];
   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
     return getNode(GV);
@@ -533,11 +571,12 @@ Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
 void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
   if (C->getType()->isFirstClassType()) {
     if (isa<PointerType>(C->getType()))
-      N->addPointerTo(getNodeForConstantPointer(C));
+      N->copyFrom(getNodeForConstantPointer(C));
+                                       
   } else if (C->isNullValue()) {
     N->addPointerTo(&GraphNodes[NullObject]);
     return;
-  } else {
+  } else if (!isa<UndefValue>(C)) {
     // If this is an array or struct, include constraints for each element.
     assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
@@ -545,8 +584,11 @@ void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
   }
 }
 
+/// AddConstraintsForNonInternalLinkage - If this function does not have
+/// internal linkage, realize that we can't trust anything passed into or
+/// returned by this function.
 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
-  for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
+  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
     if (isa<PointerType>(I->getType()))
       // If this is an argument of an externally accessible function, the
       // incoming pointer might point to anything.
@@ -554,6 +596,79 @@ void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
                                        &GraphNodes[UniversalSet]));
 }
 
+/// AddConstraintsForCall - If this is a call to a "known" function, add the
+/// constraints and return true.  If this is a call to an unknown function,
+/// return false.
+bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
+  assert(F->isExternal() && "Not an external function!");
+
+  // These functions don't induce any points-to constraints.
+  if (F->getName() == "atoi" || F->getName() == "atof" ||
+      F->getName() == "atol" || F->getName() == "atoll" ||
+      F->getName() == "remove" || F->getName() == "unlink" ||
+      F->getName() == "rename" || F->getName() == "memcmp" ||
+      F->getName() == "llvm.memset" || 
+      F->getName() == "strcmp" || F->getName() == "strncmp" ||
+      F->getName() == "execl" || F->getName() == "execlp" ||
+      F->getName() == "execle" || F->getName() == "execv" ||
+      F->getName() == "execvp" || F->getName() == "chmod" ||
+      F->getName() == "puts" || F->getName() == "write" ||
+      F->getName() == "open" || F->getName() == "create" ||
+      F->getName() == "truncate" || F->getName() == "chdir" ||
+      F->getName() == "mkdir" || F->getName() == "rmdir" ||
+      F->getName() == "read" || F->getName() == "pipe" ||
+      F->getName() == "wait" || F->getName() == "time" ||
+      F->getName() == "stat" || F->getName() == "fstat" ||
+      F->getName() == "lstat" || F->getName() == "strtod" ||
+      F->getName() == "strtof" || F->getName() == "strtold" ||
+      F->getName() == "fopen" || F->getName() == "fdopen" ||
+      F->getName() == "freopen" ||
+      F->getName() == "fflush" || F->getName() == "feof" ||
+      F->getName() == "fileno" || F->getName() == "clearerr" ||
+      F->getName() == "rewind" || F->getName() == "ftell" ||
+      F->getName() == "ferror" || F->getName() == "fgetc" ||
+      F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
+      F->getName() == "fwrite" || F->getName() == "fread" ||
+      F->getName() == "fgets" || F->getName() == "ungetc" ||
+      F->getName() == "fputc" ||
+      F->getName() == "fputs" || F->getName() == "putc" ||
+      F->getName() == "ftell" || F->getName() == "rewind" ||
+      F->getName() == "_IO_putc" || F->getName() == "fseek" ||
+      F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
+      F->getName() == "printf" || F->getName() == "fprintf" ||
+      F->getName() == "sprintf" || F->getName() == "vprintf" ||
+      F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
+      F->getName() == "scanf" || F->getName() == "fscanf" ||
+      F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
+      F->getName() == "modf")
+    return true;
+
+
+  // These functions do induce points-to edges.
+  if (F->getName() == "llvm.memcpy" || F->getName() == "llvm.memmove" ||
+      F->getName() == "memmove") {
+    // Note: this is a poor approximation, this says Dest = Src, instead of
+    // *Dest = *Src.
+    Constraints.push_back(Constraint(Constraint::Copy,
+                                     getNode(CS.getArgument(0)),
+                                     getNode(CS.getArgument(1))));
+    return true;
+  }
+
+  // Result = Arg0
+  if (F->getName() == "realloc" || F->getName() == "strchr" ||
+      F->getName() == "strrchr" || F->getName() == "strstr" ||
+      F->getName() == "strtok") {
+    Constraints.push_back(Constraint(Constraint::Copy,
+                                     getNode(CS.getInstruction()),
+                                     getNode(CS.getArgument(0))));
+    return true;
+  }
+
+  return false;
+}
+
+
 
 /// CollectConstraints - This stage scans the program, adding a constraint to
 /// the Constraints list for each instruction in the program that induces a
@@ -562,12 +677,17 @@ void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
 void Andersens::CollectConstraints(Module &M) {
   // First, the universal set points to itself.
   GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
+  //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
+  //                                 &GraphNodes[UniversalSet]));
+  Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
+                                   &GraphNodes[UniversalSet]));
 
   // Next, the null pointer points to the null object.
   GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
 
   // Next, add any constraints on global variables and their initializers.
-  for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
+  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+       I != E; ++I) {
     // Associate the address of the global object as pointing to the memory for
     // the global: &G = <G memory>
     Node *Object = getObject(I);
@@ -595,7 +715,8 @@ void Andersens::CollectConstraints(Module &M) {
       getVarargNode(F)->setValue(F);
 
     // Set up incoming argument nodes.
-    for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
+    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
+         I != E; ++I)
       if (isa<PointerType>(I->getType()))
         getNodeValue(*I);
 
@@ -616,7 +737,8 @@ void Andersens::CollectConstraints(Module &M) {
 
       // Any pointers that are passed into the function have the universal set
       // stored into them.
-      for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
+      for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
+           I != E; ++I)
         if (isa<PointerType>(I->getType())) {
           // Pointers passed into external functions could have anything stored
           // through them.
@@ -651,6 +773,7 @@ void Andersens::visitInstruction(Instruction &I) {
   case Instruction::Br:
   case Instruction::Switch:
   case Instruction::Unwind:
+  case Instruction::Unreachable:
   case Instruction::Free:
   case Instruction::Shl:
   case Instruction::Shr:
@@ -714,14 +837,22 @@ void Andersens::visitCastInst(CastInst &CI) {
                                        getNode(CI.getOperand(0))));
     } else {
       // P1 = cast int --> <Copy/P1/Univ>
+#if 0
       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
                                        &GraphNodes[UniversalSet]));
+#else
+      getNodeValue(CI);
+#endif
     }
   } else if (isa<PointerType>(Op->getType())) {
     // int = cast P1 --> <Copy/Univ/P1>
+#if 0
     Constraints.push_back(Constraint(Constraint::Copy,
                                      &GraphNodes[UniversalSet],
                                      getNode(CI.getOperand(0))));
+#else
+    getNode(CI.getOperand(0));
+#endif
   }
 }
 
@@ -750,6 +881,11 @@ void Andersens::visitVAArg(VAArgInst &I) {
 /// the function pointer has been casted.  If this is the case, do something
 /// reasonable.
 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
+  // If this is a call to an external function, handle it directly to get some
+  // taste of context sensitivity.
+  if (F->isExternal() && AddConstraintsForExternalCall(CS, F))
+    return;
+
   if (isa<PointerType>(CS.getType())) {
     Node *CSN = getNode(CS.getInstruction());
     if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
@@ -767,7 +903,7 @@ void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
                                      getReturnNode(F)));
   }
   
-  Function::aiterator AI = F->abegin(), AE = F->aend();
+  Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
   CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
   for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
     if (isa<PointerType>(AI->getType())) {