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