clang_runner.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/driver/clang_runner.h"
  5. #include <algorithm>
  6. #include <memory>
  7. #include <numeric>
  8. #include <optional>
  9. #include "clang/Basic/Diagnostic.h"
  10. #include "clang/Basic/DiagnosticOptions.h"
  11. #include "clang/Driver/Compilation.h"
  12. #include "clang/Driver/Driver.h"
  13. #include "clang/Frontend/CompilerInvocation.h"
  14. #include "clang/Frontend/TextDiagnosticPrinter.h"
  15. #include "common/command_line.h"
  16. #include "common/vlog.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/ScopeExit.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/Support/FileSystem.h"
  23. #include "llvm/Support/LLVMDriver.h"
  24. #include "llvm/Support/Path.h"
  25. #include "llvm/Support/Program.h"
  26. #include "llvm/Support/VirtualFileSystem.h"
  27. #include "llvm/TargetParser/Host.h"
  28. // Defined in:
  29. // https://github.com/llvm/llvm-project/blob/main/clang/tools/driver/driver.cpp
  30. //
  31. // While not in a header, this is the API used by llvm-driver.cpp for
  32. // busyboxing.
  33. //
  34. // NOLINTNEXTLINE(readability-identifier-naming)
  35. auto clang_main(int Argc, char** Argv, const llvm::ToolContext& ToolContext)
  36. -> int;
  37. namespace Carbon {
  38. ClangRunner::ClangRunner(const InstallPaths* install_paths,
  39. llvm::StringRef target, llvm::raw_ostream* vlog_stream)
  40. : installation_(install_paths),
  41. target_(target),
  42. vlog_stream_(vlog_stream),
  43. diagnostic_ids_(new clang::DiagnosticIDs()) {}
  44. auto ClangRunner::Run(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  45. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  46. // If we have a verbose logging stream, and that stream is the same as
  47. // `llvm::errs`, then add the `-v` flag so that the driver also prints verbose
  48. // information.
  49. bool inject_v_arg = vlog_stream_ == &llvm::errs();
  50. std::array<llvm::StringRef, 1> v_arg_storage;
  51. llvm::ArrayRef<llvm::StringRef> maybe_v_arg;
  52. if (inject_v_arg) {
  53. v_arg_storage[0] = "-v";
  54. maybe_v_arg = v_arg_storage;
  55. }
  56. CARBON_VLOG("Running Clang driver with arguments: \n");
  57. // Render the arguments into null-terminated C-strings for use by the Clang
  58. // driver. Command lines can get quite long in build systems so this tries to
  59. // minimize the memory allocation overhead.
  60. // Start with a dummy executable name. We'll manually set the install
  61. // directory below.
  62. std::array<llvm::StringRef, 1> exe_arg = {"clang-runner"};
  63. auto args_range =
  64. llvm::concat<const llvm::StringRef>(exe_arg, maybe_v_arg, args);
  65. int total_size = 0;
  66. for (llvm::StringRef arg : args_range) {
  67. // Accumulate both the string size and a null terminator byte.
  68. total_size += arg.size() + 1;
  69. }
  70. // Allocate one chunk of storage for the actual C-strings and a vector of
  71. // pointers into the storage.
  72. llvm::OwningArrayRef<char> cstr_arg_storage(total_size);
  73. llvm::SmallVector<const char*, 64> cstr_args;
  74. cstr_args.reserve(args.size() + inject_v_arg + 1);
  75. for (ssize_t i = 0; llvm::StringRef arg : args_range) {
  76. cstr_args.push_back(&cstr_arg_storage[i]);
  77. memcpy(&cstr_arg_storage[i], arg.data(), arg.size());
  78. i += arg.size();
  79. cstr_arg_storage[i] = '\0';
  80. ++i;
  81. }
  82. for (const char* cstr_arg : llvm::ArrayRef(cstr_args)) {
  83. CARBON_VLOG(" '{0}'\n", cstr_arg);
  84. }
  85. CARBON_VLOG("Preparing Clang driver...\n");
  86. // Create the diagnostic options and parse arguments controlling them out of
  87. // our arguments.
  88. llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnostic_options =
  89. clang::CreateAndPopulateDiagOpts(cstr_args);
  90. // TODO: We don't yet support serializing diagnostics the way the actual
  91. // `clang` command line does. Unclear if we need to or not, but it would need
  92. // a bit more logic here to set up chained consumers.
  93. clang::TextDiagnosticPrinter diagnostic_client(llvm::errs(),
  94. diagnostic_options.get());
  95. clang::DiagnosticsEngine diagnostics(
  96. diagnostic_ids_, diagnostic_options.get(), &diagnostic_client,
  97. /*ShouldOwnClient=*/false);
  98. clang::ProcessWarningOptions(diagnostics, *diagnostic_options);
  99. clang::driver::Driver driver("clang-runner", target_, diagnostics);
  100. // Configure the install directory to find other tools and data files.
  101. //
  102. // We directly override the detected directory as we use a synthetic path
  103. // above. This makes it appear that our binary was in the installed binaries
  104. // directory, and allows finding tools relative to it.
  105. driver.Dir = installation_->llvm_install_bin();
  106. CARBON_VLOG("Setting bin directory to: {0}\n", driver.Dir);
  107. // When there's only one command being run, this will run it in-process.
  108. // However, a `clang` invocation may cause multiple `cc1` invocations, which
  109. // still subprocess. See `InProcess` comment at:
  110. // https://github.com/llvm/llvm-project/blob/86ce8e4504c06ecc3cc42f002ad4eb05cac10925/clang/lib/Driver/Job.cpp#L411-L413
  111. //
  112. // TODO: It would be nice to find a way to set up the driver's understanding
  113. // of the executable name in a way that causes the multiple `cc1` invocations
  114. // to actually result in `carbon clang -- ...` invocations (even if as
  115. // subprocesses). This may dovetail with having symlinks that redirect to a
  116. // busybox of LLD as well, and having even the subprocesses consistently run
  117. // the Carbon install toolchain and not a system toolchain whenever possible.
  118. driver.CC1Main = [](llvm::SmallVectorImpl<const char*>& argv) -> int {
  119. llvm::ToolContext tool_context;
  120. return clang_main(argv.size(), const_cast<char**>(argv.data()),
  121. tool_context);
  122. };
  123. std::unique_ptr<clang::driver::Compilation> compilation(
  124. driver.BuildCompilation(cstr_args));
  125. CARBON_CHECK(compilation, "Should always successfully allocate!");
  126. if (compilation->containsError()) {
  127. // These should have been diagnosed by the driver.
  128. return false;
  129. }
  130. CARBON_VLOG("Running Clang driver...\n");
  131. llvm::SmallVector<std::pair<int, const clang::driver::Command*>>
  132. failing_commands;
  133. int result = driver.ExecuteCompilation(*compilation, failing_commands);
  134. // Finish diagnosing any failures before we verbosely log the source of those
  135. // failures.
  136. diagnostic_client.finish();
  137. CARBON_VLOG("Execution result code: {0}\n", result);
  138. for (const auto& [command_result, failing_command] : failing_commands) {
  139. CARBON_VLOG("Failing command '{0}' with code '{1}' was:\n",
  140. failing_command->getExecutable(), command_result);
  141. if (vlog_stream_) {
  142. failing_command->Print(*vlog_stream_, "\n\n", /*Quote=*/true);
  143. }
  144. }
  145. // Return whether the command was executed successfully.
  146. return result == 0 && failing_commands.empty();
  147. }
  148. } // namespace Carbon