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