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