]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Use BOLT in x64 dist CI to optimize LLVM
[rust.git] / src / bootstrap / native.rs
1 //! Compilation of native dependencies like LLVM.
2 //!
3 //! Native projects like LLVM unfortunately aren't suited just yet for
4 //! compilation in build scripts that Cargo has. This is because the
5 //! compilation takes a *very* long time but also because we don't want to
6 //! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
7 //!
8 //! LLVM and compiler-rt are essentially just wired up to everything else to
9 //! ensure that they're always in place if needed.
10
11 use std::env;
12 use std::env::consts::EXE_EXTENSION;
13 use std::ffi::{OsStr, OsString};
14 use std::fs::{self, File};
15 use std::io;
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
18
19 use crate::bolt::{instrument_with_bolt_inplace, optimize_library_with_bolt_inplace};
20 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
21 use crate::config::TargetSelection;
22 use crate::util::get_clang_cl_resource_dir;
23 use crate::util::{self, exe, output, program_out_of_date, t, up_to_date};
24 use crate::{CLang, GitRepo};
25
26 pub struct Meta {
27     stamp: HashStamp,
28     build_llvm_config: PathBuf,
29     out_dir: PathBuf,
30     root: String,
31 }
32
33 // Linker flags to pass to LLVM's CMake invocation.
34 #[derive(Debug, Clone, Default)]
35 struct LdFlags {
36     // CMAKE_EXE_LINKER_FLAGS
37     exe: OsString,
38     // CMAKE_SHARED_LINKER_FLAGS
39     shared: OsString,
40     // CMAKE_MODULE_LINKER_FLAGS
41     module: OsString,
42 }
43
44 impl LdFlags {
45     fn push_all(&mut self, s: impl AsRef<OsStr>) {
46         let s = s.as_ref();
47         self.exe.push(" ");
48         self.exe.push(s);
49         self.shared.push(" ");
50         self.shared.push(s);
51         self.module.push(" ");
52         self.module.push(s);
53     }
54 }
55
56 // This returns whether we've already previously built LLVM.
57 //
58 // It's used to avoid busting caches during x.py check -- if we've already built
59 // LLVM, it's fine for us to not try to avoid doing so.
60 //
61 // This will return the llvm-config if it can get it (but it will not build it
62 // if not).
63 pub fn prebuilt_llvm_config(
64     builder: &Builder<'_>,
65     target: TargetSelection,
66 ) -> Result<PathBuf, Meta> {
67     maybe_download_ci_llvm(builder);
68
69     // If we're using a custom LLVM bail out here, but we can only use a
70     // custom LLVM for the build triple.
71     if let Some(config) = builder.config.target_config.get(&target) {
72         if let Some(ref s) = config.llvm_config {
73             check_llvm_version(builder, s);
74             return Ok(s.to_path_buf());
75         }
76     }
77
78     let root = "src/llvm-project/llvm";
79     let out_dir = builder.llvm_out(target);
80
81     let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
82     if !builder.config.build.contains("msvc") || builder.ninja() {
83         llvm_config_ret_dir.push("build");
84     }
85     llvm_config_ret_dir.push("bin");
86
87     let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
88
89     let stamp = out_dir.join("llvm-finished-building");
90     let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
91
92     if builder.config.llvm_skip_rebuild && stamp.path.exists() {
93         builder.info(
94             "Warning: \
95                 Using a potentially stale build of LLVM; \
96                 This may not behave well.",
97         );
98         return Ok(build_llvm_config);
99     }
100
101     if stamp.is_done() {
102         if stamp.hash.is_none() {
103             builder.info(
104                 "Could not determine the LLVM submodule commit hash. \
105                      Assuming that an LLVM rebuild is not necessary.",
106             );
107             builder.info(&format!(
108                 "To force LLVM to rebuild, remove the file `{}`",
109                 stamp.path.display()
110             ));
111         }
112         return Ok(build_llvm_config);
113     }
114
115     Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
116 }
117
118 /// This retrieves the LLVM sha we *want* to use, according to git history.
119 pub(crate) fn detect_llvm_sha(config: &crate::config::Config) -> String {
120     let mut rev_list = config.git();
121     rev_list.args(&[
122         PathBuf::from("rev-list"),
123         format!("--author={}", config.stage0_metadata.config.git_merge_commit_email).into(),
124         "-n1".into(),
125         "--first-parent".into(),
126         "HEAD".into(),
127         "--".into(),
128         config.src.join("src/llvm-project"),
129         config.src.join("src/bootstrap/download-ci-llvm-stamp"),
130         // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
131         config.src.join("src/version"),
132     ]);
133     let llvm_sha = output(&mut rev_list);
134     let llvm_sha = llvm_sha.trim();
135
136     if llvm_sha == "" {
137         eprintln!("error: could not find commit hash for downloading LLVM");
138         eprintln!("help: maybe your repository history is too shallow?");
139         eprintln!("help: consider disabling `download-ci-llvm`");
140         eprintln!("help: or fetch enough history to include one upstream commit");
141         panic!();
142     }
143
144     llvm_sha.to_owned()
145 }
146
147 /// Returns whether the CI-found LLVM is currently usable.
148 ///
149 /// This checks both the build triple platform to confirm we're usable at all,
150 /// and then verifies if the current HEAD matches the detected LLVM SHA head,
151 /// in which case LLVM is indicated as not available.
152 pub(crate) fn is_ci_llvm_available(config: &crate::config::Config, asserts: bool) -> bool {
153     // This is currently all tier 1 targets and tier 2 targets with host tools
154     // (since others may not have CI artifacts)
155     // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
156     let supported_platforms = [
157         // tier 1
158         "aarch64-unknown-linux-gnu",
159         "i686-pc-windows-gnu",
160         "i686-pc-windows-msvc",
161         "i686-unknown-linux-gnu",
162         "x86_64-unknown-linux-gnu",
163         "x86_64-apple-darwin",
164         "x86_64-pc-windows-gnu",
165         "x86_64-pc-windows-msvc",
166         // tier 2 with host tools
167         "aarch64-apple-darwin",
168         "aarch64-pc-windows-msvc",
169         "aarch64-unknown-linux-musl",
170         "arm-unknown-linux-gnueabi",
171         "arm-unknown-linux-gnueabihf",
172         "armv7-unknown-linux-gnueabihf",
173         "mips-unknown-linux-gnu",
174         "mips64-unknown-linux-gnuabi64",
175         "mips64el-unknown-linux-gnuabi64",
176         "mipsel-unknown-linux-gnu",
177         "powerpc-unknown-linux-gnu",
178         "powerpc64-unknown-linux-gnu",
179         "powerpc64le-unknown-linux-gnu",
180         "riscv64gc-unknown-linux-gnu",
181         "s390x-unknown-linux-gnu",
182         "x86_64-unknown-freebsd",
183         "x86_64-unknown-illumos",
184         "x86_64-unknown-linux-musl",
185         "x86_64-unknown-netbsd",
186     ];
187     if !supported_platforms.contains(&&*config.build.triple) {
188         return false;
189     }
190
191     let triple = &*config.build.triple;
192     if (triple == "aarch64-unknown-linux-gnu" || triple.contains("i686")) && asserts {
193         // No alt builder for aarch64-unknown-linux-gnu today.
194         return false;
195     }
196
197     if crate::util::CiEnv::is_ci() {
198         let llvm_sha = detect_llvm_sha(config);
199         let head_sha = output(config.git().arg("rev-parse").arg("HEAD"));
200         let head_sha = head_sha.trim();
201         if llvm_sha == head_sha {
202             eprintln!(
203                 "Detected LLVM as non-available: running in CI and modified LLVM in this change"
204             );
205             return false;
206         }
207     }
208
209     true
210 }
211
212 pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) {
213     let config = &builder.config;
214     if !config.llvm_from_ci {
215         return;
216     }
217     let llvm_root = config.ci_llvm_root();
218     let llvm_stamp = llvm_root.join(".llvm-stamp");
219     let llvm_sha = detect_llvm_sha(&config);
220     let key = format!("{}{}", llvm_sha, config.llvm_assertions);
221     if program_out_of_date(&llvm_stamp, &key) && !config.dry_run {
222         download_ci_llvm(builder, &llvm_sha);
223         for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
224             builder.fix_bin_or_dylib(&t!(entry).path());
225         }
226
227         // Update the timestamp of llvm-config to force rustc_llvm to be
228         // rebuilt. This is a hacky workaround for a deficiency in Cargo where
229         // the rerun-if-changed directive doesn't handle changes very well.
230         // https://github.com/rust-lang/cargo/issues/10791
231         // Cargo only compares the timestamp of the file relative to the last
232         // time `rustc_llvm` build script ran. However, the timestamps of the
233         // files in the tarball are in the past, so it doesn't trigger a
234         // rebuild.
235         let now = filetime::FileTime::from_system_time(std::time::SystemTime::now());
236         let llvm_config = llvm_root.join("bin").join(exe("llvm-config", builder.config.build));
237         t!(filetime::set_file_times(&llvm_config, now, now));
238
239         let llvm_lib = llvm_root.join("lib");
240         for entry in t!(fs::read_dir(&llvm_lib)) {
241             let lib = t!(entry).path();
242             if lib.extension().map_or(false, |ext| ext == "so") {
243                 builder.fix_bin_or_dylib(&lib);
244             }
245         }
246         t!(fs::write(llvm_stamp, key));
247     }
248 }
249
250 fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) {
251     let llvm_assertions = builder.config.llvm_assertions;
252
253     let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
254     let cache_dst = builder.out.join("cache");
255     let rustc_cache = cache_dst.join(cache_prefix);
256     if !rustc_cache.exists() {
257         t!(fs::create_dir_all(&rustc_cache));
258     }
259     let base = if llvm_assertions {
260         &builder.config.stage0_metadata.config.artifacts_with_llvm_assertions_server
261     } else {
262         &builder.config.stage0_metadata.config.artifacts_server
263     };
264     let channel = builder.config.artifact_channel(llvm_sha);
265     let filename = format!("rust-dev-{}-{}.tar.xz", channel, builder.build.build.triple);
266     let tarball = rustc_cache.join(&filename);
267     if !tarball.exists() {
268         let help_on_error = "error: failed to download llvm from ci
269
270 help: old builds get deleted after a certain time
271 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
272
273 [llvm]
274 download-ci-llvm = false
275 ";
276         builder.download_component(
277             &format!("{base}/{llvm_sha}/{filename}"),
278             &tarball,
279             help_on_error,
280         );
281     }
282     let llvm_root = builder.config.ci_llvm_root();
283     builder.unpack(&tarball, &llvm_root, "rust-dev");
284 }
285
286 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
287 pub struct Llvm {
288     pub target: TargetSelection,
289 }
290
291 impl Step for Llvm {
292     type Output = PathBuf; // path to llvm-config
293
294     const ONLY_HOSTS: bool = true;
295
296     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
297         run.path("src/llvm-project").path("src/llvm-project/llvm")
298     }
299
300     fn make_run(run: RunConfig<'_>) {
301         run.builder.ensure(Llvm { target: run.target });
302     }
303
304     /// Compile LLVM for `target`.
305     fn run(self, builder: &Builder<'_>) -> PathBuf {
306         let target = self.target;
307         let target_native = if self.target.starts_with("riscv") {
308             // RISC-V target triples in Rust is not named the same as C compiler target triples.
309             // This converts Rust RISC-V target triples to C compiler triples.
310             let idx = target.triple.find('-').unwrap();
311
312             format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
313         } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
314             // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
315             // Set the version suffix to 13.0 so the correct target details are used.
316             format!("{}{}", self.target, "13.0")
317         } else {
318             target.to_string()
319         };
320
321         let Meta { stamp, build_llvm_config, out_dir, root } =
322             match prebuilt_llvm_config(builder, target) {
323                 Ok(p) => return p,
324                 Err(m) => m,
325             };
326
327         builder.update_submodule(&Path::new("src").join("llvm-project"));
328         if builder.llvm_link_shared() && target.contains("windows") {
329             panic!("shared linking to LLVM is not currently supported on {}", target.triple);
330         }
331
332         builder.info(&format!("Building LLVM for {}", target));
333         t!(stamp.remove());
334         let _time = util::timeit(&builder);
335         t!(fs::create_dir_all(&out_dir));
336
337         // https://llvm.org/docs/CMake.html
338         let mut cfg = cmake::Config::new(builder.src.join(root));
339         let mut ldflags = LdFlags::default();
340
341         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
342             (false, _) => "Debug",
343             (true, false) => "Release",
344             (true, true) => "RelWithDebInfo",
345         };
346
347         // NOTE: remember to also update `config.toml.example` when changing the
348         // defaults!
349         let llvm_targets = match &builder.config.llvm_targets {
350             Some(s) => s,
351             None => {
352                 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
353                      Sparc;SystemZ;WebAssembly;X86"
354             }
355         };
356
357         let llvm_exp_targets = match builder.config.llvm_experimental_targets {
358             Some(ref s) => s,
359             None => "AVR;M68k",
360         };
361
362         let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
363         let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
364         let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
365
366         cfg.out_dir(&out_dir)
367             .profile(profile)
368             .define("LLVM_ENABLE_ASSERTIONS", assertions)
369             .define("LLVM_ENABLE_PLUGINS", plugins)
370             .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
371             .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
372             .define("LLVM_INCLUDE_EXAMPLES", "OFF")
373             .define("LLVM_INCLUDE_DOCS", "OFF")
374             .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
375             .define("LLVM_INCLUDE_TESTS", enable_tests)
376             .define("LLVM_ENABLE_TERMINFO", "OFF")
377             .define("LLVM_ENABLE_LIBEDIT", "OFF")
378             .define("LLVM_ENABLE_BINDINGS", "OFF")
379             .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
380             .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
381             .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
382             .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
383
384         // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
385         // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
386         // This flag makes sure `FileCheck` is copied in the final binaries directory.
387         cfg.define("LLVM_INSTALL_UTILS", "ON");
388
389         if builder.config.llvm_profile_generate {
390             cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
391             if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
392                 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
393             }
394             cfg.define("LLVM_BUILD_RUNTIME", "No");
395         }
396         if let Some(path) = builder.config.llvm_profile_use.as_ref() {
397             cfg.define("LLVM_PROFDATA_FILE", &path);
398         }
399         if builder.config.llvm_bolt_profile_generate
400             || builder.config.llvm_bolt_profile_use.is_some()
401         {
402             // Relocations are required for BOLT to work.
403             ldflags.push_all("-Wl,-q");
404         }
405
406         // Disable zstd to avoid a dependency on libzstd.so.
407         cfg.define("LLVM_ENABLE_ZSTD", "OFF");
408
409         if target != "aarch64-apple-darwin" && !target.contains("windows") {
410             cfg.define("LLVM_ENABLE_ZLIB", "ON");
411         } else {
412             cfg.define("LLVM_ENABLE_ZLIB", "OFF");
413         }
414
415         // Are we compiling for iOS/tvOS/watchOS?
416         if target.contains("apple-ios")
417             || target.contains("apple-tvos")
418             || target.contains("apple-watchos")
419         {
420             // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
421             cfg.define("CMAKE_OSX_SYSROOT", "/");
422             cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
423             // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
424             cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
425             // Zlib fails to link properly, leading to a compiler error.
426             cfg.define("LLVM_ENABLE_ZLIB", "OFF");
427         }
428
429         // This setting makes the LLVM tools link to the dynamic LLVM library,
430         // which saves both memory during parallel links and overall disk space
431         // for the tools. We don't do this on every platform as it doesn't work
432         // equally well everywhere.
433         if builder.llvm_link_shared() {
434             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
435         }
436
437         if target.starts_with("riscv") && !target.contains("freebsd") && !target.contains("openbsd")
438         {
439             // RISC-V GCC erroneously requires linking against
440             // `libatomic` when using 1-byte and 2-byte C++
441             // atomics but the LLVM build system check cannot
442             // detect this. Therefore it is set manually here.
443             // Some BSD uses Clang as its system compiler and
444             // provides no libatomic in its base system so does
445             // not want this.
446             ldflags.exe.push(" -latomic");
447             ldflags.shared.push(" -latomic");
448         }
449
450         if target.contains("msvc") {
451             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
452             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
453             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
454             cfg.static_crt(true);
455         }
456
457         if target.starts_with("i686") {
458             cfg.define("LLVM_BUILD_32_BITS", "ON");
459         }
460
461         let mut enabled_llvm_projects = Vec::new();
462
463         if util::forcing_clang_based_tests() {
464             enabled_llvm_projects.push("clang");
465             enabled_llvm_projects.push("compiler-rt");
466         }
467
468         if builder.config.llvm_polly {
469             enabled_llvm_projects.push("polly");
470         }
471
472         if builder.config.llvm_clang {
473             enabled_llvm_projects.push("clang");
474         }
475
476         // We want libxml to be disabled.
477         // See https://github.com/rust-lang/rust/pull/50104
478         cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
479
480         if !enabled_llvm_projects.is_empty() {
481             enabled_llvm_projects.sort();
482             enabled_llvm_projects.dedup();
483             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
484         }
485
486         if let Some(num_linkers) = builder.config.llvm_link_jobs {
487             if num_linkers > 0 {
488                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
489             }
490         }
491
492         // Workaround for ppc32 lld limitation
493         if target == "powerpc-unknown-freebsd" {
494             ldflags.exe.push(" -fuse-ld=bfd");
495         }
496
497         // https://llvm.org/docs/HowToCrossCompileLLVM.html
498         if target != builder.config.build {
499             builder.ensure(Llvm { target: builder.config.build });
500             // FIXME: if the llvm root for the build triple is overridden then we
501             //        should use llvm-tblgen from there, also should verify that it
502             //        actually exists most of the time in normal installs of LLVM.
503             let host_bin = builder.llvm_out(builder.config.build).join("bin");
504             cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
505             // LLVM_NM is required for cross compiling using MSVC
506             cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
507             cfg.define(
508                 "LLVM_CONFIG_PATH",
509                 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
510             );
511             if builder.config.llvm_clang {
512                 let build_bin = builder.llvm_out(builder.config.build).join("build").join("bin");
513                 let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
514                 if !builder.config.dry_run && !clang_tblgen.exists() {
515                     panic!("unable to find {}", clang_tblgen.display());
516                 }
517                 cfg.define("CLANG_TABLEGEN", clang_tblgen);
518             }
519         }
520
521         let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
522             // Allow version-suffix="" to not define a version suffix at all.
523             if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
524         } else if builder.config.channel == "dev" {
525             // Changes to a version suffix require a complete rebuild of the LLVM.
526             // To avoid rebuilds during a time of version bump, don't include rustc
527             // release number on the dev channel.
528             Some("-rust-dev".to_string())
529         } else {
530             Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
531         };
532         if let Some(ref suffix) = llvm_version_suffix {
533             cfg.define("LLVM_VERSION_SUFFIX", suffix);
534         }
535
536         configure_cmake(builder, target, &mut cfg, true, ldflags);
537         configure_llvm(builder, target, &mut cfg);
538
539         for (key, val) in &builder.config.llvm_build_config {
540             cfg.define(key, val);
541         }
542
543         // FIXME: we don't actually need to build all LLVM tools and all LLVM
544         //        libraries here, e.g., we just want a few components and a few
545         //        tools. Figure out how to filter them down and only build the right
546         //        tools and libs on all platforms.
547
548         if builder.config.dry_run {
549             return build_llvm_config;
550         }
551
552         cfg.build();
553
554         // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
555         // libLLVM.dylib will be built. However, llvm-config will still look
556         // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
557         // link to make llvm-config happy.
558         if builder.llvm_link_shared() && target.contains("apple-darwin") {
559             let mut cmd = Command::new(&build_llvm_config);
560             let version = output(cmd.arg("--version"));
561             let major = version.split('.').next().unwrap();
562             let lib_name = match llvm_version_suffix {
563                 Some(s) => format!("libLLVM-{}{}.dylib", major, s),
564                 None => format!("libLLVM-{}.dylib", major),
565             };
566
567             let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
568             if !lib_llvm.exists() {
569                 t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
570             }
571         }
572
573         // After LLVM is built, we modify (instrument or optimize) the libLLVM.so library file
574         // in place. This is fine, because currently we do not support incrementally rebuilding
575         // LLVM after a configuration change, so to rebuild it the build files have to be removed,
576         // which will also remove these modified files.
577         if builder.config.llvm_bolt_profile_generate {
578             instrument_with_bolt_inplace(&get_built_llvm_lib_path(&build_llvm_config));
579         }
580         if let Some(path) = &builder.config.llvm_bolt_profile_use {
581             optimize_library_with_bolt_inplace(
582                 &get_built_llvm_lib_path(&build_llvm_config),
583                 &Path::new(path),
584             );
585         }
586
587         t!(stamp.write());
588
589         build_llvm_config
590     }
591 }
592
593 /// Returns path to a built LLVM library (libLLVM.so).
594 /// Assumes that we have built LLVM into a single library file.
595 fn get_built_llvm_lib_path(llvm_config_path: &Path) -> PathBuf {
596     let mut cmd = Command::new(llvm_config_path);
597     cmd.arg("--libfiles");
598     PathBuf::from(output(&mut cmd).trim())
599 }
600
601 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
602     if !builder.config.llvm_version_check {
603         return;
604     }
605
606     if builder.config.dry_run {
607         return;
608     }
609
610     let mut cmd = Command::new(llvm_config);
611     let version = output(cmd.arg("--version"));
612     let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
613     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
614         if major >= 13 {
615             return;
616         }
617     }
618     panic!("\n\nbad LLVM version: {}, need >=13.0\n\n", version)
619 }
620
621 fn configure_cmake(
622     builder: &Builder<'_>,
623     target: TargetSelection,
624     cfg: &mut cmake::Config,
625     use_compiler_launcher: bool,
626     mut ldflags: LdFlags,
627 ) {
628     // Do not print installation messages for up-to-date files.
629     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
630     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
631
632     // Do not allow the user's value of DESTDIR to influence where
633     // LLVM will install itself. LLVM must always be installed in our
634     // own build directories.
635     cfg.env("DESTDIR", "");
636
637     if builder.ninja() {
638         cfg.generator("Ninja");
639     }
640     cfg.target(&target.triple).host(&builder.config.build.triple);
641
642     if target != builder.config.build {
643         cfg.define("CMAKE_CROSSCOMPILING", "True");
644
645         if target.contains("netbsd") {
646             cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
647         } else if target.contains("freebsd") {
648             cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
649         } else if target.contains("windows") {
650             cfg.define("CMAKE_SYSTEM_NAME", "Windows");
651         } else if target.contains("haiku") {
652             cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
653         } else if target.contains("solaris") || target.contains("illumos") {
654             cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
655         }
656         // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
657         // that case like CMake we cannot easily determine system version either.
658         //
659         // Since, the LLVM itself makes rather limited use of version checks in
660         // CMakeFiles (and then only in tests), and so far no issues have been
661         // reported, the system version is currently left unset.
662
663         if target.contains("darwin") {
664             // Make sure that CMake does not build universal binaries on macOS.
665             // Explicitly specify the one single target architecture.
666             if target.starts_with("aarch64") {
667                 // macOS uses a different name for building arm64
668                 cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
669             } else {
670                 cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
671             }
672         }
673     }
674
675     let sanitize_cc = |cc: &Path| {
676         if target.contains("msvc") {
677             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
678         } else {
679             cc.as_os_str().to_owned()
680         }
681     };
682
683     // MSVC with CMake uses msbuild by default which doesn't respect these
684     // vars that we'd otherwise configure. In that case we just skip this
685     // entirely.
686     if target.contains("msvc") && !builder.ninja() {
687         return;
688     }
689
690     let (cc, cxx) = match builder.config.llvm_clang_cl {
691         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
692         None => (builder.cc(target), builder.cxx(target).unwrap()),
693     };
694
695     // Handle msvc + ninja + ccache specially (this is what the bots use)
696     if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
697         let mut wrap_cc = env::current_exe().expect("failed to get cwd");
698         wrap_cc.set_file_name("sccache-plus-cl.exe");
699
700         cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
701             .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
702         cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
703             .env("SCCACHE_TARGET", target.triple)
704             .env("SCCACHE_CC", &cc)
705             .env("SCCACHE_CXX", &cxx);
706
707         // Building LLVM on MSVC can be a little ludicrous at times. We're so far
708         // off the beaten path here that I'm not really sure this is even half
709         // supported any more. Here we're trying to:
710         //
711         // * Build LLVM on MSVC
712         // * Build LLVM with `clang-cl` instead of `cl.exe`
713         // * Build a project with `sccache`
714         // * Build for 32-bit as well
715         // * Build with Ninja
716         //
717         // For `cl.exe` there are different binaries to compile 32/64 bit which
718         // we use but for `clang-cl` there's only one which internally
719         // multiplexes via flags. As a result it appears that CMake's detection
720         // of a compiler's architecture and such on MSVC **doesn't** pass any
721         // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
722         // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
723         // definitely causes problems since all the env vars are pointing to
724         // 32-bit libraries.
725         //
726         // To hack around this... again... we pass an argument that's
727         // unconditionally passed in the sccache shim. This'll get CMake to
728         // correctly diagnose it's doing a 32-bit compilation and LLVM will
729         // internally configure itself appropriately.
730         if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
731             cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
732         }
733     } else {
734         // If ccache is configured we inform the build a little differently how
735         // to invoke ccache while also invoking our compilers.
736         if use_compiler_launcher {
737             if let Some(ref ccache) = builder.config.ccache {
738                 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
739                     .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
740             }
741         }
742         cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
743             .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
744             .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
745     }
746
747     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
748     let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
749     if let Some(ref s) = builder.config.llvm_cflags {
750         cflags.push(" ");
751         cflags.push(s);
752     }
753     // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
754     if target.contains("apple-ios") {
755         if target.contains("86-") {
756             cflags.push(" -miphonesimulator-version-min=10.0");
757         } else {
758             cflags.push(" -miphoneos-version-min=10.0");
759         }
760     }
761     if builder.config.llvm_clang_cl.is_some() {
762         cflags.push(&format!(" --target={}", target));
763     }
764     cfg.define("CMAKE_C_FLAGS", cflags);
765     let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
766     if let Some(ref s) = builder.config.llvm_cxxflags {
767         cxxflags.push(" ");
768         cxxflags.push(s);
769     }
770     if builder.config.llvm_clang_cl.is_some() {
771         cxxflags.push(&format!(" --target={}", target));
772     }
773     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
774     if let Some(ar) = builder.ar(target) {
775         if ar.is_absolute() {
776             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
777             // tries to resolve this path in the LLVM build directory.
778             cfg.define("CMAKE_AR", sanitize_cc(ar));
779         }
780     }
781
782     if let Some(ranlib) = builder.ranlib(target) {
783         if ranlib.is_absolute() {
784             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
785             // tries to resolve this path in the LLVM build directory.
786             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
787         }
788     }
789
790     if let Some(ref flags) = builder.config.llvm_ldflags {
791         ldflags.push_all(flags);
792     }
793
794     if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
795         ldflags.push_all(&flags);
796     }
797
798     // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
799     // We also do this if the user explicitly requested static libstdc++.
800     if builder.config.llvm_static_stdcpp {
801         if !target.contains("msvc") && !target.contains("netbsd") && !target.contains("solaris") {
802             if target.contains("apple") || target.contains("windows") {
803                 ldflags.push_all("-static-libstdc++");
804             } else {
805                 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
806             }
807         }
808     }
809
810     cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
811     cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
812     cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
813
814     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
815         cfg.env("RUSTC_LOG", "sccache=warn");
816     }
817 }
818
819 fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
820     // ThinLTO is only available when building with LLVM, enabling LLD is required.
821     // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
822     if builder.config.llvm_thin_lto {
823         cfg.define("LLVM_ENABLE_LTO", "Thin");
824         if !target.contains("apple") {
825             cfg.define("LLVM_ENABLE_LLD", "ON");
826         }
827     }
828
829     if let Some(ref linker) = builder.config.llvm_use_linker {
830         cfg.define("LLVM_USE_LINKER", linker);
831     }
832
833     if builder.config.llvm_allow_old_toolchain {
834         cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
835     }
836 }
837
838 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
839 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
840     let kind = if host == target { "HOST" } else { "TARGET" };
841     let target_u = target.replace("-", "_");
842     env::var_os(&format!("{}_{}", var_base, target))
843         .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
844         .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
845         .or_else(|| env::var_os(var_base))
846 }
847
848 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
849 pub struct Lld {
850     pub target: TargetSelection,
851 }
852
853 impl Step for Lld {
854     type Output = PathBuf;
855     const ONLY_HOSTS: bool = true;
856
857     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
858         run.path("src/llvm-project/lld")
859     }
860
861     fn make_run(run: RunConfig<'_>) {
862         run.builder.ensure(Lld { target: run.target });
863     }
864
865     /// Compile LLD for `target`.
866     fn run(self, builder: &Builder<'_>) -> PathBuf {
867         if builder.config.dry_run {
868             return PathBuf::from("lld-out-dir-test-gen");
869         }
870         let target = self.target;
871
872         let llvm_config = builder.ensure(Llvm { target: self.target });
873
874         let out_dir = builder.lld_out(target);
875         let done_stamp = out_dir.join("lld-finished-building");
876         if done_stamp.exists() {
877             return out_dir;
878         }
879
880         builder.info(&format!("Building LLD for {}", target));
881         let _time = util::timeit(&builder);
882         t!(fs::create_dir_all(&out_dir));
883
884         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
885         let mut ldflags = LdFlags::default();
886
887         // When building LLD as part of a build with instrumentation on windows, for example
888         // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
889         // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
890         // linking errors, much like LLVM's cmake setup does in that situation.
891         if builder.config.llvm_profile_generate && target.contains("msvc") {
892             if let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref() {
893                 // Find clang's runtime library directory and push that as a search path to the
894                 // cmake linker flags.
895                 let clang_rt_dir = get_clang_cl_resource_dir(clang_cl_path);
896                 ldflags.push_all(&format!("/libpath:{}", clang_rt_dir.display()));
897             }
898         }
899
900         configure_cmake(builder, target, &mut cfg, true, ldflags);
901         configure_llvm(builder, target, &mut cfg);
902
903         // This is an awful, awful hack. Discovered when we migrated to using
904         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
905         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
906         // that directory for later processing. Unfortunately if this path has
907         // forward slashes in it (which it basically always does on Windows)
908         // then CMake will hit a syntax error later on as... something isn't
909         // escaped it seems?
910         //
911         // Instead of attempting to fix this problem in upstream CMake and/or
912         // LLVM/LLD we just hack around it here. This thin wrapper will take the
913         // output from llvm-config and replace all instances of `\` with `/` to
914         // ensure we don't hit the same bugs with escaping. It means that you
915         // can't build on a system where your paths require `\` on Windows, but
916         // there's probably a lot of reasons you can't do that other than this.
917         let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
918
919         // Re-use the same flags as llvm to control the level of debug information
920         // generated for lld.
921         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
922             (false, _) => "Debug",
923             (true, false) => "Release",
924             (true, true) => "RelWithDebInfo",
925         };
926
927         cfg.out_dir(&out_dir)
928             .profile(profile)
929             .env("LLVM_CONFIG_REAL", &llvm_config)
930             .define("LLVM_CONFIG_PATH", llvm_config_shim)
931             .define("LLVM_INCLUDE_TESTS", "OFF");
932
933         // While we're using this horrible workaround to shim the execution of
934         // llvm-config, let's just pile on more. I can't seem to figure out how
935         // to build LLD as a standalone project and also cross-compile it at the
936         // same time. It wants a natively executable `llvm-config` to learn
937         // about LLVM, but then it learns about all the host configuration of
938         // LLVM and tries to link to host LLVM libraries.
939         //
940         // To work around that we tell our shim to replace anything with the
941         // build target with the actual target instead. This'll break parts of
942         // LLD though which try to execute host tools, such as llvm-tblgen, so
943         // we specifically tell it where to find those. This is likely super
944         // brittle and will break over time. If anyone knows better how to
945         // cross-compile LLD it would be much appreciated to fix this!
946         if target != builder.config.build {
947             cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
948                 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
949                 .define(
950                     "LLVM_TABLEGEN_EXE",
951                     llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
952                 );
953         }
954
955         // Explicitly set C++ standard, because upstream doesn't do so
956         // for standalone builds.
957         cfg.define("CMAKE_CXX_STANDARD", "14");
958
959         cfg.build();
960
961         t!(File::create(&done_stamp));
962         out_dir
963     }
964 }
965
966 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
967 pub struct TestHelpers {
968     pub target: TargetSelection,
969 }
970
971 impl Step for TestHelpers {
972     type Output = ();
973
974     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
975         run.path("src/test/auxiliary/rust_test_helpers.c")
976     }
977
978     fn make_run(run: RunConfig<'_>) {
979         run.builder.ensure(TestHelpers { target: run.target })
980     }
981
982     /// Compiles the `rust_test_helpers.c` library which we used in various
983     /// `run-pass` tests for ABI testing.
984     fn run(self, builder: &Builder<'_>) {
985         if builder.config.dry_run {
986             return;
987         }
988         // The x86_64-fortanix-unknown-sgx target doesn't have a working C
989         // toolchain. However, some x86_64 ELF objects can be linked
990         // without issues. Use this hack to compile the test helpers.
991         let target = if self.target == "x86_64-fortanix-unknown-sgx" {
992             TargetSelection::from_user("x86_64-unknown-linux-gnu")
993         } else {
994             self.target
995         };
996         let dst = builder.test_helpers_out(target);
997         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
998         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
999             return;
1000         }
1001
1002         builder.info("Building test helpers");
1003         t!(fs::create_dir_all(&dst));
1004         let mut cfg = cc::Build::new();
1005         // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
1006         if target.contains("emscripten") {
1007             cfg.pic(false);
1008         }
1009
1010         // We may have found various cross-compilers a little differently due to our
1011         // extra configuration, so inform cc of these compilers. Note, though, that
1012         // on MSVC we still need cc's detection of env vars (ugh).
1013         if !target.contains("msvc") {
1014             if let Some(ar) = builder.ar(target) {
1015                 cfg.archiver(ar);
1016             }
1017             cfg.compiler(builder.cc(target));
1018         }
1019         cfg.cargo_metadata(false)
1020             .out_dir(&dst)
1021             .target(&target.triple)
1022             .host(&builder.config.build.triple)
1023             .opt_level(0)
1024             .warnings(false)
1025             .debug(false)
1026             .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
1027             .compile("rust_test_helpers");
1028     }
1029 }
1030
1031 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1032 pub struct Sanitizers {
1033     pub target: TargetSelection,
1034 }
1035
1036 impl Step for Sanitizers {
1037     type Output = Vec<SanitizerRuntime>;
1038
1039     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1040         run.alias("sanitizers")
1041     }
1042
1043     fn make_run(run: RunConfig<'_>) {
1044         run.builder.ensure(Sanitizers { target: run.target });
1045     }
1046
1047     /// Builds sanitizer runtime libraries.
1048     fn run(self, builder: &Builder<'_>) -> Self::Output {
1049         let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1050         if !compiler_rt_dir.exists() {
1051             return Vec::new();
1052         }
1053
1054         let out_dir = builder.native_dir(self.target).join("sanitizers");
1055         let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1056         if runtimes.is_empty() {
1057             return runtimes;
1058         }
1059
1060         let llvm_config = builder.ensure(Llvm { target: builder.config.build });
1061         if builder.config.dry_run {
1062             return runtimes;
1063         }
1064
1065         let stamp = out_dir.join("sanitizers-finished-building");
1066         let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
1067
1068         if stamp.is_done() {
1069             if stamp.hash.is_none() {
1070                 builder.info(&format!(
1071                     "Rebuild sanitizers by removing the file `{}`",
1072                     stamp.path.display()
1073                 ));
1074             }
1075             return runtimes;
1076         }
1077
1078         builder.info(&format!("Building sanitizers for {}", self.target));
1079         t!(stamp.remove());
1080         let _time = util::timeit(&builder);
1081
1082         let mut cfg = cmake::Config::new(&compiler_rt_dir);
1083         cfg.profile("Release");
1084         cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1085         cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1086         cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1087         cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1088         cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1089         cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1090         cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1091         cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1092         cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1093         cfg.define("LLVM_CONFIG_PATH", &llvm_config);
1094
1095         // On Darwin targets the sanitizer runtimes are build as universal binaries.
1096         // Unfortunately sccache currently lacks support to build them successfully.
1097         // Disable compiler launcher on Darwin targets to avoid potential issues.
1098         let use_compiler_launcher = !self.target.contains("apple-darwin");
1099         configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
1100
1101         t!(fs::create_dir_all(&out_dir));
1102         cfg.out_dir(out_dir);
1103
1104         for runtime in &runtimes {
1105             cfg.build_target(&runtime.cmake_target);
1106             cfg.build();
1107         }
1108         t!(stamp.write());
1109
1110         runtimes
1111     }
1112 }
1113
1114 #[derive(Clone, Debug)]
1115 pub struct SanitizerRuntime {
1116     /// CMake target used to build the runtime.
1117     pub cmake_target: String,
1118     /// Path to the built runtime library.
1119     pub path: PathBuf,
1120     /// Library filename that will be used rustc.
1121     pub name: String,
1122 }
1123
1124 /// Returns sanitizers available on a given target.
1125 fn supported_sanitizers(
1126     out_dir: &Path,
1127     target: TargetSelection,
1128     channel: &str,
1129 ) -> Vec<SanitizerRuntime> {
1130     let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1131         components
1132             .iter()
1133             .map(move |c| SanitizerRuntime {
1134                 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
1135                 path: out_dir
1136                     .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
1137                 name: format!("librustc-{}_rt.{}.dylib", channel, c),
1138             })
1139             .collect()
1140     };
1141
1142     let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1143         components
1144             .iter()
1145             .map(move |c| SanitizerRuntime {
1146                 cmake_target: format!("clang_rt.{}-{}", c, arch),
1147                 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
1148                 name: format!("librustc-{}_rt.{}.a", channel, c),
1149             })
1150             .collect()
1151     };
1152
1153     match &*target.triple {
1154         "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1155         "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1156         "aarch64-unknown-linux-gnu" => {
1157             common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1158         }
1159         "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1160         "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1161         "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1162         "x86_64-unknown-netbsd" => {
1163             common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1164         }
1165         "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1166         "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1167         "x86_64-unknown-linux-gnu" => {
1168             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1169         }
1170         "x86_64-unknown-linux-musl" => {
1171             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1172         }
1173         _ => Vec::new(),
1174     }
1175 }
1176
1177 struct HashStamp {
1178     path: PathBuf,
1179     hash: Option<Vec<u8>>,
1180 }
1181
1182 impl HashStamp {
1183     fn new(path: PathBuf, hash: Option<&str>) -> Self {
1184         HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1185     }
1186
1187     fn is_done(&self) -> bool {
1188         match fs::read(&self.path) {
1189             Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1190             Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1191             Err(e) => {
1192                 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1193             }
1194         }
1195     }
1196
1197     fn remove(&self) -> io::Result<()> {
1198         match fs::remove_file(&self.path) {
1199             Ok(()) => Ok(()),
1200             Err(e) => {
1201                 if e.kind() == io::ErrorKind::NotFound {
1202                     Ok(())
1203                 } else {
1204                     Err(e)
1205                 }
1206             }
1207         }
1208     }
1209
1210     fn write(&self) -> io::Result<()> {
1211         fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1212     }
1213 }
1214
1215 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1216 pub struct CrtBeginEnd {
1217     pub target: TargetSelection,
1218 }
1219
1220 impl Step for CrtBeginEnd {
1221     type Output = PathBuf;
1222
1223     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1224         run.path("src/llvm-project/compiler-rt/lib/crt")
1225     }
1226
1227     fn make_run(run: RunConfig<'_>) {
1228         run.builder.ensure(CrtBeginEnd { target: run.target });
1229     }
1230
1231     /// Build crtbegin.o/crtend.o for musl target.
1232     fn run(self, builder: &Builder<'_>) -> Self::Output {
1233         let out_dir = builder.native_dir(self.target).join("crt");
1234
1235         if builder.config.dry_run {
1236             return out_dir;
1237         }
1238
1239         let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1240         let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1241         if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1242             && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1243         {
1244             return out_dir;
1245         }
1246
1247         builder.info("Building crtbegin.o and crtend.o");
1248         t!(fs::create_dir_all(&out_dir));
1249
1250         let mut cfg = cc::Build::new();
1251
1252         if let Some(ar) = builder.ar(self.target) {
1253             cfg.archiver(ar);
1254         }
1255         cfg.compiler(builder.cc(self.target));
1256         cfg.cargo_metadata(false)
1257             .out_dir(&out_dir)
1258             .target(&self.target.triple)
1259             .host(&builder.config.build.triple)
1260             .warnings(false)
1261             .debug(false)
1262             .opt_level(3)
1263             .file(crtbegin_src)
1264             .file(crtend_src);
1265
1266         // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1267         // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1268         // instead of .ctors/.dtors
1269         cfg.flag("-std=c11")
1270             .define("CRT_HAS_INITFINI_ARRAY", None)
1271             .define("EH_USE_FRAME_REGISTRY", None);
1272
1273         cfg.compile("crt");
1274
1275         t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1276         t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1277         out_dir
1278     }
1279 }
1280
1281 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1282 pub struct Libunwind {
1283     pub target: TargetSelection,
1284 }
1285
1286 impl Step for Libunwind {
1287     type Output = PathBuf;
1288
1289     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1290         run.path("src/llvm-project/libunwind")
1291     }
1292
1293     fn make_run(run: RunConfig<'_>) {
1294         run.builder.ensure(Libunwind { target: run.target });
1295     }
1296
1297     /// Build linunwind.a
1298     fn run(self, builder: &Builder<'_>) -> Self::Output {
1299         if builder.config.dry_run {
1300             return PathBuf::new();
1301         }
1302
1303         let out_dir = builder.native_dir(self.target).join("libunwind");
1304         let root = builder.src.join("src/llvm-project/libunwind");
1305
1306         if up_to_date(&root, &out_dir.join("libunwind.a")) {
1307             return out_dir;
1308         }
1309
1310         builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1311         t!(fs::create_dir_all(&out_dir));
1312
1313         let mut cc_cfg = cc::Build::new();
1314         let mut cpp_cfg = cc::Build::new();
1315
1316         cpp_cfg.cpp(true);
1317         cpp_cfg.cpp_set_stdlib(None);
1318         cpp_cfg.flag("-nostdinc++");
1319         cpp_cfg.flag("-fno-exceptions");
1320         cpp_cfg.flag("-fno-rtti");
1321         cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1322
1323         for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1324             if let Some(ar) = builder.ar(self.target) {
1325                 cfg.archiver(ar);
1326             }
1327             cfg.target(&self.target.triple);
1328             cfg.host(&builder.config.build.triple);
1329             cfg.warnings(false);
1330             cfg.debug(false);
1331             // get_compiler() need set opt_level first.
1332             cfg.opt_level(3);
1333             cfg.flag("-fstrict-aliasing");
1334             cfg.flag("-funwind-tables");
1335             cfg.flag("-fvisibility=hidden");
1336             cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1337             cfg.include(root.join("include"));
1338             cfg.cargo_metadata(false);
1339             cfg.out_dir(&out_dir);
1340
1341             if self.target.contains("x86_64-fortanix-unknown-sgx") {
1342                 cfg.static_flag(true);
1343                 cfg.flag("-fno-stack-protector");
1344                 cfg.flag("-ffreestanding");
1345                 cfg.flag("-fexceptions");
1346
1347                 // easiest way to undefine since no API available in cc::Build to undefine
1348                 cfg.flag("-U_FORTIFY_SOURCE");
1349                 cfg.define("_FORTIFY_SOURCE", "0");
1350                 cfg.define("RUST_SGX", "1");
1351                 cfg.define("__NO_STRING_INLINES", None);
1352                 cfg.define("__NO_MATH_INLINES", None);
1353                 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1354                 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1355                 cfg.define("NDEBUG", None);
1356             }
1357             if self.target.contains("windows") {
1358                 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1359                 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1360             }
1361         }
1362
1363         cc_cfg.compiler(builder.cc(self.target));
1364         if let Ok(cxx) = builder.cxx(self.target) {
1365             cpp_cfg.compiler(cxx);
1366         } else {
1367             cc_cfg.compiler(builder.cc(self.target));
1368         }
1369
1370         // Don't set this for clang
1371         // By default, Clang builds C code in GNU C17 mode.
1372         // By default, Clang builds C++ code according to the C++98 standard,
1373         // with many C++11 features accepted as extensions.
1374         if cc_cfg.get_compiler().is_like_gnu() {
1375             cc_cfg.flag("-std=c99");
1376         }
1377         if cpp_cfg.get_compiler().is_like_gnu() {
1378             cpp_cfg.flag("-std=c++11");
1379         }
1380
1381         if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1382             // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1383             // C++ compiler env variables on the builders.
1384             // Don't set this for clang++, as clang++ is able to compile this without libc++.
1385             if cpp_cfg.get_compiler().is_like_gnu() {
1386                 cpp_cfg.cpp(false);
1387                 cpp_cfg.compiler(builder.cc(self.target));
1388             }
1389         }
1390
1391         let mut c_sources = vec![
1392             "Unwind-sjlj.c",
1393             "UnwindLevel1-gcc-ext.c",
1394             "UnwindLevel1.c",
1395             "UnwindRegistersRestore.S",
1396             "UnwindRegistersSave.S",
1397         ];
1398
1399         let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1400         let cpp_len = cpp_sources.len();
1401
1402         if self.target.contains("x86_64-fortanix-unknown-sgx") {
1403             c_sources.push("UnwindRustSgx.c");
1404         }
1405
1406         for src in c_sources {
1407             cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1408         }
1409
1410         for src in &cpp_sources {
1411             cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1412         }
1413
1414         cpp_cfg.compile("unwind-cpp");
1415
1416         // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1417         let mut count = 0;
1418         for entry in fs::read_dir(&out_dir).unwrap() {
1419             let file = entry.unwrap().path().canonicalize().unwrap();
1420             if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1421                 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1422                 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1423                 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1424                     cc_cfg.object(&file);
1425                     count += 1;
1426                 }
1427             }
1428         }
1429         assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1430
1431         cc_cfg.compile("unwind");
1432         out_dir
1433     }
1434 }