]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/options.rs
Rollup merge of #71459 - divergentdave:pointer-offset-0x, r=RalfJung
[rust.git] / src / librustc_session / options.rs
1 use crate::config::*;
2
3 use crate::early_error;
4 use crate::lint;
5 use crate::search_paths::SearchPath;
6 use crate::utils::NativeLibraryKind;
7
8 use rustc_target::spec::TargetTriple;
9 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
10
11 use rustc_feature::UnstableFeatures;
12 use rustc_span::edition::Edition;
13 use rustc_span::SourceFileHashAlgorithm;
14
15 use std::collections::BTreeMap;
16
17 use std::collections::hash_map::DefaultHasher;
18 use std::hash::Hasher;
19 use std::path::PathBuf;
20 use std::str;
21
22 macro_rules! hash_option {
23     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => {{}};
24     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => {{
25         if $sub_hashes
26             .insert(stringify!($opt_name), $opt_expr as &dyn dep_tracking::DepTrackingHash)
27             .is_some()
28         {
29             panic!("duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
30         }
31     }};
32 }
33
34 macro_rules! top_level_options {
35     (pub struct Options { $(
36         $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
37     )* } ) => (
38         #[derive(Clone)]
39         pub struct Options {
40             $(pub $opt: $t),*
41         }
42
43         impl Options {
44             pub fn dep_tracking_hash(&self) -> u64 {
45                 let mut sub_hashes = BTreeMap::new();
46                 $({
47                     hash_option!($opt,
48                                  &self.$opt,
49                                  &mut sub_hashes,
50                                  [$dep_tracking_marker $($warn_val,
51                                                          $warn_text,
52                                                          self.error_format)*]);
53                 })*
54                 let mut hasher = DefaultHasher::new();
55                 dep_tracking::stable_hash(sub_hashes,
56                                           &mut hasher,
57                                           self.error_format);
58                 hasher.finish()
59             }
60         }
61     );
62 }
63
64 // The top-level command-line options struct.
65 //
66 // For each option, one has to specify how it behaves with regard to the
67 // dependency tracking system of incremental compilation. This is done via the
68 // square-bracketed directive after the field type. The options are:
69 //
70 // [TRACKED]
71 // A change in the given field will cause the compiler to completely clear the
72 // incremental compilation cache before proceeding.
73 //
74 // [UNTRACKED]
75 // Incremental compilation is not influenced by this option.
76 //
77 // If you add a new option to this struct or one of the sub-structs like
78 // `CodegenOptions`, think about how it influences incremental compilation. If in
79 // doubt, specify [TRACKED], which is always "correct" but might lead to
80 // unnecessary re-compilation.
81 top_level_options!(
82     pub struct Options {
83         // The crate config requested for the session, which may be combined
84         // with additional crate configurations during the compile process.
85         crate_types: Vec<CrateType> [TRACKED],
86         optimize: OptLevel [TRACKED],
87         // Include the `debug_assertions` flag in dependency tracking, since it
88         // can influence whether overflow checks are done or not.
89         debug_assertions: bool [TRACKED],
90         debuginfo: DebugInfo [TRACKED],
91         lint_opts: Vec<(String, lint::Level)> [TRACKED],
92         lint_cap: Option<lint::Level> [TRACKED],
93         describe_lints: bool [UNTRACKED],
94         output_types: OutputTypes [TRACKED],
95         search_paths: Vec<SearchPath> [UNTRACKED],
96         libs: Vec<(String, Option<String>, Option<NativeLibraryKind>)> [TRACKED],
97         maybe_sysroot: Option<PathBuf> [UNTRACKED],
98
99         target_triple: TargetTriple [TRACKED],
100
101         test: bool [TRACKED],
102         error_format: ErrorOutputType [UNTRACKED],
103
104         // If `Some`, enable incremental compilation, using the given
105         // directory to store intermediate results.
106         incremental: Option<PathBuf> [UNTRACKED],
107
108         debugging_opts: DebuggingOptions [TRACKED],
109         prints: Vec<PrintRequest> [UNTRACKED],
110         // Determines which borrow checker(s) to run. This is the parsed, sanitized
111         // version of `debugging_opts.borrowck`, which is just a plain string.
112         borrowck_mode: BorrowckMode [UNTRACKED],
113         cg: CodegenOptions [TRACKED],
114         externs: Externs [UNTRACKED],
115         crate_name: Option<String> [TRACKED],
116         // An optional name to use as the crate for std during std injection,
117         // written `extern crate name as std`. Defaults to `std`. Used by
118         // out-of-tree drivers.
119         alt_std_name: Option<String> [TRACKED],
120         // Indicates how the compiler should treat unstable features.
121         unstable_features: UnstableFeatures [TRACKED],
122
123         // Indicates whether this run of the compiler is actually rustdoc. This
124         // is currently just a hack and will be removed eventually, so please
125         // try to not rely on this too much.
126         actually_rustdoc: bool [TRACKED],
127
128         // Specifications of codegen units / ThinLTO which are forced as a
129         // result of parsing command line options. These are not necessarily
130         // what rustc was invoked with, but massaged a bit to agree with
131         // commands like `--emit llvm-ir` which they're often incompatible with
132         // if we otherwise use the defaults of rustc.
133         cli_forced_codegen_units: Option<usize> [UNTRACKED],
134         cli_forced_thinlto_off: bool [UNTRACKED],
135
136         // Remap source path prefixes in all output (messages, object files, debug, etc.).
137         remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],
138
139         edition: Edition [TRACKED],
140
141         // `true` if we're emitting JSON blobs about each artifact produced
142         // by the compiler.
143         json_artifact_notifications: bool [TRACKED],
144
145         pretty: Option<PpMode> [UNTRACKED],
146     }
147 );
148
149 /// Defines all `CodegenOptions`/`DebuggingOptions` fields and parsers all at once. The goal of this
150 /// macro is to define an interface that can be programmatically used by the option parser
151 /// to initialize the struct without hardcoding field names all over the place.
152 ///
153 /// The goal is to invoke this macro once with the correct fields, and then this macro generates all
154 /// necessary code. The main gotcha of this macro is the `cgsetters` module which is a bunch of
155 /// generated code to parse an option into its respective field in the struct. There are a few
156 /// hand-written parsers for parsing specific types of values in this module.
157 macro_rules! options {
158     ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
159      $buildfn:ident, $prefix:expr, $outputname:expr,
160      $stat:ident, $mod_desc:ident, $mod_set:ident,
161      $($opt:ident : $t:ty = (
162         $init:expr,
163         $parse:ident,
164         [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
165         $desc:expr)
166      ),* ,) =>
167 (
168     #[derive(Clone)]
169     pub struct $struct_name { $(pub $opt: $t),* }
170
171     pub fn $defaultfn() -> $struct_name {
172         $struct_name { $($opt: $init),* }
173     }
174
175     pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
176     {
177         let mut op = $defaultfn();
178         for option in matches.opt_strs($prefix) {
179             let mut iter = option.splitn(2, '=');
180             let key = iter.next().unwrap();
181             let value = iter.next();
182             let option_to_lookup = key.replace("-", "_");
183             let mut found = false;
184             for &(candidate, setter, type_desc, _) in $stat {
185                 if option_to_lookup != candidate { continue }
186                 if !setter(&mut op, value) {
187                     match value {
188                         None => {
189                             early_error(error_format, &format!("{0} option `{1}` requires \
190                                                                 {2} ({3} {1}=<value>)",
191                                                                $outputname, key,
192                                                                type_desc, $prefix))
193                         }
194                         Some(value) => {
195                             early_error(error_format, &format!("incorrect value `{}` for {} \
196                                                                 option `{}` - {} was expected",
197                                                                value, $outputname,
198                                                                key, type_desc))
199                         }
200                     }
201                 }
202                 found = true;
203                 break;
204             }
205             if !found {
206                 early_error(error_format, &format!("unknown {} option: `{}`",
207                                                    $outputname, key));
208             }
209         }
210         return op;
211     }
212
213     impl dep_tracking::DepTrackingHash for $struct_name {
214         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
215             let mut sub_hashes = BTreeMap::new();
216             $({
217                 hash_option!($opt,
218                              &self.$opt,
219                              &mut sub_hashes,
220                              [$dep_tracking_marker $($dep_warn_val,
221                                                      $dep_warn_text,
222                                                      error_format)*]);
223             })*
224             dep_tracking::stable_hash(sub_hashes, hasher, error_format);
225         }
226     }
227
228     pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
229     pub const $stat: &[(&str, $setter_name, &str, &str)] =
230         &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
231
232     #[allow(non_upper_case_globals, dead_code)]
233     mod $mod_desc {
234         pub const parse_no_flag: &str = "no value";
235         pub const parse_bool: &str = "one of: `y`, `yes`, `on`, `n`, `no`, or `off`";
236         pub const parse_opt_bool: &str = parse_bool;
237         pub const parse_string: &str = "a string";
238         pub const parse_opt_string: &str = parse_string;
239         pub const parse_string_push: &str = parse_string;
240         pub const parse_opt_pathbuf: &str = "a path";
241         pub const parse_pathbuf_push: &str = parse_opt_pathbuf;
242         pub const parse_list: &str = "a space-separated list of strings";
243         pub const parse_opt_list: &str = parse_list;
244         pub const parse_opt_comma_list: &str = "a comma-separated list of strings";
245         pub const parse_uint: &str = "a number";
246         pub const parse_opt_uint: &str = parse_uint;
247         pub const parse_threads: &str = parse_uint;
248         pub const parse_passes: &str = "a space-separated list of passes, or `all`";
249         pub const parse_panic_strategy: &str = "either `unwind` or `abort`";
250         pub const parse_relro_level: &str = "one of: `full`, `partial`, or `off`";
251         pub const parse_sanitizer: &str = "one of: `address`, `leak`, `memory` or `thread`";
252         pub const parse_sanitizer_list: &str = "comma separated list of sanitizers";
253         pub const parse_sanitizer_memory_track_origins: &str = "0, 1, or 2";
254         pub const parse_cfguard: &str = "either `disabled`, `nochecks`, or `checks`";
255         pub const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavor::one_of();
256         pub const parse_optimization_fuel: &str = "crate=integer";
257         pub const parse_unpretty: &str = "`string` or `string=string`";
258         pub const parse_treat_err_as_bug: &str = "either no value or a number bigger than 0";
259         pub const parse_lto: &str =
260             "either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, `fat`, or omitted";
261         pub const parse_linker_plugin_lto: &str =
262             "either a boolean (`yes`, `no`, `on`, `off`, etc), or the path to the linker plugin";
263         pub const parse_switch_with_opt_path: &str =
264             "an optional path to the profiling data output directory";
265         pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
266         pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)";
267         pub const parse_src_file_hash: &str = "either `md5` or `sha1`";
268     }
269
270     #[allow(dead_code)]
271     mod $mod_set {
272         use super::{$struct_name, Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
273             SymbolManglingVersion, CFGuard, SourceFileHashAlgorithm};
274         use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
275         use std::path::PathBuf;
276         use std::str::FromStr;
277
278         // Sometimes different options need to build a common structure.
279         // That structure can kept in one of the options' fields, the others become dummy.
280         macro_rules! redirect_field {
281             ($cg:ident.link_arg) => { $cg.link_args };
282             ($cg:ident.pre_link_arg) => { $cg.pre_link_args };
283             ($cg:ident.$field:ident) => { $cg.$field };
284         }
285
286         $(
287             pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
288                 $parse(&mut redirect_field!(cg.$opt), v)
289             }
290         )*
291
292         /// This is for boolean options that don't take a value and start with
293         /// `no-`. This style of option is deprecated.
294         fn parse_no_flag(slot: &mut bool, v: Option<&str>) -> bool {
295             match v {
296                 None => { *slot = true; true }
297                 Some(_) => false,
298             }
299         }
300
301         /// Use this for any boolean option that has a static default.
302         fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
303             match v {
304                 Some("y") | Some("yes") | Some("on") | None => { *slot = true; true }
305                 Some("n") | Some("no") | Some("off") => { *slot = false; true }
306                 _ => false,
307             }
308         }
309
310         /// Use this for any boolean option that lacks a static default. (The
311         /// actions taken when such an option is not specified will depend on
312         /// other factors, such as other options, or target options.)
313         fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
314             match v {
315                 Some("y") | Some("yes") | Some("on") | None => { *slot = Some(true); true }
316                 Some("n") | Some("no") | Some("off") => { *slot = Some(false); true }
317                 _ => false,
318             }
319         }
320
321         /// Use this for any string option that has a static default.
322         fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
323             match v {
324                 Some(s) => { *slot = s.to_string(); true },
325                 None => false,
326             }
327         }
328
329         /// Use this for any string option that lacks a static default.
330         fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
331             match v {
332                 Some(s) => { *slot = Some(s.to_string()); true },
333                 None => false,
334             }
335         }
336
337         fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
338             match v {
339                 Some(s) => { *slot = Some(PathBuf::from(s)); true },
340                 None => false,
341             }
342         }
343
344         fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
345             match v {
346                 Some(s) => { slot.push(s.to_string()); true },
347                 None => false,
348             }
349         }
350
351         fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
352             match v {
353                 Some(s) => { slot.push(PathBuf::from(s)); true },
354                 None => false,
355             }
356         }
357
358         fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
359                       -> bool {
360             match v {
361                 Some(s) => {
362                     slot.extend(s.split_whitespace().map(|s| s.to_string()));
363                     true
364                 },
365                 None => false,
366             }
367         }
368
369         fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
370                       -> bool {
371             match v {
372                 Some(s) => {
373                     let v = s.split_whitespace().map(|s| s.to_string()).collect();
374                     *slot = Some(v);
375                     true
376                 },
377                 None => false,
378             }
379         }
380
381         fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
382                       -> bool {
383             match v {
384                 Some(s) => {
385                     let v = s.split(',').map(|s| s.to_string()).collect();
386                     *slot = Some(v);
387                     true
388                 },
389                 None => false,
390             }
391         }
392
393         fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool {
394             match v.and_then(|s| s.parse().ok()) {
395                 Some(0) => { *slot = ::num_cpus::get(); true },
396                 Some(i) => { *slot = i; true },
397                 None => false
398             }
399         }
400
401         /// Use this for any uint option that has a static default.
402         fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
403             match v.and_then(|s| s.parse().ok()) {
404                 Some(i) => { *slot = i; true },
405                 None => false
406             }
407         }
408
409         /// Use this for any uint option that lacks a static default.
410         fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
411             match v {
412                 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
413                 None => false
414             }
415         }
416
417         fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
418             match v {
419                 Some("all") => {
420                     *slot = Passes::All;
421                     true
422                 }
423                 v => {
424                     let mut passes = vec![];
425                     if parse_list(&mut passes, v) {
426                         *slot = Passes::Some(passes);
427                         true
428                     } else {
429                         false
430                     }
431                 }
432             }
433         }
434
435         fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
436             match v {
437                 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
438                 Some("abort") => *slot = Some(PanicStrategy::Abort),
439                 _ => return false
440             }
441             true
442         }
443
444         fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
445             match v {
446                 Some(s) => {
447                     match s.parse::<RelroLevel>() {
448                         Ok(level) => *slot = Some(level),
449                         _ => return false
450                     }
451                 },
452                 _ => return false
453             }
454             true
455         }
456
457         fn parse_sanitizer(slot: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
458             if let Some(Ok(s)) =  v.map(str::parse) {
459                 *slot = Some(s);
460                 true
461             } else {
462                 false
463             }
464         }
465
466         fn parse_sanitizer_list(slot: &mut Vec<Sanitizer>, v: Option<&str>) -> bool {
467             if let Some(v) = v {
468                 for s in v.split(',').map(str::parse) {
469                     if let Ok(s) = s {
470                         if !slot.contains(&s) {
471                             slot.push(s);
472                         }
473                     } else {
474                         return false;
475                     }
476                 }
477                 true
478             } else {
479                 false
480             }
481         }
482
483         fn parse_sanitizer_memory_track_origins(slot: &mut usize, v: Option<&str>) -> bool {
484             match v {
485                 Some("2") | None => { *slot = 2; true }
486                 Some("1") => { *slot = 1; true }
487                 Some("0") => { *slot = 0; true }
488                 Some(_) => false,
489             }
490         }
491
492         fn parse_cfguard(slot: &mut CFGuard, v: Option<&str>) -> bool {
493             match v {
494                 Some("disabled") => *slot = CFGuard::Disabled,
495                 Some("nochecks") => *slot = CFGuard::NoChecks,
496                 Some("checks") => *slot = CFGuard::Checks,
497                 _ => return false,
498             }
499             true
500         }
501
502         fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
503             match v.and_then(LinkerFlavor::from_str) {
504                 Some(lf) => *slote = Some(lf),
505                 _ => return false,
506             }
507             true
508         }
509
510         fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
511             match v {
512                 None => false,
513                 Some(s) => {
514                     let parts = s.split('=').collect::<Vec<_>>();
515                     if parts.len() != 2 { return false; }
516                     let crate_name = parts[0].to_string();
517                     let fuel = parts[1].parse::<u64>();
518                     if fuel.is_err() { return false; }
519                     *slot = Some((crate_name, fuel.unwrap()));
520                     true
521                 }
522             }
523         }
524
525         fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
526             match v {
527                 None => false,
528                 Some(s) if s.split('=').count() <= 2 => {
529                     *slot = Some(s.to_string());
530                     true
531                 }
532                 _ => false,
533             }
534         }
535
536         fn parse_treat_err_as_bug(slot: &mut Option<usize>, v: Option<&str>) -> bool {
537             match v {
538                 Some(s) => { *slot = s.parse().ok().filter(|&x| x != 0); slot.unwrap_or(0) != 0 }
539                 None => { *slot = Some(1); true }
540             }
541         }
542
543         fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
544             if v.is_some() {
545                 let mut bool_arg = None;
546                 if parse_opt_bool(&mut bool_arg, v) {
547                     *slot = if bool_arg.unwrap() {
548                         LtoCli::Yes
549                     } else {
550                         LtoCli::No
551                     };
552                     return true
553                 }
554             }
555
556             *slot = match v {
557                 None => LtoCli::NoParam,
558                 Some("thin") => LtoCli::Thin,
559                 Some("fat") => LtoCli::Fat,
560                 Some(_) => return false,
561             };
562             true
563         }
564
565         fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
566             if v.is_some() {
567                 let mut bool_arg = None;
568                 if parse_opt_bool(&mut bool_arg, v) {
569                     *slot = if bool_arg.unwrap() {
570                         LinkerPluginLto::LinkerPluginAuto
571                     } else {
572                         LinkerPluginLto::Disabled
573                     };
574                     return true
575                 }
576             }
577
578             *slot = match v {
579                 None => LinkerPluginLto::LinkerPluginAuto,
580                 Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
581             };
582             true
583         }
584
585         fn parse_switch_with_opt_path(slot: &mut SwitchWithOptPath, v: Option<&str>) -> bool {
586             *slot = match v {
587                 None => SwitchWithOptPath::Enabled(None),
588                 Some(path) => SwitchWithOptPath::Enabled(Some(PathBuf::from(path))),
589             };
590             true
591         }
592
593         fn parse_merge_functions(slot: &mut Option<MergeFunctions>, v: Option<&str>) -> bool {
594             match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
595                 Some(mergefunc) => *slot = Some(mergefunc),
596                 _ => return false,
597             }
598             true
599         }
600
601         fn parse_symbol_mangling_version(
602             slot: &mut SymbolManglingVersion,
603             v: Option<&str>,
604         ) -> bool {
605             *slot = match v {
606                 Some("legacy") => SymbolManglingVersion::Legacy,
607                 Some("v0") => SymbolManglingVersion::V0,
608                 _ => return false,
609             };
610             true
611         }
612
613         fn parse_src_file_hash(slot: &mut Option<SourceFileHashAlgorithm>, v: Option<&str>) -> bool {
614             match v.and_then(|s| SourceFileHashAlgorithm::from_str(s).ok()) {
615                 Some(hash_kind) => *slot = Some(hash_kind),
616                 _ => return false,
617             }
618             true
619         }
620     }
621 ) }
622
623 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
624           build_codegen_options, "C", "codegen",
625           CG_OPTIONS, cg_type_desc, cgsetters,
626
627     // This list is in alphabetical order.
628     //
629     // If you add a new option, please update:
630     // - src/librustc_interface/tests.rs
631     // - src/doc/rustc/src/codegen-options/index.md
632
633     ar: String = (String::new(), parse_string, [UNTRACKED],
634         "this option is deprecated and does nothing"),
635     bitcode_in_rlib: bool = (true, parse_bool, [TRACKED],
636         "emit bitcode in rlibs (default: yes)"),
637     code_model: Option<String> = (None, parse_opt_string, [TRACKED],
638         "choose the code model to use (`rustc --print code-models` for details)"),
639     codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
640         "divide crate into N units to optimize in parallel"),
641     debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
642         "explicitly enable the `cfg(debug_assertions)` directive"),
643     debuginfo: usize = (0, parse_uint, [TRACKED],
644         "debug info emission level (0 = no debug info, 1 = line tables only, \
645         2 = full debug info with variable and type information; default: 0)"),
646     default_linker_libraries: bool = (false, parse_bool, [UNTRACKED],
647         "allow the linker to link its default libraries (default: no)"),
648     extra_filename: String = (String::new(), parse_string, [UNTRACKED],
649         "extra data to put in each output filename"),
650     force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
651         "force use of the frame pointers"),
652     incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
653         "enable incremental compilation"),
654     inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
655         "set the threshold for inlining a function"),
656     link_arg: (/* redirected to link_args */) = ((), parse_string_push, [UNTRACKED],
657         "a single extra argument to append to the linker invocation (can be used several times)"),
658     link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
659         "extra arguments to append to the linker invocation (space separated)"),
660     link_dead_code: bool = (false, parse_bool, [UNTRACKED],
661         "keep dead code at link time (useful for code coverage) (default: no)"),
662     linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
663         "system linker to link outputs with"),
664     linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
665         "linker flavor"),
666     linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
667         parse_linker_plugin_lto, [TRACKED],
668         "generate build artifacts that are compatible with linker-based LTO"),
669     llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
670         "a list of arguments to pass to LLVM (space separated)"),
671     lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
672         "perform LLVM link-time optimizations"),
673     metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
674         "metadata to mangle symbol names with"),
675     no_prepopulate_passes: bool = (false, parse_no_flag, [TRACKED],
676         "give an empty list of passes to the pass manager"),
677     no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
678         "disable the use of the redzone"),
679     no_stack_check: bool = (false, parse_no_flag, [UNTRACKED],
680         "this option is deprecated and does nothing"),
681     no_vectorize_loops: bool = (false, parse_no_flag, [TRACKED],
682         "disable loop vectorization optimization passes"),
683     no_vectorize_slp: bool = (false, parse_no_flag, [TRACKED],
684         "disable LLVM's SLP vectorization pass"),
685     opt_level: String = ("0".to_string(), parse_string, [TRACKED],
686         "optimization level (0-3, s, or z; default: 0)"),
687     overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
688         "use overflow checks for integer arithmetic"),
689     panic: Option<PanicStrategy> = (None, parse_panic_strategy, [TRACKED],
690         "panic strategy to compile crate with"),
691     passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
692         "a list of extra LLVM passes to run (space separated)"),
693     prefer_dynamic: bool = (false, parse_bool, [TRACKED],
694         "prefer dynamic linking to static linking (default: no)"),
695     profile_generate: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
696         parse_switch_with_opt_path, [TRACKED],
697         "compile the program with profiling instrumentation"),
698     profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
699         "use the given `.profdata` file for profile-guided optimization"),
700     relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
701         "choose the relocation model to use (`rustc --print relocation-models` for details)"),
702     remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
703         "print remarks for these optimization passes (space separated, or \"all\")"),
704     rpath: bool = (false, parse_bool, [UNTRACKED],
705         "set rpath values in libs/exes (default: no)"),
706     save_temps: bool = (false, parse_bool, [UNTRACKED],
707         "save all temporary output files during compilation (default: no)"),
708     soft_float: bool = (false, parse_bool, [TRACKED],
709         "use soft float ABI (*eabihf targets only) (default: no)"),
710     target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
711         "select target processor (`rustc --print target-cpus` for details)"),
712     target_feature: String = (String::new(), parse_string, [TRACKED],
713         "target specific attributes. (`rustc --print target-features` for details). \
714         This feature is unsafe."),
715
716     // This list is in alphabetical order.
717     //
718     // If you add a new option, please update:
719     // - src/librustc_interface/tests.rs
720     // - src/doc/rustc/src/codegen-options/index.md
721 }
722
723 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
724           build_debugging_options, "Z", "debugging",
725           DB_OPTIONS, db_type_desc, dbsetters,
726
727     // This list is in alphabetical order.
728     //
729     // If you add a new option, please update:
730     // - src/librustc_interface/tests.rs
731
732     allow_features: Option<Vec<String>> = (None, parse_opt_comma_list, [TRACKED],
733         "only allow the listed language features to be enabled in code (space separated)"),
734     always_encode_mir: bool = (false, parse_bool, [TRACKED],
735         "encode MIR of all functions into the crate metadata (default: no)"),
736     asm_comments: bool = (false, parse_bool, [TRACKED],
737         "generate comments into the assembly (may change behavior) (default: no)"),
738     ast_json: bool = (false, parse_bool, [UNTRACKED],
739         "print the AST as JSON and halt (default: no)"),
740     ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
741         "print the pre-expansion AST as JSON and halt (default: no)"),
742     binary_dep_depinfo: bool = (false, parse_bool, [TRACKED],
743         "include artifacts (sysroot, crate dependencies) used during compilation in dep-info \
744         (default: no)"),
745     borrowck: String = ("migrate".to_string(), parse_string, [UNTRACKED],
746         "select which borrowck is used (`mir` or `migrate`) (default: `migrate`)"),
747     borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
748         "gather borrowck statistics (default: no)"),
749     codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
750         "the backend to use"),
751     control_flow_guard: CFGuard = (CFGuard::Disabled, parse_cfguard, [UNTRACKED],
752         "use Windows Control Flow Guard (`disabled`, `nochecks` or `checks`)"),
753     crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
754         "inject the given attribute in the crate"),
755     debug_macros: bool = (false, parse_bool, [TRACKED],
756         "emit line numbers debug info inside macros (default: no)"),
757     deduplicate_diagnostics: bool = (true, parse_bool, [UNTRACKED],
758         "deduplicate identical diagnostics (default: yes)"),
759     dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
760         "in dep-info output, omit targets for tracking dependencies of the dep-info files \
761         themselves (default: no)"),
762     dep_tasks: bool = (false, parse_bool, [UNTRACKED],
763         "print tasks that execute and the color their dep node gets (requires debug build) \
764         (default: no)"),
765     dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
766         "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting) \
767         (default: no)"),
768     dual_proc_macros: bool = (false, parse_bool, [TRACKED],
769         "load proc macros for both target and host, but only link to the target (default: no)"),
770     dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
771         "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv) \
772         (default: no)"),
773     dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
774         "dump MIR state to file.
775         `val` is used to select which passes and functions to dump. For example:
776         `all` matches all passes and functions,
777         `foo` matches all passes for functions whose name contains 'foo',
778         `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
779         `foo | bar` all passes for function names containing 'foo' or 'bar'."),
780     dump_mir_dataflow: bool = (false, parse_bool, [UNTRACKED],
781         "in addition to `.mir` files, create graphviz `.dot` files with dataflow results \
782         (default: no)"),
783     dump_mir_dir: String = ("mir_dump".to_string(), parse_string, [UNTRACKED],
784         "the directory the MIR is dumped into (default: `mir_dump`)"),
785     dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
786         "exclude the pass number when dumping MIR (used in tests) (default: no)"),
787     dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
788         "in addition to `.mir` files, create graphviz `.dot` files (default: no)"),
789     embed_bitcode: bool = (false, parse_bool, [TRACKED],
790         "embed LLVM bitcode in object files (default: no)"),
791     emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
792         "emit a section containing stack size metadata (default: no)"),
793     fewer_names: bool = (false, parse_bool, [TRACKED],
794         "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR) \
795         (default: no)"),
796     force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
797         "force overflow checks on or off"),
798     force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
799         "force all crates to be `rustc_private` unstable (default: no)"),
800     fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
801         "set the optimization fuel quota for a crate"),
802     hir_stats: bool = (false, parse_bool, [UNTRACKED],
803         "print some statistics about AST and HIR (default: no)"),
804     human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
805         "generate human-readable, predictable names for codegen units (default: no)"),
806     identify_regions: bool = (false, parse_bool, [UNTRACKED],
807         "display unnamed regions as `'<id>`, using a non-ident unique id (default: no)"),
808     incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
809         "ignore spans during ICH computation -- used for testing (default: no)"),
810     incremental_info: bool = (false, parse_bool, [UNTRACKED],
811         "print high-level information about incremental reuse (or the lack thereof) \
812         (default: no)"),
813     incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
814         "verify incr. comp. hashes of green query instances (default: no)"),
815     inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
816         "control whether `#[inline]` functions are in all CGUs"),
817     input_stats: bool = (false, parse_bool, [UNTRACKED],
818         "gather statistics about the input (default: no)"),
819     insert_sideeffect: bool = (false, parse_bool, [TRACKED],
820         "fix undefined behavior when a thread doesn't eventually make progress \
821         (such as entering an empty infinite loop) by inserting llvm.sideeffect \
822         (default: no)"),
823     instrument_mcount: bool = (false, parse_bool, [TRACKED],
824         "insert function instrument code for mcount-based tracing (default: no)"),
825     keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
826         "keep hygiene data after analysis (default: no)"),
827     link_native_libraries: bool = (true, parse_bool, [UNTRACKED],
828         "link native libraries in the linker invocation (default: yes)"),
829     link_only: bool = (false, parse_bool, [TRACKED],
830         "link the `.rlink` file generated by `-Z no-link` (default: no)"),
831     llvm_time_trace: bool = (false, parse_bool, [UNTRACKED],
832         "generate JSON tracing data file from LLVM data (default: no)"),
833     ls: bool = (false, parse_bool, [UNTRACKED],
834         "list the symbols defined by a library crate (default: no)"),
835     macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
836         "show macro backtraces (default: no)"),
837     merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
838         "control the operation of the MergeFunctions LLVM pass, taking \
839         the same values as the target option of the same name"),
840     meta_stats: bool = (false, parse_bool, [UNTRACKED],
841         "gather metadata statistics (default: no)"),
842     mir_emit_retag: bool = (false, parse_bool, [TRACKED],
843         "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
844         (default: no)"),
845     mir_opt_level: usize = (1, parse_uint, [TRACKED],
846         "MIR optimization level (0-3; default: 1)"),
847     mutable_noalias: bool = (false, parse_bool, [TRACKED],
848         "emit noalias metadata for mutable references (default: no)"),
849     new_llvm_pass_manager: bool = (false, parse_bool, [TRACKED],
850         "use new LLVM pass manager (default: no)"),
851     nll_facts: bool = (false, parse_bool, [UNTRACKED],
852         "dump facts from NLL analysis into side files (default: no)"),
853     no_analysis: bool = (false, parse_no_flag, [UNTRACKED],
854         "parse and expand the source, but run no analysis"),
855     no_codegen: bool = (false, parse_no_flag, [TRACKED],
856         "run all passes except codegen; no output"),
857     no_generate_arange_section: bool = (false, parse_no_flag, [TRACKED],
858         "omit DWARF address ranges that give faster lookups"),
859     no_interleave_lints: bool = (false, parse_no_flag, [UNTRACKED],
860         "execute lints separately; allows benchmarking individual lints"),
861     no_landing_pads: bool = (false, parse_no_flag, [TRACKED],
862         "omit landing pads for unwinding"),
863     no_leak_check: bool = (false, parse_no_flag, [UNTRACKED],
864         "disable the 'leak check' for subtyping; unsound, but useful for tests"),
865     no_link: bool = (false, parse_no_flag, [TRACKED],
866         "compile without linking"),
867     no_parallel_llvm: bool = (false, parse_no_flag, [UNTRACKED],
868         "run LLVM in non-parallel mode (while keeping codegen-units and ThinLTO)"),
869     no_profiler_runtime: bool = (false, parse_no_flag, [TRACKED],
870         "prevent automatic injection of the profiler_builtins crate"),
871     osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
872         "pass `-install_name @rpath/...` to the macOS linker (default: no)"),
873     panic_abort_tests: bool = (false, parse_bool, [TRACKED],
874         "support compiling tests with panic=abort (default: no)"),
875     parse_only: bool = (false, parse_bool, [UNTRACKED],
876         "parse only; do not compile, assemble, or link (default: no)"),
877     perf_stats: bool = (false, parse_bool, [UNTRACKED],
878         "print some performance-related statistics (default: no)"),
879     plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
880         "whether to use the PLT when calling into shared libraries;
881         only has effect for PIC code on systems with ELF binaries
882         (default: PLT is disabled if full relro is enabled)"),
883     polonius: bool = (false, parse_bool, [UNTRACKED],
884         "enable polonius-based borrow-checker (default: no)"),
885     pre_link_arg: (/* redirected to pre_link_args */) = ((), parse_string_push, [UNTRACKED],
886         "a single extra argument to prepend the linker invocation (can be used several times)"),
887     pre_link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
888         "extra arguments to prepend to the linker invocation (space separated)"),
889     print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
890         "make rustc print the total optimization fuel used by a crate"),
891     print_link_args: bool = (false, parse_bool, [UNTRACKED],
892         "print the arguments passed to the linker (default: no)"),
893     print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
894         "print the LLVM optimization passes being run (default: no)"),
895     print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
896         "print the result of the monomorphization collection pass"),
897     print_region_graph: bool = (false, parse_bool, [UNTRACKED],
898         "prints region inference graph. \
899         Use with RUST_REGION_GRAPH=help for more info (default: no)"),
900     print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
901         "print layout information for each type encountered (default: no)"),
902     profile: bool = (false, parse_bool, [TRACKED],
903         "insert profiling code (default: no)"),
904     query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
905         "enable queries of the dependency graph for regression testing (default: no)"),
906     query_stats: bool = (false, parse_bool, [UNTRACKED],
907         "print some statistics about the query system (default: no)"),
908     relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
909         "choose which RELRO level to use"),
910     report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
911         "immediately print bugs registered with `delay_span_bug` (default: no)"),
912     // The default historical behavior was to always run dsymutil, so we're
913     // preserving that temporarily, but we're likely to switch the default
914     // soon.
915     run_dsymutil: bool = (true, parse_bool, [TRACKED],
916         "if on Mac, run `dsymutil` and delete intermediate object files (default: yes)"),
917     sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
918         "use a sanitizer"),
919     sanitizer_memory_track_origins: usize = (0, parse_sanitizer_memory_track_origins, [TRACKED],
920         "enable origins tracking in MemorySanitizer"),
921     sanitizer_recover: Vec<Sanitizer> = (vec![], parse_sanitizer_list, [TRACKED],
922         "enable recovery for selected sanitizers"),
923     saturating_float_casts: bool = (false, parse_bool, [TRACKED],
924         "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
925         the max/min integer respectively, and NaN is mapped to 0 (default: no)"),
926     save_analysis: bool = (false, parse_bool, [UNTRACKED],
927         "write syntax and type analysis (in JSON format) information, in \
928         addition to normal output (default: no)"),
929     self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
930         parse_switch_with_opt_path, [UNTRACKED],
931         "run the self profiler and output the raw event data"),
932     // keep this in sync with the event filter names in librustc_data_structures/profiling.rs
933     self_profile_events: Option<Vec<String>> = (None, parse_opt_comma_list, [UNTRACKED],
934         "specify the events recorded by the self profiler;
935         for example: `-Z self-profile-events=default,query-keys`
936         all options: none, all, default, generic-activity, query-provider, query-cache-hit
937                      query-blocked, incr-cache-load, query-keys, function-args, args, llvm"),
938     share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
939         "make the current crate share its generic instantiations"),
940     show_span: Option<String> = (None, parse_opt_string, [TRACKED],
941         "show spans for compiler debugging (expr|pat|ty)"),
942     // o/w tests have closure@path
943     span_free_formats: bool = (false, parse_bool, [UNTRACKED],
944         "exclude spans when debug-printing compiler state (default: no)"),
945     src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
946         "hash algorithm of source files in debug info (`md5`, or `sha1`)"),
947     strip_debuginfo_if_disabled: bool = (false, parse_bool, [TRACKED],
948         "tell the linker to strip debuginfo when building without debuginfo enabled \
949         (default: no)"),
950     symbol_mangling_version: SymbolManglingVersion = (SymbolManglingVersion::Legacy,
951         parse_symbol_mangling_version, [TRACKED],
952         "which mangling version to use for symbol names"),
953     teach: bool = (false, parse_bool, [TRACKED],
954         "show extended diagnostic help (default: no)"),
955     terminal_width: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
956         "set the current terminal width"),
957     thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
958         "enable ThinLTO when possible"),
959     // We default to 1 here since we want to behave like
960     // a sequential compiler for now. This'll likely be adjusted
961     // in the future. Note that -Zthreads=0 is the way to get
962     // the num_cpus behavior.
963     threads: usize = (1, parse_threads, [UNTRACKED],
964         "use a thread pool with N threads"),
965     time: bool = (false, parse_bool, [UNTRACKED],
966         "measure time of rustc processes (default: no)"),
967     time_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
968         "measure time of each LLVM pass (default: no)"),
969     time_passes: bool = (false, parse_bool, [UNTRACKED],
970         "measure time of each rustc pass (default: no)"),
971     tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
972         "choose the TLS model to use (`rustc --print tls-models` for details)"),
973     trace_macros: bool = (false, parse_bool, [UNTRACKED],
974         "for every macro invocation, print its name and arguments (default: no)"),
975     treat_err_as_bug: Option<usize> = (None, parse_treat_err_as_bug, [TRACKED],
976         "treat error number `val` that occurs as bug"),
977     ui_testing: bool = (false, parse_bool, [UNTRACKED],
978         "emit compiler diagnostics in a form suitable for UI testing (default: no)"),
979     unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
980         "take the brakes off const evaluation. NOTE: this is unsound (default: no)"),
981     unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
982         "present the input source, unstable (and less-pretty) variants;
983         valid types are any of the types for `--pretty`, as well as:
984         `expanded`, `expanded,identified`,
985         `expanded,hygiene` (with internal representations),
986         `everybody_loops` (all function bodies replaced with `loop {}`),
987         `hir` (the HIR), `hir,identified`,
988         `hir,typed` (HIR with types for each node),
989         `hir-tree` (dump the raw HIR),
990         `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
991     unstable_options: bool = (false, parse_bool, [UNTRACKED],
992         "adds unstable command line options to rustc interface (default: no)"),
993     verbose: bool = (false, parse_bool, [UNTRACKED],
994         "in general, enable more debug printouts (default: no)"),
995     verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
996         "verify LLVM IR (default: no)"),
997
998     // This list is in alphabetical order.
999     //
1000     // If you add a new option, please update:
1001     // - src/librustc_interface/tests.rs
1002 }