clang_runtimes.cpp 19 KB

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