Fix a bug pointed out by Zhongxing Xu
[oota-llvm.git] / lib / Analysis / IPA / CallGraph.cpp
index 6ca23c662ac99c366cc088f204ec69bbd6eb93c4..d9e7242695cffb4cf205a001e8512e1b71ae0584 100644 (file)
@@ -1,13 +1,14 @@
 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
-// 
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file was developed by the LLVM research group and is distributed under
 // the University of Illinois Open Source License. See LICENSE.TXT for details.
-// 
+//
 //===----------------------------------------------------------------------===//
 //
-//  This file implements the CallGraph class.
+// This file implements the CallGraph class and provides the BasicCallGraph
+// default implementation.
 //
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Module.h"
 #include "llvm/Instructions.h"
 #include "llvm/Support/CallSite.h"
-#include "llvm/ADT/STLExtras.h"
 #include <iostream>
 using namespace llvm;
 
-static RegisterAnalysis<CallGraph> X("callgraph", "Call Graph Construction");
-
-// getNodeFor - Return the node for the specified function or create one if it
-// does not already exist.
-//
-CallGraphNode *CallGraph::getNodeFor(Function *F) {
-  CallGraphNode *&CGN = FunctionMap[F];
-  if (CGN) return CGN;
-
-  assert((!F || F->getParent() == Mod) && "Function not in current module!");
-  return CGN = new CallGraphNode(F);
-}
-
 static bool isOnlyADirectCall(Function *F, CallSite CS) {
   if (!CS.getInstruction()) return false;
   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
@@ -39,116 +26,182 @@ static bool isOnlyADirectCall(Function *F, CallSite CS) {
   return true;
 }
 
-// addToCallGraph - Add a function to the call graph, and link the node to all
-// of the functions that it calls.
+namespace {
+
+//===----------------------------------------------------------------------===//
+// BasicCallGraph class definition
 //
-void CallGraph::addToCallGraph(Function *F) {
-  CallGraphNode *Node = getNodeFor(F);
-
-  // If this function has external linkage, anything could call it...
-  if (!F->hasInternalLinkage()) {
-    ExternalCallingNode->addCalledFunction(Node);
-
-    // Found the entry point?
-    if (F->getName() == "main") {
-      if (Root)    // Found multiple external mains?  Don't pick one.
-        Root = ExternalCallingNode;
-      else
-        Root = Node;          // Found a main, keep track of it!
-    }
+class BasicCallGraph : public CallGraph, public ModulePass {
+  // Root is root of the call graph, or the external node if a 'main' function
+  // couldn't be found.
+  //
+  CallGraphNode *Root;
+
+  // ExternalCallingNode - This node has edges to all external functions and
+  // those internal functions that have their address taken.
+  CallGraphNode *ExternalCallingNode;
+
+  // CallsExternalNode - This node has edges to it from all functions making
+  // indirect calls or calling an external function.
+  CallGraphNode *CallsExternalNode;
+
+public:
+  BasicCallGraph() : Root(0), ExternalCallingNode(0), CallsExternalNode(0) {}
+  ~BasicCallGraph() { destroy(); }
+
+  // runOnModule - Compute the call graph for the specified module.
+  virtual bool runOnModule(Module &M) {
+    destroy();
+    CallGraph::initialize(M);
+    
+    ExternalCallingNode = getOrInsertFunction(0);
+    CallsExternalNode = new CallGraphNode(0);
+    Root = 0;
+  
+    // Add every function to the call graph...
+    for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+      addToCallGraph(I);
+  
+    // If we didn't find a main function, use the external call graph node
+    if (Root == 0) Root = ExternalCallingNode;
+    
+    return false;
+  }
+
+  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+    AU.setPreservesAll();
+  }
+
+  virtual void print(std::ostream &o, const Module *M) const {
+    o << "CallGraph Root is: ";
+    if (Function *F = getRoot()->getFunction())
+      o << F->getName() << "\n";
+    else
+      o << "<<null function: 0x" << getRoot() << ">>\n";
+    
+    CallGraph::print(o, M);
+  }
+
+  virtual void releaseMemory() {
+    destroy();
   }
   
-  // If this function is not defined in this translation unit, it could call
-  // anything.
-  if (F->isExternal() && !F->getIntrinsicID())
-    Node->addCalledFunction(CallsExternalNode);
+  /// dump - Print out this call graph.
+  ///
+  inline void dump() const {
+    print(std::cerr, Mod);
+  }
+
+  CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
+  CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
 
-  // Loop over all of the users of the function... looking for callers...
+  // getRoot - Return the root of the call graph, which is either main, or if
+  // main cannot be found, the external node.
   //
-  bool isUsedExternally = false;
-  for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I) {
-    if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
-      if (isOnlyADirectCall(F, CallSite::get(Inst)))
-        getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);
-      else
-        isUsedExternally = true;
-    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
-      for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
-           I != E; ++I)
-        if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
-          if (isOnlyADirectCall(F, CallSite::get(Inst)))
-            getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);
-          else
-            isUsedExternally = true;
-        } else {
+  CallGraphNode *getRoot()             { return Root; }
+  const CallGraphNode *getRoot() const { return Root; }
+
+private:
+  //===---------------------------------------------------------------------
+  // Implementation of CallGraph construction
+  //
+
+  // addToCallGraph - Add a function to the call graph, and link the node to all
+  // of the functions that it calls.
+  //
+  void addToCallGraph(Function *F) {
+    CallGraphNode *Node = getOrInsertFunction(F);
+
+    // If this function has external linkage, anything could call it.
+    if (!F->hasInternalLinkage()) {
+      ExternalCallingNode->addCalledFunction(CallSite(), Node);
+
+      // Found the entry point?
+      if (F->getName() == "main") {
+        if (Root)    // Found multiple external mains?  Don't pick one.
+          Root = ExternalCallingNode;
+        else
+          Root = Node;          // Found a main, keep track of it!
+      }
+    }
+
+    // If this function is not defined in this translation unit, it could call
+    // anything.
+    if (F->isExternal() && !F->getIntrinsicID())
+      Node->addCalledFunction(CallSite(), CallsExternalNode);
+
+    // Loop over all of the users of the function... looking for callers...
+    //
+    bool isUsedExternally = false;
+    for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I){
+      if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
+        CallSite CS = CallSite::get(Inst);
+        if (isOnlyADirectCall(F, CS))
+          getOrInsertFunction(Inst->getParent()->getParent())
+              ->addCalledFunction(CS, Node);
+        else
           isUsedExternally = true;
-        }
-    } else {                        // Can't classify the user!
-      isUsedExternally = true;
+      } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
+        for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
+             I != E; ++I)
+          if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
+            CallSite CS = CallSite::get(Inst);
+            if (isOnlyADirectCall(F, CS))
+              getOrInsertFunction(Inst->getParent()->getParent())
+                ->addCalledFunction(CS, Node);
+            else
+              isUsedExternally = true;
+          } else {
+            isUsedExternally = true;
+          }
+      } else {                        // Can't classify the user!
+        isUsedExternally = true;
+      }
     }
-  }
-  if (isUsedExternally)
-    ExternalCallingNode->addCalledFunction(Node);
+    if (isUsedExternally)
+      ExternalCallingNode->addCalledFunction(CallSite(), Node);
 
-  // Look for an indirect function call...
-  for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
-    for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){
+    // Look for an indirect function call.
+    for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
+      for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
+           II != IE; ++II) {
       CallSite CS = CallSite::get(II);
       if (CS.getInstruction() && !CS.getCalledFunction())
-        Node->addCalledFunction(CallsExternalNode);
-    }
-}
+        Node->addCalledFunction(CS, CallsExternalNode);
+      }
+  }
 
-bool CallGraph::runOnModule(Module &M) {
-  destroy();
+  //
+  // destroy - Release memory for the call graph
+  virtual void destroy() {
+    if (!CallsExternalNode) {
+      delete CallsExternalNode;
+      CallsExternalNode = 0;
+    }
+  }
+};
 
-  Mod = &M;
-  ExternalCallingNode = getNodeFor(0);
-  CallsExternalNode = new CallGraphNode(0);
-  Root = 0;
+RegisterAnalysisGroup<CallGraph> X("Call Graph");
+RegisterPass<BasicCallGraph> Y("basiccg", "Basic CallGraph Construction");
+RegisterAnalysisGroup<CallGraph, true> Z(Y);
 
-  // Add every function to the call graph...
-  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
-    addToCallGraph(I);
+} //End anonymous namespace
 
-  // If we didn't find a main function, use the external call graph node
-  if (Root == 0) Root = ExternalCallingNode;
-  
-  return false;
+void CallGraph::initialize(Module &M) {
+  destroy();
+  Mod = &M;
 }
 
 void CallGraph::destroy() {
-  for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
-       I != E; ++I)
-    delete I->second;
-  FunctionMap.clear();
-  delete CallsExternalNode;
-  CallsExternalNode = 0;
-}
-
-void CallGraphNode::print(std::ostream &OS) const {
-  if (Function *F = getFunction())
-    OS << "Call graph node for function: '" << F->getName() <<"'\n";
-  else
-    OS << "Call graph node <<null function: 0x" << this << ">>:\n";
-
-  for (const_iterator I = begin(), E = end(); I != E; ++I)
-    if ((*I)->getFunction())
-      OS << "  Calls function '" << (*I)->getFunction()->getName() << "'\n";
-    else
-      OS << "  Calls external node\n";
-  OS << "\n";
+  if (!FunctionMap.empty()) {
+    for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
+        I != E; ++I)
+      delete I->second;
+    FunctionMap.clear();
+  }
 }
 
-void CallGraphNode::dump() const { print(std::cerr); }
-
 void CallGraph::print(std::ostream &OS, const Module *M) const {
-  OS << "CallGraph Root is: ";
-  if (Function *F = getRoot()->getFunction())
-    OS << F->getName() << "\n";
-  else
-    OS << "<<null function: 0x" << getRoot() << ">>\n";
-  
   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
     I->second->print(OS);
 }
@@ -157,7 +210,6 @@ void CallGraph::dump() const {
   print(std::cerr, 0);
 }
 
-
 //===----------------------------------------------------------------------===//
 // Implementations of public modification methods
 //
@@ -193,13 +245,37 @@ void CallGraph::changeFunction(Function *OldF, Function *NewF) {
   FunctionMap.erase(I);
 }
 
+// getOrInsertFunction - This method is identical to calling operator[], but
+// it will insert a new CallGraphNode for the specified function if one does
+// not already exist.
+CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
+  CallGraphNode *&CGN = FunctionMap[F];
+  if (CGN) return CGN;
+  
+  assert((!F || F->getParent() == Mod) && "Function not in current module!");
+  return CGN = new CallGraphNode(const_cast<Function*>(F));
+}
+
+void CallGraphNode::print(std::ostream &OS) const {
+  if (Function *F = getFunction())
+    OS << "Call graph node for function: '" << F->getName() <<"'\n";
+  else
+    OS << "Call graph node <<null function: 0x" << this << ">>:\n";
+
+  for (const_iterator I = begin(), E = end(); I != E; ++I)
+    if (I->second->getFunction())
+      OS << "  Calls function '" << I->second->getFunction()->getName() <<"'\n";
+  else
+    OS << "  Calls external node\n";
+  OS << "\n";
+}
 
-void CallGraph::stub() {}
+void CallGraphNode::dump() const { print(std::cerr); }
 
 void CallGraphNode::removeCallEdgeTo(CallGraphNode *Callee) {
   for (unsigned i = CalledFunctions.size(); ; --i) {
     assert(i && "Cannot find callee to remove!");
-    if (CalledFunctions[i-1] == Callee) {
+    if (CalledFunctions[i-1].second == Callee) {
       CalledFunctions.erase(CalledFunctions.begin()+i-1);
       return;
     }
@@ -211,9 +287,12 @@ void CallGraphNode::removeCallEdgeTo(CallGraphNode *Callee) {
 // removeCallEdgeTo, so it should not be used unless necessary.
 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
-    if (CalledFunctions[i] == Callee) {
+    if (CalledFunctions[i].second == Callee) {
       CalledFunctions[i] = CalledFunctions.back();
       CalledFunctions.pop_back();
       --i; --e;
     }
 }
+
+// Enuse that users of CallGraph.h also link with this file
+DEFINING_FILE_FOR(CallGraph)