]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Don't default on std crate when manipulating browser history
[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;
18 use cmake;
19 use cc;
20
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;
25 use crate::GitRepo;
26
27 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
28 pub struct Llvm {
29     pub target: Interned<String>,
30     pub emscripten: bool,
31 }
32
33 impl Step for Llvm {
34     type Output = PathBuf; // path to llvm-config
35
36     const ONLY_HOSTS: bool = true;
37
38     fn should_run(run: ShouldRun) -> ShouldRun {
39         run.path("src/llvm-project")
40             .path("src/llvm-project/llvm")
41             .path("src/llvm")
42             .path("src/llvm-emscripten")
43     }
44
45     fn make_run(run: RunConfig) {
46         let emscripten = run.path.ends_with("llvm-emscripten");
47         run.builder.ensure(Llvm {
48             target: run.target,
49             emscripten,
50         });
51     }
52
53     /// Compile LLVM for `target`.
54     fn run(self, builder: &Builder) -> PathBuf {
55         let target = self.target;
56         let emscripten = self.emscripten;
57
58         // If we're using a custom LLVM bail out here, but we can only use a
59         // custom LLVM for the build triple.
60         if !self.emscripten {
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()
65                 }
66             }
67         }
68
69         let rebuild_trigger = builder.src.join("src/rustllvm/llvm-rebuild-trigger");
70         let rebuild_trigger_contents = t!(fs::read_to_string(&rebuild_trigger));
71
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");
75             (dir, config_dir)
76         } else {
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             (builder.llvm_out(target), dir.join("bin"))
82         };
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));
88
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
93             }
94         }
95
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));
101
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));
105
106         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
107             (false, _) => "Debug",
108             (true, false) => "Release",
109             (true, true) => "RelWithDebInfo",
110         };
111
112         // NOTE: remember to also update `config.toml.example` when changing the
113         // defaults!
114         let llvm_targets = if self.emscripten {
115             "JSBackend"
116         } else {
117             match builder.config.llvm_targets {
118                 Some(ref s) => s,
119                 None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;MSP430;Sparc;NVPTX;Hexagon",
120             }
121         };
122
123         let llvm_exp_targets = if self.emscripten {
124             ""
125         } else {
126             &builder.config.llvm_experimental_targets[..]
127         };
128
129         let assertions = if builder.config.llvm_assertions {"ON"} else {"OFF"};
130
131         cfg.out_dir(&out_dir)
132            .profile(profile)
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);
147
148         if builder.config.llvm_thin_lto && !emscripten {
149             cfg.define("LLVM_ENABLE_LTO", "Thin")
150                .define("LLVM_ENABLE_LLD", "ON");
151         }
152
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
158         // in the prefix.
159         cfg.define("LLVM_OCAML_INSTALL_PATH",
160             env::var_os("LLVM_OCAML_INSTALL_PATH").unwrap_or_else(|| "usr/lib/ocaml".into()));
161
162         let want_lldb = builder.config.lldb_enabled && !self.emscripten;
163
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");
170         }
171
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++");
177                 } else {
178                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
179                 }
180             }
181         }
182
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);
188         }
189
190         if target.starts_with("i686") {
191             cfg.define("LLVM_BUILD_32_BITS", "ON");
192         }
193
194         if want_lldb {
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");
199         } else {
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");
203         }
204
205         if let Some(num_linkers) = builder.config.llvm_link_jobs {
206             if num_linkers > 0 {
207                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
208             }
209         }
210
211         // http://llvm.org/docs/HowToCrossCompileLLVM.html
212         if target != builder.config.build && !emscripten {
213             builder.ensure(Llvm {
214                 target: builder.config.build,
215                 emscripten: false,
216             });
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);
223
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");
228             }
229
230             cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
231         }
232
233         if let Some(ref suffix) = builder.config.llvm_version_suffix {
234             cfg.define("LLVM_VERSION_SUFFIX", suffix);
235         }
236
237         if let Some(ref linker) = builder.config.llvm_use_linker {
238             cfg.define("LLVM_USE_LINKER", linker);
239         }
240
241         if let Some(ref python) = builder.config.python {
242             cfg.define("PYTHON_EXECUTABLE", python);
243         }
244
245         configure_cmake(builder, target, &mut cfg);
246
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.
251
252         if builder.config.dry_run {
253             return build_llvm_config;
254         }
255
256         cfg.build();
257
258         t!(fs::write(&done_stamp, &rebuild_trigger_contents));
259
260         build_llvm_config
261     }
262 }
263
264 fn check_llvm_version(builder: &Builder, llvm_config: &Path) {
265     if !builder.config.llvm_version_check {
266         return
267     }
268
269     if builder.config.dry_run {
270         return;
271     }
272
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()) {
278         if major >= 6 {
279             return
280         }
281     }
282     panic!("\n\nbad LLVM version: {}, need >=6.0\n\n", version)
283 }
284
285 fn configure_cmake(builder: &Builder,
286                    target: Interned<String>,
287                    cfg: &mut cmake::Config) {
288     if builder.config.ninja {
289         cfg.generator("Ninja");
290     }
291     cfg.target(&target)
292        .host(&builder.config.build);
293
294     let sanitize_cc = |cc: &Path| {
295         if target.contains("msvc") {
296             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
297         } else {
298             cc.as_os_str().to_owned()
299         }
300     };
301
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
304     // entirely.
305     if target.contains("msvc") && !builder.config.ninja {
306         return
307     }
308
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()),
312     };
313
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()
318     {
319        let mut wrap_cc = env::current_exe().expect("failed to get cwd");
320        wrap_cc.set_file_name("sccache-plus-cl.exe");
321
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);
329
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:
333        //
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
339        //
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
347        // 32-bit libraries.
348        //
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");
355        }
356     } else {
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);
362        }
363        cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
364           .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
365     }
366
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));
371     }
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")
377     {
378         cxxflags.push_str(" -static-libstdc++");
379     }
380     if let Some(ref s) = builder.config.llvm_cxxflags {
381         cxxflags.push_str(&format!(" {}", s));
382     }
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));
389         }
390     }
391
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));
397         }
398     }
399
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);
404     }
405
406     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
407         cfg.env("RUST_LOG", "sccache=warn");
408     }
409 }
410
411 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
412 pub struct Lld {
413     pub target: Interned<String>,
414 }
415
416 impl Step for Lld {
417     type Output = PathBuf;
418     const ONLY_HOSTS: bool = true;
419
420     fn should_run(run: ShouldRun) -> ShouldRun {
421         run.path("src/llvm-project/lld").path("src/tools/lld")
422     }
423
424     fn make_run(run: RunConfig) {
425         run.builder.ensure(Lld { target: run.target });
426     }
427
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");
432         }
433         let target = self.target;
434
435         let llvm_config = builder.ensure(Llvm {
436             target: self.target,
437             emscripten: false,
438         });
439
440         let out_dir = builder.lld_out(target);
441         let done_stamp = out_dir.join("lld-finished-building");
442         if done_stamp.exists() {
443             return out_dir
444         }
445
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));
450
451         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
452         configure_cmake(builder, target, &mut cfg);
453
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
460         // escaped it seems?
461         //
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()
469             .unwrap()
470             .with_file_name("llvm-config-wrapper");
471         cfg.out_dir(&out_dir)
472            .profile("Release")
473            .env("LLVM_CONFIG_REAL", llvm_config)
474            .define("LLVM_CONFIG_PATH", llvm_config_shim)
475            .define("LLVM_INCLUDE_TESTS", "OFF");
476
477         cfg.build();
478
479         t!(File::create(&done_stamp));
480         out_dir
481     }
482 }
483
484 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
485 pub struct TestHelpers {
486     pub target: Interned<String>,
487 }
488
489 impl Step for TestHelpers {
490     type Output = ();
491
492     fn should_run(run: ShouldRun) -> ShouldRun {
493         run.path("src/test/auxiliary/rust_test_helpers.c")
494     }
495
496     fn make_run(run: RunConfig) {
497         run.builder.ensure(TestHelpers { target: run.target })
498     }
499
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 {
504             return;
505         }
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")) {
510             return
511         }
512
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();
517
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) {
523                 cfg.archiver(ar);
524             }
525             cfg.compiler(builder.cc(target));
526         }
527
528         cfg.cargo_metadata(false)
529            .out_dir(&dst)
530            .target(&target)
531            .host(&builder.config.build)
532            .opt_level(0)
533            .warnings(false)
534            .debug(false)
535            .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
536            .compile("rust_test_helpers");
537     }
538 }