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