Skip to main content

rustc_session/
session.rs

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