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, program_out_of_date, 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 maybe_download_ci_llvm(builder);
67 // If we're using a custom LLVM bail out here, but we can only use a
68 // custom LLVM for the build triple.
69 if let Some(config) = builder.config.target_config.get(&target) {
70 if let Some(ref s) = config.llvm_config {
71 check_llvm_version(builder, s);
72 return Ok(s.to_path_buf());
76 let root = "src/llvm-project/llvm";
77 let out_dir = builder.llvm_out(target);
79 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
80 if !builder.config.build.contains("msvc") || builder.ninja() {
81 llvm_config_ret_dir.push("build");
83 llvm_config_ret_dir.push("bin");
85 let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
87 let stamp = out_dir.join("llvm-finished-building");
88 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
90 if builder.config.llvm_skip_rebuild && stamp.path.exists() {
93 Using a potentially stale build of LLVM; \
94 This may not behave well.",
96 return Ok(build_llvm_config);
100 if stamp.hash.is_none() {
102 "Could not determine the LLVM submodule commit hash. \
103 Assuming that an LLVM rebuild is not necessary.",
105 builder.info(&format!(
106 "To force LLVM to rebuild, remove the file `{}`",
110 return Ok(build_llvm_config);
113 Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
116 pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) {
117 let config = &builder.config;
118 if !config.llvm_from_ci {
121 let mut rev_list = Command::new("git");
123 PathBuf::from("rev-list"),
124 format!("--author={}", builder.config.stage0_metadata.config.git_merge_commit_email).into(),
126 "--first-parent".into(),
129 builder.src.join("src/llvm-project"),
130 builder.src.join("src/bootstrap/download-ci-llvm-stamp"),
131 // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
132 builder.src.join("src/version"),
134 let llvm_sha = output(&mut rev_list);
135 let llvm_sha = llvm_sha.trim();
138 eprintln!("error: could not find commit hash for downloading LLVM");
139 eprintln!("help: maybe your repository history is too shallow?");
140 eprintln!("help: consider disabling `download-ci-llvm`");
141 eprintln!("help: or fetch enough history to include one upstream commit");
145 let llvm_root = config.ci_llvm_root();
146 let llvm_stamp = llvm_root.join(".llvm-stamp");
147 let key = format!("{}{}", llvm_sha, config.llvm_assertions);
148 if program_out_of_date(&llvm_stamp, &key) && !config.dry_run {
149 download_ci_llvm(builder, &llvm_sha);
150 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
151 builder.fix_bin_or_dylib(&t!(entry).path());
154 // Update the timestamp of llvm-config to force rustc_llvm to be
155 // rebuilt. This is a hacky workaround for a deficiency in Cargo where
156 // the rerun-if-changed directive doesn't handle changes very well.
157 // https://github.com/rust-lang/cargo/issues/10791
158 // Cargo only compares the timestamp of the file relative to the last
159 // time `rustc_llvm` build script ran. However, the timestamps of the
160 // files in the tarball are in the past, so it doesn't trigger a
162 let now = filetime::FileTime::from_system_time(std::time::SystemTime::now());
163 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", builder.config.build));
164 t!(filetime::set_file_times(&llvm_config, now, now));
166 let llvm_lib = llvm_root.join("lib");
167 for entry in t!(fs::read_dir(&llvm_lib)) {
168 let lib = t!(entry).path();
169 if lib.extension().map_or(false, |ext| ext == "so") {
170 builder.fix_bin_or_dylib(&lib);
173 t!(fs::write(llvm_stamp, key));
177 fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) {
178 let llvm_assertions = builder.config.llvm_assertions;
180 let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
181 let cache_dst = builder.out.join("cache");
182 let rustc_cache = cache_dst.join(cache_prefix);
183 if !rustc_cache.exists() {
184 t!(fs::create_dir_all(&rustc_cache));
186 let base = if llvm_assertions {
187 &builder.config.stage0_metadata.config.artifacts_with_llvm_assertions_server
189 &builder.config.stage0_metadata.config.artifacts_server
191 let filename = format!("rust-dev-nightly-{}.tar.xz", builder.build.build.triple);
192 let tarball = rustc_cache.join(&filename);
193 if !tarball.exists() {
194 let help_on_error = "error: failed to download llvm from ci
196 help: old builds get deleted after a certain time
197 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
200 download-ci-llvm = false
202 builder.download_component(
203 &format!("{base}/{llvm_sha}/{filename}"),
208 let llvm_root = builder.config.ci_llvm_root();
209 builder.unpack(&tarball, &llvm_root, "rust-dev");
212 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
214 pub target: TargetSelection,
218 type Output = PathBuf; // path to llvm-config
220 const ONLY_HOSTS: bool = true;
222 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
223 run.path("src/llvm-project").path("src/llvm-project/llvm")
226 fn make_run(run: RunConfig<'_>) {
227 run.builder.ensure(Llvm { target: run.target });
230 /// Compile LLVM for `target`.
231 fn run(self, builder: &Builder<'_>) -> PathBuf {
232 let target = self.target;
233 let target_native = if self.target.starts_with("riscv") {
234 // RISC-V target triples in Rust is not named the same as C compiler target triples.
235 // This converts Rust RISC-V target triples to C compiler triples.
236 let idx = target.triple.find('-').unwrap();
238 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
239 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
240 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
241 // Set the version suffix to 13.0 so the correct target details are used.
242 format!("{}{}", self.target, "13.0")
247 let Meta { stamp, build_llvm_config, out_dir, root } =
248 match prebuilt_llvm_config(builder, target) {
253 builder.update_submodule(&Path::new("src").join("llvm-project"));
254 if builder.llvm_link_shared() && target.contains("windows") {
255 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
258 builder.info(&format!("Building LLVM for {}", target));
260 let _time = util::timeit(&builder);
261 t!(fs::create_dir_all(&out_dir));
263 // https://llvm.org/docs/CMake.html
264 let mut cfg = cmake::Config::new(builder.src.join(root));
265 let mut ldflags = LdFlags::default();
267 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
268 (false, _) => "Debug",
269 (true, false) => "Release",
270 (true, true) => "RelWithDebInfo",
273 // NOTE: remember to also update `config.toml.example` when changing the
275 let llvm_targets = match &builder.config.llvm_targets {
278 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
279 Sparc;SystemZ;WebAssembly;X86"
283 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
288 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
289 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
290 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
292 cfg.out_dir(&out_dir)
294 .define("LLVM_ENABLE_ASSERTIONS", assertions)
295 .define("LLVM_ENABLE_PLUGINS", plugins)
296 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
297 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
298 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
299 .define("LLVM_INCLUDE_DOCS", "OFF")
300 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
301 .define("LLVM_INCLUDE_TESTS", enable_tests)
302 .define("LLVM_ENABLE_TERMINFO", "OFF")
303 .define("LLVM_ENABLE_LIBEDIT", "OFF")
304 .define("LLVM_ENABLE_BINDINGS", "OFF")
305 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
306 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
307 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
308 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
310 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
311 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
312 // This flag makes sure `FileCheck` is copied in the final binaries directory.
313 cfg.define("LLVM_INSTALL_UTILS", "ON");
315 if builder.config.llvm_profile_generate {
316 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
317 if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
318 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
320 cfg.define("LLVM_BUILD_RUNTIME", "No");
322 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
323 cfg.define("LLVM_PROFDATA_FILE", &path);
326 if target != "aarch64-apple-darwin" && !target.contains("windows") {
327 cfg.define("LLVM_ENABLE_ZLIB", "ON");
329 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
332 // Are we compiling for iOS/tvOS/watchOS?
333 if target.contains("apple-ios")
334 || target.contains("apple-tvos")
335 || target.contains("apple-watchos")
337 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
338 cfg.define("CMAKE_OSX_SYSROOT", "/");
339 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
340 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
341 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
342 // Zlib fails to link properly, leading to a compiler error.
343 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
346 if builder.config.llvm_thin_lto {
347 cfg.define("LLVM_ENABLE_LTO", "Thin");
348 if !target.contains("apple") {
349 cfg.define("LLVM_ENABLE_LLD", "ON");
353 // This setting makes the LLVM tools link to the dynamic LLVM library,
354 // which saves both memory during parallel links and overall disk space
355 // for the tools. We don't do this on every platform as it doesn't work
356 // equally well everywhere.
358 // If we're not linking rustc to a dynamic LLVM, though, then don't link
360 let llvm_link_shared =
361 builder.llvm_link_tools_dynamically(target) && builder.llvm_link_shared();
362 if llvm_link_shared {
363 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
366 if target.starts_with("riscv") && !target.contains("freebsd") {
367 // RISC-V GCC erroneously requires linking against
368 // `libatomic` when using 1-byte and 2-byte C++
369 // atomics but the LLVM build system check cannot
370 // detect this. Therefore it is set manually here.
371 // FreeBSD uses Clang as its system compiler and
372 // provides no libatomic in its base system so does
374 ldflags.exe.push(" -latomic");
375 ldflags.shared.push(" -latomic");
378 if target.contains("msvc") {
379 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
380 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
381 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
382 cfg.static_crt(true);
385 if target.starts_with("i686") {
386 cfg.define("LLVM_BUILD_32_BITS", "ON");
389 let mut enabled_llvm_projects = Vec::new();
391 if util::forcing_clang_based_tests() {
392 enabled_llvm_projects.push("clang");
393 enabled_llvm_projects.push("compiler-rt");
396 if builder.config.llvm_polly {
397 enabled_llvm_projects.push("polly");
400 if builder.config.llvm_clang {
401 enabled_llvm_projects.push("clang");
404 // We want libxml to be disabled.
405 // See https://github.com/rust-lang/rust/pull/50104
406 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
408 if !enabled_llvm_projects.is_empty() {
409 enabled_llvm_projects.sort();
410 enabled_llvm_projects.dedup();
411 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
414 if let Some(num_linkers) = builder.config.llvm_link_jobs {
416 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
420 // Workaround for ppc32 lld limitation
421 if target == "powerpc-unknown-freebsd" {
422 ldflags.exe.push(" -fuse-ld=bfd");
425 // https://llvm.org/docs/HowToCrossCompileLLVM.html
426 if target != builder.config.build {
427 builder.ensure(Llvm { target: builder.config.build });
428 // FIXME: if the llvm root for the build triple is overridden then we
429 // should use llvm-tblgen from there, also should verify that it
430 // actually exists most of the time in normal installs of LLVM.
431 let host_bin = builder.llvm_out(builder.config.build).join("bin");
432 cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
433 // LLVM_NM is required for cross compiling using MSVC
434 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
437 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
439 if builder.config.llvm_clang {
440 let build_bin = builder.llvm_out(builder.config.build).join("build").join("bin");
441 let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
442 if !builder.config.dry_run && !clang_tblgen.exists() {
443 panic!("unable to find {}", clang_tblgen.display());
445 cfg.define("CLANG_TABLEGEN", clang_tblgen);
449 let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
450 // Allow version-suffix="" to not define a version suffix at all.
451 if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
452 } else if builder.config.channel == "dev" {
453 // Changes to a version suffix require a complete rebuild of the LLVM.
454 // To avoid rebuilds during a time of version bump, don't include rustc
455 // release number on the dev channel.
456 Some("-rust-dev".to_string())
458 Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
460 if let Some(ref suffix) = llvm_version_suffix {
461 cfg.define("LLVM_VERSION_SUFFIX", suffix);
464 if let Some(ref linker) = builder.config.llvm_use_linker {
465 cfg.define("LLVM_USE_LINKER", linker);
468 if builder.config.llvm_allow_old_toolchain {
469 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
472 configure_cmake(builder, target, &mut cfg, true, ldflags);
474 for (key, val) in &builder.config.llvm_build_config {
475 cfg.define(key, val);
478 // FIXME: we don't actually need to build all LLVM tools and all LLVM
479 // libraries here, e.g., we just want a few components and a few
480 // tools. Figure out how to filter them down and only build the right
481 // tools and libs on all platforms.
483 if builder.config.dry_run {
484 return build_llvm_config;
489 // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
490 // libLLVM.dylib will be built. However, llvm-config will still look
491 // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
492 // link to make llvm-config happy.
493 if llvm_link_shared && target.contains("apple-darwin") {
494 let mut cmd = Command::new(&build_llvm_config);
495 let version = output(cmd.arg("--version"));
496 let major = version.split('.').next().unwrap();
497 let lib_name = match llvm_version_suffix {
498 Some(s) => format!("libLLVM-{}{}.dylib", major, s),
499 None => format!("libLLVM-{}.dylib", major),
502 let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
503 if !lib_llvm.exists() {
504 t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
514 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
515 if !builder.config.llvm_version_check {
519 if builder.config.dry_run {
523 let mut cmd = Command::new(llvm_config);
524 let version = output(cmd.arg("--version"));
525 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
526 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
531 panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
535 builder: &Builder<'_>,
536 target: TargetSelection,
537 cfg: &mut cmake::Config,
538 use_compiler_launcher: bool,
539 mut ldflags: LdFlags,
541 // Do not print installation messages for up-to-date files.
542 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
543 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
545 // Do not allow the user's value of DESTDIR to influence where
546 // LLVM will install itself. LLVM must always be installed in our
547 // own build directories.
548 cfg.env("DESTDIR", "");
551 cfg.generator("Ninja");
553 cfg.target(&target.triple).host(&builder.config.build.triple);
555 if target != builder.config.build {
556 cfg.define("CMAKE_CROSSCOMPILING", "True");
558 if target.contains("netbsd") {
559 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
560 } else if target.contains("freebsd") {
561 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
562 } else if target.contains("windows") {
563 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
564 } else if target.contains("haiku") {
565 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
566 } else if target.contains("solaris") || target.contains("illumos") {
567 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
569 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
570 // that case like CMake we cannot easily determine system version either.
572 // Since, the LLVM itself makes rather limited use of version checks in
573 // CMakeFiles (and then only in tests), and so far no issues have been
574 // reported, the system version is currently left unset.
576 if target.contains("darwin") {
577 // Make sure that CMake does not build universal binaries on macOS.
578 // Explicitly specifiy the one single target architecture.
579 if target.starts_with("aarch64") {
580 // macOS uses a different name for building arm64
581 cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
583 cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
588 let sanitize_cc = |cc: &Path| {
589 if target.contains("msvc") {
590 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
592 cc.as_os_str().to_owned()
596 // MSVC with CMake uses msbuild by default which doesn't respect these
597 // vars that we'd otherwise configure. In that case we just skip this
599 if target.contains("msvc") && !builder.ninja() {
603 let (cc, cxx) = match builder.config.llvm_clang_cl {
604 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
605 None => (builder.cc(target), builder.cxx(target).unwrap()),
608 // Handle msvc + ninja + ccache specially (this is what the bots use)
609 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
610 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
611 wrap_cc.set_file_name("sccache-plus-cl.exe");
613 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
614 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
615 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
616 .env("SCCACHE_TARGET", target.triple)
617 .env("SCCACHE_CC", &cc)
618 .env("SCCACHE_CXX", &cxx);
620 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
621 // off the beaten path here that I'm not really sure this is even half
622 // supported any more. Here we're trying to:
624 // * Build LLVM on MSVC
625 // * Build LLVM with `clang-cl` instead of `cl.exe`
626 // * Build a project with `sccache`
627 // * Build for 32-bit as well
628 // * Build with Ninja
630 // For `cl.exe` there are different binaries to compile 32/64 bit which
631 // we use but for `clang-cl` there's only one which internally
632 // multiplexes via flags. As a result it appears that CMake's detection
633 // of a compiler's architecture and such on MSVC **doesn't** pass any
634 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
635 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
636 // definitely causes problems since all the env vars are pointing to
639 // To hack around this... again... we pass an argument that's
640 // unconditionally passed in the sccache shim. This'll get CMake to
641 // correctly diagnose it's doing a 32-bit compilation and LLVM will
642 // internally configure itself appropriately.
643 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
644 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
647 // If ccache is configured we inform the build a little differently how
648 // to invoke ccache while also invoking our compilers.
649 if use_compiler_launcher {
650 if let Some(ref ccache) = builder.config.ccache {
651 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
652 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
655 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
656 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
657 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
660 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
661 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
662 if let Some(ref s) = builder.config.llvm_cflags {
666 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
667 if target.contains("apple-ios") {
668 if target.contains("86-") {
669 cflags.push(" -miphonesimulator-version-min=10.0");
671 cflags.push(" -miphoneos-version-min=10.0");
674 if builder.config.llvm_clang_cl.is_some() {
675 cflags.push(&format!(" --target={}", target));
677 cfg.define("CMAKE_C_FLAGS", cflags);
678 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
679 if let Some(ref s) = builder.config.llvm_cxxflags {
683 if builder.config.llvm_clang_cl.is_some() {
684 cxxflags.push(&format!(" --target={}", target));
686 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
687 if let Some(ar) = builder.ar(target) {
688 if ar.is_absolute() {
689 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
690 // tries to resolve this path in the LLVM build directory.
691 cfg.define("CMAKE_AR", sanitize_cc(ar));
695 if let Some(ranlib) = builder.ranlib(target) {
696 if ranlib.is_absolute() {
697 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
698 // tries to resolve this path in the LLVM build directory.
699 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
703 if let Some(ref flags) = builder.config.llvm_ldflags {
704 ldflags.push_all(flags);
707 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
708 ldflags.push_all(&flags);
711 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
712 // We also do this if the user explicitly requested static libstdc++.
713 if builder.config.llvm_static_stdcpp {
714 if !target.contains("msvc") && !target.contains("netbsd") && !target.contains("solaris") {
715 if target.contains("apple") || target.contains("windows") {
716 ldflags.push_all("-static-libstdc++");
718 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
723 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
724 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
725 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
727 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
728 cfg.env("RUSTC_LOG", "sccache=warn");
732 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
733 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
734 let kind = if host == target { "HOST" } else { "TARGET" };
735 let target_u = target.replace("-", "_");
736 env::var_os(&format!("{}_{}", var_base, target))
737 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
738 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
739 .or_else(|| env::var_os(var_base))
742 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
744 pub target: TargetSelection,
748 type Output = PathBuf;
749 const ONLY_HOSTS: bool = true;
751 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
752 run.path("src/llvm-project/lld")
755 fn make_run(run: RunConfig<'_>) {
756 run.builder.ensure(Lld { target: run.target });
759 /// Compile LLD for `target`.
760 fn run(self, builder: &Builder<'_>) -> PathBuf {
761 if builder.config.dry_run {
762 return PathBuf::from("lld-out-dir-test-gen");
764 let target = self.target;
766 let llvm_config = builder.ensure(Llvm { target: self.target });
768 let out_dir = builder.lld_out(target);
769 let done_stamp = out_dir.join("lld-finished-building");
770 if done_stamp.exists() {
774 builder.info(&format!("Building LLD for {}", target));
775 let _time = util::timeit(&builder);
776 t!(fs::create_dir_all(&out_dir));
778 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
779 configure_cmake(builder, target, &mut cfg, true, LdFlags::default());
781 // This is an awful, awful hack. Discovered when we migrated to using
782 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
783 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
784 // that directory for later processing. Unfortunately if this path has
785 // forward slashes in it (which it basically always does on Windows)
786 // then CMake will hit a syntax error later on as... something isn't
789 // Instead of attempting to fix this problem in upstream CMake and/or
790 // LLVM/LLD we just hack around it here. This thin wrapper will take the
791 // output from llvm-config and replace all instances of `\` with `/` to
792 // ensure we don't hit the same bugs with escaping. It means that you
793 // can't build on a system where your paths require `\` on Windows, but
794 // there's probably a lot of reasons you can't do that other than this.
795 let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
797 // Re-use the same flags as llvm to control the level of debug information
798 // generated for lld.
799 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
800 (false, _) => "Debug",
801 (true, false) => "Release",
802 (true, true) => "RelWithDebInfo",
805 cfg.out_dir(&out_dir)
807 .env("LLVM_CONFIG_REAL", &llvm_config)
808 .define("LLVM_CONFIG_PATH", llvm_config_shim)
809 .define("LLVM_INCLUDE_TESTS", "OFF");
811 if builder.config.llvm_allow_old_toolchain {
812 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
815 // While we're using this horrible workaround to shim the execution of
816 // llvm-config, let's just pile on more. I can't seem to figure out how
817 // to build LLD as a standalone project and also cross-compile it at the
818 // same time. It wants a natively executable `llvm-config` to learn
819 // about LLVM, but then it learns about all the host configuration of
820 // LLVM and tries to link to host LLVM libraries.
822 // To work around that we tell our shim to replace anything with the
823 // build target with the actual target instead. This'll break parts of
824 // LLD though which try to execute host tools, such as llvm-tblgen, so
825 // we specifically tell it where to find those. This is likely super
826 // brittle and will break over time. If anyone knows better how to
827 // cross-compile LLD it would be much appreciated to fix this!
828 if target != builder.config.build {
829 cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
830 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
833 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
837 // Explicitly set C++ standard, because upstream doesn't do so
838 // for standalone builds.
839 cfg.define("CMAKE_CXX_STANDARD", "14");
843 t!(File::create(&done_stamp));
848 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
849 pub struct TestHelpers {
850 pub target: TargetSelection,
853 impl Step for TestHelpers {
856 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
857 run.path("src/test/auxiliary/rust_test_helpers.c")
860 fn make_run(run: RunConfig<'_>) {
861 run.builder.ensure(TestHelpers { target: run.target })
864 /// Compiles the `rust_test_helpers.c` library which we used in various
865 /// `run-pass` tests for ABI testing.
866 fn run(self, builder: &Builder<'_>) {
867 if builder.config.dry_run {
870 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
871 // toolchain. However, some x86_64 ELF objects can be linked
872 // without issues. Use this hack to compile the test helpers.
873 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
874 TargetSelection::from_user("x86_64-unknown-linux-gnu")
878 let dst = builder.test_helpers_out(target);
879 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
880 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
884 builder.info("Building test helpers");
885 t!(fs::create_dir_all(&dst));
886 let mut cfg = cc::Build::new();
887 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
888 if target.contains("emscripten") {
892 // We may have found various cross-compilers a little differently due to our
893 // extra configuration, so inform cc of these compilers. Note, though, that
894 // on MSVC we still need cc's detection of env vars (ugh).
895 if !target.contains("msvc") {
896 if let Some(ar) = builder.ar(target) {
899 cfg.compiler(builder.cc(target));
901 cfg.cargo_metadata(false)
903 .target(&target.triple)
904 .host(&builder.config.build.triple)
908 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
909 .compile("rust_test_helpers");
913 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
914 pub struct Sanitizers {
915 pub target: TargetSelection,
918 impl Step for Sanitizers {
919 type Output = Vec<SanitizerRuntime>;
921 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
922 run.alias("sanitizers")
925 fn make_run(run: RunConfig<'_>) {
926 run.builder.ensure(Sanitizers { target: run.target });
929 /// Builds sanitizer runtime libraries.
930 fn run(self, builder: &Builder<'_>) -> Self::Output {
931 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
932 if !compiler_rt_dir.exists() {
936 let out_dir = builder.native_dir(self.target).join("sanitizers");
937 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
938 if runtimes.is_empty() {
942 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
943 if builder.config.dry_run {
947 let stamp = out_dir.join("sanitizers-finished-building");
948 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
951 if stamp.hash.is_none() {
952 builder.info(&format!(
953 "Rebuild sanitizers by removing the file `{}`",
960 builder.info(&format!("Building sanitizers for {}", self.target));
962 let _time = util::timeit(&builder);
964 let mut cfg = cmake::Config::new(&compiler_rt_dir);
965 cfg.profile("Release");
966 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
967 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
968 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
969 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
970 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
971 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
972 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
973 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
974 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
975 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
977 // On Darwin targets the sanitizer runtimes are build as universal binaries.
978 // Unfortunately sccache currently lacks support to build them successfully.
979 // Disable compiler launcher on Darwin targets to avoid potential issues.
980 let use_compiler_launcher = !self.target.contains("apple-darwin");
981 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
983 t!(fs::create_dir_all(&out_dir));
984 cfg.out_dir(out_dir);
986 for runtime in &runtimes {
987 cfg.build_target(&runtime.cmake_target);
996 #[derive(Clone, Debug)]
997 pub struct SanitizerRuntime {
998 /// CMake target used to build the runtime.
999 pub cmake_target: String,
1000 /// Path to the built runtime library.
1002 /// Library filename that will be used rustc.
1006 /// Returns sanitizers available on a given target.
1007 fn supported_sanitizers(
1009 target: TargetSelection,
1011 ) -> Vec<SanitizerRuntime> {
1012 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1015 .map(move |c| SanitizerRuntime {
1016 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
1018 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
1019 name: format!("librustc-{}_rt.{}.dylib", channel, c),
1024 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1027 .map(move |c| SanitizerRuntime {
1028 cmake_target: format!("clang_rt.{}-{}", c, arch),
1029 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
1030 name: format!("librustc-{}_rt.{}.a", channel, c),
1035 match &*target.triple {
1036 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1037 "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1038 "aarch64-unknown-linux-gnu" => {
1039 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1041 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1042 "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1043 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1044 "x86_64-unknown-netbsd" => {
1045 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1047 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1048 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1049 "x86_64-unknown-linux-gnu" => {
1050 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1052 "x86_64-unknown-linux-musl" => {
1053 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1061 hash: Option<Vec<u8>>,
1065 fn new(path: PathBuf, hash: Option<&str>) -> Self {
1066 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1069 fn is_done(&self) -> bool {
1070 match fs::read(&self.path) {
1071 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1072 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1074 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1079 fn remove(&self) -> io::Result<()> {
1080 match fs::remove_file(&self.path) {
1083 if e.kind() == io::ErrorKind::NotFound {
1092 fn write(&self) -> io::Result<()> {
1093 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1097 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1098 pub struct CrtBeginEnd {
1099 pub target: TargetSelection,
1102 impl Step for CrtBeginEnd {
1103 type Output = PathBuf;
1105 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1106 run.path("src/llvm-project/compiler-rt/lib/crt")
1109 fn make_run(run: RunConfig<'_>) {
1110 run.builder.ensure(CrtBeginEnd { target: run.target });
1113 /// Build crtbegin.o/crtend.o for musl target.
1114 fn run(self, builder: &Builder<'_>) -> Self::Output {
1115 let out_dir = builder.native_dir(self.target).join("crt");
1117 if builder.config.dry_run {
1121 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1122 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1123 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1124 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1129 builder.info("Building crtbegin.o and crtend.o");
1130 t!(fs::create_dir_all(&out_dir));
1132 let mut cfg = cc::Build::new();
1134 if let Some(ar) = builder.ar(self.target) {
1137 cfg.compiler(builder.cc(self.target));
1138 cfg.cargo_metadata(false)
1140 .target(&self.target.triple)
1141 .host(&builder.config.build.triple)
1148 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1149 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1150 // instead of .ctors/.dtors
1151 cfg.flag("-std=c11")
1152 .define("CRT_HAS_INITFINI_ARRAY", None)
1153 .define("EH_USE_FRAME_REGISTRY", None);
1157 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1158 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1163 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1164 pub struct Libunwind {
1165 pub target: TargetSelection,
1168 impl Step for Libunwind {
1169 type Output = PathBuf;
1171 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1172 run.path("src/llvm-project/libunwind")
1175 fn make_run(run: RunConfig<'_>) {
1176 run.builder.ensure(Libunwind { target: run.target });
1179 /// Build linunwind.a
1180 fn run(self, builder: &Builder<'_>) -> Self::Output {
1181 if builder.config.dry_run {
1182 return PathBuf::new();
1185 let out_dir = builder.native_dir(self.target).join("libunwind");
1186 let root = builder.src.join("src/llvm-project/libunwind");
1188 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1192 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1193 t!(fs::create_dir_all(&out_dir));
1195 let mut cc_cfg = cc::Build::new();
1196 let mut cpp_cfg = cc::Build::new();
1199 cpp_cfg.cpp_set_stdlib(None);
1200 cpp_cfg.flag("-nostdinc++");
1201 cpp_cfg.flag("-fno-exceptions");
1202 cpp_cfg.flag("-fno-rtti");
1203 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1205 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1206 if let Some(ar) = builder.ar(self.target) {
1209 cfg.target(&self.target.triple);
1210 cfg.host(&builder.config.build.triple);
1211 cfg.warnings(false);
1213 // get_compiler() need set opt_level first.
1215 cfg.flag("-fstrict-aliasing");
1216 cfg.flag("-funwind-tables");
1217 cfg.flag("-fvisibility=hidden");
1218 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1219 cfg.include(root.join("include"));
1220 cfg.cargo_metadata(false);
1221 cfg.out_dir(&out_dir);
1223 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1224 cfg.static_flag(true);
1225 cfg.flag("-fno-stack-protector");
1226 cfg.flag("-ffreestanding");
1227 cfg.flag("-fexceptions");
1229 // easiest way to undefine since no API available in cc::Build to undefine
1230 cfg.flag("-U_FORTIFY_SOURCE");
1231 cfg.define("_FORTIFY_SOURCE", "0");
1232 cfg.define("RUST_SGX", "1");
1233 cfg.define("__NO_STRING_INLINES", None);
1234 cfg.define("__NO_MATH_INLINES", None);
1235 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1236 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1237 cfg.define("NDEBUG", None);
1239 if self.target.contains("windows") {
1240 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1241 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1245 cc_cfg.compiler(builder.cc(self.target));
1246 if let Ok(cxx) = builder.cxx(self.target) {
1247 cpp_cfg.compiler(cxx);
1249 cc_cfg.compiler(builder.cc(self.target));
1252 // Don't set this for clang
1253 // By default, Clang builds C code in GNU C17 mode.
1254 // By default, Clang builds C++ code according to the C++98 standard,
1255 // with many C++11 features accepted as extensions.
1256 if cc_cfg.get_compiler().is_like_gnu() {
1257 cc_cfg.flag("-std=c99");
1259 if cpp_cfg.get_compiler().is_like_gnu() {
1260 cpp_cfg.flag("-std=c++11");
1263 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1264 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1265 // C++ compiler env variables on the builders.
1266 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1267 if cpp_cfg.get_compiler().is_like_gnu() {
1269 cpp_cfg.compiler(builder.cc(self.target));
1273 let mut c_sources = vec![
1275 "UnwindLevel1-gcc-ext.c",
1277 "UnwindRegistersRestore.S",
1278 "UnwindRegistersSave.S",
1281 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1282 let cpp_len = cpp_sources.len();
1284 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1285 c_sources.push("UnwindRustSgx.c");
1288 for src in c_sources {
1289 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1292 for src in &cpp_sources {
1293 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1296 cpp_cfg.compile("unwind-cpp");
1298 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1300 for entry in fs::read_dir(&out_dir).unwrap() {
1301 let file = entry.unwrap().path().canonicalize().unwrap();
1302 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1303 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1304 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1305 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1306 cc_cfg.object(&file);
1311 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1313 cc_cfg.compile("unwind");