LCOV - code coverage report
Current view: top level - lib/Analysis/IPA - CallGraph.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 109 135 80.7 %
Date: 2015-08-18 11:13:53 Functions: 20 23 87.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : 
      10             : #include "llvm/Analysis/CallGraph.h"
      11             : #include "llvm/IR/CallSite.h"
      12             : #include "llvm/IR/Instructions.h"
      13             : #include "llvm/IR/IntrinsicInst.h"
      14             : #include "llvm/IR/Module.h"
      15             : #include "llvm/Support/Debug.h"
      16             : #include "llvm/Support/raw_ostream.h"
      17             : using namespace llvm;
      18             : 
      19             : //===----------------------------------------------------------------------===//
      20             : // Implementations of the CallGraph class methods.
      21             : //
      22             : 
      23        4646 : CallGraph::CallGraph(Module &M)
      24        4646 :     : M(M), Root(nullptr), ExternalCallingNode(getOrInsertFunction(nullptr)),
      25       13938 :       CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
      26             :   // Add every function to the call graph.
      27       13938 :   for (Function &F : M)
      28       70363 :     addToCallGraph(&F);
      29             : 
      30             :   // If we didn't find a main function, use the external call graph node
      31        4646 :   if (!Root)
      32        4055 :     Root = ExternalCallingNode;
      33        4646 : }
      34             : 
      35           0 : CallGraph::CallGraph(CallGraph &&Arg)
      36           0 :     : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)), Root(Arg.Root),
      37           0 :       ExternalCallingNode(Arg.ExternalCallingNode),
      38           0 :       CallsExternalNode(std::move(Arg.CallsExternalNode)) {
      39           0 :   Arg.FunctionMap.clear();
      40           0 :   Arg.Root = nullptr;
      41           0 :   Arg.ExternalCallingNode = nullptr;
      42           0 : }
      43             : 
      44       13938 : CallGraph::~CallGraph() {
      45             :   // CallsExternalNode is not in the function map, delete it explicitly.
      46        9292 :   if (CallsExternalNode)
      47        4646 :     CallsExternalNode->allReferencesDropped();
      48             : 
      49             : // Reset all node's use counts to zero before deleting them to prevent an
      50             : // assertion from firing.
      51             : #ifndef NDEBUG
      52             :   for (auto &I : FunctionMap)
      53             :     I.second->allReferencesDropped();
      54             : #endif
      55        4646 : }
      56             : 
      57       70363 : void CallGraph::addToCallGraph(Function *F) {
      58       70363 :   CallGraphNode *Node = getOrInsertFunction(F);
      59             : 
      60             :   // If this function has external linkage, anything could call it.
      61      140726 :   if (!F->hasLocalLinkage()) {
      62      107532 :     ExternalCallingNode->addCalledFunction(CallSite(), Node);
      63             : 
      64             :     // Found the entry point?
      65      107532 :     if (F->getName() == "main") {
      66         591 :       if (Root) // Found multiple external mains?  Don't pick one.
      67           0 :         Root = ExternalCallingNode;
      68             :       else
      69         591 :         Root = Node; // Found a main, keep track of it!
      70             :     }
      71             :   }
      72             : 
      73             :   // If this function has its address taken, anything could call it.
      74       70363 :   if (F->hasAddressTaken())
      75        6783 :     ExternalCallingNode->addCalledFunction(CallSite(), Node);
      76             : 
      77             :   // If this function is not defined in this translation unit, it could call
      78             :   // anything.
      79       70363 :   if (F->isDeclaration() && !F->isIntrinsic())
      80       25827 :     Node->addCalledFunction(CallSite(), CallsExternalNode.get());
      81             : 
      82             :   // Look for calls by this function.
      83      140726 :   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
      84      204420 :     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
      85             :          ++II) {
      86      984796 :       CallSite CS(cast<Value>(II));
      87      492398 :       if (CS) {
      88       65689 :         const Function *Callee = CS.getCalledFunction();
      89       65689 :         if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
      90             :           // Indirect calls of intrinsics are not allowed so no need to check.
      91             :           // We can be more precise here by using TargetArg returned by
      92             :           // Intrinsic::isLeaf.
      93        5202 :           Node->addCalledFunction(CS, CallsExternalNode.get());
      94       63088 :         else if (!Callee->isIntrinsic())
      95       41481 :           Node->addCalledFunction(CS, getOrInsertFunction(Callee));
      96             :       }
      97             :     }
      98       70363 : }
      99             : 
     100           5 : void CallGraph::print(raw_ostream &OS) const {
     101           5 :   OS << "CallGraph Root is: ";
     102          10 :   if (Function *F = Root->getFunction())
     103           0 :     OS << F->getName() << "\n";
     104             :   else {
     105           5 :     OS << "<<null function: 0x" << Root << ">>\n";
     106             :   }
     107             : 
     108             :   // Print in a deterministic order by sorting CallGraphNodes by name.  We do
     109             :   // this here to avoid slowing down the non-printing fast path.
     110             : 
     111             :   SmallVector<CallGraphNode *, 16> Nodes;
     112          10 :   Nodes.reserve(FunctionMap.size());
     113             : 
     114          10 :   for (auto I = begin(), E = end(); I != E; ++I)
     115          32 :     Nodes.push_back(I->second.get());
     116             : 
     117           5 :   std::sort(Nodes.begin(), Nodes.end(),
     118          33 :             [](CallGraphNode *LHS, CallGraphNode *RHS) {
     119          33 :     if (Function *LF = LHS->getFunction())
     120          33 :       if (Function *RF = RHS->getFunction())
     121          12 :         return LF->getName() < RF->getName();
     122             : 
     123          21 :     return RHS->getFunction() != nullptr;
     124           5 :   });
     125             : 
     126          21 :   for (CallGraphNode *CN : Nodes)
     127          16 :     CN->print(OS);
     128           5 : }
     129             : 
     130             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     131             : void CallGraph::dump() const { print(dbgs()); }
     132             : #endif
     133             : 
     134             : // removeFunctionFromModule - Unlink the function from this module, returning
     135             : // it.  Because this removes the function from the module, the call graph node
     136             : // is destroyed.  This is only valid if the function does not call any other
     137             : // functions (ie, there are no edges in it's CGN).  The easiest way to do this
     138             : // is to dropAllReferences before calling this.
     139             : //
     140       12685 : Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
     141             :   assert(CGN->empty() && "Cannot remove function from call "
     142             :          "graph if it references other functions!");
     143       12685 :   Function *F = CGN->getFunction(); // Get the function for the call graph node
     144       25370 :   FunctionMap.erase(F);             // Remove the call graph node from the map
     145             : 
     146       25370 :   M.getFunctionList().remove(F);
     147       12685 :   return F;
     148             : }
     149             : 
     150             : /// spliceFunction - Replace the function represented by this node by another.
     151             : /// This does not rescan the body of the function, so it is suitable when
     152             : /// splicing the body of the old function to the new while also updating all
     153             : /// callers from old to new.
     154             : ///
     155           0 : void CallGraph::spliceFunction(const Function *From, const Function *To) {
     156             :   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
     157             :   assert(!FunctionMap.count(To) &&
     158             :          "Pointing CallGraphNode at a function that already exists");
     159           0 :   FunctionMapTy::iterator I = FunctionMap.find(From);
     160           0 :   I->second->F = const_cast<Function*>(To);
     161           0 :   FunctionMap[To] = std::move(I->second);
     162           0 :   FunctionMap.erase(I);
     163           0 : }
     164             : 
     165             : // getOrInsertFunction - This method is identical to calling operator[], but
     166             : // it will insert a new CallGraphNode for the specified function if one does
     167             : // not already exist.
     168      116638 : CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
     169      116638 :   auto &CGN = FunctionMap[F];
     170      116638 :   if (CGN)
     171             :     return CGN.get();
     172             : 
     173             :   assert((!F || F->getParent() == &M) && "Function not in current module!");
     174      225141 :   CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
     175       75047 :   return CGN.get();
     176             : }
     177             : 
     178             : //===----------------------------------------------------------------------===//
     179             : // Implementations of the CallGraphNode class methods.
     180             : //
     181             : 
     182          16 : void CallGraphNode::print(raw_ostream &OS) const {
     183          16 :   if (Function *F = getFunction())
     184          11 :     OS << "Call graph node for function: '" << F->getName() << "'";
     185             :   else
     186           5 :     OS << "Call graph node <<null function>>";
     187             :   
     188          48 :   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
     189             : 
     190          63 :   for (const_iterator I = begin(), E = end(); I != E; ++I) {
     191          30 :     OS << "  CS<" << I->first << "> calls ";
     192          30 :     if (Function *FI = I->second->getFunction())
     193          12 :       OS << "function '" << FI->getName() <<"'\n";
     194             :     else
     195           3 :       OS << "external node\n";
     196             :   }
     197             :   OS << '\n';
     198          16 : }
     199             : 
     200             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     201             : void CallGraphNode::dump() const { print(dbgs()); }
     202             : #endif
     203             : 
     204             : /// removeCallEdgeFor - This method removes the edge in the node for the
     205             : /// specified call site.  Note that this method takes linear time, so it
     206             : /// should be used sparingly.
     207       17015 : void CallGraphNode::removeCallEdgeFor(CallSite CS) {
     208       34030 :   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
     209             :     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
     210       63387 :     if (I->first == CS.getInstruction()) {
     211       17015 :       I->second->DropRef();
     212       34030 :       *I = CalledFunctions.back();
     213       17015 :       CalledFunctions.pop_back();
     214       17015 :       return;
     215             :     }
     216             :   }
     217             : }
     218             : 
     219             : // removeAnyCallEdgeTo - This method removes any call edges from this node to
     220             : // the specified callee function.  This takes more time to execute than
     221             : // removeCallEdgeTo, so it should not be used unless necessary.
     222         164 : void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
     223        4277 :   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
     224        7898 :     if (CalledFunctions[i].second == Callee) {
     225         157 :       Callee->DropRef();
     226         314 :       CalledFunctions[i] = CalledFunctions.back();
     227         157 :       CalledFunctions.pop_back();
     228         157 :       --i; --e;
     229             :     }
     230         164 : }
     231             : 
     232             : /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
     233             : /// from this node to the specified callee function.
     234           0 : void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
     235           0 :   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
     236             :     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
     237           0 :     CallRecord &CR = *I;
     238           0 :     if (CR.second == Callee && CR.first == nullptr) {
     239           0 :       Callee->DropRef();
     240           0 :       *I = CalledFunctions.back();
     241           0 :       CalledFunctions.pop_back();
     242           0 :       return;
     243             :     }
     244             :   }
     245             : }
     246             : 
     247             : /// replaceCallEdge - This method replaces the edge in the node for the
     248             : /// specified call site with a new one.  Note that this method takes linear
     249             : /// time, so it should be used sparingly.
     250          49 : void CallGraphNode::replaceCallEdge(CallSite CS,
     251             :                                     CallSite NewCS, CallGraphNode *NewNode){
     252          98 :   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
     253             :     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
     254         303 :     if (I->first == CS.getInstruction()) {
     255          98 :       I->second->DropRef();
     256          98 :       I->first = NewCS.getInstruction();
     257          49 :       I->second = NewNode;
     258          49 :       NewNode->AddRef();
     259          49 :       return;
     260             :     }
     261             :   }
     262             : }
     263             : 
     264             : //===----------------------------------------------------------------------===//
     265             : // Out-of-line definitions of CallGraphAnalysis class members.
     266             : //
     267             : 
     268             : char CallGraphAnalysis::PassID;
     269             : 
     270             : //===----------------------------------------------------------------------===//
     271             : // Implementations of the CallGraphWrapperPass class methods.
     272             : //
     273             : 
     274        9288 : CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
     275        4644 :   initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
     276        4644 : }
     277             : 
     278        9260 : CallGraphWrapperPass::~CallGraphWrapperPass() {}
     279             : 
     280        4644 : void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
     281        4644 :   AU.setPreservesAll();
     282        4644 : }
     283             : 
     284        4644 : bool CallGraphWrapperPass::runOnModule(Module &M) {
     285             :   // All the real work is done in the constructor for the CallGraph.
     286        4644 :   G.reset(new CallGraph(M));
     287        4644 :   return false;
     288             : }
     289             : 
     290       54190 : INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
     291             :                 false, true)
     292             : 
     293             : char CallGraphWrapperPass::ID = 0;
     294             : 
     295        4645 : void CallGraphWrapperPass::releaseMemory() { G.reset(); }
     296             : 
     297           5 : void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
     298          10 :   if (!G) {
     299           0 :     OS << "No call graph has been built!\n";
     300           0 :     return;
     301             :   }
     302             : 
     303             :   // Just delegate.
     304          10 :   G->print(OS);
     305             : }
     306             : 
     307             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     308             : void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
     309             : #endif

Generated by: LCOV version 1.11