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