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