Skip to main content

rustc_session/
session.rs

1use std::any::Any;
2use std::ops::{Deref, DerefMut};
3use std::path::Component::Prefix;
4use std::path::PathBuf;
5use std::str::FromStr;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, AtomicUsize};
8use std::{env, io};
9
10use rustc_abi::PackCoroutineLayout;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
13use rustc_data_structures::sync::{AppendOnlyVec, DynSend, DynSync, Lock};
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::{
20    Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, PResult, TerminalUrl,
21};
22use rustc_feature::UnstableFeatures;
23use rustc_lint_defs::{CheckLintNameResult, LintName, RegisteredTools};
24use rustc_macros::StableHash;
25pub use rustc_span::def_id::StableCrateId;
26use rustc_span::edition::Edition;
27use rustc_span::source_map::{FilePathMapping, SourceMap};
28use rustc_span::{RealFileName, Span, Symbol};
29use rustc_structures::{CrateType, Limit};
30use rustc_target::asm::InlineAsmArch;
31use rustc_target::spec::{
32    Arch, CfgAbi, CodeModel, DebuginfoKind, MergeFunctions, Os, PanicStrategy, RelocModel,
33    RelroLevel, SanitizerSet, SmallDataThresholdSupport, SplitDebuginfo, StackProtector,
34    SymbolVisibility, Target, 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, BranchProtection, Cfg, CheckCfg, CoverageLevel, CoverageOptions, DebugInfo,
41    FunctionReturn, Input, InstrumentCoverage, InstrumentMcount, LtoCli, NATIVE_CPU, OutFileName,
42    PAuthKey, PointerAuthOption, SwitchWithOptPath,
43};
44use crate::filesearch::FileSearch;
45use crate::lint::LintId;
46use crate::output::{ErrorOutputType, OutputType};
47use crate::parse::ParseSess;
48use crate::search_paths::SearchPath;
49use crate::{diagnostics, filesearch, lint};
50
51/// The behavior of the CTFE engine when an error occurs with regards to backtraces.
52#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CtfeBacktrace {
}
#[automatically_derived]impl ::core::clone::Clone for CtfeBacktrace {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for CtfeBacktrace { }Copy)]
53pub enum CtfeBacktrace {
54    /// Do nothing special, return the error as usual without a backtrace.
55    Disabled,
56    /// Capture a backtrace at the point the error is created and return it in the error
57    /// (to be printed later if/when the error ever actually gets shown to the user).
58    Capture,
59    /// Capture a backtrace at the point the error is created and immediately print it out.
60    Immediate,
61}
62
63#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Limits {
}
#[automatically_derived]impl ::core::clone::Clone for Limits {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        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]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "Limits recursion_limit move_size_limit type_length_limit pattern_complexity_limit",
            &self.recursion_limit, &self.move_size_limit,
            &self.type_length_limit, &&self.pattern_complexity_limit)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Limits {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::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.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
64pub struct Limits {
65    /// The maximum recursion limit for potentially infinitely recursive
66    /// operations such as auto-dereference and monomorphization.
67    pub recursion_limit: Limit,
68    /// The size at which the `large_assignments` lint starts
69    /// being emitted.
70    pub move_size_limit: Limit,
71    /// The maximum length of types during monomorphization.
72    pub type_length_limit: Limit,
73    /// The maximum pattern complexity allowed (internal only).
74    pub pattern_complexity_limit: Limit,
75}
76
77pub struct CompilerIO {
78    pub input: Input,
79    pub output_dir: Option<PathBuf>,
80    pub output_file: Option<OutFileName>,
81    pub temps_dir: Option<PathBuf>,
82}
83
84pub trait DynLintStore: Any + DynSync + DynSend {
85    /// Provides a way to access lint groups without depending on `rustc_lint`
86    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
87
88    fn check_attribute_lint_name(
89        &self,
90        lint_name: LintName,
91        lint_tools: &RegisteredTools,
92    ) -> CheckLintNameResult<'_>;
93}
94
95/// Hardware pointer-signing keys in ARM8.3.
96/// These values are the same as used in ptrauth.h.
97#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PointerAuthARM8_3Key {
}
#[automatically_derived]impl ::core::clone::Clone for PointerAuthARM8_3Key {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for PointerAuthARM8_3Key { }Copy, #[automatically_derived]impl ::core::fmt::Debug for PointerAuthARM8_3Key {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PointerAuthARM8_3Key::ASIA => "ASIA",
                PointerAuthARM8_3Key::ASIB => "ASIB",
                PointerAuthARM8_3Key::ASDA => "ASDA",
                PointerAuthARM8_3Key::ASDB => "ASDB",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    PointerAuthARM8_3Key {
}
#[automatically_derived]impl ::core::cmp::PartialEq for PointerAuthARM8_3Key {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for PointerAuthARM8_3Key { }Eq)]
98pub enum PointerAuthARM8_3Key {
99    ASIA = 0,
100    ASIB = 1,
101    ASDA = 2,
102    ASDB = 3,
103}
104
105/// Forms of extra discrimination.
106pub enum PointerAuthDiscrimination {
107    /// No additional discrimination.
108    None,
109    /// Include a hash of the entity's type.
110    Type,
111    /// Include a hash of the entity's identity.
112    Decl,
113    /// Discriminate using a constant value.
114    Constant,
115}
116
117/// Types of address discrimination.
118pub enum PointerAuthAddressDiscriminator {
119    /// Enable/disable hardware address discrimination.
120    HardwareAddress(bool),
121    /// Use a synthetic value. For instance init/fini entries can not the address of the arrays,
122    /// they must use a synthetic value of `1`.
123    Synthetic(u64),
124}
125
126pub struct PointerAuthSchema {
127    pub is_address_discriminated: PointerAuthAddressDiscriminator,
128    pub discrimination_kind: PointerAuthDiscrimination,
129    pub key: PointerAuthARM8_3Key,
130    pub constant_discriminator: u16,
131}
132impl PointerAuthSchema {
133    pub fn function_pointers_default(target: &Target) -> Self {
134        if !(target.cfg_abi == CfgAbi::Pauthtest) {
    ::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
135        return Self {
136            is_address_discriminated: PointerAuthAddressDiscriminator::HardwareAddress(false),
137            discrimination_kind: PointerAuthDiscrimination::None,
138            key: PointerAuthARM8_3Key::ASIA,
139            constant_discriminator: 0,
140        };
141    }
142    pub fn init_fini_default(target: &Target) -> Self {
143        if !(target.cfg_abi == CfgAbi::Pauthtest) {
    ::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
144        return Self {
145            is_address_discriminated: PointerAuthAddressDiscriminator::Synthetic(1),
146            discrimination_kind: PointerAuthDiscrimination::None,
147            key: PointerAuthARM8_3Key::ASIA,
148            // ptrauth_string_discriminator("init_fini")
149            constant_discriminator: 0xd9d4,
150        };
151    }
152}
153
154pub struct PointerAuthConfig {
155    /// Should return addresses be authenticated?
156    pub return_addresses: bool,
157    /// Do authentication failures cause a trap?
158    pub auth_traps: bool,
159    /// Do indirect goto label addresses need to be authenticated?
160    pub indirect_gotos: bool,
161    /// Should ELF GOT entries be signed?
162    pub elf_got: bool,
163    /// Use hardened lowering for jump-table dispatch?
164    pub aarch64_jump_table_hardening: bool,
165    /// The ABI for C function pointers.
166    pub function_pointers: Option<PointerAuthSchema>,
167    /// The ABI for function addresses in .init_array and .fini_array
168    pub init_fini: Option<PointerAuthSchema>,
169    /// Use of pointer authentication intrinsics.
170    pub intrinsics: bool,
171    /// The following are used only for compatibility with C++ and control over generated abi
172    /// version. They do not control Rust code generation.
173    pub typeinfo_vt_ptr_discrimination: bool,
174    pub vt_ptr_addr_discrimination: bool,
175    pub vt_ptr_type_discrimination: bool,
176}
177impl PointerAuthConfig {
178    fn default(target: &Target) -> Self {
179        if !(target.cfg_abi == CfgAbi::Pauthtest) {
    ::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
180        return Self {
181            return_addresses: true,
182            auth_traps: true,
183            indirect_gotos: true,
184            elf_got: false,
185            aarch64_jump_table_hardening: true,
186            function_pointers: Some(PointerAuthSchema::function_pointers_default(target)),
187            init_fini: Some(PointerAuthSchema::init_fini_default(target)),
188            intrinsics: true,
189            typeinfo_vt_ptr_discrimination: true,
190            vt_ptr_addr_discrimination: true,
191            vt_ptr_type_discrimination: true,
192        };
193    }
194    pub fn calculate_pauth_abi_version(&self, target: &Target) -> u32 {
195        if !(target.cfg_abi == CfgAbi::Pauthtest) {
    ::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
196        // Bit positions of version flags for AARCH64_PAUTH_PLATFORM_LLVM_LINUX.
197        // NOTE: The enum values must stay in sync with clang, see:
198        // <llvm_root>/llvm/include/llvm/BinaryFormat/ELF.h
199        //
200        // We do not expect to use C++ virtual dispatch, but enable these flags
201        // for compatibility with C++ code. Intrinsics are also always enabled.
202        //
203        // Link to PAuth core info documentation:
204        // <https://github.com/ARM-software/abi-aa/blob/2025Q4/pauthabielf64/pauthabielf64.rst#core-information>
205        const INTRINSICS: u32 = 0;
206        const CALLS: u32 = 1;
207        const RETURNS: u32 = 2;
208        const AUTHTRAPS: u32 = 3;
209        const VT_PTR_ADDR_DISCR: u32 = 4;
210        const VT_PTR_TYPE_DISCR: u32 = 5;
211        const INIT_FINI: u32 = 6;
212        const INIT_FINI_ADDR_DISC: u32 = 7;
213        const GOT: u32 = 8;
214        const GOTOS: u32 = 9;
215        const TYPEINFO_VT_PTR_DISCR: u32 = 10;
216        // FIXME(jchlanda) We don't yet support function pointer type discrimination.
217        // const FPTR_TYPE_DISCR: u32 = 11;
218
219        let pauth_abi_version: u32 = (u32::from(self.intrinsics) << INTRINSICS)
220            | (u32::from(self.function_pointers.is_some()) << CALLS)
221            | (u32::from(self.return_addresses) << RETURNS)
222            | (u32::from(self.auth_traps) << AUTHTRAPS)
223            | (u32::from(self.vt_ptr_addr_discrimination) << VT_PTR_ADDR_DISCR)
224            | (u32::from(self.vt_ptr_type_discrimination) << VT_PTR_TYPE_DISCR)
225            | (u32::from(self.init_fini.is_some()) << INIT_FINI)
226            | (u32::from(self.init_fini.as_ref().is_some_and(|schema| {
227                #[allow(non_exhaustive_omitted_patterns)] match schema.is_address_discriminated
    {
    PointerAuthAddressDiscriminator::HardwareAddress(true) |
        PointerAuthAddressDiscriminator::Synthetic(_) => true,
    _ => false,
}matches!(
228                    schema.is_address_discriminated,
229                    PointerAuthAddressDiscriminator::HardwareAddress(true)
230                        | PointerAuthAddressDiscriminator::Synthetic(_)
231                )
232            })) << INIT_FINI_ADDR_DISC)
233            | (u32::from(self.elf_got) << GOT)
234            | (u32::from(self.indirect_gotos) << GOTOS)
235            | (u32::from(self.typeinfo_vt_ptr_discrimination) << TYPEINFO_VT_PTR_DISCR);
236
237        pauth_abi_version
238    }
239    pub fn from_raw(raw: &[(PointerAuthOption, bool)], target: &Target) -> Option<Self> {
240        if target.cfg_abi != CfgAbi::Pauthtest {
241            return None;
242        }
243
244        let mut cfg = Self::default(target);
245        if raw.is_empty() {
246            return Some(cfg);
247        }
248
249        for (opt, enabled) in raw {
250            match opt {
251                PointerAuthOption::Calls => {
252                    if *enabled {
253                        cfg.function_pointers.get_or_insert_with(|| {
254                            PointerAuthSchema::function_pointers_default(target)
255                        });
256                    } else {
257                        cfg.function_pointers = None;
258                    }
259                }
260                PointerAuthOption::FunctionPointerTypeDiscrimination => {
261                    if *enabled {
262                        let schema = cfg.function_pointers.get_or_insert_with(|| {
263                            PointerAuthSchema::function_pointers_default(target)
264                        });
265                        schema.discrimination_kind = PointerAuthDiscrimination::Type;
266                    } else if let Some(schema) = &mut cfg.function_pointers {
267                        schema.discrimination_kind = PointerAuthDiscrimination::None;
268                    }
269                }
270                PointerAuthOption::ReturnAddresses => cfg.return_addresses = *enabled,
271                PointerAuthOption::AuthTraps => cfg.auth_traps = *enabled,
272                PointerAuthOption::IndirectGotos => cfg.indirect_gotos = *enabled,
273                PointerAuthOption::ElfGot => cfg.elf_got = *enabled,
274                PointerAuthOption::Aarch64JumpTableHardening => {
275                    cfg.aarch64_jump_table_hardening = *enabled
276                }
277                PointerAuthOption::InitFini => {
278                    if *enabled {
279                        cfg.init_fini
280                            .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
281                    } else {
282                        cfg.init_fini = None;
283                    }
284                }
285                PointerAuthOption::InitFiniAddressDiscrimination => {
286                    if *enabled {
287                        let schema = cfg
288                            .init_fini
289                            .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
290                        schema.is_address_discriminated =
291                            PointerAuthAddressDiscriminator::HardwareAddress(true);
292                    } else if let Some(schema) = &mut cfg.init_fini {
293                        schema.is_address_discriminated =
294                            PointerAuthAddressDiscriminator::Synthetic(1);
295                    }
296                }
297
298                PointerAuthOption::Intrinsics => cfg.intrinsics = *enabled,
299                PointerAuthOption::TypeInfoVTPtrDisc => {
300                    cfg.typeinfo_vt_ptr_discrimination = *enabled
301                }
302                PointerAuthOption::VTPtrAddrDisc => cfg.vt_ptr_addr_discrimination = *enabled,
303                PointerAuthOption::VTPtrTypeDisc => cfg.vt_ptr_type_discrimination = *enabled,
304            }
305        }
306
307        Some(cfg)
308    }
309    pub fn fn_attrs(&self) -> Vec<&'static str> {
310        // FIXME(jchlanda) This is not an exhaustive list of all `ptrauth`-related attributes, but only
311        // those currently supported. The list is expected to grow as additional functionality is
312        // implemented, particularly for C++ interoperability.
313        let mut attrs = ::alloc::vec::Vec::new()vec![];
314        if self.aarch64_jump_table_hardening {
315            attrs.push("aarch64-jump-table-hardening");
316        }
317        if self.auth_traps {
318            attrs.push("ptrauth-auth-traps");
319        }
320        if self.function_pointers.is_some() {
321            attrs.push("ptrauth-calls");
322        }
323        if self.indirect_gotos {
324            attrs.push("ptrauth-indirect-gotos");
325        }
326        if self.return_addresses {
327            attrs.push("ptrauth-returns");
328        }
329
330        attrs
331    }
332}
333
334/// Partial session built before the full session. More specifically, `EarlySession` is used to
335/// init the codegen backend, and then both pieces are used to build the full `Session`.
336pub struct EarlySession {
337    pub target: Target,
338    pub host: Target,
339    pub opts: config::Options,
340    pub psess: ParseSess,
341}
342
343// JUSTIFICATION: defn of the suggested wrapper fns
344#[allow(rustc::bad_opt_access)]
345impl EarlySession {
346    #[inline]
347    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
348        self.psess.dcx()
349    }
350
351    #[inline]
352    pub fn source_map(&self) -> &SourceMap {
353        self.psess.source_map()
354    }
355
356    /// Note: this is simpler than `Session::lto`, hence the `early_` prefix (to more clearly
357    /// distinguish it).
358    pub fn early_lto(&self) -> LtoCli {
359        self.opts.cg.lto
360    }
361
362    pub fn print_llvm_stats(&self) -> bool {
363        self.opts.unstable_opts.print_codegen_stats
364    }
365
366    pub fn print_llvm_stats_json(&self) -> Option<&String> {
367        self.opts.unstable_opts.print_codegen_stats_json.as_ref()
368    }
369
370    pub fn relocation_model(&self) -> RelocModel {
371        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
372    }
373
374    pub fn code_model(&self) -> Option<CodeModel> {
375        self.opts.cg.code_model.or(self.target.code_model)
376    }
377
378    pub fn tls_model(&self) -> TlsModel {
379        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
380    }
381
382    /// Returns the panic strategy for this compile session. If the user explicitly selected one
383    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
384    pub fn panic_strategy(&self) -> PanicStrategy {
385        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
386    }
387
388    /// Get the deployment target on Apple platforms based on the standard environment variables,
389    /// or fall back to the minimum version supported by `rustc`.
390    ///
391    /// This should be guarded behind `if sess.target.is_like_darwin`.
392    pub fn apple_deployment_target(&self) -> apple::OSVersion {
393        let min = apple::OSVersion::minimum_deployment_target(&self.target);
394        let env_var = apple::deployment_target_env_var(&self.target.os);
395
396        // FIXME(madsmtm): Track changes to this.
397        if let Ok(deployment_target) = env::var(env_var) {
398            match apple::OSVersion::from_str(&deployment_target) {
399                Ok(version) => {
400                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
401                    // It is common that the deployment target is set a bit too low, for example on
402                    // macOS Aarch64 to also target older x86_64. So we only want to warn when
403                    // variable is lower than the minimum OS supported by rustc, not when the
404                    // variable is lower than the minimum for a specific target.
405                    if version < os_min {
406                        self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
407                            env_var,
408                            version: version.fmt_pretty().to_string(),
409                            os_min: os_min.fmt_pretty().to_string(),
410                        });
411                    }
412
413                    // Raise the deployment target to the minimum supported.
414                    version.max(min)
415                }
416                Err(error) => {
417                    self.dcx()
418                        .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
419                    min
420                }
421            }
422        } else {
423            // If no deployment target variable is set, default to the minimum found above.
424            min
425        }
426    }
427
428    pub fn sanitizers(&self) -> SanitizerSet {
429        self.opts
430            .unstable_opts
431            .sanitizer
432            .combine_with_defaults(self.target.options.default_sanitizers)
433    }
434
435    pub fn merge_functions(&self) -> MergeFunctions {
436        self.opts.unstable_opts.merge_functions.unwrap_or(self.target.merge_functions)
437    }
438
439    pub fn is_nightly_build(&self) -> bool {
440        self.opts.unstable_features.is_nightly_build()
441    }
442}
443
444/// Some info about the backend, returned by `CodegenBackend::init` and put into the `Session`.
445#[derive(#[automatically_derived]impl ::core::default::Default for CodegenBackendInit {
    #[inline]
    fn default() -> Self {
        CodegenBackendInit {
            global_backend_features: ::core::default::Default::default(),
            replaced_rustc_intrinsics: ::core::default::Default::default(),
            fallback_rustc_intrinsics: ::core::default::Default::default(),
            thin_lto_supported: const true,
        }
    }
}Default)]
446pub struct CodegenBackendInit {
447    /// See `Session::global_backend_features`.
448    pub global_backend_features: Vec<String>,
449
450    /// See `Session::replaced_intrinsics`.
451    pub replaced_rustc_intrinsics: Vec<Symbol>,
452
453    /// See `Session::fallback_intrinsics`.
454    pub fallback_rustc_intrinsics: Vec<Symbol>,
455
456    /// See `Session::thin_lto_supported`.
457    pub thin_lto_supported: bool = true,
458}
459
460/// Represents the data associated with a compilation
461/// session for a single crate.
462pub struct Session {
463    /// The `EarlySession` is embedded so it can be passed to functions that need it.
464    /// `Session::deref{_,mut}` exist so the fields within can be accessed as if they were direct
465    /// fields of `Session`.
466    pub early_sess: EarlySession,
467    pub wasm_proc_macro_tuple: TargetTuple,
468    pub wasm_proc_macro_target: Target,
469    pub target_tlib_path: SearchPath,
470    pub unstable_features: UnstableFeatures,
471    pub config: Cfg,
472    pub check_config: CheckCfg,
473    /// Spans passed to `proc_macro::quote_span`. Each span has a numerical
474    /// identifier represented by its position in the vector.
475    proc_macro_quoted_spans: AppendOnlyVec<Span>,
476
477    /// Input, input file path and output file path to this compilation process.
478    pub io: CompilerIO,
479
480    /// Used by `-Z self-profile`.
481    pub prof: SelfProfilerRef,
482
483    /// Used to emit section timings events (enabled by `--json=timings`).
484    pub timings: TimingSectionHandler,
485
486    /// Data about code being compiled, gathered during compilation.
487    pub code_stats: CodeStats,
488
489    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
490    pub lint_store: Option<Arc<dyn DynLintStore>>,
491
492    /// Cap lint level specified by a driver specifically.
493    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
494
495    /// Tracks the current behavior of the CTFE engine when an error occurs.
496    /// Options range from returning the error without a backtrace to returning an error
497    /// and immediately printing the backtrace to stderr.
498    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
499    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
500    /// errors.
501    pub ctfe_backtrace: Lock<CtfeBacktrace>,
502
503    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
504    /// const check, optionally with the relevant feature gate. We use this to
505    /// warn about unleashing, but with a single diagnostic instead of dozens that
506    /// drown everything else in noise.
507    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
508
509    /// Architecture to use for interpreting asm!.
510    pub asm_arch: Option<InlineAsmArch>,
511
512    /// Set of actually enabled features for the current target, including ones that are not
513    /// in `cfg(target_feature)` because they are unstable or internal-only.
514    /// This is used by the compiler itself when it needs to know which target features are actually
515    /// going to be enabled in the backend (e.g. for knowing which registers inline asm can use).
516    pub internal_target_features: FxIndexSet<Symbol>,
517
518    /// The list of backend target features for this session. Not used by Rust itself because the
519    /// concrete feature names can be backend-specific. This is computed from the target's base
520    /// features, `-Ctarget-cpu`, `-Ctarget-feature`, and other flags that the current backend
521    /// models as target features (but that are not considered target features in Rust).
522    pub global_backend_features: Vec<String>,
523
524    /// The version of the rustc process, possibly including a commit hash and description.
525    pub cfg_version: &'static str,
526
527    /// The inner atomic value is set to true when a feature marked as `internal` is
528    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
529    /// internal features are wontfix, and they are usually the cause of the ICEs.
530    /// None signifies that this is not tracked.
531    pub using_internal_features: &'static AtomicBool,
532
533    /// Environment variables accessed during the build and their values when they exist.
534    pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
535
536    /// File paths accessed during the build.
537    pub file_depinfo: Lock<FxIndexSet<Symbol>>,
538
539    target_filesearch: Arc<FileSearch>,
540    host_filesearch: Arc<FileSearch>,
541    wasm_proc_macro_filesearch: Option<Arc<FileSearch>>,
542
543    /// A list of all intrinsics that the current codegen backend definitely replaces with its own
544    /// implementations, which means their fallback bodies do not need to be monomorphized.
545    pub replaced_rustc_intrinsics: FxHashSet<Symbol>,
546
547    /// A list of all intrinsics that the current codegen backend definitely does *not* replace
548    /// with its own implementations, which means their fallback bodies can be MIR-inlined.
549    pub fallback_rustc_intrinsics: FxHashSet<Symbol>,
550
551    /// Does the codegen backend support ThinLTO?
552    pub thin_lto_supported: bool,
553
554    /// Global per-session counter for MIR optimization pass applications.
555    ///
556    /// Used by `-Zmir-opt-bisect-limit` to assign an index to each
557    /// optimization-pass execution candidate during this compilation.
558    pub mir_opt_bisect_eval_count: AtomicUsize,
559
560    /// Whether the test harness removed a user-written `#[rustc_main]` attribute
561    /// while generating the synthetic test entry point.
562    pub removed_rustc_main_attr: AtomicBool,
563
564    /// Config specifying targets' pointer authentication preference.
565    pub pointer_auth_config: Option<PointerAuthConfig>,
566
567    /// Cached sanitizer set. Cached because it is accessed frequently.
568    sanitizers: SanitizerSet,
569}
570
571impl Deref for Session {
572    type Target = EarlySession;
573
574    fn deref(&self) -> &EarlySession {
575        &self.early_sess
576    }
577}
578
579impl DerefMut for Session {
580    fn deref_mut(&mut self) -> &mut EarlySession {
581        &mut self.early_sess
582    }
583}
584
585#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CodegenUnits {
}
#[automatically_derived]impl ::core::clone::Clone for CodegenUnits {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for CodegenUnits { }Copy)]
586pub enum CodegenUnits {
587    /// Specified by the user. In this case we try fairly hard to produce the
588    /// number of CGUs requested.
589    User(usize),
590
591    /// A default value, i.e. not specified by the user. In this case we take
592    /// more liberties about CGU formation, e.g. avoid producing very small
593    /// CGUs.
594    Default(usize),
595}
596
597impl CodegenUnits {
598    pub fn as_usize(self) -> usize {
599        match self {
600            CodegenUnits::User(n) => n,
601            CodegenUnits::Default(n) => n,
602        }
603    }
604}
605
606pub struct LintGroup {
607    pub name: LintName,
608    pub lints: Vec<LintId>,
609    pub is_externally_loaded: bool,
610}
611
612impl Session {
613    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
614        self.miri_unleashed_features.lock().push((span, feature_gate));
615    }
616
617    pub fn local_crate_source_file(&self) -> Option<RealFileName> {
618        Some(
619            self.source_map()
620                .path_mapping()
621                .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
622        )
623    }
624
625    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
626        let mut guar = None;
627        let unleashed_features = self.miri_unleashed_features.lock();
628        if !unleashed_features.is_empty() {
629            let mut must_err = false;
630            // Create a diagnostic pointing at where things got unleashed.
631            self.dcx().emit_warn(diagnostics::SkippingConstChecks {
632                unleashed_features: unleashed_features
633                    .iter()
634                    .map(|(span, gate)| {
635                        gate.map(|gate| {
636                            must_err = true;
637                            diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
638                        })
639                        .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
640                    })
641                    .collect(),
642            });
643
644            // If we should err, make sure we did.
645            if must_err && self.dcx().has_errors().is_none() {
646                // We have skipped a feature gate, and not run into other errors... reject.
647                guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
648            }
649        }
650        guar
651    }
652
653    /// Invoked all the way at the end to finish off diagnostics printing.
654    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
655        let mut guar = None;
656        guar = guar.or(self.check_miri_unleashed_features());
657        guar = guar.or(self.dcx().emit_stashed_diagnostics());
658        self.dcx().print_error_count();
659        if self.opts.json_future_incompat {
660            self.dcx().emit_future_breakage_report();
661        }
662        guar
663    }
664
665    /// Returns true if the crate is a testing one.
666    pub fn is_test_crate(&self) -> bool {
667        self.opts.test
668    }
669
670    /// `feature` must be a language feature.
671    #[track_caller]
672    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
673        let mut err = self.dcx().create_err(err);
674        if err.code.is_none() {
675            err.code(E0658);
676        }
677        diagnostics::add_feature_diagnostics(&mut err, self, feature);
678        err
679    }
680
681    /// Record the fact that we called `trimmed_def_paths`, and do some
682    /// checking about whether its cost was justified.
683    pub fn record_trimmed_def_paths(&self) {
684        if self.opts.unstable_opts.print_type_sizes
685            || self.opts.unstable_opts.query_dep_graph
686            || self.opts.unstable_opts.dump_mir.is_some()
687            || self.opts.unstable_opts.unpretty.is_some()
688            || self.prof.is_args_recording_enabled()
689            || self.opts.output_types.contains_key(&OutputType::Mir)
690            || std::env::var_os("RUSTC_LOG").is_some()
691        {
692            return;
693        }
694
695        self.dcx().set_must_produce_diag()
696    }
697
698    pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
699        // This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for
700        // AppendOnlyVec, so we resort to this scheme.
701        self.proc_macro_quoted_spans.iter_enumerated()
702    }
703
704    pub fn save_proc_macro_span(&self, span: Span) -> usize {
705        self.proc_macro_quoted_spans.push(span)
706    }
707
708    /// Returns `true` if internal lints should be added to the lint store - i.e. if
709    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
710    /// to be emitted under rustdoc).
711    pub fn enable_internal_lints(&self) -> bool {
712        self.unstable_options() && !self.opts.actually_rustdoc
713    }
714
715    pub fn instrument_coverage(&self) -> bool {
716        self.opts.cg.instrument_coverage() != InstrumentCoverage::No
717    }
718
719    pub fn instrument_coverage_branch(&self) -> bool {
720        self.instrument_coverage()
721            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
722    }
723
724    pub fn instrument_coverage_condition(&self) -> bool {
725        self.instrument_coverage()
726            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
727    }
728
729    /// Provides direct access to the `CoverageOptions` struct, so that
730    /// individual flags for debugging/testing coverage instrumetation don't
731    /// need separate accessors.
732    pub fn coverage_options(&self) -> &CoverageOptions {
733        &self.opts.unstable_opts.coverage_options
734    }
735
736    pub fn is_sanitizer_cfi_enabled(&self) -> bool {
737        self.sanitizers().contains(SanitizerSet::CFI)
738    }
739
740    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
741        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
742    }
743
744    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
745        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
746    }
747
748    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
749        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
750    }
751
752    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
753        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
754    }
755
756    pub fn is_sanitizer_cfi_recover_enabled(&self) -> bool {
757        self.opts.unstable_opts.sanitizer_cfi_recover == Some(true)
758    }
759
760    pub fn is_sanitizer_cfi_diag_enabled(&self) -> bool {
761        self.opts.unstable_opts.sanitizer_cfi_diag == Some(true)
762    }
763
764    pub fn is_sanitizer_cfi_minimal_runtime_enabled(&self) -> bool {
765        self.opts.unstable_opts.sanitizer_cfi_minimal_runtime == Some(true)
766    }
767
768    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
769        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
770    }
771
772    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
773        self.sanitizers().contains(SanitizerSet::KCFI)
774    }
775
776    pub fn is_split_lto_unit_enabled(&self) -> bool {
777        self.opts.unstable_opts.split_lto_unit == Some(true)
778    }
779
780    /// Check whether this compile session and crate type use static crt.
781    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
782        if !self.target.crt_static_respected {
783            // If the target does not opt in to crt-static support, use its default.
784            return self.target.crt_static_default;
785        }
786
787        let requested_features = self.opts.cg.target_feature.split(',');
788        let found_negative = requested_features.clone().any(|r| r == "-crt-static");
789        let found_positive = requested_features.clone().any(|r| r == "+crt-static");
790
791        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
792        #[allow(rustc::bad_opt_access)]
793        if found_positive || found_negative {
794            found_positive
795        } else if crate_type == Some(CrateType::ProcMacro)
796            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
797        {
798            // FIXME: When crate_type is not available,
799            // we use compiler options to determine the crate_type.
800            // We can't check `#![crate_type = "proc-macro"]` here.
801            false
802        } else {
803            self.target.crt_static_default
804        }
805    }
806
807    pub fn is_wasi_reactor(&self) -> bool {
808        self.target.options.os == Os::Wasi
809            && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
    {
    Some(config::WasiExecModel::Reactor) => true,
    _ => false,
}matches!(
810                self.opts.unstable_opts.wasi_exec_model,
811                Some(config::WasiExecModel::Reactor)
812            )
813    }
814
815    /// Returns `true` if the target can use the current split debuginfo configuration.
816    pub fn target_can_use_split_dwarf(&self) -> bool {
817        self.target.debuginfo_kind == DebuginfoKind::Dwarf
818    }
819
820    pub fn target_filesearch(&self) -> &filesearch::FileSearch {
821        &self.target_filesearch
822    }
823    pub fn host_filesearch(&self) -> &filesearch::FileSearch {
824        &self.host_filesearch
825    }
826    pub fn wasm_proc_macro_filesearch(&self) -> &filesearch::FileSearch {
827        self.wasm_proc_macro_filesearch.as_ref().expect("wasm_filesearch not set")
828    }
829
830    /// Returns a list of directories where target-specific tool binaries are located. Some fallback
831    /// directories are also returned, for example if `--sysroot` is used but tools are missing
832    /// (#125246): we also add the bin directories to the sysroot where rustc is located.
833    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
834        let search_paths = self
835            .opts
836            .sysroot
837            .all_paths()
838            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
839
840        if self_contained {
841            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the
842            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the
843            // fallback paths.
844            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
845        } else {
846            search_paths.collect()
847        }
848    }
849
850    /// Is this edition 2015?
851    pub fn is_rust_2015(&self) -> bool {
852        self.edition().is_rust_2015()
853    }
854
855    /// Are we allowed to use features from the Rust 2018 edition?
856    pub fn at_least_rust_2018(&self) -> bool {
857        self.edition().at_least_rust_2018()
858    }
859
860    /// Are we allowed to use features from the Rust 2021 edition?
861    pub fn at_least_rust_2021(&self) -> bool {
862        self.edition().at_least_rust_2021()
863    }
864
865    /// Are we allowed to use features from the Rust 2024 edition?
866    pub fn at_least_rust_2024(&self) -> bool {
867        self.edition().at_least_rust_2024()
868    }
869
870    /// Returns `true` if we should use the PLT for shared library calls.
871    pub fn needs_plt(&self) -> bool {
872        // Check if the current target usually wants PLT to be enabled.
873        // The user can use the command line flag to override it.
874        let want_plt = self.target.plt_by_default;
875
876        let dbg_opts = &self.opts.unstable_opts;
877
878        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
879
880        // Only enable this optimization by default if full relro is also enabled.
881        // In this case, lazy binding was already unavailable, so nothing is lost.
882        // This also ensures `-Wl,-z,now` is supported by the linker.
883        let full_relro = RelroLevel::Full == relro_level;
884
885        // If user didn't explicitly forced us to use / skip the PLT,
886        // then use it unless the target doesn't want it by default or the full relro forces it on.
887        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
888    }
889
890    /// Checks if LLVM lifetime markers should be emitted.
891    pub fn emit_lifetime_markers(&self) -> bool {
892        self.opts.optimize != config::OptLevel::No
893        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
894        //
895        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
896        //
897        // HWAddressSanitizer and KernelHWAddressSanitizer will use lifetimes to detect use after
898        // scope bugs in the future.
899        || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
900        // Lifetimes are necessary for retagging semantics.
901        || self.opts.unstable_opts.codegen_emit_retag.is_some()
902    }
903
904    pub fn diagnostic_width(&self) -> usize {
905        let default_column_width = 140;
906        if let Some(width) = self.opts.diagnostic_width {
907            width
908        } else if self.opts.unstable_opts.ui_testing {
909            default_column_width
910        } else {
911            termize::dimensions().map_or(default_column_width, |(w, _)| w)
912        }
913    }
914
915    /// Returns the default symbol visibility.
916    pub fn default_visibility(&self) -> SymbolVisibility {
917        self.opts
918            .unstable_opts
919            .default_visibility
920            .or(self.target.options.default_visibility)
921            .unwrap_or(SymbolVisibility::Interposable)
922    }
923
924    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
925        if verbatim {
926            ("", "")
927        } else {
928            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
929        }
930    }
931
932    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
933        match self.lint_store {
934            Some(ref lint_store) => lint_store.lint_groups_iter(),
935            None => Box::new(std::iter::empty()),
936        }
937    }
938
939    /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
940    ///
941    /// This unifies the logic used for resolving `include_*!` and debugger visualizers.
942    pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PResult<'_, PathBuf> {
943        let path = path.into();
944
945        // Relative paths are resolved relative to the file in which they are found
946        // after macro expansion (that is, they are unhygienic).
947        if !path.is_absolute() {
948            let callsite = span.source_callsite();
949            let source_map = self.source_map();
950            let Some(mut base_path) = source_map.span_to_filename(callsite).into_local_path()
951            else {
952                return Err(self.dcx().create_err(diagnostics::ResolveRelativePath {
953                    span,
954                    path: source_map
955                        .filename_for_diagnostics(&source_map.span_to_filename(callsite))
956                        .to_string(),
957                }));
958            };
959            base_path.pop();
960            base_path.push(path);
961            Ok(base_path)
962        } else {
963            // This ensures that Windows verbatim paths are fixed if mixed path separators are used,
964            // which can happen when `concat!` is used to join paths.
965            match path.components().next() {
966                Some(Prefix(prefix)) if prefix.kind().is_verbatim() => {
967                    Ok(path.components().collect())
968                }
969                _ => Ok(path),
970            }
971        }
972    }
973
974    /// Should metadata be embedded within .rlib and .dylib files?
975    pub fn embed_metadata(&self) -> bool {
976        self.opts.cg.embed_metadata.or(self.opts.unstable_opts.embed_metadata).unwrap_or(true)
977    }
978}
979
980// JUSTIFICATION: defn of the suggested wrapper fns
981#[allow(rustc::bad_opt_access)]
982impl Session {
983    pub fn verbose_internals(&self) -> bool {
984        self.opts.unstable_opts.verbose_internals
985    }
986
987    pub fn verify_llvm_ir(&self) -> bool {
988        self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
989    }
990
991    pub fn binary_dep_depinfo(&self) -> bool {
992        self.opts.unstable_opts.binary_dep_depinfo
993    }
994
995    pub fn mir_opt_level(&self) -> usize {
996        self.opts.unstable_opts.mir_opt_level.unwrap_or_else(|| self.opts.optimize.mir_opt_level())
997    }
998
999    /// What this compilation optimizes for; see [`config::OptimizationObjective`].
1000    pub fn optimization_objective(&self) -> config::OptimizationObjective {
1001        self.opts.optimize.objective()
1002    }
1003
1004    /// Calculates the flavor of LTO to use for this compilation.
1005    pub fn lto(&self) -> config::Lto {
1006        // If our target has codegen requirements ignore the command line
1007        if self.target.requires_lto {
1008            return config::Lto::Fat;
1009        }
1010
1011        // If the user specified something, return that. If they only said `-C
1012        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
1013        // then ensure we can't use a ThinLTO.
1014        match self.opts.cg.lto {
1015            config::LtoCli::Unspecified => {
1016                // The compiler was invoked without the `-Clto` flag. Fall
1017                // through to the default handling
1018            }
1019            config::LtoCli::No => {
1020                // The user explicitly opted out of any kind of LTO
1021                return config::Lto::No;
1022            }
1023            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
1024                // All of these mean fat LTO
1025                return config::Lto::Fat;
1026            }
1027            config::LtoCli::Thin => {
1028                // The user explicitly asked for ThinLTO
1029                if !self.thin_lto_supported {
1030                    // Backend doesn't support ThinLTO, fallback to fat LTO.
1031                    self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
1032                    return config::Lto::Fat;
1033                }
1034                return config::Lto::Thin;
1035            }
1036        }
1037
1038        if !self.thin_lto_supported {
1039            return config::Lto::No;
1040        }
1041
1042        // Ok at this point the target doesn't require anything and the user
1043        // hasn't asked for anything. Our next decision is whether or not
1044        // we enable "auto" ThinLTO where we use multiple codegen units and
1045        // then do ThinLTO over those codegen units. The logic below will
1046        // either return `No` or `ThinLocal`.
1047
1048        // If processing command line options determined that we're incompatible
1049        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
1050        if self.opts.cli_forced_local_thinlto_off {
1051            return config::Lto::No;
1052        }
1053
1054        // If `-Z thinlto` specified process that, but note that this is mostly
1055        // a deprecated option now that `-C lto=thin` exists.
1056        if let Some(enabled) = self.opts.unstable_opts.thinlto {
1057            if enabled {
1058                return config::Lto::ThinLocal;
1059            } else {
1060                return config::Lto::No;
1061            }
1062        }
1063
1064        // If there's only one codegen unit and LTO isn't enabled then there's
1065        // no need for ThinLTO so just return false.
1066        if self.codegen_units().as_usize() == 1 {
1067            return config::Lto::No;
1068        }
1069
1070        // Now we're in "defaults" territory. By default we enable ThinLTO for
1071        // optimized compiles (anything greater than O0).
1072        match self.opts.optimize {
1073            config::OptLevel::No => config::Lto::No,
1074            _ => config::Lto::ThinLocal,
1075        }
1076    }
1077
1078    pub fn fewer_names(&self) -> bool {
1079        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1080            fewer_names
1081        } else {
1082            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1083                || self.opts.output_types.contains_key(&OutputType::Bitcode)
1084                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1085                || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1086            !more_names
1087        }
1088    }
1089
1090    pub fn unstable_options(&self) -> bool {
1091        self.opts.unstable_opts.unstable_options
1092    }
1093
1094    pub fn is_nightly_build(&self) -> bool {
1095        self.opts.unstable_features.is_nightly_build()
1096    }
1097
1098    pub fn overflow_checks(&self) -> bool {
1099        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1100    }
1101
1102    pub fn ub_checks(&self) -> bool {
1103        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
1104    }
1105
1106    pub fn contract_checks(&self) -> bool {
1107        self.opts.unstable_opts.contract_checks.unwrap_or(false)
1108    }
1109
1110    pub fn direct_access_external_data(&self) -> Option<bool> {
1111        self.opts
1112            .unstable_opts
1113            .direct_access_external_data
1114            .or(self.target.direct_access_external_data)
1115    }
1116
1117    pub fn split_debuginfo(&self) -> SplitDebuginfo {
1118        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1119    }
1120
1121    /// Returns the DWARF version passed on the CLI or the default for the target.
1122    pub fn dwarf_version(&self) -> u32 {
1123        self.opts
1124            .cg
1125            .dwarf_version
1126            .or(self.opts.unstable_opts.dwarf_version)
1127            .unwrap_or(self.target.default_dwarf_version)
1128    }
1129
1130    pub fn stack_protector(&self) -> StackProtector {
1131        if self.target.options.supports_stack_protector {
1132            self.opts.unstable_opts.stack_protector
1133        } else {
1134            StackProtector::None
1135        }
1136    }
1137
1138    /// Returns the `-Zbranch-protection` info. Note that it is adjusted to the current target, e.g.
1139    /// some targets only support certain Pointer Authentication Code keys.
1140    ///
1141    /// Accessing the session's unstable `branch_protection` option fields directly is linted
1142    /// against.
1143    pub fn branch_protection(&self) -> Option<BranchProtection> {
1144        let mut bp = self.opts.unstable_opts.branch_protection;
1145
1146        if let Some(bp) = bp.as_mut() {
1147            // Windows on Arm only supports PAC Key B for return address signing, as shown in
1148            // https://github.com/llvm/llvm-project/pull/203989. We parse the CLI flags for branch
1149            // protection and target separately though, so we adjust this possible discrepancy here.
1150            if self.target.os == Os::Windows && self.target.arch == Arch::AArch64 {
1151                if let Some(pac_ret) = bp.pac_ret.as_mut()
1152                    && pac_ret.key == PAuthKey::A
1153                {
1154                    pac_ret.key = PAuthKey::B;
1155                }
1156            }
1157        }
1158
1159        bp
1160    }
1161
1162    pub fn must_emit_unwind_tables(&self) -> bool {
1163        // This is used to control the emission of the `uwtable` attribute on
1164        // LLVM functions. The `uwtable` attribute according to LLVM is:
1165        //
1166        //     This attribute indicates that the ABI being targeted requires that an
1167        //     unwind table entry be produced for this function even if we can show
1168        //     that no exceptions passes by it. This is normally the case for the
1169        //     ELF x86-64 abi, but it can be disabled for some compilation units.
1170        //
1171        // Typically when we're compiling with `-C panic=abort` we don't need
1172        // `uwtable` because we can't generate any exceptions! But note that
1173        // some targets require unwind tables to generate backtraces.
1174        // Unwind tables are needed when compiling with `-C panic=unwind`, but
1175        // LLVM won't omit unwind tables unless the function is also marked as
1176        // `nounwind`, so users are allowed to disable `uwtable` emission.
1177        // Historically rustc always emits `uwtable` attributes by default, so
1178        // even they can be disabled, they're still emitted by default.
1179        //
1180        // On some targets (including windows), however, exceptions include
1181        // other events such as illegal instructions, segfaults, etc. This means
1182        // that on Windows we end up still needing unwind tables even if the `-C
1183        // panic=abort` flag is passed.
1184        //
1185        // You can also find more info on why Windows needs unwind tables in:
1186        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1187        //
1188        // If a target requires unwind tables, then they must be emitted.
1189        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1190        // value, if it is provided, or disable them, if not.
1191        self.target.requires_uwtable
1192            || self
1193                .opts
1194                .cg
1195                .force_unwind_tables
1196                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1197    }
1198
1199    /// Returns the number of codegen units that should be used for this
1200    /// compilation
1201    pub fn codegen_units(&self) -> CodegenUnits {
1202        if let Some(n) = self.opts.cli_forced_codegen_units {
1203            return CodegenUnits::User(n);
1204        }
1205        if let Some(n) = self.target.default_codegen_units {
1206            return CodegenUnits::Default(n as usize);
1207        }
1208
1209        // If incremental compilation is turned on, we default to a high number
1210        // codegen units in order to reduce the "collateral damage" small
1211        // changes cause.
1212        if self.opts.incremental.is_some() {
1213            return CodegenUnits::Default(256);
1214        }
1215
1216        // Why is 16 codegen units the default all the time?
1217        //
1218        // The main reason for enabling multiple codegen units by default is to
1219        // leverage the ability for the codegen backend to do codegen and
1220        // optimization in parallel. This allows us, especially for large crates, to
1221        // make good use of all available resources on the machine once we've
1222        // hit that stage of compilation. Large crates especially then often
1223        // take a long time in codegen/optimization and this helps us amortize that
1224        // cost.
1225        //
1226        // Note that a high number here doesn't mean that we'll be spawning a
1227        // large number of threads in parallel. The backend of rustc contains
1228        // global rate limiting through the `jobserver` crate so we'll never
1229        // overload the system with too much work, but rather we'll only be
1230        // optimizing when we're otherwise cooperating with other instances of
1231        // rustc.
1232        //
1233        // Rather a high number here means that we should be able to keep a lot
1234        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1235        // to build we'll be guaranteed that all cpus will finish pretty closely
1236        // to one another and we should make relatively optimal use of system
1237        // resources
1238        //
1239        // Note that the main cost of codegen units is that it prevents LLVM
1240        // from inlining across codegen units. Users in general don't have a lot
1241        // of control over how codegen units are split up so it's our job in the
1242        // compiler to ensure that undue performance isn't lost when using
1243        // codegen units (aka we can't require everyone to slap `#[inline]` on
1244        // everything).
1245        //
1246        // If we're compiling at `-O0` then the number doesn't really matter too
1247        // much because performance doesn't matter and inlining is ok to lose.
1248        // In debug mode we just want to try to guarantee that no cpu is stuck
1249        // doing work that could otherwise be farmed to others.
1250        //
1251        // In release mode, however (O1 and above) performance does indeed
1252        // matter! To recover the loss in performance due to inlining we'll be
1253        // enabling ThinLTO by default (the function for which is just below).
1254        // This will ensure that we recover any inlining wins we otherwise lost
1255        // through codegen unit partitioning.
1256        //
1257        // ---
1258        //
1259        // Ok that's a lot of words but the basic tl;dr; is that we want a high
1260        // number here -- but not too high. Additionally we're "safe" to have it
1261        // always at the same number at all optimization levels.
1262        //
1263        // As a result 16 was chosen here! Mostly because it was a power of 2
1264        // and most benchmarks agreed it was roughly a local optimum. Not very
1265        // scientific.
1266        CodegenUnits::Default(16)
1267    }
1268
1269    pub fn teach(&self, code: ErrCode) -> bool {
1270        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1271    }
1272
1273    pub fn edition(&self) -> Edition {
1274        self.opts.edition
1275    }
1276
1277    pub fn link_dead_code(&self) -> bool {
1278        self.opts.cg.link_dead_code.unwrap_or(false)
1279    }
1280
1281    pub fn sanitizers(&self) -> SanitizerSet {
1282        self.sanitizers
1283    }
1284
1285    pub fn pointer_authentication(&self) -> bool {
1286        self.pointer_auth_config.is_some()
1287    }
1288
1289    pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1290        self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1291    }
1292
1293    pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1294        self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1295    }
1296}
1297
1298// JUSTIFICATION: part of session construction
1299#[allow(rustc::bad_opt_access)]
1300fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1301    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1302    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1303    let terminal_url = match sopts.unstable_opts.terminal_urls {
1304        TerminalUrl::Auto => {
1305            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1306                (Ok("truecolor"), Ok("xterm-256color"))
1307                    if sopts.unstable_features.is_nightly_build() =>
1308                {
1309                    TerminalUrl::Yes
1310                }
1311                _ => TerminalUrl::No,
1312            }
1313        }
1314        t => t,
1315    };
1316
1317    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1318
1319    match sopts.error_format {
1320        ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1321            HumanReadableErrorType { no_graphics, short, unicode } => {
1322                let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1323                    .sm(source_map)
1324                    .short_message(short)
1325                    .diagnostic_width(sopts.diagnostic_width)
1326                    .macro_backtrace(macro_backtrace)
1327                    .track_diagnostics(track_diagnostics)
1328                    .terminal_url(terminal_url)
1329                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1330                    .ignored_directories_in_source_blocks(
1331                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1332                    )
1333                    .no_graphics(no_graphics);
1334                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1335            }
1336        },
1337        ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1338            JsonEmitter::new(
1339                Box::new(io::BufWriter::new(io::stderr())),
1340                source_map,
1341                pretty,
1342                json_rendered,
1343                color_config,
1344            )
1345            .ui_testing(sopts.unstable_opts.ui_testing)
1346            .ignored_directories_in_source_blocks(
1347                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1348            )
1349            .diagnostic_width(sopts.diagnostic_width)
1350            .macro_backtrace(macro_backtrace)
1351            .track_diagnostics(track_diagnostics)
1352            .terminal_url(terminal_url),
1353        ),
1354    }
1355}
1356
1357// JUSTIFICATION: literally session construction
1358#[allow(rustc::bad_opt_access)]
1359pub fn build_early_session(
1360    sopts: config::Options,
1361    target: Target,
1362    ice_file: Option<PathBuf>,
1363) -> EarlySession {
1364    // FIXME: This is not general enough to make the warning lint completely override
1365    // normal diagnostic warnings, since the warning lint can also be denied and changed
1366    // later via the source code.
1367    let warnings_allow = sopts
1368        .lint_opts
1369        .iter()
1370        .rfind(|&(key, _)| *key == "warnings")
1371        .is_some_and(|&(_, level)| level == lint::Allow);
1372    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1373    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1374
1375    let source_map = rustc_span::source_map::get_source_map().unwrap();
1376    let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1377
1378    let mut dcx =
1379        DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1380    if let Some(ice_file) = ice_file {
1381        dcx = dcx.with_ice_file(ice_file);
1382    }
1383
1384    if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1385        dcx = dcx.with_msrv(msrv);
1386    }
1387
1388    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1389    let (host, target_warnings) =
1390        Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1391            .unwrap_or_else(|e| {
1392                dcx.handle().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading host specification: {0}",
                e))
    })format!("Error loading host specification: {e}"))
1393            });
1394    for warning in target_warnings.warning_messages() {
1395        dcx.handle().warn(warning)
1396    }
1397
1398    let psess = ParseSess::with_dcx(dcx, source_map);
1399
1400    EarlySession { target, host, opts: sopts, psess }
1401}
1402
1403// JUSTIFICATION: literally session construction
1404#[allow(rustc::bad_opt_access)]
1405pub fn build_session(
1406    early_sess: EarlySession,
1407    codegen_backend_init: CodegenBackendInit,
1408    io: CompilerIO,
1409    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1410    cfg_version: &'static str,
1411    using_internal_features: &'static AtomicBool,
1412) -> Session {
1413    let EarlySession { target, host, opts: sopts, psess } = &early_sess;
1414    let dcx = psess.dcx();
1415
1416    let wasm_proc_macro_tuple = TargetTuple::from_tuple("wasm32-wasip2");
1417    let (wasm_proc_macro_target, target_warnings) = Target::search(
1418        &wasm_proc_macro_tuple,
1419        sopts.sysroot.path(),
1420        sopts.unstable_opts.unstable_options,
1421    )
1422    .unwrap_or_else(|e| {
1423        dcx.fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading wasm proc-macro target specification: {0}",
                e))
    })format!("Error loading wasm proc-macro target specification: {e}"))
1424    });
1425    for warning in target_warnings.warning_messages() {
1426        dcx.warn(warning)
1427    }
1428
1429    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1430    {
1431        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1432
1433        let profiler = SelfProfiler::new(
1434            directory,
1435            sopts.crate_name.as_deref(),
1436            sopts.unstable_opts.self_profile_events.as_deref(),
1437            &sopts.unstable_opts.self_profile_counter,
1438        );
1439        match profiler {
1440            Ok(profiler) => Some(Arc::new(profiler)),
1441            Err(e) => {
1442                dcx.emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1443                None
1444            }
1445        }
1446    } else {
1447        None
1448    };
1449
1450    let host_triple = config::host_tuple();
1451    let target_triple = sopts.target_triple.tuple();
1452    // FIXME use host sysroot?
1453    let host_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple);
1454    let target_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple);
1455    let wasm_proc_macro_tlib_path =
1456        SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), wasm_proc_macro_tuple.tuple());
1457
1458    let prof = SelfProfilerRef::new(
1459        self_profiler,
1460        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1461    );
1462
1463    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1464        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1465        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1466        _ => CtfeBacktrace::Disabled,
1467    });
1468
1469    let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1470    let target_filesearch = Arc::new(filesearch::FileSearch::new(
1471        &sopts.search_paths,
1472        &target_tlib_path,
1473        &target,
1474        sopts.unstable_opts.implicit_sysroot_deps,
1475    ));
1476    let host_filesearch = if target == host {
1477        Arc::clone(&target_filesearch)
1478    } else {
1479        Arc::new(filesearch::FileSearch::new(
1480            &sopts.search_paths,
1481            &host_tlib_path,
1482            &host,
1483            sopts.unstable_opts.implicit_sysroot_deps,
1484        ))
1485    };
1486    let wasm_proc_macro_filesearch = if sopts.unstable_opts.wasm_proc_macros {
1487        Some(Arc::new(FileSearch::new(
1488            &sopts.search_paths,
1489            &wasm_proc_macro_tlib_path,
1490            &wasm_proc_macro_target,
1491            sopts.unstable_opts.implicit_sysroot_deps,
1492        )))
1493    } else {
1494        None
1495    };
1496
1497    let timings = TimingSectionHandler::new(sopts.json_timings);
1498
1499    let pointer_auth_config: Option<PointerAuthConfig> =
1500        PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1501
1502    // `EarlySess::sanitizers` does some computation but is called infrequently. `Sess::sanitizers`
1503    // is called much more often so we cache the value.
1504    let sanitizers = early_sess.sanitizers();
1505
1506    let CodegenBackendInit {
1507        global_backend_features,
1508        replaced_rustc_intrinsics: replaced_intrinsics,
1509        fallback_rustc_intrinsics: fallback_intrinsics,
1510        thin_lto_supported,
1511    } = codegen_backend_init;
1512
1513    let sess = Session {
1514        early_sess,
1515        wasm_proc_macro_tuple,
1516        wasm_proc_macro_target,
1517        target_tlib_path,
1518        unstable_features: UnstableFeatures::from_environment(None),
1519        config: Cfg::default(),
1520        check_config: CheckCfg::default(),
1521        proc_macro_quoted_spans: Default::default(),
1522        io,
1523        prof,
1524        timings,
1525        code_stats: Default::default(),
1526        lint_store: None,
1527        driver_lint_caps,
1528        ctfe_backtrace,
1529        miri_unleashed_features: Lock::new(Default::default()),
1530        asm_arch,
1531        internal_target_features: Default::default(),
1532        global_backend_features,
1533        cfg_version,
1534        using_internal_features,
1535        env_depinfo: Default::default(),
1536        file_depinfo: Default::default(),
1537        target_filesearch,
1538        host_filesearch,
1539        wasm_proc_macro_filesearch,
1540        replaced_rustc_intrinsics: FxHashSet::from_iter(replaced_intrinsics),
1541        fallback_rustc_intrinsics: FxHashSet::from_iter(fallback_intrinsics),
1542        thin_lto_supported,
1543        mir_opt_bisect_eval_count: AtomicUsize::new(0),
1544        removed_rustc_main_attr: AtomicBool::new(false),
1545        pointer_auth_config,
1546        sanitizers,
1547    };
1548
1549    validate_commandline_args_with_session_available(&sess);
1550
1551    sess
1552}
1553
1554pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1555    ::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())
1556}
1557
1558/// Validate command line arguments with a `Session`.
1559///
1560/// If it is useful to have a Session available already for validating a commandline argument, you
1561/// can do so here.
1562// JUSTIFICATION: needs to access args to validate them
1563#[allow(rustc::bad_opt_access)]
1564fn validate_commandline_args_with_session_available(sess: &Session) {
1565    // Since we don't know if code in an rlib will be linked to statically or
1566    // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1567    // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1568    // these manually generated symbols confuse LLD when it tries to merge
1569    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1570    // when compiling for LLD ThinLTO. This way we can validly just not generate
1571    // the `dllimport` attributes and `__imp_` symbols in that case.
1572    if sess.opts.cg.linker_plugin_lto.enabled()
1573        && sess.opts.cg.prefer_dynamic
1574        && sess.target.is_like_windows
1575    {
1576        sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1577    }
1578
1579    if sess
1580        .pointer_auth_config
1581        .as_ref()
1582        .and_then(|cfg| cfg.function_pointers.as_ref())
1583        .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
    PointerAuthDiscrimination::Type => true,
    _ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1584    {
1585        sess.dcx().emit_err(
1586            diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1587                target_triple: &sess.opts.target_triple,
1588            },
1589        );
1590    }
1591
1592    if sess.target.cfg_abi != CfgAbi::Pauthtest
1593        && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1594    {
1595        sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1596            target_triple: &sess.opts.target_triple,
1597        });
1598    }
1599
1600    // Make sure that any given profiling data actually exists so LLVM can't
1601    // decide to silently skip PGO.
1602    if let Some(ref path) = sess.opts.cg.profile_use {
1603        if !path.exists() {
1604            sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1605        }
1606    }
1607
1608    // Do the same for sample profile data.
1609    if let Some(ref path) = sess.opts.cg.profile_sample_use {
1610        if !path.exists() {
1611            sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1612        }
1613    }
1614
1615    // Unwind tables cannot be disabled if the target requires them.
1616    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1617        if sess.target.requires_uwtable && !include_uwtables {
1618            sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1619        }
1620    }
1621
1622    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1623    let supported_sanitizers = sess.target.options.supported_sanitizers;
1624    let mut unsupported_sanitizers = sess.sanitizers() - supported_sanitizers;
1625    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled
1626    // we should allow Shadow Call Stack sanitizer.
1627    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1628        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1629    }
1630    match unsupported_sanitizers.into_iter().count() {
1631        0 => {}
1632        1 => {
1633            sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1634                us: unsupported_sanitizers.to_string(),
1635            });
1636        }
1637        _ => {
1638            sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1639                us: unsupported_sanitizers.to_string(),
1640            });
1641        }
1642    }
1643
1644    // Cannot mix and match mutually-exclusive sanitizers.
1645    if let Some((first, second)) = sess.sanitizers().mutually_exclusive() {
1646        sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1647            first: first.to_string(),
1648            second: second.to_string(),
1649        });
1650    }
1651
1652    // Cannot enable crt-static with sanitizers on Linux
1653    if sess.crt_static(None) && !sess.sanitizers().is_empty() && !sess.target.is_like_msvc {
1654        sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1655    }
1656
1657    // FIXME(jchlanda) Pauthtest does not support static linking. It must be dynamically linked,
1658    // with a dynamic linker acting as the ELF interpreter that can resolve pauth relocations and
1659    // enforce pointer authentication constraints.
1660    if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1661        sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1662    }
1663
1664    // LLVM CFI requires LTO.
1665    if sess.is_sanitizer_cfi_enabled()
1666        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1667    {
1668        sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1669    }
1670
1671    // KCFI requires panic=abort
1672    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1673        sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1674    }
1675
1676    // LLVM CFI using rustc LTO requires a single codegen unit.
1677    if sess.is_sanitizer_cfi_enabled()
1678        && sess.lto() == config::Lto::Fat
1679        && (sess.codegen_units().as_usize() != 1)
1680    {
1681        sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1682    }
1683
1684    // Canonical jump tables requires CFI.
1685    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1686        if !sess.is_sanitizer_cfi_enabled() {
1687            sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1688        }
1689    }
1690
1691    // KCFI arity indicator requires KCFI.
1692    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1693        sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1694    }
1695
1696    // LLVM CFI pointer generalization requires CFI or KCFI.
1697    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1698        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1699            sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1700        }
1701    }
1702
1703    // LLVM CFI recovery requires CFI.
1704    if sess.is_sanitizer_cfi_recover_enabled() {
1705        if !sess.is_sanitizer_cfi_enabled() {
1706            sess.dcx().emit_err(diagnostics::SanitizerCfiRecoverRequiresCfi);
1707        }
1708    }
1709
1710    // LLVM CFI diagnostics requires CFI.
1711    if sess.is_sanitizer_cfi_diag_enabled() {
1712        if !sess.is_sanitizer_cfi_enabled() {
1713            sess.dcx().emit_err(diagnostics::SanitizerCfiDiagRequiresCfi);
1714        }
1715    }
1716
1717    // LLVM CFI minimal runtime requires CFI recovery or CFI diagnostics.
1718    if sess.is_sanitizer_cfi_minimal_runtime_enabled() {
1719        if !sess.is_sanitizer_cfi_enabled() {
1720            sess.dcx().emit_err(diagnostics::SanitizerCfiMinimalRuntimeRequiresCfi);
1721        } else if !(sess.is_sanitizer_cfi_recover_enabled() || sess.is_sanitizer_cfi_diag_enabled())
1722        {
1723            sess.dcx().emit_err(diagnostics::SanitizerCfiMinimalRuntimeRequiresCfiRecoverOrDiag);
1724        }
1725    }
1726
1727    // LLVM CFI integer normalization requires CFI or KCFI.
1728    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1729        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1730            sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1731        }
1732    }
1733
1734    // LTO unit splitting requires LTO.
1735    if sess.is_split_lto_unit_enabled()
1736        && !(sess.lto() == config::Lto::Fat
1737            || sess.lto() == config::Lto::Thin
1738            || sess.opts.cg.linker_plugin_lto.enabled())
1739    {
1740        sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1741    }
1742
1743    // VFE requires LTO.
1744    if sess.lto() != config::Lto::Fat {
1745        if sess.opts.unstable_opts.virtual_function_elimination {
1746            sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1747        }
1748    }
1749
1750    if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1751        if !sess.target.options.supports_stack_protector {
1752            sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1753                stack_protector: sess.opts.unstable_opts.stack_protector,
1754                target_triple: &sess.opts.target_triple,
1755            });
1756        }
1757    }
1758
1759    if sess.opts.unstable_opts.small_data_threshold.is_some() {
1760        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1761            sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1762                target_triple: &sess.opts.target_triple,
1763            })
1764        }
1765    }
1766
1767    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1768        sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1769    }
1770
1771    if let Some(dwarf_version) =
1772        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1773    {
1774        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.
1775        if dwarf_version < 2 || dwarf_version > 5 {
1776            sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1777        }
1778    }
1779
1780    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1781        && !sess.opts.unstable_opts.unstable_options
1782    {
1783        sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1784            debuginfo: sess.split_debuginfo(),
1785        });
1786    }
1787
1788    if sess.opts.unstable_opts.embed_source {
1789        let dwarf_version = sess.dwarf_version();
1790
1791        if dwarf_version < 5 {
1792            sess.dcx()
1793                .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1794        }
1795
1796        if sess.opts.debuginfo == DebugInfo::None {
1797            sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1798        }
1799    }
1800
1801    if let InstrumentMcount::Fentry(opts) = sess.opts.unstable_opts.instrument_mcount {
1802        if !sess.target.options.supports_fentry {
1803            sess.dcx()
1804                .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1805        }
1806        if (opts.no_call || opts.record) && sess.target.arch != Arch::S390x {
1807            sess.dcx()
1808                .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry-*".to_string() });
1809        }
1810    }
1811
1812    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1813        sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1814    }
1815
1816    if let Some(flavor) = sess.opts.cg.linker_flavor
1817        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1818    {
1819        let flavor = flavor.desc();
1820        sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1821    }
1822
1823    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1824        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) {
1825            sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1826        }
1827    }
1828
1829    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1830        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) {
1831            sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1832        }
1833    }
1834
1835    if let Some(regparm) = sess.opts.unstable_opts.regparm {
1836        if regparm > 3 {
1837            sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1838        }
1839        if sess.target.arch != Arch::X86 {
1840            sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1841        }
1842    }
1843    if sess.opts.unstable_opts.reg_struct_return {
1844        if sess.target.arch != Arch::X86 {
1845            sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1846        }
1847    }
1848
1849    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1850    // kept as a `match` to force a change if new ones are added, even if we currently only support
1851    // `thunk-extern` like Clang.
1852    match sess.opts.unstable_opts.function_return {
1853        FunctionReturn::Keep => (),
1854        FunctionReturn::ThunkExtern => {
1855            // FIXME: In principle, the inherited base LLVM target code model could be large,
1856            // but this only checks whether we were passed one explicitly (like Clang does).
1857            if let Some(code_model) = sess.code_model()
1858                && code_model == CodeModel::Large
1859            {
1860                sess.dcx()
1861                    .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1862            }
1863        }
1864    }
1865
1866    if sess.opts.unstable_opts.packed_stack {
1867        if sess.target.arch != Arch::S390x {
1868            sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1869        }
1870    }
1871
1872    match sess.opts.unstable_opts.pack_coroutine_layout {
1873        PackCoroutineLayout::Classic => {}
1874        PackCoroutineLayout::CapturesOnly => {
1875            sess.dcx().emit_warn(diagnostics::PackCoroutineLayoutNotImplemented);
1876        }
1877    }
1878
1879    if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1880        if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1881            sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1882                target_triple: &sess.opts.target_triple,
1883                need_explicit_cpu: sess.target.need_explicit_cpu,
1884            });
1885        }
1886    }
1887}
1888
1889/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1890pub struct EarlyDiagCtxt {
1891    dcx: DiagCtxt,
1892}
1893
1894impl EarlyDiagCtxt {
1895    pub fn new(output: ErrorOutputType) -> Self {
1896        let emitter = mk_emitter(output);
1897        Self { dcx: DiagCtxt::new(emitter) }
1898    }
1899
1900    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1901    /// format. If `early_err` was previously called this will panic.
1902    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1903        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());
1904
1905        let emitter = mk_emitter(output);
1906        self.dcx = DiagCtxt::new(emitter);
1907    }
1908
1909    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1910    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1911        self.dcx.handle().err(msg)
1912    }
1913
1914    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1915        self.dcx.handle().fatal(msg)
1916    }
1917
1918    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1919        self.dcx.handle().struct_fatal(msg)
1920    }
1921
1922    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1923        self.dcx.handle().warn(msg)
1924    }
1925
1926    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1927        self.dcx.handle().struct_warn(msg)
1928    }
1929}
1930
1931fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1932    let emitter: Box<DynEmitter> = match output {
1933        ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1934            HumanReadableErrorType { no_graphics, short, unicode } => Box::new(
1935                AnnotateSnippetEmitter::new(stderr_destination(color_config))
1936                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1937                    .short_message(short)
1938                    .no_graphics(no_graphics),
1939            ),
1940        },
1941        ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1942            Box::new(JsonEmitter::new(
1943                Box::new(io::BufWriter::new(io::stderr())),
1944                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1945                pretty,
1946                json_rendered,
1947                color_config,
1948            ))
1949        }
1950    };
1951    emitter
1952}