30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/IntrusiveRefCntPtr.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/Option/Arg.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/ErrorOr.h"
40#include "llvm/Support/LineIterator.h"
41#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/raw_ostream.h"
44#include "llvm/TargetParser/Host.h"
52#include <system_error>
57using namespace tooling;
63std::unique_ptr<CompilationDatabase>
65 std::string &ErrorMessage) {
66 llvm::raw_string_ostream ErrorStream(ErrorMessage);
67 for (
const CompilationDatabasePluginRegistry::entry &Database :
68 CompilationDatabasePluginRegistry::entries()) {
69 std::string DatabaseErrorMessage;
70 std::unique_ptr<CompilationDatabasePlugin> Plugin(Database.instantiate());
71 if (std::unique_ptr<CompilationDatabase> DB =
72 Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
74 ErrorStream << Database.getName() <<
": " << DatabaseErrorMessage <<
"\n";
79static std::unique_ptr<CompilationDatabase>
81 std::string &ErrorMessage) {
82 std::stringstream ErrorStream;
83 bool HasErrorMessage =
false;
84 while (!Directory.empty()) {
85 std::string LoadErrorMessage;
87 if (std::unique_ptr<CompilationDatabase> DB =
91 if (!HasErrorMessage) {
92 ErrorStream <<
"No compilation database found in " << Directory.str()
93 <<
" or any parent directory\n" << LoadErrorMessage;
94 HasErrorMessage =
true;
97 Directory = llvm::sys::path::parent_path(Directory);
99 ErrorMessage = ErrorStream.str();
103std::unique_ptr<CompilationDatabase>
105 std::string &ErrorMessage) {
107 StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
109 std::unique_ptr<CompilationDatabase> DB =
113 ErrorMessage = (
"Could not auto-detect compilation database for file \"" +
114 SourceFile +
"\"\n" + ErrorMessage).str();
118std::unique_ptr<CompilationDatabase>
120 std::string &ErrorMessage) {
123 std::unique_ptr<CompilationDatabase> DB =
127 ErrorMessage = (
"Could not auto-detect compilation database from directory \"" +
128 SourceDir +
"\"\n" + ErrorMessage).str();
133 std::vector<CompileCommand>
Result;
136 std::move(
C.begin(),
C.end(), std::back_inserter(
Result));
147struct CompileJobAnalyzer {
156 bool CollectChildren = Collect;
160 CollectChildren =
true;
165 const auto *IA = cast<driver::InputAction>(A);
166 Inputs.push_back(std::string(IA->getInputArg().getSpelling()));
176 runImpl(AI, CollectChildren);
189 if (Info.
getID() == diag::warn_drv_input_file_unused) {
195 Other.HandleDiagnostic(DiagLevel, Info);
206struct FilterUnusedFlags {
207 bool operator() (StringRef S) {
208 return (S ==
"-no-integrated-as") || S.starts_with(
"-Wa,");
212std::string GetClangToolCommand() {
214 std::string ClangExecutable =
215 llvm::sys::fs::getMainExecutable(
"clang", (
void *)&Dummy);
217 ClangToolPath = llvm::sys::path::parent_path(ClangExecutable);
218 llvm::sys::path::append(ClangToolPath,
"clang-tool");
219 return std::string(ClangToolPath);
244 std::vector<std::string> &
Result,
245 std::string &ErrorMsg) {
247 llvm::raw_string_ostream Output(ErrorMsg);
249 UnusedInputDiagConsumer DiagClient(DiagnosticPrinter);
252 &*DiagOpts, &DiagClient,
false);
257 "", llvm::sys::getDefaultTargetTriple(),
259 NewDriver->setCheckInputsExist(
false);
263 std::string Argv0 = GetClangToolCommand();
264 Args.insert(Args.begin(), Argv0.c_str());
272 Args.push_back(
"-c");
278 Args.push_back(
"placeholder.cpp");
280 llvm::erase_if(Args, FilterUnusedFlags());
282 const std::unique_ptr<driver::Compilation> Compilation(
283 NewDriver->BuildCompilation(Args));
289 CompileJobAnalyzer CompileAnalyzer;
291 for (
const auto &
Cmd : Jobs) {
299 CompileAnalyzer.run(&
Cmd.getSource());
303 if (CompileAnalyzer.Inputs.empty()) {
304 ErrorMsg =
"warning: no compile jobs found\n";
311 std::vector<const char *>::iterator End =
312 llvm::remove_if(Args, [&](StringRef S) {
313 return llvm::is_contained(CompileAnalyzer.Inputs, S) ||
314 llvm::is_contained(DiagClient.UnusedInputs, S);
317 assert(strcmp(*(End - 1),
"-c") == 0);
320 Result = std::vector<std::string>(Args.begin() + 1, End);
324std::unique_ptr<FixedCompilationDatabase>
326 const char *
const *Argv,
327 std::string &ErrorMsg,
328 const Twine &Directory) {
332 const char *
const *DoubleDash = std::find(Argv, Argv + Argc, StringRef(
"--"));
333 if (DoubleDash == Argv + Argc)
335 std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
336 Argc = DoubleDash - Argv;
338 std::vector<std::string> StrippedArgs;
341 return std::make_unique<FixedCompilationDatabase>(Directory, StrippedArgs);
344std::unique_ptr<FixedCompilationDatabase>
347 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
File =
348 llvm::MemoryBuffer::getFile(
Path);
349 if (std::error_code
Result =
File.getError()) {
350 ErrorMsg =
"Error while opening fixed database: " +
Result.message();
354 (*File)->getBuffer(), ErrorMsg);
357std::unique_ptr<FixedCompilationDatabase>
359 std::string &ErrorMsg) {
361 std::vector<std::string> Args;
363 while (!
Data.empty()) {
368 Args.push_back(
Line.str());
370 return std::make_unique<FixedCompilationDatabase>(Directory, std::move(Args));
375 std::vector<std::string> ToolCommandLine(1, GetClangToolCommand());
376 ToolCommandLine.insert(ToolCommandLine.end(),
377 CommandLine.begin(), CommandLine.end());
378 CompileCommands.emplace_back(Directory, StringRef(),
379 std::move(ToolCommandLine),
383std::vector<CompileCommand>
385 std::vector<CompileCommand>
Result(CompileCommands);
386 Result[0].CommandLine.push_back(std::string(FilePath));
387 Result[0].Filename = std::string(FilePath);
394 std::unique_ptr<CompilationDatabase>
395 loadFromDirectory(StringRef Directory, std::string &ErrorMessage)
override {
397 llvm::sys::path::append(DatabasePath,
"compile_flags.txt");
404static CompilationDatabasePluginRegistry::Add<FixedCompilationDatabasePlugin>
405X(
"fixed-compilation-database",
"Reads plain-text flags file");
Defines the Diagnostic-related interfaces.
static std::unique_ptr< CompilationDatabase > findCompilationDatabaseFromDirectory(StringRef Directory, std::string &ErrorMessage)
static bool stripPositionalArgs(std::vector< const char * > Args, std::vector< std::string > &Result, std::string &ErrorMsg)
Strips any positional args and possible argv[0] from a command-line provided by the user to construct...
Defines the Diagnostic IDs-related interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Used for handling and querying diagnostic IDs.
Options for controlling the compiler diagnostics engine.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
const std::string & getArgStdStr(unsigned Idx) const
Return the provided argument string specified by Idx.
Concrete class used by the front-end to report problems and issues.
Level
The level of the diagnostic, after it has been through mapping.
Action - Represent an abstract compilation step to perform.
ActionClass getKind() const
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
JobList - A sequence of jobs to perform.
const list_type & getJobs() const
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
@ Other
Other implicit parameter.