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