clang_runner.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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 <string>
  10. #include <utility>
  11. #include "clang/Basic/Diagnostic.h"
  12. #include "clang/Basic/DiagnosticOptions.h"
  13. #include "clang/Driver/Compilation.h"
  14. #include "clang/Driver/Driver.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Frontend/TextDiagnosticPrinter.h"
  17. #include "common/vlog.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/ScopeExit.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/IR/LLVMContext.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/LLVMDriver.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/Program.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,
  40. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  41. llvm::raw_ostream* vlog_stream)
  42. : ToolRunnerBase(install_paths, vlog_stream),
  43. target_(target),
  44. fs_(std::move(fs)),
  45. diagnostic_ids_(new clang::DiagnosticIDs()) {}
  46. auto ClangRunner::Run(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  47. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  48. std::string clang_path = installation_->clang_path();
  49. // Rebuild the args as C-string args.
  50. llvm::OwningArrayRef<char> cstr_arg_storage;
  51. llvm::SmallVector<const char*, 64> cstr_args =
  52. BuildCStrArgs("Clang", clang_path, "-v", args, cstr_arg_storage);
  53. if (!args.empty() && args[0].starts_with("-cc1")) {
  54. CARBON_VLOG("Calling clang_main for cc1...");
  55. // cstr_args[0] will be the `clang_path` so we don't need the prepend arg.
  56. llvm::ToolContext tool_context = {
  57. .Path = cstr_args[0], .PrependArg = "clang", .NeedsPrependArg = false};
  58. int exit_code = clang_main(
  59. cstr_args.size(), const_cast<char**>(cstr_args.data()), tool_context);
  60. // TODO: Should this be forwarding the full exit code?
  61. return exit_code == 0;
  62. }
  63. CARBON_VLOG("Preparing Clang driver...\n");
  64. // Create the diagnostic options and parse arguments controlling them out of
  65. // our arguments.
  66. std::unique_ptr<clang::DiagnosticOptions> diagnostic_options =
  67. clang::CreateAndPopulateDiagOpts(cstr_args);
  68. // TODO: We don't yet support serializing diagnostics the way the actual
  69. // `clang` command line does. Unclear if we need to or not, but it would need
  70. // a bit more logic here to set up chained consumers.
  71. clang::TextDiagnosticPrinter diagnostic_client(llvm::errs(),
  72. *diagnostic_options);
  73. clang::DiagnosticsEngine diagnostics(diagnostic_ids_, *diagnostic_options,
  74. &diagnostic_client,
  75. /*ShouldOwnClient=*/false);
  76. clang::ProcessWarningOptions(diagnostics, *diagnostic_options, *fs_);
  77. clang::driver::Driver driver(clang_path, target_, diagnostics,
  78. "clang LLVM compiler", fs_);
  79. // Configure the install directory to find other tools and data files.
  80. //
  81. // We directly override the detected directory as we use a synthetic path
  82. // above. This makes it appear that our binary was in the installed binaries
  83. // directory, and allows finding tools relative to it.
  84. driver.Dir = installation_->llvm_install_bin();
  85. CARBON_VLOG("Setting bin directory to: {0}\n", driver.Dir);
  86. // When there's only one command being run, this will run it in-process.
  87. // However, a `clang` invocation may cause multiple `cc1` invocations, which
  88. // still subprocess. See `InProcess` comment at:
  89. // https://github.com/llvm/llvm-project/blob/86ce8e4504c06ecc3cc42f002ad4eb05cac10925/clang/lib/Driver/Job.cpp#L411-L413
  90. //
  91. // Note the subprocessing will effectively call `clang -cc1`, which turns into
  92. // `carbon-busybox clang -cc1`, which results in an equivalent `clang_main`
  93. // call.
  94. //
  95. // Also note that we only do `-disable-free` filtering in the in-process
  96. // execution here, as subprocesses leaking memory won't impact this process.
  97. auto cc1_main = [enable_leaking = enable_leaking_](
  98. llvm::SmallVectorImpl<const char*>& cc1_args) -> int {
  99. if (!enable_leaking) {
  100. // Last-flag wins, so this forcibly re-enables freeing memory.
  101. cc1_args.push_back("-no-disable-free");
  102. }
  103. // cc1_args[0] will be the `clang_path` so we don't need the prepend arg.
  104. llvm::ToolContext tool_context = {
  105. .Path = cc1_args[0], .PrependArg = "clang", .NeedsPrependArg = false};
  106. return clang_main(cc1_args.size(), const_cast<char**>(cc1_args.data()),
  107. tool_context);
  108. };
  109. driver.CC1Main = cc1_main;
  110. std::unique_ptr<clang::driver::Compilation> compilation(
  111. driver.BuildCompilation(cstr_args));
  112. CARBON_CHECK(compilation, "Should always successfully allocate!");
  113. if (compilation->containsError()) {
  114. // These should have been diagnosed by the driver.
  115. return false;
  116. }
  117. CARBON_VLOG("Running Clang driver...\n");
  118. llvm::SmallVector<std::pair<int, const clang::driver::Command*>>
  119. failing_commands;
  120. int result = driver.ExecuteCompilation(*compilation, failing_commands);
  121. // Finish diagnosing any failures before we verbosely log the source of those
  122. // failures.
  123. diagnostic_client.finish();
  124. CARBON_VLOG("Execution result code: {0}\n", result);
  125. for (const auto& [command_result, failing_command] : failing_commands) {
  126. CARBON_VLOG("Failing command '{0}' with code '{1}' was:\n",
  127. failing_command->getExecutable(), command_result);
  128. if (vlog_stream_) {
  129. failing_command->Print(*vlog_stream_, "\n\n", /*Quote=*/true);
  130. }
  131. }
  132. // Return whether the command was executed successfully.
  133. return result == 0 && failing_commands.empty();
  134. }
  135. } // namespace Carbon