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 #include "llvm/Analysis/CallGraph.h"
00011 #include "llvm/IR/CallSite.h"
00012 #include "llvm/IR/Instructions.h"
00013 #include "llvm/IR/IntrinsicInst.h"
00014 #include "llvm/IR/Module.h"
00015 #include "llvm/Support/Debug.h"
00016 #include "llvm/Support/raw_ostream.h"
00017 using namespace llvm;
00018 
00019 //===----------------------------------------------------------------------===//
00020 // Implementations of the CallGraph class methods.
00021 //
00022 
00023 CallGraph::CallGraph(Module &M)
00024     : M(M), Root(0), ExternalCallingNode(getOrInsertFunction(0)),
00025       CallsExternalNode(new CallGraphNode(0)) {
00026   // Add every function to the call graph.
00027   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00028     addToCallGraph(I);
00029 
00030   // If we didn't find a main function, use the external call graph node
00031   if (Root == 0)
00032     Root = ExternalCallingNode;
00033 }
00034 
00035 CallGraph::~CallGraph() {
00036   // CallsExternalNode is not in the function map, delete it explicitly.
00037   CallsExternalNode->allReferencesDropped();
00038   delete CallsExternalNode;
00039 
00040 // Reset all node's use counts to zero before deleting them to prevent an
00041 // assertion from firing.
00042 #ifndef NDEBUG
00043   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
00044        I != E; ++I)
00045     I->second->allReferencesDropped();
00046 #endif
00047   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
00048        I != E; ++I)
00049     delete I->second;
00050 }
00051 
00052 void CallGraph::addToCallGraph(Function *F) {
00053   CallGraphNode *Node = getOrInsertFunction(F);
00054 
00055   // If this function has external linkage, anything could call it.
00056   if (!F->hasLocalLinkage()) {
00057     ExternalCallingNode->addCalledFunction(CallSite(), Node);
00058 
00059     // Found the entry point?
00060     if (F->getName() == "main") {
00061       if (Root) // Found multiple external mains?  Don't pick one.
00062         Root = ExternalCallingNode;
00063       else
00064         Root = Node; // Found a main, keep track of it!
00065     }
00066   }
00067 
00068   // If this function has its address taken, anything could call it.
00069   if (F->hasAddressTaken())
00070     ExternalCallingNode->addCalledFunction(CallSite(), Node);
00071 
00072   // If this function is not defined in this translation unit, it could call
00073   // anything.
00074   if (F->isDeclaration() && !F->isIntrinsic())
00075     Node->addCalledFunction(CallSite(), CallsExternalNode);
00076 
00077   // Look for calls by this function.
00078   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
00079     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
00080          ++II) {
00081       CallSite CS(cast<Value>(II));
00082       if (CS) {
00083         const Function *Callee = CS.getCalledFunction();
00084         if (!Callee)
00085           // Indirect calls of intrinsics are not allowed so no need to check.
00086           Node->addCalledFunction(CS, CallsExternalNode);
00087         else if (!Callee->isIntrinsic())
00088           Node->addCalledFunction(CS, getOrInsertFunction(Callee));
00089       }
00090     }
00091 }
00092 
00093 void CallGraph::print(raw_ostream &OS) const {
00094   OS << "CallGraph Root is: ";
00095   if (Function *F = Root->getFunction())
00096     OS << F->getName() << "\n";
00097   else {
00098     OS << "<<null function: 0x" << Root << ">>\n";
00099   }
00100 
00101   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
00102     I->second->print(OS);
00103 }
00104 
00105 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00106 void CallGraph::dump() const { print(dbgs()); }
00107 #endif
00108 
00109 // removeFunctionFromModule - Unlink the function from this module, returning
00110 // it.  Because this removes the function from the module, the call graph node
00111 // is destroyed.  This is only valid if the function does not call any other
00112 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
00113 // is to dropAllReferences before calling this.
00114 //
00115 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
00116   assert(CGN->empty() && "Cannot remove function from call "
00117          "graph if it references other functions!");
00118   Function *F = CGN->getFunction(); // Get the function for the call graph node
00119   delete CGN;                       // Delete the call graph node for this func
00120   FunctionMap.erase(F);             // Remove the call graph node from the map
00121 
00122   M.getFunctionList().remove(F);
00123   return F;
00124 }
00125 
00126 /// spliceFunction - Replace the function represented by this node by another.
00127 /// This does not rescan the body of the function, so it is suitable when
00128 /// splicing the body of the old function to the new while also updating all
00129 /// callers from old to new.
00130 ///
00131 void CallGraph::spliceFunction(const Function *From, const Function *To) {
00132   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
00133   assert(!FunctionMap.count(To) &&
00134          "Pointing CallGraphNode at a function that already exists");
00135   FunctionMapTy::iterator I = FunctionMap.find(From);
00136   I->second->F = const_cast<Function*>(To);
00137   FunctionMap[To] = I->second;
00138   FunctionMap.erase(I);
00139 }
00140 
00141 // getOrInsertFunction - This method is identical to calling operator[], but
00142 // it will insert a new CallGraphNode for the specified function if one does
00143 // not already exist.
00144 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
00145   CallGraphNode *&CGN = FunctionMap[F];
00146   if (CGN)
00147     return CGN;
00148 
00149   assert((!F || F->getParent() == &M) && "Function not in current module!");
00150   return CGN = new CallGraphNode(const_cast<Function*>(F));
00151 }
00152 
00153 //===----------------------------------------------------------------------===//
00154 // Implementations of the CallGraphNode class methods.
00155 //
00156 
00157 void CallGraphNode::print(raw_ostream &OS) const {
00158   if (Function *F = getFunction())
00159     OS << "Call graph node for function: '" << F->getName() << "'";
00160   else
00161     OS << "Call graph node <<null function>>";
00162   
00163   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
00164 
00165   for (const_iterator I = begin(), E = end(); I != E; ++I) {
00166     OS << "  CS<" << I->first << "> calls ";
00167     if (Function *FI = I->second->getFunction())
00168       OS << "function '" << FI->getName() <<"'\n";
00169     else
00170       OS << "external node\n";
00171   }
00172   OS << '\n';
00173 }
00174 
00175 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00176 void CallGraphNode::dump() const { print(dbgs()); }
00177 #endif
00178 
00179 /// removeCallEdgeFor - This method removes the edge in the node for the
00180 /// specified call site.  Note that this method takes linear time, so it
00181 /// should be used sparingly.
00182 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
00183   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00184     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
00185     if (I->first == CS.getInstruction()) {
00186       I->second->DropRef();
00187       *I = CalledFunctions.back();
00188       CalledFunctions.pop_back();
00189       return;
00190     }
00191   }
00192 }
00193 
00194 // removeAnyCallEdgeTo - This method removes any call edges from this node to
00195 // the specified callee function.  This takes more time to execute than
00196 // removeCallEdgeTo, so it should not be used unless necessary.
00197 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
00198   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
00199     if (CalledFunctions[i].second == Callee) {
00200       Callee->DropRef();
00201       CalledFunctions[i] = CalledFunctions.back();
00202       CalledFunctions.pop_back();
00203       --i; --e;
00204     }
00205 }
00206 
00207 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
00208 /// from this node to the specified callee function.
00209 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
00210   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00211     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
00212     CallRecord &CR = *I;
00213     if (CR.second == Callee && CR.first == 0) {
00214       Callee->DropRef();
00215       *I = CalledFunctions.back();
00216       CalledFunctions.pop_back();
00217       return;
00218     }
00219   }
00220 }
00221 
00222 /// replaceCallEdge - This method replaces the edge in the node for the
00223 /// specified call site with a new one.  Note that this method takes linear
00224 /// time, so it should be used sparingly.
00225 void CallGraphNode::replaceCallEdge(CallSite CS,
00226                                     CallSite NewCS, CallGraphNode *NewNode){
00227   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00228     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
00229     if (I->first == CS.getInstruction()) {
00230       I->second->DropRef();
00231       I->first = NewCS.getInstruction();
00232       I->second = NewNode;
00233       NewNode->AddRef();
00234       return;
00235     }
00236   }
00237 }
00238 
00239 //===----------------------------------------------------------------------===//
00240 // Out-of-line definitions of CallGraphAnalysis class members.
00241 //
00242 
00243 char CallGraphAnalysis::PassID;
00244 
00245 //===----------------------------------------------------------------------===//
00246 // Implementations of the CallGraphWrapperPass class methods.
00247 //
00248 
00249 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
00250   initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
00251 }
00252 
00253 CallGraphWrapperPass::~CallGraphWrapperPass() {}
00254 
00255 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
00256   AU.setPreservesAll();
00257 }
00258 
00259 bool CallGraphWrapperPass::runOnModule(Module &M) {
00260   // All the real work is done in the constructor for the CallGraph.
00261   G.reset(new CallGraph(M));
00262   return false;
00263 }
00264 
00265 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
00266                 false, true)
00267 
00268 char CallGraphWrapperPass::ID = 0;
00269 
00270 void CallGraphWrapperPass::releaseMemory() { G.reset(0); }
00271 
00272 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
00273   if (!G) {
00274     OS << "No call graph has been built!\n";
00275     return;
00276   }
00277 
00278   // Just delegate.
00279   G->print(OS);
00280 }
00281 
00282 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00283 void CallGraphWrapperPass::dump() const { print(dbgs(), 0); }
00284 #endif
00285 
00286 // Enuse that users of CallGraph.h also link with this file
00287 DEFINING_FILE_FOR(CallGraph)