LLVM API Documentation

CallGraph.cpp

Go to the documentation of this file.
00001 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the CallGraph class and provides the BasicCallGraph
00011 // default implementation.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/CallGraph.h"
00016 #include "llvm/Module.h"
00017 #include "llvm/Instructions.h"
00018 #include "llvm/Support/CallSite.h"
00019 #include "llvm/Support/Compiler.h"
00020 #include "llvm/Support/Streams.h"
00021 #include <ostream>
00022 using namespace llvm;
00023 
00024 namespace {
00025 
00026 //===----------------------------------------------------------------------===//
00027 // BasicCallGraph class definition
00028 //
00029 class VISIBILITY_HIDDEN BasicCallGraph : public CallGraph, public ModulePass {
00030   // Root is root of the call graph, or the external node if a 'main' function
00031   // couldn't be found.
00032   //
00033   CallGraphNode *Root;
00034 
00035   // ExternalCallingNode - This node has edges to all external functions and
00036   // those internal functions that have their address taken.
00037   CallGraphNode *ExternalCallingNode;
00038 
00039   // CallsExternalNode - This node has edges to it from all functions making
00040   // indirect calls or calling an external function.
00041   CallGraphNode *CallsExternalNode;
00042 
00043 public:
00044   static char ID; // Class identification, replacement for typeinfo
00045   BasicCallGraph() : ModulePass(&ID), Root(0), 
00046     ExternalCallingNode(0), CallsExternalNode(0) {}
00047 
00048   // runOnModule - Compute the call graph for the specified module.
00049   virtual bool runOnModule(Module &M) {
00050     CallGraph::initialize(M);
00051     
00052     ExternalCallingNode = getOrInsertFunction(0);
00053     CallsExternalNode = new CallGraphNode(0);
00054     Root = 0;
00055   
00056     // Add every function to the call graph...
00057     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00058       addToCallGraph(I);
00059   
00060     // If we didn't find a main function, use the external call graph node
00061     if (Root == 0) Root = ExternalCallingNode;
00062     
00063     return false;
00064   }
00065 
00066   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00067     AU.setPreservesAll();
00068   }
00069 
00070   void print(std::ostream *o, const Module *M) const {
00071     if (o) print(*o, M);
00072   }
00073 
00074   virtual void print(std::ostream &o, const Module *M) const {
00075     o << "CallGraph Root is: ";
00076     if (Function *F = getRoot()->getFunction())
00077       o << F->getName() << "\n";
00078     else
00079       o << "<<null function: 0x" << getRoot() << ">>\n";
00080     
00081     CallGraph::print(o, M);
00082   }
00083 
00084   virtual void releaseMemory() {
00085     destroy();
00086   }
00087   
00088   /// dump - Print out this call graph.
00089   ///
00090   inline void dump() const {
00091     print(cerr, Mod);
00092   }
00093 
00094   CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
00095   CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
00096 
00097   // getRoot - Return the root of the call graph, which is either main, or if
00098   // main cannot be found, the external node.
00099   //
00100   CallGraphNode *getRoot()             { return Root; }
00101   const CallGraphNode *getRoot() const { return Root; }
00102 
00103 private:
00104   //===---------------------------------------------------------------------
00105   // Implementation of CallGraph construction
00106   //
00107 
00108   // addToCallGraph - Add a function to the call graph, and link the node to all
00109   // of the functions that it calls.
00110   //
00111   void addToCallGraph(Function *F) {
00112     CallGraphNode *Node = getOrInsertFunction(F);
00113 
00114     // If this function has external linkage, anything could call it.
00115     if (!F->hasLocalLinkage()) {
00116       ExternalCallingNode->addCalledFunction(CallSite(), Node);
00117 
00118       // Found the entry point?
00119       if (F->getName() == "main") {
00120         if (Root)    // Found multiple external mains?  Don't pick one.
00121           Root = ExternalCallingNode;
00122         else
00123           Root = Node;          // Found a main, keep track of it!
00124       }
00125     }
00126 
00127     // Loop over all of the users of the function, looking for non-call uses.
00128     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I)
00129       if ((!isa<CallInst>(I) && !isa<InvokeInst>(I))
00130           || !CallSite(cast<Instruction>(I)).isCallee(I)) {
00131         // Not a call, or being used as a parameter rather than as the callee.
00132         ExternalCallingNode->addCalledFunction(CallSite(), Node);
00133         break;
00134       }
00135 
00136     // If this function is not defined in this translation unit, it could call
00137     // anything.
00138     if (F->isDeclaration() && !F->isIntrinsic())
00139       Node->addCalledFunction(CallSite(), CallsExternalNode);
00140 
00141     // Look for calls by this function.
00142     for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
00143       for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
00144            II != IE; ++II) {
00145         CallSite CS = CallSite::get(II);
00146         if (CS.getInstruction()) {
00147           const Function *Callee = CS.getCalledFunction();
00148           if (Callee)
00149             Node->addCalledFunction(CS, getOrInsertFunction(Callee));
00150           else
00151             Node->addCalledFunction(CS, CallsExternalNode);
00152         }
00153       }
00154   }
00155 
00156   //
00157   // destroy - Release memory for the call graph
00158   virtual void destroy() {
00159     /// CallsExternalNode is not in the function map, delete it explicitly.
00160     delete CallsExternalNode;
00161     CallsExternalNode = 0;
00162     CallGraph::destroy();
00163   }
00164 };
00165 
00166 } //End anonymous namespace
00167 
00168 static RegisterAnalysisGroup<CallGraph> X("Call Graph");
00169 static RegisterPass<BasicCallGraph>
00170 Y("basiccg", "Basic CallGraph Construction", false, true);
00171 static RegisterAnalysisGroup<CallGraph, true> Z(Y);
00172 
00173 char CallGraph::ID = 0;
00174 char BasicCallGraph::ID = 0;
00175 
00176 void CallGraph::initialize(Module &M) {
00177   Mod = &M;
00178 }
00179 
00180 void CallGraph::destroy() {
00181   if (!FunctionMap.empty()) {
00182     for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
00183         I != E; ++I)
00184       delete I->second;
00185     FunctionMap.clear();
00186   }
00187 }
00188 
00189 void CallGraph::print(std::ostream &OS, const Module *M) const {
00190   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
00191     I->second->print(OS);
00192 }
00193 
00194 void CallGraph::dump() const {
00195   print(cerr, 0);
00196 }
00197 
00198 //===----------------------------------------------------------------------===//
00199 // Implementations of public modification methods
00200 //
00201 
00202 // removeFunctionFromModule - Unlink the function from this module, returning
00203 // it.  Because this removes the function from the module, the call graph node
00204 // is destroyed.  This is only valid if the function does not call any other
00205 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
00206 // is to dropAllReferences before calling this.
00207 //
00208 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
00209   assert(CGN->CalledFunctions.empty() && "Cannot remove function from call "
00210          "graph if it references other functions!");
00211   Function *F = CGN->getFunction(); // Get the function for the call graph node
00212   delete CGN;                       // Delete the call graph node for this func
00213   FunctionMap.erase(F);             // Remove the call graph node from the map
00214 
00215   Mod->getFunctionList().remove(F);
00216   return F;
00217 }
00218 
00219 // changeFunction - This method changes the function associated with this
00220 // CallGraphNode, for use by transformations that need to change the prototype
00221 // of a Function (thus they must create a new Function and move the old code
00222 // over).
00223 void CallGraph::changeFunction(Function *OldF, Function *NewF) {
00224   iterator I = FunctionMap.find(OldF);
00225   CallGraphNode *&New = FunctionMap[NewF];
00226   assert(I != FunctionMap.end() && I->second && !New &&
00227          "OldF didn't exist in CG or NewF already does!");
00228   New = I->second;
00229   New->F = NewF;
00230   FunctionMap.erase(I);
00231 }
00232 
00233 // getOrInsertFunction - This method is identical to calling operator[], but
00234 // it will insert a new CallGraphNode for the specified function if one does
00235 // not already exist.
00236 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
00237   CallGraphNode *&CGN = FunctionMap[F];
00238   if (CGN) return CGN;
00239   
00240   assert((!F || F->getParent() == Mod) && "Function not in current module!");
00241   return CGN = new CallGraphNode(const_cast<Function*>(F));
00242 }
00243 
00244 void CallGraphNode::print(std::ostream &OS) const {
00245   if (Function *F = getFunction())
00246     OS << "Call graph node for function: '" << F->getName() <<"'\n";
00247   else
00248     OS << "Call graph node <<null function: 0x" << this << ">>:\n";
00249 
00250   for (const_iterator I = begin(), E = end(); I != E; ++I)
00251     if (Function *FI = I->second->getFunction())
00252       OS << "  Calls function '" << FI->getName() <<"'\n";
00253   else
00254     OS << "  Calls external node\n";
00255   OS << "\n";
00256 }
00257 
00258 void CallGraphNode::dump() const { print(cerr); }
00259 
00260 /// removeCallEdgeFor - This method removes the edge in the node for the
00261 /// specified call site.  Note that this method takes linear time, so it
00262 /// should be used sparingly.
00263 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
00264   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00265     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
00266     if (I->first == CS) {
00267       CalledFunctions.erase(I);
00268       return;
00269     }
00270   }
00271 }
00272 
00273 
00274 // removeAnyCallEdgeTo - This method removes any call edges from this node to
00275 // the specified callee function.  This takes more time to execute than
00276 // removeCallEdgeTo, so it should not be used unless necessary.
00277 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
00278   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
00279     if (CalledFunctions[i].second == Callee) {
00280       CalledFunctions[i] = CalledFunctions.back();
00281       CalledFunctions.pop_back();
00282       --i; --e;
00283     }
00284 }
00285 
00286 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
00287 /// from this node to the specified callee function.
00288 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
00289   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00290     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
00291     CallRecord &CR = *I;
00292     if (CR.second == Callee && !CR.first.getInstruction()) {
00293       CalledFunctions.erase(I);
00294       return;
00295     }
00296   }
00297 }
00298 
00299 /// replaceCallSite - Make the edge in the node for Old CallSite be for
00300 /// New CallSite instead.  Note that this method takes linear time, so it
00301 /// should be used sparingly.
00302 void CallGraphNode::replaceCallSite(CallSite Old, CallSite New) {
00303   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00304     assert(I != CalledFunctions.end() && "Cannot find callsite to replace!");
00305     if (I->first == Old) {
00306       I->first = New;
00307       return;
00308     }
00309   }
00310 }
00311 
00312 // Enuse that users of CallGraph.h also link with this file
00313 DEFINING_FILE_FOR(CallGraph)