clang_runtimes.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. However, we log and ignore
  180. // any errors here as they aren't fatal.
  181. auto unlink_result = builder_->runtimes_builder_->dir().Unlink(obj_path);
  182. if (!unlink_result.ok()) {
  183. CARBON_VLOG("Unable to unlink object file `{0}`: {1}\n", obj_path,
  184. unlink_result.error());
  185. }
  186. return std::move(*obj_result);
  187. }
  188. template <Runtimes::Component Component>
  189. requires(Component == Runtimes::LibUnwind)
  190. ClangArchiveRuntimesBuilder<Component>::ClangArchiveRuntimesBuilder(
  191. ClangRunner* clang, llvm::ThreadPoolInterface* threads,
  192. llvm::Triple target_triple, Runtimes* runtimes)
  193. : ClangRuntimesBuilderBase(clang, threads, std::move(target_triple)) {
  194. // Ensure we're on a platform where we _can_ build a working runtime.
  195. if (target_triple_.isOSWindows()) {
  196. result_ =
  197. Error("TODO: Windows runtimes are untested and not yet supported.");
  198. return;
  199. }
  200. auto build_dir_or_error = runtimes->Build(Component);
  201. if (!build_dir_or_error.ok()) {
  202. result_ = std::move(build_dir_or_error).error();
  203. return;
  204. }
  205. auto build_dir = *(std::move(build_dir_or_error));
  206. CARBON_KIND_SWITCH(std::move(build_dir)) {
  207. case CARBON_KIND(std::filesystem::path build_dir_path): {
  208. // Found cached build.
  209. result_ = std::move(build_dir_path);
  210. return;
  211. }
  212. case CARBON_KIND(Runtimes::Builder builder): {
  213. runtimes_builder_ = std::move(builder);
  214. // Building the runtimes is handled below.
  215. break;
  216. }
  217. }
  218. if constexpr (Component == Runtimes::LibUnwind) {
  219. srcs_path_ = installation().libunwind_path();
  220. include_path_ = installation().libunwind_path() / "include";
  221. archive_path_ = std::filesystem::path("lib") / "libunwind.a";
  222. } else {
  223. static_assert(false,
  224. "Invalid runtimes component for an archive runtime builder.");
  225. }
  226. archive_.emplace(this, archive_path_, srcs_path_, CollectSrcFiles(),
  227. CollectCflags());
  228. tasks_.async([this]() mutable { Setup(); });
  229. }
  230. template <Runtimes::Component Component>
  231. requires(Component == Runtimes::LibUnwind)
  232. auto ClangArchiveRuntimesBuilder<Component>::CollectSrcFiles()
  233. -> llvm::SmallVector<llvm::StringRef> {
  234. if constexpr (Component == Runtimes::LibUnwind) {
  235. return llvm::SmallVector<llvm::StringRef>(llvm::make_filter_range(
  236. RuntimeSources::LibunwindSrcs, [](llvm::StringRef src) {
  237. return src.ends_with(".c") || src.ends_with(".cpp") ||
  238. src.ends_with(".S");
  239. }));
  240. } else {
  241. static_assert(false,
  242. "Invalid runtimes component for an archive runtime builder.");
  243. }
  244. }
  245. template <Runtimes::Component Component>
  246. requires(Component == Runtimes::LibUnwind)
  247. auto ClangArchiveRuntimesBuilder<Component>::CollectCflags()
  248. -> llvm::SmallVector<llvm::StringRef> {
  249. if constexpr (Component == Runtimes::LibUnwind) {
  250. return {
  251. "-no-canonical-prefixes",
  252. "-O3",
  253. "-fPIC",
  254. "-funwind-tables",
  255. "-fno-exceptions",
  256. "-fno-rtti",
  257. "-nostdinc++",
  258. "-I",
  259. include_path_.native(),
  260. "-D_LIBUNWIND_IS_NATIVE_ONLY",
  261. "-w",
  262. };
  263. } else {
  264. static_assert(false,
  265. "Invalid runtimes component for an archive runtime builder.");
  266. }
  267. }
  268. template <Runtimes::Component Component>
  269. requires(Component == Runtimes::LibUnwind)
  270. auto ClangArchiveRuntimesBuilder<Component>::Setup() -> void {
  271. // Symlink the installation's `include` into the runtime.
  272. CARBON_CHECK(include_path_.is_absolute(),
  273. "Unexpected relative include path: {0}", include_path_);
  274. if (auto result = runtimes_builder_->dir().Symlink("include", include_path_);
  275. !result.ok()) {
  276. result_ = std::move(result).error();
  277. return;
  278. }
  279. // Finish building the runtime once the archive is built.
  280. Latch::Handle latch_handle = step_counter_.Init(
  281. [this]() mutable { tasks_.async([this]() mutable { Finish(); }); });
  282. // Start building the archive itself with a handle to detect when complete.
  283. archive_->Setup(std::move(latch_handle));
  284. }
  285. template <Runtimes::Component Component>
  286. requires(Component == Runtimes::LibUnwind)
  287. auto ClangArchiveRuntimesBuilder<Component>::Finish() -> void {
  288. CARBON_VLOG("Finished building {0}...\n", archive_path_);
  289. if (!archive_->result().ok()) {
  290. result_ = std::move(archive_->result()).error();
  291. return;
  292. }
  293. result_ = (*std::move(runtimes_builder_)).Commit();
  294. }
  295. template class ClangArchiveRuntimesBuilder<Runtimes::LibUnwind>;
  296. ClangResourceDirBuilder::ClangResourceDirBuilder(
  297. ClangRunner* clang, llvm::ThreadPoolInterface* threads,
  298. llvm::Triple target_triple, Runtimes* runtimes)
  299. : ClangRuntimesBuilderBase(clang, threads, std::move(target_triple)),
  300. crt_begin_result_(Error("Never built CRT begin file!")),
  301. crt_end_result_(Error("Never built CRT end file!")) {
  302. // Ensure we're on a platform where we _can_ build a working runtime.
  303. if (target_triple_.isOSWindows()) {
  304. result_ =
  305. Error("TODO: Windows runtimes are untested and not yet supported.");
  306. return;
  307. }
  308. auto build_dir_or_error = runtimes->Build(Runtimes::ClangResourceDir);
  309. if (!build_dir_or_error.ok()) {
  310. result_ = std::move(build_dir_or_error).error();
  311. return;
  312. }
  313. auto build_dir = *std::move(build_dir_or_error);
  314. if (std::holds_alternative<std::filesystem::path>(build_dir)) {
  315. // Found cached build.
  316. result_ = std::get<std::filesystem::path>(std::move(build_dir));
  317. return;
  318. }
  319. runtimes_builder_ = std::get<Runtimes::Builder>(std::move(build_dir));
  320. lib_path_ = std::filesystem::path("lib") / target_triple_.str();
  321. archive_.emplace(this, lib_path_ / "libclang_rt.builtins.a",
  322. installation().llvm_runtime_srcs(),
  323. CollectBuiltinsSrcFiles(), /*cflags=*/
  324. llvm::SmallVector<llvm::StringRef>{
  325. "-no-canonical-prefixes",
  326. "-O3",
  327. "-fPIC",
  328. "-ffreestanding",
  329. "-fno-builtin",
  330. "-fomit-frame-pointer",
  331. "-fvisibility=hidden",
  332. "-w",
  333. });
  334. tasks_.async([this]() { Setup(); });
  335. }
  336. auto ClangResourceDirBuilder::CollectBuiltinsSrcFiles()
  337. -> llvm::SmallVector<llvm::StringRef> {
  338. llvm::SmallVector<llvm::StringRef> src_files;
  339. auto append_src_files =
  340. [&](auto input_srcs,
  341. llvm::function_ref<bool(llvm::StringRef)> filter_out = {}) {
  342. for (llvm::StringRef input_src : input_srcs) {
  343. if (!input_src.ends_with(".c") && !input_src.ends_with(".S")) {
  344. // Not a compiled file.
  345. continue;
  346. }
  347. if (filter_out && filter_out(input_src)) {
  348. // Filtered out.
  349. continue;
  350. }
  351. src_files.push_back(input_src);
  352. }
  353. };
  354. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsGenericSrcs));
  355. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsBf16Srcs));
  356. if (target_triple_.isArch64Bit()) {
  357. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsTfSrcs));
  358. }
  359. auto filter_out_chkstk = [&](llvm::StringRef src) {
  360. return !target_triple_.isOSWindows() || !src.ends_with("chkstk.S");
  361. };
  362. if (target_triple_.isAArch64()) {
  363. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsAarch64Srcs),
  364. filter_out_chkstk);
  365. } else if (target_triple_.isX86()) {
  366. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsX86ArchSrcs));
  367. if (target_triple_.isArch64Bit()) {
  368. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsX86_64Srcs),
  369. filter_out_chkstk);
  370. } else {
  371. // TODO: This should be turned into a nice user-facing diagnostic about an
  372. // unsupported target.
  373. CARBON_CHECK(
  374. target_triple_.isArch32Bit(),
  375. "The Carbon toolchain doesn't currently support 16-bit x86.");
  376. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsI386Srcs),
  377. filter_out_chkstk);
  378. }
  379. } else {
  380. // TODO: This should be turned into a nice user-facing diagnostic about an
  381. // unsupported target.
  382. CARBON_FATAL("Target architecture is not supported: {0}",
  383. target_triple_.str());
  384. }
  385. return src_files;
  386. }
  387. auto ClangResourceDirBuilder::Setup() -> void {
  388. // Symlink the installation's `include` and `share` directories.
  389. std::filesystem::path install_resource_path =
  390. installation().clang_resource_path();
  391. if (auto result = runtimes_builder_->dir().Symlink(
  392. "include", install_resource_path / "include");
  393. !result.ok()) {
  394. result_ = std::move(result).error();
  395. return;
  396. }
  397. if (auto result = runtimes_builder_->dir().Symlink(
  398. "share", install_resource_path / "share");
  399. !result.ok()) {
  400. result_ = std::move(result).error();
  401. return;
  402. }
  403. // Create the target's `lib` directory.
  404. auto lib_dir_result = runtimes_builder_->dir().CreateDirectories(lib_path_);
  405. if (!lib_dir_result.ok()) {
  406. result_ = std::move(lib_dir_result).error();
  407. return;
  408. }
  409. lib_dir_ = *std::move(lib_dir_result);
  410. Latch::Handle latch_handle =
  411. step_counter_.Init([this] { tasks_.async([this] { Finish(); }); });
  412. // For Linux targets, the system libc (typically glibc) doesn't necessarily
  413. // provide the CRT begin/end files, and so we need to build them.
  414. if (target_triple_.isOSLinux()) {
  415. tasks_.async([this, latch_handle] {
  416. crt_begin_result_ = BuildCrtFile(RuntimeSources::CrtBegin);
  417. });
  418. tasks_.async([this, latch_handle] {
  419. crt_end_result_ = BuildCrtFile(RuntimeSources::CrtEnd);
  420. });
  421. }
  422. archive_->Setup(std::move(latch_handle));
  423. }
  424. auto ClangResourceDirBuilder::Finish() -> void {
  425. CARBON_VLOG("Finished building resource dir...\n");
  426. if (!archive_->result().ok()) {
  427. result_ = std::move(archive_->result()).error();
  428. return;
  429. }
  430. if (target_triple_.isOSLinux()) {
  431. for (ErrorOr<Success>* result : {&crt_begin_result_, &crt_end_result_}) {
  432. if (!result->ok()) {
  433. result_ = std::move(*result).error();
  434. return;
  435. }
  436. }
  437. }
  438. result_ = (*std::move(runtimes_builder_)).Commit();
  439. }
  440. auto ClangResourceDirBuilder::BuildCrtFile(llvm::StringRef src_file)
  441. -> ErrorOr<Success> {
  442. CARBON_CHECK(src_file == RuntimeSources::CrtBegin ||
  443. src_file == RuntimeSources::CrtEnd);
  444. std::filesystem::path out_path =
  445. runtimes_builder_->path() / lib_path_ /
  446. (src_file == RuntimeSources::CrtBegin ? "clang_rt.crtbegin.o"
  447. : "clang_rt.crtend.o");
  448. std::filesystem::path src_path =
  449. installation().llvm_runtime_srcs() / std::string_view(src_file);
  450. CARBON_VLOG("Building `{0}' from `{1}`...\n", out_path, src_path);
  451. bool success = clang_->RunWithNoRuntimes({
  452. "-no-canonical-prefixes",
  453. "-DCRT_HAS_INITFINI_ARRAY",
  454. "-DEH_USE_FRAME_REGISTRY",
  455. "-O3",
  456. "-fPIC",
  457. "-ffreestanding",
  458. "-std=c11",
  459. "-w",
  460. "-c",
  461. target_flag_,
  462. "-o",
  463. out_path.native(),
  464. src_path.native(),
  465. });
  466. if (success) {
  467. return Success();
  468. }
  469. return Error(llvm::formatv("Failed to compile CRT file: {0}", src_file));
  470. }
  471. } // namespace Carbon