]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
d009d9645c35aa388ebf7f639f533984491b7de5
[rust.git] / src / bootstrap / compile.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Implementation of compiling various phases of the compiler and standard
12 //! library.
13 //!
14 //! This module contains some of the real meat in the rustbuild build system
15 //! which is where Cargo is used to compiler the standard library, libtest, and
16 //! compiler. This module is also responsible for assembling the sysroot as it
17 //! goes along from the output of the previous stage.
18
19 use std::borrow::Cow;
20 use std::env;
21 use std::fs::{self, File};
22 use std::io::BufReader;
23 use std::io::prelude::*;
24 use std::path::{Path, PathBuf};
25 use std::process::{Command, Stdio};
26 use std::str;
27
28 use build_helper::{output, mtime, up_to_date};
29 use filetime::FileTime;
30 use serde_json;
31
32 use util::{exe, libdir, is_dylib};
33 use {Compiler, Mode, GitRepo};
34 use native;
35
36 use cache::{INTERNER, Interned};
37 use builder::{Step, RunConfig, ShouldRun, Builder};
38
39 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
40 pub struct Std {
41     pub target: Interned<String>,
42     pub compiler: Compiler,
43 }
44
45 impl Step for Std {
46     type Output = ();
47     const DEFAULT: bool = true;
48
49     fn should_run(run: ShouldRun) -> ShouldRun {
50         run.all_krates("std")
51     }
52
53     fn make_run(run: RunConfig) {
54         run.builder.ensure(Std {
55             compiler: run.builder.compiler(run.builder.top_stage, run.host),
56             target: run.target,
57         });
58     }
59
60     /// Build the standard library.
61     ///
62     /// This will build the standard library for a particular stage of the build
63     /// using the `compiler` targeting the `target` architecture. The artifacts
64     /// created will also be linked into the sysroot directory.
65     fn run(self, builder: &Builder) {
66         let target = self.target;
67         let compiler = self.compiler;
68
69         if builder.config.keep_stage.contains(&compiler.stage) {
70             builder.info("Warning: Using a potentially old libstd. This may not behave well.");
71             builder.ensure(StdLink {
72                 compiler,
73                 target_compiler: compiler,
74                 target,
75             });
76             return;
77         }
78
79         builder.ensure(StartupObjects { compiler, target });
80
81         if builder.force_use_stage1(compiler, target) {
82             let from = builder.compiler(1, builder.config.build);
83             builder.ensure(Std {
84                 compiler: from,
85                 target,
86             });
87             builder.info(&format!("Uplifting stage1 std ({} -> {})", from.host, target));
88
89             // Even if we're not building std this stage, the new sysroot must
90             // still contain the musl startup objects.
91             if target.contains("musl") {
92                 let libdir = builder.sysroot_libdir(compiler, target);
93                 copy_musl_third_party_objects(builder, target, &libdir);
94             }
95
96             builder.ensure(StdLink {
97                 compiler: from,
98                 target_compiler: compiler,
99                 target,
100             });
101             return;
102         }
103
104         if target.contains("musl") {
105             let libdir = builder.sysroot_libdir(compiler, target);
106             copy_musl_third_party_objects(builder, target, &libdir);
107         }
108
109         let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
110         std_cargo(builder, &compiler, target, &mut cargo);
111
112         let _folder = builder.fold_output(|| format!("stage{}-std", compiler.stage));
113         builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
114                 &compiler.host, target));
115         run_cargo(builder,
116                   &mut cargo,
117                   vec![],
118                   &libstd_stamp(builder, compiler, target),
119                   false);
120
121         builder.ensure(StdLink {
122             compiler: builder.compiler(compiler.stage, builder.config.build),
123             target_compiler: compiler,
124             target,
125         });
126     }
127 }
128
129 /// Copies the crt(1,i,n).o startup objects
130 ///
131 /// Since musl supports fully static linking, we can cross link for it even
132 /// with a glibc-targeting toolchain, given we have the appropriate startup
133 /// files. As those shipped with glibc won't work, copy the ones provided by
134 /// musl so we have them on linux-gnu hosts.
135 fn copy_musl_third_party_objects(builder: &Builder,
136                                  target: Interned<String>,
137                                  into: &Path) {
138     for &obj in &["crt1.o", "crti.o", "crtn.o"] {
139         builder.copy(&builder.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
140     }
141 }
142
143 /// Configure cargo to compile the standard library, adding appropriate env vars
144 /// and such.
145 pub fn std_cargo(builder: &Builder,
146                  compiler: &Compiler,
147                  target: Interned<String>,
148                  cargo: &mut Command) {
149     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
150         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
151     }
152
153     if builder.no_std(target) == Some(true) {
154         // for no-std targets we only compile a few no_std crates
155         cargo.arg("--features").arg("c mem")
156             .args(&["-p", "alloc"])
157             .args(&["-p", "compiler_builtins"])
158             .arg("--manifest-path")
159             .arg(builder.src.join("src/rustc/compiler_builtins_shim/Cargo.toml"));
160     } else {
161         let mut features = builder.std_features();
162
163         // When doing a local rebuild we tell cargo that we're stage1 rather than
164         // stage0. This works fine if the local rust and being-built rust have the
165         // same view of what the default allocator is, but fails otherwise. Since
166         // we don't have a way to express an allocator preference yet, work
167         // around the issue in the case of a local rebuild with jemalloc disabled.
168         if compiler.stage == 0 && builder.local_rebuild && !builder.config.use_jemalloc {
169             features.push_str(" force_alloc_system");
170         }
171
172         if compiler.stage != 0 && builder.config.sanitizers {
173             // This variable is used by the sanitizer runtime crates, e.g.
174             // rustc_lsan, to build the sanitizer runtime from C code
175             // When this variable is missing, those crates won't compile the C code,
176             // so we don't set this variable during stage0 where llvm-config is
177             // missing
178             // We also only build the runtimes when --enable-sanitizers (or its
179             // config.toml equivalent) is used
180             let llvm_config = builder.ensure(native::Llvm {
181                 target: builder.config.build,
182                 emscripten: false,
183             });
184             cargo.env("LLVM_CONFIG", llvm_config);
185         }
186
187         cargo.arg("--features").arg(features)
188             .arg("--manifest-path")
189             .arg(builder.src.join("src/libstd/Cargo.toml"));
190
191         if let Some(target) = builder.config.target_config.get(&target) {
192             if let Some(ref jemalloc) = target.jemalloc {
193                 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
194             }
195         }
196         if target.contains("musl") {
197             if let Some(p) = builder.musl_root(target) {
198                 cargo.env("MUSL_ROOT", p);
199             }
200         }
201     }
202 }
203
204 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
205 struct StdLink {
206     pub compiler: Compiler,
207     pub target_compiler: Compiler,
208     pub target: Interned<String>,
209 }
210
211 impl Step for StdLink {
212     type Output = ();
213
214     fn should_run(run: ShouldRun) -> ShouldRun {
215         run.never()
216     }
217
218     /// Link all libstd rlibs/dylibs into the sysroot location.
219     ///
220     /// Links those artifacts generated by `compiler` to a the `stage` compiler's
221     /// sysroot for the specified `host` and `target`.
222     ///
223     /// Note that this assumes that `compiler` has already generated the libstd
224     /// libraries for `target`, and this method will find them in the relevant
225     /// output directory.
226     fn run(self, builder: &Builder) {
227         let compiler = self.compiler;
228         let target_compiler = self.target_compiler;
229         let target = self.target;
230         builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
231                 target_compiler.stage,
232                 compiler.stage,
233                 &compiler.host,
234                 target_compiler.host,
235                 target));
236         let libdir = builder.sysroot_libdir(target_compiler, target);
237         add_to_sysroot(builder, &libdir, &libstd_stamp(builder, compiler, target));
238
239         if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
240             // The sanitizers are only built in stage1 or above, so the dylibs will
241             // be missing in stage0 and causes panic. See the `std()` function above
242             // for reason why the sanitizers are not built in stage0.
243             copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
244         }
245
246         builder.cargo(target_compiler, Mode::ToolStd, target, "clean");
247     }
248 }
249
250 fn copy_apple_sanitizer_dylibs(builder: &Builder, native_dir: &Path, platform: &str, into: &Path) {
251     for &sanitizer in &["asan", "tsan"] {
252         let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
253         let mut src_path = native_dir.join(sanitizer);
254         src_path.push("build");
255         src_path.push("lib");
256         src_path.push("darwin");
257         src_path.push(&filename);
258         builder.copy(&src_path, &into.join(filename));
259     }
260 }
261
262 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
263 pub struct StartupObjects {
264     pub compiler: Compiler,
265     pub target: Interned<String>,
266 }
267
268 impl Step for StartupObjects {
269     type Output = ();
270
271     fn should_run(run: ShouldRun) -> ShouldRun {
272         run.path("src/rtstartup")
273     }
274
275     fn make_run(run: RunConfig) {
276         run.builder.ensure(StartupObjects {
277             compiler: run.builder.compiler(run.builder.top_stage, run.host),
278             target: run.target,
279         });
280     }
281
282     /// Build and prepare startup objects like rsbegin.o and rsend.o
283     ///
284     /// These are primarily used on Windows right now for linking executables/dlls.
285     /// They don't require any library support as they're just plain old object
286     /// files, so we just use the nightly snapshot compiler to always build them (as
287     /// no other compilers are guaranteed to be available).
288     fn run(self, builder: &Builder) {
289         let for_compiler = self.compiler;
290         let target = self.target;
291         if !target.contains("pc-windows-gnu") {
292             return
293         }
294
295         let src_dir = &builder.src.join("src/rtstartup");
296         let dst_dir = &builder.native_dir(target).join("rtstartup");
297         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
298         t!(fs::create_dir_all(dst_dir));
299
300         for file in &["rsbegin", "rsend"] {
301             let src_file = &src_dir.join(file.to_string() + ".rs");
302             let dst_file = &dst_dir.join(file.to_string() + ".o");
303             if !up_to_date(src_file, dst_file) {
304                 let mut cmd = Command::new(&builder.initial_rustc);
305                 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
306                             .arg("--cfg").arg("stage0")
307                             .arg("--target").arg(target)
308                             .arg("--emit=obj")
309                             .arg("-o").arg(dst_file)
310                             .arg(src_file));
311             }
312
313             builder.copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
314         }
315
316         for obj in ["crt2.o", "dllcrt2.o"].iter() {
317             let src = compiler_file(builder,
318                                     builder.cc(target),
319                                     target,
320                                     obj);
321             builder.copy(&src, &sysroot_dir.join(obj));
322         }
323     }
324 }
325
326 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
327 pub struct Test {
328     pub target: Interned<String>,
329     pub compiler: Compiler,
330 }
331
332 impl Step for Test {
333     type Output = ();
334     const DEFAULT: bool = true;
335
336     fn should_run(run: ShouldRun) -> ShouldRun {
337         run.all_krates("test")
338     }
339
340     fn make_run(run: RunConfig) {
341         run.builder.ensure(Test {
342             compiler: run.builder.compiler(run.builder.top_stage, run.host),
343             target: run.target,
344         });
345     }
346
347     /// Build libtest.
348     ///
349     /// This will build libtest and supporting libraries for a particular stage of
350     /// the build using the `compiler` targeting the `target` architecture. The
351     /// artifacts created will also be linked into the sysroot directory.
352     fn run(self, builder: &Builder) {
353         let target = self.target;
354         let compiler = self.compiler;
355
356         builder.ensure(Std { compiler, target });
357
358         if builder.config.keep_stage.contains(&compiler.stage) {
359             builder.info("Warning: Using a potentially old libtest. This may not behave well.");
360             builder.ensure(TestLink {
361                 compiler,
362                 target_compiler: compiler,
363                 target,
364             });
365             return;
366         }
367
368         if builder.force_use_stage1(compiler, target) {
369             builder.ensure(Test {
370                 compiler: builder.compiler(1, builder.config.build),
371                 target,
372             });
373             builder.info(
374                 &format!("Uplifting stage1 test ({} -> {})", builder.config.build, target));
375             builder.ensure(TestLink {
376                 compiler: builder.compiler(1, builder.config.build),
377                 target_compiler: compiler,
378                 target,
379             });
380             return;
381         }
382
383         let mut cargo = builder.cargo(compiler, Mode::Test, target, "build");
384         test_cargo(builder, &compiler, target, &mut cargo);
385
386         let _folder = builder.fold_output(|| format!("stage{}-test", compiler.stage));
387         builder.info(&format!("Building stage{} test artifacts ({} -> {})", compiler.stage,
388                 &compiler.host, target));
389         run_cargo(builder,
390                   &mut cargo,
391                   vec![],
392                   &libtest_stamp(builder, compiler, target),
393                   false);
394
395         builder.ensure(TestLink {
396             compiler: builder.compiler(compiler.stage, builder.config.build),
397             target_compiler: compiler,
398             target,
399         });
400     }
401 }
402
403 /// Same as `std_cargo`, but for libtest
404 pub fn test_cargo(builder: &Builder,
405                   _compiler: &Compiler,
406                   _target: Interned<String>,
407                   cargo: &mut Command) {
408     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
409         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
410     }
411     cargo.arg("--manifest-path")
412         .arg(builder.src.join("src/libtest/Cargo.toml"));
413 }
414
415 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
416 pub struct TestLink {
417     pub compiler: Compiler,
418     pub target_compiler: Compiler,
419     pub target: Interned<String>,
420 }
421
422 impl Step for TestLink {
423     type Output = ();
424
425     fn should_run(run: ShouldRun) -> ShouldRun {
426         run.never()
427     }
428
429     /// Same as `std_link`, only for libtest
430     fn run(self, builder: &Builder) {
431         let compiler = self.compiler;
432         let target_compiler = self.target_compiler;
433         let target = self.target;
434         builder.info(&format!("Copying stage{} test from stage{} ({} -> {} / {})",
435                 target_compiler.stage,
436                 compiler.stage,
437                 &compiler.host,
438                 target_compiler.host,
439                 target));
440         add_to_sysroot(builder, &builder.sysroot_libdir(target_compiler, target),
441                     &libtest_stamp(builder, compiler, target));
442
443         builder.cargo(target_compiler, Mode::ToolTest, target, "clean");
444     }
445 }
446
447 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
448 pub struct Rustc {
449     pub target: Interned<String>,
450     pub compiler: Compiler,
451 }
452
453 impl Step for Rustc {
454     type Output = ();
455     const ONLY_HOSTS: bool = true;
456     const DEFAULT: bool = true;
457
458     fn should_run(run: ShouldRun) -> ShouldRun {
459         run.all_krates("rustc-main")
460     }
461
462     fn make_run(run: RunConfig) {
463         run.builder.ensure(Rustc {
464             compiler: run.builder.compiler(run.builder.top_stage, run.host),
465             target: run.target,
466         });
467     }
468
469     /// Build the compiler.
470     ///
471     /// This will build the compiler for a particular stage of the build using
472     /// the `compiler` targeting the `target` architecture. The artifacts
473     /// created will also be linked into the sysroot directory.
474     fn run(self, builder: &Builder) {
475         let compiler = self.compiler;
476         let target = self.target;
477
478         builder.ensure(Test { compiler, target });
479
480         if builder.config.keep_stage.contains(&compiler.stage) {
481             builder.info("Warning: Using a potentially old librustc. This may not behave well.");
482             builder.ensure(RustcLink {
483                 compiler,
484                 target_compiler: compiler,
485                 target,
486             });
487             return;
488         }
489
490         if builder.force_use_stage1(compiler, target) {
491             builder.ensure(Rustc {
492                 compiler: builder.compiler(1, builder.config.build),
493                 target,
494             });
495             builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
496                 builder.config.build, target));
497             builder.ensure(RustcLink {
498                 compiler: builder.compiler(1, builder.config.build),
499                 target_compiler: compiler,
500                 target,
501             });
502             return;
503         }
504
505         // Ensure that build scripts have a std to link against.
506         builder.ensure(Std {
507             compiler: builder.compiler(self.compiler.stage, builder.config.build),
508             target: builder.config.build,
509         });
510
511         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
512         rustc_cargo(builder, &mut cargo);
513
514         let _folder = builder.fold_output(|| format!("stage{}-rustc", compiler.stage));
515         builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
516                  compiler.stage, &compiler.host, target));
517         run_cargo(builder,
518                   &mut cargo,
519                   vec![],
520                   &librustc_stamp(builder, compiler, target),
521                   false);
522
523         builder.ensure(RustcLink {
524             compiler: builder.compiler(compiler.stage, builder.config.build),
525             target_compiler: compiler,
526             target,
527         });
528     }
529 }
530
531 pub fn rustc_cargo(builder: &Builder, cargo: &mut Command) {
532     cargo.arg("--features").arg(builder.rustc_features())
533          .arg("--manifest-path")
534          .arg(builder.src.join("src/rustc/Cargo.toml"));
535     rustc_cargo_env(builder, cargo);
536 }
537
538 pub fn rustc_cargo_env(builder: &Builder, cargo: &mut Command) {
539     // Set some configuration variables picked up by build scripts and
540     // the compiler alike
541     cargo.env("CFG_RELEASE", builder.rust_release())
542          .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
543          .env("CFG_VERSION", builder.rust_version())
544          .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default())
545          .env("CFG_CODEGEN_BACKENDS_DIR", &builder.config.rust_codegen_backends_dir);
546
547     let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
548     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
549
550     // If we're not building a compiler with debugging information then remove
551     // these two env vars which would be set otherwise.
552     if builder.config.rust_debuginfo_only_std {
553         cargo.env_remove("RUSTC_DEBUGINFO");
554         cargo.env_remove("RUSTC_DEBUGINFO_LINES");
555     }
556
557     if let Some(ref ver_date) = builder.rust_info.commit_date() {
558         cargo.env("CFG_VER_DATE", ver_date);
559     }
560     if let Some(ref ver_hash) = builder.rust_info.sha() {
561         cargo.env("CFG_VER_HASH", ver_hash);
562     }
563     if !builder.unstable_features() {
564         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
565     }
566     if let Some(ref s) = builder.config.rustc_default_linker {
567         cargo.env("CFG_DEFAULT_LINKER", s);
568     }
569     if builder.config.rustc_parallel_queries {
570         cargo.env("RUSTC_PARALLEL_QUERIES", "1");
571     }
572     if builder.config.rust_verify_llvm_ir {
573         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
574     }
575 }
576
577 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
578 struct RustcLink {
579     pub compiler: Compiler,
580     pub target_compiler: Compiler,
581     pub target: Interned<String>,
582 }
583
584 impl Step for RustcLink {
585     type Output = ();
586
587     fn should_run(run: ShouldRun) -> ShouldRun {
588         run.never()
589     }
590
591     /// Same as `std_link`, only for librustc
592     fn run(self, builder: &Builder) {
593         let compiler = self.compiler;
594         let target_compiler = self.target_compiler;
595         let target = self.target;
596         builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
597                  target_compiler.stage,
598                  compiler.stage,
599                  &compiler.host,
600                  target_compiler.host,
601                  target));
602         add_to_sysroot(builder, &builder.sysroot_libdir(target_compiler, target),
603                        &librustc_stamp(builder, compiler, target));
604         builder.cargo(target_compiler, Mode::ToolRustc, target, "clean");
605     }
606 }
607
608 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
609 pub struct CodegenBackend {
610     pub compiler: Compiler,
611     pub target: Interned<String>,
612     pub backend: Interned<String>,
613 }
614
615 impl Step for CodegenBackend {
616     type Output = ();
617     const ONLY_HOSTS: bool = true;
618     const DEFAULT: bool = true;
619
620     fn should_run(run: ShouldRun) -> ShouldRun {
621         run.all_krates("rustc_codegen_llvm")
622     }
623
624     fn make_run(run: RunConfig) {
625         let backend = run.builder.config.rust_codegen_backends.get(0);
626         let backend = backend.cloned().unwrap_or_else(|| {
627             INTERNER.intern_str("llvm")
628         });
629         run.builder.ensure(CodegenBackend {
630             compiler: run.builder.compiler(run.builder.top_stage, run.host),
631             target: run.target,
632             backend,
633         });
634     }
635
636     fn run(self, builder: &Builder) {
637         let compiler = self.compiler;
638         let target = self.target;
639         let backend = self.backend;
640
641         builder.ensure(Rustc { compiler, target });
642
643         if builder.config.keep_stage.contains(&compiler.stage) {
644             builder.info("Warning: Using a potentially old codegen backend. \
645                 This may not behave well.");
646             // Codegen backends are linked separately from this step today, so we don't do
647             // anything here.
648             return;
649         }
650
651         if builder.force_use_stage1(compiler, target) {
652             builder.ensure(CodegenBackend {
653                 compiler: builder.compiler(1, builder.config.build),
654                 target,
655                 backend,
656             });
657             return;
658         }
659
660         let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
661
662         let mut cargo = builder.cargo(compiler, Mode::Codegen, target, "rustc");
663         cargo.arg("--manifest-path")
664             .arg(builder.src.join("src/librustc_codegen_llvm/Cargo.toml"));
665         rustc_cargo_env(builder, &mut cargo);
666
667         let features = build_codegen_backend(&builder, &mut cargo, &compiler, target, backend);
668
669         let mut cargo_tails_args = vec![];
670
671         if builder.config.llvm_thin_lto {
672             cargo_tails_args.push("--".to_string());
673
674             let num_jobs = builder.jobs();
675
676             if !target.contains("msvc") {
677                 // Here we assume that the linker is clang. If it's not, there'll
678                 // be linker errors.
679                 cargo_tails_args.push("-Clink-arg=-fuse-ld=lld".to_string());
680                 cargo_tails_args.push("-Clink-arg=-flto=thin".to_string());
681
682                 if builder.config.llvm_optimize {
683                     cargo_tails_args.push("-Clink-arg=-O2".to_string());
684                 }
685
686                 // Let's make LLD respect the `-j` option.
687                 let num_jobs_arg = format!("-Clink-arg=-Wl,--thinlto-jobs={}", num_jobs);
688                 cargo_tails_args.push(num_jobs_arg);
689             } else {
690                 // Here we assume that the linker is lld-link.exe. lld-link.exe
691                 // does not need the extra arguments except for num_jobs
692                 let num_jobs_arg = format!("-Clink-arg=/opt:lldltojobs={}", num_jobs);
693                 cargo_tails_args.push(num_jobs_arg);
694             }
695         }
696
697         let tmp_stamp = out_dir.join(".tmp.stamp");
698
699         let _folder = builder.fold_output(|| format!("stage{}-rustc_codegen_llvm", compiler.stage));
700         let files = run_cargo(builder,
701                               cargo.arg("--features").arg(features),
702                               cargo_tails_args,
703                               &tmp_stamp,
704                               false);
705         if builder.config.dry_run {
706             return;
707         }
708         let mut files = files.into_iter()
709             .filter(|f| {
710                 let filename = f.file_name().unwrap().to_str().unwrap();
711                 is_dylib(filename) && filename.contains("rustc_codegen_llvm-")
712             });
713         let codegen_backend = match files.next() {
714             Some(f) => f,
715             None => panic!("no dylibs built for codegen backend?"),
716         };
717         if let Some(f) = files.next() {
718             panic!("codegen backend built two dylibs:\n{}\n{}",
719                    codegen_backend.display(),
720                    f.display());
721         }
722         let stamp = codegen_backend_stamp(builder, compiler, target, backend);
723         let codegen_backend = codegen_backend.to_str().unwrap();
724         t!(t!(File::create(&stamp)).write_all(codegen_backend.as_bytes()));
725     }
726 }
727
728 pub fn build_codegen_backend(builder: &Builder,
729                              cargo: &mut Command,
730                              compiler: &Compiler,
731                              target: Interned<String>,
732                              backend: Interned<String>) -> String {
733     let mut features = String::new();
734
735     match &*backend {
736         "llvm" | "emscripten" => {
737             // Build LLVM for our target. This will implicitly build the
738             // host LLVM if necessary.
739             let llvm_config = builder.ensure(native::Llvm {
740                 target,
741                 emscripten: backend == "emscripten",
742             });
743
744             if backend == "emscripten" {
745                 features.push_str(" emscripten");
746             }
747
748             builder.info(&format!("Building stage{} codegen artifacts ({} -> {}, {})",
749                      compiler.stage, &compiler.host, target, backend));
750
751             // Pass down configuration from the LLVM build into the build of
752             // librustc_llvm and librustc_codegen_llvm.
753             if builder.is_rust_llvm(target) {
754                 cargo.env("LLVM_RUSTLLVM", "1");
755             }
756             cargo.env("LLVM_CONFIG", &llvm_config);
757             if backend != "emscripten" {
758                 let target_config = builder.config.target_config.get(&target);
759                 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
760                     cargo.env("CFG_LLVM_ROOT", s);
761                 }
762             }
763             // Building with a static libstdc++ is only supported on linux right now,
764             // not for MSVC or macOS
765             if builder.config.llvm_static_stdcpp &&
766                !target.contains("freebsd") &&
767                !target.contains("windows") &&
768                !target.contains("apple") {
769                 let file = compiler_file(builder,
770                                          builder.cxx(target).unwrap(),
771                                          target,
772                                          "libstdc++.a");
773                 cargo.env("LLVM_STATIC_STDCPP", file);
774             }
775             if builder.config.llvm_link_shared {
776                 cargo.env("LLVM_LINK_SHARED", "1");
777             }
778         }
779         _ => panic!("unknown backend: {}", backend),
780     }
781
782     features
783 }
784
785 /// Creates the `codegen-backends` folder for a compiler that's about to be
786 /// assembled as a complete compiler.
787 ///
788 /// This will take the codegen artifacts produced by `compiler` and link them
789 /// into an appropriate location for `target_compiler` to be a functional
790 /// compiler.
791 fn copy_codegen_backends_to_sysroot(builder: &Builder,
792                                     compiler: Compiler,
793                                     target_compiler: Compiler) {
794     let target = target_compiler.host;
795
796     // Note that this step is different than all the other `*Link` steps in
797     // that it's not assembling a bunch of libraries but rather is primarily
798     // moving the codegen backend into place. The codegen backend of rustc is
799     // not linked into the main compiler by default but is rather dynamically
800     // selected at runtime for inclusion.
801     //
802     // Here we're looking for the output dylib of the `CodegenBackend` step and
803     // we're copying that into the `codegen-backends` folder.
804     let dst = builder.sysroot_codegen_backends(target_compiler);
805     t!(fs::create_dir_all(&dst));
806
807     if builder.config.dry_run {
808         return;
809     }
810
811     for backend in builder.config.rust_codegen_backends.iter() {
812         let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
813         let mut dylib = String::new();
814         t!(t!(File::open(&stamp)).read_to_string(&mut dylib));
815         let file = Path::new(&dylib);
816         let filename = file.file_name().unwrap().to_str().unwrap();
817         // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
818         let target_filename = {
819             let dash = filename.find('-').unwrap();
820             let dot = filename.find('.').unwrap();
821             format!("{}-{}{}",
822                     &filename[..dash],
823                     backend,
824                     &filename[dot..])
825         };
826         builder.copy(&file, &dst.join(target_filename));
827     }
828 }
829
830 fn copy_lld_to_sysroot(builder: &Builder,
831                        target_compiler: Compiler,
832                        lld_install_root: &Path) {
833     let target = target_compiler.host;
834
835     let dst = builder.sysroot_libdir(target_compiler, target)
836         .parent()
837         .unwrap()
838         .join("bin");
839     t!(fs::create_dir_all(&dst));
840
841     let src_exe = exe("lld", &target);
842     let dst_exe = exe("rust-lld", &target);
843     // we prepend this bin directory to the user PATH when linking Rust binaries. To
844     // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
845     builder.copy(&lld_install_root.join("bin").join(&src_exe), &dst.join(&dst_exe));
846 }
847
848 /// Cargo's output path for the standard library in a given stage, compiled
849 /// by a particular compiler for the specified target.
850 pub fn libstd_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
851     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
852 }
853
854 /// Cargo's output path for libtest in a given stage, compiled by a particular
855 /// compiler for the specified target.
856 pub fn libtest_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
857     builder.cargo_out(compiler, Mode::Test, target).join(".libtest.stamp")
858 }
859
860 /// Cargo's output path for librustc in a given stage, compiled by a particular
861 /// compiler for the specified target.
862 pub fn librustc_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
863     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
864 }
865
866 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
867 /// compiler for the specified target and backend.
868 fn codegen_backend_stamp(builder: &Builder,
869                          compiler: Compiler,
870                          target: Interned<String>,
871                          backend: Interned<String>) -> PathBuf {
872     builder.cargo_out(compiler, Mode::Codegen, target)
873         .join(format!(".librustc_codegen_llvm-{}.stamp", backend))
874 }
875
876 pub fn compiler_file(builder: &Builder,
877                  compiler: &Path,
878                  target: Interned<String>,
879                  file: &str) -> PathBuf {
880     let mut cmd = Command::new(compiler);
881     cmd.args(builder.cflags(target, GitRepo::Rustc));
882     cmd.arg(format!("-print-file-name={}", file));
883     let out = output(&mut cmd);
884     PathBuf::from(out.trim())
885 }
886
887 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
888 pub struct Sysroot {
889     pub compiler: Compiler,
890 }
891
892 impl Step for Sysroot {
893     type Output = Interned<PathBuf>;
894
895     fn should_run(run: ShouldRun) -> ShouldRun {
896         run.never()
897     }
898
899     /// Returns the sysroot for the `compiler` specified that *this build system
900     /// generates*.
901     ///
902     /// That is, the sysroot for the stage0 compiler is not what the compiler
903     /// thinks it is by default, but it's the same as the default for stages
904     /// 1-3.
905     fn run(self, builder: &Builder) -> Interned<PathBuf> {
906         let compiler = self.compiler;
907         let sysroot = if compiler.stage == 0 {
908             builder.out.join(&compiler.host).join("stage0-sysroot")
909         } else {
910             builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
911         };
912         let _ = fs::remove_dir_all(&sysroot);
913         t!(fs::create_dir_all(&sysroot));
914         INTERNER.intern_path(sysroot)
915     }
916 }
917
918 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
919 pub struct Assemble {
920     /// The compiler which we will produce in this step. Assemble itself will
921     /// take care of ensuring that the necessary prerequisites to do so exist,
922     /// that is, this target can be a stage2 compiler and Assemble will build
923     /// previous stages for you.
924     pub target_compiler: Compiler,
925 }
926
927 impl Step for Assemble {
928     type Output = Compiler;
929
930     fn should_run(run: ShouldRun) -> ShouldRun {
931         run.never()
932     }
933
934     /// Prepare a new compiler from the artifacts in `stage`
935     ///
936     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
937     /// must have been previously produced by the `stage - 1` builder.build
938     /// compiler.
939     fn run(self, builder: &Builder) -> Compiler {
940         let target_compiler = self.target_compiler;
941
942         if target_compiler.stage == 0 {
943             assert_eq!(builder.config.build, target_compiler.host,
944                 "Cannot obtain compiler for non-native build triple at stage 0");
945             // The stage 0 compiler for the build triple is always pre-built.
946             return target_compiler;
947         }
948
949         // Get the compiler that we'll use to bootstrap ourselves.
950         //
951         // Note that this is where the recursive nature of the bootstrap
952         // happens, as this will request the previous stage's compiler on
953         // downwards to stage 0.
954         //
955         // Also note that we're building a compiler for the host platform. We
956         // only assume that we can run `build` artifacts, which means that to
957         // produce some other architecture compiler we need to start from
958         // `build` to get there.
959         //
960         // FIXME: Perhaps we should download those libraries?
961         //        It would make builds faster...
962         //
963         // FIXME: It may be faster if we build just a stage 1 compiler and then
964         //        use that to bootstrap this compiler forward.
965         let build_compiler =
966             builder.compiler(target_compiler.stage - 1, builder.config.build);
967
968         // Build the libraries for this compiler to link to (i.e., the libraries
969         // it uses at runtime). NOTE: Crates the target compiler compiles don't
970         // link to these. (FIXME: Is that correct? It seems to be correct most
971         // of the time but I think we do link to these for stage2/bin compilers
972         // when not performing a full bootstrap).
973         builder.ensure(Rustc {
974             compiler: build_compiler,
975             target: target_compiler.host,
976         });
977         for &backend in builder.config.rust_codegen_backends.iter() {
978             builder.ensure(CodegenBackend {
979                 compiler: build_compiler,
980                 target: target_compiler.host,
981                 backend,
982             });
983         }
984
985         let lld_install = if builder.config.lld_enabled {
986             Some(builder.ensure(native::Lld {
987                 target: target_compiler.host,
988             }))
989         } else {
990             None
991         };
992
993         let stage = target_compiler.stage;
994         let host = target_compiler.host;
995         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
996
997         // Link in all dylibs to the libdir
998         let sysroot = builder.sysroot(target_compiler);
999         let sysroot_libdir = sysroot.join(libdir(&*host));
1000         t!(fs::create_dir_all(&sysroot_libdir));
1001         let src_libdir = builder.sysroot_libdir(build_compiler, host);
1002         for f in builder.read_dir(&src_libdir) {
1003             let filename = f.file_name().into_string().unwrap();
1004             if is_dylib(&filename) {
1005                 builder.copy(&f.path(), &sysroot_libdir.join(&filename));
1006             }
1007         }
1008
1009         copy_codegen_backends_to_sysroot(builder,
1010                                          build_compiler,
1011                                          target_compiler);
1012         if let Some(lld_install) = lld_install {
1013             copy_lld_to_sysroot(builder, target_compiler, &lld_install);
1014         }
1015
1016         // Link the compiler binary itself into place
1017         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
1018         let rustc = out_dir.join(exe("rustc_binary", &*host));
1019         let bindir = sysroot.join("bin");
1020         t!(fs::create_dir_all(&bindir));
1021         let compiler = builder.rustc(target_compiler);
1022         let _ = fs::remove_file(&compiler);
1023         builder.copy(&rustc, &compiler);
1024
1025         target_compiler
1026     }
1027 }
1028
1029 /// Link some files into a rustc sysroot.
1030 ///
1031 /// For a particular stage this will link the file listed in `stamp` into the
1032 /// `sysroot_dst` provided.
1033 pub fn add_to_sysroot(builder: &Builder, sysroot_dst: &Path, stamp: &Path) {
1034     t!(fs::create_dir_all(&sysroot_dst));
1035     for path in builder.read_stamp_file(stamp) {
1036         builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
1037     }
1038 }
1039
1040 pub fn run_cargo(builder: &Builder,
1041                  cargo: &mut Command,
1042                  tail_args: Vec<String>,
1043                  stamp: &Path,
1044                  is_check: bool)
1045     -> Vec<PathBuf>
1046 {
1047     if builder.config.dry_run {
1048         return Vec::new();
1049     }
1050
1051     // `target_root_dir` looks like $dir/$target/release
1052     let target_root_dir = stamp.parent().unwrap();
1053     // `target_deps_dir` looks like $dir/$target/release/deps
1054     let target_deps_dir = target_root_dir.join("deps");
1055     // `host_root_dir` looks like $dir/release
1056     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
1057                                        .parent().unwrap() // chop off `$target`
1058                                        .join(target_root_dir.file_name().unwrap());
1059
1060     // Spawn Cargo slurping up its JSON output. We'll start building up the
1061     // `deps` array of all files it generated along with a `toplevel` array of
1062     // files we need to probe for later.
1063     let mut deps = Vec::new();
1064     let mut toplevel = Vec::new();
1065     let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
1066         let filenames = match msg {
1067             CargoMessage::CompilerArtifact { filenames, .. } => filenames,
1068             _ => return,
1069         };
1070         for filename in filenames {
1071             // Skip files like executables
1072             if !filename.ends_with(".rlib") &&
1073                !filename.ends_with(".lib") &&
1074                !is_dylib(&filename) &&
1075                !(is_check && filename.ends_with(".rmeta")) {
1076                 continue;
1077             }
1078
1079             let filename = Path::new(&*filename);
1080
1081             // If this was an output file in the "host dir" we don't actually
1082             // worry about it, it's not relevant for us.
1083             if filename.starts_with(&host_root_dir) {
1084                 continue;
1085             }
1086
1087             // If this was output in the `deps` dir then this is a precise file
1088             // name (hash included) so we start tracking it.
1089             if filename.starts_with(&target_deps_dir) {
1090                 deps.push(filename.to_path_buf());
1091                 continue;
1092             }
1093
1094             // Otherwise this was a "top level artifact" which right now doesn't
1095             // have a hash in the name, but there's a version of this file in
1096             // the `deps` folder which *does* have a hash in the name. That's
1097             // the one we'll want to we'll probe for it later.
1098             //
1099             // We do not use `Path::file_stem` or `Path::extension` here,
1100             // because some generated files may have multiple extensions e.g.
1101             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1102             // split the file name by the last extension (`.lib`) while we need
1103             // to split by all extensions (`.dll.lib`).
1104             let expected_len = t!(filename.metadata()).len();
1105             let filename = filename.file_name().unwrap().to_str().unwrap();
1106             let mut parts = filename.splitn(2, '.');
1107             let file_stem = parts.next().unwrap().to_owned();
1108             let extension = parts.next().unwrap().to_owned();
1109
1110             toplevel.push((file_stem, extension, expected_len));
1111         }
1112     });
1113
1114     if !ok {
1115         panic!("cargo must succeed");
1116     }
1117
1118     // Ok now we need to actually find all the files listed in `toplevel`. We've
1119     // got a list of prefix/extensions and we basically just need to find the
1120     // most recent file in the `deps` folder corresponding to each one.
1121     let contents = t!(target_deps_dir.read_dir())
1122         .map(|e| t!(e))
1123         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1124         .collect::<Vec<_>>();
1125     for (prefix, extension, expected_len) in toplevel {
1126         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1127             filename.starts_with(&prefix[..]) &&
1128                 filename[prefix.len()..].starts_with("-") &&
1129                 filename.ends_with(&extension[..]) &&
1130                 meta.len() == expected_len
1131         });
1132         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1133             FileTime::from_last_modification_time(metadata)
1134         });
1135         let path_to_add = match max {
1136             Some(triple) => triple.0.to_str().unwrap(),
1137             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1138         };
1139         if is_dylib(path_to_add) {
1140             let candidate = format!("{}.lib", path_to_add);
1141             let candidate = PathBuf::from(candidate);
1142             if candidate.exists() {
1143                 deps.push(candidate);
1144             }
1145         }
1146         deps.push(path_to_add.into());
1147     }
1148
1149     // Now we want to update the contents of the stamp file, if necessary. First
1150     // we read off the previous contents along with its mtime. If our new
1151     // contents (the list of files to copy) is different or if any dep's mtime
1152     // is newer then we rewrite the stamp file.
1153     deps.sort();
1154     let mut stamp_contents = Vec::new();
1155     if let Ok(mut f) = File::open(stamp) {
1156         t!(f.read_to_end(&mut stamp_contents));
1157     }
1158     let stamp_mtime = mtime(&stamp);
1159     let mut new_contents = Vec::new();
1160     let mut max = None;
1161     let mut max_path = None;
1162     for dep in deps.iter() {
1163         let mtime = mtime(dep);
1164         if Some(mtime) > max {
1165             max = Some(mtime);
1166             max_path = Some(dep.clone());
1167         }
1168         new_contents.extend(dep.to_str().unwrap().as_bytes());
1169         new_contents.extend(b"\0");
1170     }
1171     let max = max.unwrap();
1172     let max_path = max_path.unwrap();
1173     if stamp_contents == new_contents && max <= stamp_mtime {
1174         builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}",
1175                 stamp, max, stamp_mtime));
1176         return deps
1177     }
1178     if max > stamp_mtime {
1179         builder.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1180     } else {
1181         builder.verbose(&format!("updating {:?} as deps changed", stamp));
1182     }
1183     t!(t!(File::create(stamp)).write_all(&new_contents));
1184     deps
1185 }
1186
1187 pub fn stream_cargo(
1188     builder: &Builder,
1189     cargo: &mut Command,
1190     tail_args: Vec<String>,
1191     cb: &mut dyn FnMut(CargoMessage),
1192 ) -> bool {
1193     if builder.config.dry_run {
1194         return true;
1195     }
1196     // Instruct Cargo to give us json messages on stdout, critically leaving
1197     // stderr as piped so we can get those pretty colors.
1198     cargo.arg("--message-format").arg("json")
1199          .stdout(Stdio::piped());
1200
1201     for arg in tail_args {
1202         cargo.arg(arg);
1203     }
1204
1205     builder.verbose(&format!("running: {:?}", cargo));
1206     let mut child = match cargo.spawn() {
1207         Ok(child) => child,
1208         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1209     };
1210
1211     // Spawn Cargo slurping up its JSON output. We'll start building up the
1212     // `deps` array of all files it generated along with a `toplevel` array of
1213     // files we need to probe for later.
1214     let stdout = BufReader::new(child.stdout.take().unwrap());
1215     for line in stdout.lines() {
1216         let line = t!(line);
1217         match serde_json::from_str::<CargoMessage>(&line) {
1218             Ok(msg) => cb(msg),
1219             // If this was informational, just print it out and continue
1220             Err(_) => println!("{}", line)
1221         }
1222     }
1223
1224     // Make sure Cargo actually succeeded after we read all of its stdout.
1225     let status = t!(child.wait());
1226     if !status.success() {
1227         eprintln!("command did not execute successfully: {:?}\n\
1228                   expected success, got: {}",
1229                  cargo,
1230                  status);
1231     }
1232     status.success()
1233 }
1234
1235 #[derive(Deserialize)]
1236 #[serde(tag = "reason", rename_all = "kebab-case")]
1237 pub enum CargoMessage<'a> {
1238     CompilerArtifact {
1239         package_id: Cow<'a, str>,
1240         features: Vec<Cow<'a, str>>,
1241         filenames: Vec<Cow<'a, str>>,
1242     },
1243     BuildScriptExecuted {
1244         package_id: Cow<'a, str>,
1245     }
1246 }