clang_runner.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 <stdlib.h>
  6. #include <unistd.h>
  7. #include <filesystem>
  8. #include <memory>
  9. #include <optional>
  10. #include <string>
  11. #include <utility>
  12. #include "clang/Basic/Diagnostic.h"
  13. #include "clang/Basic/DiagnosticDriver.h"
  14. #include "clang/Basic/DiagnosticIDs.h"
  15. #include "clang/Basic/DiagnosticOptions.h"
  16. #include "clang/CodeGen/ObjectFilePCHContainerWriter.h"
  17. #include "clang/Driver/Compilation.h"
  18. #include "clang/Driver/Driver.h"
  19. #include "clang/Frontend/CompilerInstance.h"
  20. #include "clang/Frontend/CompilerInvocation.h"
  21. #include "clang/Frontend/TextDiagnosticBuffer.h"
  22. #include "clang/Frontend/TextDiagnosticPrinter.h"
  23. #include "clang/Frontend/Utils.h"
  24. #include "clang/FrontendTool/Utils.h"
  25. #include "clang/Serialization/ObjectFilePCHContainerReader.h"
  26. #include "clang/Serialization/PCHContainerOperations.h"
  27. #include "common/check.h"
  28. #include "common/error.h"
  29. #include "common/string_helpers.h"
  30. #include "common/vlog.h"
  31. #include "llvm/ADT/ArrayRef.h"
  32. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/ADT/SmallVector.h"
  35. #include "llvm/ADT/Statistic.h"
  36. #include "llvm/ADT/StringExtras.h"
  37. #include "llvm/ADT/StringRef.h"
  38. #include "llvm/IR/LLVMContext.h"
  39. #include "llvm/Support/Allocator.h"
  40. #include "llvm/Support/BuryPointer.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/Error.h"
  43. #include "llvm/Support/LLVMDriver.h"
  44. #include "llvm/Support/ThreadPool.h"
  45. #include "llvm/Support/TimeProfiler.h"
  46. #include "llvm/Support/Timer.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/TargetParser/Host.h"
  49. #include "third_party/llvm/clang_cc1.h"
  50. #include "toolchain/base/clang_invocation.h"
  51. #include "toolchain/base/install_paths.h"
  52. #include "toolchain/driver/clang_runtimes.h"
  53. #include "toolchain/driver/runtimes_cache.h"
  54. #include "toolchain/driver/tool_runner_base.h"
  55. // Defined in:
  56. // https://github.com/llvm/llvm-project/blob/main/clang/tools/driver/driver.cpp
  57. //
  58. // While not in a header, this is the API used by llvm-driver.cpp for
  59. // busyboxing.
  60. //
  61. // NOLINTNEXTLINE(readability-identifier-naming)
  62. auto clang_main(int Argc, char** Argv, const llvm::ToolContext& ToolContext)
  63. -> int;
  64. namespace Carbon {
  65. ClangRunner::ClangRunner(
  66. const InstallPaths* install_paths,
  67. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  68. llvm::raw_ostream* vlog_stream,
  69. std::optional<std::filesystem::path> override_clang_path)
  70. : ToolRunnerBase(install_paths, vlog_stream),
  71. fs_(std::move(fs)),
  72. clang_path_(override_clang_path ? *std::move(override_clang_path)
  73. : installation_->clang_path()) {}
  74. // Searches an argument list to a Clang execution to determine the expected
  75. // target string, suitable for use with `llvm::Triple`.
  76. //
  77. // If no explicit target flags are present, this defaults to the default
  78. // LLVM target.
  79. //
  80. // Works to handle the most common flags that modify the expected target as
  81. // well as direct target flags.
  82. //
  83. // Note: this has known fidelity issues if the args include separate-value flags
  84. // (`--flag value` style as opposed to `--flag=value`) where the value might
  85. // match the spelling of one of the target flags. For example, args that include
  86. // an output file spelled `-m32` (so `-o` followed by `-m32`) will be
  87. // misinterpreted by considering the value to itself be a flag. Addressing this
  88. // would add substantial complexity, including likely parsing the entire args
  89. // twice with the Clang driver. Instead, our current plan is to document this
  90. // limitation and encourage the use of flags with joined values
  91. // (`--flag=value`).
  92. static auto ComputeClangTarget(llvm::ArrayRef<llvm::StringRef> args)
  93. -> std::string {
  94. std::string target = llvm::sys::getDefaultTargetTriple();
  95. bool explicit_target = false;
  96. for (auto [i, arg] : llvm::enumerate(args)) {
  97. if (llvm::StringRef arg_copy = arg; arg_copy.consume_front("--target=")) {
  98. target = arg_copy.str();
  99. explicit_target = true;
  100. } else if ((arg == "--target" || arg == "-target") &&
  101. (i + 1) < args.size()) {
  102. target = args[i + 1].str();
  103. explicit_target = true;
  104. } else if (!explicit_target &&
  105. (arg == "--driver-mode=cl" ||
  106. ((arg == "--driver-mode" || arg == "-driver-mode") &&
  107. (i + 1) < args.size() && args[i + 1] == "cl"))) {
  108. // The `cl.exe` compatible driver mode should switch the default target to
  109. // a `...-pc-windows-msvc` target. However, a subsequent explicit target
  110. // should override this.
  111. llvm::Triple triple(target);
  112. triple.setVendor(llvm::Triple::PC);
  113. triple.setOS(llvm::Triple::Win32);
  114. triple.setEnvironment(llvm::Triple::MSVC);
  115. target = triple.str();
  116. } else if (arg == "-m32") {
  117. llvm::Triple triple(target);
  118. if (!triple.isArch32Bit()) {
  119. target = triple.get32BitArchVariant().str();
  120. }
  121. } else if (arg == "-m64") {
  122. llvm::Triple triple(target);
  123. if (!triple.isArch64Bit()) {
  124. target = triple.get64BitArchVariant().str();
  125. }
  126. }
  127. }
  128. return target;
  129. }
  130. // Tries to detect a a non-linking list of Clang arguments to avoid setting up
  131. // the more complete resource directory needed for linking. False negatives are
  132. // fine here, and we use that to keep things simple.
  133. static auto IsNonLinkCommand(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  134. return llvm::any_of(args, [](llvm::StringRef arg) {
  135. // Only check the most common cases as we have to do this for each argument.
  136. // Everything else is rare and likely not worth the cost of searching for
  137. // since it's fine to have false negatives.
  138. return arg == "-c" || arg == "-E" || arg == "-S" ||
  139. arg == "-fsyntax-only" || arg == "--version" || arg == "--help" ||
  140. arg == "/?" || arg == "--driver-mode=cpp";
  141. });
  142. }
  143. auto ClangRunner::RunWithPrebuiltRuntimes(llvm::ArrayRef<llvm::StringRef> args,
  144. Runtimes& prebuilt_runtimes,
  145. bool enable_leaking)
  146. -> ErrorOr<bool> {
  147. // Check the args to see if we have a known target-independent command. If so,
  148. // directly dispatch it to avoid the cost of building the target resource
  149. // directory.
  150. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  151. if (args.empty() || args[0].starts_with("-cc1") || IsNonLinkCommand(args)) {
  152. return RunWithNoRuntimes(args, enable_leaking);
  153. }
  154. std::string target = ComputeClangTarget(args);
  155. CARBON_ASSIGN_OR_RETURN(std::filesystem::path prebuilt_resource_dir_path,
  156. prebuilt_runtimes.Get(Runtimes::ClangResourceDir));
  157. return RunInternal(args, target, prebuilt_resource_dir_path.native(),
  158. enable_leaking);
  159. }
  160. auto ClangRunner::Run(llvm::ArrayRef<llvm::StringRef> args,
  161. Runtimes::Cache& runtimes_cache,
  162. llvm::ThreadPoolInterface& runtimes_build_thread_pool,
  163. bool enable_leaking) -> ErrorOr<bool> {
  164. // Check the args to see if we have a known target-independent command. If so,
  165. // directly dispatch it to avoid the cost of building the target resource
  166. // directory.
  167. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  168. if (args.empty() || args[0].starts_with("-cc1") || IsNonLinkCommand(args)) {
  169. return RunWithNoRuntimes(args, enable_leaking);
  170. }
  171. std::string target = ComputeClangTarget(args);
  172. CARBON_VLOG("Building target resource dir...\n");
  173. Runtimes::Cache::Features features = {.target = target};
  174. CARBON_ASSIGN_OR_RETURN(Runtimes runtimes, runtimes_cache.Lookup(features));
  175. // We need to build the Clang resource directory for these runtimes. This
  176. // requires a temporary directory as well as the destination directory for
  177. // the build. The temporary directory should only be used during the build,
  178. // not once we are running Clang with the built runtime.
  179. std::filesystem::path resource_dir_path;
  180. {
  181. ClangResourceDirBuilder builder(this, &runtimes_build_thread_pool,
  182. llvm::Triple(features.target), &runtimes);
  183. CARBON_ASSIGN_OR_RETURN(resource_dir_path, std::move(builder).Wait());
  184. }
  185. // Note that this function always successfully runs `clang` and returns a bool
  186. // to indicate whether `clang` itself succeeded, not whether the runner was
  187. // able to run it. As a consequence, even a `false` here is a non-`Error`
  188. // return.
  189. return RunInternal(args, target, resource_dir_path.native(), enable_leaking);
  190. }
  191. auto ClangRunner::RunWithNoRuntimes(llvm::ArrayRef<llvm::StringRef> args,
  192. bool enable_leaking) -> bool {
  193. std::string target = ComputeClangTarget(args);
  194. return RunInternal(args, target, std::nullopt, enable_leaking);
  195. }
  196. auto ClangRunner::RunInternal(
  197. llvm::ArrayRef<llvm::StringRef> args, llvm::StringRef target,
  198. std::optional<llvm::StringRef> target_resource_dir_path,
  199. bool enable_leaking) -> bool {
  200. // Rebuild the args as C-string args.
  201. llvm::OwningArrayRef<char> cstr_arg_storage;
  202. // Handle special dispatch for CC1 commands as they don't use the driver and
  203. // we don't synthesize any default arguments there.
  204. if (!args.empty() && args[0].starts_with("-cc1")) {
  205. llvm::SmallVector<const char*, 64> cstr_args =
  206. BuildCStrArgs(clang_path_.native(), args, cstr_arg_storage);
  207. if (args[0] == "-cc1") {
  208. CARBON_VLOG("Dispatching `-cc1` command line...");
  209. int exit_code =
  210. RunClangCC1(*installation_, fs_, cstr_args, enable_leaking);
  211. // TODO: Should this be forwarding the full exit code?
  212. return exit_code == 0;
  213. }
  214. // Other CC1-based invocations need to dispatch into the `clang_main`
  215. // routine to work correctly. This means they're not reliable in a library
  216. // context but currently there is too much logic to reasonably extract here.
  217. // This at least allows simple cases (often when directly used on the
  218. // command line) to work correctly.
  219. //
  220. // TODO: Factor the relevant code paths into a library API or move this into
  221. // the busybox dispatch logic.
  222. CARBON_VLOG("Calling clang_main for a cc1-based invocation...");
  223. // cstr_args[0] will be the `clang_path` so we don't need the prepend arg.
  224. llvm::ToolContext tool_context = {
  225. .Path = cstr_args[0], .PrependArg = "clang", .NeedsPrependArg = false};
  226. int exit_code = clang_main(
  227. cstr_args.size(), const_cast<char**>(cstr_args.data()), tool_context);
  228. // TODO: Should this be forwarding the full exit code?
  229. return exit_code == 0;
  230. }
  231. // We start with a custom prefix of arguments to establish Carbon's default
  232. // configuration for invoking Clang. These may not all be needed for all
  233. // invocations, so we also suppress warnings about any that are ignored.
  234. llvm::SmallVector<std::string> prefix_args;
  235. prefix_args.push_back("--start-no-unused-arguments");
  236. AppendDefaultClangArgs(*installation_, target, prefix_args);
  237. prefix_args.push_back("--end-no-unused-arguments");
  238. // Rebuild the args as C-string args.
  239. llvm::SmallVector<const char*, 64> cstr_args =
  240. BuildCStrArgs(clang_path_.native(), prefix_args, args, cstr_arg_storage);
  241. CARBON_VLOG("Running Clang driver with the following arguments:\n");
  242. for (const char* cstr_arg : llvm::ArrayRef(cstr_args)) {
  243. CARBON_VLOG(" '{0}'\n", cstr_arg);
  244. }
  245. // Create the diagnostic options and parse arguments controlling them out of
  246. // our arguments.
  247. std::unique_ptr<clang::DiagnosticOptions> diagnostic_options =
  248. clang::CreateAndPopulateDiagOpts(cstr_args);
  249. // TODO: We don't yet support serializing diagnostics the way the actual
  250. // `clang` command line does. Unclear if we need to or not, but it would need
  251. // a bit more logic here to set up chained consumers.
  252. clang::TextDiagnosticPrinter diagnostic_client(llvm::errs(),
  253. *diagnostic_options);
  254. // Note that the `DiagnosticsEngine` takes ownership (via a ref count) of the
  255. // DiagnosticIDs, unlike the other parameters.
  256. clang::DiagnosticsEngine diagnostics(clang::DiagnosticIDs::create(),
  257. *diagnostic_options, &diagnostic_client,
  258. /*ShouldOwnClient=*/false);
  259. clang::ProcessWarningOptions(diagnostics, *diagnostic_options, *fs_);
  260. // Note that we configure the driver's *default* target here, not the expected
  261. // target as that will be parsed out of the command line below.
  262. clang::driver::Driver driver(clang_path_.native(),
  263. llvm::sys::getDefaultTargetTriple(), diagnostics,
  264. "clang LLVM compiler", fs_);
  265. llvm::Triple target_triple(target);
  266. // We need to set an SDK system root on macOS by default. Setting it here
  267. // allows a custom sysroot to still be specified on the command line.
  268. //
  269. // TODO: A different system root should be used for iOS, watchOS, tvOS.
  270. // Currently, we're only targeting macOS support though.
  271. if (target_triple.isMacOSX()) {
  272. // This is the default CLT system root, shown by `xcrun --show-sdk-path`.
  273. // We hard code it here to avoid the overhead of subprocessing to `xcrun` on
  274. // each Clang invocation, but this may need to be updated to search or
  275. // reflect macOS versions if this changes in the future.
  276. driver.SysRoot = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk";
  277. }
  278. // If we have a target-specific resource directory, set it as the default
  279. // here, otherwise use the installation's resource directory.
  280. driver.ResourceDir = target_resource_dir_path
  281. ? target_resource_dir_path->str()
  282. : installation_->clang_resource_path().native();
  283. // Configure the install directory to find other tools and data files.
  284. //
  285. // We directly override the detected directory as we use a synthetic path
  286. // above. This makes it appear that our binary was in the installed binaries
  287. // directory, and allows finding tools relative to it.
  288. driver.Dir = installation_->llvm_install_bin();
  289. CARBON_VLOG("Setting bin directory to: {0}\n", driver.Dir);
  290. // When there's only one command being run, this will run it in-process.
  291. // However, a `clang` invocation may cause multiple `cc1` invocations, which
  292. // still subprocess. See `InProcess` comment at:
  293. // https://github.com/llvm/llvm-project/blob/86ce8e4504c06ecc3cc42f002ad4eb05cac10925/clang/lib/Driver/Job.cpp#L411-L413
  294. //
  295. // Note the subprocessing will effectively call `clang -cc1`, which turns into
  296. // `carbon-busybox clang -cc1`, which results in an equivalent `clang_main`
  297. // call.
  298. //
  299. // Also note that we only do `-disable-free` filtering in the in-process
  300. // execution here, as subprocesses leaking memory won't impact this process.
  301. auto cc1_main = [this, enable_leaking](
  302. llvm::SmallVectorImpl<const char*>& cc1_args) -> int {
  303. return RunClangCC1(*installation_, fs_, cc1_args, enable_leaking);
  304. };
  305. driver.CC1Main = cc1_main;
  306. std::unique_ptr<clang::driver::Compilation> compilation(
  307. driver.BuildCompilation(cstr_args));
  308. CARBON_CHECK(compilation, "Should always successfully allocate!");
  309. if (compilation->containsError()) {
  310. // These should have been diagnosed by the driver.
  311. return false;
  312. }
  313. // Make sure our target detection matches Clang's. Sadly, we can't just reuse
  314. // Clang's as it is available too late.
  315. // TODO: Use nice diagnostics here rather than a check failure.
  316. CARBON_CHECK(llvm::Triple(target) == llvm::Triple(driver.getTargetTriple()),
  317. "Mismatch between the expected target '{0}' and the one "
  318. "computed by Clang '{1}'",
  319. target, driver.getTargetTriple());
  320. CARBON_VLOG("Running Clang driver...\n");
  321. llvm::SmallVector<std::pair<int, const clang::driver::Command*>>
  322. failing_commands;
  323. int result = driver.ExecuteCompilation(*compilation, failing_commands);
  324. // Finish diagnosing any failures before we verbosely log the source of those
  325. // failures.
  326. diagnostic_client.finish();
  327. CARBON_VLOG("Execution result code: {0}\n", result);
  328. for (const auto& [command_result, failing_command] : failing_commands) {
  329. CARBON_VLOG("Failing command '{0}' with code '{1}' was:\n",
  330. failing_command->getExecutable(), command_result);
  331. if (vlog_stream_) {
  332. failing_command->Print(*vlog_stream_, "\n\n", /*Quote=*/true);
  333. }
  334. }
  335. // Return whether the command was executed successfully.
  336. return result == 0 && failing_commands.empty();
  337. }
  338. } // namespace Carbon