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