]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
f02def3e1b05dcf0c32a94c7237af828903d0a65
[rust.git] / src / bootstrap / native.rs
1 //! Compilation of native dependencies like LLVM.
2 //!
3 //! Native projects like LLVM unfortunately aren't suited just yet for
4 //! compilation in build scripts that Cargo has. This is because the
5 //! compilation takes a *very* long time but also because we don't want to
6 //! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
7 //!
8 //! LLVM and compiler-rt are essentially just wired up to everything else to
9 //! ensure that they're always in place if needed.
10
11 use std::env;
12 use std::ffi::OsString;
13 use std::fs::{self, File};
14 use std::path::{Path, PathBuf};
15 use std::process::Command;
16
17 use build_helper::{output, t};
18 use cmake;
19 use cc;
20
21 use crate::channel;
22 use crate::util::{self, exe};
23 use build_helper::up_to_date;
24 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
25 use crate::cache::Interned;
26 use crate::GitRepo;
27
28 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
29 pub struct Llvm {
30     pub target: Interned<String>,
31     pub emscripten: bool,
32 }
33
34 impl Step for Llvm {
35     type Output = PathBuf; // path to llvm-config
36
37     const ONLY_HOSTS: bool = true;
38
39     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
40         run.path("src/llvm-project")
41             .path("src/llvm-project/llvm")
42             .path("src/llvm")
43             .path("src/llvm-emscripten")
44     }
45
46     fn make_run(run: RunConfig<'_>) {
47         let emscripten = run.path.ends_with("llvm-emscripten");
48         run.builder.ensure(Llvm {
49             target: run.target,
50             emscripten,
51         });
52     }
53
54     /// Compile LLVM for `target`.
55     fn run(self, builder: &Builder<'_>) -> PathBuf {
56         let target = self.target;
57         let emscripten = self.emscripten;
58
59         // If we're using a custom LLVM bail out here, but we can only use a
60         // custom LLVM for the build triple.
61         if !self.emscripten {
62             if let Some(config) = builder.config.target_config.get(&target) {
63                 if let Some(ref s) = config.llvm_config {
64                     check_llvm_version(builder, s);
65                     return s.to_path_buf()
66                 }
67             }
68         }
69
70         let (llvm_info, root, out_dir, llvm_config_ret_dir) = if emscripten {
71             let info = &builder.emscripten_llvm_info;
72             let dir = builder.emscripten_llvm_out(target);
73             let config_dir = dir.join("bin");
74             (info, "src/llvm-emscripten", dir, config_dir)
75         } else {
76             let info = &builder.in_tree_llvm_info;
77             let mut dir = builder.llvm_out(builder.config.build);
78             if !builder.config.build.contains("msvc") || builder.config.ninja {
79                 dir.push("build");
80             }
81             (info, "src/llvm-project/llvm", builder.llvm_out(target), dir.join("bin"))
82         };
83
84         if !llvm_info.is_git() {
85             println!(
86                 "git could not determine the LLVM submodule commit hash. \
87                 Assuming that an LLVM build is necessary.",
88             );
89         }
90
91         let build_llvm_config = llvm_config_ret_dir
92             .join(exe("llvm-config", &*builder.config.build));
93         let done_stamp = out_dir.join("llvm-finished-building");
94
95         if let Some(llvm_commit) = llvm_info.sha() {
96             if done_stamp.exists() {
97                 let done_contents = t!(fs::read(&done_stamp));
98
99                 // If LLVM was already built previously and the submodule's commit didn't change
100                 // from the previous build, then no action is required.
101                 if done_contents == llvm_commit.as_bytes() {
102                     return build_llvm_config
103                 }
104             }
105         }
106
107         let descriptor = if emscripten { "Emscripten " } else { "" };
108         builder.info(&format!("Building {}LLVM for {}", descriptor, target));
109         let _time = util::timeit(&builder);
110         t!(fs::create_dir_all(&out_dir));
111
112         // http://llvm.org/docs/CMake.html
113         let mut cfg = cmake::Config::new(builder.src.join(root));
114
115         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
116             (false, _) => "Debug",
117             (true, false) => "Release",
118             (true, true) => "RelWithDebInfo",
119         };
120
121         // NOTE: remember to also update `config.toml.example` when changing the
122         // defaults!
123         let llvm_targets = if self.emscripten {
124             "JSBackend"
125         } else {
126             match builder.config.llvm_targets {
127                 Some(ref s) => s,
128                 None => "AArch64;ARM;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
129                          Sparc;SystemZ;WebAssembly;X86",
130             }
131         };
132
133         let llvm_exp_targets = if self.emscripten {
134             ""
135         } else {
136             match builder.config.llvm_experimental_targets {
137                 Some(ref s) => s,
138                 None => "",
139             }
140         };
141
142         let assertions = if builder.config.llvm_assertions {"ON"} else {"OFF"};
143
144         cfg.out_dir(&out_dir)
145            .profile(profile)
146            .define("LLVM_ENABLE_ASSERTIONS", assertions)
147            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
148            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
149            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
150            .define("LLVM_INCLUDE_TESTS", "OFF")
151            .define("LLVM_INCLUDE_DOCS", "OFF")
152            .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
153            .define("LLVM_ENABLE_ZLIB", "OFF")
154            .define("WITH_POLLY", "OFF")
155            .define("LLVM_ENABLE_TERMINFO", "OFF")
156            .define("LLVM_ENABLE_LIBEDIT", "OFF")
157            .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
158            .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
159            .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
160            .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
161
162         if builder.config.llvm_thin_lto && !emscripten {
163             cfg.define("LLVM_ENABLE_LTO", "Thin");
164             if !target.contains("apple") {
165                cfg.define("LLVM_ENABLE_LLD", "ON");
166             }
167         }
168
169         // By default, LLVM will automatically find OCaml and, if it finds it,
170         // install the LLVM bindings in LLVM_OCAML_INSTALL_PATH, which defaults
171         // to /usr/bin/ocaml.
172         // This causes problem for non-root builds of Rust. Side-step the issue
173         // by setting LLVM_OCAML_INSTALL_PATH to a relative path, so it installs
174         // in the prefix.
175         cfg.define("LLVM_OCAML_INSTALL_PATH",
176             env::var_os("LLVM_OCAML_INSTALL_PATH").unwrap_or_else(|| "usr/lib/ocaml".into()));
177
178         let want_lldb = builder.config.lldb_enabled && !self.emscripten;
179
180         // This setting makes the LLVM tools link to the dynamic LLVM library,
181         // which saves both memory during parallel links and overall disk space
182         // for the tools. We don't do this on every platform as it doesn't work
183         // equally well everywhere.
184         if builder.llvm_link_tools_dynamically(target) && !emscripten {
185             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
186         }
187
188         // For distribution we want the LLVM tools to be *statically* linked to libstdc++
189         if builder.config.llvm_tools_enabled || want_lldb {
190             if !target.contains("windows") {
191                 if target.contains("apple") {
192                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
193                 } else {
194                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
195                 }
196             }
197         }
198
199         if target.contains("msvc") {
200             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
201             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
202             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
203             cfg.static_crt(true);
204         }
205
206         if target.starts_with("i686") {
207             cfg.define("LLVM_BUILD_32_BITS", "ON");
208         }
209
210         let mut enabled_llvm_projects = Vec::new();
211
212         if util::forcing_clang_based_tests() {
213             enabled_llvm_projects.push("clang");
214             enabled_llvm_projects.push("compiler-rt");
215         }
216
217         if want_lldb {
218             enabled_llvm_projects.push("clang");
219             enabled_llvm_projects.push("lldb");
220             // For the time being, disable code signing.
221             cfg.define("LLDB_CODESIGN_IDENTITY", "");
222             cfg.define("LLDB_NO_DEBUGSERVER", "ON");
223         } else {
224             // LLDB requires libxml2; but otherwise we want it to be disabled.
225             // See https://github.com/rust-lang/rust/pull/50104
226             cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
227         }
228
229         if enabled_llvm_projects.len() > 0 {
230             enabled_llvm_projects.sort();
231             enabled_llvm_projects.dedup();
232             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
233         }
234
235         if let Some(num_linkers) = builder.config.llvm_link_jobs {
236             if num_linkers > 0 {
237                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
238             }
239         }
240
241         // http://llvm.org/docs/HowToCrossCompileLLVM.html
242         if target != builder.config.build && !emscripten {
243             builder.ensure(Llvm {
244                 target: builder.config.build,
245                 emscripten: false,
246             });
247             // FIXME: if the llvm root for the build triple is overridden then we
248             //        should use llvm-tblgen from there, also should verify that it
249             //        actually exists most of the time in normal installs of LLVM.
250             let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
251             cfg.define("CMAKE_CROSSCOMPILING", "True")
252                .define("LLVM_TABLEGEN", &host);
253
254             if target.contains("netbsd") {
255                cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
256             } else if target.contains("freebsd") {
257                cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
258             }
259
260             cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
261         }
262
263         if let Some(ref suffix) = builder.config.llvm_version_suffix {
264             // Allow version-suffix="" to not define a version suffix at all.
265             if !suffix.is_empty() {
266                 cfg.define("LLVM_VERSION_SUFFIX", suffix);
267             }
268         } else {
269             let mut default_suffix = format!(
270                 "-rust-{}-{}",
271                 channel::CFG_RELEASE_NUM,
272                 builder.config.channel,
273             );
274             if let Some(sha) = llvm_info.sha_short() {
275                 default_suffix.push_str("-");
276                 default_suffix.push_str(sha);
277             }
278             cfg.define("LLVM_VERSION_SUFFIX", default_suffix);
279         }
280
281         if let Some(ref linker) = builder.config.llvm_use_linker {
282             cfg.define("LLVM_USE_LINKER", linker);
283         }
284
285         if let Some(true) = builder.config.llvm_allow_old_toolchain {
286             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
287         }
288
289         if let Some(ref python) = builder.config.python {
290             cfg.define("PYTHON_EXECUTABLE", python);
291         }
292
293         configure_cmake(builder, target, &mut cfg);
294
295         // FIXME: we don't actually need to build all LLVM tools and all LLVM
296         //        libraries here, e.g., we just want a few components and a few
297         //        tools. Figure out how to filter them down and only build the right
298         //        tools and libs on all platforms.
299
300         if builder.config.dry_run {
301             return build_llvm_config;
302         }
303
304         cfg.build();
305
306         if let Some(llvm_commit) = llvm_info.sha() {
307             t!(fs::write(&done_stamp, llvm_commit));
308         }
309
310         build_llvm_config
311     }
312 }
313
314 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
315     if !builder.config.llvm_version_check {
316         return
317     }
318
319     if builder.config.dry_run {
320         return;
321     }
322
323     let mut cmd = Command::new(llvm_config);
324     let version = output(cmd.arg("--version"));
325     let mut parts = version.split('.').take(2)
326         .filter_map(|s| s.parse::<u32>().ok());
327     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
328         if major >= 6 {
329             return
330         }
331     }
332     panic!("\n\nbad LLVM version: {}, need >=6.0\n\n", version)
333 }
334
335 fn configure_cmake(builder: &Builder<'_>,
336                    target: Interned<String>,
337                    cfg: &mut cmake::Config) {
338     // Do not print installation messages for up-to-date files.
339     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
340     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
341
342     if builder.config.ninja {
343         cfg.generator("Ninja");
344     }
345     cfg.target(&target)
346        .host(&builder.config.build);
347
348     let sanitize_cc = |cc: &Path| {
349         if target.contains("msvc") {
350             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
351         } else {
352             cc.as_os_str().to_owned()
353         }
354     };
355
356     // MSVC with CMake uses msbuild by default which doesn't respect these
357     // vars that we'd otherwise configure. In that case we just skip this
358     // entirely.
359     if target.contains("msvc") && !builder.config.ninja {
360         return
361     }
362
363     let (cc, cxx) = match builder.config.llvm_clang_cl {
364         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
365         None => (builder.cc(target), builder.cxx(target).unwrap()),
366     };
367
368     // Handle msvc + ninja + ccache specially (this is what the bots use)
369     if target.contains("msvc") &&
370        builder.config.ninja &&
371        builder.config.ccache.is_some()
372     {
373        let mut wrap_cc = env::current_exe().expect("failed to get cwd");
374        wrap_cc.set_file_name("sccache-plus-cl.exe");
375
376        cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
377           .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
378        cfg.env("SCCACHE_PATH",
379                builder.config.ccache.as_ref().unwrap())
380           .env("SCCACHE_TARGET", target)
381           .env("SCCACHE_CC", &cc)
382           .env("SCCACHE_CXX", &cxx);
383
384        // Building LLVM on MSVC can be a little ludicrous at times. We're so far
385        // off the beaten path here that I'm not really sure this is even half
386        // supported any more. Here we're trying to:
387        //
388        // * Build LLVM on MSVC
389        // * Build LLVM with `clang-cl` instead of `cl.exe`
390        // * Build a project with `sccache`
391        // * Build for 32-bit as well
392        // * Build with Ninja
393        //
394        // For `cl.exe` there are different binaries to compile 32/64 bit which
395        // we use but for `clang-cl` there's only one which internally
396        // multiplexes via flags. As a result it appears that CMake's detection
397        // of a compiler's architecture and such on MSVC **doesn't** pass any
398        // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
399        // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
400        // definitely causes problems since all the env vars are pointing to
401        // 32-bit libraries.
402        //
403        // To hack around this... again... we pass an argument that's
404        // unconditionally passed in the sccache shim. This'll get CMake to
405        // correctly diagnose it's doing a 32-bit compilation and LLVM will
406        // internally configure itself appropriately.
407        if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
408            cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
409        }
410     } else {
411        // If ccache is configured we inform the build a little differently how
412        // to invoke ccache while also invoking our compilers.
413        if let Some(ref ccache) = builder.config.ccache {
414          cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
415             .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
416        }
417        cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
418           .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
419     }
420
421     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
422     let mut cflags = builder.cflags(target, GitRepo::Llvm).join(" ");
423     if let Some(ref s) = builder.config.llvm_cflags {
424         cflags.push_str(&format!(" {}", s));
425     }
426     cfg.define("CMAKE_C_FLAGS", cflags);
427     let mut cxxflags = builder.cflags(target, GitRepo::Llvm).join(" ");
428     if builder.config.llvm_static_stdcpp &&
429         !target.contains("windows") &&
430         !target.contains("netbsd")
431     {
432         cxxflags.push_str(" -static-libstdc++");
433     }
434     if let Some(ref s) = builder.config.llvm_cxxflags {
435         cxxflags.push_str(&format!(" {}", s));
436     }
437     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
438     if let Some(ar) = builder.ar(target) {
439         if ar.is_absolute() {
440             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
441             // tries to resolve this path in the LLVM build directory.
442             cfg.define("CMAKE_AR", sanitize_cc(ar));
443         }
444     }
445
446     if let Some(ranlib) = builder.ranlib(target) {
447         if ranlib.is_absolute() {
448             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
449             // tries to resolve this path in the LLVM build directory.
450             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
451         }
452     }
453
454     if let Some(ref s) = builder.config.llvm_ldflags {
455         cfg.define("CMAKE_SHARED_LINKER_FLAGS", s);
456         cfg.define("CMAKE_MODULE_LINKER_FLAGS", s);
457         cfg.define("CMAKE_EXE_LINKER_FLAGS", s);
458     }
459
460     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
461         cfg.env("RUSTC_LOG", "sccache=warn");
462     }
463 }
464
465 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
466 pub struct Lld {
467     pub target: Interned<String>,
468 }
469
470 impl Step for Lld {
471     type Output = PathBuf;
472     const ONLY_HOSTS: bool = true;
473
474     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
475         run.path("src/llvm-project/lld").path("src/tools/lld")
476     }
477
478     fn make_run(run: RunConfig<'_>) {
479         run.builder.ensure(Lld { target: run.target });
480     }
481
482     /// Compile LLVM for `target`.
483     fn run(self, builder: &Builder<'_>) -> PathBuf {
484         if builder.config.dry_run {
485             return PathBuf::from("lld-out-dir-test-gen");
486         }
487         let target = self.target;
488
489         let llvm_config = builder.ensure(Llvm {
490             target: self.target,
491             emscripten: false,
492         });
493
494         let out_dir = builder.lld_out(target);
495         let done_stamp = out_dir.join("lld-finished-building");
496         if done_stamp.exists() {
497             return out_dir
498         }
499
500         builder.info(&format!("Building LLD for {}", target));
501         let _time = util::timeit(&builder);
502         t!(fs::create_dir_all(&out_dir));
503
504         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
505         configure_cmake(builder, target, &mut cfg);
506
507         // This is an awful, awful hack. Discovered when we migrated to using
508         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
509         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
510         // that directory for later processing. Unfortunately if this path has
511         // forward slashes in it (which it basically always does on Windows)
512         // then CMake will hit a syntax error later on as... something isn't
513         // escaped it seems?
514         //
515         // Instead of attempting to fix this problem in upstream CMake and/or
516         // LLVM/LLD we just hack around it here. This thin wrapper will take the
517         // output from llvm-config and replace all instances of `\` with `/` to
518         // ensure we don't hit the same bugs with escaping. It means that you
519         // can't build on a system where your paths require `\` on Windows, but
520         // there's probably a lot of reasons you can't do that other than this.
521         let llvm_config_shim = env::current_exe()
522             .unwrap()
523             .with_file_name("llvm-config-wrapper");
524         cfg.out_dir(&out_dir)
525            .profile("Release")
526            .env("LLVM_CONFIG_REAL", llvm_config)
527            .define("LLVM_CONFIG_PATH", llvm_config_shim)
528            .define("LLVM_INCLUDE_TESTS", "OFF");
529
530         cfg.build();
531
532         t!(File::create(&done_stamp));
533         out_dir
534     }
535 }
536
537 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
538 pub struct TestHelpers {
539     pub target: Interned<String>,
540 }
541
542 impl Step for TestHelpers {
543     type Output = ();
544
545     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
546         run.path("src/test/auxiliary/rust_test_helpers.c")
547     }
548
549     fn make_run(run: RunConfig<'_>) {
550         run.builder.ensure(TestHelpers { target: run.target })
551     }
552
553     /// Compiles the `rust_test_helpers.c` library which we used in various
554     /// `run-pass` tests for ABI testing.
555     fn run(self, builder: &Builder<'_>) {
556         if builder.config.dry_run {
557             return;
558         }
559         let target = self.target;
560         let dst = builder.test_helpers_out(target);
561         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
562         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
563             return
564         }
565
566         builder.info("Building test helpers");
567         t!(fs::create_dir_all(&dst));
568         let mut cfg = cc::Build::new();
569
570         // We may have found various cross-compilers a little differently due to our
571         // extra configuration, so inform gcc of these compilers. Note, though, that
572         // on MSVC we still need gcc's detection of env vars (ugh).
573         if !target.contains("msvc") {
574             if let Some(ar) = builder.ar(target) {
575                 cfg.archiver(ar);
576             }
577             cfg.compiler(builder.cc(target));
578         }
579
580         cfg.cargo_metadata(false)
581            .out_dir(&dst)
582            .target(&target)
583            .host(&builder.config.build)
584            .opt_level(0)
585            .warnings(false)
586            .debug(false)
587            .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
588            .compile("rust_test_helpers");
589     }
590 }