compiler/rustc_session/src/session.rs RUST 1,494 lines View on github.com → Search inside
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};78use rustc_data_structures::flock;9use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};10use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};11use rustc_data_structures::sync::{12    AppendOnlyVec, DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock,13};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_hir::limit::Limit;25use rustc_macros::StableHash;26pub use rustc_span::def_id::StableCrateId;27use rustc_span::edition::Edition;28use rustc_span::source_map::{FilePathMapping, SourceMap};29use rustc_span::{RealFileName, Span, Symbol};30use rustc_target::asm::InlineAsmArch;31use rustc_target::spec::{32    Arch, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,33    SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,34    TargetTuple, TlsModel, apple,35};3637use crate::code_stats::CodeStats;38pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};39use crate::config::{40    self, Cfg, CheckCfg, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType,41    FunctionReturn, Input, InstrumentCoverage, OptLevel, OutFileName, OutputType,42    SwitchWithOptPath,43};44use crate::filesearch::FileSearch;45use crate::lint::LintId;46use crate::parse::ParseSess;47use crate::search_paths::SearchPath;48use crate::{errors, filesearch, lint};4950/// The behavior of the CTFE engine when an error occurs with regards to backtraces.51#[derive(Clone, Copy)]52pub enum CtfeBacktrace {53    /// Do nothing special, return the error as usual without a backtrace.54    Disabled,55    /// Capture a backtrace at the point the error is created and return it in the error56    /// (to be printed later if/when the error ever actually gets shown to the user).57    Capture,58    /// Capture a backtrace at the point the error is created and immediately print it out.59    Immediate,60}6162#[derive(Clone, Copy, Debug, StableHash)]63pub struct Limits {64    /// The maximum recursion limit for potentially infinitely recursive65    /// operations such as auto-dereference and monomorphization.66    pub recursion_limit: Limit,67    /// The size at which the `large_assignments` lint starts68    /// being emitted.69    pub move_size_limit: Limit,70    /// The maximum length of types during monomorphization.71    pub type_length_limit: Limit,72    /// The maximum pattern complexity allowed (internal only).73    pub pattern_complexity_limit: Limit,74}7576pub struct CompilerIO {77    pub input: Input,78    pub output_dir: Option<PathBuf>,79    pub output_file: Option<OutFileName>,80    pub temps_dir: Option<PathBuf>,81}8283pub trait DynLintStore: Any + DynSync + DynSend {84    /// Provides a way to access lint groups without depending on `rustc_lint`85    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;86}8788/// Represents the data associated with a compilation89/// session for a single crate.90pub struct Session {91    pub target: Target,92    pub host: Target,93    pub opts: config::Options,94    pub target_tlib_path: Arc<SearchPath>,95    pub psess: ParseSess,96    pub unstable_features: UnstableFeatures,97    pub config: Cfg,98    pub check_config: CheckCfg,99    /// Spans passed to `proc_macro::quote_span`. Each span has a numerical100    /// identifier represented by its position in the vector.101    proc_macro_quoted_spans: AppendOnlyVec<Span>,102103    /// Input, input file path and output file path to this compilation process.104    pub io: CompilerIO,105106    incr_comp_session: RwLock<IncrCompSession>,107108    /// Used by `-Z self-profile`.109    pub prof: SelfProfilerRef,110111    /// Used to emit section timings events (enabled by `--json=timings`).112    pub timings: TimingSectionHandler,113114    /// Data about code being compiled, gathered during compilation.115    pub code_stats: CodeStats,116117    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.118    pub lint_store: Option<Arc<dyn DynLintStore>>,119120    /// Cap lint level specified by a driver specifically.121    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,122123    /// Tracks the current behavior of the CTFE engine when an error occurs.124    /// Options range from returning the error without a backtrace to returning an error125    /// and immediately printing the backtrace to stderr.126    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when127    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE128    /// errors.129    pub ctfe_backtrace: Lock<CtfeBacktrace>,130131    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a132    /// const check, optionally with the relevant feature gate. We use this to133    /// warn about unleashing, but with a single diagnostic instead of dozens that134    /// drown everything else in noise.135    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,136137    /// Architecture to use for interpreting asm!.138    pub asm_arch: Option<InlineAsmArch>,139140    /// Set of enabled features for the current target.141    pub target_features: FxIndexSet<Symbol>,142143    /// Set of enabled features for the current target, including unstable ones.144    pub unstable_target_features: FxIndexSet<Symbol>,145146    /// The version of the rustc process, possibly including a commit hash and description.147    pub cfg_version: &'static str,148149    /// The inner atomic value is set to true when a feature marked as `internal` is150    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with151    /// internal features are wontfix, and they are usually the cause of the ICEs.152    /// None signifies that this is not tracked.153    pub using_internal_features: &'static AtomicBool,154155    /// Environment variables accessed during the build and their values when they exist.156    pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,157158    /// File paths accessed during the build.159    pub file_depinfo: Lock<FxIndexSet<Symbol>>,160161    target_filesearch: FileSearch,162    host_filesearch: FileSearch,163164    /// The names of intrinsics that the current codegen backend replaces165    /// with its own implementations.166    pub replaced_intrinsics: FxHashSet<Symbol>,167    /// The names of intrinsics that the current codegen backend does *not* replace168    /// with its own implementations.169    pub fallback_intrinsics: FxHashSet<Symbol>,170171    /// Does the codegen backend support ThinLTO?172    pub thin_lto_supported: bool,173174    /// Global per-session counter for MIR optimization pass applications.175    ///176    /// Used by `-Zmir-opt-bisect-limit` to assign an index to each177    /// optimization-pass execution candidate during this compilation.178    pub mir_opt_bisect_eval_count: AtomicUsize,179180    /// Enabled features that are used in the current compilation.181    ///182    /// The value is the `DepNodeIndex` of the node encodes the used feature.183    pub used_features: Lock<FxHashMap<Symbol, u32>>,184185    /// Whether the test harness removed a user-written `#[rustc_main]` attribute186    /// while generating the synthetic test entry point.187    pub removed_rustc_main_attr: AtomicBool,188}189190#[derive(Clone, Copy)]191pub enum CodegenUnits {192    /// Specified by the user. In this case we try fairly hard to produce the193    /// number of CGUs requested.194    User(usize),195196    /// A default value, i.e. not specified by the user. In this case we take197    /// more liberties about CGU formation, e.g. avoid producing very small198    /// CGUs.199    Default(usize),200}201202impl CodegenUnits {203    pub fn as_usize(self) -> usize {204        match self {205            CodegenUnits::User(n) => n,206            CodegenUnits::Default(n) => n,207        }208    }209}210211pub struct LintGroup {212    pub name: &'static str,213    pub lints: Vec<LintId>,214    pub is_externally_loaded: bool,215}216217impl Session {218    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {219        self.miri_unleashed_features.lock().push((span, feature_gate));220    }221222    pub fn local_crate_source_file(&self) -> Option<RealFileName> {223        Some(224            self.source_map()225                .path_mapping()226                .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),227        )228    }229230    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {231        let mut guar = None;232        let unleashed_features = self.miri_unleashed_features.lock();233        if !unleashed_features.is_empty() {234            let mut must_err = false;235            // Create a diagnostic pointing at where things got unleashed.236            self.dcx().emit_warn(errors::SkippingConstChecks {237                unleashed_features: unleashed_features238                    .iter()239                    .map(|(span, gate)| {240                        gate.map(|gate| {241                            must_err = true;242                            errors::UnleashedFeatureHelp::Named { span: *span, gate }243                        })244                        .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })245                    })246                    .collect(),247            });248249            // If we should err, make sure we did.250            if must_err && self.dcx().has_errors().is_none() {251                // We have skipped a feature gate, and not run into other errors... reject.252                guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));253            }254        }255        guar256    }257258    /// Invoked all the way at the end to finish off diagnostics printing.259    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {260        let mut guar = None;261        guar = guar.or(self.check_miri_unleashed_features());262        guar = guar.or(self.dcx().emit_stashed_diagnostics());263        self.dcx().print_error_count();264        if self.opts.json_future_incompat {265            self.dcx().emit_future_breakage_report();266        }267        guar268    }269270    /// Returns true if the crate is a testing one.271    pub fn is_test_crate(&self) -> bool {272        self.opts.test273    }274275    /// `feature` must be a language feature.276    #[track_caller]277    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {278        let mut err = self.dcx().create_err(err);279        if err.code.is_none() {280            err.code(E0658);281        }282        errors::add_feature_diagnostics(&mut err, self, feature);283        err284    }285286    /// Record the fact that we called `trimmed_def_paths`, and do some287    /// checking about whether its cost was justified.288    pub fn record_trimmed_def_paths(&self) {289        if self.opts.unstable_opts.print_type_sizes290            || self.opts.unstable_opts.query_dep_graph291            || self.opts.unstable_opts.dump_mir.is_some()292            || self.opts.unstable_opts.unpretty.is_some()293            || self.prof.is_args_recording_enabled()294            || self.opts.output_types.contains_key(&OutputType::Mir)295            || std::env::var_os("RUSTC_LOG").is_some()296        {297            return;298        }299300        self.dcx().set_must_produce_diag()301    }302303    #[inline]304    pub fn dcx(&self) -> DiagCtxtHandle<'_> {305        self.psess.dcx()306    }307308    #[inline]309    pub fn source_map(&self) -> &SourceMap {310        self.psess.source_map()311    }312313    pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {314        // This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for315        // AppendOnlyVec, so we resort to this scheme.316        self.proc_macro_quoted_spans.iter_enumerated()317    }318319    pub fn save_proc_macro_span(&self, span: Span) -> usize {320        self.proc_macro_quoted_spans.push(span)321    }322323    /// Returns `true` if internal lints should be added to the lint store - i.e. if324    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors325    /// to be emitted under rustdoc).326    pub fn enable_internal_lints(&self) -> bool {327        self.unstable_options() && !self.opts.actually_rustdoc328    }329330    pub fn instrument_coverage(&self) -> bool {331        self.opts.cg.instrument_coverage() != InstrumentCoverage::No332    }333334    pub fn instrument_coverage_branch(&self) -> bool {335        self.instrument_coverage()336            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch337    }338339    pub fn instrument_coverage_condition(&self) -> bool {340        self.instrument_coverage()341            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition342    }343344    /// Provides direct access to the `CoverageOptions` struct, so that345    /// individual flags for debugging/testing coverage instrumetation don't346    /// need separate accessors.347    pub fn coverage_options(&self) -> &CoverageOptions {348        &self.opts.unstable_opts.coverage_options349    }350351    pub fn is_sanitizer_cfi_enabled(&self) -> bool {352        self.sanitizers().contains(SanitizerSet::CFI)353    }354355    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {356        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)357    }358359    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {360        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)361    }362363    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {364        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)365    }366367    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {368        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)369    }370371    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {372        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)373    }374375    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {376        self.sanitizers().contains(SanitizerSet::KCFI)377    }378379    pub fn is_split_lto_unit_enabled(&self) -> bool {380        self.opts.unstable_opts.split_lto_unit == Some(true)381    }382383    /// Check whether this compile session and crate type use static crt.384    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {385        if !self.target.crt_static_respected {386            // If the target does not opt in to crt-static support, use its default.387            return self.target.crt_static_default;388        }389390        let requested_features = self.opts.cg.target_feature.split(',');391        let found_negative = requested_features.clone().any(|r| r == "-crt-static");392        let found_positive = requested_features.clone().any(|r| r == "+crt-static");393394        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)395        #[allow(rustc::bad_opt_access)]396        if found_positive || found_negative {397            found_positive398        } else if crate_type == Some(CrateType::ProcMacro)399            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)400        {401            // FIXME: When crate_type is not available,402            // we use compiler options to determine the crate_type.403            // We can't check `#![crate_type = "proc-macro"]` here.404            false405        } else {406            self.target.crt_static_default407        }408    }409410    pub fn is_wasi_reactor(&self) -> bool {411        self.target.options.os == Os::Wasi412            && matches!(413                self.opts.unstable_opts.wasi_exec_model,414                Some(config::WasiExecModel::Reactor)415            )416    }417418    /// Returns `true` if the target can use the current split debuginfo configuration.419    pub fn target_can_use_split_dwarf(&self) -> bool {420        self.target.debuginfo_kind == DebuginfoKind::Dwarf421    }422423    pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {424        format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())425    }426427    pub fn target_filesearch(&self) -> &filesearch::FileSearch {428        &self.target_filesearch429    }430    pub fn host_filesearch(&self) -> &filesearch::FileSearch {431        &self.host_filesearch432    }433434    /// Returns a list of directories where target-specific tool binaries are located. Some fallback435    /// directories are also returned, for example if `--sysroot` is used but tools are missing436    /// (#125246): we also add the bin directories to the sysroot where rustc is located.437    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {438        let search_paths = self439            .opts440            .sysroot441            .all_paths()442            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));443444        if self_contained {445            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the446            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the447            // fallback paths.448            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()449        } else {450            search_paths.collect()451        }452    }453454    pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {455        let mut incr_comp_session = self.incr_comp_session.borrow_mut();456457        if let IncrCompSession::NotInitialized = *incr_comp_session {458        } else {459            panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)460        }461462        *incr_comp_session =463            IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };464    }465466    pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {467        let mut incr_comp_session = self.incr_comp_session.borrow_mut();468469        if let IncrCompSession::Active { .. } = *incr_comp_session {470        } else {471            panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);472        }473474        // Note: this will also drop the lock file, thus unlocking the directory.475        *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };476    }477478    pub fn mark_incr_comp_session_as_invalid(&self) {479        let mut incr_comp_session = self.incr_comp_session.borrow_mut();480481        let session_directory = match *incr_comp_session {482            IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),483            IncrCompSession::InvalidBecauseOfErrors { .. } => return,484            _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),485        };486487        // Note: this will also drop the lock file, thus unlocking the directory.488        *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };489    }490491    pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {492        let incr_comp_session = self.incr_comp_session.borrow();493        ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {494            IncrCompSession::NotInitialized => panic!(495                "trying to get session directory from `IncrCompSession`: {:?}",496                *incr_comp_session,497            ),498            IncrCompSession::Active { ref session_directory, .. }499            | IncrCompSession::Finalized { ref session_directory }500            | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {501                session_directory502            }503        })504    }505506    pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {507        self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())508    }509510    /// Is this edition 2015?511    pub fn is_rust_2015(&self) -> bool {512        self.edition().is_rust_2015()513    }514515    /// Are we allowed to use features from the Rust 2018 edition?516    pub fn at_least_rust_2018(&self) -> bool {517        self.edition().at_least_rust_2018()518    }519520    /// Are we allowed to use features from the Rust 2021 edition?521    pub fn at_least_rust_2021(&self) -> bool {522        self.edition().at_least_rust_2021()523    }524525    /// Are we allowed to use features from the Rust 2024 edition?526    pub fn at_least_rust_2024(&self) -> bool {527        self.edition().at_least_rust_2024()528    }529530    /// Returns `true` if we should use the PLT for shared library calls.531    pub fn needs_plt(&self) -> bool {532        // Check if the current target usually wants PLT to be enabled.533        // The user can use the command line flag to override it.534        let want_plt = self.target.plt_by_default;535536        let dbg_opts = &self.opts.unstable_opts;537538        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);539540        // Only enable this optimization by default if full relro is also enabled.541        // In this case, lazy binding was already unavailable, so nothing is lost.542        // This also ensures `-Wl,-z,now` is supported by the linker.543        let full_relro = RelroLevel::Full == relro_level;544545        // If user didn't explicitly forced us to use / skip the PLT,546        // then use it unless the target doesn't want it by default or the full relro forces it on.547        dbg_opts.plt.unwrap_or(want_plt || !full_relro)548    }549550    /// Checks if LLVM lifetime markers should be emitted.551    pub fn emit_lifetime_markers(&self) -> bool {552        self.opts.optimize != config::OptLevel::No553        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.554        //555        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.556        //557        // HWAddressSanitizer and KernelHWAddressSanitizer will use lifetimes to detect use after558        // scope bugs in the future.559        || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)560        // Lifetimes are necessary for retagging semantics.561        || self.opts.unstable_opts.codegen_emit_retag.is_some()562    }563564    pub fn diagnostic_width(&self) -> usize {565        let default_column_width = 140;566        if let Some(width) = self.opts.diagnostic_width {567            width568        } else if self.opts.unstable_opts.ui_testing {569            default_column_width570        } else {571            termize::dimensions().map_or(default_column_width, |(w, _)| w)572        }573    }574575    /// Returns the default symbol visibility.576    pub fn default_visibility(&self) -> SymbolVisibility {577        self.opts578            .unstable_opts579            .default_visibility580            .or(self.target.options.default_visibility)581            .unwrap_or(SymbolVisibility::Interposable)582    }583584    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {585        if verbatim {586            ("", "")587        } else {588            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)589        }590    }591592    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {593        match self.lint_store {594            Some(ref lint_store) => lint_store.lint_groups_iter(),595            None => Box::new(std::iter::empty()),596        }597    }598}599600// JUSTIFICATION: defn of the suggested wrapper fns601#[allow(rustc::bad_opt_access)]602impl Session {603    pub fn verbose_internals(&self) -> bool {604        self.opts.unstable_opts.verbose_internals605    }606607    pub fn print_llvm_stats(&self) -> bool {608        self.opts.unstable_opts.print_codegen_stats609    }610611    pub fn print_llvm_stats_json(&self) -> Option<&String> {612        self.opts.unstable_opts.print_codegen_stats_json.as_ref()613    }614615    pub fn verify_llvm_ir(&self) -> bool {616        self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()617    }618619    pub fn binary_dep_depinfo(&self) -> bool {620        self.opts.unstable_opts.binary_dep_depinfo621    }622623    pub fn mir_opt_level(&self) -> usize {624        self.opts625            .unstable_opts626            .mir_opt_level627            .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })628    }629630    /// Calculates the flavor of LTO to use for this compilation.631    pub fn lto(&self) -> config::Lto {632        // If our target has codegen requirements ignore the command line633        if self.target.requires_lto {634            return config::Lto::Fat;635        }636637        // If the user specified something, return that. If they only said `-C638        // lto` and we've for whatever reason forced off ThinLTO via the CLI,639        // then ensure we can't use a ThinLTO.640        match self.opts.cg.lto {641            config::LtoCli::Unspecified => {642                // The compiler was invoked without the `-Clto` flag. Fall643                // through to the default handling644            }645            config::LtoCli::No => {646                // The user explicitly opted out of any kind of LTO647                return config::Lto::No;648            }649            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {650                // All of these mean fat LTO651                return config::Lto::Fat;652            }653            config::LtoCli::Thin => {654                // The user explicitly asked for ThinLTO655                if !self.thin_lto_supported {656                    // Backend doesn't support ThinLTO, fallback to fat LTO.657                    self.dcx().emit_warn(errors::ThinLtoNotSupportedByBackend);658                    return config::Lto::Fat;659                }660                return config::Lto::Thin;661            }662        }663664        if !self.thin_lto_supported {665            return config::Lto::No;666        }667668        // Ok at this point the target doesn't require anything and the user669        // hasn't asked for anything. Our next decision is whether or not670        // we enable "auto" ThinLTO where we use multiple codegen units and671        // then do ThinLTO over those codegen units. The logic below will672        // either return `No` or `ThinLocal`.673674        // If processing command line options determined that we're incompatible675        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.676        if self.opts.cli_forced_local_thinlto_off {677            return config::Lto::No;678        }679680        // If `-Z thinlto` specified process that, but note that this is mostly681        // a deprecated option now that `-C lto=thin` exists.682        if let Some(enabled) = self.opts.unstable_opts.thinlto {683            if enabled {684                return config::Lto::ThinLocal;685            } else {686                return config::Lto::No;687            }688        }689690        // If there's only one codegen unit and LTO isn't enabled then there's691        // no need for ThinLTO so just return false.692        if self.codegen_units().as_usize() == 1 {693            return config::Lto::No;694        }695696        // Now we're in "defaults" territory. By default we enable ThinLTO for697        // optimized compiles (anything greater than O0).698        match self.opts.optimize {699            config::OptLevel::No => config::Lto::No,700            _ => config::Lto::ThinLocal,701        }702    }703704    /// Returns the panic strategy for this compile session. If the user explicitly selected one705    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.706    pub fn panic_strategy(&self) -> PanicStrategy {707        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)708    }709710    pub fn fewer_names(&self) -> bool {711        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {712            fewer_names713        } else {714            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)715                || self.opts.output_types.contains_key(&OutputType::Bitcode)716                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.717                || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);718            !more_names719        }720    }721722    pub fn unstable_options(&self) -> bool {723        self.opts.unstable_opts.unstable_options724    }725726    pub fn is_nightly_build(&self) -> bool {727        self.opts.unstable_features.is_nightly_build()728    }729730    pub fn overflow_checks(&self) -> bool {731        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)732    }733734    pub fn ub_checks(&self) -> bool {735        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)736    }737738    pub fn contract_checks(&self) -> bool {739        self.opts.unstable_opts.contract_checks.unwrap_or(false)740    }741742    pub fn relocation_model(&self) -> RelocModel {743        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)744    }745746    pub fn code_model(&self) -> Option<CodeModel> {747        self.opts.cg.code_model.or(self.target.code_model)748    }749750    pub fn tls_model(&self) -> TlsModel {751        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)752    }753754    pub fn direct_access_external_data(&self) -> Option<bool> {755        self.opts756            .unstable_opts757            .direct_access_external_data758            .or(self.target.direct_access_external_data)759    }760761    pub fn split_debuginfo(&self) -> SplitDebuginfo {762        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)763    }764765    /// Returns the DWARF version passed on the CLI or the default for the target.766    pub fn dwarf_version(&self) -> u32 {767        self.opts768            .cg769            .dwarf_version770            .or(self.opts.unstable_opts.dwarf_version)771            .unwrap_or(self.target.default_dwarf_version)772    }773774    pub fn stack_protector(&self) -> StackProtector {775        if self.target.options.supports_stack_protector {776            self.opts.unstable_opts.stack_protector777        } else {778            StackProtector::None779        }780    }781782    pub fn must_emit_unwind_tables(&self) -> bool {783        // This is used to control the emission of the `uwtable` attribute on784        // LLVM functions. The `uwtable` attribute according to LLVM is:785        //786        //     This attribute indicates that the ABI being targeted requires that an787        //     unwind table entry be produced for this function even if we can show788        //     that no exceptions passes by it. This is normally the case for the789        //     ELF x86-64 abi, but it can be disabled for some compilation units.790        //791        // Typically when we're compiling with `-C panic=abort` we don't need792        // `uwtable` because we can't generate any exceptions! But note that793        // some targets require unwind tables to generate backtraces.794        // Unwind tables are needed when compiling with `-C panic=unwind`, but795        // LLVM won't omit unwind tables unless the function is also marked as796        // `nounwind`, so users are allowed to disable `uwtable` emission.797        // Historically rustc always emits `uwtable` attributes by default, so798        // even they can be disabled, they're still emitted by default.799        //800        // On some targets (including windows), however, exceptions include801        // other events such as illegal instructions, segfaults, etc. This means802        // that on Windows we end up still needing unwind tables even if the `-C803        // panic=abort` flag is passed.804        //805        // You can also find more info on why Windows needs unwind tables in:806        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078807        //808        // If a target requires unwind tables, then they must be emitted.809        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`810        // value, if it is provided, or disable them, if not.811        self.target.requires_uwtable812            || self813                .opts814                .cg815                .force_unwind_tables816                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)817    }818819    /// Returns the number of threads used for the thread pool.820    ///821    /// `None` means thread pool is not used and synchronization is disabled.822    /// `Some(n)` means synchronization is enabled with `n` worker threads.823    #[inline]824    pub fn threads(&self) -> Option<usize> {825        self.opts.unstable_opts.threads826    }827828    /// Returns the number of codegen units that should be used for this829    /// compilation830    pub fn codegen_units(&self) -> CodegenUnits {831        if let Some(n) = self.opts.cli_forced_codegen_units {832            return CodegenUnits::User(n);833        }834        if let Some(n) = self.target.default_codegen_units {835            return CodegenUnits::Default(n as usize);836        }837838        // If incremental compilation is turned on, we default to a high number839        // codegen units in order to reduce the "collateral damage" small840        // changes cause.841        if self.opts.incremental.is_some() {842            return CodegenUnits::Default(256);843        }844845        // Why is 16 codegen units the default all the time?846        //847        // The main reason for enabling multiple codegen units by default is to848        // leverage the ability for the codegen backend to do codegen and849        // optimization in parallel. This allows us, especially for large crates, to850        // make good use of all available resources on the machine once we've851        // hit that stage of compilation. Large crates especially then often852        // take a long time in codegen/optimization and this helps us amortize that853        // cost.854        //855        // Note that a high number here doesn't mean that we'll be spawning a856        // large number of threads in parallel. The backend of rustc contains857        // global rate limiting through the `jobserver` crate so we'll never858        // overload the system with too much work, but rather we'll only be859        // optimizing when we're otherwise cooperating with other instances of860        // rustc.861        //862        // Rather a high number here means that we should be able to keep a lot863        // of idle cpus busy. By ensuring that no codegen unit takes *too* long864        // to build we'll be guaranteed that all cpus will finish pretty closely865        // to one another and we should make relatively optimal use of system866        // resources867        //868        // Note that the main cost of codegen units is that it prevents LLVM869        // from inlining across codegen units. Users in general don't have a lot870        // of control over how codegen units are split up so it's our job in the871        // compiler to ensure that undue performance isn't lost when using872        // codegen units (aka we can't require everyone to slap `#[inline]` on873        // everything).874        //875        // If we're compiling at `-O0` then the number doesn't really matter too876        // much because performance doesn't matter and inlining is ok to lose.877        // In debug mode we just want to try to guarantee that no cpu is stuck878        // doing work that could otherwise be farmed to others.879        //880        // In release mode, however (O1 and above) performance does indeed881        // matter! To recover the loss in performance due to inlining we'll be882        // enabling ThinLTO by default (the function for which is just below).883        // This will ensure that we recover any inlining wins we otherwise lost884        // through codegen unit partitioning.885        //886        // ---887        //888        // Ok that's a lot of words but the basic tl;dr; is that we want a high889        // number here -- but not too high. Additionally we're "safe" to have it890        // always at the same number at all optimization levels.891        //892        // As a result 16 was chosen here! Mostly because it was a power of 2893        // and most benchmarks agreed it was roughly a local optimum. Not very894        // scientific.895        CodegenUnits::Default(16)896    }897898    pub fn teach(&self, code: ErrCode) -> bool {899        self.opts.unstable_opts.teach && self.dcx().must_teach(code)900    }901902    pub fn edition(&self) -> Edition {903        self.opts.edition904    }905906    pub fn link_dead_code(&self) -> bool {907        self.opts.cg.link_dead_code.unwrap_or(false)908    }909910    /// Get the deployment target on Apple platforms based on the standard environment variables,911    /// or fall back to the minimum version supported by `rustc`.912    ///913    /// This should be guarded behind `if sess.target.is_like_darwin`.914    pub fn apple_deployment_target(&self) -> apple::OSVersion {915        let min = apple::OSVersion::minimum_deployment_target(&self.target);916        let env_var = apple::deployment_target_env_var(&self.target.os);917918        // FIXME(madsmtm): Track changes to this.919        if let Ok(deployment_target) = env::var(env_var) {920            match apple::OSVersion::from_str(&deployment_target) {921                Ok(version) => {922                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);923                    // It is common that the deployment target is set a bit too low, for example on924                    // macOS Aarch64 to also target older x86_64. So we only want to warn when variable925                    // is lower than the minimum OS supported by rustc, not when the variable is lower926                    // than the minimum for a specific target.927                    if version < os_min {928                        self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {929                            env_var,930                            version: version.fmt_pretty().to_string(),931                            os_min: os_min.fmt_pretty().to_string(),932                        });933                    }934935                    // Raise the deployment target to the minimum supported.936                    version.max(min)937                }938                Err(error) => {939                    self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });940                    min941                }942            }943        } else {944            // If no deployment target variable is set, default to the minimum found above.945            min946        }947    }948949    pub fn sanitizers(&self) -> SanitizerSet {950        return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;951    }952}953954// JUSTIFICATION: part of session construction955#[allow(rustc::bad_opt_access)]956fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {957    let macro_backtrace = sopts.unstable_opts.macro_backtrace;958    let track_diagnostics = sopts.unstable_opts.track_diagnostics;959    let terminal_url = match sopts.unstable_opts.terminal_urls {960        TerminalUrl::Auto => {961            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {962                (Ok("truecolor"), Ok("xterm-256color"))963                    if sopts.unstable_features.is_nightly_build() =>964                {965                    TerminalUrl::Yes966                }967                _ => TerminalUrl::No,968            }969        }970        t => t,971    };972973    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };974975    match sopts.error_format {976        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {977            HumanReadableErrorType { short, unicode } => {978                let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))979                    .sm(source_map)980                    .short_message(short)981                    .diagnostic_width(sopts.diagnostic_width)982                    .macro_backtrace(macro_backtrace)983                    .track_diagnostics(track_diagnostics)984                    .terminal_url(terminal_url)985                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })986                    .ignored_directories_in_source_blocks(987                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),988                    );989                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))990            }991        },992        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(993            JsonEmitter::new(994                Box::new(io::BufWriter::new(io::stderr())),995                source_map,996                pretty,997                json_rendered,998                color_config,999            )1000            .ui_testing(sopts.unstable_opts.ui_testing)1001            .ignored_directories_in_source_blocks(1002                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),1003            )1004            .diagnostic_width(sopts.diagnostic_width)1005            .macro_backtrace(macro_backtrace)1006            .track_diagnostics(track_diagnostics)1007            .terminal_url(terminal_url),1008        ),1009    }1010}10111012// JUSTIFICATION: literally session construction1013#[allow(rustc::bad_opt_access)]1014pub fn build_session(1015    sopts: config::Options,1016    io: CompilerIO,1017    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,1018    target: Target,1019    cfg_version: &'static str,1020    ice_file: Option<PathBuf>,1021    using_internal_features: &'static AtomicBool,1022) -> Session {1023    // FIXME: This is not general enough to make the warning lint completely override1024    // normal diagnostic warnings, since the warning lint can also be denied and changed1025    // later via the source code.1026    let warnings_allow = sopts1027        .lint_opts1028        .iter()1029        .rfind(|&(key, _)| *key == "warnings")1030        .is_some_and(|&(_, level)| level == lint::Allow);1031    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);1032    let can_emit_warnings = !(warnings_allow || cap_lints_allow);10331034    let source_map = rustc_span::source_map::get_source_map().unwrap();1035    let emitter = default_emitter(&sopts, Arc::clone(&source_map));10361037    let mut dcx =1038        DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));1039    if let Some(ice_file) = ice_file {1040        dcx = dcx.with_ice_file(ice_file);1041    }10421043    if let Some(msrv) = sopts.unstable_opts.hint_msrv {1044        dcx = dcx.with_msrv(msrv);1045    }10461047    let host_triple = TargetTuple::from_tuple(config::host_tuple());1048    let (host, target_warnings) =1049        Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)1050            .unwrap_or_else(|e| {1051                dcx.handle().fatal(format!("Error loading host specification: {e}"))1052            });1053    for warning in target_warnings.warning_messages() {1054        dcx.handle().warn(warning)1055    }10561057    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile1058    {1059        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };10601061        let profiler = SelfProfiler::new(1062            directory,1063            sopts.crate_name.as_deref(),1064            sopts.unstable_opts.self_profile_events.as_deref(),1065            &sopts.unstable_opts.self_profile_counter,1066        );1067        match profiler {1068            Ok(profiler) => Some(Arc::new(profiler)),1069            Err(e) => {1070                dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });1071                None1072            }1073        }1074    } else {1075        None1076    };10771078    let psess = ParseSess::with_dcx(dcx, source_map);10791080    let host_triple = config::host_tuple();1081    let target_triple = sopts.target_triple.tuple();1082    // FIXME use host sysroot?1083    let host_tlib_path =1084        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));1085    let target_tlib_path = if host_triple == target_triple {1086        // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary1087        // rescanning of the target lib path and an unnecessary allocation.1088        Arc::clone(&host_tlib_path)1089    } else {1090        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))1091    };10921093    let prof = SelfProfilerRef::new(1094        self_profiler,1095        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),1096    );10971098    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {1099        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,1100        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,1101        _ => CtfeBacktrace::Disabled,1102    });11031104    let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };1105    let target_filesearch =1106        filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);1107    let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);11081109    let timings = TimingSectionHandler::new(sopts.json_timings);11101111    let sess = Session {1112        target,1113        host,1114        opts: sopts,1115        target_tlib_path,1116        psess,1117        unstable_features: UnstableFeatures::from_environment(None),1118        config: Cfg::default(),1119        check_config: CheckCfg::default(),1120        proc_macro_quoted_spans: Default::default(),1121        io,1122        incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),1123        prof,1124        timings,1125        code_stats: Default::default(),1126        lint_store: None,1127        driver_lint_caps,1128        ctfe_backtrace,1129        miri_unleashed_features: Lock::new(Default::default()),1130        asm_arch,1131        target_features: Default::default(),1132        unstable_target_features: Default::default(),1133        cfg_version,1134        using_internal_features,1135        env_depinfo: Default::default(),1136        file_depinfo: Default::default(),1137        target_filesearch,1138        host_filesearch,1139        replaced_intrinsics: FxHashSet::default(), // filled by `run_compiler`1140        fallback_intrinsics: FxHashSet::default(), // filled by `run_compiler`1141        thin_lto_supported: true,                  // filled by `run_compiler`1142        mir_opt_bisect_eval_count: AtomicUsize::new(0),1143        used_features: Lock::default(),1144        removed_rustc_main_attr: AtomicBool::new(false),1145    };11461147    validate_commandline_args_with_session_available(&sess);11481149    sess1150}11511152/// Validate command line arguments with a `Session`.1153///1154/// If it is useful to have a Session available already for validating a commandline argument, you1155/// can do so here.1156// JUSTIFICATION: needs to access args to validate them1157#[allow(rustc::bad_opt_access)]1158fn validate_commandline_args_with_session_available(sess: &Session) {1159    // Since we don't know if code in an rlib will be linked to statically or1160    // dynamically downstream, rustc generates `__imp_` symbols that help linkers1161    // on Windows deal with this lack of knowledge (#27438). Unfortunately,1162    // these manually generated symbols confuse LLD when it tries to merge1163    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows1164    // when compiling for LLD ThinLTO. This way we can validly just not generate1165    // the `dllimport` attributes and `__imp_` symbols in that case.1166    if sess.opts.cg.linker_plugin_lto.enabled()1167        && sess.opts.cg.prefer_dynamic1168        && sess.target.is_like_windows1169    {1170        sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);1171    }11721173    // Make sure that any given profiling data actually exists so LLVM can't1174    // decide to silently skip PGO.1175    if let Some(ref path) = sess.opts.cg.profile_use {1176        if !path.exists() {1177            sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });1178        }1179    }11801181    // Do the same for sample profile data.1182    if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {1183        if !path.exists() {1184            sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });1185        }1186    }11871188    // Unwind tables cannot be disabled if the target requires them.1189    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {1190        if sess.target.requires_uwtable && !include_uwtables {1191            sess.dcx().emit_err(errors::TargetRequiresUnwindTables);1192        }1193    }11941195    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.1196    let supported_sanitizers = sess.target.options.supported_sanitizers;1197    let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;1198    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled1199    // we should allow Shadow Call Stack sanitizer.1200    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {1201        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;1202    }1203    match unsupported_sanitizers.into_iter().count() {1204        0 => {}1205        1 => {1206            sess.dcx()1207                .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });1208        }1209        _ => {1210            sess.dcx().emit_err(errors::SanitizersNotSupported {1211                us: unsupported_sanitizers.to_string(),1212            });1213        }1214    }12151216    // Cannot mix and match mutually-exclusive sanitizers.1217    if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {1218        sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {1219            first: first.to_string(),1220            second: second.to_string(),1221        });1222    }12231224    // Cannot enable crt-static with sanitizers on Linux1225    if sess.crt_static(None)1226        && !sess.opts.unstable_opts.sanitizer.is_empty()1227        && !sess.target.is_like_msvc1228    {1229        sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);1230    }12311232    // LLVM CFI requires LTO.1233    if sess.is_sanitizer_cfi_enabled()1234        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())1235    {1236        sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);1237    }12381239    // KCFI requires panic=abort1240    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {1241        sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);1242    }12431244    // LLVM CFI using rustc LTO requires a single codegen unit.1245    if sess.is_sanitizer_cfi_enabled()1246        && sess.lto() == config::Lto::Fat1247        && (sess.codegen_units().as_usize() != 1)1248    {1249        sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);1250    }12511252    // Canonical jump tables requires CFI.1253    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {1254        if !sess.is_sanitizer_cfi_enabled() {1255            sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);1256        }1257    }12581259    // KCFI arity indicator requires KCFI.1260    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {1261        sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);1262    }12631264    // LLVM CFI pointer generalization requires CFI or KCFI.1265    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {1266        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {1267            sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);1268        }1269    }12701271    // LLVM CFI integer normalization requires CFI or KCFI.1272    if sess.is_sanitizer_cfi_normalize_integers_enabled() {1273        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {1274            sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);1275        }1276    }12771278    // LTO unit splitting requires LTO.1279    if sess.is_split_lto_unit_enabled()1280        && !(sess.lto() == config::Lto::Fat1281            || sess.lto() == config::Lto::Thin1282            || sess.opts.cg.linker_plugin_lto.enabled())1283    {1284        sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);1285    }12861287    // VFE requires LTO.1288    if sess.lto() != config::Lto::Fat {1289        if sess.opts.unstable_opts.virtual_function_elimination {1290            sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);1291        }1292    }12931294    if sess.opts.unstable_opts.stack_protector != StackProtector::None {1295        if !sess.target.options.supports_stack_protector {1296            sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {1297                stack_protector: sess.opts.unstable_opts.stack_protector,1298                target_triple: &sess.opts.target_triple,1299            });1300        }1301    }13021303    if sess.opts.unstable_opts.small_data_threshold.is_some() {1304        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {1305            sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {1306                target_triple: &sess.opts.target_triple,1307            })1308        }1309    }13101311    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {1312        sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);1313    }13141315    if let Some(dwarf_version) =1316        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)1317    {1318        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.1319        if dwarf_version < 2 || dwarf_version > 5 {1320            sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });1321        }1322    }13231324    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())1325        && !sess.opts.unstable_opts.unstable_options1326    {1327        sess.dcx()1328            .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });1329    }13301331    if sess.opts.unstable_opts.embed_source {1332        let dwarf_version = sess.dwarf_version();13331334        if dwarf_version < 5 {1335            sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });1336        }13371338        if sess.opts.debuginfo == DebugInfo::None {1339            sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);1340        }1341    }13421343    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {1344        sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });1345    }13461347    if let Some(flavor) = sess.opts.cg.linker_flavor1348        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)1349    {1350        let flavor = flavor.desc();1351        sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });1352    }13531354    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {1355        if !matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {1356            sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);1357        }1358    }13591360    if sess.opts.unstable_opts.indirect_branch_cs_prefix {1361        if !matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {1362            sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);1363        }1364    }13651366    if let Some(regparm) = sess.opts.unstable_opts.regparm {1367        if regparm > 3 {1368            sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });1369        }1370        if sess.target.arch != Arch::X86 {1371            sess.dcx().emit_err(errors::UnsupportedRegparmArch);1372        }1373    }1374    if sess.opts.unstable_opts.reg_struct_return {1375        if sess.target.arch != Arch::X86 {1376            sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);1377        }1378    }13791380    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is1381    // kept as a `match` to force a change if new ones are added, even if we currently only support1382    // `thunk-extern` like Clang.1383    match sess.opts.unstable_opts.function_return {1384        FunctionReturn::Keep => (),1385        FunctionReturn::ThunkExtern => {1386            // FIXME: In principle, the inherited base LLVM target code model could be large,1387            // but this only checks whether we were passed one explicitly (like Clang does).1388            if let Some(code_model) = sess.code_model()1389                && code_model == CodeModel::Large1390            {1391                sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);1392            }1393        }1394    }13951396    if sess.opts.unstable_opts.packed_stack {1397        if sess.target.arch != Arch::S390x {1398            sess.dcx().emit_err(errors::UnsupportedPackedStack);1399        }1400    }1401}14021403/// Holds data on the current incremental compilation session, if there is one.1404#[derive(Debug)]1405enum IncrCompSession {1406    /// This is the state the session will be in until the incr. comp. dir is1407    /// needed.1408    NotInitialized,1409    /// This is the state during which the session directory is private and can1410    /// be modified. `_lock_file` is never directly used, but its presence1411    /// alone has an effect, because the file will unlock when the session is1412    /// dropped.1413    Active { session_directory: PathBuf, _lock_file: flock::Lock },1414    /// This is the state after the session directory has been finalized. In this1415    /// state, the contents of the directory must not be modified any more.1416    Finalized { session_directory: PathBuf },1417    /// This is an error state that is reached when some compilation error has1418    /// occurred. It indicates that the contents of the session directory must1419    /// not be used, since they might be invalid.1420    InvalidBecauseOfErrors { session_directory: PathBuf },1421}14221423/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.1424pub struct EarlyDiagCtxt {1425    dcx: DiagCtxt,1426}14271428impl EarlyDiagCtxt {1429    pub fn new(output: ErrorOutputType) -> Self {1430        let emitter = mk_emitter(output);1431        Self { dcx: DiagCtxt::new(emitter) }1432    }14331434    /// Swap out the underlying dcx once we acquire the user's preference on error emission1435    /// format. If `early_err` was previously called this will panic.1436    pub fn set_error_format(&mut self, output: ErrorOutputType) {1437        assert!(self.dcx.handle().has_errors().is_none());14381439        let emitter = mk_emitter(output);1440        self.dcx = DiagCtxt::new(emitter);1441    }14421443    pub fn early_note(&self, msg: impl Into<DiagMessage>) {1444        self.dcx.handle().note(msg)1445    }14461447    pub fn early_help(&self, msg: impl Into<DiagMessage>) {1448        self.dcx.handle().struct_help(msg).emit()1449    }14501451    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]1452    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {1453        self.dcx.handle().err(msg)1454    }14551456    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {1457        self.dcx.handle().fatal(msg)1458    }14591460    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {1461        self.dcx.handle().struct_fatal(msg)1462    }14631464    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {1465        self.dcx.handle().warn(msg)1466    }14671468    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {1469        self.dcx.handle().struct_warn(msg)1470    }1471}14721473fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {1474    let emitter: Box<DynEmitter> = match output {1475        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {1476            HumanReadableErrorType { short, unicode } => Box::new(1477                AnnotateSnippetEmitter::new(stderr_destination(color_config))1478                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })1479                    .short_message(short),1480            ),1481        },1482        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {1483            Box::new(JsonEmitter::new(1484                Box::new(io::BufWriter::new(io::stderr())),1485                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),1486                pretty,1487                json_rendered,1488                color_config,1489            ))1490        }1491    };1492    emitter1493}

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.