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