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