clang  19.0.0git
CallGraph.cpp
Go to the documentation of this file.
1 //===- CallGraph.cpp - AST-based Call graph -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the AST-based CallGraph.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/Stmt.h"
21 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/LLVM.h"
24 #include "llvm/ADT/PostOrderIterator.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/DOTGraphTraits.h"
30 #include "llvm/Support/GraphWriter.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <cassert>
33 #include <memory>
34 #include <string>
35 
36 using namespace clang;
37 
38 #define DEBUG_TYPE "CallGraph"
39 
40 STATISTIC(NumObjCCallEdges, "Number of Objective-C method call edges");
41 STATISTIC(NumBlockCallEdges, "Number of block call edges");
42 
43 namespace {
44 
45 /// A helper class, which walks the AST and locates all the call sites in the
46 /// given function body.
47 class CGBuilder : public StmtVisitor<CGBuilder> {
48  CallGraph *G;
49  CallGraphNode *CallerNode;
50 
51 public:
52  CGBuilder(CallGraph *g, CallGraphNode *N) : G(g), CallerNode(N) {}
53 
54  void VisitStmt(Stmt *S) { VisitChildren(S); }
55 
56  Decl *getDeclFromCall(CallExpr *CE) {
57  if (FunctionDecl *CalleeDecl = CE->getDirectCallee())
58  return CalleeDecl;
59 
60  // Simple detection of a call through a block.
61  Expr *CEE = CE->getCallee()->IgnoreParenImpCasts();
62  if (BlockExpr *Block = dyn_cast<BlockExpr>(CEE)) {
63  NumBlockCallEdges++;
64  return Block->getBlockDecl();
65  }
66 
67  return nullptr;
68  }
69 
70  void addCalledDecl(Decl *D, Expr *CallExpr) {
71  if (G->includeCalleeInGraph(D)) {
72  CallGraphNode *CalleeNode = G->getOrInsertNode(D);
73  CallerNode->addCallee({CalleeNode, CallExpr});
74  }
75  }
76 
77  void VisitCallExpr(CallExpr *CE) {
78  if (Decl *D = getDeclFromCall(CE))
79  addCalledDecl(D, CE);
80  VisitChildren(CE);
81  }
82 
83  void VisitLambdaExpr(LambdaExpr *LE) {
84  if (FunctionTemplateDecl *FTD = LE->getDependentCallOperator())
85  for (FunctionDecl *FD : FTD->specializations())
86  G->VisitFunctionDecl(FD);
87  else if (CXXMethodDecl *MD = LE->getCallOperator())
88  G->VisitFunctionDecl(MD);
89  }
90 
91  void VisitCXXNewExpr(CXXNewExpr *E) {
92  if (FunctionDecl *FD = E->getOperatorNew())
93  addCalledDecl(FD, E);
94  VisitChildren(E);
95  }
96 
97  void VisitCXXConstructExpr(CXXConstructExpr *E) {
99  if (FunctionDecl *Def = Ctor->getDefinition())
100  addCalledDecl(Def, E);
101  // TODO: resolve issues raised in review with llorg. See
102  // https://reviews.llvm.org/D65453?vs=on&id=212351&whitespace=ignore-most#1632207
103  const auto *ConstructedType = Ctor->getParent();
104  if (ConstructedType->hasUserDeclaredDestructor()) {
105  CXXDestructorDecl *Dtor = ConstructedType->getDestructor();
106  if (FunctionDecl *Def = Dtor->getDefinition())
107  addCalledDecl(Def, E);
108  }
109  VisitChildren(E);
110  }
111 
112  // Include the evaluation of the default argument.
113  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
114  Visit(E->getExpr());
115  }
116 
117  // Include the evaluation of the default initializers in a class.
118  void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
119  Visit(E->getExpr());
120  }
121 
122  // Adds may-call edges for the ObjC message sends.
123  void VisitObjCMessageExpr(ObjCMessageExpr *ME) {
124  if (ObjCInterfaceDecl *IDecl = ME->getReceiverInterface()) {
125  Selector Sel = ME->getSelector();
126 
127  // Find the callee definition within the same translation unit.
128  Decl *D = nullptr;
129  if (ME->isInstanceMessage())
130  D = IDecl->lookupPrivateMethod(Sel);
131  else
132  D = IDecl->lookupPrivateClassMethod(Sel);
133  if (D) {
134  addCalledDecl(D, ME);
135  NumObjCCallEdges++;
136  }
137  }
138  }
139 
140  void VisitIfStmt(IfStmt *If) {
142  if (std::optional<Stmt *> ActiveStmt =
143  If->getNondiscardedCase(G->getASTContext())) {
144  if (*ActiveStmt)
145  this->Visit(*ActiveStmt);
146  return;
147  }
148  }
149 
150  StmtVisitor::VisitIfStmt(If);
151  }
152 
153  void VisitChildren(Stmt *S) {
154  for (Stmt *SubStmt : S->children())
155  if (SubStmt)
156  this->Visit(SubStmt);
157  }
158 };
159 
160 } // namespace
161 
163  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
164  addNodeForDecl(BD, true);
165 
166  for (auto *I : D->decls())
167  if (auto *DC = dyn_cast<DeclContext>(I))
168  addNodesForBlocks(DC);
169 }
170 
172  Root = getOrInsertNode(nullptr);
173 }
174 
175 CallGraph::~CallGraph() = default;
176 
178  assert(D);
179  if (!D->hasBody())
180  return false;
181 
182  return includeCalleeInGraph(D);
183 }
184 
186  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
187  // We skip function template definitions, as their semantics is
188  // only determined when they are instantiated.
189  if (FD->isDependentContext())
190  return false;
191 
192  IdentifierInfo *II = FD->getIdentifier();
193  if (II && II->getName().starts_with("__inline"))
194  return false;
195  }
196 
197  return true;
198 }
199 
200 void CallGraph::addNodeForDecl(Decl* D, bool IsGlobal) {
201  assert(D);
202 
203  // Allocate a new node, mark it as root, and process its calls.
205 
206  // Process all the calls by this function as well.
207  CGBuilder builder(this, Node);
208  if (Stmt *Body = D->getBody())
209  builder.Visit(Body);
210 
211  // Include C++ constructor member initializers.
212  if (auto constructor = dyn_cast<CXXConstructorDecl>(D)) {
213  for (CXXCtorInitializer *init : constructor->inits()) {
214  builder.Visit(init->getInit());
215  }
216  }
217 }
218 
220  FunctionMapTy::const_iterator I = FunctionMap.find(F);
221  if (I == FunctionMap.end()) return nullptr;
222  return I->second.get();
223 }
224 
226  if (F && !isa<ObjCMethodDecl>(F))
227  F = F->getCanonicalDecl();
228 
229  std::unique_ptr<CallGraphNode> &Node = FunctionMap[F];
230  if (Node)
231  return Node.get();
232 
233  Node = std::make_unique<CallGraphNode>(F);
234  // Make Root node a parent of all functions to make sure all are reachable.
235  if (F)
236  Root->addCallee({Node.get(), /*Call=*/nullptr});
237  return Node.get();
238 }
239 
240 void CallGraph::print(raw_ostream &OS) const {
241  OS << " --- Call graph Dump --- \n";
242 
243  // We are going to print the graph in reverse post order, partially, to make
244  // sure the output is deterministic.
245  llvm::ReversePostOrderTraversal<const CallGraph *> RPOT(this);
246  for (llvm::ReversePostOrderTraversal<const CallGraph *>::rpo_iterator
247  I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
248  const CallGraphNode *N = *I;
249 
250  OS << " Function: ";
251  if (N == Root)
252  OS << "< root >";
253  else
254  N->print(OS);
255 
256  OS << " calls: ";
257  for (CallGraphNode::const_iterator CI = N->begin(),
258  CE = N->end(); CI != CE; ++CI) {
259  assert(CI->Callee != Root && "No one can call the root node.");
260  CI->Callee->print(OS);
261  OS << " ";
262  }
263  OS << '\n';
264  }
265  OS.flush();
266 }
267 
268 LLVM_DUMP_METHOD void CallGraph::dump() const {
269  print(llvm::errs());
270 }
271 
272 void CallGraph::viewGraph() const {
273  llvm::ViewGraph(this, "CallGraph");
274 }
275 
276 void CallGraphNode::print(raw_ostream &os) const {
277  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(FD))
278  return ND->printQualifiedName(os);
279  os << "< >";
280 }
281 
282 LLVM_DUMP_METHOD void CallGraphNode::dump() const {
283  print(llvm::errs());
284 }
285 
286 namespace llvm {
287 
288 template <>
289 struct DOTGraphTraits<const CallGraph*> : public DefaultDOTGraphTraits {
290  DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
291 
292  static std::string getNodeLabel(const CallGraphNode *Node,
293  const CallGraph *CG) {
294  if (CG->getRoot() == Node) {
295  return "< root >";
296  }
297  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Node->getDecl()))
298  return ND->getNameAsString();
299  else
300  return "< >";
301  }
302 };
303 
304 } // namespace llvm
Defines the clang::ASTContext interface.
DynTypedNode Node
STATISTIC(NumObjCCallEdges, "Number of Objective-C method call edges")
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4497
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6214
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1542
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1605
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1264
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1371
Expr * getExpr()
Get the initialization expression that will be used.
Definition: ExprCXX.cpp:1035
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2236
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2339
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2872
Expr * getCallee()
Definition: Expr.h:3022
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3042
void dump() const
Definition: CallGraph.cpp:282
iterator begin()
Iterators through all the callees/children of the node.
Definition: CallGraph.h:193
void print(raw_ostream &os) const
Definition: CallGraph.cpp:276
SmallVectorImpl< CallRecord >::const_iterator const_iterator
Definition: CallGraph.h:190
void addCallee(CallRecord Call)
Definition: CallGraph.h:209
The AST-based call graph.
Definition: CallGraph.h:43
ASTContext & getASTContext()
Definition: CallGraph.h:153
void viewGraph() const
Definition: CallGraph.cpp:272
CallGraphNode * getRoot() const
Get the virtual root of the graph, all the functions available externally are represented as callees ...
Definition: CallGraph.h:103
CallGraphNode * getNode(const Decl *) const
Lookup the node for the given declaration.
Definition: CallGraph.cpp:219
void dump() const
Definition: CallGraph.cpp:268
bool VisitFunctionDecl(FunctionDecl *FD)
Part of recursive declaration visitation.
Definition: CallGraph.h:119
void addNodesForBlocks(DeclContext *D)
Definition: CallGraph.cpp:162
CallGraphNode * getOrInsertNode(Decl *)
Lookup the node for the given declaration.
Definition: CallGraph.cpp:225
void print(raw_ostream &os) const
Definition: CallGraph.cpp:240
static bool includeCalleeInGraph(const Decl *D)
Determine if a declaration should be included in the graph for the purposes of being a callee.
Definition: CallGraph.cpp:185
bool shouldSkipConstantExpressions() const
Definition: CallGraph.h:148
static bool includeInGraph(const Decl *D)
Determine if a declaration should be included in the graph.
Definition: CallGraph.cpp:177
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:1077
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:1083
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
const T * get() const
Retrieve the stored node as type T.
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3111
Represents a function declaration or definition.
Definition: Decl.h:1972
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2254
Declaration of a template function.
Definition: DeclTemplate.h:957
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2138
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1950
This represents a decl that may have a name.
Definition: Decl.h:249
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
Selector getSelector() const
Definition: ExprObjC.cpp:293
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition: ExprObjC.h:1248
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
Definition: ExprObjC.cpp:314
Smart pointer class that efficiently represents Objective-C method names.
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:883
The JSON file list parser is used to communicate input to InstallAPI.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
static std::string getNodeLabel(const CallGraphNode *Node, const CallGraph *CG)
Definition: CallGraph.cpp:292