Skip to main content

rustc_session/
session.rs

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