]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Rollup merge of #93412 - fee1-dead:improve-rustdoc-const-bounds, r=GuillaumeGomez
[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         // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
263         // We also do this if the user explicitly requested static libstdc++.
264         if builder.config.llvm_tools_enabled || builder.config.llvm_static_stdcpp {
265             if !target.contains("msvc") && !target.contains("netbsd") {
266                 if target.contains("apple") {
267                     ldflags.push_all("-static-libstdc++");
268                 } else {
269                     ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
270                 }
271             }
272         }
273
274         if target.starts_with("riscv") && !target.contains("freebsd") {
275             // RISC-V GCC erroneously requires linking against
276             // `libatomic` when using 1-byte and 2-byte C++
277             // atomics but the LLVM build system check cannot
278             // detect this. Therefore it is set manually here.
279             // FreeBSD uses Clang as its system compiler and
280             // provides no libatomic in its base system so does
281             // not want this.
282             ldflags.exe.push(" -latomic");
283             ldflags.shared.push(" -latomic");
284         }
285
286         if target.contains("msvc") {
287             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
288             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
289             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
290             cfg.static_crt(true);
291         }
292
293         if target.starts_with("i686") {
294             cfg.define("LLVM_BUILD_32_BITS", "ON");
295         }
296
297         let mut enabled_llvm_projects = Vec::new();
298
299         if util::forcing_clang_based_tests() {
300             enabled_llvm_projects.push("clang");
301             enabled_llvm_projects.push("compiler-rt");
302         }
303
304         if builder.config.llvm_polly {
305             enabled_llvm_projects.push("polly");
306         }
307
308         if builder.config.llvm_clang {
309             enabled_llvm_projects.push("clang");
310         }
311
312         // We want libxml to be disabled.
313         // See https://github.com/rust-lang/rust/pull/50104
314         cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
315
316         if !enabled_llvm_projects.is_empty() {
317             enabled_llvm_projects.sort();
318             enabled_llvm_projects.dedup();
319             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
320         }
321
322         if let Some(num_linkers) = builder.config.llvm_link_jobs {
323             if num_linkers > 0 {
324                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
325             }
326         }
327
328         // Workaround for ppc32 lld limitation
329         if target == "powerpc-unknown-freebsd" {
330             ldflags.exe.push(" -fuse-ld=bfd");
331         }
332
333         // https://llvm.org/docs/HowToCrossCompileLLVM.html
334         if target != builder.config.build {
335             builder.ensure(Llvm { target: builder.config.build });
336             // FIXME: if the llvm root for the build triple is overridden then we
337             //        should use llvm-tblgen from there, also should verify that it
338             //        actually exists most of the time in normal installs of LLVM.
339             let host_bin = builder.llvm_out(builder.config.build).join("bin");
340             cfg.define("CMAKE_CROSSCOMPILING", "True");
341             cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
342             cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
343             cfg.define(
344                 "LLVM_CONFIG_PATH",
345                 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
346             );
347         }
348
349         if let Some(ref suffix) = builder.config.llvm_version_suffix {
350             // Allow version-suffix="" to not define a version suffix at all.
351             if !suffix.is_empty() {
352                 cfg.define("LLVM_VERSION_SUFFIX", suffix);
353             }
354         } else if builder.config.channel == "dev" {
355             // Changes to a version suffix require a complete rebuild of the LLVM.
356             // To avoid rebuilds during a time of version bump, don't include rustc
357             // release number on the dev channel.
358             cfg.define("LLVM_VERSION_SUFFIX", "-rust-dev");
359         } else {
360             let suffix = format!("-rust-{}-{}", builder.version, builder.config.channel);
361             cfg.define("LLVM_VERSION_SUFFIX", suffix);
362         }
363
364         if let Some(ref linker) = builder.config.llvm_use_linker {
365             cfg.define("LLVM_USE_LINKER", linker);
366         }
367
368         if builder.config.llvm_allow_old_toolchain {
369             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
370         }
371
372         configure_cmake(builder, target, &mut cfg, true, ldflags);
373
374         for (key, val) in &builder.config.llvm_build_config {
375             cfg.define(key, val);
376         }
377
378         // FIXME: we don't actually need to build all LLVM tools and all LLVM
379         //        libraries here, e.g., we just want a few components and a few
380         //        tools. Figure out how to filter them down and only build the right
381         //        tools and libs on all platforms.
382
383         if builder.config.dry_run {
384             return build_llvm_config;
385         }
386
387         cfg.build();
388
389         t!(stamp.write());
390
391         build_llvm_config
392     }
393 }
394
395 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
396     if !builder.config.llvm_version_check {
397         return;
398     }
399
400     if builder.config.dry_run {
401         return;
402     }
403
404     let mut cmd = Command::new(llvm_config);
405     let version = output(cmd.arg("--version"));
406     let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
407     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
408         if major >= 12 {
409             return;
410         }
411     }
412     panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
413 }
414
415 fn configure_cmake(
416     builder: &Builder<'_>,
417     target: TargetSelection,
418     cfg: &mut cmake::Config,
419     use_compiler_launcher: bool,
420     mut ldflags: LdFlags,
421 ) {
422     // Do not print installation messages for up-to-date files.
423     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
424     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
425
426     // Do not allow the user's value of DESTDIR to influence where
427     // LLVM will install itself. LLVM must always be installed in our
428     // own build directories.
429     cfg.env("DESTDIR", "");
430
431     if builder.ninja() {
432         cfg.generator("Ninja");
433     }
434     cfg.target(&target.triple).host(&builder.config.build.triple);
435
436     if target != builder.config.build {
437         if target.contains("netbsd") {
438             cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
439         } else if target.contains("freebsd") {
440             cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
441         } else if target.contains("windows") {
442             cfg.define("CMAKE_SYSTEM_NAME", "Windows");
443         } else if target.contains("haiku") {
444             cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
445         } else if target.contains("solaris") || target.contains("illumos") {
446             cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
447         }
448         // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
449         // that case like CMake we cannot easily determine system version either.
450         //
451         // Since, the LLVM itself makes rather limited use of version checks in
452         // CMakeFiles (and then only in tests), and so far no issues have been
453         // reported, the system version is currently left unset.
454     }
455
456     let sanitize_cc = |cc: &Path| {
457         if target.contains("msvc") {
458             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
459         } else {
460             cc.as_os_str().to_owned()
461         }
462     };
463
464     // MSVC with CMake uses msbuild by default which doesn't respect these
465     // vars that we'd otherwise configure. In that case we just skip this
466     // entirely.
467     if target.contains("msvc") && !builder.ninja() {
468         return;
469     }
470
471     let (cc, cxx) = match builder.config.llvm_clang_cl {
472         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
473         None => (builder.cc(target), builder.cxx(target).unwrap()),
474     };
475
476     // Handle msvc + ninja + ccache specially (this is what the bots use)
477     if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
478         let mut wrap_cc = env::current_exe().expect("failed to get cwd");
479         wrap_cc.set_file_name("sccache-plus-cl.exe");
480
481         cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
482             .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
483         cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
484             .env("SCCACHE_TARGET", target.triple)
485             .env("SCCACHE_CC", &cc)
486             .env("SCCACHE_CXX", &cxx);
487
488         // Building LLVM on MSVC can be a little ludicrous at times. We're so far
489         // off the beaten path here that I'm not really sure this is even half
490         // supported any more. Here we're trying to:
491         //
492         // * Build LLVM on MSVC
493         // * Build LLVM with `clang-cl` instead of `cl.exe`
494         // * Build a project with `sccache`
495         // * Build for 32-bit as well
496         // * Build with Ninja
497         //
498         // For `cl.exe` there are different binaries to compile 32/64 bit which
499         // we use but for `clang-cl` there's only one which internally
500         // multiplexes via flags. As a result it appears that CMake's detection
501         // of a compiler's architecture and such on MSVC **doesn't** pass any
502         // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
503         // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
504         // definitely causes problems since all the env vars are pointing to
505         // 32-bit libraries.
506         //
507         // To hack around this... again... we pass an argument that's
508         // unconditionally passed in the sccache shim. This'll get CMake to
509         // correctly diagnose it's doing a 32-bit compilation and LLVM will
510         // internally configure itself appropriately.
511         if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
512             cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
513         }
514     } else {
515         // If ccache is configured we inform the build a little differently how
516         // to invoke ccache while also invoking our compilers.
517         if use_compiler_launcher {
518             if let Some(ref ccache) = builder.config.ccache {
519                 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
520                     .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
521             }
522         }
523         cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
524             .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
525             .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
526     }
527
528     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
529     let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
530     if let Some(ref s) = builder.config.llvm_cflags {
531         cflags.push(" ");
532         cflags.push(s);
533     }
534     // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
535     if target.contains("apple-ios") {
536         if target.contains("86-") {
537             cflags.push(" -miphonesimulator-version-min=10.0");
538         } else {
539             cflags.push(" -miphoneos-version-min=10.0");
540         }
541     }
542     if builder.config.llvm_clang_cl.is_some() {
543         cflags.push(&format!(" --target={}", target));
544     }
545     cfg.define("CMAKE_C_FLAGS", cflags);
546     let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
547     if let Some(ref s) = builder.config.llvm_cxxflags {
548         cxxflags.push(" ");
549         cxxflags.push(s);
550     }
551     if builder.config.llvm_clang_cl.is_some() {
552         cxxflags.push(&format!(" --target={}", target));
553     }
554     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
555     if let Some(ar) = builder.ar(target) {
556         if ar.is_absolute() {
557             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
558             // tries to resolve this path in the LLVM build directory.
559             cfg.define("CMAKE_AR", sanitize_cc(ar));
560         }
561     }
562
563     if let Some(ranlib) = builder.ranlib(target) {
564         if ranlib.is_absolute() {
565             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
566             // tries to resolve this path in the LLVM build directory.
567             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
568         }
569     }
570
571     if let Some(ref flags) = builder.config.llvm_ldflags {
572         ldflags.push_all(flags);
573     }
574
575     if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
576         ldflags.push_all(&flags);
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         cfg.out_dir(&out_dir)
654             .profile("Release")
655             .env("LLVM_CONFIG_REAL", &llvm_config)
656             .define("LLVM_CONFIG_PATH", llvm_config_shim)
657             .define("LLVM_INCLUDE_TESTS", "OFF");
658
659         // While we're using this horrible workaround to shim the execution of
660         // llvm-config, let's just pile on more. I can't seem to figure out how
661         // to build LLD as a standalone project and also cross-compile it at the
662         // same time. It wants a natively executable `llvm-config` to learn
663         // about LLVM, but then it learns about all the host configuration of
664         // LLVM and tries to link to host LLVM libraries.
665         //
666         // To work around that we tell our shim to replace anything with the
667         // build target with the actual target instead. This'll break parts of
668         // LLD though which try to execute host tools, such as llvm-tblgen, so
669         // we specifically tell it where to find those. This is likely super
670         // brittle and will break over time. If anyone knows better how to
671         // cross-compile LLD it would be much appreciated to fix this!
672         if target != builder.config.build {
673             cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
674                 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
675                 .define(
676                     "LLVM_TABLEGEN_EXE",
677                     llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
678                 );
679         }
680
681         // Explicitly set C++ standard, because upstream doesn't do so
682         // for standalone builds.
683         cfg.define("CMAKE_CXX_STANDARD", "14");
684
685         cfg.build();
686
687         t!(File::create(&done_stamp));
688         out_dir
689     }
690 }
691
692 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
693 pub struct TestHelpers {
694     pub target: TargetSelection,
695 }
696
697 impl Step for TestHelpers {
698     type Output = ();
699
700     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
701         run.path("src/test/auxiliary/rust_test_helpers.c")
702     }
703
704     fn make_run(run: RunConfig<'_>) {
705         run.builder.ensure(TestHelpers { target: run.target })
706     }
707
708     /// Compiles the `rust_test_helpers.c` library which we used in various
709     /// `run-pass` tests for ABI testing.
710     fn run(self, builder: &Builder<'_>) {
711         if builder.config.dry_run {
712             return;
713         }
714         // The x86_64-fortanix-unknown-sgx target doesn't have a working C
715         // toolchain. However, some x86_64 ELF objects can be linked
716         // without issues. Use this hack to compile the test helpers.
717         let target = if self.target == "x86_64-fortanix-unknown-sgx" {
718             TargetSelection::from_user("x86_64-unknown-linux-gnu")
719         } else {
720             self.target
721         };
722         let dst = builder.test_helpers_out(target);
723         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
724         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
725             return;
726         }
727
728         builder.info("Building test helpers");
729         t!(fs::create_dir_all(&dst));
730         let mut cfg = cc::Build::new();
731         // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
732         if target.contains("emscripten") {
733             cfg.pic(false);
734         }
735
736         // We may have found various cross-compilers a little differently due to our
737         // extra configuration, so inform cc of these compilers. Note, though, that
738         // on MSVC we still need cc's detection of env vars (ugh).
739         if !target.contains("msvc") {
740             if let Some(ar) = builder.ar(target) {
741                 cfg.archiver(ar);
742             }
743             cfg.compiler(builder.cc(target));
744         }
745         cfg.cargo_metadata(false)
746             .out_dir(&dst)
747             .target(&target.triple)
748             .host(&builder.config.build.triple)
749             .opt_level(0)
750             .warnings(false)
751             .debug(false)
752             .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
753             .compile("rust_test_helpers");
754     }
755 }
756
757 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
758 pub struct Sanitizers {
759     pub target: TargetSelection,
760 }
761
762 impl Step for Sanitizers {
763     type Output = Vec<SanitizerRuntime>;
764
765     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
766         run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
767     }
768
769     fn make_run(run: RunConfig<'_>) {
770         run.builder.ensure(Sanitizers { target: run.target });
771     }
772
773     /// Builds sanitizer runtime libraries.
774     fn run(self, builder: &Builder<'_>) -> Self::Output {
775         let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
776         if !compiler_rt_dir.exists() {
777             return Vec::new();
778         }
779
780         let out_dir = builder.native_dir(self.target).join("sanitizers");
781         let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
782         if runtimes.is_empty() {
783             return runtimes;
784         }
785
786         let llvm_config = builder.ensure(Llvm { target: builder.config.build });
787         if builder.config.dry_run {
788             return runtimes;
789         }
790
791         let stamp = out_dir.join("sanitizers-finished-building");
792         let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
793
794         if stamp.is_done() {
795             if stamp.hash.is_none() {
796                 builder.info(&format!(
797                     "Rebuild sanitizers by removing the file `{}`",
798                     stamp.path.display()
799                 ));
800             }
801             return runtimes;
802         }
803
804         builder.info(&format!("Building sanitizers for {}", self.target));
805         t!(stamp.remove());
806         let _time = util::timeit(&builder);
807
808         let mut cfg = cmake::Config::new(&compiler_rt_dir);
809         cfg.profile("Release");
810         cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
811         cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
812         cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
813         cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
814         cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
815         cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
816         cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
817         cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
818         cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
819         cfg.define("LLVM_CONFIG_PATH", &llvm_config);
820
821         // On Darwin targets the sanitizer runtimes are build as universal binaries.
822         // Unfortunately sccache currently lacks support to build them successfully.
823         // Disable compiler launcher on Darwin targets to avoid potential issues.
824         let use_compiler_launcher = !self.target.contains("apple-darwin");
825         configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
826
827         t!(fs::create_dir_all(&out_dir));
828         cfg.out_dir(out_dir);
829
830         for runtime in &runtimes {
831             cfg.build_target(&runtime.cmake_target);
832             cfg.build();
833         }
834         t!(stamp.write());
835
836         runtimes
837     }
838 }
839
840 #[derive(Clone, Debug)]
841 pub struct SanitizerRuntime {
842     /// CMake target used to build the runtime.
843     pub cmake_target: String,
844     /// Path to the built runtime library.
845     pub path: PathBuf,
846     /// Library filename that will be used rustc.
847     pub name: String,
848 }
849
850 /// Returns sanitizers available on a given target.
851 fn supported_sanitizers(
852     out_dir: &Path,
853     target: TargetSelection,
854     channel: &str,
855 ) -> Vec<SanitizerRuntime> {
856     let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
857         components
858             .iter()
859             .map(move |c| SanitizerRuntime {
860                 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
861                 path: out_dir
862                     .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
863                 name: format!("librustc-{}_rt.{}.dylib", channel, c),
864             })
865             .collect()
866     };
867
868     let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
869         components
870             .iter()
871             .map(move |c| SanitizerRuntime {
872                 cmake_target: format!("clang_rt.{}-{}", c, arch),
873                 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
874                 name: format!("librustc-{}_rt.{}.a", channel, c),
875             })
876             .collect()
877     };
878
879     match &*target.triple {
880         "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
881         "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
882         "aarch64-unknown-linux-gnu" => {
883             common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
884         }
885         "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
886         "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
887         "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
888         "x86_64-unknown-netbsd" => {
889             common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
890         }
891         "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
892         "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
893         "x86_64-unknown-linux-gnu" => {
894             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
895         }
896         "x86_64-unknown-linux-musl" => {
897             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
898         }
899         _ => Vec::new(),
900     }
901 }
902
903 struct HashStamp {
904     path: PathBuf,
905     hash: Option<Vec<u8>>,
906 }
907
908 impl HashStamp {
909     fn new(path: PathBuf, hash: Option<&str>) -> Self {
910         HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
911     }
912
913     fn is_done(&self) -> bool {
914         match fs::read(&self.path) {
915             Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
916             Err(e) if e.kind() == io::ErrorKind::NotFound => false,
917             Err(e) => {
918                 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
919             }
920         }
921     }
922
923     fn remove(&self) -> io::Result<()> {
924         match fs::remove_file(&self.path) {
925             Ok(()) => Ok(()),
926             Err(e) => {
927                 if e.kind() == io::ErrorKind::NotFound {
928                     Ok(())
929                 } else {
930                     Err(e)
931                 }
932             }
933         }
934     }
935
936     fn write(&self) -> io::Result<()> {
937         fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
938     }
939 }
940
941 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
942 pub struct CrtBeginEnd {
943     pub target: TargetSelection,
944 }
945
946 impl Step for CrtBeginEnd {
947     type Output = PathBuf;
948
949     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
950         run.path("src/llvm-project/compiler-rt/lib/crt")
951     }
952
953     fn make_run(run: RunConfig<'_>) {
954         run.builder.ensure(CrtBeginEnd { target: run.target });
955     }
956
957     /// Build crtbegin.o/crtend.o for musl target.
958     fn run(self, builder: &Builder<'_>) -> Self::Output {
959         let out_dir = builder.native_dir(self.target).join("crt");
960
961         if builder.config.dry_run {
962             return out_dir;
963         }
964
965         let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
966         let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
967         if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
968             && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
969         {
970             return out_dir;
971         }
972
973         builder.info("Building crtbegin.o and crtend.o");
974         t!(fs::create_dir_all(&out_dir));
975
976         let mut cfg = cc::Build::new();
977
978         if let Some(ar) = builder.ar(self.target) {
979             cfg.archiver(ar);
980         }
981         cfg.compiler(builder.cc(self.target));
982         cfg.cargo_metadata(false)
983             .out_dir(&out_dir)
984             .target(&self.target.triple)
985             .host(&builder.config.build.triple)
986             .warnings(false)
987             .debug(false)
988             .opt_level(3)
989             .file(crtbegin_src)
990             .file(crtend_src);
991
992         // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
993         // Currently only consumer of those objects is musl, which use .init_array/.fini_array
994         // instead of .ctors/.dtors
995         cfg.flag("-std=c11")
996             .define("CRT_HAS_INITFINI_ARRAY", None)
997             .define("EH_USE_FRAME_REGISTRY", None);
998
999         cfg.compile("crt");
1000
1001         t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1002         t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1003         out_dir
1004     }
1005 }
1006
1007 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1008 pub struct Libunwind {
1009     pub target: TargetSelection,
1010 }
1011
1012 impl Step for Libunwind {
1013     type Output = PathBuf;
1014
1015     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1016         run.path("src/llvm-project/libunwind")
1017     }
1018
1019     fn make_run(run: RunConfig<'_>) {
1020         run.builder.ensure(Libunwind { target: run.target });
1021     }
1022
1023     /// Build linunwind.a
1024     fn run(self, builder: &Builder<'_>) -> Self::Output {
1025         if builder.config.dry_run {
1026             return PathBuf::new();
1027         }
1028
1029         let out_dir = builder.native_dir(self.target).join("libunwind");
1030         let root = builder.src.join("src/llvm-project/libunwind");
1031
1032         if up_to_date(&root, &out_dir.join("libunwind.a")) {
1033             return out_dir;
1034         }
1035
1036         builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1037         t!(fs::create_dir_all(&out_dir));
1038
1039         let mut cc_cfg = cc::Build::new();
1040         let mut cpp_cfg = cc::Build::new();
1041
1042         cpp_cfg.cpp(true);
1043         cpp_cfg.cpp_set_stdlib(None);
1044         cpp_cfg.flag("-nostdinc++");
1045         cpp_cfg.flag("-fno-exceptions");
1046         cpp_cfg.flag("-fno-rtti");
1047         cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1048
1049         for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1050             if let Some(ar) = builder.ar(self.target) {
1051                 cfg.archiver(ar);
1052             }
1053             cfg.target(&self.target.triple);
1054             cfg.host(&builder.config.build.triple);
1055             cfg.warnings(false);
1056             cfg.debug(false);
1057             // get_compiler() need set opt_level first.
1058             cfg.opt_level(3);
1059             cfg.flag("-fstrict-aliasing");
1060             cfg.flag("-funwind-tables");
1061             cfg.flag("-fvisibility=hidden");
1062             cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1063             cfg.include(root.join("include"));
1064             cfg.cargo_metadata(false);
1065             cfg.out_dir(&out_dir);
1066
1067             if self.target.contains("x86_64-fortanix-unknown-sgx") {
1068                 cfg.static_flag(true);
1069                 cfg.flag("-fno-stack-protector");
1070                 cfg.flag("-ffreestanding");
1071                 cfg.flag("-fexceptions");
1072
1073                 // easiest way to undefine since no API available in cc::Build to undefine
1074                 cfg.flag("-U_FORTIFY_SOURCE");
1075                 cfg.define("_FORTIFY_SOURCE", "0");
1076                 cfg.define("RUST_SGX", "1");
1077                 cfg.define("__NO_STRING_INLINES", None);
1078                 cfg.define("__NO_MATH_INLINES", None);
1079                 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1080                 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1081                 cfg.define("NDEBUG", None);
1082             }
1083         }
1084
1085         cc_cfg.compiler(builder.cc(self.target));
1086         if let Ok(cxx) = builder.cxx(self.target) {
1087             cpp_cfg.compiler(cxx);
1088         } else {
1089             cc_cfg.compiler(builder.cc(self.target));
1090         }
1091
1092         // Don't set this for clang
1093         // By default, Clang builds C code in GNU C17 mode.
1094         // By default, Clang builds C++ code according to the C++98 standard,
1095         // with many C++11 features accepted as extensions.
1096         if cc_cfg.get_compiler().is_like_gnu() {
1097             cc_cfg.flag("-std=c99");
1098         }
1099         if cpp_cfg.get_compiler().is_like_gnu() {
1100             cpp_cfg.flag("-std=c++11");
1101         }
1102
1103         if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1104             // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1105             // C++ compiler env variables on the builders.
1106             // Don't set this for clang++, as clang++ is able to compile this without libc++.
1107             if cpp_cfg.get_compiler().is_like_gnu() {
1108                 cpp_cfg.cpp(false);
1109                 cpp_cfg.compiler(builder.cc(self.target));
1110             }
1111         }
1112
1113         let mut c_sources = vec![
1114             "Unwind-sjlj.c",
1115             "UnwindLevel1-gcc-ext.c",
1116             "UnwindLevel1.c",
1117             "UnwindRegistersRestore.S",
1118             "UnwindRegistersSave.S",
1119         ];
1120
1121         let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1122         let cpp_len = cpp_sources.len();
1123
1124         if self.target.contains("x86_64-fortanix-unknown-sgx") {
1125             c_sources.push("UnwindRustSgx.c");
1126         }
1127
1128         for src in c_sources {
1129             cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1130         }
1131
1132         for src in &cpp_sources {
1133             cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1134         }
1135
1136         cpp_cfg.compile("unwind-cpp");
1137
1138         // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1139         let mut count = 0;
1140         for entry in fs::read_dir(&out_dir).unwrap() {
1141             let file = entry.unwrap().path().canonicalize().unwrap();
1142             if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1143                 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1144                 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1145                 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1146                     cc_cfg.object(&file);
1147                     count += 1;
1148                 }
1149             }
1150         }
1151         assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1152
1153         cc_cfg.compile("unwind");
1154         out_dir
1155     }
1156 }