clang_runtimes.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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_runtimes.h"
  5. #include <unistd.h>
  6. #include <algorithm>
  7. #include <filesystem>
  8. #include <functional>
  9. #include <mutex>
  10. #include <numeric>
  11. #include <optional>
  12. #include <string_view>
  13. #include <utility>
  14. #include <variant>
  15. #include "common/check.h"
  16. #include "common/error.h"
  17. #include "common/filesystem.h"
  18. #include "common/latch.h"
  19. #include "common/vlog.h"
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/STLFunctionalExtras.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/Object/Archive.h"
  27. #include "llvm/Object/ArchiveWriter.h"
  28. #include "llvm/Support/Error.h"
  29. #include "llvm/Support/FormatAdapters.h"
  30. #include "llvm/Support/FormatVariadic.h"
  31. #include "llvm/Support/Path.h"
  32. #include "llvm/Support/ThreadPool.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/TargetParser/Host.h"
  35. #include "llvm/TargetParser/Triple.h"
  36. #include "toolchain/base/kind_switch.h"
  37. #include "toolchain/base/runtime_sources.h"
  38. #include "toolchain/driver/clang_runner.h"
  39. #include "toolchain/driver/runtimes_cache.h"
  40. namespace Carbon {
  41. auto ClangRuntimesBuilderBase::ArchiveBuilder::Setup(Latch::Handle latch_handle)
  42. -> void {
  43. // `NewArchiveMember` isn't default constructable unfortunately, so we have to
  44. // manually populate the vector with errors that we'll replace with the actual
  45. // result in each thread.
  46. objs_.reserve(src_files_.size());
  47. for (const auto& _ : src_files_) {
  48. objs_.push_back(Error("Never constructed archive member!"));
  49. }
  50. // Finish building the archive when the last compile finishes.
  51. Latch::Handle comp_latch_handle =
  52. compilation_latch_.Init([this, latch_handle] { result_ = Finish(); });
  53. // Add all the compiles to the thread pool to run concurrently. The latch
  54. // handle ensures the last one triggers the finishing closure above.
  55. for (auto [src_file, obj] : llvm::zip_equal(src_files_, objs_)) {
  56. builder_->tasks_.async([this, comp_latch_handle, src_file, &obj]() mutable {
  57. obj = CompileMember(src_file);
  58. });
  59. }
  60. }
  61. auto ClangRuntimesBuilderBase::ArchiveBuilder::Finish() -> ErrorOr<Success> {
  62. // We build this directly into the desired location as this is expected to be
  63. // a staging directory and cleaned up on errors. We do need to create any
  64. // intermediate directories.
  65. Filesystem::DirRef runtimes_dir = builder_->runtimes_builder_->dir();
  66. if (archive_path_.has_parent_path()) {
  67. CARBON_RETURN_IF_ERROR(
  68. runtimes_dir.CreateDirectories(archive_path_.parent_path()));
  69. }
  70. // Check if any compilations ended up producing an error. If so, return the
  71. // first error for the entire function. Otherwise, move the archive member
  72. // into a direct vector to match the required archive building API.
  73. llvm::SmallVector<llvm::NewArchiveMember> unwrapped_objs;
  74. unwrapped_objs.reserve(objs_.size());
  75. for (auto& obj : objs_) {
  76. if (!obj.ok()) {
  77. return std::move(obj).error();
  78. }
  79. unwrapped_objs.push_back(*std::move(obj));
  80. }
  81. objs_.clear();
  82. // Remove any directories created for the object files, the files should
  83. // already be removed. We walk the sorted list of these in reverse so we
  84. // remove child directories before parent directories.
  85. for (const auto& obj_dir : llvm::reverse(obj_dirs_)) {
  86. auto rmdir_result = runtimes_dir.Rmdir(obj_dir);
  87. // Don't return an error on failure here as this has no problematic
  88. // effect, just log that we couldn't clean up a directory.
  89. if (!rmdir_result.ok()) {
  90. CARBON_VLOG("Unable to remove object directory `{0}` in the runtime: {1}",
  91. obj_dir.native(), rmdir_result.error());
  92. }
  93. }
  94. // Write the actual archive.
  95. CARBON_ASSIGN_OR_RETURN(
  96. Filesystem::WriteFile archive_file,
  97. runtimes_dir.OpenWriteOnly(archive_path_, Filesystem::CreateAlways));
  98. {
  99. llvm::raw_fd_ostream archive_os = archive_file.WriteStream();
  100. llvm::Error archive_err = llvm::writeArchiveToStream(
  101. archive_os, unwrapped_objs, llvm::SymtabWritingMode::NormalSymtab,
  102. builder_->target_triple_.isOSDarwin() ? llvm::object::Archive::K_DARWIN
  103. : llvm::object::Archive::K_GNU,
  104. /*Deterministic=*/true, /*Thin=*/false);
  105. // The presence of an error is `true`.
  106. if (archive_err) {
  107. (void)std::move(archive_file).Close();
  108. return Error(llvm::toString(std::move(archive_err)));
  109. }
  110. }
  111. // Close and return any errors, potentially from the writes above.
  112. CARBON_RETURN_IF_ERROR(std::move(archive_file).Close());
  113. return Success();
  114. }
  115. auto ClangRuntimesBuilderBase::ArchiveBuilder::CreateObjDir(
  116. const std::filesystem::path& src_path) -> ErrorOr<Success> {
  117. auto obj_dir_path = src_path.parent_path();
  118. if (obj_dir_path.empty()) {
  119. return Success();
  120. }
  121. std::scoped_lock lock(obj_dirs_mu_);
  122. auto* it = std::lower_bound(obj_dirs_.begin(), obj_dirs_.end(), obj_dir_path);
  123. if (it != obj_dirs_.end() && *it == obj_dir_path) {
  124. return Success();
  125. }
  126. auto create_result =
  127. builder_->runtimes_builder_->dir().CreateDirectories(obj_dir_path);
  128. if (!create_result.ok()) {
  129. return Error(llvm::formatv(
  130. "Unable to create object directory mirroring source file `{0}`: {1}",
  131. src_path, create_result.error()));
  132. }
  133. it = obj_dirs_.insert(it, obj_dir_path);
  134. // Also insert any parent paths. These should always sort earlier.
  135. CARBON_DCHECK(!obj_dir_path.has_parent_path() ||
  136. obj_dir_path.parent_path() < obj_dir_path);
  137. obj_dir_path = obj_dir_path.parent_path();
  138. while (!obj_dir_path.empty()) {
  139. it = std::lower_bound(obj_dirs_.begin(), it, obj_dir_path);
  140. if (*it != obj_dir_path) {
  141. it = obj_dirs_.insert(it, obj_dir_path);
  142. }
  143. obj_dir_path = obj_dir_path.parent_path();
  144. }
  145. return Success();
  146. }
  147. auto ClangRuntimesBuilderBase::ArchiveBuilder::CompileMember(
  148. llvm::StringRef src_file) -> ErrorOr<llvm::NewArchiveMember> {
  149. // Create any obj subdirectories needed for this file.
  150. CARBON_RETURN_IF_ERROR(CreateObjDir(src_file.str()));
  151. std::filesystem::path src_path = srcs_root_ / std::string_view(src_file);
  152. std::filesystem::path obj_path =
  153. builder_->runtimes_builder_->path() / std::string_view(src_file);
  154. obj_path += ".o";
  155. CARBON_VLOG("Building `{0}' from `{1}`...\n", obj_path, src_file);
  156. llvm::SmallVector<llvm::StringRef> args(cflags_);
  157. // Add language-specific flags based on file extension.
  158. //
  159. // Currently, we hard code a sufficiently "recent" C++ standard, but this is
  160. // arbitrary and brittle. We'll have to update these any time one of the
  161. // libraries uses a too-new feature.
  162. //
  163. // TODO: We should eventually switch to something more like `/std:c++latest`
  164. // in MSVC-style command lines, but would need that implemented in Clang.
  165. if (src_file.ends_with(".c")) {
  166. args.push_back("-std=c11");
  167. } else if (src_file.ends_with(".cpp")) {
  168. args.push_back("-std=c++26");
  169. }
  170. // Collect the additional required flags and dynamic flags for this builder.
  171. args.append({
  172. "-c",
  173. builder_->target_flag_,
  174. "-o",
  175. obj_path.native(),
  176. src_path.native(),
  177. });
  178. if (!builder_->clang_->RunWithNoRuntimes(args)) {
  179. return Error(
  180. llvm::formatv("Failed to compile runtime source file '{0}'", src_file));
  181. }
  182. auto obj_result = llvm::NewArchiveMember::getFile(obj_path.native(),
  183. /*Deterministic=*/true);
  184. if (!obj_result) {
  185. return Error(llvm::formatv("Unable to read `{0}` object file: {1}",
  186. src_file,
  187. llvm::fmt_consume(obj_result.takeError())));
  188. }
  189. // Only use the basename as the member name to match the behavior of `ar`. We
  190. // also specifically use the LLVM path function rather than the standard
  191. // library as it allows us to get the filename within the member-owned
  192. // filename storage.
  193. obj_result->MemberName = llvm::sys::path::filename(obj_result->MemberName);
  194. // Unlink the object file once we've read it -- we only want to retain the
  195. // copy inside the archive member and there's no advantage to using
  196. // thin-archives or something else that leaves the object file in place.
  197. // However, we log and ignore any errors here as they aren't fatal.
  198. auto unlink_result = builder_->runtimes_builder_->dir().Unlink(obj_path);
  199. if (!unlink_result.ok()) {
  200. CARBON_VLOG("Unable to unlink object file `{0}`: {1}\n", obj_path,
  201. unlink_result.error());
  202. }
  203. return std::move(*obj_result);
  204. }
  205. template <Runtimes::Component Component>
  206. requires IsClangArchiveRuntimes<Component>
  207. ClangArchiveRuntimesBuilder<Component>::ClangArchiveRuntimesBuilder(
  208. ClangRunner* clang, llvm::ThreadPoolInterface* threads,
  209. llvm::Triple target_triple, Runtimes* runtimes)
  210. : ClangRuntimesBuilderBase(clang, threads, std::move(target_triple)) {
  211. // Ensure we're on a platform where we _can_ build a working runtime.
  212. if (target_triple_.isOSWindows()) {
  213. result_ =
  214. Error("TODO: Windows runtimes are untested and not yet supported.");
  215. return;
  216. }
  217. auto build_dir_or_error = runtimes->Build(Component);
  218. if (!build_dir_or_error.ok()) {
  219. result_ = std::move(build_dir_or_error).error();
  220. return;
  221. }
  222. auto build_dir = *(std::move(build_dir_or_error));
  223. CARBON_KIND_SWITCH(std::move(build_dir)) {
  224. case CARBON_KIND(std::filesystem::path build_dir_path): {
  225. // Found cached build.
  226. result_ = std::move(build_dir_path);
  227. return;
  228. }
  229. case CARBON_KIND(Runtimes::Builder builder): {
  230. runtimes_builder_ = std::move(builder);
  231. // Building the runtimes is handled below.
  232. break;
  233. }
  234. }
  235. if constexpr (Component == Runtimes::LibUnwind) {
  236. archive_path_ = std::filesystem::path("lib") / "libunwind.a";
  237. include_paths_ = {installation().libunwind_path() / "include"};
  238. } else if constexpr (Component == Runtimes::Libcxx) {
  239. archive_path_ = std::filesystem::path("lib") / "libc++.a";
  240. include_paths_ = {
  241. installation().libcxx_path() / "include",
  242. // Some private headers of libc++ are nested in the source directory.
  243. installation().libcxx_path() / "src",
  244. installation().libcxxabi_path() / "include",
  245. // Libc++ also uses llvm-libc header-only libraries for parts of its
  246. // implementation. All the `#include`s are relative to the root of the
  247. // internal libc source tree rather than an `include` directory.
  248. installation().libc_path() / "internal",
  249. };
  250. } else {
  251. static_assert(false,
  252. "Invalid runtimes component for an archive runtime builder.");
  253. }
  254. archive_.emplace(this, archive_path_, installation().runtimes_root(),
  255. CollectSrcFiles(), CollectCflags());
  256. tasks_.async([this]() mutable { Setup(); });
  257. }
  258. template <Runtimes::Component Component>
  259. requires IsClangArchiveRuntimes<Component>
  260. auto ClangArchiveRuntimesBuilder<Component>::CollectSrcFiles()
  261. -> llvm::SmallVector<llvm::StringRef> {
  262. if constexpr (Component == Runtimes::LibUnwind) {
  263. return llvm::to_vector_of<llvm::StringRef>(llvm::make_filter_range(
  264. RuntimeSources::LibunwindSrcs, [](llvm::StringRef src) {
  265. return src.ends_with(".c") || src.ends_with(".cpp") ||
  266. src.ends_with(".S");
  267. }));
  268. } else if constexpr (Component == Runtimes::Libcxx) {
  269. auto libcxx_srcs = llvm::make_filter_range(
  270. RuntimeSources::LibcxxSrcs, [this](llvm::StringRef src) {
  271. if (!src.ends_with(".cpp")) {
  272. return false;
  273. }
  274. // We include libc++abi and so don't need new/delete definitions.
  275. if (src == "libcxx/src/new.cpp") {
  276. return false;
  277. }
  278. // We use compiler-rt for builtins, so we don't need int128 helpers.
  279. if (src == "libcxx/src/filesystem/int128_builtins.cpp") {
  280. return false;
  281. }
  282. // We don't currently use the libdispatch PSTL backend.
  283. // TODO: We should evaluate enabling this on macOS.
  284. if (src == "libcxx/src/pstl/libdispatch.cpp") {
  285. return false;
  286. }
  287. // Skip platform-specific code for unsupported platforms.
  288. // TODO: We should revisit this and include the code for these targets
  289. // along with testing to make sure it works.
  290. if (src.starts_with("libcxx/src/support/ibm/") ||
  291. src.starts_with("libcxx/src/support/win32/")) {
  292. return false;
  293. }
  294. // The timezone database is currently only enabled on Linux in
  295. // upstream.
  296. if (!target_triple_.isOSLinux() &&
  297. (src == "libcxx/src/experimental/chrono_exception.cpp" ||
  298. src == "libcxx/src/experimental/time_zone.cpp" ||
  299. src == "libcxx/src/experimental/tzdb.cpp" ||
  300. src == "libcxx/src/experimental/tzdb_list.cpp")) {
  301. return false;
  302. }
  303. return true;
  304. });
  305. auto libcxxabi_srcs = llvm::make_filter_range(
  306. RuntimeSources::LibcxxabiSrcs,
  307. [](llvm::StringRef src) { return src.ends_with(".cpp"); });
  308. return llvm::to_vector(
  309. llvm::concat<llvm::StringRef>(libcxx_srcs, libcxxabi_srcs));
  310. } else {
  311. static_assert(false,
  312. "Invalid runtimes component for an archive runtime builder.");
  313. }
  314. }
  315. template <Runtimes::Component Component>
  316. requires IsClangArchiveRuntimes<Component>
  317. auto ClangArchiveRuntimesBuilder<Component>::CollectCflags()
  318. -> llvm::SmallVector<llvm::StringRef> {
  319. llvm::SmallVector<llvm::StringRef> cflags;
  320. // TODO: It would be nice to plumb through an option to enable (some) warnings
  321. // when building runtimes, especially for folks working directly on the Carbon
  322. // toolchain to validate our builds of runtimes.
  323. if constexpr (Component == Runtimes::LibUnwind) {
  324. // TODO: Should libunwind also limit symbol visibility?
  325. cflags = {
  326. "-no-canonical-prefixes",
  327. "-D_LIBUNWIND_IS_NATIVE_ONLY",
  328. "-O3",
  329. "-fPIC",
  330. "-fno-exceptions",
  331. "-fno-rtti",
  332. "-funwind-tables",
  333. "-nostdinc++",
  334. "-w",
  335. };
  336. } else if constexpr (Component == Runtimes::Libcxx) {
  337. cflags = {
  338. "-no-canonical-prefixes",
  339. "-DLIBCXX_BUILDING_LIBCXXABI",
  340. "-D_LIBCPP_BUILDING_LIBRARY",
  341. "-D_LIBCPP_REMOVE_TRANSITIVE_INCLUDES",
  342. "-O3",
  343. "-fPIC",
  344. "-fvisibility-inlines-hidden",
  345. "-fvisibility=hidden",
  346. "-nostdinc++",
  347. "-w",
  348. };
  349. } else {
  350. static_assert(false,
  351. "Invalid runtimes component for an archive runtime builder.");
  352. }
  353. for (const auto& include_path : include_paths_) {
  354. cflags.append({"-I", include_path.native()});
  355. }
  356. return cflags;
  357. }
  358. template <Runtimes::Component Component>
  359. requires IsClangArchiveRuntimes<Component>
  360. auto ClangArchiveRuntimesBuilder<Component>::Setup() -> void {
  361. // Finish building the runtime once the archive is built.
  362. Latch::Handle latch_handle = step_counter_.Init(
  363. [this]() mutable { tasks_.async([this]() mutable { Finish(); }); });
  364. // Start building the archive itself with a handle to detect when complete.
  365. archive_->Setup(std::move(latch_handle));
  366. }
  367. template <Runtimes::Component Component>
  368. requires IsClangArchiveRuntimes<Component>
  369. auto ClangArchiveRuntimesBuilder<Component>::Finish() -> void {
  370. CARBON_VLOG("Finished building {0}...\n", archive_path_);
  371. if (!archive_->result().ok()) {
  372. result_ = std::move(archive_->result()).error();
  373. return;
  374. }
  375. result_ = (*std::move(runtimes_builder_)).Commit();
  376. }
  377. template class ClangArchiveRuntimesBuilder<Runtimes::LibUnwind>;
  378. template class ClangArchiveRuntimesBuilder<Runtimes::Libcxx>;
  379. ClangResourceDirBuilder::ClangResourceDirBuilder(
  380. ClangRunner* clang, llvm::ThreadPoolInterface* threads,
  381. llvm::Triple target_triple, Runtimes* runtimes)
  382. : ClangRuntimesBuilderBase(clang, threads, std::move(target_triple)),
  383. crt_begin_result_(Error("Never built CRT begin file!")),
  384. crt_end_result_(Error("Never built CRT end file!")) {
  385. // Ensure we're on a platform where we _can_ build a working runtime.
  386. if (target_triple_.isOSWindows()) {
  387. result_ =
  388. Error("TODO: Windows runtimes are untested and not yet supported.");
  389. return;
  390. }
  391. auto build_dir_or_error = runtimes->Build(Runtimes::ClangResourceDir);
  392. if (!build_dir_or_error.ok()) {
  393. result_ = std::move(build_dir_or_error).error();
  394. return;
  395. }
  396. auto build_dir = *std::move(build_dir_or_error);
  397. if (std::holds_alternative<std::filesystem::path>(build_dir)) {
  398. // Found cached build.
  399. result_ = std::get<std::filesystem::path>(std::move(build_dir));
  400. return;
  401. }
  402. runtimes_builder_ = std::get<Runtimes::Builder>(std::move(build_dir));
  403. lib_path_ = std::filesystem::path("lib") / target_triple_.str();
  404. archive_.emplace(this, lib_path_ / "libclang_rt.builtins.a",
  405. installation().runtimes_root(),
  406. CollectBuiltinsSrcFiles(), /*cflags=*/
  407. llvm::SmallVector<llvm::StringRef>{
  408. "-no-canonical-prefixes",
  409. "-O3",
  410. "-fPIC",
  411. "-ffreestanding",
  412. "-fno-builtin",
  413. "-fomit-frame-pointer",
  414. "-fvisibility=hidden",
  415. "-w",
  416. });
  417. tasks_.async([this]() { Setup(); });
  418. }
  419. auto ClangResourceDirBuilder::CollectBuiltinsSrcFiles()
  420. -> llvm::SmallVector<llvm::StringRef> {
  421. llvm::SmallVector<llvm::StringRef> src_files;
  422. auto append_src_files =
  423. [&](auto input_srcs,
  424. llvm::function_ref<bool(llvm::StringRef)> filter_out = {}) {
  425. for (llvm::StringRef input_src : input_srcs) {
  426. if (!input_src.ends_with(".c") && !input_src.ends_with(".S")) {
  427. // Not a compiled file.
  428. continue;
  429. }
  430. if (filter_out && filter_out(input_src)) {
  431. // Filtered out.
  432. continue;
  433. }
  434. src_files.push_back(input_src);
  435. }
  436. };
  437. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsGenericSrcs));
  438. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsBf16Srcs));
  439. if (target_triple_.isArch64Bit()) {
  440. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsTfSrcs));
  441. }
  442. auto filter_out_chkstk = [&](llvm::StringRef src) {
  443. return !target_triple_.isOSWindows() || !src.ends_with("chkstk.S");
  444. };
  445. if (target_triple_.isAArch64()) {
  446. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsAarch64Srcs),
  447. filter_out_chkstk);
  448. } else if (target_triple_.isX86()) {
  449. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsX86ArchSrcs));
  450. if (target_triple_.isArch64Bit()) {
  451. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsX86_64Srcs),
  452. filter_out_chkstk);
  453. } else {
  454. // TODO: This should be turned into a nice user-facing diagnostic about an
  455. // unsupported target.
  456. CARBON_CHECK(
  457. target_triple_.isArch32Bit(),
  458. "The Carbon toolchain doesn't currently support 16-bit x86.");
  459. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsI386Srcs),
  460. filter_out_chkstk);
  461. }
  462. } else {
  463. // TODO: This should be turned into a nice user-facing diagnostic about an
  464. // unsupported target.
  465. CARBON_FATAL("Target architecture is not supported: {0}",
  466. target_triple_.str());
  467. }
  468. return src_files;
  469. }
  470. auto ClangResourceDirBuilder::Setup() -> void {
  471. // Symlink the installation's `include` and `share` directories.
  472. std::filesystem::path install_resource_path =
  473. installation().clang_resource_path();
  474. if (auto result = runtimes_builder_->dir().Symlink(
  475. "include", install_resource_path / "include");
  476. !result.ok()) {
  477. result_ = std::move(result).error();
  478. return;
  479. }
  480. if (auto result = runtimes_builder_->dir().Symlink(
  481. "share", install_resource_path / "share");
  482. !result.ok()) {
  483. result_ = std::move(result).error();
  484. return;
  485. }
  486. // Create the target's `lib` directory.
  487. auto lib_dir_result = runtimes_builder_->dir().CreateDirectories(lib_path_);
  488. if (!lib_dir_result.ok()) {
  489. result_ = std::move(lib_dir_result).error();
  490. return;
  491. }
  492. lib_dir_ = *std::move(lib_dir_result);
  493. Latch::Handle latch_handle =
  494. step_counter_.Init([this] { tasks_.async([this] { Finish(); }); });
  495. // For Linux targets, the system libc (typically glibc) doesn't necessarily
  496. // provide the CRT begin/end files, and so we need to build them.
  497. if (target_triple_.isOSLinux()) {
  498. tasks_.async([this, latch_handle] {
  499. crt_begin_result_ = BuildCrtFile(RuntimeSources::CrtBegin);
  500. });
  501. tasks_.async([this, latch_handle] {
  502. crt_end_result_ = BuildCrtFile(RuntimeSources::CrtEnd);
  503. });
  504. }
  505. archive_->Setup(std::move(latch_handle));
  506. }
  507. auto ClangResourceDirBuilder::Finish() -> void {
  508. CARBON_VLOG("Finished building resource dir...\n");
  509. if (!archive_->result().ok()) {
  510. result_ = std::move(archive_->result()).error();
  511. return;
  512. }
  513. if (target_triple_.isOSLinux()) {
  514. for (ErrorOr<Success>* result : {&crt_begin_result_, &crt_end_result_}) {
  515. if (!result->ok()) {
  516. result_ = std::move(*result).error();
  517. return;
  518. }
  519. }
  520. }
  521. result_ = (*std::move(runtimes_builder_)).Commit();
  522. }
  523. auto ClangResourceDirBuilder::BuildCrtFile(llvm::StringRef src_file)
  524. -> ErrorOr<Success> {
  525. CARBON_CHECK(src_file == RuntimeSources::CrtBegin ||
  526. src_file == RuntimeSources::CrtEnd);
  527. std::filesystem::path out_path =
  528. runtimes_builder_->path() / lib_path_ /
  529. (src_file == RuntimeSources::CrtBegin ? "clang_rt.crtbegin.o"
  530. : "clang_rt.crtend.o");
  531. std::filesystem::path src_path =
  532. installation().runtimes_root() / std::string_view(src_file);
  533. CARBON_VLOG("Building `{0}' from `{1}`...\n", out_path, src_path);
  534. bool success = clang_->RunWithNoRuntimes({
  535. "-no-canonical-prefixes",
  536. "-DCRT_HAS_INITFINI_ARRAY",
  537. "-DEH_USE_FRAME_REGISTRY",
  538. "-O3",
  539. "-fPIC",
  540. "-ffreestanding",
  541. "-std=c11",
  542. "-w",
  543. "-c",
  544. target_flag_,
  545. "-o",
  546. out_path.native(),
  547. src_path.native(),
  548. });
  549. if (success) {
  550. return Success();
  551. }
  552. return Error(llvm::formatv("Failed to compile CRT file: {0}", src_file));
  553. }
  554. } // namespace Carbon