Chris Lattner | 41fbf30 | 2001-09-28 00:08:15 +0000 | [diff] [blame] | 1 | //===- CallGraph.cpp - Build a Module's call graph --------------------------=// |
| 2 | // |
| 3 | // This file implements call graph construction (from a module), and will |
| 4 | // eventually implement call graph serialization and deserialization for |
| 5 | // annotation support. |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "llvm/Analysis/CallGraph.h" |
| 10 | #include "llvm/Analysis/Writer.h" |
| 11 | #include "llvm/Support/STLExtras.h" |
| 12 | #include "llvm/Module.h" |
| 13 | #include "llvm/Method.h" |
| 14 | #include "llvm/iOther.h" |
| 15 | #include <algorithm> |
| 16 | |
| 17 | using namespace cfg; |
| 18 | |
| 19 | // getNodeFor - Return the node for the specified method or create one if it |
| 20 | // does not already exist. |
| 21 | // |
| 22 | CallGraphNode *CallGraph::getNodeFor(Method *M) { |
| 23 | iterator I = MethodMap.find(M); |
| 24 | if (I != MethodMap.end()) return I->second; |
| 25 | |
| 26 | assert(M->getParent() == Mod && "Method not in current module!"); |
| 27 | CallGraphNode *New = new CallGraphNode(M); |
| 28 | |
| 29 | MethodMap.insert(pair<const Method*, CallGraphNode*>(M, New)); |
| 30 | return New; |
| 31 | } |
| 32 | |
| 33 | // addToCallGraph - Add a method to the call graph, and link the node to all of |
| 34 | // the methods that it calls. |
| 35 | // |
| 36 | void CallGraph::addToCallGraph(Method *M) { |
| 37 | CallGraphNode *Node = getNodeFor(M); |
| 38 | |
| 39 | for (Method::inst_iterator II = M->inst_begin(), IE = M->inst_end(); |
| 40 | II != IE; ++II) { |
| 41 | if (II->getOpcode() == Instruction::Call) { |
| 42 | CallInst *CI = (CallInst*)*II; |
| 43 | Node->addCalledMethod(getNodeFor(CI->getCalledMethod())); |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | CallGraph::CallGraph(Module *TheModule) { |
| 49 | Mod = TheModule; |
| 50 | |
| 51 | // Add every method to the call graph... |
| 52 | for_each(Mod->begin(), Mod->end(), bind_obj(this,&CallGraph::addToCallGraph)); |
| 53 | } |
| 54 | |
| 55 | |
| 56 | void cfg::WriteToOutput(const CallGraphNode *CGN, ostream &o) { |
| 57 | o << "Call graph node for method: '" << CGN->getMethod()->getName() << "'\n"; |
| 58 | for (unsigned i = 0; i < CGN->size(); ++i) |
| 59 | o << " Calls method '" << (*CGN)[i]->getMethod()->getName() << "'\n"; |
| 60 | o << endl; |
| 61 | } |
| 62 | |
| 63 | void cfg::WriteToOutput(const CallGraph &CG, ostream &o) { |
| 64 | for (CallGraph::const_iterator I = CG.begin(), E = CG.end(); I != E; ++I) |
| 65 | o << I->second; |
| 66 | } |