CFGBuildResult.h
2.56 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
81
82
//===- unittests/Analysis/CFGBuildResult.h - CFG tests --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Analysis/CFG.h"
#include "clang/Tooling/Tooling.h"
#include <memory>
namespace clang {
namespace analysis {
class BuildResult {
public:
enum Status {
ToolFailed,
ToolRan,
SawFunctionBody,
BuiltCFG,
};
BuildResult(Status S, const FunctionDecl *Func = nullptr,
std::unique_ptr<CFG> Cfg = nullptr,
std::unique_ptr<ASTUnit> AST = nullptr)
: S(S), Cfg(std::move(Cfg)), AST(std::move(AST)), Func(Func) {}
Status getStatus() const { return S; }
CFG *getCFG() const { return Cfg.get(); }
ASTUnit *getAST() const { return AST.get(); }
const FunctionDecl *getFunc() const { return Func; }
private:
Status S;
std::unique_ptr<CFG> Cfg;
std::unique_ptr<ASTUnit> AST;
const FunctionDecl *Func;
};
class CFGCallback : public ast_matchers::MatchFinder::MatchCallback {
public:
CFGCallback(std::unique_ptr<ASTUnit> AST) : AST(std::move(AST)) {}
std::unique_ptr<ASTUnit> AST;
BuildResult TheBuildResult = BuildResult::ToolRan;
CFG::BuildOptions Options;
void run(const ast_matchers::MatchFinder::MatchResult &Result) override {
const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func");
Stmt *Body = Func->getBody();
if (!Body)
return;
TheBuildResult = BuildResult::SawFunctionBody;
Options.AddImplicitDtors = true;
if (std::unique_ptr<CFG> Cfg =
CFG::buildCFG(nullptr, Body, Result.Context, Options))
TheBuildResult = {BuildResult::BuiltCFG, Func, std::move(Cfg),
std::move(AST)};
}
};
inline BuildResult BuildCFG(const char *Code, CFG::BuildOptions Options = {}) {
std::vector<std::string> Args = {"-std=c++11",
"-fno-delayed-template-parsing"};
std::unique_ptr<ASTUnit> AST = tooling::buildASTFromCodeWithArgs(Code, Args);
if (!AST)
return BuildResult::ToolFailed;
CFGCallback Callback(std::move(AST));
Callback.Options = Options;
ast_matchers::MatchFinder Finder;
Finder.addMatcher(ast_matchers::functionDecl().bind("func"), &Callback);
Finder.matchAST(Callback.AST->getASTContext());
return std::move(Callback.TheBuildResult);
}
} // namespace analysis
} // namespace clang