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