CompilationDatabase.cpp 12 KB

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