Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/clang-check/ClangCheck.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- tools/clang-check/ClangCheck.cpp - Clang check tool --------------===//
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 implements a clang-check tool that runs clang based on the info
10
//  stored in a compilation database.
11
//
12
//  This tool uses the Clang Tooling infrastructure, see
13
//    http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
14
//  for details on setting it up with LLVM source tree.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "clang/AST/ASTConsumer.h"
19
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
20
#include "clang/Driver/Options.h"
21
#include "clang/Frontend/ASTConsumers.h"
22
#include "clang/Frontend/CompilerInstance.h"
23
#include "clang/Rewrite/Frontend/FixItRewriter.h"
24
#include "clang/Rewrite/Frontend/FrontendActions.h"
25
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
26
#include "clang/Tooling/CommonOptionsParser.h"
27
#include "clang/Tooling/Syntax/BuildTree.h"
28
#include "clang/Tooling/Syntax/Tokens.h"
29
#include "clang/Tooling/Syntax/Tree.h"
30
#include "clang/Tooling/Tooling.h"
31
#include "llvm/ADT/STLExtras.h"
32
#include "llvm/Option/OptTable.h"
33
#include "llvm/Support/Path.h"
34
#include "llvm/Support/Signals.h"
35
#include "llvm/Support/TargetSelect.h"
36
37
using namespace clang::driver;
38
using namespace clang::tooling;
39
using namespace llvm;
40
41
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
42
static cl::extrahelp MoreHelp(
43
    "\tFor example, to run clang-check on all files in a subtree of the\n"
44
    "\tsource tree, use:\n"
45
    "\n"
46
    "\t  find path/in/subtree -name '*.cpp'|xargs clang-check\n"
47
    "\n"
48
    "\tor using a specific build path:\n"
49
    "\n"
50
    "\t  find path/in/subtree -name '*.cpp'|xargs clang-check -p build/path\n"
51
    "\n"
52
    "\tNote, that path/in/subtree and current directory should follow the\n"
53
    "\trules described above.\n"
54
    "\n"
55
);
56
57
static cl::OptionCategory ClangCheckCategory("clang-check options");
58
static const opt::OptTable &Options = getDriverOptTable();
59
static cl::opt<bool>
60
    ASTDump("ast-dump",
61
            cl::desc(Options.getOptionHelpText(options::OPT_ast_dump)),
62
            cl::cat(ClangCheckCategory));
63
static cl::opt<bool>
64
    ASTList("ast-list",
65
            cl::desc(Options.getOptionHelpText(options::OPT_ast_list)),
66
            cl::cat(ClangCheckCategory));
67
static cl::opt<bool>
68
    ASTPrint("ast-print",
69
             cl::desc(Options.getOptionHelpText(options::OPT_ast_print)),
70
             cl::cat(ClangCheckCategory));
71
static cl::opt<std::string> ASTDumpFilter(
72
    "ast-dump-filter",
73
    cl::desc(Options.getOptionHelpText(options::OPT_ast_dump_filter)),
74
    cl::cat(ClangCheckCategory));
75
static cl::opt<bool>
76
    Analyze("analyze",
77
            cl::desc(Options.getOptionHelpText(options::OPT_analyze)),
78
            cl::cat(ClangCheckCategory));
79
static cl::opt<std::string>
80
    AnalyzerOutput("analyzer-output-path",
81
                   cl::desc(Options.getOptionHelpText(options::OPT_o)),
82
                   cl::cat(ClangCheckCategory));
83
84
static cl::opt<bool>
85
    Fixit("fixit", cl::desc(Options.getOptionHelpText(options::OPT_fixit)),
86
          cl::cat(ClangCheckCategory));
87
static cl::opt<bool> FixWhatYouCan(
88
    "fix-what-you-can",
89
    cl::desc(Options.getOptionHelpText(options::OPT_fix_what_you_can)),
90
    cl::cat(ClangCheckCategory));
91
92
static cl::opt<bool> SyntaxTreeDump("syntax-tree-dump",
93
                                    cl::desc("dump the syntax tree"),
94
                                    cl::cat(ClangCheckCategory));
95
static cl::opt<bool> TokensDump("tokens-dump",
96
                                cl::desc("dump the preprocessed tokens"),
97
                                cl::cat(ClangCheckCategory));
98
99
namespace {
100
101
// FIXME: Move FixItRewriteInPlace from lib/Rewrite/Frontend/FrontendActions.cpp
102
// into a header file and reuse that.
103
class FixItOptions : public clang::FixItOptions {
104
public:
105
4
  FixItOptions() {
106
4
    FixWhatYouCan = ::FixWhatYouCan;
107
4
  }
108
109
4
  std::string RewriteFilename(const std::string& filename, int &fd) override {
110
    // We don't need to do permission checking here since clang will diagnose
111
    // any I/O errors itself.
112
113
4
    fd = -1;  // No file descriptor for file.
114
115
4
    return filename;
116
4
  }
117
};
118
119
/// Subclasses \c clang::FixItRewriter to not count fixed errors/warnings
120
/// in the final error counts.
121
///
122
/// This has the side-effect that clang-check -fixit exits with code 0 on
123
/// successfully fixing all errors.
124
class FixItRewriter : public clang::FixItRewriter {
125
public:
126
  FixItRewriter(clang::DiagnosticsEngine& Diags,
127
                clang::SourceManager& SourceMgr,
128
                const clang::LangOptions& LangOpts,
129
                clang::FixItOptions* FixItOpts)
130
4
      : clang::FixItRewriter(Diags, SourceMgr, LangOpts, FixItOpts) {
131
4
  }
132
133
12
  bool IncludeInDiagnosticCounts() const override { return false; }
134
};
135
136
/// Subclasses \c clang::FixItAction so that we can install the custom
137
/// \c FixItRewriter.
138
class ClangCheckFixItAction : public clang::FixItAction {
139
public:
140
4
  bool BeginSourceFileAction(clang::CompilerInstance& CI) override {
141
4
    FixItOpts.reset(new FixItOptions);
142
4
    Rewriter.reset(new FixItRewriter(CI.getDiagnostics(), CI.getSourceManager(),
143
4
                                     CI.getLangOpts(), FixItOpts.get()));
144
4
    return true;
145
4
  }
146
};
147
148
class DumpSyntaxTree : public clang::ASTFrontendAction {
149
public:
150
  std::unique_ptr<clang::ASTConsumer>
151
1
  CreateASTConsumer(clang::CompilerInstance &CI, StringRef InFile) override {
152
1
    class Consumer : public clang::ASTConsumer {
153
1
    public:
154
1
      Consumer(clang::CompilerInstance &CI) : Collector(CI.getPreprocessor()) {}
155
156
1
      void HandleTranslationUnit(clang::ASTContext &AST) override {
157
1
        clang::syntax::TokenBuffer TB = std::move(Collector).consume();
158
1
        if (TokensDump)
159
0
          llvm::outs() << TB.dumpForTests();
160
1
        clang::syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(), TB);
161
1
        llvm::outs() << clang::syntax::buildSyntaxTree(A, AST)->dump(
162
1
            AST.getSourceManager());
163
1
      }
164
165
1
    private:
166
1
      clang::syntax::TokenCollector Collector;
167
1
    };
168
1
    return std::make_unique<Consumer>(CI);
169
1
  }
170
};
171
172
class ClangCheckActionFactory {
173
public:
174
29
  std::unique_ptr<clang::ASTConsumer> newASTConsumer() {
175
29
    if (ASTList)
176
1
      return clang::CreateASTDeclNodeLister();
177
28
    if (ASTDump)
178
6
      return clang::CreateASTDumper(nullptr /*Dump to stdout.*/, ASTDumpFilter,
179
6
                                    /*DumpDecls=*/true,
180
6
                                    /*Deserialize=*/false,
181
6
                                    /*DumpLookups=*/false,
182
6
                                    /*DumpDeclTypes=*/false,
183
6
                                    clang::ADOF_Default);
184
22
    if (ASTPrint)
185
1
      return clang::CreateASTPrinter(nullptr, ASTDumpFilter);
186
21
    return std::make_unique<clang::ASTConsumer>();
187
22
  }
188
};
189
190
} // namespace
191
192
40
int main(int argc, const char **argv) {
193
40
  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
194
195
  // Initialize targets for clang module support.
196
40
  llvm::InitializeAllTargets();
197
40
  llvm::InitializeAllTargetMCs();
198
40
  llvm::InitializeAllAsmPrinters();
199
40
  llvm::InitializeAllAsmParsers();
200
201
40
  auto ExpectedParser =
202
40
      CommonOptionsParser::create(argc, argv, ClangCheckCategory);
203
40
  if (!ExpectedParser) {
204
0
    llvm::errs() << ExpectedParser.takeError();
205
0
    return 1;
206
0
  }
207
40
  CommonOptionsParser &OptionsParser = ExpectedParser.get();
208
40
  ClangTool Tool(OptionsParser.getCompilations(),
209
40
                 OptionsParser.getSourcePathList());
210
211
40
  if (Analyze) {
212
    // Set output path if is provided by user.
213
    //
214
    // As the original -o options have been removed by default via the
215
    // strip-output adjuster, we only need to add the analyzer -o options here
216
    // when it is provided by users.
217
7
    if (!AnalyzerOutput.empty())
218
1
      Tool.appendArgumentsAdjuster(
219
1
          getInsertArgumentAdjuster(CommandLineArguments{"-o", AnalyzerOutput},
220
1
                                    ArgumentInsertPosition::END));
221
222
    // Running the analyzer requires --analyze. Other modes can work with the
223
    // -fsyntax-only option.
224
    //
225
    // The syntax-only adjuster is installed by default.
226
    // Good: It also strips options that trigger extra output, like -save-temps.
227
    // Bad:  We don't want the -fsyntax-only when executing the static analyzer.
228
    //
229
    // To enable the static analyzer, we first strip all -fsyntax-only options
230
    // and then add an --analyze option to the front.
231
7
    Tool.appendArgumentsAdjuster(
232
7
        [&](const CommandLineArguments &Args, StringRef /*unused*/) {
233
7
          CommandLineArguments AdjustedArgs;
234
7
          for (const std::string &Arg : Args)
235
42
            if (Arg != "-fsyntax-only")
236
34
              AdjustedArgs.emplace_back(Arg);
237
7
          return AdjustedArgs;
238
7
        });
239
7
    Tool.appendArgumentsAdjuster(
240
7
        getInsertArgumentAdjuster("--analyze", ArgumentInsertPosition::BEGIN));
241
7
  }
242
243
40
  ClangCheckActionFactory CheckFactory;
244
40
  std::unique_ptr<FrontendActionFactory> FrontendFactory;
245
246
  // Choose the correct factory based on the selected mode.
247
40
  if (Analyze)
248
7
    FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
249
33
  else if (Fixit)
250
4
    FrontendFactory = newFrontendActionFactory<ClangCheckFixItAction>();
251
29
  else if (SyntaxTreeDump || 
TokensDump28
)
252
1
    FrontendFactory = newFrontendActionFactory<DumpSyntaxTree>();
253
28
  else
254
28
    FrontendFactory = newFrontendActionFactory(&CheckFactory);
255
256
40
  return Tool.run(FrontendFactory.get());
257
40
}