llvm-project/clang-tools-extra/clang-tidy/ClangTidy.cpp

608 lines
24 KiB
C++
Raw Normal View History

//===--- tools/extra/clang-tidy/ClangTidy.cpp - Clang tidy tool -----------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file This file implements a clang-tidy tool.
///
/// This tool uses the Clang Tooling infrastructure, see
/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
/// for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//
#include "ClangTidy.h"
#include "ClangTidyDiagnosticConsumer.h"
#include "ClangTidyModuleRegistry.h"
#include "ClangTidyProfiling.h"
#include "ExpandModularHeadersPPCallbacks.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Config/config.h"
#include "clang/Format/Format.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/MultiplexConsumer.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Rewrite/Frontend/FixItRewriter.h"
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/Tooling/Core/Diagnostic.h"
#if CLANG_ENABLE_STATIC_ANALYZER
#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
#endif // CLANG_ENABLE_STATIC_ANALYZER
#include "clang/Tooling/DiagnosticsYaml.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/ReplacementsYaml.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include <algorithm>
#include <utility>
using namespace clang::ast_matchers;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;
Reapply r276973 "Adjust Registry interface to not require plugins to export a registry" This differs from the previous version by being more careful about template instantiation/specialization in order to prevent errors when building with clang -Werror. Specifically: * begin is not defined in the template and is instead instantiated when Head is. I think the warning when we don't do that is wrong (PR28815) but for now at least do it this way to avoid the warning. * Instead of performing template specializations in LLVM_INSTANTIATE_REGISTRY instead provide a template definition then do explicit instantiation. No compiler I've tried has problems with doing it the other way, but strictly speaking it's not permitted by the C++ standard so better safe than sorry. Original commit message: Currently the Registry class contains the vestiges of a previous attempt to allow plugins to be used on Windows without using BUILD_SHARED_LIBS, where a plugin would have its own copy of a registry and export it to be imported by the tool that's loading the plugin. This only works if the plugin is entirely self-contained with the only interface between the plugin and tool being the registry, and in particular this conflicts with how IR pass plugins work. This patch changes things so that instead the add_node function of the registry is exported by the tool and then imported by the plugin, which solves this problem and also means that instead of every plugin having to export every registry they use instead LLVM only has to export the add_node functions. This allows plugins that use a registry to work on Windows if LLVM_EXPORT_SYMBOLS_FOR_PLUGINS is used. llvm-svn: 277806
2016-08-05 19:01:08 +08:00
LLVM_INSTANTIATE_REGISTRY(clang::tidy::ClangTidyModuleRegistry)
namespace clang {
namespace tidy {
namespace {
#if CLANG_ENABLE_STATIC_ANALYZER
static const char *AnalyzerCheckNamePrefix = "clang-analyzer-";
class AnalyzerDiagnosticConsumer : public ento::PathDiagnosticConsumer {
public:
AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
FilesMade *filesMade) override {
for (const ento::PathDiagnostic *PD : Diags) {
SmallString<64> CheckName(AnalyzerCheckNamePrefix);
CheckName += PD->getCheckName();
Context.diag(CheckName, PD->getLocation().asLocation(),
PD->getShortDescription())
<< PD->path.back()->getRanges();
for (const auto &DiagPiece :
PD->path.flatten(/*ShouldFlattenMacros=*/true)) {
Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
DiagPiece->getString(), DiagnosticIDs::Note)
<< DiagPiece->getRanges();
}
}
}
StringRef getName() const override { return "ClangTidyDiags"; }
bool supportsLogicalOpControlFlow() const override { return true; }
bool supportsCrossFileDiagnostics() const override { return true; }
private:
ClangTidyContext &Context;
};
#endif // CLANG_ENABLE_STATIC_ANALYZER
class ErrorReporter {
public:
ErrorReporter(ClangTidyContext &Context, bool ApplyFixes,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)
: Files(FileSystemOptions(), BaseFS), DiagOpts(new DiagnosticOptions()),
DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts)),
Diags(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts,
DiagPrinter),
SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes),
TotalFixes(0), AppliedFixes(0), WarningsAsErrors(0) {
DiagOpts->ShowColors = llvm::sys::Process::StandardOutHasColors();
DiagPrinter->BeginSourceFile(LangOpts);
}
[clang-tidy] filter plugins and plugin arguments of the command-line Summary: This patch remove the plugin argument from the command-line. Loading plugins was making clang-tidy to fail when running over chromium (linux). Example of a command-line executed when running clang-tidy over chromium (from the compilation database). ``` ../../third_party/llvm-build/Release+Asserts/bin/clang++ -MMD -MF obj/third_party/WebKit/Source/core/fetch/webcore_shared.Resource.o.d -DV8_DEPRECATION_WARNINGS -DCLD_VERSION=2 -D_FILE_OFFSET_BITS=64 -DCHROMIUM_BUILD -DCR_CLANG_REVISION=264915-1 -DCOMPONENT_BUILD -DUI_COMPOSITOR_IMAGE_TRANSPORT -DUSE_AURA=1 -DUSE_PANGO=1 -DUSE_CAIRO=1 -DUSE_DEFAULT_RENDER_THEME=1 -DUSE_LIBJPEG_TURBO=1 -DUSE_X11=1 -DUSE_CLIPBOARD_AURAX11=1 -DENABLE_WEBRTC=1 -DENABLE_MEDIA_ROUTER=1 -DENABLE_PEPPER_CDMS -DENABLE_NOTIFICATIONS -DENABLE_TOPCHROME_MD=1 -DUSE_UDEV -DFIELDTRIAL_TESTING_ENABLED -DENABLE_TASK_MANAGER=1 -DENABLE_EXTENSIONS=1 -DENABLE_PDF=1 -DENABLE_PLUGINS=1 -DENABLE_SESSION_SERVICE=1 -DENABLE_THEMES=1 -DENABLE_AUTOFILL_DIALOG=1 -DENABLE_PRINTING=1 -DENABLE_BASIC_PRINTING=1 -DENABLE_PRINT_PREVIEW=1 -DENABLE_SPELLCHECK=1 -DENABLE_CAPTIVE_PORTAL_DETECTION=1 -DENABLE_APP_LIST=1 -DENABLE_SETTINGS_APP=1 -DENABLE_SUPERVISED_USERS=1 -DENABLE_MDNS=1 -DENABLE_SERVICE_DISCOVERY=1 -DV8_USE_EXTERNAL_STARTUP_DATA -DFULL_SAFE_BROWSING -DSAFE_BROWSING_CSD -DSAFE_BROWSING_DB_LOCAL -DBLINK_CORE_IMPLEMENTATION=1 -DBLINK_IMPLEMENTATION=1 -DINSIDE_BLINK -DGL_GLEXT_PROTOTYPES -DMOJO_USE_SYSTEM_IMPL -DCHROME_PNG_WRITE_SUPPORT -DPNG_USER_CONFIG -DENABLE_LAYOUT_UNIT_IN_INLINE_BOXES=0 -DENABLE_OILPAN=1 -DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1 -DENABLE_INPUT_MULTIPLE_FIELDS_UI=1 -DWTF_USE_ICCJPEG=1 -DWTF_USE_QCMSLIB=1 -DWTF_USE_WEBAUDIO_FFMPEG=1 -DWTF_USE_DEFAULT_RENDER_THEME=1 -DU_USING_ICU_NAMESPACE=0 -DU_ENABLE_DYLOAD=0 -DU_NOEXCEPT= -DSKIA_DLL -DGR_GL_IGNORE_ES3_MSAA=0 -DSK_SUPPORT_GPU=1 -DSK_IGNORE_LINEONLY_AA_CONVEX_PATH_OPTS -DLIBXML_STATIC -DLIBXSLT_STATIC -DV8_SHARED -DUSING_V8_SHARED -DUSE_LIBPCI=1 -DUSE_OPENSSL=1 -DUSE_GLIB=1 -DUSE_NSS_CERTS=1 -DUSE_NSS_VERIFIER=1 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DWTF_USE_DYNAMIC_ANNOTATIONS=1 -D_DEBUG -D_GLIBCXX_DEBUG=1 -Igen -I../../third_party/WebKit/Source -Igen/blink -I../../third_party/WebKit -I../../third_party/WebKit/Source/core/testing -I../../third_party/WebKit/Source/core/testing/v8 -I../.. -I../../skia/config -I../../third_party/khronos -I../../gpu -Igen/angle -I../../third_party/angle/include -I../../third_party/ffmpeg -Igen/third_party/WebKit -I../../third_party/iccjpeg -I../../third_party/libpng -I../../third_party/libwebp -I../../third_party/ots/include -I../../third_party/zlib -I../../third_party/libjpeg_turbo -I../../third_party/icu/source/i18n -I../../third_party/icu/source/common -I../../skia/ext -I../../third_party/skia/include/core -I../../third_party/skia/include/effects -I../../third_party/skia/include/pdf -I../../third_party/skia/include/gpu -I../../third_party/skia/include/lazy -I../../third_party/skia/include/pathops -I../../third_party/skia/include/pipe -I../../third_party/skia/include/ports -I../../third_party/skia/include/utils -I../../third_party/libxml/linux/include -I../../third_party/libxml/src/include -I../../third_party/libxslt -I../../third_party/npapi -I../../third_party/npapi/bindings -I../../third_party/qcms/src -I../../third_party/snappy/linux -I../../third_party/snappy/src -I../../v8/include -fstack-protector --param=ssp-buffer-size=4 -Werror -pthread -fno-strict-aliasing -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -fvisibility=hidden -pipe -fPIC -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libFindBadConstructs.so -Xclang -add-plugin -Xclang find-bad-constructs -Xclang -plugin-arg-find-bad-constructs -Xclang check-templates -Xclang -plugin-arg-find-bad-constructs -Xclang follow-macro-expansion -fcolor-diagnostics -B/home/etienneb/chromium/src/third_party/binutils/Linux_x64/Release/bin -Wheader-hygiene -Wno-char-subscripts -Wno-unneeded-internal-declaration -Wno-covered-switch-default -Wstring-conversion -Wno-c++11-narrowing -Wno-deprecated-register -Wno-inconsistent-missing-override -Wno-shift-negative-value -Wglobal-constructors -Wexit-time-destructors -fno-strict-aliasing -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libBlinkGCPlugin.so -Xclang -add-plugin -Xclang blink-gc-plugin -Xclang -plugin-arg-blink-gc-plugin -Xclang enable-oilpan -Xclang -plugin-arg-blink-gc-plugin -Xclang warn-raw-ptr -pthread -I/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot/usr/include/glib-2.0 -I/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot/usr/lib/x86_64-linux-gnu/glib-2.0/include -m64 -march=x86-64 --sysroot=/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot -O0 -g -funwind-tables -gsplit-dwarf -g0 -fno-exceptions -fno-rtti -fno-threadsafe-statics -fvisibility-inlines-hidden -std=gnu++11 -c ../../third_party/WebKit/Source/core/fetch/Resource.cpp -o obj/third_party/WebKit/Source/core/fetch/webcore_shared.Resource.o ``` The plugins are added with the following arguments: ``` -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libFindBadConstructs.so -Xclang -add-plugin -Xclang find-bad-constructs -Xclang -plugin-arg-find-bad-constructs -Xclang check-templates -Xclang -plugin-arg-find-bad-constructs -Xclang follow-macro-expansion ``` Reviewers: alexfh Subscribers: cfe-commits Differential Revision: http://reviews.llvm.org/D18806 llvm-svn: 265542
2016-04-06 22:07:51 +08:00
SourceManager &getSourceManager() { return SourceMgr; }
void reportDiagnostic(const ClangTidyError &Error) {
const tooling::DiagnosticMessage &Message = Error.Message;
SourceLocation Loc = getLocation(Message.FilePath, Message.FileOffset);
// Contains a pair for each attempted fix: location and whether the fix was
// applied successfully.
SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
{
auto Level = static_cast<DiagnosticsEngine::Level>(Error.DiagLevel);
std::string Name = Error.DiagnosticName;
if (Error.IsWarningAsError) {
Name += ",-warnings-as-errors";
Level = DiagnosticsEngine::Error;
WarningsAsErrors++;
}
auto Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level, "%0 [%1]"))
<< Message.Message << Name;
// FIXME: explore options to support interactive fix selection.
const llvm::StringMap<Replacements> *ChosenFix = selectFirstFix(Error);
if (ApplyFixes && ChosenFix) {
for (const auto &FileAndReplacements : *ChosenFix) {
for (const auto &Repl : FileAndReplacements.second) {
++TotalFixes;
bool CanBeApplied = false;
if (!Repl.isApplicable())
continue;
SourceLocation FixLoc;
SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
Files.makeAbsolutePath(FixAbsoluteFilePath);
tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
Repl.getLength(), Repl.getReplacementText());
Replacements &Replacements = FileReplacements[R.getFilePath()];
llvm::Error Err = Replacements.add(R);
if (Err) {
// FIXME: Implement better conflict handling.
llvm::errs() << "Trying to resolve conflict: "
<< llvm::toString(std::move(Err)) << "\n";
unsigned NewOffset =
Replacements.getShiftedCodePosition(R.getOffset());
unsigned NewLength = Replacements.getShiftedCodePosition(
R.getOffset() + R.getLength()) -
NewOffset;
if (NewLength == R.getLength()) {
R = Replacement(R.getFilePath(), NewOffset, NewLength,
R.getReplacementText());
Replacements = Replacements.merge(tooling::Replacements(R));
CanBeApplied = true;
++AppliedFixes;
} else {
llvm::errs()
<< "Can't resolve conflict, skipping the replacement.\n";
}
} else {
CanBeApplied = true;
++AppliedFixes;
}
FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
FixLocations.push_back(std::make_pair(FixLoc, CanBeApplied));
}
}
}
reportFix(Diag, Error.Message.Fix);
}
for (auto Fix : FixLocations) {
Diags.Report(Fix.first, Fix.second ? diag::note_fixit_applied
: diag::note_fixit_failed);
}
for (const auto &Note : Error.Notes)
reportNote(Note);
}
void Finish() {
if (ApplyFixes && TotalFixes > 0) {
Rewriter Rewrite(SourceMgr, LangOpts);
for (const auto &FileAndReplacements : FileReplacements) {
StringRef File = FileAndReplacements.first();
llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
SourceMgr.getFileManager().getBufferForFile(File);
if (!Buffer) {
llvm::errs() << "Can't get buffer for file " << File << ": "
<< Buffer.getError().message() << "\n";
// FIXME: Maybe don't apply fixes for other files as well.
continue;
}
StringRef Code = Buffer.get()->getBuffer();
auto Style = format::getStyle(
*Context.getOptionsForFile(File).FormatStyle, File, "none");
if (!Style) {
llvm::errs() << llvm::toString(Style.takeError()) << "\n";
continue;
}
llvm::Expected<tooling::Replacements> Replacements =
format::cleanupAroundReplacements(Code, FileAndReplacements.second,
*Style);
if (!Replacements) {
llvm::errs() << llvm::toString(Replacements.takeError()) << "\n";
continue;
}
if (llvm::Expected<tooling::Replacements> FormattedReplacements =
format::formatReplacements(Code, *Replacements, *Style)) {
Replacements = std::move(FormattedReplacements);
if (!Replacements)
llvm_unreachable("!Replacements");
} else {
llvm::errs() << llvm::toString(FormattedReplacements.takeError())
<< ". Skipping formatting.\n";
}
if (!tooling::applyAllReplacements(Replacements.get(), Rewrite)) {
llvm::errs() << "Can't apply replacements for file " << File << "\n";
}
}
if (Rewrite.overwriteChangedFiles()) {
llvm::errs() << "clang-tidy failed to apply suggested fixes.\n";
} else {
llvm::errs() << "clang-tidy applied " << AppliedFixes << " of "
<< TotalFixes << " suggested fixes.\n";
}
}
}
unsigned getWarningsAsErrorsCount() const { return WarningsAsErrors; }
private:
SourceLocation getLocation(StringRef FilePath, unsigned Offset) {
if (FilePath.empty())
return SourceLocation();
const FileEntry *File = SourceMgr.getFileManager().getFile(FilePath);
FileID ID = SourceMgr.getOrCreateFileID(File, SrcMgr::C_User);
return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
}
void reportFix(const DiagnosticBuilder &Diag,
const llvm::StringMap<Replacements> &Fix) {
for (const auto &FileAndReplacements : Fix) {
for (const auto &Repl : FileAndReplacements.second) {
if (!Repl.isApplicable())
continue;
SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
Files.makeAbsolutePath(FixAbsoluteFilePath);
SourceLocation FixLoc =
getLocation(FixAbsoluteFilePath, Repl.getOffset());
SourceLocation FixEndLoc = FixLoc.getLocWithOffset(Repl.getLength());
// Retrieve the source range for applicable fixes. Macro definitions
// on the command line have locations in a virtual buffer and don't
// have valid file paths and are therefore not applicable.
CharSourceRange Range =
CharSourceRange::getCharRange(SourceRange(FixLoc, FixEndLoc));
Diag << FixItHint::CreateReplacement(Range, Repl.getReplacementText());
}
}
}
void reportNote(const tooling::DiagnosticMessage &Message) {
SourceLocation Loc = getLocation(Message.FilePath, Message.FileOffset);
auto Diag =
Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note, "%0"))
<< Message.Message;
reportFix(Diag, Message.Fix);
}
FileManager Files;
LangOptions LangOpts; // FIXME: use langopts from each original file
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
DiagnosticConsumer *DiagPrinter;
DiagnosticsEngine Diags;
SourceManager SourceMgr;
llvm::StringMap<Replacements> FileReplacements;
ClangTidyContext &Context;
bool ApplyFixes;
unsigned TotalFixes;
unsigned AppliedFixes;
unsigned WarningsAsErrors;
};
class ClangTidyASTConsumer : public MultiplexConsumer {
public:
ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
std::unique_ptr<ClangTidyProfiling> Profiling,
std::unique_ptr<ast_matchers::MatchFinder> Finder,
std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
: MultiplexConsumer(std::move(Consumers)),
Profiling(std::move(Profiling)), Finder(std::move(Finder)),
Checks(std::move(Checks)) {}
private:
// Destructor order matters! Profiling must be destructed last.
// Or at least after Finder.
std::unique_ptr<ClangTidyProfiling> Profiling;
std::unique_ptr<ast_matchers::MatchFinder> Finder;
std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
};
} // namespace
ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
ClangTidyContext &Context,
IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
: Context(Context), OverlayFS(OverlayFS),
CheckFactories(new ClangTidyCheckFactories) {
for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
E = ClangTidyModuleRegistry::end();
I != E; ++I) {
std::unique_ptr<ClangTidyModule> Module(I->instantiate());
Module->addCheckFactories(*CheckFactories);
}
}
#if CLANG_ENABLE_STATIC_ANALYZER
static void setStaticAnalyzerCheckerOpts(const ClangTidyOptions &Opts,
AnalyzerOptionsRef AnalyzerOptions) {
StringRef AnalyzerPrefix(AnalyzerCheckNamePrefix);
for (const auto &Opt : Opts.CheckOptions) {
StringRef OptName(Opt.first);
if (!OptName.startswith(AnalyzerPrefix))
continue;
AnalyzerOptions->Config[OptName.substr(AnalyzerPrefix.size())] = Opt.second;
}
}
typedef std::vector<std::pair<std::string, bool>> CheckersList;
static CheckersList getCheckersControlList(ClangTidyContext &Context,
bool IncludeExperimental) {
CheckersList List;
const auto &RegisteredCheckers =
AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
bool AnalyzerChecksEnabled = false;
for (StringRef CheckName : RegisteredCheckers) {
std::string ClangTidyCheckName((AnalyzerCheckNamePrefix + CheckName).str());
AnalyzerChecksEnabled |= Context.isCheckEnabled(ClangTidyCheckName);
}
if (!AnalyzerChecksEnabled)
return List;
// List all static analyzer checkers that our filter enables.
//
// Always add all core checkers if any other static analyzer check is enabled.
// This is currently necessary, as other path sensitive checks rely on the
// core checkers.
for (StringRef CheckName : RegisteredCheckers) {
std::string ClangTidyCheckName((AnalyzerCheckNamePrefix + CheckName).str());
if (CheckName.startswith("core") ||
Context.isCheckEnabled(ClangTidyCheckName)) {
List.emplace_back(CheckName, true);
}
}
return List;
}
#endif // CLANG_ENABLE_STATIC_ANALYZER
std::unique_ptr<clang::ASTConsumer>
ClangTidyASTConsumerFactory::CreateASTConsumer(
clang::CompilerInstance &Compiler, StringRef File) {
// FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
// modify Compiler.
SourceManager *SM = &Compiler.getSourceManager();
Context.setSourceManager(SM);
Context.setCurrentFile(File);
Context.setASTContext(&Compiler.getASTContext());
auto WorkingDir = Compiler.getSourceManager()
.getFileManager()
.getVirtualFileSystem()
.getCurrentWorkingDirectory();
if (WorkingDir)
Context.setCurrentBuildDirectory(WorkingDir.get());
std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
CheckFactories->createChecks(&Context, Checks);
ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
std::unique_ptr<ClangTidyProfiling> Profiling;
if (Context.getEnableProfiling()) {
[clang-tidy] Store checks profiling info as JSON files Summary: Continuation of D46504. Example output: ``` $ clang-tidy -enable-check-profile -store-check-profile=. -checks=-*,readability-function-size source.cpp $ # Note that there won't be timings table printed to the console. $ cat *.json { "file": "/path/to/source.cpp", "timestamp": "2018-05-16 16:13:18.717446360", "profile": { "time.clang-tidy.readability-function-size.wall": 1.0421266555786133e+00, "time.clang-tidy.readability-function-size.user": 9.2088400000005421e-01, "time.clang-tidy.readability-function-size.sys": 1.2418899999999974e-01 } } ``` There are two arguments that control profile storage: * `-store-check-profile=<prefix>` By default reports are printed in tabulated format to stderr. When this option is passed, these per-TU profiles are instead stored as JSON. If the prefix is not an absolute path, it is considered to be relative to the directory from where you have run :program:`clang-tidy`. All `.` and `..` patterns in the path are collapsed, and symlinks are resolved. Example: Let's suppose you have a source file named `example.cpp`, located in `/source` directory. * If you specify `-store-check-profile=/tmp`, then the profile will be saved to `/tmp/<timestamp>-example.cpp.json` * If you run :program:`clang-tidy` from within `/foo` directory, and specify `-store-check-profile=.`, then the profile will still be saved to `/foo/<timestamp>-example.cpp.json` Reviewers: alexfh, sbenza, george.karpenkov, NoQ, aaron.ballman Reviewed By: alexfh, george.karpenkov, aaron.ballman Subscribers: Quuxplusone, JonasToth, aaron.ballman, llvm-commits, rja, Eugene.Zelenko, xazax.hun, mgrang, cfe-commits Tags: #clang-tools-extra Differential Revision: https://reviews.llvm.org/D46602 llvm-svn: 334101
2018-06-06 23:07:51 +08:00
Profiling = llvm::make_unique<ClangTidyProfiling>(
Context.getProfileStorageParams());
FinderOptions.CheckProfiling.emplace(Profiling->Records);
}
std::unique_ptr<ast_matchers::MatchFinder> Finder(
new ast_matchers::MatchFinder(std::move(FinderOptions)));
Preprocessor *PP = &Compiler.getPreprocessor();
Preprocessor *ModuleExpanderPP = PP;
if (Context.getLangOpts().Modules && OverlayFS != nullptr) {
auto ModuleExpander = llvm::make_unique<ExpandModularHeadersPPCallbacks>(
&Compiler, OverlayFS);
ModuleExpanderPP = ModuleExpander->getPreprocessor();
PP->addPPCallbacks(std::move(ModuleExpander));
}
for (auto &Check : Checks) {
Check->registerMatchers(&*Finder);
Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
}
std::vector<std::unique_ptr<ASTConsumer>> Consumers;
if (!Checks.empty())
Consumers.push_back(Finder->newASTConsumer());
#if CLANG_ENABLE_STATIC_ANALYZER
AnalyzerOptionsRef AnalyzerOptions = Compiler.getAnalyzerOpts();
AnalyzerOptions->CheckersControlList =
getCheckersControlList(Context, Context.canEnableAnalyzerAlphaCheckers());
if (!AnalyzerOptions->CheckersControlList.empty()) {
setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
AnalyzerOptions->AnalysisStoreOpt = RegionStoreModel;
AnalyzerOptions->AnalysisDiagOpt = PD_NONE;
AnalyzerOptions->AnalyzeNestedBlocks = true;
AnalyzerOptions->eagerlyAssumeBinOpBifurcation = true;
std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
ento::CreateAnalysisConsumer(Compiler);
AnalysisConsumer->AddDiagnosticConsumer(
new AnalyzerDiagnosticConsumer(Context));
Consumers.push_back(std::move(AnalysisConsumer));
}
#endif // CLANG_ENABLE_STATIC_ANALYZER
return llvm::make_unique<ClangTidyASTConsumer>(
std::move(Consumers), std::move(Profiling), std::move(Finder),
std::move(Checks));
}
std::vector<std::string> ClangTidyASTConsumerFactory::getCheckNames() {
std::vector<std::string> CheckNames;
for (const auto &CheckFactory : *CheckFactories) {
if (Context.isCheckEnabled(CheckFactory.first))
CheckNames.push_back(CheckFactory.first);
}
#if CLANG_ENABLE_STATIC_ANALYZER
for (const auto &AnalyzerCheck : getCheckersControlList(
Context, Context.canEnableAnalyzerAlphaCheckers()))
CheckNames.push_back(AnalyzerCheckNamePrefix + AnalyzerCheck.first);
#endif // CLANG_ENABLE_STATIC_ANALYZER
std::sort(CheckNames.begin(), CheckNames.end());
return CheckNames;
}
ClangTidyOptions::OptionMap ClangTidyASTConsumerFactory::getCheckOptions() {
ClangTidyOptions::OptionMap Options;
std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
CheckFactories->createChecks(&Context, Checks);
for (const auto &Check : Checks)
Check->storeOptions(Options);
return Options;
}
std::vector<std::string>
getCheckNames(const ClangTidyOptions &Options,
bool AllowEnablingAnalyzerAlphaCheckers) {
clang::tidy::ClangTidyContext Context(
llvm::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(),
Options),
AllowEnablingAnalyzerAlphaCheckers);
ClangTidyASTConsumerFactory Factory(Context);
return Factory.getCheckNames();
}
ClangTidyOptions::OptionMap
getCheckOptions(const ClangTidyOptions &Options,
bool AllowEnablingAnalyzerAlphaCheckers) {
clang::tidy::ClangTidyContext Context(
llvm::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(),
Options),
AllowEnablingAnalyzerAlphaCheckers);
ClangTidyASTConsumerFactory Factory(Context);
return Factory.getCheckOptions();
}
std::vector<ClangTidyError>
runClangTidy(clang::tidy::ClangTidyContext &Context,
const CompilationDatabase &Compilations,
ArrayRef<std::string> InputFiles,
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
bool EnableCheckProfile, llvm::StringRef StoreCheckProfile) {
ClangTool Tool(Compilations, InputFiles,
std::make_shared<PCHContainerOperations>(), BaseFS);
[clang-tidy] filter plugins and plugin arguments of the command-line Summary: This patch remove the plugin argument from the command-line. Loading plugins was making clang-tidy to fail when running over chromium (linux). Example of a command-line executed when running clang-tidy over chromium (from the compilation database). ``` ../../third_party/llvm-build/Release+Asserts/bin/clang++ -MMD -MF obj/third_party/WebKit/Source/core/fetch/webcore_shared.Resource.o.d -DV8_DEPRECATION_WARNINGS -DCLD_VERSION=2 -D_FILE_OFFSET_BITS=64 -DCHROMIUM_BUILD -DCR_CLANG_REVISION=264915-1 -DCOMPONENT_BUILD -DUI_COMPOSITOR_IMAGE_TRANSPORT -DUSE_AURA=1 -DUSE_PANGO=1 -DUSE_CAIRO=1 -DUSE_DEFAULT_RENDER_THEME=1 -DUSE_LIBJPEG_TURBO=1 -DUSE_X11=1 -DUSE_CLIPBOARD_AURAX11=1 -DENABLE_WEBRTC=1 -DENABLE_MEDIA_ROUTER=1 -DENABLE_PEPPER_CDMS -DENABLE_NOTIFICATIONS -DENABLE_TOPCHROME_MD=1 -DUSE_UDEV -DFIELDTRIAL_TESTING_ENABLED -DENABLE_TASK_MANAGER=1 -DENABLE_EXTENSIONS=1 -DENABLE_PDF=1 -DENABLE_PLUGINS=1 -DENABLE_SESSION_SERVICE=1 -DENABLE_THEMES=1 -DENABLE_AUTOFILL_DIALOG=1 -DENABLE_PRINTING=1 -DENABLE_BASIC_PRINTING=1 -DENABLE_PRINT_PREVIEW=1 -DENABLE_SPELLCHECK=1 -DENABLE_CAPTIVE_PORTAL_DETECTION=1 -DENABLE_APP_LIST=1 -DENABLE_SETTINGS_APP=1 -DENABLE_SUPERVISED_USERS=1 -DENABLE_MDNS=1 -DENABLE_SERVICE_DISCOVERY=1 -DV8_USE_EXTERNAL_STARTUP_DATA -DFULL_SAFE_BROWSING -DSAFE_BROWSING_CSD -DSAFE_BROWSING_DB_LOCAL -DBLINK_CORE_IMPLEMENTATION=1 -DBLINK_IMPLEMENTATION=1 -DINSIDE_BLINK -DGL_GLEXT_PROTOTYPES -DMOJO_USE_SYSTEM_IMPL -DCHROME_PNG_WRITE_SUPPORT -DPNG_USER_CONFIG -DENABLE_LAYOUT_UNIT_IN_INLINE_BOXES=0 -DENABLE_OILPAN=1 -DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1 -DENABLE_INPUT_MULTIPLE_FIELDS_UI=1 -DWTF_USE_ICCJPEG=1 -DWTF_USE_QCMSLIB=1 -DWTF_USE_WEBAUDIO_FFMPEG=1 -DWTF_USE_DEFAULT_RENDER_THEME=1 -DU_USING_ICU_NAMESPACE=0 -DU_ENABLE_DYLOAD=0 -DU_NOEXCEPT= -DSKIA_DLL -DGR_GL_IGNORE_ES3_MSAA=0 -DSK_SUPPORT_GPU=1 -DSK_IGNORE_LINEONLY_AA_CONVEX_PATH_OPTS -DLIBXML_STATIC -DLIBXSLT_STATIC -DV8_SHARED -DUSING_V8_SHARED -DUSE_LIBPCI=1 -DUSE_OPENSSL=1 -DUSE_GLIB=1 -DUSE_NSS_CERTS=1 -DUSE_NSS_VERIFIER=1 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DWTF_USE_DYNAMIC_ANNOTATIONS=1 -D_DEBUG -D_GLIBCXX_DEBUG=1 -Igen -I../../third_party/WebKit/Source -Igen/blink -I../../third_party/WebKit -I../../third_party/WebKit/Source/core/testing -I../../third_party/WebKit/Source/core/testing/v8 -I../.. -I../../skia/config -I../../third_party/khronos -I../../gpu -Igen/angle -I../../third_party/angle/include -I../../third_party/ffmpeg -Igen/third_party/WebKit -I../../third_party/iccjpeg -I../../third_party/libpng -I../../third_party/libwebp -I../../third_party/ots/include -I../../third_party/zlib -I../../third_party/libjpeg_turbo -I../../third_party/icu/source/i18n -I../../third_party/icu/source/common -I../../skia/ext -I../../third_party/skia/include/core -I../../third_party/skia/include/effects -I../../third_party/skia/include/pdf -I../../third_party/skia/include/gpu -I../../third_party/skia/include/lazy -I../../third_party/skia/include/pathops -I../../third_party/skia/include/pipe -I../../third_party/skia/include/ports -I../../third_party/skia/include/utils -I../../third_party/libxml/linux/include -I../../third_party/libxml/src/include -I../../third_party/libxslt -I../../third_party/npapi -I../../third_party/npapi/bindings -I../../third_party/qcms/src -I../../third_party/snappy/linux -I../../third_party/snappy/src -I../../v8/include -fstack-protector --param=ssp-buffer-size=4 -Werror -pthread -fno-strict-aliasing -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -fvisibility=hidden -pipe -fPIC -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libFindBadConstructs.so -Xclang -add-plugin -Xclang find-bad-constructs -Xclang -plugin-arg-find-bad-constructs -Xclang check-templates -Xclang -plugin-arg-find-bad-constructs -Xclang follow-macro-expansion -fcolor-diagnostics -B/home/etienneb/chromium/src/third_party/binutils/Linux_x64/Release/bin -Wheader-hygiene -Wno-char-subscripts -Wno-unneeded-internal-declaration -Wno-covered-switch-default -Wstring-conversion -Wno-c++11-narrowing -Wno-deprecated-register -Wno-inconsistent-missing-override -Wno-shift-negative-value -Wglobal-constructors -Wexit-time-destructors -fno-strict-aliasing -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libBlinkGCPlugin.so -Xclang -add-plugin -Xclang blink-gc-plugin -Xclang -plugin-arg-blink-gc-plugin -Xclang enable-oilpan -Xclang -plugin-arg-blink-gc-plugin -Xclang warn-raw-ptr -pthread -I/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot/usr/include/glib-2.0 -I/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot/usr/lib/x86_64-linux-gnu/glib-2.0/include -m64 -march=x86-64 --sysroot=/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot -O0 -g -funwind-tables -gsplit-dwarf -g0 -fno-exceptions -fno-rtti -fno-threadsafe-statics -fvisibility-inlines-hidden -std=gnu++11 -c ../../third_party/WebKit/Source/core/fetch/Resource.cpp -o obj/third_party/WebKit/Source/core/fetch/webcore_shared.Resource.o ``` The plugins are added with the following arguments: ``` -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libFindBadConstructs.so -Xclang -add-plugin -Xclang find-bad-constructs -Xclang -plugin-arg-find-bad-constructs -Xclang check-templates -Xclang -plugin-arg-find-bad-constructs -Xclang follow-macro-expansion ``` Reviewers: alexfh Subscribers: cfe-commits Differential Revision: http://reviews.llvm.org/D18806 llvm-svn: 265542
2016-04-06 22:07:51 +08:00
// Add extra arguments passed by the clang-tidy command-line.
ArgumentsAdjuster PerFileExtraArgumentsInserter =
[&Context](const CommandLineArguments &Args, StringRef Filename) {
ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
CommandLineArguments AdjustedArgs = Args;
if (Opts.ExtraArgsBefore) {
auto I = AdjustedArgs.begin();
if (I != AdjustedArgs.end() && !StringRef(*I).startswith("-"))
++I; // Skip compiler binary name, if it is there.
AdjustedArgs.insert(I, Opts.ExtraArgsBefore->begin(),
Opts.ExtraArgsBefore->end());
}
[clang-tidy] filter plugins and plugin arguments of the command-line Summary: This patch remove the plugin argument from the command-line. Loading plugins was making clang-tidy to fail when running over chromium (linux). Example of a command-line executed when running clang-tidy over chromium (from the compilation database). ``` ../../third_party/llvm-build/Release+Asserts/bin/clang++ -MMD -MF obj/third_party/WebKit/Source/core/fetch/webcore_shared.Resource.o.d -DV8_DEPRECATION_WARNINGS -DCLD_VERSION=2 -D_FILE_OFFSET_BITS=64 -DCHROMIUM_BUILD -DCR_CLANG_REVISION=264915-1 -DCOMPONENT_BUILD -DUI_COMPOSITOR_IMAGE_TRANSPORT -DUSE_AURA=1 -DUSE_PANGO=1 -DUSE_CAIRO=1 -DUSE_DEFAULT_RENDER_THEME=1 -DUSE_LIBJPEG_TURBO=1 -DUSE_X11=1 -DUSE_CLIPBOARD_AURAX11=1 -DENABLE_WEBRTC=1 -DENABLE_MEDIA_ROUTER=1 -DENABLE_PEPPER_CDMS -DENABLE_NOTIFICATIONS -DENABLE_TOPCHROME_MD=1 -DUSE_UDEV -DFIELDTRIAL_TESTING_ENABLED -DENABLE_TASK_MANAGER=1 -DENABLE_EXTENSIONS=1 -DENABLE_PDF=1 -DENABLE_PLUGINS=1 -DENABLE_SESSION_SERVICE=1 -DENABLE_THEMES=1 -DENABLE_AUTOFILL_DIALOG=1 -DENABLE_PRINTING=1 -DENABLE_BASIC_PRINTING=1 -DENABLE_PRINT_PREVIEW=1 -DENABLE_SPELLCHECK=1 -DENABLE_CAPTIVE_PORTAL_DETECTION=1 -DENABLE_APP_LIST=1 -DENABLE_SETTINGS_APP=1 -DENABLE_SUPERVISED_USERS=1 -DENABLE_MDNS=1 -DENABLE_SERVICE_DISCOVERY=1 -DV8_USE_EXTERNAL_STARTUP_DATA -DFULL_SAFE_BROWSING -DSAFE_BROWSING_CSD -DSAFE_BROWSING_DB_LOCAL -DBLINK_CORE_IMPLEMENTATION=1 -DBLINK_IMPLEMENTATION=1 -DINSIDE_BLINK -DGL_GLEXT_PROTOTYPES -DMOJO_USE_SYSTEM_IMPL -DCHROME_PNG_WRITE_SUPPORT -DPNG_USER_CONFIG -DENABLE_LAYOUT_UNIT_IN_INLINE_BOXES=0 -DENABLE_OILPAN=1 -DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1 -DENABLE_INPUT_MULTIPLE_FIELDS_UI=1 -DWTF_USE_ICCJPEG=1 -DWTF_USE_QCMSLIB=1 -DWTF_USE_WEBAUDIO_FFMPEG=1 -DWTF_USE_DEFAULT_RENDER_THEME=1 -DU_USING_ICU_NAMESPACE=0 -DU_ENABLE_DYLOAD=0 -DU_NOEXCEPT= -DSKIA_DLL -DGR_GL_IGNORE_ES3_MSAA=0 -DSK_SUPPORT_GPU=1 -DSK_IGNORE_LINEONLY_AA_CONVEX_PATH_OPTS -DLIBXML_STATIC -DLIBXSLT_STATIC -DV8_SHARED -DUSING_V8_SHARED -DUSE_LIBPCI=1 -DUSE_OPENSSL=1 -DUSE_GLIB=1 -DUSE_NSS_CERTS=1 -DUSE_NSS_VERIFIER=1 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DWTF_USE_DYNAMIC_ANNOTATIONS=1 -D_DEBUG -D_GLIBCXX_DEBUG=1 -Igen -I../../third_party/WebKit/Source -Igen/blink -I../../third_party/WebKit -I../../third_party/WebKit/Source/core/testing -I../../third_party/WebKit/Source/core/testing/v8 -I../.. -I../../skia/config -I../../third_party/khronos -I../../gpu -Igen/angle -I../../third_party/angle/include -I../../third_party/ffmpeg -Igen/third_party/WebKit -I../../third_party/iccjpeg -I../../third_party/libpng -I../../third_party/libwebp -I../../third_party/ots/include -I../../third_party/zlib -I../../third_party/libjpeg_turbo -I../../third_party/icu/source/i18n -I../../third_party/icu/source/common -I../../skia/ext -I../../third_party/skia/include/core -I../../third_party/skia/include/effects -I../../third_party/skia/include/pdf -I../../third_party/skia/include/gpu -I../../third_party/skia/include/lazy -I../../third_party/skia/include/pathops -I../../third_party/skia/include/pipe -I../../third_party/skia/include/ports -I../../third_party/skia/include/utils -I../../third_party/libxml/linux/include -I../../third_party/libxml/src/include -I../../third_party/libxslt -I../../third_party/npapi -I../../third_party/npapi/bindings -I../../third_party/qcms/src -I../../third_party/snappy/linux -I../../third_party/snappy/src -I../../v8/include -fstack-protector --param=ssp-buffer-size=4 -Werror -pthread -fno-strict-aliasing -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -fvisibility=hidden -pipe -fPIC -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libFindBadConstructs.so -Xclang -add-plugin -Xclang find-bad-constructs -Xclang -plugin-arg-find-bad-constructs -Xclang check-templates -Xclang -plugin-arg-find-bad-constructs -Xclang follow-macro-expansion -fcolor-diagnostics -B/home/etienneb/chromium/src/third_party/binutils/Linux_x64/Release/bin -Wheader-hygiene -Wno-char-subscripts -Wno-unneeded-internal-declaration -Wno-covered-switch-default -Wstring-conversion -Wno-c++11-narrowing -Wno-deprecated-register -Wno-inconsistent-missing-override -Wno-shift-negative-value -Wglobal-constructors -Wexit-time-destructors -fno-strict-aliasing -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libBlinkGCPlugin.so -Xclang -add-plugin -Xclang blink-gc-plugin -Xclang -plugin-arg-blink-gc-plugin -Xclang enable-oilpan -Xclang -plugin-arg-blink-gc-plugin -Xclang warn-raw-ptr -pthread -I/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot/usr/include/glib-2.0 -I/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot/usr/lib/x86_64-linux-gnu/glib-2.0/include -m64 -march=x86-64 --sysroot=/home/etienneb/chromium/src/build/linux/debian_wheezy_amd64-sysroot -O0 -g -funwind-tables -gsplit-dwarf -g0 -fno-exceptions -fno-rtti -fno-threadsafe-statics -fvisibility-inlines-hidden -std=gnu++11 -c ../../third_party/WebKit/Source/core/fetch/Resource.cpp -o obj/third_party/WebKit/Source/core/fetch/webcore_shared.Resource.o ``` The plugins are added with the following arguments: ``` -Xclang -load -Xclang /home/etienneb/chromium/src/third_party/llvm-build/Release+Asserts/lib/libFindBadConstructs.so -Xclang -add-plugin -Xclang find-bad-constructs -Xclang -plugin-arg-find-bad-constructs -Xclang check-templates -Xclang -plugin-arg-find-bad-constructs -Xclang follow-macro-expansion ``` Reviewers: alexfh Subscribers: cfe-commits Differential Revision: http://reviews.llvm.org/D18806 llvm-svn: 265542
2016-04-06 22:07:51 +08:00
if (Opts.ExtraArgs)
AdjustedArgs.insert(AdjustedArgs.end(), Opts.ExtraArgs->begin(),
Opts.ExtraArgs->end());
return AdjustedArgs;
};
Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
Context.setEnableProfiling(EnableCheckProfile);
[clang-tidy] Store checks profiling info as JSON files Summary: Continuation of D46504. Example output: ``` $ clang-tidy -enable-check-profile -store-check-profile=. -checks=-*,readability-function-size source.cpp $ # Note that there won't be timings table printed to the console. $ cat *.json { "file": "/path/to/source.cpp", "timestamp": "2018-05-16 16:13:18.717446360", "profile": { "time.clang-tidy.readability-function-size.wall": 1.0421266555786133e+00, "time.clang-tidy.readability-function-size.user": 9.2088400000005421e-01, "time.clang-tidy.readability-function-size.sys": 1.2418899999999974e-01 } } ``` There are two arguments that control profile storage: * `-store-check-profile=<prefix>` By default reports are printed in tabulated format to stderr. When this option is passed, these per-TU profiles are instead stored as JSON. If the prefix is not an absolute path, it is considered to be relative to the directory from where you have run :program:`clang-tidy`. All `.` and `..` patterns in the path are collapsed, and symlinks are resolved. Example: Let's suppose you have a source file named `example.cpp`, located in `/source` directory. * If you specify `-store-check-profile=/tmp`, then the profile will be saved to `/tmp/<timestamp>-example.cpp.json` * If you run :program:`clang-tidy` from within `/foo` directory, and specify `-store-check-profile=.`, then the profile will still be saved to `/foo/<timestamp>-example.cpp.json` Reviewers: alexfh, sbenza, george.karpenkov, NoQ, aaron.ballman Reviewed By: alexfh, george.karpenkov, aaron.ballman Subscribers: Quuxplusone, JonasToth, aaron.ballman, llvm-commits, rja, Eugene.Zelenko, xazax.hun, mgrang, cfe-commits Tags: #clang-tools-extra Differential Revision: https://reviews.llvm.org/D46602 llvm-svn: 334101
2018-06-06 23:07:51 +08:00
Context.setProfileStoragePrefix(StoreCheckProfile);
ClangTidyDiagnosticConsumer DiagConsumer(Context);
DiagnosticsEngine DE(new DiagnosticIDs(), new DiagnosticOptions(),
&DiagConsumer, /*ShouldOwnClient=*/false);
Context.setDiagnosticsEngine(&DE);
Tool.setDiagnosticConsumer(&DiagConsumer);
class ActionFactory : public FrontendActionFactory {
public:
ActionFactory(ClangTidyContext &Context,
IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS)
: ConsumerFactory(Context, BaseFS) {}
FrontendAction *create() override { return new Action(&ConsumerFactory); }
bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
FileManager *Files,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
DiagnosticConsumer *DiagConsumer) override {
// Explicitly set ProgramAction to RunAnalysis to make the preprocessor
// define __clang_analyzer__ macro. The frontend analyzer action will not
// be called here.
Invocation->getFrontendOpts().ProgramAction = frontend::RunAnalysis;
return FrontendActionFactory::runInvocation(
Invocation, Files, PCHContainerOps, DiagConsumer);
}
private:
class Action : public ASTFrontendAction {
public:
Action(ClangTidyASTConsumerFactory *Factory) : Factory(Factory) {}
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
StringRef File) override {
return Factory->CreateASTConsumer(Compiler, File);
}
private:
ClangTidyASTConsumerFactory *Factory;
};
ClangTidyASTConsumerFactory ConsumerFactory;
};
ActionFactory Factory(Context, BaseFS);
Tool.run(&Factory);
return DiagConsumer.take();
}
void handleErrors(llvm::ArrayRef<ClangTidyError> Errors,
ClangTidyContext &Context, bool Fix,
unsigned &WarningsAsErrorsCount,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
ErrorReporter Reporter(Context, Fix, BaseFS);
llvm::vfs::FileSystem &FileSystem =
Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
if (!InitialWorkingDir)
llvm::report_fatal_error("Cannot get current working path.");
for (const ClangTidyError &Error : Errors) {
if (!Error.BuildDirectory.empty()) {
// By default, the working directory of file system is the current
// clang-tidy running directory.
//
// Change the directory to the one used during the analysis.
FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
}
Reporter.reportDiagnostic(Error);
// Return to the initial directory to correctly resolve next Error.
FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
}
Reporter.Finish();
WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
}
void exportReplacements(const llvm::StringRef MainFilePath,
const std::vector<ClangTidyError> &Errors,
raw_ostream &OS) {
TranslationUnitDiagnostics TUD;
TUD.MainSourceFile = MainFilePath;
for (const auto &Error : Errors) {
tooling::Diagnostic Diag = Error;
TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
}
yaml::Output YAML(OS);
YAML << TUD;
}
} // namespace tidy
} // namespace clang