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