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