Skip to main content

rustc_session/
session.rs

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