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;
21 use crate::util::{self, exe};
22 use build_helper::up_to_date;
23 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
24 use crate::cache::Interned;
27 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
29 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")
40 .path("src/llvm-project/llvm")
42 .path("src/llvm-emscripten")
45 fn make_run(run: RunConfig) {
46 let emscripten = run.path.ends_with("llvm-emscripten");
47 run.builder.ensure(Llvm {
53 /// Compile LLVM for `target`.
54 fn run(self, builder: &Builder) -> PathBuf {
55 let target = self.target;
56 let emscripten = self.emscripten;
58 // If we're using a custom LLVM bail out here, but we can only use a
59 // custom LLVM for the build triple.
61 if let Some(config) = builder.config.target_config.get(&target) {
62 if let Some(ref s) = config.llvm_config {
63 check_llvm_version(builder, s);
64 return s.to_path_buf()
69 let rebuild_trigger = builder.src.join("src/rustllvm/llvm-rebuild-trigger");
70 let rebuild_trigger_contents = t!(fs::read_to_string(&rebuild_trigger));
72 let (out_dir, llvm_config_ret_dir) = if emscripten {
73 let dir = builder.emscripten_llvm_out(target);
74 let config_dir = dir.join("bin");
77 let mut dir = builder.llvm_out(builder.config.build);
78 if !builder.config.build.contains("msvc") || builder.config.ninja {
81 (builder.llvm_out(target), dir.join("bin"))
83 let done_stamp = out_dir.join("llvm-finished-building");
84 let build_llvm_config = llvm_config_ret_dir
85 .join(exe("llvm-config", &*builder.config.build));
86 if done_stamp.exists() {
87 let done_contents = t!(fs::read_to_string(&done_stamp));
89 // If LLVM was already built previously and contents of the rebuild-trigger file
90 // didn't change from the previous build, then no action is required.
91 if done_contents == rebuild_trigger_contents {
92 return build_llvm_config
96 let _folder = builder.fold_output(|| "llvm");
97 let descriptor = if emscripten { "Emscripten " } else { "" };
98 builder.info(&format!("Building {}LLVM for {}", descriptor, target));
99 let _time = util::timeit(&builder);
100 t!(fs::create_dir_all(&out_dir));
102 // http://llvm.org/docs/CMake.html
103 let root = if self.emscripten { "src/llvm-emscripten" } else { "src/llvm-project/llvm" };
104 let mut cfg = cmake::Config::new(builder.src.join(root));
106 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
107 (false, _) => "Debug",
108 (true, false) => "Release",
109 (true, true) => "RelWithDebInfo",
112 // NOTE: remember to also update `config.toml.example` when changing the
114 let llvm_targets = if self.emscripten {
117 match builder.config.llvm_targets {
119 None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;MSP430;Sparc;NVPTX;Hexagon",
123 let llvm_exp_targets = if self.emscripten {
126 &builder.config.llvm_experimental_targets[..]
129 let assertions = if builder.config.llvm_assertions {"ON"} else {"OFF"};
131 cfg.out_dir(&out_dir)
133 .define("LLVM_ENABLE_ASSERTIONS", assertions)
134 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
135 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
136 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
137 .define("LLVM_INCLUDE_TESTS", "OFF")
138 .define("LLVM_INCLUDE_DOCS", "OFF")
139 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
140 .define("LLVM_ENABLE_ZLIB", "OFF")
141 .define("WITH_POLLY", "OFF")
142 .define("LLVM_ENABLE_TERMINFO", "OFF")
143 .define("LLVM_ENABLE_LIBEDIT", "OFF")
144 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
145 .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
146 .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
148 if builder.config.llvm_thin_lto && !emscripten {
149 cfg.define("LLVM_ENABLE_LTO", "Thin")
150 .define("LLVM_ENABLE_LLD", "ON");
153 // By default, LLVM will automatically find OCaml and, if it finds it,
154 // install the LLVM bindings in LLVM_OCAML_INSTALL_PATH, which defaults
155 // to /usr/bin/ocaml.
156 // This causes problem for non-root builds of Rust. Side-step the issue
157 // by setting LLVM_OCAML_INSTALL_PATH to a relative path, so it installs
159 cfg.define("LLVM_OCAML_INSTALL_PATH",
160 env::var_os("LLVM_OCAML_INSTALL_PATH").unwrap_or_else(|| "usr/lib/ocaml".into()));
162 let want_lldb = builder.config.lldb_enabled && !self.emscripten;
164 // This setting makes the LLVM tools link to the dynamic LLVM library,
165 // which saves both memory during parallel links and overall disk space
166 // for the tools. We don't do this on every platform as it doesn't work
167 // equally well everywhere.
168 if builder.llvm_link_tools_dynamically(target) && !emscripten {
169 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
172 // For distribution we want the LLVM tools to be *statically* linked to libstdc++
173 if builder.config.llvm_tools_enabled || want_lldb {
174 if !target.contains("windows") {
175 if target.contains("apple") {
176 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
178 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
183 if target.contains("msvc") {
184 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
185 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
186 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
187 cfg.static_crt(true);
190 if target.starts_with("i686") {
191 cfg.define("LLVM_BUILD_32_BITS", "ON");
195 cfg.define("LLVM_ENABLE_PROJECTS", "clang;lldb");
196 // For the time being, disable code signing.
197 cfg.define("LLDB_CODESIGN_IDENTITY", "");
198 cfg.define("LLDB_NO_DEBUGSERVER", "ON");
200 // LLDB requires libxml2; but otherwise we want it to be disabled.
201 // See https://github.com/rust-lang/rust/pull/50104
202 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
205 if let Some(num_linkers) = builder.config.llvm_link_jobs {
207 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
211 // http://llvm.org/docs/HowToCrossCompileLLVM.html
212 if target != builder.config.build && !emscripten {
213 builder.ensure(Llvm {
214 target: builder.config.build,
217 // FIXME: if the llvm root for the build triple is overridden then we
218 // should use llvm-tblgen from there, also should verify that it
219 // actually exists most of the time in normal installs of LLVM.
220 let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
221 cfg.define("CMAKE_CROSSCOMPILING", "True")
222 .define("LLVM_TABLEGEN", &host);
224 if target.contains("netbsd") {
225 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
226 } else if target.contains("freebsd") {
227 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
230 cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
233 if let Some(ref suffix) = builder.config.llvm_version_suffix {
234 cfg.define("LLVM_VERSION_SUFFIX", suffix);
237 if let Some(ref linker) = builder.config.llvm_use_linker {
238 cfg.define("LLVM_USE_LINKER", linker);
241 if let Some(ref python) = builder.config.python {
242 cfg.define("PYTHON_EXECUTABLE", python);
245 configure_cmake(builder, target, &mut cfg);
247 // FIXME: we don't actually need to build all LLVM tools and all LLVM
248 // libraries here, e.g., we just want a few components and a few
249 // tools. Figure out how to filter them down and only build the right
250 // tools and libs on all platforms.
252 if builder.config.dry_run {
253 return build_llvm_config;
258 t!(fs::write(&done_stamp, &rebuild_trigger_contents));
264 fn check_llvm_version(builder: &Builder, llvm_config: &Path) {
265 if !builder.config.llvm_version_check {
269 if builder.config.dry_run {
273 let mut cmd = Command::new(llvm_config);
274 let version = output(cmd.arg("--version"));
275 let mut parts = version.split('.').take(2)
276 .filter_map(|s| s.parse::<u32>().ok());
277 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
282 panic!("\n\nbad LLVM version: {}, need >=6.0\n\n", version)
285 fn configure_cmake(builder: &Builder,
286 target: Interned<String>,
287 cfg: &mut cmake::Config) {
288 if builder.config.ninja {
289 cfg.generator("Ninja");
292 .host(&builder.config.build);
294 let sanitize_cc = |cc: &Path| {
295 if target.contains("msvc") {
296 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
298 cc.as_os_str().to_owned()
302 // MSVC with CMake uses msbuild by default which doesn't respect these
303 // vars that we'd otherwise configure. In that case we just skip this
305 if target.contains("msvc") && !builder.config.ninja {
309 let (cc, cxx) = match builder.config.llvm_clang_cl {
310 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
311 None => (builder.cc(target), builder.cxx(target).unwrap()),
314 // Handle msvc + ninja + ccache specially (this is what the bots use)
315 if target.contains("msvc") &&
316 builder.config.ninja &&
317 builder.config.ccache.is_some()
319 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
320 wrap_cc.set_file_name("sccache-plus-cl.exe");
322 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
323 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
324 cfg.env("SCCACHE_PATH",
325 builder.config.ccache.as_ref().unwrap())
326 .env("SCCACHE_TARGET", target)
327 .env("SCCACHE_CC", &cc)
328 .env("SCCACHE_CXX", &cxx);
330 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
331 // off the beaten path here that I'm not really sure this is even half
332 // supported any more. Here we're trying to:
334 // * Build LLVM on MSVC
335 // * Build LLVM with `clang-cl` instead of `cl.exe`
336 // * Build a project with `sccache`
337 // * Build for 32-bit as well
338 // * Build with Ninja
340 // For `cl.exe` there are different binaries to compile 32/64 bit which
341 // we use but for `clang-cl` there's only one which internally
342 // multiplexes via flags. As a result it appears that CMake's detection
343 // of a compiler's architecture and such on MSVC **doesn't** pass any
344 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
345 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
346 // definitely causes problems since all the env vars are pointing to
349 // To hack around this... again... we pass an argument that's
350 // unconditionally passed in the sccache shim. This'll get CMake to
351 // correctly diagnose it's doing a 32-bit compilation and LLVM will
352 // internally configure itself appropriately.
353 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
354 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
357 // If ccache is configured we inform the build a little differently how
358 // to invoke ccache while also invoking our compilers.
359 if let Some(ref ccache) = builder.config.ccache {
360 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
361 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
363 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
364 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
367 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
368 let mut cflags = builder.cflags(target, GitRepo::Llvm).join(" ");
369 if let Some(ref s) = builder.config.llvm_cxxflags {
370 cflags.push_str(&format!(" {}", s));
372 cfg.define("CMAKE_C_FLAGS", cflags);
373 let mut cxxflags = builder.cflags(target, GitRepo::Llvm).join(" ");
374 if builder.config.llvm_static_stdcpp &&
375 !target.contains("windows") &&
376 !target.contains("netbsd")
378 cxxflags.push_str(" -static-libstdc++");
380 if let Some(ref s) = builder.config.llvm_cxxflags {
381 cxxflags.push_str(&format!(" {}", s));
383 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
384 if let Some(ar) = builder.ar(target) {
385 if ar.is_absolute() {
386 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
387 // tries to resolve this path in the LLVM build directory.
388 cfg.define("CMAKE_AR", sanitize_cc(ar));
392 if let Some(ranlib) = builder.ranlib(target) {
393 if ranlib.is_absolute() {
394 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
395 // tries to resolve this path in the LLVM build directory.
396 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
400 if let Some(ref s) = builder.config.llvm_ldflags {
401 cfg.define("CMAKE_SHARED_LINKER_FLAGS", s);
402 cfg.define("CMAKE_MODULE_LINKER_FLAGS", s);
403 cfg.define("CMAKE_EXE_LINKER_FLAGS", s);
406 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
407 cfg.env("RUST_LOG", "sccache=warn");
411 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
413 pub target: Interned<String>,
417 type Output = PathBuf;
418 const ONLY_HOSTS: bool = true;
420 fn should_run(run: ShouldRun) -> ShouldRun {
421 run.path("src/llvm-project/lld").path("src/tools/lld")
424 fn make_run(run: RunConfig) {
425 run.builder.ensure(Lld { target: run.target });
428 /// Compile LLVM for `target`.
429 fn run(self, builder: &Builder) -> PathBuf {
430 if builder.config.dry_run {
431 return PathBuf::from("lld-out-dir-test-gen");
433 let target = self.target;
435 let llvm_config = builder.ensure(Llvm {
440 let out_dir = builder.lld_out(target);
441 let done_stamp = out_dir.join("lld-finished-building");
442 if done_stamp.exists() {
446 let _folder = builder.fold_output(|| "lld");
447 builder.info(&format!("Building LLD for {}", target));
448 let _time = util::timeit(&builder);
449 t!(fs::create_dir_all(&out_dir));
451 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
452 configure_cmake(builder, target, &mut cfg);
454 // This is an awful, awful hack. Discovered when we migrated to using
455 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
456 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
457 // that directory for later processing. Unfortunately if this path has
458 // forward slashes in it (which it basically always does on Windows)
459 // then CMake will hit a syntax error later on as... something isn't
462 // Instead of attempting to fix this problem in upstream CMake and/or
463 // LLVM/LLD we just hack around it here. This thin wrapper will take the
464 // output from llvm-config and replace all instances of `\` with `/` to
465 // ensure we don't hit the same bugs with escaping. It means that you
466 // can't build on a system where your paths require `\` on Windows, but
467 // there's probably a lot of reasons you can't do that other than this.
468 let llvm_config_shim = env::current_exe()
470 .with_file_name("llvm-config-wrapper");
471 cfg.out_dir(&out_dir)
473 .env("LLVM_CONFIG_REAL", llvm_config)
474 .define("LLVM_CONFIG_PATH", llvm_config_shim)
475 .define("LLVM_INCLUDE_TESTS", "OFF");
479 t!(File::create(&done_stamp));
484 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
485 pub struct TestHelpers {
486 pub target: Interned<String>,
489 impl Step for TestHelpers {
492 fn should_run(run: ShouldRun) -> ShouldRun {
493 run.path("src/test/auxiliary/rust_test_helpers.c")
496 fn make_run(run: RunConfig) {
497 run.builder.ensure(TestHelpers { target: run.target })
500 /// Compiles the `rust_test_helpers.c` library which we used in various
501 /// `run-pass` test suites for ABI testing.
502 fn run(self, builder: &Builder) {
503 if builder.config.dry_run {
506 let target = self.target;
507 let dst = builder.test_helpers_out(target);
508 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
509 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
513 let _folder = builder.fold_output(|| "build_test_helpers");
514 builder.info("Building test helpers");
515 t!(fs::create_dir_all(&dst));
516 let mut cfg = cc::Build::new();
518 // We may have found various cross-compilers a little differently due to our
519 // extra configuration, so inform gcc of these compilers. Note, though, that
520 // on MSVC we still need gcc's detection of env vars (ugh).
521 if !target.contains("msvc") {
522 if let Some(ar) = builder.ar(target) {
525 cfg.compiler(builder.cc(target));
528 cfg.cargo_metadata(false)
531 .host(&builder.config.build)
535 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
536 .compile("rust_test_helpers");