CompilationDatabase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. //===- CompilationDatabase.cpp --------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains implementations of the CompilationDatabase base class
  11. // and the FixedCompilationDatabase.
  12. //
  13. // FIXME: Various functions that take a string &ErrorMessage should be upgraded
  14. // to Expected.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/Tooling/CompilationDatabase.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/DiagnosticIDs.h"
  20. #include "clang/Basic/DiagnosticOptions.h"
  21. #include "clang/Basic/LLVM.h"
  22. #include "clang/Driver/Action.h"
  23. #include "clang/Driver/Compilation.h"
  24. #include "clang/Driver/Driver.h"
  25. #include "clang/Driver/DriverDiagnostic.h"
  26. #include "clang/Driver/Job.h"
  27. #include "clang/Frontend/TextDiagnosticPrinter.h"
  28. #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
  29. #include "clang/Tooling/Tooling.h"
  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/Host.h"
  41. #include "llvm/Support/LineIterator.h"
  42. #include "llvm/Support/MemoryBuffer.h"
  43. #include "llvm/Support/Path.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include <algorithm>
  46. #include <cassert>
  47. #include <cstring>
  48. #include <iterator>
  49. #include <memory>
  50. #include <sstream>
  51. #include <string>
  52. #include <system_error>
  53. #include <utility>
  54. #include <vector>
  55. using namespace clang;
  56. using namespace tooling;
  57. LLVM_INSTANTIATE_REGISTRY(CompilationDatabasePluginRegistry)
  58. CompilationDatabase::~CompilationDatabase() = default;
  59. std::unique_ptr<CompilationDatabase>
  60. CompilationDatabase::loadFromDirectory(StringRef BuildDirectory,
  61. std::string &ErrorMessage) {
  62. llvm::raw_string_ostream ErrorStream(ErrorMessage);
  63. for (CompilationDatabasePluginRegistry::iterator
  64. It = CompilationDatabasePluginRegistry::begin(),
  65. Ie = CompilationDatabasePluginRegistry::end();
  66. It != Ie; ++It) {
  67. std::string DatabaseErrorMessage;
  68. std::unique_ptr<CompilationDatabasePlugin> Plugin(It->instantiate());
  69. if (std::unique_ptr<CompilationDatabase> DB =
  70. Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
  71. return DB;
  72. ErrorStream << It->getName() << ": " << DatabaseErrorMessage << "\n";
  73. }
  74. return nullptr;
  75. }
  76. static std::unique_ptr<CompilationDatabase>
  77. findCompilationDatabaseFromDirectory(StringRef Directory,
  78. std::string &ErrorMessage) {
  79. std::stringstream ErrorStream;
  80. bool HasErrorMessage = false;
  81. while (!Directory.empty()) {
  82. std::string LoadErrorMessage;
  83. if (std::unique_ptr<CompilationDatabase> DB =
  84. CompilationDatabase::loadFromDirectory(Directory, LoadErrorMessage))
  85. return DB;
  86. if (!HasErrorMessage) {
  87. ErrorStream << "No compilation database found in " << Directory.str()
  88. << " or any parent directory\n" << LoadErrorMessage;
  89. HasErrorMessage = true;
  90. }
  91. Directory = llvm::sys::path::parent_path(Directory);
  92. }
  93. ErrorMessage = ErrorStream.str();
  94. return nullptr;
  95. }
  96. std::unique_ptr<CompilationDatabase>
  97. CompilationDatabase::autoDetectFromSource(StringRef SourceFile,
  98. std::string &ErrorMessage) {
  99. SmallString<1024> AbsolutePath(getAbsolutePath(SourceFile));
  100. StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
  101. std::unique_ptr<CompilationDatabase> DB =
  102. findCompilationDatabaseFromDirectory(Directory, ErrorMessage);
  103. if (!DB)
  104. ErrorMessage = ("Could not auto-detect compilation database for file \"" +
  105. SourceFile + "\"\n" + ErrorMessage).str();
  106. return DB;
  107. }
  108. std::unique_ptr<CompilationDatabase>
  109. CompilationDatabase::autoDetectFromDirectory(StringRef SourceDir,
  110. std::string &ErrorMessage) {
  111. SmallString<1024> AbsolutePath(getAbsolutePath(SourceDir));
  112. std::unique_ptr<CompilationDatabase> DB =
  113. findCompilationDatabaseFromDirectory(AbsolutePath, ErrorMessage);
  114. if (!DB)
  115. ErrorMessage = ("Could not auto-detect compilation database from directory \"" +
  116. SourceDir + "\"\n" + ErrorMessage).str();
  117. return DB;
  118. }
  119. std::vector<CompileCommand> CompilationDatabase::getAllCompileCommands() const {
  120. std::vector<CompileCommand> Result;
  121. for (const auto &File : getAllFiles()) {
  122. auto C = getCompileCommands(File);
  123. std::move(C.begin(), C.end(), std::back_inserter(Result));
  124. }
  125. return Result;
  126. }
  127. CompilationDatabasePlugin::~CompilationDatabasePlugin() = default;
  128. namespace {
  129. // Helper for recursively searching through a chain of actions and collecting
  130. // all inputs, direct and indirect, of compile jobs.
  131. struct CompileJobAnalyzer {
  132. SmallVector<std::string, 2> Inputs;
  133. void run(const driver::Action *A) {
  134. runImpl(A, false);
  135. }
  136. private:
  137. void runImpl(const driver::Action *A, bool Collect) {
  138. bool CollectChildren = Collect;
  139. switch (A->getKind()) {
  140. case driver::Action::CompileJobClass:
  141. CollectChildren = true;
  142. break;
  143. case driver::Action::InputClass:
  144. if (Collect) {
  145. const auto *IA = cast<driver::InputAction>(A);
  146. Inputs.push_back(IA->getInputArg().getSpelling());
  147. }
  148. break;
  149. default:
  150. // Don't care about others
  151. break;
  152. }
  153. for (const driver::Action *AI : A->inputs())
  154. runImpl(AI, CollectChildren);
  155. }
  156. };
  157. // Special DiagnosticConsumer that looks for warn_drv_input_file_unused
  158. // diagnostics from the driver and collects the option strings for those unused
  159. // options.
  160. class UnusedInputDiagConsumer : public DiagnosticConsumer {
  161. public:
  162. UnusedInputDiagConsumer(DiagnosticConsumer &Other) : Other(Other) {}
  163. void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  164. const Diagnostic &Info) override {
  165. if (Info.getID() == diag::warn_drv_input_file_unused) {
  166. // Arg 1 for this diagnostic is the option that didn't get used.
  167. UnusedInputs.push_back(Info.getArgStdStr(0));
  168. } else if (DiagLevel >= DiagnosticsEngine::Error) {
  169. // If driver failed to create compilation object, show the diagnostics
  170. // to user.
  171. Other.HandleDiagnostic(DiagLevel, Info);
  172. }
  173. }
  174. DiagnosticConsumer &Other;
  175. SmallVector<std::string, 2> UnusedInputs;
  176. };
  177. // Unary functor for asking "Given a StringRef S1, does there exist a string
  178. // S2 in Arr where S1 == S2?"
  179. struct MatchesAny {
  180. MatchesAny(ArrayRef<std::string> Arr) : Arr(Arr) {}
  181. bool operator() (StringRef S) {
  182. for (const std::string *I = Arr.begin(), *E = Arr.end(); I != E; ++I)
  183. if (*I == S)
  184. return true;
  185. return false;
  186. }
  187. private:
  188. ArrayRef<std::string> Arr;
  189. };
  190. // Filter of tools unused flags such as -no-integrated-as and -Wa,*.
  191. // They are not used for syntax checking, and could confuse targets
  192. // which don't support these options.
  193. struct FilterUnusedFlags {
  194. bool operator() (StringRef S) {
  195. return (S == "-no-integrated-as") || S.startswith("-Wa,");
  196. }
  197. };
  198. std::string GetClangToolCommand() {
  199. static int Dummy;
  200. std::string ClangExecutable =
  201. llvm::sys::fs::getMainExecutable("clang", (void *)&Dummy);
  202. SmallString<128> ClangToolPath;
  203. ClangToolPath = llvm::sys::path::parent_path(ClangExecutable);
  204. llvm::sys::path::append(ClangToolPath, "clang-tool");
  205. return ClangToolPath.str();
  206. }
  207. } // namespace
  208. /// Strips any positional args and possible argv[0] from a command-line
  209. /// provided by the user to construct a FixedCompilationDatabase.
  210. ///
  211. /// FixedCompilationDatabase requires a command line to be in this format as it
  212. /// constructs the command line for each file by appending the name of the file
  213. /// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
  214. /// start of the command line although its value is not important as it's just
  215. /// ignored by the Driver invoked by the ClangTool using the
  216. /// FixedCompilationDatabase.
  217. ///
  218. /// FIXME: This functionality should probably be made available by
  219. /// clang::driver::Driver although what the interface should look like is not
  220. /// clear.
  221. ///
  222. /// \param[in] Args Args as provided by the user.
  223. /// \return Resulting stripped command line.
  224. /// \li true if successful.
  225. /// \li false if \c Args cannot be used for compilation jobs (e.g.
  226. /// contains an option like -E or -version).
  227. static bool stripPositionalArgs(std::vector<const char *> Args,
  228. std::vector<std::string> &Result,
  229. std::string &ErrorMsg) {
  230. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  231. llvm::raw_string_ostream Output(ErrorMsg);
  232. TextDiagnosticPrinter DiagnosticPrinter(Output, &*DiagOpts);
  233. UnusedInputDiagConsumer DiagClient(DiagnosticPrinter);
  234. DiagnosticsEngine Diagnostics(
  235. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
  236. &*DiagOpts, &DiagClient, false);
  237. // The clang executable path isn't required since the jobs the driver builds
  238. // will not be executed.
  239. std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
  240. /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
  241. Diagnostics));
  242. NewDriver->setCheckInputsExist(false);
  243. // This becomes the new argv[0]. The value is used to detect libc++ include
  244. // dirs on Mac, it isn't used for other platforms.
  245. std::string Argv0 = GetClangToolCommand();
  246. Args.insert(Args.begin(), Argv0.c_str());
  247. // By adding -c, we force the driver to treat compilation as the last phase.
  248. // It will then issue warnings via Diagnostics about un-used options that
  249. // would have been used for linking. If the user provided a compiler name as
  250. // the original argv[0], this will be treated as a linker input thanks to
  251. // insertng a new argv[0] above. All un-used options get collected by
  252. // UnusedInputdiagConsumer and get stripped out later.
  253. Args.push_back("-c");
  254. // Put a dummy C++ file on to ensure there's at least one compile job for the
  255. // driver to construct. If the user specified some other argument that
  256. // prevents compilation, e.g. -E or something like -version, we may still end
  257. // up with no jobs but then this is the user's fault.
  258. Args.push_back("placeholder.cpp");
  259. Args.erase(std::remove_if(Args.begin(), Args.end(), FilterUnusedFlags()),
  260. Args.end());
  261. const std::unique_ptr<driver::Compilation> Compilation(
  262. NewDriver->BuildCompilation(Args));
  263. if (!Compilation)
  264. return false;
  265. const driver::JobList &Jobs = Compilation->getJobs();
  266. CompileJobAnalyzer CompileAnalyzer;
  267. for (const auto &Cmd : Jobs) {
  268. // Collect only for Assemble, Backend, and Compile jobs. If we do all jobs
  269. // we get duplicates since Link jobs point to Assemble jobs as inputs.
  270. // -flto* flags make the BackendJobClass, which still needs analyzer.
  271. if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass ||
  272. Cmd.getSource().getKind() == driver::Action::BackendJobClass ||
  273. Cmd.getSource().getKind() == driver::Action::CompileJobClass) {
  274. CompileAnalyzer.run(&Cmd.getSource());
  275. }
  276. }
  277. if (CompileAnalyzer.Inputs.empty()) {
  278. ErrorMsg = "warning: no compile jobs found\n";
  279. return false;
  280. }
  281. // Remove all compilation input files from the command line. This is
  282. // necessary so that getCompileCommands() can construct a command line for
  283. // each file.
  284. std::vector<const char *>::iterator End = std::remove_if(
  285. Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs));
  286. // Remove all inputs deemed unused for compilation.
  287. End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs));
  288. // Remove the -c add above as well. It will be at the end right now.
  289. assert(strcmp(*(End - 1), "-c") == 0);
  290. --End;
  291. Result = std::vector<std::string>(Args.begin() + 1, End);
  292. return true;
  293. }
  294. std::unique_ptr<FixedCompilationDatabase>
  295. FixedCompilationDatabase::loadFromCommandLine(int &Argc,
  296. const char *const *Argv,
  297. std::string &ErrorMsg,
  298. Twine Directory) {
  299. ErrorMsg.clear();
  300. if (Argc == 0)
  301. return nullptr;
  302. const char *const *DoubleDash = std::find(Argv, Argv + Argc, StringRef("--"));
  303. if (DoubleDash == Argv + Argc)
  304. return nullptr;
  305. std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
  306. Argc = DoubleDash - Argv;
  307. std::vector<std::string> StrippedArgs;
  308. if (!stripPositionalArgs(CommandLine, StrippedArgs, ErrorMsg))
  309. return nullptr;
  310. return llvm::make_unique<FixedCompilationDatabase>(Directory, StrippedArgs);
  311. }
  312. std::unique_ptr<FixedCompilationDatabase>
  313. FixedCompilationDatabase::loadFromFile(StringRef Path, std::string &ErrorMsg) {
  314. ErrorMsg.clear();
  315. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
  316. llvm::MemoryBuffer::getFile(Path);
  317. if (std::error_code Result = File.getError()) {
  318. ErrorMsg = "Error while opening fixed database: " + Result.message();
  319. return nullptr;
  320. }
  321. std::vector<std::string> Args{llvm::line_iterator(**File),
  322. llvm::line_iterator()};
  323. return llvm::make_unique<FixedCompilationDatabase>(
  324. llvm::sys::path::parent_path(Path), std::move(Args));
  325. }
  326. FixedCompilationDatabase::
  327. FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine) {
  328. std::vector<std::string> ToolCommandLine(1, GetClangToolCommand());
  329. ToolCommandLine.insert(ToolCommandLine.end(),
  330. CommandLine.begin(), CommandLine.end());
  331. CompileCommands.emplace_back(Directory, StringRef(),
  332. std::move(ToolCommandLine),
  333. StringRef());
  334. }
  335. std::vector<CompileCommand>
  336. FixedCompilationDatabase::getCompileCommands(StringRef FilePath) const {
  337. std::vector<CompileCommand> Result(CompileCommands);
  338. Result[0].CommandLine.push_back(FilePath);
  339. Result[0].Filename = FilePath;
  340. return Result;
  341. }
  342. namespace {
  343. class FixedCompilationDatabasePlugin : public CompilationDatabasePlugin {
  344. std::unique_ptr<CompilationDatabase>
  345. loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
  346. SmallString<1024> DatabasePath(Directory);
  347. llvm::sys::path::append(DatabasePath, "compile_flags.txt");
  348. return FixedCompilationDatabase::loadFromFile(DatabasePath, ErrorMessage);
  349. }
  350. };
  351. } // namespace
  352. static CompilationDatabasePluginRegistry::Add<FixedCompilationDatabasePlugin>
  353. X("fixed-compilation-database", "Reads plain-text flags file");
  354. namespace clang {
  355. namespace tooling {
  356. // This anchor is used to force the linker to link in the generated object file
  357. // and thus register the JSONCompilationDatabasePlugin.
  358. extern volatile int JSONAnchorSource;
  359. static int LLVM_ATTRIBUTE_UNUSED JSONAnchorDest = JSONAnchorSource;
  360. } // namespace tooling
  361. } // namespace clang