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::ffi::OsString;
13 use std::fs::{self, File};
14 use std::path::{Path, PathBuf};
15 use std::process::Command;
17 use build_helper::{output, t};
21 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
22 use crate::cache::Interned;
24 use crate::util::{self, exe};
26 use build_helper::up_to_date;
28 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
30 pub target: Interned<String>,
34 type Output = PathBuf; // path to llvm-config
36 const ONLY_HOSTS: bool = true;
38 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
39 run.path("src/llvm-project").path("src/llvm-project/llvm").path("src/llvm")
42 fn make_run(run: RunConfig<'_>) {
43 run.builder.ensure(Llvm { target: run.target });
46 /// Compile LLVM for `target`.
47 fn run(self, builder: &Builder<'_>) -> PathBuf {
48 let target = self.target;
50 // If we're using a custom LLVM bail out here, but we can only use a
51 // custom LLVM for the build triple.
52 if let Some(config) = builder.config.target_config.get(&target) {
53 if let Some(ref s) = config.llvm_config {
54 check_llvm_version(builder, s);
55 return s.to_path_buf();
59 let llvm_info = &builder.in_tree_llvm_info;
60 let root = "src/llvm-project/llvm";
61 let out_dir = builder.llvm_out(target);
62 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
63 if !builder.config.build.contains("msvc") || builder.config.ninja {
64 llvm_config_ret_dir.push("build");
66 llvm_config_ret_dir.push("bin");
68 let build_llvm_config =
69 llvm_config_ret_dir.join(exe("llvm-config", &*builder.config.build));
70 let done_stamp = out_dir.join("llvm-finished-building");
72 if done_stamp.exists() {
73 if builder.config.llvm_skip_rebuild {
76 Using a potentially stale build of LLVM; \
77 This may not behave well.",
79 return build_llvm_config;
82 if let Some(llvm_commit) = llvm_info.sha() {
83 let done_contents = t!(fs::read(&done_stamp));
85 // If LLVM was already built previously and the submodule's commit didn't change
86 // from the previous build, then no action is required.
87 if done_contents == llvm_commit.as_bytes() {
88 return build_llvm_config;
92 "Could not determine the LLVM submodule commit hash. \
93 Assuming that an LLVM rebuild is not necessary.",
95 builder.info(&format!(
96 "To force LLVM to rebuild, remove the file `{}`",
99 return build_llvm_config;
103 builder.info(&format!("Building LLVM for {}", target));
104 let _time = util::timeit(&builder);
105 t!(fs::create_dir_all(&out_dir));
107 // http://llvm.org/docs/CMake.html
108 let mut cfg = cmake::Config::new(builder.src.join(root));
110 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
111 (false, _) => "Debug",
112 (true, false) => "Release",
113 (true, true) => "RelWithDebInfo",
116 // NOTE: remember to also update `config.toml.example` when changing the
118 let llvm_targets = match &builder.config.llvm_targets {
121 "AArch64;ARM;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
122 Sparc;SystemZ;WebAssembly;X86"
126 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
131 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
133 cfg.out_dir(&out_dir)
135 .define("LLVM_ENABLE_ASSERTIONS", assertions)
136 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
137 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
138 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
139 .define("LLVM_INCLUDE_TESTS", "OFF")
140 .define("LLVM_INCLUDE_DOCS", "OFF")
141 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
142 .define("LLVM_ENABLE_ZLIB", "OFF")
143 .define("WITH_POLLY", "OFF")
144 .define("LLVM_ENABLE_TERMINFO", "OFF")
145 .define("LLVM_ENABLE_LIBEDIT", "OFF")
146 .define("LLVM_ENABLE_BINDINGS", "OFF")
147 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
148 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
149 .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
150 .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
152 if builder.config.llvm_thin_lto {
153 cfg.define("LLVM_ENABLE_LTO", "Thin");
154 if !target.contains("apple") {
155 cfg.define("LLVM_ENABLE_LLD", "ON");
159 // This setting makes the LLVM tools link to the dynamic LLVM library,
160 // which saves both memory during parallel links and overall disk space
161 // for the tools. We don't do this on every platform as it doesn't work
162 // equally well everywhere.
163 if builder.llvm_link_tools_dynamically(target) {
164 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
167 // For distribution we want the LLVM tools to be *statically* linked to libstdc++
168 if builder.config.llvm_tools_enabled || builder.config.lldb_enabled {
169 if !target.contains("msvc") {
170 if target.contains("apple") {
171 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
173 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
178 if target.contains("msvc") {
179 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
180 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
181 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
182 cfg.static_crt(true);
185 if target.starts_with("i686") {
186 cfg.define("LLVM_BUILD_32_BITS", "ON");
189 let mut enabled_llvm_projects = Vec::new();
191 if util::forcing_clang_based_tests() {
192 enabled_llvm_projects.push("clang");
193 enabled_llvm_projects.push("compiler-rt");
196 if builder.config.lldb_enabled {
197 enabled_llvm_projects.push("clang");
198 enabled_llvm_projects.push("lldb");
199 // For the time being, disable code signing.
200 cfg.define("LLDB_CODESIGN_IDENTITY", "");
201 cfg.define("LLDB_NO_DEBUGSERVER", "ON");
203 // LLDB requires libxml2; but otherwise we want it to be disabled.
204 // See https://github.com/rust-lang/rust/pull/50104
205 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
208 if enabled_llvm_projects.len() > 0 {
209 enabled_llvm_projects.sort();
210 enabled_llvm_projects.dedup();
211 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
214 if let Some(num_linkers) = builder.config.llvm_link_jobs {
216 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
220 // http://llvm.org/docs/HowToCrossCompileLLVM.html
221 if target != builder.config.build {
222 builder.ensure(Llvm { target: builder.config.build });
223 // FIXME: if the llvm root for the build triple is overridden then we
224 // should use llvm-tblgen from there, also should verify that it
225 // actually exists most of the time in normal installs of LLVM.
226 let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
227 cfg.define("CMAKE_CROSSCOMPILING", "True").define("LLVM_TABLEGEN", &host);
229 if target.contains("netbsd") {
230 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
231 } else if target.contains("freebsd") {
232 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
233 } else if target.contains("windows") {
234 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
237 cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
240 if let Some(ref suffix) = builder.config.llvm_version_suffix {
241 // Allow version-suffix="" to not define a version suffix at all.
242 if !suffix.is_empty() {
243 cfg.define("LLVM_VERSION_SUFFIX", suffix);
246 let mut default_suffix =
247 format!("-rust-{}-{}", channel::CFG_RELEASE_NUM, builder.config.channel,);
248 if let Some(sha) = llvm_info.sha_short() {
249 default_suffix.push_str("-");
250 default_suffix.push_str(sha);
252 cfg.define("LLVM_VERSION_SUFFIX", default_suffix);
255 if let Some(ref linker) = builder.config.llvm_use_linker {
256 cfg.define("LLVM_USE_LINKER", linker);
259 if let Some(true) = builder.config.llvm_allow_old_toolchain {
260 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
263 if let Some(ref python) = builder.config.python {
264 cfg.define("PYTHON_EXECUTABLE", python);
267 configure_cmake(builder, target, &mut cfg);
269 // FIXME: we don't actually need to build all LLVM tools and all LLVM
270 // libraries here, e.g., we just want a few components and a few
271 // tools. Figure out how to filter them down and only build the right
272 // tools and libs on all platforms.
274 if builder.config.dry_run {
275 return build_llvm_config;
280 t!(fs::write(&done_stamp, llvm_info.sha().unwrap_or("")));
286 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
287 if !builder.config.llvm_version_check {
291 if builder.config.dry_run {
295 let mut cmd = Command::new(llvm_config);
296 let version = output(cmd.arg("--version"));
297 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
298 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
303 panic!("\n\nbad LLVM version: {}, need >=7.0\n\n", version)
306 fn configure_cmake(builder: &Builder<'_>, target: Interned<String>, cfg: &mut cmake::Config) {
307 // Do not print installation messages for up-to-date files.
308 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
309 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
311 if builder.config.ninja {
312 cfg.generator("Ninja");
314 cfg.target(&target).host(&builder.config.build);
316 let sanitize_cc = |cc: &Path| {
317 if target.contains("msvc") {
318 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
320 cc.as_os_str().to_owned()
324 // MSVC with CMake uses msbuild by default which doesn't respect these
325 // vars that we'd otherwise configure. In that case we just skip this
327 if target.contains("msvc") && !builder.config.ninja {
331 let (cc, cxx) = match builder.config.llvm_clang_cl {
332 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
333 None => (builder.cc(target), builder.cxx(target).unwrap()),
336 // Handle msvc + ninja + ccache specially (this is what the bots use)
337 if target.contains("msvc") && builder.config.ninja && builder.config.ccache.is_some() {
338 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
339 wrap_cc.set_file_name("sccache-plus-cl.exe");
341 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
342 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
343 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
344 .env("SCCACHE_TARGET", target)
345 .env("SCCACHE_CC", &cc)
346 .env("SCCACHE_CXX", &cxx);
348 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
349 // off the beaten path here that I'm not really sure this is even half
350 // supported any more. Here we're trying to:
352 // * Build LLVM on MSVC
353 // * Build LLVM with `clang-cl` instead of `cl.exe`
354 // * Build a project with `sccache`
355 // * Build for 32-bit as well
356 // * Build with Ninja
358 // For `cl.exe` there are different binaries to compile 32/64 bit which
359 // we use but for `clang-cl` there's only one which internally
360 // multiplexes via flags. As a result it appears that CMake's detection
361 // of a compiler's architecture and such on MSVC **doesn't** pass any
362 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
363 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
364 // definitely causes problems since all the env vars are pointing to
367 // To hack around this... again... we pass an argument that's
368 // unconditionally passed in the sccache shim. This'll get CMake to
369 // correctly diagnose it's doing a 32-bit compilation and LLVM will
370 // internally configure itself appropriately.
371 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
372 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
375 // If ccache is configured we inform the build a little differently how
376 // to invoke ccache while also invoking our compilers.
377 if let Some(ref ccache) = builder.config.ccache {
378 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
379 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
381 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
382 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
385 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
386 let mut cflags = builder.cflags(target, GitRepo::Llvm).join(" ");
387 if let Some(ref s) = builder.config.llvm_cflags {
388 cflags.push_str(&format!(" {}", s));
390 cfg.define("CMAKE_C_FLAGS", cflags);
391 let mut cxxflags = builder.cflags(target, GitRepo::Llvm).join(" ");
392 if builder.config.llvm_static_stdcpp && !target.contains("msvc") && !target.contains("netbsd") {
393 cxxflags.push_str(" -static-libstdc++");
395 if let Some(ref s) = builder.config.llvm_cxxflags {
396 cxxflags.push_str(&format!(" {}", s));
398 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
399 if let Some(ar) = builder.ar(target) {
400 if ar.is_absolute() {
401 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
402 // tries to resolve this path in the LLVM build directory.
403 cfg.define("CMAKE_AR", sanitize_cc(ar));
407 if let Some(ranlib) = builder.ranlib(target) {
408 if ranlib.is_absolute() {
409 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
410 // tries to resolve this path in the LLVM build directory.
411 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
415 if let Some(ref s) = builder.config.llvm_ldflags {
416 cfg.define("CMAKE_SHARED_LINKER_FLAGS", s);
417 cfg.define("CMAKE_MODULE_LINKER_FLAGS", s);
418 cfg.define("CMAKE_EXE_LINKER_FLAGS", s);
421 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
422 cfg.env("RUSTC_LOG", "sccache=warn");
426 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
428 pub target: Interned<String>,
432 type Output = PathBuf;
433 const ONLY_HOSTS: bool = true;
435 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
436 run.path("src/llvm-project/lld").path("src/tools/lld")
439 fn make_run(run: RunConfig<'_>) {
440 run.builder.ensure(Lld { target: run.target });
443 /// Compile LLVM for `target`.
444 fn run(self, builder: &Builder<'_>) -> PathBuf {
445 if builder.config.dry_run {
446 return PathBuf::from("lld-out-dir-test-gen");
448 let target = self.target;
450 let llvm_config = builder.ensure(Llvm { target: self.target });
452 let out_dir = builder.lld_out(target);
453 let done_stamp = out_dir.join("lld-finished-building");
454 if done_stamp.exists() {
458 builder.info(&format!("Building LLD for {}", target));
459 let _time = util::timeit(&builder);
460 t!(fs::create_dir_all(&out_dir));
462 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
463 configure_cmake(builder, target, &mut cfg);
465 // This is an awful, awful hack. Discovered when we migrated to using
466 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
467 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
468 // that directory for later processing. Unfortunately if this path has
469 // forward slashes in it (which it basically always does on Windows)
470 // then CMake will hit a syntax error later on as... something isn't
473 // Instead of attempting to fix this problem in upstream CMake and/or
474 // LLVM/LLD we just hack around it here. This thin wrapper will take the
475 // output from llvm-config and replace all instances of `\` with `/` to
476 // ensure we don't hit the same bugs with escaping. It means that you
477 // can't build on a system where your paths require `\` on Windows, but
478 // there's probably a lot of reasons you can't do that other than this.
479 let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
480 cfg.out_dir(&out_dir)
482 .env("LLVM_CONFIG_REAL", llvm_config)
483 .define("LLVM_CONFIG_PATH", llvm_config_shim)
484 .define("LLVM_INCLUDE_TESTS", "OFF");
488 t!(File::create(&done_stamp));
493 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
494 pub struct TestHelpers {
495 pub target: Interned<String>,
498 impl Step for TestHelpers {
501 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
502 run.path("src/test/auxiliary/rust_test_helpers.c")
505 fn make_run(run: RunConfig<'_>) {
506 run.builder.ensure(TestHelpers { target: run.target })
509 /// Compiles the `rust_test_helpers.c` library which we used in various
510 /// `run-pass` tests for ABI testing.
511 fn run(self, builder: &Builder<'_>) {
512 if builder.config.dry_run {
515 let target = self.target;
516 let dst = builder.test_helpers_out(target);
517 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
518 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
522 builder.info("Building test helpers");
523 t!(fs::create_dir_all(&dst));
524 let mut cfg = cc::Build::new();
525 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
526 if target.contains("emscripten") {
530 // We may have found various cross-compilers a little differently due to our
531 // extra configuration, so inform gcc of these compilers. Note, though, that
532 // on MSVC we still need gcc's detection of env vars (ugh).
533 if !target.contains("msvc") {
534 if let Some(ar) = builder.ar(target) {
537 cfg.compiler(builder.cc(target));
540 cfg.cargo_metadata(false)
543 .host(&builder.config.build)
547 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
548 .compile("rust_test_helpers");
552 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
553 pub struct Sanitizers {
554 pub target: Interned<String>,
557 impl Step for Sanitizers {
558 type Output = Vec<SanitizerRuntime>;
560 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
561 run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
564 fn make_run(run: RunConfig<'_>) {
565 run.builder.ensure(Sanitizers { target: run.target });
568 /// Builds sanitizer runtime libraries.
569 fn run(self, builder: &Builder<'_>) -> Self::Output {
570 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
571 if !compiler_rt_dir.exists() {
575 let out_dir = builder.native_dir(self.target).join("sanitizers");
576 let runtimes = supported_sanitizers(&out_dir, self.target);
577 if runtimes.is_empty() {
581 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
582 if builder.config.dry_run {
586 let done_stamp = out_dir.join("sanitizers-finished-building");
587 if done_stamp.exists() {
588 builder.info(&format!(
589 "Assuming that sanitizers rebuild is not necessary. \
590 To force a rebuild, remove the file `{}`",
596 builder.info(&format!("Building sanitizers for {}", self.target));
597 let _time = util::timeit(&builder);
599 let mut cfg = cmake::Config::new(&compiler_rt_dir);
600 cfg.target(&self.target);
601 cfg.host(&builder.config.build);
602 cfg.profile("Release");
604 cfg.define("CMAKE_C_COMPILER_TARGET", self.target);
605 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
606 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
607 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
608 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
609 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
610 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
611 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
612 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
613 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
615 t!(fs::create_dir_all(&out_dir));
616 cfg.out_dir(out_dir);
618 for runtime in &runtimes {
619 cfg.build_target(&runtime.cmake_target);
623 t!(fs::write(&done_stamp, b""));
629 #[derive(Clone, Debug)]
630 pub struct SanitizerRuntime {
631 /// CMake target used to build the runtime.
632 pub cmake_target: String,
633 /// Path to the built runtime library.
635 /// Library filename that will be used rustc.
639 /// Returns sanitizers available on a given target.
640 fn supported_sanitizers(out_dir: &Path, target: Interned<String>) -> Vec<SanitizerRuntime> {
641 let mut result = Vec::new();
643 "x86_64-apple-darwin" => {
644 for s in &["asan", "lsan", "tsan"] {
645 result.push(SanitizerRuntime {
646 cmake_target: format!("clang_rt.{}_osx_dynamic", s),
648 .join(&format!("build/lib/darwin/libclang_rt.{}_osx_dynamic.dylib", s)),
649 name: format!("librustc_rt.{}.dylib", s),
653 "x86_64-unknown-linux-gnu" => {
654 for s in &["asan", "lsan", "msan", "tsan"] {
655 result.push(SanitizerRuntime {
656 cmake_target: format!("clang_rt.{}-x86_64", s),
657 path: out_dir.join(&format!("build/lib/linux/libclang_rt.{}-x86_64.a", s)),
658 name: format!("librustc_rt.{}.a", s),