clang_runner.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 <unistd.h>
  6. #include <algorithm>
  7. #include <filesystem>
  8. #include <memory>
  9. #include <numeric>
  10. #include <optional>
  11. #include <string>
  12. #include <system_error>
  13. #include <utility>
  14. #include "clang/Basic/Diagnostic.h"
  15. #include "clang/Basic/DiagnosticOptions.h"
  16. #include "clang/Driver/Compilation.h"
  17. #include "clang/Driver/Driver.h"
  18. #include "clang/Frontend/CompilerInvocation.h"
  19. #include "clang/Frontend/TextDiagnosticPrinter.h"
  20. #include "common/filesystem.h"
  21. #include "common/vlog.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/ScopeExit.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/IR/LLVMContext.h"
  27. #include "llvm/Object/ArchiveWriter.h"
  28. #include "llvm/Support/Error.h"
  29. #include "llvm/Support/FileSystem.h"
  30. #include "llvm/Support/FormatAdapters.h"
  31. #include "llvm/Support/LLVMDriver.h"
  32. #include "llvm/Support/Path.h"
  33. #include "llvm/Support/Program.h"
  34. #include "llvm/TargetParser/Host.h"
  35. #include "toolchain/base/runtime_sources.h"
  36. // Defined in:
  37. // https://github.com/llvm/llvm-project/blob/main/clang/tools/driver/driver.cpp
  38. //
  39. // While not in a header, this is the API used by llvm-driver.cpp for
  40. // busyboxing.
  41. //
  42. // NOLINTNEXTLINE(readability-identifier-naming)
  43. auto clang_main(int Argc, char** Argv, const llvm::ToolContext& ToolContext)
  44. -> int;
  45. namespace Carbon {
  46. ClangRunner::ClangRunner(const InstallPaths* install_paths,
  47. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  48. llvm::raw_ostream* vlog_stream,
  49. bool build_runtimes_on_demand)
  50. : ToolRunnerBase(install_paths, vlog_stream),
  51. fs_(std::move(fs)),
  52. diagnostic_ids_(new clang::DiagnosticIDs()),
  53. build_runtimes_on_demand_(build_runtimes_on_demand) {}
  54. // Searches an argument list to a Clang execution to determine the expected
  55. // target string, suitable for use with `llvm::Triple`.
  56. //
  57. // If no explicit target flags are present, this defaults to the default
  58. // LLVM target.
  59. //
  60. // Works to handle the most common flags that modify the expected target as
  61. // well as direct target flags.
  62. //
  63. // Note: this has known fidelity issues if the args include separate-value flags
  64. // (`--flag value` style as opposed to `--flag=value`) where the value might
  65. // match the spelling of one of the target flags. For example, args that include
  66. // an output file spelled `-m32` (so `-o` followed by `-m32`) will be
  67. // misinterpreted by considering the value to itself be a flag. Addressing this
  68. // would add substantial complexity, including likely parsing the entire args
  69. // twice with the Clang driver. Instead, our current plan is to document this
  70. // limitation and encourage the use of flags with joined values
  71. // (`--flag=value`).
  72. static auto ComputeClangTarget(llvm::ArrayRef<llvm::StringRef> args)
  73. -> std::string {
  74. std::string target = llvm::sys::getDefaultTargetTriple();
  75. bool explicit_target = false;
  76. for (auto [i, arg] : llvm::enumerate(args)) {
  77. if (llvm::StringRef arg_copy = arg; arg_copy.consume_front("--target=")) {
  78. target = arg_copy.str();
  79. explicit_target = true;
  80. } else if ((arg == "--target" || arg == "-target") &&
  81. (i + 1) < args.size()) {
  82. target = args[i + 1].str();
  83. explicit_target = true;
  84. } else if (!explicit_target &&
  85. (arg == "--driver-mode=cl" ||
  86. ((arg == "--driver-mode" || arg == "-driver-mode") &&
  87. (i + 1) < args.size() && args[i + 1] == "cl"))) {
  88. // The `cl.exe` compatible driver mode should switch the default target to
  89. // a `...-pc-windows-msvc` target. However, a subsequent explicit target
  90. // should override this.
  91. llvm::Triple triple(target);
  92. triple.setVendor(llvm::Triple::PC);
  93. triple.setOS(llvm::Triple::Win32);
  94. triple.setEnvironment(llvm::Triple::MSVC);
  95. target = triple.str();
  96. } else if (arg == "-m32") {
  97. llvm::Triple triple(target);
  98. if (!triple.isArch32Bit()) {
  99. target = triple.get32BitArchVariant().str();
  100. }
  101. } else if (arg == "-m64") {
  102. llvm::Triple triple(target);
  103. if (!triple.isArch64Bit()) {
  104. target = triple.get64BitArchVariant().str();
  105. }
  106. }
  107. }
  108. return target;
  109. }
  110. // Tries to detect a a non-linking list of Clang arguments to avoid setting up
  111. // the more complete resource directory needed for linking. False negatives are
  112. // fine here, and we use that to keep things simple.
  113. static auto IsNonLinkCommand(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  114. return llvm::any_of(args, [](llvm::StringRef arg) {
  115. // Only check the most common cases as we have to do this for each argument.
  116. // Everything else is rare and likely not worth the cost of searching for
  117. // since it's fine to have false negatives.
  118. return arg == "-c" || arg == "-E" || arg == "-S" ||
  119. arg == "-fsyntax-only" || arg == "--version" || arg == "--help" ||
  120. arg == "/?" || arg == "--driver-mode=cpp";
  121. });
  122. }
  123. auto ClangRunner::Run(
  124. llvm::ArrayRef<llvm::StringRef> args,
  125. std::optional<std::filesystem::path> prebuilt_resource_dir_path)
  126. -> ErrorOr<bool> {
  127. // Check the args to see if we have a known target-independent command. If so,
  128. // directly dispatch it to avoid the cost of building the target resource
  129. // directory.
  130. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  131. if (args.empty() || args[0].starts_with("-cc1") || IsNonLinkCommand(args) ||
  132. (!build_runtimes_on_demand_ && !prebuilt_resource_dir_path)) {
  133. return RunTargetIndependentCommand(args);
  134. }
  135. std::string target = ComputeClangTarget(args);
  136. // If we have pre-built runtimes, use them rather than building on demand.
  137. if (prebuilt_resource_dir_path) {
  138. return RunInternal(args, target, prebuilt_resource_dir_path->native());
  139. }
  140. CARBON_CHECK(build_runtimes_on_demand_);
  141. // Otherwise, we need to build a target resource directory.
  142. //
  143. // TODO: Currently, this builds the runtimes in a temporary directory that is
  144. // removed after the Clang invocation. That requires building them on each
  145. // execution which is expensive and slow. Eventually, we want to replace this
  146. // with using an on-disk cache so that only the first execution has to build
  147. // the runtimes and subsequently the cached build can be used.
  148. CARBON_VLOG("Building target resource dir...\n");
  149. CARBON_ASSIGN_OR_RETURN(Filesystem::RemovingDir tmp_dir,
  150. Filesystem::MakeTmpDir());
  151. // Hard code the subdirectory for the resource-dir runtimes.
  152. //
  153. // TODO: This should be replaced with an abstraction that manages the layout
  154. // of a built runtimes tree.
  155. std::filesystem::path resource_dir_path =
  156. tmp_dir.abs_path() / "clang_resource_dir";
  157. CARBON_RETURN_IF_ERROR(
  158. BuildTargetResourceDir(target, resource_dir_path, tmp_dir.abs_path()));
  159. // Note that this function always successfully runs `clang` and returns a bool
  160. // to indicate whether `clang` itself succeeded, not whether the runner was
  161. // able to run it. As a consequence, even a `false` here is a non-`Error`
  162. // return.
  163. return RunInternal(args, target, resource_dir_path.native());
  164. }
  165. auto ClangRunner::RunTargetIndependentCommand(
  166. llvm::ArrayRef<llvm::StringRef> args) -> bool {
  167. std::string target = ComputeClangTarget(args);
  168. return RunInternal(args, target, std::nullopt);
  169. }
  170. auto ClangRunner::BuildTargetResourceDir(
  171. llvm::StringRef target, const std::filesystem::path& resource_dir_path,
  172. const std::filesystem::path& tmp_path) -> ErrorOr<Success> {
  173. // Disable any leaking of memory while building the target resource dir, and
  174. // restore the previous setting at the end.
  175. auto restore_leak_flag = llvm::make_scope_exit(
  176. [&, orig_flag = enable_leaking_] { enable_leaking_ = orig_flag; });
  177. enable_leaking_ = false;
  178. // Create the destination directory if needed.
  179. CARBON_ASSIGN_OR_RETURN(
  180. Filesystem::Dir resource_dir,
  181. Filesystem::Cwd().CreateDirectories(resource_dir_path));
  182. // Symlink the installation's `include` and `share` directories.
  183. std::filesystem::path install_resource_path =
  184. installation_->clang_resource_path();
  185. CARBON_RETURN_IF_ERROR(
  186. resource_dir.Symlink("include", install_resource_path / "include"));
  187. CARBON_RETURN_IF_ERROR(
  188. resource_dir.Symlink("share", install_resource_path / "share"));
  189. // Create the target's `lib` directory.
  190. std::filesystem::path lib_path =
  191. std::filesystem::path("lib") / std::string_view(target);
  192. CARBON_ASSIGN_OR_RETURN(Filesystem::Dir lib_dir,
  193. resource_dir.CreateDirectories(lib_path));
  194. llvm::Triple target_triple(target);
  195. if (target_triple.isOSWindows()) {
  196. return Error("TODO: Windows runtimes are untested and not yet supported.");
  197. }
  198. // For Linux targets, the system libc (typically glibc) doesn't necessarily
  199. // provide the CRT begin/end files, and so we need to build them.
  200. if (target_triple.isOSLinux()) {
  201. BuildCrtFile(target, RuntimeSources::CrtBegin,
  202. resource_dir_path / lib_path / "clang_rt.crtbegin.o");
  203. BuildCrtFile(target, RuntimeSources::CrtEnd,
  204. resource_dir_path / lib_path / "clang_rt.crtend.o");
  205. }
  206. CARBON_RETURN_IF_ERROR(
  207. BuildBuiltinsLib(target, target_triple, tmp_path, lib_dir));
  208. return Success();
  209. }
  210. auto ClangRunner::RunInternal(
  211. llvm::ArrayRef<llvm::StringRef> args, llvm::StringRef target,
  212. std::optional<llvm::StringRef> target_resource_dir_path) -> bool {
  213. std::string clang_path = installation_->clang_path();
  214. // Rebuild the args as C-string args.
  215. llvm::OwningArrayRef<char> cstr_arg_storage;
  216. llvm::SmallVector<const char*, 64> cstr_args =
  217. BuildCStrArgs("Clang", clang_path, "-v", args, cstr_arg_storage);
  218. // Handle special dispatch for CC1 commands as they don't use the driver.
  219. if (!args.empty() && args[0].starts_with("-cc1")) {
  220. CARBON_VLOG("Calling clang_main for cc1...");
  221. // cstr_args[0] will be the `clang_path` so we don't need the prepend arg.
  222. llvm::ToolContext tool_context = {
  223. .Path = cstr_args[0], .PrependArg = "clang", .NeedsPrependArg = false};
  224. int exit_code = clang_main(
  225. cstr_args.size(), const_cast<char**>(cstr_args.data()), tool_context);
  226. // TODO: Should this be forwarding the full exit code?
  227. return exit_code == 0;
  228. }
  229. CARBON_VLOG("Preparing Clang driver...\n");
  230. // Create the diagnostic options and parse arguments controlling them out of
  231. // our arguments.
  232. std::unique_ptr<clang::DiagnosticOptions> diagnostic_options =
  233. clang::CreateAndPopulateDiagOpts(cstr_args);
  234. // TODO: We don't yet support serializing diagnostics the way the actual
  235. // `clang` command line does. Unclear if we need to or not, but it would need
  236. // a bit more logic here to set up chained consumers.
  237. clang::TextDiagnosticPrinter diagnostic_client(llvm::errs(),
  238. *diagnostic_options);
  239. clang::DiagnosticsEngine diagnostics(diagnostic_ids_, *diagnostic_options,
  240. &diagnostic_client,
  241. /*ShouldOwnClient=*/false);
  242. clang::ProcessWarningOptions(diagnostics, *diagnostic_options, *fs_);
  243. // Note that we configure the driver's *default* target here, not the expected
  244. // target as that will be parsed out of the command line below.
  245. clang::driver::Driver driver(clang_path, llvm::sys::getDefaultTargetTriple(),
  246. diagnostics, "clang LLVM compiler", fs_);
  247. llvm::Triple target_triple(target);
  248. // We need to set an SDK system root on macOS by default. Setting it here
  249. // allows a custom sysroot to still be specified on the command line.
  250. //
  251. // TODO: A different system root should be used for iOS, watchOS, tvOS.
  252. // Currently, we're only targeting macOS support though.
  253. if (target_triple.isMacOSX()) {
  254. // This is the default CLT system root, shown by `xcrun --show-sdk-path`.
  255. // We hard code it here to avoid the overhead of subprocessing to `xcrun` on
  256. // each Clang invocation, but this may need to be updated to search or
  257. // reflect macOS versions if this changes in the future.
  258. driver.SysRoot = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk";
  259. }
  260. // If we have a target-specific resource directory, set it as the default
  261. // here.
  262. if (target_resource_dir_path) {
  263. driver.ResourceDir = target_resource_dir_path->str();
  264. }
  265. // Configure the install directory to find other tools and data files.
  266. //
  267. // We directly override the detected directory as we use a synthetic path
  268. // above. This makes it appear that our binary was in the installed binaries
  269. // directory, and allows finding tools relative to it.
  270. driver.Dir = installation_->llvm_install_bin();
  271. CARBON_VLOG("Setting bin directory to: {0}\n", driver.Dir);
  272. // When there's only one command being run, this will run it in-process.
  273. // However, a `clang` invocation may cause multiple `cc1` invocations, which
  274. // still subprocess. See `InProcess` comment at:
  275. // https://github.com/llvm/llvm-project/blob/86ce8e4504c06ecc3cc42f002ad4eb05cac10925/clang/lib/Driver/Job.cpp#L411-L413
  276. //
  277. // Note the subprocessing will effectively call `clang -cc1`, which turns into
  278. // `carbon-busybox clang -cc1`, which results in an equivalent `clang_main`
  279. // call.
  280. //
  281. // Also note that we only do `-disable-free` filtering in the in-process
  282. // execution here, as subprocesses leaking memory won't impact this process.
  283. auto cc1_main = [enable_leaking = enable_leaking_](
  284. llvm::SmallVectorImpl<const char*>& cc1_args) -> int {
  285. if (!enable_leaking) {
  286. // Last-flag wins, so this forcibly re-enables freeing memory.
  287. cc1_args.push_back("-no-disable-free");
  288. }
  289. // cc1_args[0] will be the `clang_path` so we don't need the prepend arg.
  290. llvm::ToolContext tool_context = {
  291. .Path = cc1_args[0], .PrependArg = "clang", .NeedsPrependArg = false};
  292. return clang_main(cc1_args.size(), const_cast<char**>(cc1_args.data()),
  293. tool_context);
  294. };
  295. driver.CC1Main = cc1_main;
  296. std::unique_ptr<clang::driver::Compilation> compilation(
  297. driver.BuildCompilation(cstr_args));
  298. CARBON_CHECK(compilation, "Should always successfully allocate!");
  299. if (compilation->containsError()) {
  300. // These should have been diagnosed by the driver.
  301. return false;
  302. }
  303. // Make sure our target detection matches Clang's. Sadly, we can't just reuse
  304. // Clang's as it is available too late.
  305. // TODO: Use nice diagnostics here rather than a check failure.
  306. CARBON_CHECK(llvm::Triple(target) == llvm::Triple(driver.getTargetTriple()),
  307. "Mismatch between the expected target '{0}' and the one "
  308. "computed by Clang '{1}'",
  309. target, driver.getTargetTriple());
  310. CARBON_VLOG("Running Clang driver...\n");
  311. llvm::SmallVector<std::pair<int, const clang::driver::Command*>>
  312. failing_commands;
  313. int result = driver.ExecuteCompilation(*compilation, failing_commands);
  314. // Finish diagnosing any failures before we verbosely log the source of those
  315. // failures.
  316. diagnostic_client.finish();
  317. CARBON_VLOG("Execution result code: {0}\n", result);
  318. for (const auto& [command_result, failing_command] : failing_commands) {
  319. CARBON_VLOG("Failing command '{0}' with code '{1}' was:\n",
  320. failing_command->getExecutable(), command_result);
  321. if (vlog_stream_) {
  322. failing_command->Print(*vlog_stream_, "\n\n", /*Quote=*/true);
  323. }
  324. }
  325. // Return whether the command was executed successfully.
  326. return result == 0 && failing_commands.empty();
  327. }
  328. auto ClangRunner::BuildCrtFile(llvm::StringRef target, llvm::StringRef src_file,
  329. const std::filesystem::path& out_path) -> void {
  330. std::filesystem::path src_path =
  331. installation_->llvm_runtime_srcs() / std::string_view(src_file);
  332. CARBON_VLOG("Building `{0}' from `{1}`...\n", out_path, src_path);
  333. std::string target_arg = llvm::formatv("--target={0}", target).str();
  334. CARBON_CHECK(RunTargetIndependentCommand({
  335. "-no-canonical-prefixes",
  336. target_arg,
  337. "-DCRT_HAS_INITFINI_ARRAY",
  338. "-DEH_USE_FRAME_REGISTRY",
  339. "-O3",
  340. "-fPIC",
  341. "-ffreestanding",
  342. "-std=c11",
  343. "-w",
  344. "-c",
  345. "-o",
  346. out_path.native(),
  347. src_path.native(),
  348. }));
  349. }
  350. auto ClangRunner::CollectBuiltinsSrcFiles(const llvm::Triple& target_triple)
  351. -> llvm::SmallVector<llvm::StringRef> {
  352. llvm::SmallVector<llvm::StringRef> src_files;
  353. auto append_src_files =
  354. [&](auto input_srcs,
  355. llvm::function_ref<bool(llvm::StringRef)> filter_out = {}) {
  356. for (llvm::StringRef input_src : input_srcs) {
  357. if (!input_src.ends_with(".c") && !input_src.ends_with(".S")) {
  358. // Not a compiled file.
  359. continue;
  360. }
  361. if (filter_out && filter_out(input_src)) {
  362. // Filtered out.
  363. continue;
  364. }
  365. src_files.push_back(input_src);
  366. }
  367. };
  368. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsGenericSrcs));
  369. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsBf16Srcs));
  370. if (target_triple.isArch64Bit()) {
  371. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsTfSrcs));
  372. }
  373. auto filter_out_chkstk = [&](llvm::StringRef src) {
  374. return !target_triple.isOSWindows() || !src.ends_with("chkstk.S");
  375. };
  376. if (target_triple.isAArch64()) {
  377. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsAarch64Srcs),
  378. filter_out_chkstk);
  379. } else if (target_triple.isX86()) {
  380. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsX86ArchSrcs));
  381. if (target_triple.isArch64Bit()) {
  382. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsX86_64Srcs),
  383. filter_out_chkstk);
  384. } else {
  385. // TODO: This should be turned into a nice user-facing diagnostic about an
  386. // unsupported target.
  387. CARBON_CHECK(
  388. target_triple.isArch32Bit(),
  389. "The Carbon toolchain doesn't currently support 16-bit x86.");
  390. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsI386Srcs),
  391. filter_out_chkstk);
  392. }
  393. } else {
  394. // TODO: This should be turned into a nice user-facing diagnostic about an
  395. // unsupported target.
  396. CARBON_FATAL("Target architecture is not supported: {0}",
  397. target_triple.str());
  398. }
  399. return src_files;
  400. }
  401. auto ClangRunner::BuildBuiltinsFile(llvm::StringRef target,
  402. llvm::StringRef src_file,
  403. const std::filesystem::path& out_path)
  404. -> void {
  405. std::filesystem::path src_path =
  406. installation_->llvm_runtime_srcs() / std::string_view(src_file);
  407. CARBON_VLOG("Building `{0}' from `{1}`...\n", out_path, src_path);
  408. std::string target_arg = llvm::formatv("--target={0}", target).str();
  409. CARBON_CHECK(RunTargetIndependentCommand({
  410. "-no-canonical-prefixes",
  411. target_arg,
  412. "-O3",
  413. "-fPIC",
  414. "-ffreestanding",
  415. "-fno-builtin",
  416. "-fomit-frame-pointer",
  417. "-fvisibility=hidden",
  418. "-std=c11",
  419. "-w",
  420. "-c",
  421. "-o",
  422. out_path.native(),
  423. src_path.native(),
  424. }));
  425. }
  426. auto ClangRunner::BuildBuiltinsLib(llvm::StringRef target,
  427. const llvm::Triple& target_triple,
  428. const std::filesystem::path& tmp_path,
  429. Filesystem::DirRef lib_dir)
  430. -> ErrorOr<Success> {
  431. llvm::SmallVector<llvm::StringRef> src_files =
  432. CollectBuiltinsSrcFiles(target_triple);
  433. CARBON_ASSIGN_OR_RETURN(Filesystem::Dir tmp_dir,
  434. Filesystem::Cwd().OpenDir(tmp_path));
  435. llvm::SmallVector<llvm::NewArchiveMember> objs;
  436. objs.reserve(src_files.size());
  437. for (llvm::StringRef src_file : src_files) {
  438. // Create any subdirectories needed for this file.
  439. std::filesystem::path src_path = src_file.str();
  440. if (src_path.has_parent_path()) {
  441. CARBON_RETURN_IF_ERROR(tmp_dir.CreateDirectories(src_path.parent_path()));
  442. }
  443. std::filesystem::path obj_path = tmp_path / std::string_view(src_file);
  444. obj_path += ".o";
  445. BuildBuiltinsFile(target, src_file, obj_path);
  446. llvm::Expected<llvm::NewArchiveMember> obj =
  447. llvm::NewArchiveMember::getFile(obj_path.native(),
  448. /*Deterministic=*/true);
  449. CARBON_CHECK(obj, "TODO: Diagnose this: {0}",
  450. llvm::fmt_consume(obj.takeError()));
  451. objs.push_back(std::move(*obj));
  452. }
  453. // Now build an archive out of the `.o` files for the builtins.
  454. std::filesystem::path builtins_a_path = "libclang_rt.builtins.a";
  455. CARBON_ASSIGN_OR_RETURN(
  456. Filesystem::WriteFile builtins_a_file,
  457. tmp_dir.OpenWriteOnly(builtins_a_path, Filesystem::CreateAlways));
  458. {
  459. llvm::raw_fd_ostream builtins_a_os = builtins_a_file.WriteStream();
  460. llvm::Error archive_err = llvm::writeArchiveToStream(
  461. builtins_a_os, objs, llvm::SymtabWritingMode::NormalSymtab,
  462. target_triple.isOSDarwin() ? llvm::object::Archive::K_DARWIN
  463. : llvm::object::Archive::K_GNU,
  464. /*Deterministic=*/true, /*Thin=*/false);
  465. // The presence of an error is `true`.
  466. if (archive_err) {
  467. return Error(llvm::toString(std::move(archive_err)));
  468. }
  469. }
  470. CARBON_RETURN_IF_ERROR(std::move(builtins_a_file).Close());
  471. // Move it into the lib directory.
  472. CARBON_RETURN_IF_ERROR(
  473. tmp_dir.Rename(builtins_a_path, lib_dir, builtins_a_path));
  474. return Success();
  475. }
  476. } // namespace Carbon