CompilationDatabase.cpp 12 KB

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