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