1//== CallGraph.cpp - AST-based Call graph  ----------------------*- C++ -*--==//
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//  This file defines the AST-based CallGraph.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Analysis/CallGraph.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/StmtVisitor.h"
17#include "llvm/ADT/PostOrderIterator.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Support/GraphWriter.h"
20
21using namespace clang;
22
23#define DEBUG_TYPE "CallGraph"
24
25STATISTIC(NumObjCCallEdges, "Number of Objective-C method call edges");
26STATISTIC(NumBlockCallEdges, "Number of block call edges");
27
28namespace {
29/// A helper class, which walks the AST and locates all the call sites in the
30/// given function body.
31class CGBuilder : public StmtVisitor<CGBuilder> {
32  CallGraph *G;
33  CallGraphNode *CallerNode;
34
35public:
36  CGBuilder(CallGraph *g, CallGraphNode *N)
37    : G(g), CallerNode(N) {}
38
39  void VisitStmt(Stmt *S) { VisitChildren(S); }
40
41  Decl *getDeclFromCall(CallExpr *CE) {
42    if (FunctionDecl *CalleeDecl = CE->getDirectCallee())
43      return CalleeDecl;
44
45    // Simple detection of a call through a block.
46    Expr *CEE = CE->getCallee()->IgnoreParenImpCasts();
47    if (BlockExpr *Block = dyn_cast<BlockExpr>(CEE)) {
48      NumBlockCallEdges++;
49      return Block->getBlockDecl();
50    }
51
52    return nullptr;
53  }
54
55  void addCalledDecl(Decl *D) {
56    if (G->includeInGraph(D)) {
57      CallGraphNode *CalleeNode = G->getOrInsertNode(D);
58      CallerNode->addCallee(CalleeNode, G);
59    }
60  }
61
62  void VisitCallExpr(CallExpr *CE) {
63    if (Decl *D = getDeclFromCall(CE))
64      addCalledDecl(D);
65  }
66
67  // Adds may-call edges for the ObjC message sends.
68  void VisitObjCMessageExpr(ObjCMessageExpr *ME) {
69    if (ObjCInterfaceDecl *IDecl = ME->getReceiverInterface()) {
70      Selector Sel = ME->getSelector();
71
72      // Find the callee definition within the same translation unit.
73      Decl *D = nullptr;
74      if (ME->isInstanceMessage())
75        D = IDecl->lookupPrivateMethod(Sel);
76      else
77        D = IDecl->lookupPrivateClassMethod(Sel);
78      if (D) {
79        addCalledDecl(D);
80        NumObjCCallEdges++;
81      }
82    }
83  }
84
85  void VisitChildren(Stmt *S) {
86    for (Stmt::child_range I = S->children(); I; ++I)
87      if (*I)
88        static_cast<CGBuilder*>(this)->Visit(*I);
89  }
90};
91
92} // end anonymous namespace
93
94void CallGraph::addNodesForBlocks(DeclContext *D) {
95  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
96    addNodeForDecl(BD, true);
97
98  for (auto *I : D->decls())
99    if (auto *DC = dyn_cast<DeclContext>(I))
100      addNodesForBlocks(DC);
101}
102
103CallGraph::CallGraph() {
104  Root = getOrInsertNode(nullptr);
105}
106
107CallGraph::~CallGraph() {
108  llvm::DeleteContainerSeconds(FunctionMap);
109}
110
111bool CallGraph::includeInGraph(const Decl *D) {
112  assert(D);
113  if (!D->getBody())
114    return false;
115
116  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
117    // We skip function template definitions, as their semantics is
118    // only determined when they are instantiated.
119    if (!FD->isThisDeclarationADefinition() ||
120        FD->isDependentContext())
121      return false;
122
123    IdentifierInfo *II = FD->getIdentifier();
124    if (II && II->getName().startswith("__inline"))
125      return false;
126  }
127
128  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
129    if (!ID->isThisDeclarationADefinition())
130      return false;
131  }
132
133  return true;
134}
135
136void CallGraph::addNodeForDecl(Decl* D, bool IsGlobal) {
137  assert(D);
138
139  // Allocate a new node, mark it as root, and process it's calls.
140  CallGraphNode *Node = getOrInsertNode(D);
141
142  // Process all the calls by this function as well.
143  CGBuilder builder(this, Node);
144  if (Stmt *Body = D->getBody())
145    builder.Visit(Body);
146}
147
148CallGraphNode *CallGraph::getNode(const Decl *F) const {
149  FunctionMapTy::const_iterator I = FunctionMap.find(F);
150  if (I == FunctionMap.end()) return nullptr;
151  return I->second;
152}
153
154CallGraphNode *CallGraph::getOrInsertNode(Decl *F) {
155  CallGraphNode *&Node = FunctionMap[F];
156  if (Node)
157    return Node;
158
159  Node = new CallGraphNode(F);
160  // Make Root node a parent of all functions to make sure all are reachable.
161  if (F)
162    Root->addCallee(Node, this);
163  return Node;
164}
165
166void CallGraph::print(raw_ostream &OS) const {
167  OS << " --- Call graph Dump --- \n";
168
169  // We are going to print the graph in reverse post order, partially, to make
170  // sure the output is deterministic.
171  llvm::ReversePostOrderTraversal<const clang::CallGraph*> RPOT(this);
172  for (llvm::ReversePostOrderTraversal<const clang::CallGraph*>::rpo_iterator
173         I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
174    const CallGraphNode *N = *I;
175
176    OS << "  Function: ";
177    if (N == Root)
178      OS << "< root >";
179    else
180      N->print(OS);
181
182    OS << " calls: ";
183    for (CallGraphNode::const_iterator CI = N->begin(),
184                                       CE = N->end(); CI != CE; ++CI) {
185      assert(*CI != Root && "No one can call the root node.");
186      (*CI)->print(OS);
187      OS << " ";
188    }
189    OS << '\n';
190  }
191  OS.flush();
192}
193
194void CallGraph::dump() const {
195  print(llvm::errs());
196}
197
198void CallGraph::viewGraph() const {
199  llvm::ViewGraph(this, "CallGraph");
200}
201
202void CallGraphNode::print(raw_ostream &os) const {
203  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(FD))
204      return ND->printName(os);
205  os << "< >";
206}
207
208void CallGraphNode::dump() const {
209  print(llvm::errs());
210}
211
212namespace llvm {
213
214template <>
215struct DOTGraphTraits<const CallGraph*> : public DefaultDOTGraphTraits {
216
217  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
218
219  static std::string getNodeLabel(const CallGraphNode *Node,
220                                  const CallGraph *CG) {
221    if (CG->getRoot() == Node) {
222      return "< root >";
223    }
224    if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Node->getDecl()))
225      return ND->getNameAsString();
226    else
227      return "< >";
228  }
229
230};
231}
232