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