1 //! Compilation of native dependencies like LLVM.
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).
8 //! LLVM and compiler-rt are essentially just wired up to everything else to
9 //! ensure that they're always in place if needed.
12 use std::env::consts::EXE_EXTENSION;
13 use std::ffi::{OsStr, OsString};
14 use std::fs::{self, File};
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
19 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
20 use crate::config::TargetSelection;
21 use crate::util::{self, exe, output, t, up_to_date};
22 use crate::{CLang, GitRepo};
26 build_llvm_config: PathBuf,
31 // Linker flags to pass to LLVM's CMake invocation.
32 #[derive(Debug, Clone, Default)]
34 // CMAKE_EXE_LINKER_FLAGS
36 // CMAKE_SHARED_LINKER_FLAGS
38 // CMAKE_MODULE_LINKER_FLAGS
43 fn push_all(&mut self, s: impl AsRef<OsStr>) {
47 self.shared.push(" ");
49 self.module.push(" ");
54 // This returns whether we've already previously built LLVM.
56 // It's used to avoid busting caches during x.py check -- if we've already built
57 // LLVM, it's fine for us to not try to avoid doing so.
59 // This will return the llvm-config if it can get it (but it will not build it
61 pub fn prebuilt_llvm_config(
62 builder: &Builder<'_>,
63 target: TargetSelection,
64 ) -> Result<PathBuf, Meta> {
65 // If we're using a custom LLVM bail out here, but we can only use a
66 // custom LLVM for the build triple.
67 if let Some(config) = builder.config.target_config.get(&target) {
68 if let Some(ref s) = config.llvm_config {
69 check_llvm_version(builder, s);
70 return Ok(s.to_path_buf());
74 let root = "src/llvm-project/llvm";
75 let out_dir = builder.llvm_out(target);
77 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
78 if !builder.config.build.contains("msvc") || builder.ninja() {
79 llvm_config_ret_dir.push("build");
81 llvm_config_ret_dir.push("bin");
83 let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
85 let stamp = out_dir.join("llvm-finished-building");
86 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
88 if builder.config.llvm_skip_rebuild && stamp.path.exists() {
91 Using a potentially stale build of LLVM; \
92 This may not behave well.",
94 return Ok(build_llvm_config);
98 if stamp.hash.is_none() {
100 "Could not determine the LLVM submodule commit hash. \
101 Assuming that an LLVM rebuild is not necessary.",
103 builder.info(&format!(
104 "To force LLVM to rebuild, remove the file `{}`",
108 return Ok(build_llvm_config);
111 Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
114 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
116 pub target: TargetSelection,
120 type Output = PathBuf; // path to llvm-config
122 const ONLY_HOSTS: bool = true;
124 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
125 run.path("src/llvm-project").path("src/llvm-project/llvm").path("src/llvm")
128 fn make_run(run: RunConfig<'_>) {
129 run.builder.ensure(Llvm { target: run.target });
132 /// Compile LLVM for `target`.
133 fn run(self, builder: &Builder<'_>) -> PathBuf {
134 let target = self.target;
135 let target_native = if self.target.starts_with("riscv") {
136 // RISC-V target triples in Rust is not named the same as C compiler target triples.
137 // This converts Rust RISC-V target triples to C compiler triples.
138 let idx = target.triple.find('-').unwrap();
140 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
141 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
142 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
143 // Set the version suffix to 13.0 so the correct target details are used.
144 format!("{}{}", self.target, "13.0")
149 let Meta { stamp, build_llvm_config, out_dir, root } =
150 match prebuilt_llvm_config(builder, target) {
155 builder.update_submodule(&Path::new("src").join("llvm-project"));
156 if builder.config.llvm_link_shared
157 && (target.contains("windows") || target.contains("apple-darwin"))
159 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
162 builder.info(&format!("Building LLVM for {}", target));
164 let _time = util::timeit(&builder);
165 t!(fs::create_dir_all(&out_dir));
167 // https://llvm.org/docs/CMake.html
168 let mut cfg = cmake::Config::new(builder.src.join(root));
169 let mut ldflags = LdFlags::default();
171 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
172 (false, _) => "Debug",
173 (true, false) => "Release",
174 (true, true) => "RelWithDebInfo",
177 // NOTE: remember to also update `config.toml.example` when changing the
179 let llvm_targets = match &builder.config.llvm_targets {
182 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
183 Sparc;SystemZ;WebAssembly;X86"
187 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
192 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
193 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
194 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
196 cfg.out_dir(&out_dir)
198 .define("LLVM_ENABLE_ASSERTIONS", assertions)
199 .define("LLVM_ENABLE_PLUGINS", plugins)
200 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
201 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
202 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
203 .define("LLVM_INCLUDE_DOCS", "OFF")
204 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
205 .define("LLVM_INCLUDE_TESTS", enable_tests)
206 .define("LLVM_ENABLE_TERMINFO", "OFF")
207 .define("LLVM_ENABLE_LIBEDIT", "OFF")
208 .define("LLVM_ENABLE_BINDINGS", "OFF")
209 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
210 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
211 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
212 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
214 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
215 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
216 // This flag makes sure `FileCheck` is copied in the final binaries directory.
217 cfg.define("LLVM_INSTALL_UTILS", "ON");
219 if builder.config.llvm_profile_generate {
220 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
221 cfg.define("LLVM_BUILD_RUNTIME", "No");
223 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
224 cfg.define("LLVM_PROFDATA_FILE", &path);
227 if target != "aarch64-apple-darwin" && !target.contains("windows") {
228 cfg.define("LLVM_ENABLE_ZLIB", "ON");
230 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
233 // Are we compiling for iOS/tvOS?
234 if target.contains("apple-ios") || target.contains("apple-tvos") {
235 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
236 cfg.define("CMAKE_OSX_SYSROOT", "/");
237 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
238 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
239 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
240 // Zlib fails to link properly, leading to a compiler error.
241 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
244 if builder.config.llvm_thin_lto {
245 cfg.define("LLVM_ENABLE_LTO", "Thin");
246 if !target.contains("apple") {
247 cfg.define("LLVM_ENABLE_LLD", "ON");
251 // This setting makes the LLVM tools link to the dynamic LLVM library,
252 // which saves both memory during parallel links and overall disk space
253 // for the tools. We don't do this on every platform as it doesn't work
254 // equally well everywhere.
256 // If we're not linking rustc to a dynamic LLVM, though, then don't link
258 if builder.llvm_link_tools_dynamically(target) && builder.config.llvm_link_shared {
259 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
262 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
263 // We also do this if the user explicitly requested static libstdc++.
264 if builder.config.llvm_tools_enabled || builder.config.llvm_static_stdcpp {
265 if !target.contains("msvc") && !target.contains("netbsd") {
266 if target.contains("apple") {
267 ldflags.push_all("-static-libstdc++");
269 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
274 if target.starts_with("riscv") && !target.contains("freebsd") {
275 // RISC-V GCC erroneously requires linking against
276 // `libatomic` when using 1-byte and 2-byte C++
277 // atomics but the LLVM build system check cannot
278 // detect this. Therefore it is set manually here.
279 // FreeBSD uses Clang as its system compiler and
280 // provides no libatomic in its base system so does
282 ldflags.exe.push(" -latomic");
283 ldflags.shared.push(" -latomic");
286 if target.contains("msvc") {
287 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
288 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
289 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
290 cfg.static_crt(true);
293 if target.starts_with("i686") {
294 cfg.define("LLVM_BUILD_32_BITS", "ON");
297 let mut enabled_llvm_projects = Vec::new();
299 if util::forcing_clang_based_tests() {
300 enabled_llvm_projects.push("clang");
301 enabled_llvm_projects.push("compiler-rt");
304 if builder.config.llvm_polly {
305 enabled_llvm_projects.push("polly");
308 if builder.config.llvm_clang {
309 enabled_llvm_projects.push("clang");
312 // We want libxml to be disabled.
313 // See https://github.com/rust-lang/rust/pull/50104
314 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
316 if !enabled_llvm_projects.is_empty() {
317 enabled_llvm_projects.sort();
318 enabled_llvm_projects.dedup();
319 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
322 if let Some(num_linkers) = builder.config.llvm_link_jobs {
324 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
328 // Workaround for ppc32 lld limitation
329 if target == "powerpc-unknown-freebsd" {
330 ldflags.exe.push(" -fuse-ld=bfd");
333 // https://llvm.org/docs/HowToCrossCompileLLVM.html
334 if target != builder.config.build {
335 builder.ensure(Llvm { target: builder.config.build });
336 // FIXME: if the llvm root for the build triple is overridden then we
337 // should use llvm-tblgen from there, also should verify that it
338 // actually exists most of the time in normal installs of LLVM.
339 let host_bin = builder.llvm_out(builder.config.build).join("bin");
340 cfg.define("CMAKE_CROSSCOMPILING", "True");
341 cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
342 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
345 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
349 if let Some(ref suffix) = builder.config.llvm_version_suffix {
350 // Allow version-suffix="" to not define a version suffix at all.
351 if !suffix.is_empty() {
352 cfg.define("LLVM_VERSION_SUFFIX", suffix);
354 } else if builder.config.channel == "dev" {
355 // Changes to a version suffix require a complete rebuild of the LLVM.
356 // To avoid rebuilds during a time of version bump, don't include rustc
357 // release number on the dev channel.
358 cfg.define("LLVM_VERSION_SUFFIX", "-rust-dev");
360 let suffix = format!("-rust-{}-{}", builder.version, builder.config.channel);
361 cfg.define("LLVM_VERSION_SUFFIX", suffix);
364 if let Some(ref linker) = builder.config.llvm_use_linker {
365 cfg.define("LLVM_USE_LINKER", linker);
368 if builder.config.llvm_allow_old_toolchain {
369 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
372 configure_cmake(builder, target, &mut cfg, true, ldflags);
374 for (key, val) in &builder.config.llvm_build_config {
375 cfg.define(key, val);
378 // FIXME: we don't actually need to build all LLVM tools and all LLVM
379 // libraries here, e.g., we just want a few components and a few
380 // tools. Figure out how to filter them down and only build the right
381 // tools and libs on all platforms.
383 if builder.config.dry_run {
384 return build_llvm_config;
395 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
396 if !builder.config.llvm_version_check {
400 if builder.config.dry_run {
404 let mut cmd = Command::new(llvm_config);
405 let version = output(cmd.arg("--version"));
406 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
407 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
412 panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
416 builder: &Builder<'_>,
417 target: TargetSelection,
418 cfg: &mut cmake::Config,
419 use_compiler_launcher: bool,
420 mut ldflags: LdFlags,
422 // Do not print installation messages for up-to-date files.
423 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
424 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
426 // Do not allow the user's value of DESTDIR to influence where
427 // LLVM will install itself. LLVM must always be installed in our
428 // own build directories.
429 cfg.env("DESTDIR", "");
432 cfg.generator("Ninja");
434 cfg.target(&target.triple).host(&builder.config.build.triple);
436 if target != builder.config.build {
437 if target.contains("netbsd") {
438 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
439 } else if target.contains("freebsd") {
440 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
441 } else if target.contains("windows") {
442 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
443 } else if target.contains("haiku") {
444 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
445 } else if target.contains("solaris") || target.contains("illumos") {
446 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
448 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
449 // that case like CMake we cannot easily determine system version either.
451 // Since, the LLVM itself makes rather limited use of version checks in
452 // CMakeFiles (and then only in tests), and so far no issues have been
453 // reported, the system version is currently left unset.
456 let sanitize_cc = |cc: &Path| {
457 if target.contains("msvc") {
458 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
460 cc.as_os_str().to_owned()
464 // MSVC with CMake uses msbuild by default which doesn't respect these
465 // vars that we'd otherwise configure. In that case we just skip this
467 if target.contains("msvc") && !builder.ninja() {
471 let (cc, cxx) = match builder.config.llvm_clang_cl {
472 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
473 None => (builder.cc(target), builder.cxx(target).unwrap()),
476 // Handle msvc + ninja + ccache specially (this is what the bots use)
477 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
478 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
479 wrap_cc.set_file_name("sccache-plus-cl.exe");
481 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
482 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
483 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
484 .env("SCCACHE_TARGET", target.triple)
485 .env("SCCACHE_CC", &cc)
486 .env("SCCACHE_CXX", &cxx);
488 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
489 // off the beaten path here that I'm not really sure this is even half
490 // supported any more. Here we're trying to:
492 // * Build LLVM on MSVC
493 // * Build LLVM with `clang-cl` instead of `cl.exe`
494 // * Build a project with `sccache`
495 // * Build for 32-bit as well
496 // * Build with Ninja
498 // For `cl.exe` there are different binaries to compile 32/64 bit which
499 // we use but for `clang-cl` there's only one which internally
500 // multiplexes via flags. As a result it appears that CMake's detection
501 // of a compiler's architecture and such on MSVC **doesn't** pass any
502 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
503 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
504 // definitely causes problems since all the env vars are pointing to
507 // To hack around this... again... we pass an argument that's
508 // unconditionally passed in the sccache shim. This'll get CMake to
509 // correctly diagnose it's doing a 32-bit compilation and LLVM will
510 // internally configure itself appropriately.
511 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
512 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
515 // If ccache is configured we inform the build a little differently how
516 // to invoke ccache while also invoking our compilers.
517 if use_compiler_launcher {
518 if let Some(ref ccache) = builder.config.ccache {
519 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
520 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
523 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
524 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
525 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
528 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
529 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
530 if let Some(ref s) = builder.config.llvm_cflags {
534 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
535 if target.contains("apple-ios") {
536 if target.contains("86-") {
537 cflags.push(" -miphonesimulator-version-min=10.0");
539 cflags.push(" -miphoneos-version-min=10.0");
542 if builder.config.llvm_clang_cl.is_some() {
543 cflags.push(&format!(" --target={}", target));
545 cfg.define("CMAKE_C_FLAGS", cflags);
546 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
547 if let Some(ref s) = builder.config.llvm_cxxflags {
551 if builder.config.llvm_clang_cl.is_some() {
552 cxxflags.push(&format!(" --target={}", target));
554 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
555 if let Some(ar) = builder.ar(target) {
556 if ar.is_absolute() {
557 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
558 // tries to resolve this path in the LLVM build directory.
559 cfg.define("CMAKE_AR", sanitize_cc(ar));
563 if let Some(ranlib) = builder.ranlib(target) {
564 if ranlib.is_absolute() {
565 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
566 // tries to resolve this path in the LLVM build directory.
567 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
571 if let Some(ref flags) = builder.config.llvm_ldflags {
572 ldflags.push_all(flags);
575 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
576 ldflags.push_all(&flags);
579 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
580 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
581 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
583 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
584 cfg.env("RUSTC_LOG", "sccache=warn");
588 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
589 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
590 let kind = if host == target { "HOST" } else { "TARGET" };
591 let target_u = target.replace("-", "_");
592 env::var_os(&format!("{}_{}", var_base, target))
593 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
594 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
595 .or_else(|| env::var_os(var_base))
598 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
600 pub target: TargetSelection,
604 type Output = PathBuf;
605 const ONLY_HOSTS: bool = true;
607 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
608 run.path("src/llvm-project/lld").path("src/tools/lld")
611 fn make_run(run: RunConfig<'_>) {
612 run.builder.ensure(Lld { target: run.target });
615 /// Compile LLD for `target`.
616 fn run(self, builder: &Builder<'_>) -> PathBuf {
617 if builder.config.dry_run {
618 return PathBuf::from("lld-out-dir-test-gen");
620 let target = self.target;
622 let llvm_config = builder.ensure(Llvm { target: self.target });
624 let out_dir = builder.lld_out(target);
625 let done_stamp = out_dir.join("lld-finished-building");
626 if done_stamp.exists() {
630 builder.info(&format!("Building LLD for {}", target));
631 let _time = util::timeit(&builder);
632 t!(fs::create_dir_all(&out_dir));
634 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
635 configure_cmake(builder, target, &mut cfg, true, LdFlags::default());
637 // This is an awful, awful hack. Discovered when we migrated to using
638 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
639 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
640 // that directory for later processing. Unfortunately if this path has
641 // forward slashes in it (which it basically always does on Windows)
642 // then CMake will hit a syntax error later on as... something isn't
645 // Instead of attempting to fix this problem in upstream CMake and/or
646 // LLVM/LLD we just hack around it here. This thin wrapper will take the
647 // output from llvm-config and replace all instances of `\` with `/` to
648 // ensure we don't hit the same bugs with escaping. It means that you
649 // can't build on a system where your paths require `\` on Windows, but
650 // there's probably a lot of reasons you can't do that other than this.
651 let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
653 // Re-use the same flags as llvm to control the level of debug information
654 // generated for lld.
655 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
656 (false, _) => "Debug",
657 (true, false) => "Release",
658 (true, true) => "RelWithDebInfo",
661 cfg.out_dir(&out_dir)
663 .env("LLVM_CONFIG_REAL", &llvm_config)
664 .define("LLVM_CONFIG_PATH", llvm_config_shim)
665 .define("LLVM_INCLUDE_TESTS", "OFF");
667 // While we're using this horrible workaround to shim the execution of
668 // llvm-config, let's just pile on more. I can't seem to figure out how
669 // to build LLD as a standalone project and also cross-compile it at the
670 // same time. It wants a natively executable `llvm-config` to learn
671 // about LLVM, but then it learns about all the host configuration of
672 // LLVM and tries to link to host LLVM libraries.
674 // To work around that we tell our shim to replace anything with the
675 // build target with the actual target instead. This'll break parts of
676 // LLD though which try to execute host tools, such as llvm-tblgen, so
677 // we specifically tell it where to find those. This is likely super
678 // brittle and will break over time. If anyone knows better how to
679 // cross-compile LLD it would be much appreciated to fix this!
680 if target != builder.config.build {
681 cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
682 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
685 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
689 // Explicitly set C++ standard, because upstream doesn't do so
690 // for standalone builds.
691 cfg.define("CMAKE_CXX_STANDARD", "14");
695 t!(File::create(&done_stamp));
700 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
701 pub struct TestHelpers {
702 pub target: TargetSelection,
705 impl Step for TestHelpers {
708 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
709 run.path("src/test/auxiliary/rust_test_helpers.c")
712 fn make_run(run: RunConfig<'_>) {
713 run.builder.ensure(TestHelpers { target: run.target })
716 /// Compiles the `rust_test_helpers.c` library which we used in various
717 /// `run-pass` tests for ABI testing.
718 fn run(self, builder: &Builder<'_>) {
719 if builder.config.dry_run {
722 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
723 // toolchain. However, some x86_64 ELF objects can be linked
724 // without issues. Use this hack to compile the test helpers.
725 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
726 TargetSelection::from_user("x86_64-unknown-linux-gnu")
730 let dst = builder.test_helpers_out(target);
731 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
732 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
736 builder.info("Building test helpers");
737 t!(fs::create_dir_all(&dst));
738 let mut cfg = cc::Build::new();
739 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
740 if target.contains("emscripten") {
744 // We may have found various cross-compilers a little differently due to our
745 // extra configuration, so inform cc of these compilers. Note, though, that
746 // on MSVC we still need cc's detection of env vars (ugh).
747 if !target.contains("msvc") {
748 if let Some(ar) = builder.ar(target) {
751 cfg.compiler(builder.cc(target));
753 cfg.cargo_metadata(false)
755 .target(&target.triple)
756 .host(&builder.config.build.triple)
760 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
761 .compile("rust_test_helpers");
765 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
766 pub struct Sanitizers {
767 pub target: TargetSelection,
770 impl Step for Sanitizers {
771 type Output = Vec<SanitizerRuntime>;
773 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
774 run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
777 fn make_run(run: RunConfig<'_>) {
778 run.builder.ensure(Sanitizers { target: run.target });
781 /// Builds sanitizer runtime libraries.
782 fn run(self, builder: &Builder<'_>) -> Self::Output {
783 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
784 if !compiler_rt_dir.exists() {
788 let out_dir = builder.native_dir(self.target).join("sanitizers");
789 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
790 if runtimes.is_empty() {
794 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
795 if builder.config.dry_run {
799 let stamp = out_dir.join("sanitizers-finished-building");
800 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
803 if stamp.hash.is_none() {
804 builder.info(&format!(
805 "Rebuild sanitizers by removing the file `{}`",
812 builder.info(&format!("Building sanitizers for {}", self.target));
814 let _time = util::timeit(&builder);
816 let mut cfg = cmake::Config::new(&compiler_rt_dir);
817 cfg.profile("Release");
818 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
819 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
820 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
821 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
822 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
823 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
824 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
825 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
826 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
827 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
829 // On Darwin targets the sanitizer runtimes are build as universal binaries.
830 // Unfortunately sccache currently lacks support to build them successfully.
831 // Disable compiler launcher on Darwin targets to avoid potential issues.
832 let use_compiler_launcher = !self.target.contains("apple-darwin");
833 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
835 t!(fs::create_dir_all(&out_dir));
836 cfg.out_dir(out_dir);
838 for runtime in &runtimes {
839 cfg.build_target(&runtime.cmake_target);
848 #[derive(Clone, Debug)]
849 pub struct SanitizerRuntime {
850 /// CMake target used to build the runtime.
851 pub cmake_target: String,
852 /// Path to the built runtime library.
854 /// Library filename that will be used rustc.
858 /// Returns sanitizers available on a given target.
859 fn supported_sanitizers(
861 target: TargetSelection,
863 ) -> Vec<SanitizerRuntime> {
864 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
867 .map(move |c| SanitizerRuntime {
868 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
870 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
871 name: format!("librustc-{}_rt.{}.dylib", channel, c),
876 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
879 .map(move |c| SanitizerRuntime {
880 cmake_target: format!("clang_rt.{}-{}", c, arch),
881 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
882 name: format!("librustc-{}_rt.{}.a", channel, c),
887 match &*target.triple {
888 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
889 "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
890 "aarch64-unknown-linux-gnu" => {
891 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
893 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
894 "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
895 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
896 "x86_64-unknown-netbsd" => {
897 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
899 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
900 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
901 "x86_64-unknown-linux-gnu" => {
902 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
904 "x86_64-unknown-linux-musl" => {
905 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
913 hash: Option<Vec<u8>>,
917 fn new(path: PathBuf, hash: Option<&str>) -> Self {
918 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
921 fn is_done(&self) -> bool {
922 match fs::read(&self.path) {
923 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
924 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
926 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
931 fn remove(&self) -> io::Result<()> {
932 match fs::remove_file(&self.path) {
935 if e.kind() == io::ErrorKind::NotFound {
944 fn write(&self) -> io::Result<()> {
945 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
949 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
950 pub struct CrtBeginEnd {
951 pub target: TargetSelection,
954 impl Step for CrtBeginEnd {
955 type Output = PathBuf;
957 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
958 run.path("src/llvm-project/compiler-rt/lib/crt")
961 fn make_run(run: RunConfig<'_>) {
962 run.builder.ensure(CrtBeginEnd { target: run.target });
965 /// Build crtbegin.o/crtend.o for musl target.
966 fn run(self, builder: &Builder<'_>) -> Self::Output {
967 let out_dir = builder.native_dir(self.target).join("crt");
969 if builder.config.dry_run {
973 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
974 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
975 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
976 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
981 builder.info("Building crtbegin.o and crtend.o");
982 t!(fs::create_dir_all(&out_dir));
984 let mut cfg = cc::Build::new();
986 if let Some(ar) = builder.ar(self.target) {
989 cfg.compiler(builder.cc(self.target));
990 cfg.cargo_metadata(false)
992 .target(&self.target.triple)
993 .host(&builder.config.build.triple)
1000 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1001 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1002 // instead of .ctors/.dtors
1003 cfg.flag("-std=c11")
1004 .define("CRT_HAS_INITFINI_ARRAY", None)
1005 .define("EH_USE_FRAME_REGISTRY", None);
1009 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1010 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1015 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1016 pub struct Libunwind {
1017 pub target: TargetSelection,
1020 impl Step for Libunwind {
1021 type Output = PathBuf;
1023 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1024 run.path("src/llvm-project/libunwind")
1027 fn make_run(run: RunConfig<'_>) {
1028 run.builder.ensure(Libunwind { target: run.target });
1031 /// Build linunwind.a
1032 fn run(self, builder: &Builder<'_>) -> Self::Output {
1033 if builder.config.dry_run {
1034 return PathBuf::new();
1037 let out_dir = builder.native_dir(self.target).join("libunwind");
1038 let root = builder.src.join("src/llvm-project/libunwind");
1040 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1044 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1045 t!(fs::create_dir_all(&out_dir));
1047 let mut cc_cfg = cc::Build::new();
1048 let mut cpp_cfg = cc::Build::new();
1051 cpp_cfg.cpp_set_stdlib(None);
1052 cpp_cfg.flag("-nostdinc++");
1053 cpp_cfg.flag("-fno-exceptions");
1054 cpp_cfg.flag("-fno-rtti");
1055 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1057 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1058 if let Some(ar) = builder.ar(self.target) {
1061 cfg.target(&self.target.triple);
1062 cfg.host(&builder.config.build.triple);
1063 cfg.warnings(false);
1065 // get_compiler() need set opt_level first.
1067 cfg.flag("-fstrict-aliasing");
1068 cfg.flag("-funwind-tables");
1069 cfg.flag("-fvisibility=hidden");
1070 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1071 cfg.include(root.join("include"));
1072 cfg.cargo_metadata(false);
1073 cfg.out_dir(&out_dir);
1075 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1076 cfg.static_flag(true);
1077 cfg.flag("-fno-stack-protector");
1078 cfg.flag("-ffreestanding");
1079 cfg.flag("-fexceptions");
1081 // easiest way to undefine since no API available in cc::Build to undefine
1082 cfg.flag("-U_FORTIFY_SOURCE");
1083 cfg.define("_FORTIFY_SOURCE", "0");
1084 cfg.define("RUST_SGX", "1");
1085 cfg.define("__NO_STRING_INLINES", None);
1086 cfg.define("__NO_MATH_INLINES", None);
1087 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1088 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1089 cfg.define("NDEBUG", None);
1093 cc_cfg.compiler(builder.cc(self.target));
1094 if let Ok(cxx) = builder.cxx(self.target) {
1095 cpp_cfg.compiler(cxx);
1097 cc_cfg.compiler(builder.cc(self.target));
1100 // Don't set this for clang
1101 // By default, Clang builds C code in GNU C17 mode.
1102 // By default, Clang builds C++ code according to the C++98 standard,
1103 // with many C++11 features accepted as extensions.
1104 if cc_cfg.get_compiler().is_like_gnu() {
1105 cc_cfg.flag("-std=c99");
1107 if cpp_cfg.get_compiler().is_like_gnu() {
1108 cpp_cfg.flag("-std=c++11");
1111 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1112 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1113 // C++ compiler env variables on the builders.
1114 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1115 if cpp_cfg.get_compiler().is_like_gnu() {
1117 cpp_cfg.compiler(builder.cc(self.target));
1121 let mut c_sources = vec![
1123 "UnwindLevel1-gcc-ext.c",
1125 "UnwindRegistersRestore.S",
1126 "UnwindRegistersSave.S",
1129 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1130 let cpp_len = cpp_sources.len();
1132 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1133 c_sources.push("UnwindRustSgx.c");
1136 for src in c_sources {
1137 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1140 for src in &cpp_sources {
1141 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1144 cpp_cfg.compile("unwind-cpp");
1146 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1148 for entry in fs::read_dir(&out_dir).unwrap() {
1149 let file = entry.unwrap().path().canonicalize().unwrap();
1150 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1151 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1152 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1153 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1154 cc_cfg.object(&file);
1159 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1161 cc_cfg.compile("unwind");