blob: 3f997a9dd40c3c8815b495d4cbfea3e317cb6e13 [file] [log] [blame]
Chris Lattner41fbf302001-09-28 00:08:15 +00001//===- 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//
Chris Lattner9f9e2be2001-10-13 06:33:19 +00007// This call graph represents a dynamic method invocation as a null method node.
8// A call graph may only have up to one null method node that represents all of
9// the dynamic method invocations.
10//
Chris Lattner41fbf302001-09-28 00:08:15 +000011//===----------------------------------------------------------------------===//
12
13#include "llvm/Analysis/CallGraph.h"
14#include "llvm/Analysis/Writer.h"
15#include "llvm/Support/STLExtras.h"
16#include "llvm/Module.h"
17#include "llvm/Method.h"
18#include "llvm/iOther.h"
Chris Lattner9f9e2be2001-10-13 06:33:19 +000019#include "llvm/iTerminators.h"
Chris Lattner41fbf302001-09-28 00:08:15 +000020#include <algorithm>
21
22using namespace cfg;
23
24// getNodeFor - Return the node for the specified method or create one if it
25// does not already exist.
26//
27CallGraphNode *CallGraph::getNodeFor(Method *M) {
28 iterator I = MethodMap.find(M);
29 if (I != MethodMap.end()) return I->second;
30
31 assert(M->getParent() == Mod && "Method not in current module!");
32 CallGraphNode *New = new CallGraphNode(M);
33
34 MethodMap.insert(pair<const Method*, CallGraphNode*>(M, New));
35 return New;
36}
37
38// addToCallGraph - Add a method to the call graph, and link the node to all of
39// the methods that it calls.
40//
41void CallGraph::addToCallGraph(Method *M) {
42 CallGraphNode *Node = getNodeFor(M);
43
Chris Lattner9f9e2be2001-10-13 06:33:19 +000044 for (Method::inst_iterator I = M->inst_begin(), E = M->inst_end();
45 I != E; ++I) {
46 // Dynamic calls will cause Null nodes to be created
47 if (CallInst *CI = dyn_cast<CallInst>(*I))
Chris Lattner41fbf302001-09-28 00:08:15 +000048 Node->addCalledMethod(getNodeFor(CI->getCalledMethod()));
Chris Lattner9f9e2be2001-10-13 06:33:19 +000049 else if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
50 Node->addCalledMethod(getNodeFor(II->getCalledMethod()));
Chris Lattner41fbf302001-09-28 00:08:15 +000051 }
52}
53
54CallGraph::CallGraph(Module *TheModule) {
55 Mod = TheModule;
56
57 // Add every method to the call graph...
58 for_each(Mod->begin(), Mod->end(), bind_obj(this,&CallGraph::addToCallGraph));
59}
60
61
62void cfg::WriteToOutput(const CallGraphNode *CGN, ostream &o) {
63 o << "Call graph node for method: '" << CGN->getMethod()->getName() << "'\n";
64 for (unsigned i = 0; i < CGN->size(); ++i)
65 o << " Calls method '" << (*CGN)[i]->getMethod()->getName() << "'\n";
66 o << endl;
67}
68
69void cfg::WriteToOutput(const CallGraph &CG, ostream &o) {
70 for (CallGraph::const_iterator I = CG.begin(), E = CG.end(); I != E; ++I)
71 o << I->second;
72}