clang_runtimes.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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/runtimes_build_info.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. CARBON_ASSIGN_OR_RETURN(bool success,
  179. builder_->clang_->RunWithNoRuntimes(args));
  180. if (!success) {
  181. return Error(
  182. llvm::formatv("Failed to compile runtime source file '{0}'", src_file));
  183. }
  184. auto obj_result = llvm::NewArchiveMember::getFile(obj_path.native(),
  185. /*Deterministic=*/true);
  186. if (!obj_result) {
  187. return Error(llvm::formatv("Unable to read `{0}` object file: {1}",
  188. src_file,
  189. llvm::fmt_consume(obj_result.takeError())));
  190. }
  191. // Only use the basename as the member name to match the behavior of `ar`. We
  192. // also specifically use the LLVM path function rather than the standard
  193. // library as it allows us to get the filename within the member-owned
  194. // filename storage.
  195. obj_result->MemberName = llvm::sys::path::filename(obj_result->MemberName);
  196. // Unlink the object file once we've read it -- we only want to retain the
  197. // copy inside the archive member and there's no advantage to using
  198. // thin-archives or something else that leaves the object file in place.
  199. // However, we log and ignore any errors here as they aren't fatal.
  200. auto unlink_result = builder_->runtimes_builder_->dir().Unlink(obj_path);
  201. if (!unlink_result.ok()) {
  202. CARBON_VLOG("Unable to unlink object file `{0}`: {1}\n", obj_path,
  203. unlink_result.error());
  204. }
  205. return std::move(*obj_result);
  206. }
  207. template <Runtimes::Component Component>
  208. requires IsClangArchiveRuntimes<Component>
  209. ClangArchiveRuntimesBuilder<Component>::ClangArchiveRuntimesBuilder(
  210. ClangRunner* clang, llvm::ThreadPoolInterface* threads,
  211. llvm::Triple target_triple, Runtimes* runtimes)
  212. : ClangRuntimesBuilderBase(clang, threads, std::move(target_triple)) {
  213. // Ensure we're on a platform where we _can_ build a working runtime.
  214. if (target_triple_.isOSWindows()) {
  215. result_ =
  216. Error("TODO: Windows runtimes are untested and not yet supported.");
  217. return;
  218. }
  219. auto build_dir_or_error = runtimes->Build(Component);
  220. if (!build_dir_or_error.ok()) {
  221. result_ = std::move(build_dir_or_error).error();
  222. return;
  223. }
  224. auto build_dir = *(std::move(build_dir_or_error));
  225. CARBON_KIND_SWITCH(std::move(build_dir)) {
  226. case CARBON_KIND(std::filesystem::path build_dir_path): {
  227. // Found cached build.
  228. result_ = std::move(build_dir_path);
  229. return;
  230. }
  231. case CARBON_KIND(Runtimes::Builder builder): {
  232. runtimes_builder_ = std::move(builder);
  233. // Building the runtimes is handled below.
  234. break;
  235. }
  236. }
  237. if constexpr (Component == Runtimes::LibUnwind) {
  238. archive_path_ = std::filesystem::path("lib") / "libunwind.a";
  239. include_paths_ = {installation().libunwind_path() / "include"};
  240. } else if constexpr (Component == Runtimes::Libcxx) {
  241. archive_path_ = std::filesystem::path("lib") / "libc++.a";
  242. include_paths_ = {
  243. installation().libcxx_path() / "include",
  244. // Some private headers of libc++ are nested in the source directory.
  245. installation().libcxx_path() / "src",
  246. installation().libcxxabi_path() / "include",
  247. // Libc++ also uses llvm-libc header-only libraries for parts of its
  248. // implementation. All the `#include`s are relative to the root of the
  249. // internal libc source tree rather than an `include` directory.
  250. installation().libc_path() / "internal",
  251. };
  252. } else {
  253. static_assert(false,
  254. "Invalid runtimes component for an archive runtime builder.");
  255. }
  256. archive_.emplace(this, archive_path_, installation().root(),
  257. CollectSrcFiles(), CollectCflags());
  258. tasks_.async([this]() mutable { Setup(); });
  259. }
  260. template <Runtimes::Component Component>
  261. requires IsClangArchiveRuntimes<Component>
  262. auto ClangArchiveRuntimesBuilder<Component>::CollectSrcFiles()
  263. -> llvm::SmallVector<llvm::StringRef> {
  264. if constexpr (Component == Runtimes::LibUnwind) {
  265. return llvm::to_vector_of<llvm::StringRef>(llvm::make_filter_range(
  266. RuntimesBuildInfo::LibunwindSrcs, [](llvm::StringRef src) {
  267. return src.ends_with(".c") || src.ends_with(".cpp") ||
  268. src.ends_with(".S");
  269. }));
  270. } else if constexpr (Component == Runtimes::Libcxx) {
  271. auto libcxx_target_srcs =
  272. target_triple_.isOSWindows()
  273. ? llvm::ArrayRef(RuntimesBuildInfo::LibcxxWin32Srcs)
  274. : target_triple_.isMacOSX()
  275. ? llvm::ArrayRef(RuntimesBuildInfo::LibcxxMacosSrcs)
  276. : llvm::ArrayRef(RuntimesBuildInfo::LibcxxLinuxSrcs);
  277. auto libcxx_srcs = llvm::make_filter_range(
  278. libcxx_target_srcs,
  279. [](llvm::StringRef src) { return src.ends_with(".cpp"); });
  280. auto libcxxabi_srcs = llvm::make_filter_range(
  281. RuntimesBuildInfo::LibcxxabiSrcs,
  282. [](llvm::StringRef src) { return src.ends_with(".cpp"); });
  283. return llvm::to_vector(
  284. llvm::concat<llvm::StringRef>(libcxx_srcs, libcxxabi_srcs));
  285. } else {
  286. static_assert(false,
  287. "Invalid runtimes component for an archive runtime builder.");
  288. }
  289. }
  290. template <Runtimes::Component Component>
  291. requires IsClangArchiveRuntimes<Component>
  292. auto ClangArchiveRuntimesBuilder<Component>::CollectCflags()
  293. -> llvm::SmallVector<llvm::StringRef> {
  294. // Start with some hard-coded flags used across any runtime.
  295. //
  296. // TODO: It would be nice to plumb through an option to enable (some) warnings
  297. // when building runtimes, especially for folks working directly on the Carbon
  298. // toolchain to validate our builds of runtimes.
  299. llvm::SmallVector<llvm::StringRef> cflags = {
  300. "-no-canonical-prefixes",
  301. "-w",
  302. };
  303. if constexpr (Component == Runtimes::LibUnwind) {
  304. llvm::append_range(cflags, RuntimesBuildInfo::LibunwindCopts);
  305. } else if constexpr (Component == Runtimes::Libcxx) {
  306. llvm::append_range(cflags, RuntimesBuildInfo::LibcxxCopts);
  307. } else {
  308. static_assert(false,
  309. "Invalid runtimes component for an archive runtime builder.");
  310. }
  311. for (const auto& include_path : include_paths_) {
  312. cflags.append({"-I", include_path.native()});
  313. }
  314. return cflags;
  315. }
  316. template <Runtimes::Component Component>
  317. requires IsClangArchiveRuntimes<Component>
  318. auto ClangArchiveRuntimesBuilder<Component>::Setup() -> void {
  319. // Finish building the runtime once the archive is built.
  320. Latch::Handle latch_handle = step_counter_.Init(
  321. [this]() mutable { tasks_.async([this]() mutable { Finish(); }); });
  322. // Start building the archive itself with a handle to detect when complete.
  323. archive_->Setup(std::move(latch_handle));
  324. }
  325. template <Runtimes::Component Component>
  326. requires IsClangArchiveRuntimes<Component>
  327. auto ClangArchiveRuntimesBuilder<Component>::Finish() -> void {
  328. CARBON_VLOG("Finished building {0}...\n", archive_path_);
  329. if (!archive_->result().ok()) {
  330. result_ = std::move(archive_->result()).error();
  331. return;
  332. }
  333. result_ = (*std::move(runtimes_builder_)).Commit();
  334. }
  335. template class ClangArchiveRuntimesBuilder<Runtimes::LibUnwind>;
  336. template class ClangArchiveRuntimesBuilder<Runtimes::Libcxx>;
  337. auto ClangResourceDirBuilder::GetDarwinOsSuffix(llvm::Triple target_triple)
  338. -> llvm::StringRef {
  339. switch (target_triple.getOS()) {
  340. case llvm::Triple::IOS:
  341. return target_triple.isSimulatorEnvironment() ? "iossim" : "ios";
  342. case llvm::Triple::WatchOS:
  343. return target_triple.isSimulatorEnvironment() ? "watchossim" : "watchos";
  344. case llvm::Triple::TvOS:
  345. return target_triple.isSimulatorEnvironment() ? "tvossim" : "tvos";
  346. case llvm::Triple::XROS:
  347. return target_triple.isSimulatorEnvironment() ? "xrossim" : "xros";
  348. default:
  349. return "osx";
  350. }
  351. }
  352. ClangResourceDirBuilder::ClangResourceDirBuilder(
  353. ClangRunner* clang, llvm::ThreadPoolInterface* threads,
  354. llvm::Triple target_triple, Runtimes* runtimes)
  355. : ClangRuntimesBuilderBase(clang, threads, std::move(target_triple)),
  356. crt_begin_result_(Error("Never built CRT begin file!")),
  357. crt_end_result_(Error("Never built CRT end file!")) {
  358. // Ensure we're on a platform where we _can_ build a working runtime.
  359. if (target_triple_.isOSWindows()) {
  360. result_ =
  361. Error("TODO: Windows runtimes are untested and not yet supported.");
  362. return;
  363. }
  364. auto build_dir_or_error = runtimes->Build(Runtimes::ClangResourceDir);
  365. if (!build_dir_or_error.ok()) {
  366. result_ = std::move(build_dir_or_error).error();
  367. return;
  368. }
  369. auto build_dir = *std::move(build_dir_or_error);
  370. if (std::holds_alternative<std::filesystem::path>(build_dir)) {
  371. // Found cached build.
  372. result_ = std::get<std::filesystem::path>(std::move(build_dir));
  373. return;
  374. }
  375. runtimes_builder_ = std::get<Runtimes::Builder>(std::move(build_dir));
  376. lib_path_ = std::filesystem::path("lib");
  377. std::filesystem::path builtins_name = "libclang_rt.builtins.a";
  378. if (target_triple.isOSDarwin()) {
  379. // Darwin targets don't use the full triple, and don't include the
  380. // architecture in the resource directory naming structure.
  381. //
  382. // TODO: We should add support for embedded Darwin as well which uses a
  383. // different layout.
  384. lib_path_ /= "darwin";
  385. // Darwin targets also use a custom naming convention for the builtins
  386. // archive.
  387. builtins_name =
  388. llvm::formatv("libclang_rt.{0}.a", GetDarwinOsSuffix(target_triple_))
  389. .str();
  390. } else {
  391. lib_path_ /= target_triple_.str();
  392. }
  393. // TODO: Currently, we only need a single include path to see headers inside
  394. // the `builtins` directory. However, we're anticipating needing more, for
  395. // example to support SipHash. If that need doesn't materialize, we should
  396. // simplify this to a single path instead of a vector.
  397. include_paths_.push_back(installation().runtimes_root() / "builtins");
  398. llvm::SmallVector<llvm::StringRef> copts = {
  399. "-no-canonical-prefixes",
  400. "-w",
  401. };
  402. llvm::append_range(copts, RuntimesBuildInfo::BuiltinsCopts);
  403. for (const auto& include_path : include_paths_) {
  404. copts.append({"-I", include_path.native()});
  405. }
  406. archive_.emplace(this, lib_path_ / builtins_name, installation().root(),
  407. CollectBuiltinsSrcFiles(), copts);
  408. tasks_.async([this]() { Setup(); });
  409. }
  410. auto ClangResourceDirBuilder::CollectBuiltinsSrcFiles()
  411. -> llvm::SmallVector<llvm::StringRef> {
  412. llvm::SmallVector<llvm::StringRef> src_files;
  413. if (target_triple_.isAArch64()) {
  414. llvm::append_range(src_files, RuntimesBuildInfo::BuiltinsAarch64Srcs);
  415. } else if (target_triple_.isX86()) {
  416. if (target_triple_.isArch64Bit()) {
  417. llvm::append_range(src_files, RuntimesBuildInfo::BuiltinsX86_64Srcs);
  418. } else {
  419. // TODO: This should be turned into a nice user-facing diagnostic about an
  420. // unsupported target.
  421. CARBON_CHECK(
  422. target_triple_.isArch32Bit(),
  423. "The Carbon toolchain doesn't currently support 16-bit x86.");
  424. llvm::append_range(src_files, RuntimesBuildInfo::BuiltinsI386Srcs);
  425. }
  426. } else {
  427. // TODO: This should be turned into a nice user-facing diagnostic about an
  428. // unsupported target.
  429. CARBON_FATAL("Target architecture is not supported: {0}",
  430. target_triple_.str());
  431. }
  432. // Only compile source files, not headers.
  433. llvm::erase_if(src_files,
  434. [](llvm::StringRef file) { return file.ends_with(".h"); });
  435. return src_files;
  436. }
  437. auto ClangResourceDirBuilder::Setup() -> void {
  438. // Symlink the installation's `include` and `share` directories.
  439. std::filesystem::path install_resource_path =
  440. installation().clang_resource_path();
  441. if (auto result = runtimes_builder_->dir().Symlink(
  442. "include", install_resource_path / "include");
  443. !result.ok()) {
  444. result_ = std::move(result).error();
  445. return;
  446. }
  447. // Create the target's `lib` directory.
  448. auto lib_dir_result = runtimes_builder_->dir().CreateDirectories(lib_path_);
  449. if (!lib_dir_result.ok()) {
  450. result_ = std::move(lib_dir_result).error();
  451. return;
  452. }
  453. lib_dir_ = *std::move(lib_dir_result);
  454. Latch::Handle latch_handle =
  455. step_counter_.Init([this] { tasks_.async([this] { Finish(); }); });
  456. // For Linux targets, the system libc (typically glibc) doesn't necessarily
  457. // provide the CRT begin/end files, and so we need to build them.
  458. if (target_triple_.isOSLinux()) {
  459. tasks_.async([this, latch_handle] {
  460. crt_begin_result_ = BuildCrtFile(RuntimesBuildInfo::CrtBegin);
  461. });
  462. tasks_.async([this, latch_handle] {
  463. crt_end_result_ = BuildCrtFile(RuntimesBuildInfo::CrtEnd);
  464. });
  465. }
  466. archive_->Setup(std::move(latch_handle));
  467. }
  468. auto ClangResourceDirBuilder::Finish() -> void {
  469. CARBON_VLOG("Finished building resource dir...\n");
  470. if (!archive_->result().ok()) {
  471. result_ = std::move(archive_->result()).error();
  472. return;
  473. }
  474. if (target_triple_.isOSLinux()) {
  475. for (ErrorOr<Success>* result : {&crt_begin_result_, &crt_end_result_}) {
  476. if (!result->ok()) {
  477. result_ = std::move(*result).error();
  478. return;
  479. }
  480. }
  481. }
  482. result_ = (*std::move(runtimes_builder_)).Commit();
  483. }
  484. auto ClangResourceDirBuilder::BuildCrtFile(llvm::StringRef src_file)
  485. -> ErrorOr<Success> {
  486. CARBON_CHECK(src_file == RuntimesBuildInfo::CrtBegin ||
  487. src_file == RuntimesBuildInfo::CrtEnd);
  488. std::filesystem::path out_path =
  489. runtimes_builder_->path() / lib_path_ /
  490. (src_file == RuntimesBuildInfo::CrtBegin ? "clang_rt.crtbegin.o"
  491. : "clang_rt.crtend.o");
  492. std::filesystem::path src_path =
  493. installation().root() / std::string_view(src_file);
  494. CARBON_VLOG("Building `{0}' from `{1}`...\n", out_path, src_path);
  495. llvm::SmallVector<llvm::StringRef> copts = {
  496. "-no-canonical-prefixes",
  497. "-w",
  498. target_flag_,
  499. };
  500. llvm::append_range(copts, RuntimesBuildInfo::CrtCopts);
  501. copts.append({
  502. "-c",
  503. "-o",
  504. out_path.native(),
  505. src_path.native(),
  506. });
  507. CARBON_ASSIGN_OR_RETURN(bool success, clang_->RunWithNoRuntimes(copts));
  508. if (success) {
  509. return Success();
  510. }
  511. return Error(llvm::formatv("Failed to compile CRT file: {0}", src_file));
  512. }
  513. } // namespace Carbon