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