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