rustc_session/
session.rs

1use std::any::Any;
2use std::path::{Path, PathBuf};
3use std::str::FromStr;
4use std::sync::Arc;
5use std::sync::atomic::AtomicBool;
6use std::{env, io};
7
8use rand::{RngCore, rng};
9use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
10use rustc_data_structures::flock;
11use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
13use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
14use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
15use rustc_errors::codes::*;
16use rustc_errors::emitter::{
17    DynEmitter, HumanEmitter, HumanReadableErrorType, OutputTheme, stderr_destination,
18};
19use rustc_errors::json::JsonEmitter;
20use rustc_errors::timings::TimingSectionHandler;
21use rustc_errors::translation::Translator;
22use rustc_errors::{
23    Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
24    TerminalUrl, fallback_fluent_bundle,
25};
26use rustc_hir::limit::Limit;
27use rustc_macros::HashStable_Generic;
28pub use rustc_span::def_id::StableCrateId;
29use rustc_span::edition::Edition;
30use rustc_span::source_map::{FilePathMapping, SourceMap};
31use rustc_span::{FileNameDisplayPreference, RealFileName, Span, Symbol};
32use rustc_target::asm::InlineAsmArch;
33use rustc_target::spec::{
34    Arch, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
35    SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
36    TargetTuple, TlsModel, apple,
37};
38
39use crate::code_stats::CodeStats;
40pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
41use crate::config::{
42    self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
43    Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents,
44    SwitchWithOptPath,
45};
46use crate::filesearch::FileSearch;
47use crate::lint::LintId;
48use crate::parse::{ParseSess, add_feature_diagnostics};
49use crate::search_paths::SearchPath;
50use crate::{errors, filesearch, lint};
51
52/// The behavior of the CTFE engine when an error occurs with regards to backtraces.
53#[derive(Clone, Copy)]
54pub enum CtfeBacktrace {
55    /// Do nothing special, return the error as usual without a backtrace.
56    Disabled,
57    /// Capture a backtrace at the point the error is created and return it in the error
58    /// (to be printed later if/when the error ever actually gets shown to the user).
59    Capture,
60    /// Capture a backtrace at the point the error is created and immediately print it out.
61    Immediate,
62}
63
64#[derive(Clone, Copy, Debug, HashStable_Generic)]
65pub struct Limits {
66    /// The maximum recursion limit for potentially infinitely recursive
67    /// operations such as auto-dereference and monomorphization.
68    pub recursion_limit: Limit,
69    /// The size at which the `large_assignments` lint starts
70    /// being emitted.
71    pub move_size_limit: Limit,
72    /// The maximum length of types during monomorphization.
73    pub type_length_limit: Limit,
74    /// The maximum pattern complexity allowed (internal only).
75    pub pattern_complexity_limit: Limit,
76}
77
78pub struct CompilerIO {
79    pub input: Input,
80    pub output_dir: Option<PathBuf>,
81    pub output_file: Option<OutFileName>,
82    pub temps_dir: Option<PathBuf>,
83}
84
85pub trait DynLintStore: Any + DynSync + DynSend {
86    /// Provides a way to access lint groups without depending on `rustc_lint`
87    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
88}
89
90/// Represents the data associated with a compilation
91/// session for a single crate.
92pub struct Session {
93    pub target: Target,
94    pub host: Target,
95    pub opts: config::Options,
96    pub target_tlib_path: Arc<SearchPath>,
97    pub psess: ParseSess,
98    /// Input, input file path and output file path to this compilation process.
99    pub io: CompilerIO,
100
101    incr_comp_session: RwLock<IncrCompSession>,
102
103    /// Used by `-Z self-profile`.
104    pub prof: SelfProfilerRef,
105
106    /// Used to emit section timings events (enabled by `--json=timings`).
107    pub timings: TimingSectionHandler,
108
109    /// Data about code being compiled, gathered during compilation.
110    pub code_stats: CodeStats,
111
112    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
113    pub lint_store: Option<Arc<dyn DynLintStore>>,
114
115    /// Cap lint level specified by a driver specifically.
116    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
117
118    /// Tracks the current behavior of the CTFE engine when an error occurs.
119    /// Options range from returning the error without a backtrace to returning an error
120    /// and immediately printing the backtrace to stderr.
121    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
122    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
123    /// errors.
124    pub ctfe_backtrace: Lock<CtfeBacktrace>,
125
126    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
127    /// const check, optionally with the relevant feature gate. We use this to
128    /// warn about unleashing, but with a single diagnostic instead of dozens that
129    /// drown everything else in noise.
130    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
131
132    /// Architecture to use for interpreting asm!.
133    pub asm_arch: Option<InlineAsmArch>,
134
135    /// Set of enabled features for the current target.
136    pub target_features: FxIndexSet<Symbol>,
137
138    /// Set of enabled features for the current target, including unstable ones.
139    pub unstable_target_features: FxIndexSet<Symbol>,
140
141    /// The version of the rustc process, possibly including a commit hash and description.
142    pub cfg_version: &'static str,
143
144    /// The inner atomic value is set to true when a feature marked as `internal` is
145    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
146    /// internal features are wontfix, and they are usually the cause of the ICEs.
147    /// None signifies that this is not tracked.
148    pub using_internal_features: &'static AtomicBool,
149
150    target_filesearch: FileSearch,
151    host_filesearch: FileSearch,
152
153    /// A random string generated per invocation of rustc.
154    ///
155    /// This is prepended to all temporary files so that they do not collide
156    /// during concurrent invocations of rustc, or past invocations that were
157    /// preserved with a flag like `-C save-temps`, since these files may be
158    /// hard linked.
159    pub invocation_temp: Option<String>,
160}
161
162#[derive(Clone, Copy)]
163pub enum CodegenUnits {
164    /// Specified by the user. In this case we try fairly hard to produce the
165    /// number of CGUs requested.
166    User(usize),
167
168    /// A default value, i.e. not specified by the user. In this case we take
169    /// more liberties about CGU formation, e.g. avoid producing very small
170    /// CGUs.
171    Default(usize),
172}
173
174impl CodegenUnits {
175    pub fn as_usize(self) -> usize {
176        match self {
177            CodegenUnits::User(n) => n,
178            CodegenUnits::Default(n) => n,
179        }
180    }
181}
182
183pub struct LintGroup {
184    pub name: &'static str,
185    pub lints: Vec<LintId>,
186    pub is_externally_loaded: bool,
187}
188
189impl Session {
190    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
191        self.miri_unleashed_features.lock().push((span, feature_gate));
192    }
193
194    pub fn local_crate_source_file(&self) -> Option<RealFileName> {
195        Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
196    }
197
198    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
199        let mut guar = None;
200        let unleashed_features = self.miri_unleashed_features.lock();
201        if !unleashed_features.is_empty() {
202            let mut must_err = false;
203            // Create a diagnostic pointing at where things got unleashed.
204            self.dcx().emit_warn(errors::SkippingConstChecks {
205                unleashed_features: unleashed_features
206                    .iter()
207                    .map(|(span, gate)| {
208                        gate.map(|gate| {
209                            must_err = true;
210                            errors::UnleashedFeatureHelp::Named { span: *span, gate }
211                        })
212                        .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
213                    })
214                    .collect(),
215            });
216
217            // If we should err, make sure we did.
218            if must_err && self.dcx().has_errors().is_none() {
219                // We have skipped a feature gate, and not run into other errors... reject.
220                guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
221            }
222        }
223        guar
224    }
225
226    /// Invoked all the way at the end to finish off diagnostics printing.
227    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
228        let mut guar = None;
229        guar = guar.or(self.check_miri_unleashed_features());
230        guar = guar.or(self.dcx().emit_stashed_diagnostics());
231        self.dcx().print_error_count();
232        if self.opts.json_future_incompat {
233            self.dcx().emit_future_breakage_report();
234        }
235        guar
236    }
237
238    /// Returns true if the crate is a testing one.
239    pub fn is_test_crate(&self) -> bool {
240        self.opts.test
241    }
242
243    /// `feature` must be a language feature.
244    #[track_caller]
245    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
246        let mut err = self.dcx().create_err(err);
247        if err.code.is_none() {
248            #[allow(rustc::diagnostic_outside_of_impl)]
249            err.code(E0658);
250        }
251        add_feature_diagnostics(&mut err, self, feature);
252        err
253    }
254
255    /// Record the fact that we called `trimmed_def_paths`, and do some
256    /// checking about whether its cost was justified.
257    pub fn record_trimmed_def_paths(&self) {
258        if self.opts.unstable_opts.print_type_sizes
259            || self.opts.unstable_opts.query_dep_graph
260            || self.opts.unstable_opts.dump_mir.is_some()
261            || self.opts.unstable_opts.unpretty.is_some()
262            || self.prof.is_args_recording_enabled()
263            || self.opts.output_types.contains_key(&OutputType::Mir)
264            || std::env::var_os("RUSTC_LOG").is_some()
265        {
266            return;
267        }
268
269        self.dcx().set_must_produce_diag()
270    }
271
272    #[inline]
273    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
274        self.psess.dcx()
275    }
276
277    #[inline]
278    pub fn source_map(&self) -> &SourceMap {
279        self.psess.source_map()
280    }
281
282    /// Returns `true` if internal lints should be added to the lint store - i.e. if
283    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
284    /// to be emitted under rustdoc).
285    pub fn enable_internal_lints(&self) -> bool {
286        self.unstable_options() && !self.opts.actually_rustdoc
287    }
288
289    pub fn instrument_coverage(&self) -> bool {
290        self.opts.cg.instrument_coverage() != InstrumentCoverage::No
291    }
292
293    pub fn instrument_coverage_branch(&self) -> bool {
294        self.instrument_coverage()
295            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
296    }
297
298    pub fn instrument_coverage_condition(&self) -> bool {
299        self.instrument_coverage()
300            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
301    }
302
303    /// Provides direct access to the `CoverageOptions` struct, so that
304    /// individual flags for debugging/testing coverage instrumetation don't
305    /// need separate accessors.
306    pub fn coverage_options(&self) -> &CoverageOptions {
307        &self.opts.unstable_opts.coverage_options
308    }
309
310    pub fn is_sanitizer_cfi_enabled(&self) -> bool {
311        self.sanitizers().contains(SanitizerSet::CFI)
312    }
313
314    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
315        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
316    }
317
318    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
319        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
320    }
321
322    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
323        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
324    }
325
326    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
327        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
328    }
329
330    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
331        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
332    }
333
334    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
335        self.sanitizers().contains(SanitizerSet::KCFI)
336    }
337
338    pub fn is_split_lto_unit_enabled(&self) -> bool {
339        self.opts.unstable_opts.split_lto_unit == Some(true)
340    }
341
342    /// Check whether this compile session and crate type use static crt.
343    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
344        if !self.target.crt_static_respected {
345            // If the target does not opt in to crt-static support, use its default.
346            return self.target.crt_static_default;
347        }
348
349        let requested_features = self.opts.cg.target_feature.split(',');
350        let found_negative = requested_features.clone().any(|r| r == "-crt-static");
351        let found_positive = requested_features.clone().any(|r| r == "+crt-static");
352
353        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
354        #[allow(rustc::bad_opt_access)]
355        if found_positive || found_negative {
356            found_positive
357        } else if crate_type == Some(CrateType::ProcMacro)
358            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
359        {
360            // FIXME: When crate_type is not available,
361            // we use compiler options to determine the crate_type.
362            // We can't check `#![crate_type = "proc-macro"]` here.
363            false
364        } else {
365            self.target.crt_static_default
366        }
367    }
368
369    pub fn is_wasi_reactor(&self) -> bool {
370        self.target.options.os == Os::Wasi
371            && matches!(
372                self.opts.unstable_opts.wasi_exec_model,
373                Some(config::WasiExecModel::Reactor)
374            )
375    }
376
377    /// Returns `true` if the target can use the current split debuginfo configuration.
378    pub fn target_can_use_split_dwarf(&self) -> bool {
379        self.target.debuginfo_kind == DebuginfoKind::Dwarf
380    }
381
382    pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
383        format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
384    }
385
386    pub fn target_filesearch(&self) -> &filesearch::FileSearch {
387        &self.target_filesearch
388    }
389    pub fn host_filesearch(&self) -> &filesearch::FileSearch {
390        &self.host_filesearch
391    }
392
393    /// Returns a list of directories where target-specific tool binaries are located. Some fallback
394    /// directories are also returned, for example if `--sysroot` is used but tools are missing
395    /// (#125246): we also add the bin directories to the sysroot where rustc is located.
396    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
397        let search_paths = self
398            .opts
399            .sysroot
400            .all_paths()
401            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
402
403        if self_contained {
404            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the
405            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the
406            // fallback paths.
407            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
408        } else {
409            search_paths.collect()
410        }
411    }
412
413    pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
414        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
415
416        if let IncrCompSession::NotInitialized = *incr_comp_session {
417        } else {
418            panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
419        }
420
421        *incr_comp_session =
422            IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
423    }
424
425    pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
426        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
427
428        if let IncrCompSession::Active { .. } = *incr_comp_session {
429        } else {
430            panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
431        }
432
433        // Note: this will also drop the lock file, thus unlocking the directory.
434        *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
435    }
436
437    pub fn mark_incr_comp_session_as_invalid(&self) {
438        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
439
440        let session_directory = match *incr_comp_session {
441            IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
442            IncrCompSession::InvalidBecauseOfErrors { .. } => return,
443            _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
444        };
445
446        // Note: this will also drop the lock file, thus unlocking the directory.
447        *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
448    }
449
450    pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
451        let incr_comp_session = self.incr_comp_session.borrow();
452        ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
453            IncrCompSession::NotInitialized => panic!(
454                "trying to get session directory from `IncrCompSession`: {:?}",
455                *incr_comp_session,
456            ),
457            IncrCompSession::Active { ref session_directory, .. }
458            | IncrCompSession::Finalized { ref session_directory }
459            | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
460                session_directory
461            }
462        })
463    }
464
465    pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
466        self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
467    }
468
469    /// Is this edition 2015?
470    pub fn is_rust_2015(&self) -> bool {
471        self.edition().is_rust_2015()
472    }
473
474    /// Are we allowed to use features from the Rust 2018 edition?
475    pub fn at_least_rust_2018(&self) -> bool {
476        self.edition().at_least_rust_2018()
477    }
478
479    /// Are we allowed to use features from the Rust 2021 edition?
480    pub fn at_least_rust_2021(&self) -> bool {
481        self.edition().at_least_rust_2021()
482    }
483
484    /// Are we allowed to use features from the Rust 2024 edition?
485    pub fn at_least_rust_2024(&self) -> bool {
486        self.edition().at_least_rust_2024()
487    }
488
489    /// Returns `true` if we should use the PLT for shared library calls.
490    pub fn needs_plt(&self) -> bool {
491        // Check if the current target usually wants PLT to be enabled.
492        // The user can use the command line flag to override it.
493        let want_plt = self.target.plt_by_default;
494
495        let dbg_opts = &self.opts.unstable_opts;
496
497        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
498
499        // Only enable this optimization by default if full relro is also enabled.
500        // In this case, lazy binding was already unavailable, so nothing is lost.
501        // This also ensures `-Wl,-z,now` is supported by the linker.
502        let full_relro = RelroLevel::Full == relro_level;
503
504        // If user didn't explicitly forced us to use / skip the PLT,
505        // then use it unless the target doesn't want it by default or the full relro forces it on.
506        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
507    }
508
509    /// Checks if LLVM lifetime markers should be emitted.
510    pub fn emit_lifetime_markers(&self) -> bool {
511        self.opts.optimize != config::OptLevel::No
512        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
513        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
514        // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
515        || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
516    }
517
518    pub fn diagnostic_width(&self) -> usize {
519        let default_column_width = 140;
520        if let Some(width) = self.opts.diagnostic_width {
521            width
522        } else if self.opts.unstable_opts.ui_testing {
523            default_column_width
524        } else {
525            termize::dimensions().map_or(default_column_width, |(w, _)| w)
526        }
527    }
528
529    /// Returns the default symbol visibility.
530    pub fn default_visibility(&self) -> SymbolVisibility {
531        self.opts
532            .unstable_opts
533            .default_visibility
534            .or(self.target.options.default_visibility)
535            .unwrap_or(SymbolVisibility::Interposable)
536    }
537
538    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
539        if verbatim {
540            ("", "")
541        } else {
542            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
543        }
544    }
545
546    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
547        match self.lint_store {
548            Some(ref lint_store) => lint_store.lint_groups_iter(),
549            None => Box::new(std::iter::empty()),
550        }
551    }
552}
553
554// JUSTIFICATION: defn of the suggested wrapper fns
555#[allow(rustc::bad_opt_access)]
556impl Session {
557    pub fn verbose_internals(&self) -> bool {
558        self.opts.unstable_opts.verbose_internals
559    }
560
561    pub fn print_llvm_stats(&self) -> bool {
562        self.opts.unstable_opts.print_codegen_stats
563    }
564
565    pub fn verify_llvm_ir(&self) -> bool {
566        self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
567    }
568
569    pub fn binary_dep_depinfo(&self) -> bool {
570        self.opts.unstable_opts.binary_dep_depinfo
571    }
572
573    pub fn mir_opt_level(&self) -> usize {
574        self.opts
575            .unstable_opts
576            .mir_opt_level
577            .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
578    }
579
580    /// Calculates the flavor of LTO to use for this compilation.
581    pub fn lto(&self) -> config::Lto {
582        // If our target has codegen requirements ignore the command line
583        if self.target.requires_lto {
584            return config::Lto::Fat;
585        }
586
587        // If the user specified something, return that. If they only said `-C
588        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
589        // then ensure we can't use a ThinLTO.
590        match self.opts.cg.lto {
591            config::LtoCli::Unspecified => {
592                // The compiler was invoked without the `-Clto` flag. Fall
593                // through to the default handling
594            }
595            config::LtoCli::No => {
596                // The user explicitly opted out of any kind of LTO
597                return config::Lto::No;
598            }
599            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
600                // All of these mean fat LTO
601                return config::Lto::Fat;
602            }
603            config::LtoCli::Thin => {
604                // The user explicitly asked for ThinLTO
605                return config::Lto::Thin;
606            }
607        }
608
609        // Ok at this point the target doesn't require anything and the user
610        // hasn't asked for anything. Our next decision is whether or not
611        // we enable "auto" ThinLTO where we use multiple codegen units and
612        // then do ThinLTO over those codegen units. The logic below will
613        // either return `No` or `ThinLocal`.
614
615        // If processing command line options determined that we're incompatible
616        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
617        if self.opts.cli_forced_local_thinlto_off {
618            return config::Lto::No;
619        }
620
621        // If `-Z thinlto` specified process that, but note that this is mostly
622        // a deprecated option now that `-C lto=thin` exists.
623        if let Some(enabled) = self.opts.unstable_opts.thinlto {
624            if enabled {
625                return config::Lto::ThinLocal;
626            } else {
627                return config::Lto::No;
628            }
629        }
630
631        // If there's only one codegen unit and LTO isn't enabled then there's
632        // no need for ThinLTO so just return false.
633        if self.codegen_units().as_usize() == 1 {
634            return config::Lto::No;
635        }
636
637        // Now we're in "defaults" territory. By default we enable ThinLTO for
638        // optimized compiles (anything greater than O0).
639        match self.opts.optimize {
640            config::OptLevel::No => config::Lto::No,
641            _ => config::Lto::ThinLocal,
642        }
643    }
644
645    /// Returns the panic strategy for this compile session. If the user explicitly selected one
646    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
647    pub fn panic_strategy(&self) -> PanicStrategy {
648        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
649    }
650
651    pub fn fewer_names(&self) -> bool {
652        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
653            fewer_names
654        } else {
655            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
656                || self.opts.output_types.contains_key(&OutputType::Bitcode)
657                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
658                || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
659            !more_names
660        }
661    }
662
663    pub fn unstable_options(&self) -> bool {
664        self.opts.unstable_opts.unstable_options
665    }
666
667    pub fn is_nightly_build(&self) -> bool {
668        self.opts.unstable_features.is_nightly_build()
669    }
670
671    pub fn overflow_checks(&self) -> bool {
672        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
673    }
674
675    pub fn ub_checks(&self) -> bool {
676        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
677    }
678
679    pub fn contract_checks(&self) -> bool {
680        self.opts.unstable_opts.contract_checks.unwrap_or(false)
681    }
682
683    pub fn relocation_model(&self) -> RelocModel {
684        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
685    }
686
687    pub fn code_model(&self) -> Option<CodeModel> {
688        self.opts.cg.code_model.or(self.target.code_model)
689    }
690
691    pub fn tls_model(&self) -> TlsModel {
692        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
693    }
694
695    pub fn direct_access_external_data(&self) -> Option<bool> {
696        self.opts
697            .unstable_opts
698            .direct_access_external_data
699            .or(self.target.direct_access_external_data)
700    }
701
702    pub fn split_debuginfo(&self) -> SplitDebuginfo {
703        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
704    }
705
706    /// Returns the DWARF version passed on the CLI or the default for the target.
707    pub fn dwarf_version(&self) -> u32 {
708        self.opts
709            .cg
710            .dwarf_version
711            .or(self.opts.unstable_opts.dwarf_version)
712            .unwrap_or(self.target.default_dwarf_version)
713    }
714
715    pub fn stack_protector(&self) -> StackProtector {
716        if self.target.options.supports_stack_protector {
717            self.opts.unstable_opts.stack_protector
718        } else {
719            StackProtector::None
720        }
721    }
722
723    pub fn must_emit_unwind_tables(&self) -> bool {
724        // This is used to control the emission of the `uwtable` attribute on
725        // LLVM functions. The `uwtable` attribute according to LLVM is:
726        //
727        //     This attribute indicates that the ABI being targeted requires that an
728        //     unwind table entry be produced for this function even if we can show
729        //     that no exceptions passes by it. This is normally the case for the
730        //     ELF x86-64 abi, but it can be disabled for some compilation units.
731        //
732        // Typically when we're compiling with `-C panic=abort` we don't need
733        // `uwtable` because we can't generate any exceptions! But note that
734        // some targets require unwind tables to generate backtraces.
735        // Unwind tables are needed when compiling with `-C panic=unwind`, but
736        // LLVM won't omit unwind tables unless the function is also marked as
737        // `nounwind`, so users are allowed to disable `uwtable` emission.
738        // Historically rustc always emits `uwtable` attributes by default, so
739        // even they can be disabled, they're still emitted by default.
740        //
741        // On some targets (including windows), however, exceptions include
742        // other events such as illegal instructions, segfaults, etc. This means
743        // that on Windows we end up still needing unwind tables even if the `-C
744        // panic=abort` flag is passed.
745        //
746        // You can also find more info on why Windows needs unwind tables in:
747        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
748        //
749        // If a target requires unwind tables, then they must be emitted.
750        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
751        // value, if it is provided, or disable them, if not.
752        self.target.requires_uwtable
753            || self
754                .opts
755                .cg
756                .force_unwind_tables
757                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
758    }
759
760    /// Returns the number of query threads that should be used for this
761    /// compilation
762    #[inline]
763    pub fn threads(&self) -> usize {
764        self.opts.unstable_opts.threads
765    }
766
767    /// Returns the number of codegen units that should be used for this
768    /// compilation
769    pub fn codegen_units(&self) -> CodegenUnits {
770        if let Some(n) = self.opts.cli_forced_codegen_units {
771            return CodegenUnits::User(n);
772        }
773        if let Some(n) = self.target.default_codegen_units {
774            return CodegenUnits::Default(n as usize);
775        }
776
777        // If incremental compilation is turned on, we default to a high number
778        // codegen units in order to reduce the "collateral damage" small
779        // changes cause.
780        if self.opts.incremental.is_some() {
781            return CodegenUnits::Default(256);
782        }
783
784        // Why is 16 codegen units the default all the time?
785        //
786        // The main reason for enabling multiple codegen units by default is to
787        // leverage the ability for the codegen backend to do codegen and
788        // optimization in parallel. This allows us, especially for large crates, to
789        // make good use of all available resources on the machine once we've
790        // hit that stage of compilation. Large crates especially then often
791        // take a long time in codegen/optimization and this helps us amortize that
792        // cost.
793        //
794        // Note that a high number here doesn't mean that we'll be spawning a
795        // large number of threads in parallel. The backend of rustc contains
796        // global rate limiting through the `jobserver` crate so we'll never
797        // overload the system with too much work, but rather we'll only be
798        // optimizing when we're otherwise cooperating with other instances of
799        // rustc.
800        //
801        // Rather a high number here means that we should be able to keep a lot
802        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
803        // to build we'll be guaranteed that all cpus will finish pretty closely
804        // to one another and we should make relatively optimal use of system
805        // resources
806        //
807        // Note that the main cost of codegen units is that it prevents LLVM
808        // from inlining across codegen units. Users in general don't have a lot
809        // of control over how codegen units are split up so it's our job in the
810        // compiler to ensure that undue performance isn't lost when using
811        // codegen units (aka we can't require everyone to slap `#[inline]` on
812        // everything).
813        //
814        // If we're compiling at `-O0` then the number doesn't really matter too
815        // much because performance doesn't matter and inlining is ok to lose.
816        // In debug mode we just want to try to guarantee that no cpu is stuck
817        // doing work that could otherwise be farmed to others.
818        //
819        // In release mode, however (O1 and above) performance does indeed
820        // matter! To recover the loss in performance due to inlining we'll be
821        // enabling ThinLTO by default (the function for which is just below).
822        // This will ensure that we recover any inlining wins we otherwise lost
823        // through codegen unit partitioning.
824        //
825        // ---
826        //
827        // Ok that's a lot of words but the basic tl;dr; is that we want a high
828        // number here -- but not too high. Additionally we're "safe" to have it
829        // always at the same number at all optimization levels.
830        //
831        // As a result 16 was chosen here! Mostly because it was a power of 2
832        // and most benchmarks agreed it was roughly a local optimum. Not very
833        // scientific.
834        CodegenUnits::Default(16)
835    }
836
837    pub fn teach(&self, code: ErrCode) -> bool {
838        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
839    }
840
841    pub fn edition(&self) -> Edition {
842        self.opts.edition
843    }
844
845    pub fn link_dead_code(&self) -> bool {
846        self.opts.cg.link_dead_code.unwrap_or(false)
847    }
848
849    pub fn filename_display_preference(
850        &self,
851        scope: RemapPathScopeComponents,
852    ) -> FileNameDisplayPreference {
853        assert!(
854            scope.bits().count_ones() == 1,
855            "one and only one scope should be passed to `Session::filename_display_preference`"
856        );
857        if self.opts.unstable_opts.remap_path_scope.contains(scope) {
858            FileNameDisplayPreference::Remapped
859        } else {
860            FileNameDisplayPreference::Local
861        }
862    }
863
864    /// Get the deployment target on Apple platforms based on the standard environment variables,
865    /// or fall back to the minimum version supported by `rustc`.
866    ///
867    /// This should be guarded behind `if sess.target.is_like_darwin`.
868    pub fn apple_deployment_target(&self) -> apple::OSVersion {
869        let min = apple::OSVersion::minimum_deployment_target(&self.target);
870        let env_var = apple::deployment_target_env_var(&self.target.os);
871
872        // FIXME(madsmtm): Track changes to this.
873        if let Ok(deployment_target) = env::var(env_var) {
874            match apple::OSVersion::from_str(&deployment_target) {
875                Ok(version) => {
876                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
877                    // It is common that the deployment target is set a bit too low, for example on
878                    // macOS Aarch64 to also target older x86_64. So we only want to warn when variable
879                    // is lower than the minimum OS supported by rustc, not when the variable is lower
880                    // than the minimum for a specific target.
881                    if version < os_min {
882                        self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
883                            env_var,
884                            version: version.fmt_pretty().to_string(),
885                            os_min: os_min.fmt_pretty().to_string(),
886                        });
887                    }
888
889                    // Raise the deployment target to the minimum supported.
890                    version.max(min)
891                }
892                Err(error) => {
893                    self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
894                    min
895                }
896            }
897        } else {
898            // If no deployment target variable is set, default to the minimum found above.
899            min
900        }
901    }
902
903    pub fn sanitizers(&self) -> SanitizerSet {
904        return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
905    }
906}
907
908// JUSTIFICATION: part of session construction
909#[allow(rustc::bad_opt_access)]
910fn default_emitter(
911    sopts: &config::Options,
912    source_map: Arc<SourceMap>,
913    translator: Translator,
914) -> Box<DynEmitter> {
915    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
916    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
917    let terminal_url = match sopts.unstable_opts.terminal_urls {
918        TerminalUrl::Auto => {
919            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
920                (Ok("truecolor"), Ok("xterm-256color"))
921                    if sopts.unstable_features.is_nightly_build() =>
922                {
923                    TerminalUrl::Yes
924                }
925                _ => TerminalUrl::No,
926            }
927        }
928        t => t,
929    };
930
931    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
932
933    match sopts.error_format {
934        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
935            HumanReadableErrorType::AnnotateSnippet { short, unicode } => {
936                let emitter =
937                    AnnotateSnippetEmitter::new(stderr_destination(color_config), translator)
938                        .sm(source_map)
939                        .short_message(short)
940                        .diagnostic_width(sopts.diagnostic_width)
941                        .macro_backtrace(macro_backtrace)
942                        .track_diagnostics(track_diagnostics)
943                        .terminal_url(terminal_url)
944                        .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
945                        .ignored_directories_in_source_blocks(
946                            sopts
947                                .unstable_opts
948                                .ignore_directory_in_diagnostics_source_blocks
949                                .clone(),
950                        );
951                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
952            }
953            HumanReadableErrorType::Default { short } => {
954                let emitter = HumanEmitter::new(stderr_destination(color_config), translator)
955                    .sm(source_map)
956                    .short_message(short)
957                    .diagnostic_width(sopts.diagnostic_width)
958                    .macro_backtrace(macro_backtrace)
959                    .track_diagnostics(track_diagnostics)
960                    .terminal_url(terminal_url)
961                    .theme(OutputTheme::Ascii)
962                    .ignored_directories_in_source_blocks(
963                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
964                    );
965                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
966            }
967        },
968        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
969            JsonEmitter::new(
970                Box::new(io::BufWriter::new(io::stderr())),
971                source_map,
972                translator,
973                pretty,
974                json_rendered,
975                color_config,
976            )
977            .ui_testing(sopts.unstable_opts.ui_testing)
978            .ignored_directories_in_source_blocks(
979                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
980            )
981            .diagnostic_width(sopts.diagnostic_width)
982            .macro_backtrace(macro_backtrace)
983            .track_diagnostics(track_diagnostics)
984            .terminal_url(terminal_url),
985        ),
986    }
987}
988
989// JUSTIFICATION: literally session construction
990#[allow(rustc::bad_opt_access)]
991#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
992pub fn build_session(
993    sopts: config::Options,
994    io: CompilerIO,
995    fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
996    registry: rustc_errors::registry::Registry,
997    fluent_resources: Vec<&'static str>,
998    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
999    target: Target,
1000    cfg_version: &'static str,
1001    ice_file: Option<PathBuf>,
1002    using_internal_features: &'static AtomicBool,
1003) -> Session {
1004    // FIXME: This is not general enough to make the warning lint completely override
1005    // normal diagnostic warnings, since the warning lint can also be denied and changed
1006    // later via the source code.
1007    let warnings_allow = sopts
1008        .lint_opts
1009        .iter()
1010        .rfind(|&(key, _)| *key == "warnings")
1011        .is_some_and(|&(_, level)| level == lint::Allow);
1012    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1013    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1014
1015    let translator = Translator {
1016        fluent_bundle,
1017        fallback_fluent_bundle: fallback_fluent_bundle(
1018            fluent_resources,
1019            sopts.unstable_opts.translate_directionality_markers,
1020        ),
1021    };
1022    let source_map = rustc_span::source_map::get_source_map().unwrap();
1023    let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
1024
1025    let mut dcx = DiagCtxt::new(emitter)
1026        .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1027        .with_registry(registry);
1028    if let Some(ice_file) = ice_file {
1029        dcx = dcx.with_ice_file(ice_file);
1030    }
1031
1032    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1033    let (host, target_warnings) = Target::search(&host_triple, sopts.sysroot.path())
1034        .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1035    for warning in target_warnings.warning_messages() {
1036        dcx.handle().warn(warning)
1037    }
1038
1039    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1040    {
1041        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1042
1043        let profiler = SelfProfiler::new(
1044            directory,
1045            sopts.crate_name.as_deref(),
1046            sopts.unstable_opts.self_profile_events.as_deref(),
1047            &sopts.unstable_opts.self_profile_counter,
1048        );
1049        match profiler {
1050            Ok(profiler) => Some(Arc::new(profiler)),
1051            Err(e) => {
1052                dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1053                None
1054            }
1055        }
1056    } else {
1057        None
1058    };
1059
1060    let mut psess = ParseSess::with_dcx(dcx, source_map);
1061    psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1062
1063    let host_triple = config::host_tuple();
1064    let target_triple = sopts.target_triple.tuple();
1065    // FIXME use host sysroot?
1066    let host_tlib_path =
1067        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1068    let target_tlib_path = if host_triple == target_triple {
1069        // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1070        // rescanning of the target lib path and an unnecessary allocation.
1071        Arc::clone(&host_tlib_path)
1072    } else {
1073        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1074    };
1075
1076    let prof = SelfProfilerRef::new(
1077        self_profiler,
1078        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1079    );
1080
1081    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1082        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1083        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1084        _ => CtfeBacktrace::Disabled,
1085    });
1086
1087    let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1088    let target_filesearch =
1089        filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1090    let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1091
1092    let invocation_temp = sopts
1093        .incremental
1094        .as_ref()
1095        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1096
1097    let timings = TimingSectionHandler::new(sopts.json_timings);
1098
1099    let sess = Session {
1100        target,
1101        host,
1102        opts: sopts,
1103        target_tlib_path,
1104        psess,
1105        io,
1106        incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1107        prof,
1108        timings,
1109        code_stats: Default::default(),
1110        lint_store: None,
1111        driver_lint_caps,
1112        ctfe_backtrace,
1113        miri_unleashed_features: Lock::new(Default::default()),
1114        asm_arch,
1115        target_features: Default::default(),
1116        unstable_target_features: Default::default(),
1117        cfg_version,
1118        using_internal_features,
1119        target_filesearch,
1120        host_filesearch,
1121        invocation_temp,
1122    };
1123
1124    validate_commandline_args_with_session_available(&sess);
1125
1126    sess
1127}
1128
1129/// Validate command line arguments with a `Session`.
1130///
1131/// If it is useful to have a Session available already for validating a commandline argument, you
1132/// can do so here.
1133// JUSTIFICATION: needs to access args to validate them
1134#[allow(rustc::bad_opt_access)]
1135fn validate_commandline_args_with_session_available(sess: &Session) {
1136    // Since we don't know if code in an rlib will be linked to statically or
1137    // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1138    // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1139    // these manually generated symbols confuse LLD when it tries to merge
1140    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1141    // when compiling for LLD ThinLTO. This way we can validly just not generate
1142    // the `dllimport` attributes and `__imp_` symbols in that case.
1143    if sess.opts.cg.linker_plugin_lto.enabled()
1144        && sess.opts.cg.prefer_dynamic
1145        && sess.target.is_like_windows
1146    {
1147        sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1148    }
1149
1150    // Make sure that any given profiling data actually exists so LLVM can't
1151    // decide to silently skip PGO.
1152    if let Some(ref path) = sess.opts.cg.profile_use {
1153        if !path.exists() {
1154            sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1155        }
1156    }
1157
1158    // Do the same for sample profile data.
1159    if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1160        if !path.exists() {
1161            sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1162        }
1163    }
1164
1165    // Unwind tables cannot be disabled if the target requires them.
1166    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1167        if sess.target.requires_uwtable && !include_uwtables {
1168            sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1169        }
1170    }
1171
1172    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1173    let supported_sanitizers = sess.target.options.supported_sanitizers;
1174    let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1175    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled
1176    // we should allow Shadow Call Stack sanitizer.
1177    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1178        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1179    }
1180    match unsupported_sanitizers.into_iter().count() {
1181        0 => {}
1182        1 => {
1183            sess.dcx()
1184                .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1185        }
1186        _ => {
1187            sess.dcx().emit_err(errors::SanitizersNotSupported {
1188                us: unsupported_sanitizers.to_string(),
1189            });
1190        }
1191    }
1192
1193    // Cannot mix and match mutually-exclusive sanitizers.
1194    if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1195        sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1196            first: first.to_string(),
1197            second: second.to_string(),
1198        });
1199    }
1200
1201    // Cannot enable crt-static with sanitizers on Linux
1202    if sess.crt_static(None)
1203        && !sess.opts.unstable_opts.sanitizer.is_empty()
1204        && !sess.target.is_like_msvc
1205    {
1206        sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1207    }
1208
1209    // LLVM CFI requires LTO.
1210    if sess.is_sanitizer_cfi_enabled()
1211        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1212    {
1213        sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1214    }
1215
1216    // KCFI requires panic=abort
1217    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1218        sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1219    }
1220
1221    // LLVM CFI using rustc LTO requires a single codegen unit.
1222    if sess.is_sanitizer_cfi_enabled()
1223        && sess.lto() == config::Lto::Fat
1224        && (sess.codegen_units().as_usize() != 1)
1225    {
1226        sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1227    }
1228
1229    // Canonical jump tables requires CFI.
1230    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1231        if !sess.is_sanitizer_cfi_enabled() {
1232            sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1233        }
1234    }
1235
1236    // KCFI arity indicator requires KCFI.
1237    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1238        sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1239    }
1240
1241    // LLVM CFI pointer generalization requires CFI or KCFI.
1242    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1243        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1244            sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1245        }
1246    }
1247
1248    // LLVM CFI integer normalization requires CFI or KCFI.
1249    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1250        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1251            sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1252        }
1253    }
1254
1255    // LTO unit splitting requires LTO.
1256    if sess.is_split_lto_unit_enabled()
1257        && !(sess.lto() == config::Lto::Fat
1258            || sess.lto() == config::Lto::Thin
1259            || sess.opts.cg.linker_plugin_lto.enabled())
1260    {
1261        sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1262    }
1263
1264    // VFE requires LTO.
1265    if sess.lto() != config::Lto::Fat {
1266        if sess.opts.unstable_opts.virtual_function_elimination {
1267            sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1268        }
1269    }
1270
1271    if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1272        if !sess.target.options.supports_stack_protector {
1273            sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1274                stack_protector: sess.opts.unstable_opts.stack_protector,
1275                target_triple: &sess.opts.target_triple,
1276            });
1277        }
1278    }
1279
1280    if sess.opts.unstable_opts.small_data_threshold.is_some() {
1281        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1282            sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1283                target_triple: &sess.opts.target_triple,
1284            })
1285        }
1286    }
1287
1288    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1289        sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1290    }
1291
1292    if let Some(dwarf_version) =
1293        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1294    {
1295        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.
1296        if dwarf_version < 2 || dwarf_version > 5 {
1297            sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1298        }
1299    }
1300
1301    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1302        && !sess.opts.unstable_opts.unstable_options
1303    {
1304        sess.dcx()
1305            .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1306    }
1307
1308    if sess.opts.unstable_opts.embed_source {
1309        let dwarf_version = sess.dwarf_version();
1310
1311        if dwarf_version < 5 {
1312            sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1313        }
1314
1315        if sess.opts.debuginfo == DebugInfo::None {
1316            sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1317        }
1318    }
1319
1320    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1321        sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1322    }
1323
1324    if let Some(flavor) = sess.opts.cg.linker_flavor
1325        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1326    {
1327        let flavor = flavor.desc();
1328        sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1329    }
1330
1331    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1332        if !matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {
1333            sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1334        }
1335    }
1336
1337    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1338        if !matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {
1339            sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1340        }
1341    }
1342
1343    if let Some(regparm) = sess.opts.unstable_opts.regparm {
1344        if regparm > 3 {
1345            sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1346        }
1347        if sess.target.arch != Arch::X86 {
1348            sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1349        }
1350    }
1351    if sess.opts.unstable_opts.reg_struct_return {
1352        if sess.target.arch != Arch::X86 {
1353            sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1354        }
1355    }
1356
1357    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1358    // kept as a `match` to force a change if new ones are added, even if we currently only support
1359    // `thunk-extern` like Clang.
1360    match sess.opts.unstable_opts.function_return {
1361        FunctionReturn::Keep => (),
1362        FunctionReturn::ThunkExtern => {
1363            // FIXME: In principle, the inherited base LLVM target code model could be large,
1364            // but this only checks whether we were passed one explicitly (like Clang does).
1365            if let Some(code_model) = sess.code_model()
1366                && code_model == CodeModel::Large
1367            {
1368                sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1369            }
1370        }
1371    }
1372
1373    if sess.opts.cg.soft_float {
1374        if sess.target.arch == Arch::Arm {
1375            sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1376        } else {
1377            // All `use_softfp` does is the equivalent of `-mfloat-abi` in GCC/clang, which only exists on ARM targets.
1378            // We document this flag to only affect `*eabihf` targets, so let's show a warning for all other targets.
1379            sess.dcx().emit_warn(errors::SoftFloatIgnored);
1380        }
1381    }
1382}
1383
1384/// Holds data on the current incremental compilation session, if there is one.
1385#[derive(Debug)]
1386enum IncrCompSession {
1387    /// This is the state the session will be in until the incr. comp. dir is
1388    /// needed.
1389    NotInitialized,
1390    /// This is the state during which the session directory is private and can
1391    /// be modified. `_lock_file` is never directly used, but its presence
1392    /// alone has an effect, because the file will unlock when the session is
1393    /// dropped.
1394    Active { session_directory: PathBuf, _lock_file: flock::Lock },
1395    /// This is the state after the session directory has been finalized. In this
1396    /// state, the contents of the directory must not be modified any more.
1397    Finalized { session_directory: PathBuf },
1398    /// This is an error state that is reached when some compilation error has
1399    /// occurred. It indicates that the contents of the session directory must
1400    /// not be used, since they might be invalid.
1401    InvalidBecauseOfErrors { session_directory: PathBuf },
1402}
1403
1404/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1405pub struct EarlyDiagCtxt {
1406    dcx: DiagCtxt,
1407}
1408
1409impl EarlyDiagCtxt {
1410    pub fn new(output: ErrorOutputType) -> Self {
1411        let emitter = mk_emitter(output);
1412        Self { dcx: DiagCtxt::new(emitter) }
1413    }
1414
1415    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1416    /// format. If `early_err` was previously called this will panic.
1417    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1418        assert!(self.dcx.handle().has_errors().is_none());
1419
1420        let emitter = mk_emitter(output);
1421        self.dcx = DiagCtxt::new(emitter);
1422    }
1423
1424    #[allow(rustc::untranslatable_diagnostic)]
1425    #[allow(rustc::diagnostic_outside_of_impl)]
1426    pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1427        self.dcx.handle().note(msg)
1428    }
1429
1430    #[allow(rustc::untranslatable_diagnostic)]
1431    #[allow(rustc::diagnostic_outside_of_impl)]
1432    pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1433        self.dcx.handle().struct_help(msg).emit()
1434    }
1435
1436    #[allow(rustc::untranslatable_diagnostic)]
1437    #[allow(rustc::diagnostic_outside_of_impl)]
1438    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1439    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1440        self.dcx.handle().err(msg)
1441    }
1442
1443    #[allow(rustc::untranslatable_diagnostic)]
1444    #[allow(rustc::diagnostic_outside_of_impl)]
1445    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1446        self.dcx.handle().fatal(msg)
1447    }
1448
1449    #[allow(rustc::untranslatable_diagnostic)]
1450    #[allow(rustc::diagnostic_outside_of_impl)]
1451    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1452        self.dcx.handle().struct_fatal(msg)
1453    }
1454
1455    #[allow(rustc::untranslatable_diagnostic)]
1456    #[allow(rustc::diagnostic_outside_of_impl)]
1457    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1458        self.dcx.handle().warn(msg)
1459    }
1460
1461    #[allow(rustc::untranslatable_diagnostic)]
1462    #[allow(rustc::diagnostic_outside_of_impl)]
1463    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1464        self.dcx.handle().struct_warn(msg)
1465    }
1466}
1467
1468fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1469    // FIXME(#100717): early errors aren't translated at the moment, so this is fine, but it will
1470    // need to reference every crate that might emit an early error for translation to work.
1471    let translator =
1472        Translator::with_fallback_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1473    let emitter: Box<DynEmitter> = match output {
1474        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1475            HumanReadableErrorType::AnnotateSnippet { short, unicode } => Box::new(
1476                AnnotateSnippetEmitter::new(stderr_destination(color_config), translator)
1477                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1478                    .short_message(short),
1479            ),
1480            HumanReadableErrorType::Default { short } => Box::new(
1481                HumanEmitter::new(stderr_destination(color_config), translator)
1482                    .theme(OutputTheme::Ascii)
1483                    .short_message(short),
1484            ),
1485        },
1486        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1487            Box::new(JsonEmitter::new(
1488                Box::new(io::BufWriter::new(io::stderr())),
1489                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1490                translator,
1491                pretty,
1492                json_rendered,
1493                color_config,
1494            ))
1495        }
1496    };
1497    emitter
1498}
1499
1500pub trait RemapFileNameExt {
1501    type Output<'a>
1502    where
1503        Self: 'a;
1504
1505    /// Returns a possibly remapped filename based on the passed scope and remap cli options.
1506    ///
1507    /// One and only one scope should be passed to this method, it will panic otherwise.
1508    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1509}
1510
1511impl RemapFileNameExt for rustc_span::FileName {
1512    type Output<'a> = rustc_span::FileNameDisplay<'a>;
1513
1514    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1515        assert!(
1516            scope.bits().count_ones() == 1,
1517            "one and only one scope should be passed to for_scope"
1518        );
1519        if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1520            self.prefer_remapped_unconditionally()
1521        } else {
1522            self.prefer_local()
1523        }
1524    }
1525}
1526
1527impl RemapFileNameExt for rustc_span::RealFileName {
1528    type Output<'a> = &'a Path;
1529
1530    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1531        assert!(
1532            scope.bits().count_ones() == 1,
1533            "one and only one scope should be passed to for_scope"
1534        );
1535        if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1536            self.remapped_path_if_available()
1537        } else {
1538            self.local_path_if_available()
1539        }
1540    }
1541}