rustc_session/
session.rs

1use std::any::Any;
2use std::ops::{Div, Mul};
3use std::path::{Path, PathBuf};
4use std::str::FromStr;
5use std::sync::Arc;
6use std::sync::atomic::AtomicBool;
7use std::{env, fmt, io};
8
9use rand::{RngCore, rng};
10use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
11use rustc_data_structures::flock;
12use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
13use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
14use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
15use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
16use rustc_errors::codes::*;
17use rustc_errors::emitter::{
18    DynEmitter, HumanEmitter, HumanReadableErrorType, OutputTheme, stderr_destination,
19};
20use rustc_errors::json::JsonEmitter;
21use rustc_errors::timings::TimingSectionHandler;
22use rustc_errors::translation::Translator;
23use rustc_errors::{
24    Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
25    TerminalUrl, fallback_fluent_bundle,
26};
27use rustc_macros::HashStable_Generic;
28pub use rustc_span::def_id::StableCrateId;
29use rustc_span::edition::Edition;
30use rustc_span::source_map::{FilePathMapping, SourceMap};
31use rustc_span::{FileNameDisplayPreference, RealFileName, Span, Symbol};
32use rustc_target::asm::InlineAsmArch;
33use rustc_target::spec::{
34    CodeModel, DebuginfoKind, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
35    SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
36    TargetTuple, TlsModel, apple,
37};
38
39use crate::code_stats::CodeStats;
40pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
41use crate::config::{
42    self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
43    Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents,
44    SwitchWithOptPath,
45};
46use crate::filesearch::FileSearch;
47use crate::lint::LintId;
48use crate::parse::{ParseSess, add_feature_diagnostics};
49use crate::search_paths::SearchPath;
50use crate::{errors, filesearch, lint};
51
52/// The behavior of the CTFE engine when an error occurs with regards to backtraces.
53#[derive(Clone, Copy)]
54pub enum CtfeBacktrace {
55    /// Do nothing special, return the error as usual without a backtrace.
56    Disabled,
57    /// Capture a backtrace at the point the error is created and return it in the error
58    /// (to be printed later if/when the error ever actually gets shown to the user).
59    Capture,
60    /// Capture a backtrace at the point the error is created and immediately print it out.
61    Immediate,
62}
63
64/// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
65/// limits are consistent throughout the compiler.
66#[derive(Clone, Copy, Debug, HashStable_Generic)]
67pub struct Limit(pub usize);
68
69impl Limit {
70    /// Create a new limit from a `usize`.
71    pub fn new(value: usize) -> Self {
72        Limit(value)
73    }
74
75    /// Create a new unlimited limit.
76    pub fn unlimited() -> Self {
77        Limit(usize::MAX)
78    }
79
80    /// Check that `value` is within the limit. Ensures that the same comparisons are used
81    /// throughout the compiler, as mismatches can cause ICEs, see #72540.
82    #[inline]
83    pub fn value_within_limit(&self, value: usize) -> bool {
84        value <= self.0
85    }
86}
87
88impl From<usize> for Limit {
89    fn from(value: usize) -> Self {
90        Self::new(value)
91    }
92}
93
94impl fmt::Display for Limit {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        self.0.fmt(f)
97    }
98}
99
100impl Div<usize> for Limit {
101    type Output = Limit;
102
103    fn div(self, rhs: usize) -> Self::Output {
104        Limit::new(self.0 / rhs)
105    }
106}
107
108impl Mul<usize> for Limit {
109    type Output = Limit;
110
111    fn mul(self, rhs: usize) -> Self::Output {
112        Limit::new(self.0 * rhs)
113    }
114}
115
116impl rustc_errors::IntoDiagArg for Limit {
117    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
118        self.to_string().into_diag_arg(&mut None)
119    }
120}
121
122#[derive(Clone, Copy, Debug, HashStable_Generic)]
123pub struct Limits {
124    /// The maximum recursion limit for potentially infinitely recursive
125    /// operations such as auto-dereference and monomorphization.
126    pub recursion_limit: Limit,
127    /// The size at which the `large_assignments` lint starts
128    /// being emitted.
129    pub move_size_limit: Limit,
130    /// The maximum length of types during monomorphization.
131    pub type_length_limit: Limit,
132    /// The maximum pattern complexity allowed (internal only).
133    pub pattern_complexity_limit: Limit,
134}
135
136pub struct CompilerIO {
137    pub input: Input,
138    pub output_dir: Option<PathBuf>,
139    pub output_file: Option<OutFileName>,
140    pub temps_dir: Option<PathBuf>,
141}
142
143pub trait DynLintStore: Any + DynSync + DynSend {
144    /// Provides a way to access lint groups without depending on `rustc_lint`
145    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
146}
147
148/// Represents the data associated with a compilation
149/// session for a single crate.
150pub struct Session {
151    pub target: Target,
152    pub host: Target,
153    pub opts: config::Options,
154    pub target_tlib_path: Arc<SearchPath>,
155    pub psess: ParseSess,
156    /// Input, input file path and output file path to this compilation process.
157    pub io: CompilerIO,
158
159    incr_comp_session: RwLock<IncrCompSession>,
160
161    /// Used by `-Z self-profile`.
162    pub prof: SelfProfilerRef,
163
164    /// Used to emit section timings events (enabled by `--json=timings`).
165    pub timings: TimingSectionHandler,
166
167    /// Data about code being compiled, gathered during compilation.
168    pub code_stats: CodeStats,
169
170    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
171    pub lint_store: Option<Arc<dyn DynLintStore>>,
172
173    /// Cap lint level specified by a driver specifically.
174    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
175
176    /// Tracks the current behavior of the CTFE engine when an error occurs.
177    /// Options range from returning the error without a backtrace to returning an error
178    /// and immediately printing the backtrace to stderr.
179    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
180    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
181    /// errors.
182    pub ctfe_backtrace: Lock<CtfeBacktrace>,
183
184    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
185    /// const check, optionally with the relevant feature gate. We use this to
186    /// warn about unleashing, but with a single diagnostic instead of dozens that
187    /// drown everything else in noise.
188    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
189
190    /// Architecture to use for interpreting asm!.
191    pub asm_arch: Option<InlineAsmArch>,
192
193    /// Set of enabled features for the current target.
194    pub target_features: FxIndexSet<Symbol>,
195
196    /// Set of enabled features for the current target, including unstable ones.
197    pub unstable_target_features: FxIndexSet<Symbol>,
198
199    /// The version of the rustc process, possibly including a commit hash and description.
200    pub cfg_version: &'static str,
201
202    /// The inner atomic value is set to true when a feature marked as `internal` is
203    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
204    /// internal features are wontfix, and they are usually the cause of the ICEs.
205    /// None signifies that this is not tracked.
206    pub using_internal_features: &'static AtomicBool,
207
208    /// All commandline args used to invoke the compiler, with @file args fully expanded.
209    /// This will only be used within debug info, e.g. in the pdb file on windows
210    /// This is mainly useful for other tools that reads that debuginfo to figure out
211    /// how to call the compiler with the same arguments.
212    pub expanded_args: Vec<String>,
213
214    target_filesearch: FileSearch,
215    host_filesearch: FileSearch,
216
217    /// A random string generated per invocation of rustc.
218    ///
219    /// This is prepended to all temporary files so that they do not collide
220    /// during concurrent invocations of rustc, or past invocations that were
221    /// preserved with a flag like `-C save-temps`, since these files may be
222    /// hard linked.
223    pub invocation_temp: Option<String>,
224}
225
226#[derive(Clone, Copy)]
227pub enum CodegenUnits {
228    /// Specified by the user. In this case we try fairly hard to produce the
229    /// number of CGUs requested.
230    User(usize),
231
232    /// A default value, i.e. not specified by the user. In this case we take
233    /// more liberties about CGU formation, e.g. avoid producing very small
234    /// CGUs.
235    Default(usize),
236}
237
238impl CodegenUnits {
239    pub fn as_usize(self) -> usize {
240        match self {
241            CodegenUnits::User(n) => n,
242            CodegenUnits::Default(n) => n,
243        }
244    }
245}
246
247pub struct LintGroup {
248    pub name: &'static str,
249    pub lints: Vec<LintId>,
250    pub is_externally_loaded: bool,
251}
252
253impl Session {
254    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
255        self.miri_unleashed_features.lock().push((span, feature_gate));
256    }
257
258    pub fn local_crate_source_file(&self) -> Option<RealFileName> {
259        Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
260    }
261
262    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
263        let mut guar = None;
264        let unleashed_features = self.miri_unleashed_features.lock();
265        if !unleashed_features.is_empty() {
266            let mut must_err = false;
267            // Create a diagnostic pointing at where things got unleashed.
268            self.dcx().emit_warn(errors::SkippingConstChecks {
269                unleashed_features: unleashed_features
270                    .iter()
271                    .map(|(span, gate)| {
272                        gate.map(|gate| {
273                            must_err = true;
274                            errors::UnleashedFeatureHelp::Named { span: *span, gate }
275                        })
276                        .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
277                    })
278                    .collect(),
279            });
280
281            // If we should err, make sure we did.
282            if must_err && self.dcx().has_errors().is_none() {
283                // We have skipped a feature gate, and not run into other errors... reject.
284                guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
285            }
286        }
287        guar
288    }
289
290    /// Invoked all the way at the end to finish off diagnostics printing.
291    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
292        let mut guar = None;
293        guar = guar.or(self.check_miri_unleashed_features());
294        guar = guar.or(self.dcx().emit_stashed_diagnostics());
295        self.dcx().print_error_count();
296        if self.opts.json_future_incompat {
297            self.dcx().emit_future_breakage_report();
298        }
299        guar
300    }
301
302    /// Returns true if the crate is a testing one.
303    pub fn is_test_crate(&self) -> bool {
304        self.opts.test
305    }
306
307    /// `feature` must be a language feature.
308    #[track_caller]
309    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
310        let mut err = self.dcx().create_err(err);
311        if err.code.is_none() {
312            #[allow(rustc::diagnostic_outside_of_impl)]
313            err.code(E0658);
314        }
315        add_feature_diagnostics(&mut err, self, feature);
316        err
317    }
318
319    /// Record the fact that we called `trimmed_def_paths`, and do some
320    /// checking about whether its cost was justified.
321    pub fn record_trimmed_def_paths(&self) {
322        if self.opts.unstable_opts.print_type_sizes
323            || self.opts.unstable_opts.query_dep_graph
324            || self.opts.unstable_opts.dump_mir.is_some()
325            || self.opts.unstable_opts.unpretty.is_some()
326            || self.prof.is_args_recording_enabled()
327            || self.opts.output_types.contains_key(&OutputType::Mir)
328            || std::env::var_os("RUSTC_LOG").is_some()
329        {
330            return;
331        }
332
333        self.dcx().set_must_produce_diag()
334    }
335
336    #[inline]
337    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
338        self.psess.dcx()
339    }
340
341    #[inline]
342    pub fn source_map(&self) -> &SourceMap {
343        self.psess.source_map()
344    }
345
346    /// Returns `true` if internal lints should be added to the lint store - i.e. if
347    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
348    /// to be emitted under rustdoc).
349    pub fn enable_internal_lints(&self) -> bool {
350        self.unstable_options() && !self.opts.actually_rustdoc
351    }
352
353    pub fn instrument_coverage(&self) -> bool {
354        self.opts.cg.instrument_coverage() != InstrumentCoverage::No
355    }
356
357    pub fn instrument_coverage_branch(&self) -> bool {
358        self.instrument_coverage()
359            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
360    }
361
362    pub fn instrument_coverage_condition(&self) -> bool {
363        self.instrument_coverage()
364            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
365    }
366
367    /// Provides direct access to the `CoverageOptions` struct, so that
368    /// individual flags for debugging/testing coverage instrumetation don't
369    /// need separate accessors.
370    pub fn coverage_options(&self) -> &CoverageOptions {
371        &self.opts.unstable_opts.coverage_options
372    }
373
374    pub fn is_sanitizer_cfi_enabled(&self) -> bool {
375        self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
376    }
377
378    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
379        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
380    }
381
382    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
383        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
384    }
385
386    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
387        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
388    }
389
390    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
391        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
392    }
393
394    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
395        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
396    }
397
398    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
399        self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
400    }
401
402    pub fn is_split_lto_unit_enabled(&self) -> bool {
403        self.opts.unstable_opts.split_lto_unit == Some(true)
404    }
405
406    /// Check whether this compile session and crate type use static crt.
407    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
408        if !self.target.crt_static_respected {
409            // If the target does not opt in to crt-static support, use its default.
410            return self.target.crt_static_default;
411        }
412
413        let requested_features = self.opts.cg.target_feature.split(',');
414        let found_negative = requested_features.clone().any(|r| r == "-crt-static");
415        let found_positive = requested_features.clone().any(|r| r == "+crt-static");
416
417        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
418        #[allow(rustc::bad_opt_access)]
419        if found_positive || found_negative {
420            found_positive
421        } else if crate_type == Some(CrateType::ProcMacro)
422            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
423        {
424            // FIXME: When crate_type is not available,
425            // we use compiler options to determine the crate_type.
426            // We can't check `#![crate_type = "proc-macro"]` here.
427            false
428        } else {
429            self.target.crt_static_default
430        }
431    }
432
433    pub fn is_wasi_reactor(&self) -> bool {
434        self.target.options.os == "wasi"
435            && matches!(
436                self.opts.unstable_opts.wasi_exec_model,
437                Some(config::WasiExecModel::Reactor)
438            )
439    }
440
441    /// Returns `true` if the target can use the current split debuginfo configuration.
442    pub fn target_can_use_split_dwarf(&self) -> bool {
443        self.target.debuginfo_kind == DebuginfoKind::Dwarf
444    }
445
446    pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
447        format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
448    }
449
450    pub fn target_filesearch(&self) -> &filesearch::FileSearch {
451        &self.target_filesearch
452    }
453    pub fn host_filesearch(&self) -> &filesearch::FileSearch {
454        &self.host_filesearch
455    }
456
457    /// Returns a list of directories where target-specific tool binaries are located. Some fallback
458    /// directories are also returned, for example if `--sysroot` is used but tools are missing
459    /// (#125246): we also add the bin directories to the sysroot where rustc is located.
460    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
461        let search_paths = self
462            .opts
463            .sysroot
464            .all_paths()
465            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
466
467        if self_contained {
468            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the
469            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the
470            // fallback paths.
471            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
472        } else {
473            search_paths.collect()
474        }
475    }
476
477    pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
478        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
479
480        if let IncrCompSession::NotInitialized = *incr_comp_session {
481        } else {
482            panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
483        }
484
485        *incr_comp_session =
486            IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
487    }
488
489    pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
490        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
491
492        if let IncrCompSession::Active { .. } = *incr_comp_session {
493        } else {
494            panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
495        }
496
497        // Note: this will also drop the lock file, thus unlocking the directory.
498        *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
499    }
500
501    pub fn mark_incr_comp_session_as_invalid(&self) {
502        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
503
504        let session_directory = match *incr_comp_session {
505            IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
506            IncrCompSession::InvalidBecauseOfErrors { .. } => return,
507            _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
508        };
509
510        // Note: this will also drop the lock file, thus unlocking the directory.
511        *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
512    }
513
514    pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
515        let incr_comp_session = self.incr_comp_session.borrow();
516        ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
517            IncrCompSession::NotInitialized => panic!(
518                "trying to get session directory from `IncrCompSession`: {:?}",
519                *incr_comp_session,
520            ),
521            IncrCompSession::Active { ref session_directory, .. }
522            | IncrCompSession::Finalized { ref session_directory }
523            | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
524                session_directory
525            }
526        })
527    }
528
529    pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
530        self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
531    }
532
533    /// Is this edition 2015?
534    pub fn is_rust_2015(&self) -> bool {
535        self.edition().is_rust_2015()
536    }
537
538    /// Are we allowed to use features from the Rust 2018 edition?
539    pub fn at_least_rust_2018(&self) -> bool {
540        self.edition().at_least_rust_2018()
541    }
542
543    /// Are we allowed to use features from the Rust 2021 edition?
544    pub fn at_least_rust_2021(&self) -> bool {
545        self.edition().at_least_rust_2021()
546    }
547
548    /// Are we allowed to use features from the Rust 2024 edition?
549    pub fn at_least_rust_2024(&self) -> bool {
550        self.edition().at_least_rust_2024()
551    }
552
553    /// Returns `true` if we should use the PLT for shared library calls.
554    pub fn needs_plt(&self) -> bool {
555        // Check if the current target usually wants PLT to be enabled.
556        // The user can use the command line flag to override it.
557        let want_plt = self.target.plt_by_default;
558
559        let dbg_opts = &self.opts.unstable_opts;
560
561        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
562
563        // Only enable this optimization by default if full relro is also enabled.
564        // In this case, lazy binding was already unavailable, so nothing is lost.
565        // This also ensures `-Wl,-z,now` is supported by the linker.
566        let full_relro = RelroLevel::Full == relro_level;
567
568        // If user didn't explicitly forced us to use / skip the PLT,
569        // then use it unless the target doesn't want it by default or the full relro forces it on.
570        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
571    }
572
573    /// Checks if LLVM lifetime markers should be emitted.
574    pub fn emit_lifetime_markers(&self) -> bool {
575        self.opts.optimize != config::OptLevel::No
576        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
577        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
578        // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
579        || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
580    }
581
582    pub fn diagnostic_width(&self) -> usize {
583        let default_column_width = 140;
584        if let Some(width) = self.opts.diagnostic_width {
585            width
586        } else if self.opts.unstable_opts.ui_testing {
587            default_column_width
588        } else {
589            termize::dimensions().map_or(default_column_width, |(w, _)| w)
590        }
591    }
592
593    /// Returns the default symbol visibility.
594    pub fn default_visibility(&self) -> SymbolVisibility {
595        self.opts
596            .unstable_opts
597            .default_visibility
598            .or(self.target.options.default_visibility)
599            .unwrap_or(SymbolVisibility::Interposable)
600    }
601
602    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
603        if verbatim {
604            ("", "")
605        } else {
606            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
607        }
608    }
609
610    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
611        match self.lint_store {
612            Some(ref lint_store) => lint_store.lint_groups_iter(),
613            None => Box::new(std::iter::empty()),
614        }
615    }
616}
617
618// JUSTIFICATION: defn of the suggested wrapper fns
619#[allow(rustc::bad_opt_access)]
620impl Session {
621    pub fn verbose_internals(&self) -> bool {
622        self.opts.unstable_opts.verbose_internals
623    }
624
625    pub fn print_llvm_stats(&self) -> bool {
626        self.opts.unstable_opts.print_codegen_stats
627    }
628
629    pub fn verify_llvm_ir(&self) -> bool {
630        self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
631    }
632
633    pub fn binary_dep_depinfo(&self) -> bool {
634        self.opts.unstable_opts.binary_dep_depinfo
635    }
636
637    pub fn mir_opt_level(&self) -> usize {
638        self.opts
639            .unstable_opts
640            .mir_opt_level
641            .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
642    }
643
644    /// Calculates the flavor of LTO to use for this compilation.
645    pub fn lto(&self) -> config::Lto {
646        // If our target has codegen requirements ignore the command line
647        if self.target.requires_lto {
648            return config::Lto::Fat;
649        }
650
651        // If the user specified something, return that. If they only said `-C
652        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
653        // then ensure we can't use a ThinLTO.
654        match self.opts.cg.lto {
655            config::LtoCli::Unspecified => {
656                // The compiler was invoked without the `-Clto` flag. Fall
657                // through to the default handling
658            }
659            config::LtoCli::No => {
660                // The user explicitly opted out of any kind of LTO
661                return config::Lto::No;
662            }
663            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
664                // All of these mean fat LTO
665                return config::Lto::Fat;
666            }
667            config::LtoCli::Thin => {
668                // The user explicitly asked for ThinLTO
669                return config::Lto::Thin;
670            }
671        }
672
673        // Ok at this point the target doesn't require anything and the user
674        // hasn't asked for anything. Our next decision is whether or not
675        // we enable "auto" ThinLTO where we use multiple codegen units and
676        // then do ThinLTO over those codegen units. The logic below will
677        // either return `No` or `ThinLocal`.
678
679        // If processing command line options determined that we're incompatible
680        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
681        if self.opts.cli_forced_local_thinlto_off {
682            return config::Lto::No;
683        }
684
685        // If `-Z thinlto` specified process that, but note that this is mostly
686        // a deprecated option now that `-C lto=thin` exists.
687        if let Some(enabled) = self.opts.unstable_opts.thinlto {
688            if enabled {
689                return config::Lto::ThinLocal;
690            } else {
691                return config::Lto::No;
692            }
693        }
694
695        // If there's only one codegen unit and LTO isn't enabled then there's
696        // no need for ThinLTO so just return false.
697        if self.codegen_units().as_usize() == 1 {
698            return config::Lto::No;
699        }
700
701        // Now we're in "defaults" territory. By default we enable ThinLTO for
702        // optimized compiles (anything greater than O0).
703        match self.opts.optimize {
704            config::OptLevel::No => config::Lto::No,
705            _ => config::Lto::ThinLocal,
706        }
707    }
708
709    /// Returns the panic strategy for this compile session. If the user explicitly selected one
710    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
711    pub fn panic_strategy(&self) -> PanicStrategy {
712        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
713    }
714
715    pub fn fewer_names(&self) -> bool {
716        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
717            fewer_names
718        } else {
719            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
720                || self.opts.output_types.contains_key(&OutputType::Bitcode)
721                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
722                || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
723            !more_names
724        }
725    }
726
727    pub fn unstable_options(&self) -> bool {
728        self.opts.unstable_opts.unstable_options
729    }
730
731    pub fn is_nightly_build(&self) -> bool {
732        self.opts.unstable_features.is_nightly_build()
733    }
734
735    pub fn overflow_checks(&self) -> bool {
736        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
737    }
738
739    pub fn ub_checks(&self) -> bool {
740        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
741    }
742
743    pub fn contract_checks(&self) -> bool {
744        self.opts.unstable_opts.contract_checks.unwrap_or(false)
745    }
746
747    pub fn relocation_model(&self) -> RelocModel {
748        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
749    }
750
751    pub fn code_model(&self) -> Option<CodeModel> {
752        self.opts.cg.code_model.or(self.target.code_model)
753    }
754
755    pub fn tls_model(&self) -> TlsModel {
756        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
757    }
758
759    pub fn direct_access_external_data(&self) -> Option<bool> {
760        self.opts
761            .unstable_opts
762            .direct_access_external_data
763            .or(self.target.direct_access_external_data)
764    }
765
766    pub fn split_debuginfo(&self) -> SplitDebuginfo {
767        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
768    }
769
770    /// Returns the DWARF version passed on the CLI or the default for the target.
771    pub fn dwarf_version(&self) -> u32 {
772        self.opts
773            .cg
774            .dwarf_version
775            .or(self.opts.unstable_opts.dwarf_version)
776            .unwrap_or(self.target.default_dwarf_version)
777    }
778
779    pub fn stack_protector(&self) -> StackProtector {
780        if self.target.options.supports_stack_protector {
781            self.opts.unstable_opts.stack_protector
782        } else {
783            StackProtector::None
784        }
785    }
786
787    pub fn must_emit_unwind_tables(&self) -> bool {
788        // This is used to control the emission of the `uwtable` attribute on
789        // LLVM functions. The `uwtable` attribute according to LLVM is:
790        //
791        //     This attribute indicates that the ABI being targeted requires that an
792        //     unwind table entry be produced for this function even if we can show
793        //     that no exceptions passes by it. This is normally the case for the
794        //     ELF x86-64 abi, but it can be disabled for some compilation units.
795        //
796        // Typically when we're compiling with `-C panic=abort` we don't need
797        // `uwtable` because we can't generate any exceptions!
798        // Unwind tables are needed when compiling with `-C panic=unwind`, but
799        // LLVM won't omit unwind tables unless the function is also marked as
800        // `nounwind`, so users are allowed to disable `uwtable` emission.
801        // Historically rustc always emits `uwtable` attributes by default, so
802        // even they can be disabled, they're still emitted by default.
803        //
804        // On some targets (including windows), however, exceptions include
805        // other events such as illegal instructions, segfaults, etc. This means
806        // that on Windows we end up still needing unwind tables even if the `-C
807        // panic=abort` flag is passed.
808        //
809        // You can also find more info on why Windows needs unwind tables in:
810        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
811        //
812        // If a target requires unwind tables, then they must be emitted.
813        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
814        // value, if it is provided, or disable them, if not.
815        self.target.requires_uwtable
816            || self.opts.cg.force_unwind_tables.unwrap_or(
817                self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
818            )
819    }
820
821    /// Returns the number of query threads that should be used for this
822    /// compilation
823    #[inline]
824    pub fn threads(&self) -> usize {
825        self.opts.unstable_opts.threads
826    }
827
828    /// Returns the number of codegen units that should be used for this
829    /// compilation
830    pub fn codegen_units(&self) -> CodegenUnits {
831        if let Some(n) = self.opts.cli_forced_codegen_units {
832            return CodegenUnits::User(n);
833        }
834        if let Some(n) = self.target.default_codegen_units {
835            return CodegenUnits::Default(n as usize);
836        }
837
838        // If incremental compilation is turned on, we default to a high number
839        // codegen units in order to reduce the "collateral damage" small
840        // changes cause.
841        if self.opts.incremental.is_some() {
842            return CodegenUnits::Default(256);
843        }
844
845        // Why is 16 codegen units the default all the time?
846        //
847        // The main reason for enabling multiple codegen units by default is to
848        // leverage the ability for the codegen backend to do codegen and
849        // optimization in parallel. This allows us, especially for large crates, to
850        // make good use of all available resources on the machine once we've
851        // hit that stage of compilation. Large crates especially then often
852        // take a long time in codegen/optimization and this helps us amortize that
853        // cost.
854        //
855        // Note that a high number here doesn't mean that we'll be spawning a
856        // large number of threads in parallel. The backend of rustc contains
857        // global rate limiting through the `jobserver` crate so we'll never
858        // overload the system with too much work, but rather we'll only be
859        // optimizing when we're otherwise cooperating with other instances of
860        // rustc.
861        //
862        // Rather a high number here means that we should be able to keep a lot
863        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
864        // to build we'll be guaranteed that all cpus will finish pretty closely
865        // to one another and we should make relatively optimal use of system
866        // resources
867        //
868        // Note that the main cost of codegen units is that it prevents LLVM
869        // from inlining across codegen units. Users in general don't have a lot
870        // of control over how codegen units are split up so it's our job in the
871        // compiler to ensure that undue performance isn't lost when using
872        // codegen units (aka we can't require everyone to slap `#[inline]` on
873        // everything).
874        //
875        // If we're compiling at `-O0` then the number doesn't really matter too
876        // much because performance doesn't matter and inlining is ok to lose.
877        // In debug mode we just want to try to guarantee that no cpu is stuck
878        // doing work that could otherwise be farmed to others.
879        //
880        // In release mode, however (O1 and above) performance does indeed
881        // matter! To recover the loss in performance due to inlining we'll be
882        // enabling ThinLTO by default (the function for which is just below).
883        // This will ensure that we recover any inlining wins we otherwise lost
884        // through codegen unit partitioning.
885        //
886        // ---
887        //
888        // Ok that's a lot of words but the basic tl;dr; is that we want a high
889        // number here -- but not too high. Additionally we're "safe" to have it
890        // always at the same number at all optimization levels.
891        //
892        // As a result 16 was chosen here! Mostly because it was a power of 2
893        // and most benchmarks agreed it was roughly a local optimum. Not very
894        // scientific.
895        CodegenUnits::Default(16)
896    }
897
898    pub fn teach(&self, code: ErrCode) -> bool {
899        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
900    }
901
902    pub fn edition(&self) -> Edition {
903        self.opts.edition
904    }
905
906    pub fn link_dead_code(&self) -> bool {
907        self.opts.cg.link_dead_code.unwrap_or(false)
908    }
909
910    pub fn filename_display_preference(
911        &self,
912        scope: RemapPathScopeComponents,
913    ) -> FileNameDisplayPreference {
914        assert!(
915            scope.bits().count_ones() == 1,
916            "one and only one scope should be passed to `Session::filename_display_preference`"
917        );
918        if self.opts.unstable_opts.remap_path_scope.contains(scope) {
919            FileNameDisplayPreference::Remapped
920        } else {
921            FileNameDisplayPreference::Local
922        }
923    }
924
925    /// Get the deployment target on Apple platforms based on the standard environment variables,
926    /// or fall back to the minimum version supported by `rustc`.
927    ///
928    /// This should be guarded behind `if sess.target.is_like_darwin`.
929    pub fn apple_deployment_target(&self) -> apple::OSVersion {
930        let min = apple::OSVersion::minimum_deployment_target(&self.target);
931        let env_var = apple::deployment_target_env_var(&self.target.os);
932
933        // FIXME(madsmtm): Track changes to this.
934        if let Ok(deployment_target) = env::var(env_var) {
935            match apple::OSVersion::from_str(&deployment_target) {
936                Ok(version) => {
937                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
938                    // It is common that the deployment target is set a bit too low, for example on
939                    // macOS Aarch64 to also target older x86_64. So we only want to warn when variable
940                    // is lower than the minimum OS supported by rustc, not when the variable is lower
941                    // than the minimum for a specific target.
942                    if version < os_min {
943                        self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
944                            env_var,
945                            version: version.fmt_pretty().to_string(),
946                            os_min: os_min.fmt_pretty().to_string(),
947                        });
948                    }
949
950                    // Raise the deployment target to the minimum supported.
951                    version.max(min)
952                }
953                Err(error) => {
954                    self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
955                    min
956                }
957            }
958        } else {
959            // If no deployment target variable is set, default to the minimum found above.
960            min
961        }
962    }
963}
964
965// JUSTIFICATION: part of session construction
966#[allow(rustc::bad_opt_access)]
967fn default_emitter(
968    sopts: &config::Options,
969    source_map: Arc<SourceMap>,
970    translator: Translator,
971) -> Box<DynEmitter> {
972    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
973    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
974    let terminal_url = match sopts.unstable_opts.terminal_urls {
975        TerminalUrl::Auto => {
976            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
977                (Ok("truecolor"), Ok("xterm-256color"))
978                    if sopts.unstable_features.is_nightly_build() =>
979                {
980                    TerminalUrl::Yes
981                }
982                _ => TerminalUrl::No,
983            }
984        }
985        t => t,
986    };
987
988    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
989
990    match sopts.error_format {
991        config::ErrorOutputType::HumanReadable { kind, color_config } => {
992            let short = kind.short();
993
994            if let HumanReadableErrorType::AnnotateSnippet = kind {
995                let emitter =
996                    AnnotateSnippetEmitter::new(source_map, translator, short, macro_backtrace);
997                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
998            } else {
999                let emitter = HumanEmitter::new(stderr_destination(color_config), translator)
1000                    .sm(source_map)
1001                    .short_message(short)
1002                    .diagnostic_width(sopts.diagnostic_width)
1003                    .macro_backtrace(macro_backtrace)
1004                    .track_diagnostics(track_diagnostics)
1005                    .terminal_url(terminal_url)
1006                    .theme(if let HumanReadableErrorType::Unicode = kind {
1007                        OutputTheme::Unicode
1008                    } else {
1009                        OutputTheme::Ascii
1010                    })
1011                    .ignored_directories_in_source_blocks(
1012                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1013                    );
1014                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1015            }
1016        }
1017        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1018            JsonEmitter::new(
1019                Box::new(io::BufWriter::new(io::stderr())),
1020                source_map,
1021                translator,
1022                pretty,
1023                json_rendered,
1024                color_config,
1025            )
1026            .ui_testing(sopts.unstable_opts.ui_testing)
1027            .ignored_directories_in_source_blocks(
1028                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1029            )
1030            .diagnostic_width(sopts.diagnostic_width)
1031            .macro_backtrace(macro_backtrace)
1032            .track_diagnostics(track_diagnostics)
1033            .terminal_url(terminal_url),
1034        ),
1035    }
1036}
1037
1038// JUSTIFICATION: literally session construction
1039#[allow(rustc::bad_opt_access)]
1040#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
1041pub fn build_session(
1042    sopts: config::Options,
1043    io: CompilerIO,
1044    fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
1045    registry: rustc_errors::registry::Registry,
1046    fluent_resources: Vec<&'static str>,
1047    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1048    target: Target,
1049    cfg_version: &'static str,
1050    ice_file: Option<PathBuf>,
1051    using_internal_features: &'static AtomicBool,
1052    expanded_args: Vec<String>,
1053) -> Session {
1054    // FIXME: This is not general enough to make the warning lint completely override
1055    // normal diagnostic warnings, since the warning lint can also be denied and changed
1056    // later via the source code.
1057    let warnings_allow = sopts
1058        .lint_opts
1059        .iter()
1060        .rfind(|&(key, _)| *key == "warnings")
1061        .is_some_and(|&(_, level)| level == lint::Allow);
1062    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1063    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1064
1065    let translator = Translator {
1066        fluent_bundle,
1067        fallback_fluent_bundle: fallback_fluent_bundle(
1068            fluent_resources,
1069            sopts.unstable_opts.translate_directionality_markers,
1070        ),
1071    };
1072    let source_map = rustc_span::source_map::get_source_map().unwrap();
1073    let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
1074
1075    let mut dcx = DiagCtxt::new(emitter)
1076        .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1077        .with_registry(registry);
1078    if let Some(ice_file) = ice_file {
1079        dcx = dcx.with_ice_file(ice_file);
1080    }
1081
1082    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1083    let (host, target_warnings) = Target::search(&host_triple, sopts.sysroot.path())
1084        .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1085    for warning in target_warnings.warning_messages() {
1086        dcx.handle().warn(warning)
1087    }
1088
1089    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1090    {
1091        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1092
1093        let profiler = SelfProfiler::new(
1094            directory,
1095            sopts.crate_name.as_deref(),
1096            sopts.unstable_opts.self_profile_events.as_deref(),
1097            &sopts.unstable_opts.self_profile_counter,
1098        );
1099        match profiler {
1100            Ok(profiler) => Some(Arc::new(profiler)),
1101            Err(e) => {
1102                dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1103                None
1104            }
1105        }
1106    } else {
1107        None
1108    };
1109
1110    let mut psess = ParseSess::with_dcx(dcx, source_map);
1111    psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1112
1113    let host_triple = config::host_tuple();
1114    let target_triple = sopts.target_triple.tuple();
1115    // FIXME use host sysroot?
1116    let host_tlib_path =
1117        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1118    let target_tlib_path = if host_triple == target_triple {
1119        // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1120        // rescanning of the target lib path and an unnecessary allocation.
1121        Arc::clone(&host_tlib_path)
1122    } else {
1123        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1124    };
1125
1126    let prof = SelfProfilerRef::new(
1127        self_profiler,
1128        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1129    );
1130
1131    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1132        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1133        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1134        _ => CtfeBacktrace::Disabled,
1135    });
1136
1137    let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1138    let target_filesearch =
1139        filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1140    let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1141
1142    let invocation_temp = sopts
1143        .incremental
1144        .as_ref()
1145        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1146
1147    let timings = TimingSectionHandler::new(sopts.json_timings);
1148
1149    let sess = Session {
1150        target,
1151        host,
1152        opts: sopts,
1153        target_tlib_path,
1154        psess,
1155        io,
1156        incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1157        prof,
1158        timings,
1159        code_stats: Default::default(),
1160        lint_store: None,
1161        driver_lint_caps,
1162        ctfe_backtrace,
1163        miri_unleashed_features: Lock::new(Default::default()),
1164        asm_arch,
1165        target_features: Default::default(),
1166        unstable_target_features: Default::default(),
1167        cfg_version,
1168        using_internal_features,
1169        expanded_args,
1170        target_filesearch,
1171        host_filesearch,
1172        invocation_temp,
1173    };
1174
1175    validate_commandline_args_with_session_available(&sess);
1176
1177    sess
1178}
1179
1180/// Validate command line arguments with a `Session`.
1181///
1182/// If it is useful to have a Session available already for validating a commandline argument, you
1183/// can do so here.
1184// JUSTIFICATION: needs to access args to validate them
1185#[allow(rustc::bad_opt_access)]
1186fn validate_commandline_args_with_session_available(sess: &Session) {
1187    // Since we don't know if code in an rlib will be linked to statically or
1188    // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1189    // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1190    // these manually generated symbols confuse LLD when it tries to merge
1191    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1192    // when compiling for LLD ThinLTO. This way we can validly just not generate
1193    // the `dllimport` attributes and `__imp_` symbols in that case.
1194    if sess.opts.cg.linker_plugin_lto.enabled()
1195        && sess.opts.cg.prefer_dynamic
1196        && sess.target.is_like_windows
1197    {
1198        sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1199    }
1200
1201    // Make sure that any given profiling data actually exists so LLVM can't
1202    // decide to silently skip PGO.
1203    if let Some(ref path) = sess.opts.cg.profile_use {
1204        if !path.exists() {
1205            sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1206        }
1207    }
1208
1209    // Do the same for sample profile data.
1210    if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1211        if !path.exists() {
1212            sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1213        }
1214    }
1215
1216    // Unwind tables cannot be disabled if the target requires them.
1217    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1218        if sess.target.requires_uwtable && !include_uwtables {
1219            sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1220        }
1221    }
1222
1223    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1224    let supported_sanitizers = sess.target.options.supported_sanitizers;
1225    let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1226    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled
1227    // we should allow Shadow Call Stack sanitizer.
1228    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1229        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1230    }
1231    match unsupported_sanitizers.into_iter().count() {
1232        0 => {}
1233        1 => {
1234            sess.dcx()
1235                .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1236        }
1237        _ => {
1238            sess.dcx().emit_err(errors::SanitizersNotSupported {
1239                us: unsupported_sanitizers.to_string(),
1240            });
1241        }
1242    }
1243
1244    // Cannot mix and match mutually-exclusive sanitizers.
1245    if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1246        sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1247            first: first.to_string(),
1248            second: second.to_string(),
1249        });
1250    }
1251
1252    // Cannot enable crt-static with sanitizers on Linux
1253    if sess.crt_static(None)
1254        && !sess.opts.unstable_opts.sanitizer.is_empty()
1255        && !sess.target.is_like_msvc
1256    {
1257        sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1258    }
1259
1260    // LLVM CFI requires LTO.
1261    if sess.is_sanitizer_cfi_enabled()
1262        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1263    {
1264        sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1265    }
1266
1267    // KCFI requires panic=abort
1268    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1269        sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1270    }
1271
1272    // LLVM CFI using rustc LTO requires a single codegen unit.
1273    if sess.is_sanitizer_cfi_enabled()
1274        && sess.lto() == config::Lto::Fat
1275        && (sess.codegen_units().as_usize() != 1)
1276    {
1277        sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1278    }
1279
1280    // Canonical jump tables requires CFI.
1281    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1282        if !sess.is_sanitizer_cfi_enabled() {
1283            sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1284        }
1285    }
1286
1287    // KCFI arity indicator requires KCFI.
1288    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1289        sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1290    }
1291
1292    // LLVM CFI pointer generalization requires CFI or KCFI.
1293    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1294        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1295            sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1296        }
1297    }
1298
1299    // LLVM CFI integer normalization requires CFI or KCFI.
1300    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1301        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1302            sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1303        }
1304    }
1305
1306    // LTO unit splitting requires LTO.
1307    if sess.is_split_lto_unit_enabled()
1308        && !(sess.lto() == config::Lto::Fat
1309            || sess.lto() == config::Lto::Thin
1310            || sess.opts.cg.linker_plugin_lto.enabled())
1311    {
1312        sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1313    }
1314
1315    // VFE requires LTO.
1316    if sess.lto() != config::Lto::Fat {
1317        if sess.opts.unstable_opts.virtual_function_elimination {
1318            sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1319        }
1320    }
1321
1322    if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1323        if !sess.target.options.supports_stack_protector {
1324            sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1325                stack_protector: sess.opts.unstable_opts.stack_protector,
1326                target_triple: &sess.opts.target_triple,
1327            });
1328        }
1329    }
1330
1331    if sess.opts.unstable_opts.small_data_threshold.is_some() {
1332        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1333            sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1334                target_triple: &sess.opts.target_triple,
1335            })
1336        }
1337    }
1338
1339    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1340        sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1341    }
1342
1343    if let Some(dwarf_version) =
1344        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1345    {
1346        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.
1347        if dwarf_version < 2 || dwarf_version > 5 {
1348            sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1349        }
1350    }
1351
1352    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1353        && !sess.opts.unstable_opts.unstable_options
1354    {
1355        sess.dcx()
1356            .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1357    }
1358
1359    if sess.opts.unstable_opts.embed_source {
1360        let dwarf_version = sess.dwarf_version();
1361
1362        if dwarf_version < 5 {
1363            sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1364        }
1365
1366        if sess.opts.debuginfo == DebugInfo::None {
1367            sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1368        }
1369    }
1370
1371    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1372        sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1373    }
1374
1375    if let Some(flavor) = sess.opts.cg.linker_flavor
1376        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1377    {
1378        let flavor = flavor.desc();
1379        sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1380    }
1381
1382    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1383        if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1384            sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1385        }
1386    }
1387
1388    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1389        if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1390            sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1391        }
1392    }
1393
1394    if let Some(regparm) = sess.opts.unstable_opts.regparm {
1395        if regparm > 3 {
1396            sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1397        }
1398        if sess.target.arch != "x86" {
1399            sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1400        }
1401    }
1402    if sess.opts.unstable_opts.reg_struct_return {
1403        if sess.target.arch != "x86" {
1404            sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1405        }
1406    }
1407
1408    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1409    // kept as a `match` to force a change if new ones are added, even if we currently only support
1410    // `thunk-extern` like Clang.
1411    match sess.opts.unstable_opts.function_return {
1412        FunctionReturn::Keep => (),
1413        FunctionReturn::ThunkExtern => {
1414            // FIXME: In principle, the inherited base LLVM target code model could be large,
1415            // but this only checks whether we were passed one explicitly (like Clang does).
1416            if let Some(code_model) = sess.code_model()
1417                && code_model == CodeModel::Large
1418            {
1419                sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1420            }
1421        }
1422    }
1423
1424    if sess.opts.cg.soft_float {
1425        if sess.target.arch == "arm" {
1426            sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1427        } else {
1428            // All `use_softfp` does is the equivalent of `-mfloat-abi` in GCC/clang, which only exists on ARM targets.
1429            // We document this flag to only affect `*eabihf` targets, so let's show a warning for all other targets.
1430            sess.dcx().emit_warn(errors::SoftFloatIgnored);
1431        }
1432    }
1433}
1434
1435/// Holds data on the current incremental compilation session, if there is one.
1436#[derive(Debug)]
1437enum IncrCompSession {
1438    /// This is the state the session will be in until the incr. comp. dir is
1439    /// needed.
1440    NotInitialized,
1441    /// This is the state during which the session directory is private and can
1442    /// be modified. `_lock_file` is never directly used, but its presence
1443    /// alone has an effect, because the file will unlock when the session is
1444    /// dropped.
1445    Active { session_directory: PathBuf, _lock_file: flock::Lock },
1446    /// This is the state after the session directory has been finalized. In this
1447    /// state, the contents of the directory must not be modified any more.
1448    Finalized { session_directory: PathBuf },
1449    /// This is an error state that is reached when some compilation error has
1450    /// occurred. It indicates that the contents of the session directory must
1451    /// not be used, since they might be invalid.
1452    InvalidBecauseOfErrors { session_directory: PathBuf },
1453}
1454
1455/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1456pub struct EarlyDiagCtxt {
1457    dcx: DiagCtxt,
1458}
1459
1460impl EarlyDiagCtxt {
1461    pub fn new(output: ErrorOutputType) -> Self {
1462        let emitter = mk_emitter(output);
1463        Self { dcx: DiagCtxt::new(emitter) }
1464    }
1465
1466    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1467    /// format. If `early_err` was previously called this will panic.
1468    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1469        assert!(self.dcx.handle().has_errors().is_none());
1470
1471        let emitter = mk_emitter(output);
1472        self.dcx = DiagCtxt::new(emitter);
1473    }
1474
1475    #[allow(rustc::untranslatable_diagnostic)]
1476    #[allow(rustc::diagnostic_outside_of_impl)]
1477    pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1478        self.dcx.handle().note(msg)
1479    }
1480
1481    #[allow(rustc::untranslatable_diagnostic)]
1482    #[allow(rustc::diagnostic_outside_of_impl)]
1483    pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1484        self.dcx.handle().struct_help(msg).emit()
1485    }
1486
1487    #[allow(rustc::untranslatable_diagnostic)]
1488    #[allow(rustc::diagnostic_outside_of_impl)]
1489    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1490    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1491        self.dcx.handle().err(msg)
1492    }
1493
1494    #[allow(rustc::untranslatable_diagnostic)]
1495    #[allow(rustc::diagnostic_outside_of_impl)]
1496    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1497        self.dcx.handle().fatal(msg)
1498    }
1499
1500    #[allow(rustc::untranslatable_diagnostic)]
1501    #[allow(rustc::diagnostic_outside_of_impl)]
1502    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1503        self.dcx.handle().struct_fatal(msg)
1504    }
1505
1506    #[allow(rustc::untranslatable_diagnostic)]
1507    #[allow(rustc::diagnostic_outside_of_impl)]
1508    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1509        self.dcx.handle().warn(msg)
1510    }
1511
1512    #[allow(rustc::untranslatable_diagnostic)]
1513    #[allow(rustc::diagnostic_outside_of_impl)]
1514    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1515        self.dcx.handle().struct_warn(msg)
1516    }
1517}
1518
1519fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1520    // FIXME(#100717): early errors aren't translated at the moment, so this is fine, but it will
1521    // need to reference every crate that might emit an early error for translation to work.
1522    let translator =
1523        Translator::with_fallback_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1524    let emitter: Box<DynEmitter> = match output {
1525        config::ErrorOutputType::HumanReadable { kind, color_config } => {
1526            let short = kind.short();
1527            Box::new(
1528                HumanEmitter::new(stderr_destination(color_config), translator)
1529                    .theme(if let HumanReadableErrorType::Unicode = kind {
1530                        OutputTheme::Unicode
1531                    } else {
1532                        OutputTheme::Ascii
1533                    })
1534                    .short_message(short),
1535            )
1536        }
1537        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1538            Box::new(JsonEmitter::new(
1539                Box::new(io::BufWriter::new(io::stderr())),
1540                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1541                translator,
1542                pretty,
1543                json_rendered,
1544                color_config,
1545            ))
1546        }
1547    };
1548    emitter
1549}
1550
1551pub trait RemapFileNameExt {
1552    type Output<'a>
1553    where
1554        Self: 'a;
1555
1556    /// Returns a possibly remapped filename based on the passed scope and remap cli options.
1557    ///
1558    /// One and only one scope should be passed to this method, it will panic otherwise.
1559    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1560}
1561
1562impl RemapFileNameExt for rustc_span::FileName {
1563    type Output<'a> = rustc_span::FileNameDisplay<'a>;
1564
1565    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1566        assert!(
1567            scope.bits().count_ones() == 1,
1568            "one and only one scope should be passed to for_scope"
1569        );
1570        if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1571            self.prefer_remapped_unconditionally()
1572        } else {
1573            self.prefer_local()
1574        }
1575    }
1576}
1577
1578impl RemapFileNameExt for rustc_span::RealFileName {
1579    type Output<'a> = &'a Path;
1580
1581    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1582        assert!(
1583            scope.bits().count_ones() == 1,
1584            "one and only one scope should be passed to for_scope"
1585        );
1586        if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1587            self.remapped_path_if_available()
1588        } else {
1589            self.local_path_if_available()
1590        }
1591    }
1592}