]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/config.rs
use iter:: before free functions
[rust.git] / src / bootstrap / config.rs
1 //! Serialized configuration of a build.
2 //!
3 //! This module implements parsing `config.toml` configuration files to tweak
4 //! how the build runs.
5
6 use std::cmp;
7 use std::collections::{HashMap, HashSet};
8 use std::env;
9 use std::ffi::OsString;
10 use std::fmt;
11 use std::fs;
12 use std::path::{Path, PathBuf};
13
14 use crate::cache::{Interned, INTERNER};
15 use crate::flags::Flags;
16 pub use crate::flags::Subcommand;
17 use crate::util::exe;
18 use build_helper::t;
19 use serde::Deserialize;
20
21 macro_rules! check_ci_llvm {
22     ($name:expr) => {
23         assert!(
24             $name.is_none(),
25             "setting {} is incompatible with download-ci-llvm.",
26             stringify!($name)
27         );
28     };
29 }
30
31 /// Global configuration for the entire build and/or bootstrap.
32 ///
33 /// This structure is derived from a combination of both `config.toml` and
34 /// `config.mk`. As of the time of this writing it's unlikely that `config.toml`
35 /// is used all that much, so this is primarily filled out by `config.mk` which
36 /// is generated from `./configure`.
37 ///
38 /// Note that this structure is not decoded directly into, but rather it is
39 /// filled out from the decoded forms of the structs below. For documentation
40 /// each field, see the corresponding fields in
41 /// `config.toml.example`.
42 #[derive(Default)]
43 pub struct Config {
44     pub ccache: Option<String>,
45     /// Call Build::ninja() instead of this.
46     pub ninja_in_file: bool,
47     pub verbose: usize,
48     pub submodules: bool,
49     pub fast_submodules: bool,
50     pub compiler_docs: bool,
51     pub docs: bool,
52     pub locked_deps: bool,
53     pub vendor: bool,
54     pub target_config: HashMap<TargetSelection, Target>,
55     pub full_bootstrap: bool,
56     pub extended: bool,
57     pub tools: Option<HashSet<String>>,
58     pub sanitizers: bool,
59     pub profiler: bool,
60     pub ignore_git: bool,
61     pub exclude: Vec<PathBuf>,
62     pub rustc_error_format: Option<String>,
63     pub json_output: bool,
64     pub test_compare_mode: bool,
65     pub llvm_libunwind: bool,
66
67     pub skip_only_host_steps: bool,
68
69     pub on_fail: Option<String>,
70     pub stage: u32,
71     pub keep_stage: Vec<u32>,
72     pub src: PathBuf,
73     pub jobs: Option<u32>,
74     pub cmd: Subcommand,
75     pub incremental: bool,
76     pub dry_run: bool,
77
78     pub deny_warnings: bool,
79     pub backtrace_on_ice: bool,
80
81     // llvm codegen options
82     pub llvm_skip_rebuild: bool,
83     pub llvm_assertions: bool,
84     pub llvm_optimize: bool,
85     pub llvm_thin_lto: bool,
86     pub llvm_release_debuginfo: bool,
87     pub llvm_version_check: bool,
88     pub llvm_static_stdcpp: bool,
89     pub llvm_link_shared: bool,
90     pub llvm_clang_cl: Option<String>,
91     pub llvm_targets: Option<String>,
92     pub llvm_experimental_targets: Option<String>,
93     pub llvm_link_jobs: Option<u32>,
94     pub llvm_version_suffix: Option<String>,
95     pub llvm_use_linker: Option<String>,
96     pub llvm_allow_old_toolchain: Option<bool>,
97     pub llvm_from_ci: bool,
98
99     pub use_lld: bool,
100     pub lld_enabled: bool,
101     pub llvm_tools_enabled: bool,
102
103     pub llvm_cflags: Option<String>,
104     pub llvm_cxxflags: Option<String>,
105     pub llvm_ldflags: Option<String>,
106     pub llvm_use_libcxx: bool,
107
108     // rust codegen options
109     pub rust_optimize: bool,
110     pub rust_codegen_units: Option<u32>,
111     pub rust_codegen_units_std: Option<u32>,
112     pub rust_debug_assertions: bool,
113     pub rust_debug_assertions_std: bool,
114     pub rust_debug_logging: bool,
115     pub rust_debuginfo_level_rustc: u32,
116     pub rust_debuginfo_level_std: u32,
117     pub rust_debuginfo_level_tools: u32,
118     pub rust_debuginfo_level_tests: u32,
119     pub rust_rpath: bool,
120     pub rustc_parallel: bool,
121     pub rustc_default_linker: Option<String>,
122     pub rust_optimize_tests: bool,
123     pub rust_dist_src: bool,
124     pub rust_codegen_backends: Vec<Interned<String>>,
125     pub rust_verify_llvm_ir: bool,
126     pub rust_thin_lto_import_instr_limit: Option<u32>,
127     pub rust_remap_debuginfo: bool,
128     pub rust_new_symbol_mangling: bool,
129
130     pub build: TargetSelection,
131     pub hosts: Vec<TargetSelection>,
132     pub targets: Vec<TargetSelection>,
133     pub local_rebuild: bool,
134     pub jemalloc: bool,
135     pub control_flow_guard: bool,
136
137     // dist misc
138     pub dist_sign_folder: Option<PathBuf>,
139     pub dist_upload_addr: Option<String>,
140     pub dist_gpg_password_file: Option<PathBuf>,
141
142     // libstd features
143     pub backtrace: bool, // support for RUST_BACKTRACE
144
145     // misc
146     pub low_priority: bool,
147     pub channel: String,
148     pub verbose_tests: bool,
149     pub save_toolstates: Option<PathBuf>,
150     pub print_step_timings: bool,
151     pub missing_tools: bool,
152
153     // Fallback musl-root for all targets
154     pub musl_root: Option<PathBuf>,
155     pub prefix: Option<PathBuf>,
156     pub sysconfdir: Option<PathBuf>,
157     pub datadir: Option<PathBuf>,
158     pub docdir: Option<PathBuf>,
159     pub bindir: PathBuf,
160     pub libdir: Option<PathBuf>,
161     pub mandir: Option<PathBuf>,
162     pub codegen_tests: bool,
163     pub nodejs: Option<PathBuf>,
164     pub gdb: Option<PathBuf>,
165     pub python: Option<PathBuf>,
166     pub cargo_native_static: bool,
167     pub configure_args: Vec<String>,
168
169     // These are either the stage0 downloaded binaries or the locally installed ones.
170     pub initial_cargo: PathBuf,
171     pub initial_rustc: PathBuf,
172     pub initial_rustfmt: Option<PathBuf>,
173     pub out: PathBuf,
174 }
175
176 #[derive(Debug, Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
177 pub struct TargetSelection {
178     pub triple: Interned<String>,
179     file: Option<Interned<String>>,
180 }
181
182 impl TargetSelection {
183     pub fn from_user(selection: &str) -> Self {
184         let path = Path::new(selection);
185
186         let (triple, file) = if path.exists() {
187             let triple = path
188                 .file_stem()
189                 .expect("Target specification file has no file stem")
190                 .to_str()
191                 .expect("Target specification file stem is not UTF-8");
192
193             (triple, Some(selection))
194         } else {
195             (selection, None)
196         };
197
198         let triple = INTERNER.intern_str(triple);
199         let file = file.map(|f| INTERNER.intern_str(f));
200
201         Self { triple, file }
202     }
203
204     pub fn rustc_target_arg(&self) -> &str {
205         self.file.as_ref().unwrap_or(&self.triple)
206     }
207
208     pub fn contains(&self, needle: &str) -> bool {
209         self.triple.contains(needle)
210     }
211
212     pub fn starts_with(&self, needle: &str) -> bool {
213         self.triple.starts_with(needle)
214     }
215
216     pub fn ends_with(&self, needle: &str) -> bool {
217         self.triple.ends_with(needle)
218     }
219 }
220
221 impl fmt::Display for TargetSelection {
222     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223         write!(f, "{}", self.triple)?;
224         if let Some(file) = self.file {
225             write!(f, "({})", file)?;
226         }
227         Ok(())
228     }
229 }
230
231 impl PartialEq<&str> for TargetSelection {
232     fn eq(&self, other: &&str) -> bool {
233         self.triple == *other
234     }
235 }
236
237 /// Per-target configuration stored in the global configuration structure.
238 #[derive(Default)]
239 pub struct Target {
240     /// Some(path to llvm-config) if using an external LLVM.
241     pub llvm_config: Option<PathBuf>,
242     /// Some(path to FileCheck) if one was specified.
243     pub llvm_filecheck: Option<PathBuf>,
244     pub cc: Option<PathBuf>,
245     pub cxx: Option<PathBuf>,
246     pub ar: Option<PathBuf>,
247     pub ranlib: Option<PathBuf>,
248     pub linker: Option<PathBuf>,
249     pub ndk: Option<PathBuf>,
250     pub crt_static: Option<bool>,
251     pub musl_root: Option<PathBuf>,
252     pub musl_libdir: Option<PathBuf>,
253     pub wasi_root: Option<PathBuf>,
254     pub qemu_rootfs: Option<PathBuf>,
255     pub no_std: bool,
256 }
257
258 impl Target {
259     pub fn from_triple(triple: &str) -> Self {
260         let mut target: Self = Default::default();
261         if triple.contains("-none") || triple.contains("nvptx") {
262             target.no_std = true;
263         }
264         target
265     }
266 }
267 /// Structure of the `config.toml` file that configuration is read from.
268 ///
269 /// This structure uses `Decodable` to automatically decode a TOML configuration
270 /// file into this format, and then this is traversed and written into the above
271 /// `Config` structure.
272 #[derive(Deserialize, Default)]
273 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
274 struct TomlConfig {
275     build: Option<Build>,
276     install: Option<Install>,
277     llvm: Option<Llvm>,
278     rust: Option<Rust>,
279     target: Option<HashMap<String, TomlTarget>>,
280     dist: Option<Dist>,
281 }
282
283 /// TOML representation of various global build decisions.
284 #[derive(Deserialize, Default, Clone)]
285 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
286 struct Build {
287     build: Option<String>,
288     host: Option<Vec<String>>,
289     target: Option<Vec<String>>,
290     // This is ignored, the rust code always gets the build directory from the `BUILD_DIR` env variable
291     build_dir: Option<String>,
292     cargo: Option<String>,
293     rustc: Option<String>,
294     rustfmt: Option<String>, /* allow bootstrap.py to use rustfmt key */
295     docs: Option<bool>,
296     compiler_docs: Option<bool>,
297     submodules: Option<bool>,
298     fast_submodules: Option<bool>,
299     gdb: Option<String>,
300     nodejs: Option<String>,
301     python: Option<String>,
302     locked_deps: Option<bool>,
303     vendor: Option<bool>,
304     full_bootstrap: Option<bool>,
305     extended: Option<bool>,
306     tools: Option<HashSet<String>>,
307     verbose: Option<usize>,
308     sanitizers: Option<bool>,
309     profiler: Option<bool>,
310     cargo_native_static: Option<bool>,
311     low_priority: Option<bool>,
312     configure_args: Option<Vec<String>>,
313     local_rebuild: Option<bool>,
314     print_step_timings: Option<bool>,
315     doc_stage: Option<u32>,
316     build_stage: Option<u32>,
317     test_stage: Option<u32>,
318     install_stage: Option<u32>,
319     dist_stage: Option<u32>,
320     bench_stage: Option<u32>,
321 }
322
323 /// TOML representation of various global install decisions.
324 #[derive(Deserialize, Default, Clone)]
325 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
326 struct Install {
327     prefix: Option<String>,
328     sysconfdir: Option<String>,
329     docdir: Option<String>,
330     bindir: Option<String>,
331     libdir: Option<String>,
332     mandir: Option<String>,
333     datadir: Option<String>,
334
335     // standard paths, currently unused
336     infodir: Option<String>,
337     localstatedir: Option<String>,
338 }
339
340 /// TOML representation of how the LLVM build is configured.
341 #[derive(Deserialize, Default)]
342 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
343 struct Llvm {
344     skip_rebuild: Option<bool>,
345     optimize: Option<bool>,
346     thin_lto: Option<bool>,
347     release_debuginfo: Option<bool>,
348     assertions: Option<bool>,
349     ccache: Option<StringOrBool>,
350     version_check: Option<bool>,
351     static_libstdcpp: Option<bool>,
352     ninja: Option<bool>,
353     targets: Option<String>,
354     experimental_targets: Option<String>,
355     link_jobs: Option<u32>,
356     link_shared: Option<bool>,
357     version_suffix: Option<String>,
358     clang_cl: Option<String>,
359     cflags: Option<String>,
360     cxxflags: Option<String>,
361     ldflags: Option<String>,
362     use_libcxx: Option<bool>,
363     use_linker: Option<String>,
364     allow_old_toolchain: Option<bool>,
365     download_ci_llvm: Option<bool>,
366 }
367
368 #[derive(Deserialize, Default, Clone)]
369 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
370 struct Dist {
371     sign_folder: Option<String>,
372     gpg_password_file: Option<String>,
373     upload_addr: Option<String>,
374     src_tarball: Option<bool>,
375     missing_tools: Option<bool>,
376 }
377
378 #[derive(Deserialize)]
379 #[serde(untagged)]
380 enum StringOrBool {
381     String(String),
382     Bool(bool),
383 }
384
385 impl Default for StringOrBool {
386     fn default() -> StringOrBool {
387         StringOrBool::Bool(false)
388     }
389 }
390
391 /// TOML representation of how the Rust build is configured.
392 #[derive(Deserialize, Default)]
393 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
394 struct Rust {
395     optimize: Option<bool>,
396     debug: Option<bool>,
397     codegen_units: Option<u32>,
398     codegen_units_std: Option<u32>,
399     debug_assertions: Option<bool>,
400     debug_assertions_std: Option<bool>,
401     debug_logging: Option<bool>,
402     debuginfo_level: Option<u32>,
403     debuginfo_level_rustc: Option<u32>,
404     debuginfo_level_std: Option<u32>,
405     debuginfo_level_tools: Option<u32>,
406     debuginfo_level_tests: Option<u32>,
407     backtrace: Option<bool>,
408     incremental: Option<bool>,
409     parallel_compiler: Option<bool>,
410     default_linker: Option<String>,
411     channel: Option<String>,
412     musl_root: Option<String>,
413     rpath: Option<bool>,
414     verbose_tests: Option<bool>,
415     optimize_tests: Option<bool>,
416     codegen_tests: Option<bool>,
417     ignore_git: Option<bool>,
418     dist_src: Option<bool>,
419     save_toolstates: Option<String>,
420     codegen_backends: Option<Vec<String>>,
421     lld: Option<bool>,
422     use_lld: Option<bool>,
423     llvm_tools: Option<bool>,
424     deny_warnings: Option<bool>,
425     backtrace_on_ice: Option<bool>,
426     verify_llvm_ir: Option<bool>,
427     thin_lto_import_instr_limit: Option<u32>,
428     remap_debuginfo: Option<bool>,
429     jemalloc: Option<bool>,
430     test_compare_mode: Option<bool>,
431     llvm_libunwind: Option<bool>,
432     control_flow_guard: Option<bool>,
433     new_symbol_mangling: Option<bool>,
434 }
435
436 /// TOML representation of how each build target is configured.
437 #[derive(Deserialize, Default)]
438 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
439 struct TomlTarget {
440     cc: Option<String>,
441     cxx: Option<String>,
442     ar: Option<String>,
443     ranlib: Option<String>,
444     linker: Option<String>,
445     llvm_config: Option<String>,
446     llvm_filecheck: Option<String>,
447     android_ndk: Option<String>,
448     crt_static: Option<bool>,
449     musl_root: Option<String>,
450     musl_libdir: Option<String>,
451     wasi_root: Option<String>,
452     qemu_rootfs: Option<String>,
453     no_std: Option<bool>,
454 }
455
456 impl Config {
457     fn path_from_python(var_key: &str) -> PathBuf {
458         match env::var_os(var_key) {
459             Some(var_val) => Self::normalize_python_path(var_val),
460             _ => panic!("expected '{}' to be set", var_key),
461         }
462     }
463
464     /// Normalizes paths from Python slightly. We don't trust paths from Python (#49785).
465     fn normalize_python_path(path: OsString) -> PathBuf {
466         Path::new(&path).components().collect()
467     }
468
469     pub fn default_opts() -> Config {
470         let mut config = Config::default();
471         config.llvm_optimize = true;
472         config.ninja_in_file = true;
473         config.llvm_version_check = true;
474         config.backtrace = true;
475         config.rust_optimize = true;
476         config.rust_optimize_tests = true;
477         config.submodules = true;
478         config.fast_submodules = true;
479         config.docs = true;
480         config.rust_rpath = true;
481         config.channel = "dev".to_string();
482         config.codegen_tests = true;
483         config.ignore_git = false;
484         config.rust_dist_src = true;
485         config.rust_codegen_backends = vec![INTERNER.intern_str("llvm")];
486         config.deny_warnings = true;
487         config.missing_tools = false;
488
489         // set by bootstrap.py
490         config.build = TargetSelection::from_user(&env::var("BUILD").expect("'BUILD' to be set"));
491         config.src = Config::path_from_python("SRC");
492         config.out = Config::path_from_python("BUILD_DIR");
493
494         config.initial_rustc = Config::path_from_python("RUSTC");
495         config.initial_cargo = Config::path_from_python("CARGO");
496         config.initial_rustfmt = env::var_os("RUSTFMT").map(Config::normalize_python_path);
497
498         config
499     }
500
501     pub fn parse(args: &[String]) -> Config {
502         let flags = Flags::parse(&args);
503
504         let mut config = Config::default_opts();
505         config.exclude = flags.exclude;
506         config.rustc_error_format = flags.rustc_error_format;
507         config.json_output = flags.json_output;
508         config.on_fail = flags.on_fail;
509         config.jobs = flags.jobs.map(threads_from_config);
510         config.cmd = flags.cmd;
511         config.incremental = flags.incremental;
512         config.dry_run = flags.dry_run;
513         config.keep_stage = flags.keep_stage;
514         config.bindir = "bin".into(); // default
515         if let Some(value) = flags.deny_warnings {
516             config.deny_warnings = value;
517         }
518
519         if config.dry_run {
520             let dir = config.out.join("tmp-dry-run");
521             t!(fs::create_dir_all(&dir));
522             config.out = dir;
523         }
524
525         #[cfg(test)]
526         let toml = TomlConfig::default();
527         #[cfg(not(test))]
528         let toml = flags
529             .config
530             .map(|file| {
531                 use std::process;
532
533                 let contents = t!(fs::read_to_string(&file));
534                 match toml::from_str(&contents) {
535                     Ok(table) => table,
536                     Err(err) => {
537                         println!(
538                             "failed to parse TOML configuration '{}': {}",
539                             file.display(),
540                             err
541                         );
542                         process::exit(2);
543                     }
544                 }
545             })
546             .unwrap_or_else(TomlConfig::default);
547
548         let build = toml.build.unwrap_or_default();
549
550         // If --target was specified but --host wasn't specified, don't run any host-only tests.
551         let has_hosts = build.host.is_some() || flags.host.is_some();
552         let has_targets = build.target.is_some() || flags.target.is_some();
553         config.skip_only_host_steps = !has_hosts && has_targets;
554
555         config.hosts = if let Some(arg_host) = flags.host {
556             arg_host
557         } else if let Some(file_host) = build.host {
558             file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
559         } else {
560             vec![config.build]
561         };
562         config.targets = if let Some(arg_target) = flags.target {
563             arg_target
564         } else if let Some(file_target) = build.target {
565             file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
566         } else {
567             // If target is *not* configured, then default to the host
568             // toolchains.
569             config.hosts.clone()
570         };
571
572         config.nodejs = build.nodejs.map(PathBuf::from);
573         config.gdb = build.gdb.map(PathBuf::from);
574         config.python = build.python.map(PathBuf::from);
575         set(&mut config.low_priority, build.low_priority);
576         set(&mut config.compiler_docs, build.compiler_docs);
577         set(&mut config.docs, build.docs);
578         set(&mut config.submodules, build.submodules);
579         set(&mut config.fast_submodules, build.fast_submodules);
580         set(&mut config.locked_deps, build.locked_deps);
581         set(&mut config.vendor, build.vendor);
582         set(&mut config.full_bootstrap, build.full_bootstrap);
583         set(&mut config.extended, build.extended);
584         config.tools = build.tools;
585         set(&mut config.verbose, build.verbose);
586         set(&mut config.sanitizers, build.sanitizers);
587         set(&mut config.profiler, build.profiler);
588         set(&mut config.cargo_native_static, build.cargo_native_static);
589         set(&mut config.configure_args, build.configure_args);
590         set(&mut config.local_rebuild, build.local_rebuild);
591         set(&mut config.print_step_timings, build.print_step_timings);
592
593         // See https://github.com/rust-lang/compiler-team/issues/326
594         config.stage = match config.cmd {
595             Subcommand::Doc { .. } => flags.stage.or(build.doc_stage).unwrap_or(0),
596             Subcommand::Build { .. } => flags.stage.or(build.build_stage).unwrap_or(1),
597             Subcommand::Test { .. } => flags.stage.or(build.test_stage).unwrap_or(1),
598             Subcommand::Bench { .. } => flags.stage.or(build.bench_stage).unwrap_or(2),
599             Subcommand::Dist { .. } => flags.stage.or(build.dist_stage).unwrap_or(2),
600             Subcommand::Install { .. } => flags.stage.or(build.install_stage).unwrap_or(2),
601             // These are all bootstrap tools, which don't depend on the compiler.
602             // The stage we pass shouldn't matter, but use 0 just in case.
603             Subcommand::Clean { .. }
604             | Subcommand::Check { .. }
605             | Subcommand::Clippy { .. }
606             | Subcommand::Fix { .. }
607             | Subcommand::Run { .. }
608             | Subcommand::Format { .. } => flags.stage.unwrap_or(0),
609         };
610
611         // CI should always run stage 2 builds, unless it specifically states otherwise
612         #[cfg(not(test))]
613         if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None {
614             match config.cmd {
615                 Subcommand::Test { .. }
616                 | Subcommand::Doc { .. }
617                 | Subcommand::Build { .. }
618                 | Subcommand::Bench { .. }
619                 | Subcommand::Dist { .. }
620                 | Subcommand::Install { .. } => assert_eq!(config.stage, 2),
621                 Subcommand::Clean { .. }
622                 | Subcommand::Check { .. }
623                 | Subcommand::Clippy { .. }
624                 | Subcommand::Fix { .. }
625                 | Subcommand::Run { .. }
626                 | Subcommand::Format { .. } => {}
627             }
628         }
629
630         config.verbose = cmp::max(config.verbose, flags.verbose);
631
632         if let Some(install) = toml.install {
633             config.prefix = install.prefix.map(PathBuf::from);
634             config.sysconfdir = install.sysconfdir.map(PathBuf::from);
635             config.datadir = install.datadir.map(PathBuf::from);
636             config.docdir = install.docdir.map(PathBuf::from);
637             set(&mut config.bindir, install.bindir.map(PathBuf::from));
638             config.libdir = install.libdir.map(PathBuf::from);
639             config.mandir = install.mandir.map(PathBuf::from);
640         }
641
642         // We want the llvm-skip-rebuild flag to take precedence over the
643         // skip-rebuild config.toml option so we store it separately
644         // so that we can infer the right value
645         let mut llvm_skip_rebuild = flags.llvm_skip_rebuild;
646
647         // Store off these values as options because if they're not provided
648         // we'll infer default values for them later
649         let mut llvm_assertions = None;
650         let mut debug = None;
651         let mut debug_assertions = None;
652         let mut debug_assertions_std = None;
653         let mut debug_logging = None;
654         let mut debuginfo_level = None;
655         let mut debuginfo_level_rustc = None;
656         let mut debuginfo_level_std = None;
657         let mut debuginfo_level_tools = None;
658         let mut debuginfo_level_tests = None;
659         let mut optimize = None;
660         let mut ignore_git = None;
661
662         if let Some(llvm) = toml.llvm {
663             match llvm.ccache {
664                 Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
665                 Some(StringOrBool::Bool(true)) => {
666                     config.ccache = Some("ccache".to_string());
667                 }
668                 Some(StringOrBool::Bool(false)) | None => {}
669             }
670             set(&mut config.ninja_in_file, llvm.ninja);
671             llvm_assertions = llvm.assertions;
672             llvm_skip_rebuild = llvm_skip_rebuild.or(llvm.skip_rebuild);
673             set(&mut config.llvm_optimize, llvm.optimize);
674             set(&mut config.llvm_thin_lto, llvm.thin_lto);
675             set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
676             set(&mut config.llvm_version_check, llvm.version_check);
677             set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp);
678             set(&mut config.llvm_link_shared, llvm.link_shared);
679             config.llvm_targets = llvm.targets.clone();
680             config.llvm_experimental_targets = llvm.experimental_targets.clone();
681             config.llvm_link_jobs = llvm.link_jobs;
682             config.llvm_version_suffix = llvm.version_suffix.clone();
683             config.llvm_clang_cl = llvm.clang_cl.clone();
684
685             config.llvm_cflags = llvm.cflags.clone();
686             config.llvm_cxxflags = llvm.cxxflags.clone();
687             config.llvm_ldflags = llvm.ldflags.clone();
688             set(&mut config.llvm_use_libcxx, llvm.use_libcxx);
689             config.llvm_use_linker = llvm.use_linker.clone();
690             config.llvm_allow_old_toolchain = llvm.allow_old_toolchain;
691             config.llvm_from_ci = llvm.download_ci_llvm.unwrap_or(false);
692
693             if config.llvm_from_ci {
694                 // None of the LLVM options, except assertions, are supported
695                 // when using downloaded LLVM. We could just ignore these but
696                 // that's potentially confusing, so force them to not be
697                 // explicitly set. The defaults and CI defaults don't
698                 // necessarily match but forcing people to match (somewhat
699                 // arbitrary) CI configuration locally seems bad/hard.
700                 check_ci_llvm!(llvm.optimize);
701                 check_ci_llvm!(llvm.thin_lto);
702                 check_ci_llvm!(llvm.release_debuginfo);
703                 check_ci_llvm!(llvm.link_shared);
704                 check_ci_llvm!(llvm.static_libstdcpp);
705                 check_ci_llvm!(llvm.targets);
706                 check_ci_llvm!(llvm.experimental_targets);
707                 check_ci_llvm!(llvm.link_jobs);
708                 check_ci_llvm!(llvm.link_shared);
709                 check_ci_llvm!(llvm.clang_cl);
710                 check_ci_llvm!(llvm.version_suffix);
711                 check_ci_llvm!(llvm.cflags);
712                 check_ci_llvm!(llvm.cxxflags);
713                 check_ci_llvm!(llvm.ldflags);
714                 check_ci_llvm!(llvm.use_libcxx);
715                 check_ci_llvm!(llvm.use_linker);
716                 check_ci_llvm!(llvm.allow_old_toolchain);
717
718                 // CI-built LLVM is shared
719                 config.llvm_link_shared = true;
720             }
721
722             if config.llvm_thin_lto {
723                 // If we're building with ThinLTO on, we want to link to LLVM
724                 // shared, to avoid re-doing ThinLTO (which happens in the link
725                 // step) with each stage.
726                 config.llvm_link_shared = true;
727             }
728         }
729
730         if let Some(rust) = toml.rust {
731             debug = rust.debug;
732             debug_assertions = rust.debug_assertions;
733             debug_assertions_std = rust.debug_assertions_std;
734             debug_logging = rust.debug_logging;
735             debuginfo_level = rust.debuginfo_level;
736             debuginfo_level_rustc = rust.debuginfo_level_rustc;
737             debuginfo_level_std = rust.debuginfo_level_std;
738             debuginfo_level_tools = rust.debuginfo_level_tools;
739             debuginfo_level_tests = rust.debuginfo_level_tests;
740             optimize = rust.optimize;
741             ignore_git = rust.ignore_git;
742             set(&mut config.rust_new_symbol_mangling, rust.new_symbol_mangling);
743             set(&mut config.rust_optimize_tests, rust.optimize_tests);
744             set(&mut config.codegen_tests, rust.codegen_tests);
745             set(&mut config.rust_rpath, rust.rpath);
746             set(&mut config.jemalloc, rust.jemalloc);
747             set(&mut config.test_compare_mode, rust.test_compare_mode);
748             set(&mut config.llvm_libunwind, rust.llvm_libunwind);
749             set(&mut config.backtrace, rust.backtrace);
750             set(&mut config.channel, rust.channel);
751             set(&mut config.rust_dist_src, rust.dist_src);
752             set(&mut config.verbose_tests, rust.verbose_tests);
753             // in the case "false" is set explicitly, do not overwrite the command line args
754             if let Some(true) = rust.incremental {
755                 config.incremental = true;
756             }
757             set(&mut config.use_lld, rust.use_lld);
758             set(&mut config.lld_enabled, rust.lld);
759             set(&mut config.llvm_tools_enabled, rust.llvm_tools);
760             config.rustc_parallel = rust.parallel_compiler.unwrap_or(false);
761             config.rustc_default_linker = rust.default_linker;
762             config.musl_root = rust.musl_root.map(PathBuf::from);
763             config.save_toolstates = rust.save_toolstates.map(PathBuf::from);
764             set(&mut config.deny_warnings, flags.deny_warnings.or(rust.deny_warnings));
765             set(&mut config.backtrace_on_ice, rust.backtrace_on_ice);
766             set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir);
767             config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit;
768             set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo);
769             set(&mut config.control_flow_guard, rust.control_flow_guard);
770
771             if let Some(ref backends) = rust.codegen_backends {
772                 config.rust_codegen_backends =
773                     backends.iter().map(|s| INTERNER.intern_str(s)).collect();
774             }
775
776             config.rust_codegen_units = rust.codegen_units.map(threads_from_config);
777             config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config);
778         }
779
780         if let Some(t) = toml.target {
781             for (triple, cfg) in t {
782                 let mut target = Target::from_triple(&triple);
783
784                 if let Some(ref s) = cfg.llvm_config {
785                     target.llvm_config = Some(config.src.join(s));
786                 }
787                 if let Some(ref s) = cfg.llvm_filecheck {
788                     target.llvm_filecheck = Some(config.src.join(s));
789                 }
790                 if let Some(ref s) = cfg.android_ndk {
791                     target.ndk = Some(config.src.join(s));
792                 }
793                 if let Some(s) = cfg.no_std {
794                     target.no_std = s;
795                 }
796                 target.cc = cfg.cc.map(PathBuf::from);
797                 target.cxx = cfg.cxx.map(PathBuf::from);
798                 target.ar = cfg.ar.map(PathBuf::from);
799                 target.ranlib = cfg.ranlib.map(PathBuf::from);
800                 target.linker = cfg.linker.map(PathBuf::from);
801                 target.crt_static = cfg.crt_static;
802                 target.musl_root = cfg.musl_root.map(PathBuf::from);
803                 target.musl_libdir = cfg.musl_libdir.map(PathBuf::from);
804                 target.wasi_root = cfg.wasi_root.map(PathBuf::from);
805                 target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from);
806
807                 config.target_config.insert(TargetSelection::from_user(&triple), target);
808             }
809         }
810
811         if config.llvm_from_ci {
812             let triple = &config.build.triple;
813             let mut build_target = config
814                 .target_config
815                 .entry(config.build)
816                 .or_insert_with(|| Target::from_triple(&triple));
817
818             check_ci_llvm!(build_target.llvm_config);
819             check_ci_llvm!(build_target.llvm_filecheck);
820             let ci_llvm_bin = config.out.join(&*config.build.triple).join("ci-llvm/bin");
821             build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", config.build)));
822             build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", config.build)));
823         }
824
825         if let Some(t) = toml.dist {
826             config.dist_sign_folder = t.sign_folder.map(PathBuf::from);
827             config.dist_gpg_password_file = t.gpg_password_file.map(PathBuf::from);
828             config.dist_upload_addr = t.upload_addr;
829             set(&mut config.rust_dist_src, t.src_tarball);
830             set(&mut config.missing_tools, t.missing_tools);
831         }
832
833         // Now that we've reached the end of our configuration, infer the
834         // default values for all options that we haven't otherwise stored yet.
835
836         set(&mut config.initial_rustc, build.rustc.map(PathBuf::from));
837         set(&mut config.initial_cargo, build.cargo.map(PathBuf::from));
838
839         config.llvm_skip_rebuild = llvm_skip_rebuild.unwrap_or(false);
840
841         let default = false;
842         config.llvm_assertions = llvm_assertions.unwrap_or(default);
843
844         let default = true;
845         config.rust_optimize = optimize.unwrap_or(default);
846
847         let default = debug == Some(true);
848         config.rust_debug_assertions = debug_assertions.unwrap_or(default);
849         config.rust_debug_assertions_std =
850             debug_assertions_std.unwrap_or(config.rust_debug_assertions);
851
852         config.rust_debug_logging = debug_logging.unwrap_or(config.rust_debug_assertions);
853
854         let with_defaults = |debuginfo_level_specific: Option<u32>| {
855             debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
856                 1
857             } else {
858                 0
859             })
860         };
861         config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
862         config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
863         config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
864         config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(0);
865
866         let default = config.channel == "dev";
867         config.ignore_git = ignore_git.unwrap_or(default);
868
869         config
870     }
871
872     /// Try to find the relative path of `bindir`, otherwise return it in full.
873     pub fn bindir_relative(&self) -> &Path {
874         let bindir = &self.bindir;
875         if bindir.is_absolute() {
876             // Try to make it relative to the prefix.
877             if let Some(prefix) = &self.prefix {
878                 if let Ok(stripped) = bindir.strip_prefix(prefix) {
879                     return stripped;
880                 }
881             }
882         }
883         bindir
884     }
885
886     /// Try to find the relative path of `libdir`.
887     pub fn libdir_relative(&self) -> Option<&Path> {
888         let libdir = self.libdir.as_ref()?;
889         if libdir.is_relative() {
890             Some(libdir)
891         } else {
892             // Try to make it relative to the prefix.
893             libdir.strip_prefix(self.prefix.as_ref()?).ok()
894         }
895     }
896
897     pub fn verbose(&self) -> bool {
898         self.verbose > 0
899     }
900
901     pub fn very_verbose(&self) -> bool {
902         self.verbose > 1
903     }
904
905     pub fn llvm_enabled(&self) -> bool {
906         self.rust_codegen_backends.contains(&INTERNER.intern_str("llvm"))
907     }
908 }
909
910 fn set<T>(field: &mut T, val: Option<T>) {
911     if let Some(v) = val {
912         *field = v;
913     }
914 }
915
916 fn threads_from_config(v: u32) -> u32 {
917     match v {
918         0 => num_cpus::get() as u32,
919         n => n,
920     }
921 }