rustc_session/
session.rs

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