-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallGraphExtractor.cpp
More file actions
80 lines (64 loc) · 2.35 KB
/
Copy pathCallGraphExtractor.cpp
File metadata and controls
80 lines (64 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "llvm/Support/CommandLine.h"
#include <set>
#include <map>
#include <iostream>
using namespace clang;
using namespace clang::tooling;
using namespace clang::ast_matchers;
std::map<std::string, std::set<std::string>> callGraph;
class FunctionCallGraphVisitor : public RecursiveASTVisitor<FunctionCallGraphVisitor> {
public:
explicit FunctionCallGraphVisitor(ASTContext *Context) : Context(Context) {}
bool VisitFunctionDecl(FunctionDecl *Func) {
if (!Func->hasBody()) return true;
currentFunc = Func->getNameAsString();
Stmt *Body = Func->getBody();
TraverseStmt(Body);
return true;
}
bool VisitCallExpr(CallExpr *Call) {
if (FunctionDecl *Callee = Call->getDirectCallee()) {
callGraph[currentFunc].insert(Callee->getNameAsString());
}
return true;
}
private:
ASTContext *Context;
std::string currentFunc;
};
class CallGraphConsumer : public ASTConsumer {
public:
explicit CallGraphConsumer(ASTContext *Context) : Visitor(Context) {}
void HandleTranslationUnit(ASTContext &Context) override {
Visitor.TraverseDecl(Context.getTranslationUnitDecl());
for (auto &[caller, callees] : callGraph) {
for (const auto &callee : callees) {
std::cout << caller << " -> " << callee << std::endl;
}
}
}
private:
FunctionCallGraphVisitor Visitor;
};
class CallGraphAction : public ASTFrontendAction {
public:
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) override {
return std::make_unique<CallGraphConsumer>(&CI.getASTContext());
}
};
static llvm::cl::OptionCategory ToolCategory("call-graph options");
int main(int argc, const char **argv) {
auto ExpectedParser = CommonOptionsParser::create(argc, argv, ToolCategory);
if (!ExpectedParser) {
llvm::errs() << ExpectedParser.takeError();
return 1;
}
ClangTool Tool(ExpectedParser->getCompilations(), ExpectedParser->getSourcePathList());
return Tool.run(newFrontendActionFactory<CallGraphAction>().get());
}