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