1use std::any::Any;2use std::path::PathBuf;3use std::str::FromStr;4use std::sync::Arc;5use std::sync::atomic::{AtomicBool, AtomicUsize};6use std::{env, io};78use rand::{RngCore, rng};9use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};10use rustc_data_structures::flock;11use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};13use rustc_data_structures::sync::{14 AppendOnlyVec, DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock,15};16use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;17use rustc_errors::codes::*;18use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};19use rustc_errors::json::JsonEmitter;20use rustc_errors::timings::TimingSectionHandler;21use rustc_errors::{22 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,23 TerminalUrl,24};25use rustc_feature::UnstableFeatures;26use rustc_hir::limit::Limit;27use rustc_macros::StableHash;28pub use rustc_span::def_id::StableCrateId;29use rustc_span::edition::Edition;30use rustc_span::source_map::{FilePathMapping, SourceMap};31use rustc_span::{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};3839use crate::code_stats::CodeStats;40pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};41use crate::config::{42 self, Cfg, CheckCfg, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType,43 FunctionReturn, Input, InstrumentCoverage, OptLevel, OutFileName, OutputType,44 SwitchWithOptPath,45};46use crate::filesearch::FileSearch;47use crate::lint::LintId;48use crate::parse::ParseSess;49use crate::search_paths::SearchPath;50use crate::{errors, filesearch, lint};5152/// 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 error58 /// (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}6364#[derive(Clone, Copy, Debug, StableHash)]65pub struct Limits {66 /// The maximum recursion limit for potentially infinitely recursive67 /// operations such as auto-dereference and monomorphization.68 pub recursion_limit: Limit,69 /// The size at which the `large_assignments` lint starts70 /// 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}7778pub 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}8485pub 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}8990/// Represents the data associated with a compilation91/// 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 pub unstable_features: UnstableFeatures,99 pub config: Cfg,100 pub check_config: CheckCfg,101 /// Spans passed to `proc_macro::quote_span`. Each span has a numerical102 /// identifier represented by its position in the vector.103 proc_macro_quoted_spans: AppendOnlyVec<Span>,104105 /// Input, input file path and output file path to this compilation process.106 pub io: CompilerIO,107108 incr_comp_session: RwLock<IncrCompSession>,109110 /// Used by `-Z self-profile`.111 pub prof: SelfProfilerRef,112113 /// Used to emit section timings events (enabled by `--json=timings`).114 pub timings: TimingSectionHandler,115116 /// Data about code being compiled, gathered during compilation.117 pub code_stats: CodeStats,118119 /// This only ever stores a `LintStore` but we don't want a dependency on that type here.120 pub lint_store: Option<Arc<dyn DynLintStore>>,121122 /// Cap lint level specified by a driver specifically.123 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,124125 /// Tracks the current behavior of the CTFE engine when an error occurs.126 /// Options range from returning the error without a backtrace to returning an error127 /// and immediately printing the backtrace to stderr.128 /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when129 /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE130 /// errors.131 pub ctfe_backtrace: Lock<CtfeBacktrace>,132133 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a134 /// const check, optionally with the relevant feature gate. We use this to135 /// warn about unleashing, but with a single diagnostic instead of dozens that136 /// drown everything else in noise.137 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,138139 /// Architecture to use for interpreting asm!.140 pub asm_arch: Option<InlineAsmArch>,141142 /// Set of enabled features for the current target.143 pub target_features: FxIndexSet<Symbol>,144145 /// Set of enabled features for the current target, including unstable ones.146 pub unstable_target_features: FxIndexSet<Symbol>,147148 /// The version of the rustc process, possibly including a commit hash and description.149 pub cfg_version: &'static str,150151 /// The inner atomic value is set to true when a feature marked as `internal` is152 /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with153 /// internal features are wontfix, and they are usually the cause of the ICEs.154 /// None signifies that this is not tracked.155 pub using_internal_features: &'static AtomicBool,156157 /// Environment variables accessed during the build and their values when they exist.158 pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,159160 /// File paths accessed during the build.161 pub file_depinfo: Lock<FxIndexSet<Symbol>>,162163 target_filesearch: FileSearch,164 host_filesearch: FileSearch,165166 /// A random string generated per invocation of rustc.167 ///168 /// This is prepended to all temporary files so that they do not collide169 /// during concurrent invocations of rustc, or past invocations that were170 /// preserved with a flag like `-C save-temps`, since these files may be171 /// hard linked.172 pub invocation_temp: Option<String>,173174 /// The names of intrinsics that the current codegen backend replaces175 /// with its own implementations.176 pub replaced_intrinsics: FxHashSet<Symbol>,177178 /// Does the codegen backend support ThinLTO?179 pub thin_lto_supported: bool,180181 /// Global per-session counter for MIR optimization pass applications.182 ///183 /// Used by `-Zmir-opt-bisect-limit` to assign an index to each184 /// optimization-pass execution candidate during this compilation.185 pub mir_opt_bisect_eval_count: AtomicUsize,186187 /// Enabled features that are used in the current compilation.188 ///189 /// The value is the `DepNodeIndex` of the node encodes the used feature.190 pub used_features: Lock<FxHashMap<Symbol, u32>>,191}192193#[derive(Clone, Copy)]194pub enum CodegenUnits {195 /// Specified by the user. In this case we try fairly hard to produce the196 /// number of CGUs requested.197 User(usize),198199 /// A default value, i.e. not specified by the user. In this case we take200 /// more liberties about CGU formation, e.g. avoid producing very small201 /// CGUs.202 Default(usize),203}204205impl CodegenUnits {206 pub fn as_usize(self) -> usize {207 match self {208 CodegenUnits::User(n) => n,209 CodegenUnits::Default(n) => n,210 }211 }212}213214pub struct LintGroup {215 pub name: &'static str,216 pub lints: Vec<LintId>,217 pub is_externally_loaded: bool,218}219220impl Session {221 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {222 self.miri_unleashed_features.lock().push((span, feature_gate));223 }224225 pub fn local_crate_source_file(&self) -> Option<RealFileName> {226 Some(227 self.source_map()228 .path_mapping()229 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),230 )231 }232233 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {234 let mut guar = None;235 let unleashed_features = self.miri_unleashed_features.lock();236 if !unleashed_features.is_empty() {237 let mut must_err = false;238 // Create a diagnostic pointing at where things got unleashed.239 self.dcx().emit_warn(errors::SkippingConstChecks {240 unleashed_features: unleashed_features241 .iter()242 .map(|(span, gate)| {243 gate.map(|gate| {244 must_err = true;245 errors::UnleashedFeatureHelp::Named { span: *span, gate }246 })247 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })248 })249 .collect(),250 });251252 // If we should err, make sure we did.253 if must_err && self.dcx().has_errors().is_none() {254 // We have skipped a feature gate, and not run into other errors... reject.255 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));256 }257 }258 guar259 }260261 /// Invoked all the way at the end to finish off diagnostics printing.262 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {263 let mut guar = None;264 guar = guar.or(self.check_miri_unleashed_features());265 guar = guar.or(self.dcx().emit_stashed_diagnostics());266 self.dcx().print_error_count();267 if self.opts.json_future_incompat {268 self.dcx().emit_future_breakage_report();269 }270 guar271 }272273 /// Returns true if the crate is a testing one.274 pub fn is_test_crate(&self) -> bool {275 self.opts.test276 }277278 /// `feature` must be a language feature.279 #[track_caller]280 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {281 let mut err = self.dcx().create_err(err);282 if err.code.is_none() {283 err.code(E0658);284 }285 errors::add_feature_diagnostics(&mut err, self, feature);286 err287 }288289 /// Record the fact that we called `trimmed_def_paths`, and do some290 /// checking about whether its cost was justified.291 pub fn record_trimmed_def_paths(&self) {292 if self.opts.unstable_opts.print_type_sizes293 || self.opts.unstable_opts.query_dep_graph294 || self.opts.unstable_opts.dump_mir.is_some()295 || self.opts.unstable_opts.unpretty.is_some()296 || self.prof.is_args_recording_enabled()297 || self.opts.output_types.contains_key(&OutputType::Mir)298 || std::env::var_os("RUSTC_LOG").is_some()299 {300 return;301 }302303 self.dcx().set_must_produce_diag()304 }305306 #[inline]307 pub fn dcx(&self) -> DiagCtxtHandle<'_> {308 self.psess.dcx()309 }310311 #[inline]312 pub fn source_map(&self) -> &SourceMap {313 self.psess.source_map()314 }315316 pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {317 // This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for318 // AppendOnlyVec, so we resort to this scheme.319 self.proc_macro_quoted_spans.iter_enumerated()320 }321322 pub fn save_proc_macro_span(&self, span: Span) -> usize {323 self.proc_macro_quoted_spans.push(span)324 }325326 /// Returns `true` if internal lints should be added to the lint store - i.e. if327 /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors328 /// to be emitted under rustdoc).329 pub fn enable_internal_lints(&self) -> bool {330 self.unstable_options() && !self.opts.actually_rustdoc331 }332333 pub fn instrument_coverage(&self) -> bool {334 self.opts.cg.instrument_coverage() != InstrumentCoverage::No335 }336337 pub fn instrument_coverage_branch(&self) -> bool {338 self.instrument_coverage()339 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch340 }341342 pub fn instrument_coverage_condition(&self) -> bool {343 self.instrument_coverage()344 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition345 }346347 /// Provides direct access to the `CoverageOptions` struct, so that348 /// individual flags for debugging/testing coverage instrumetation don't349 /// need separate accessors.350 pub fn coverage_options(&self) -> &CoverageOptions {351 &self.opts.unstable_opts.coverage_options352 }353354 pub fn is_sanitizer_cfi_enabled(&self) -> bool {355 self.sanitizers().contains(SanitizerSet::CFI)356 }357358 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {359 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)360 }361362 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {363 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)364 }365366 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {367 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)368 }369370 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {371 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)372 }373374 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {375 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)376 }377378 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {379 self.sanitizers().contains(SanitizerSet::KCFI)380 }381382 pub fn is_split_lto_unit_enabled(&self) -> bool {383 self.opts.unstable_opts.split_lto_unit == Some(true)384 }385386 /// Check whether this compile session and crate type use static crt.387 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {388 if !self.target.crt_static_respected {389 // If the target does not opt in to crt-static support, use its default.390 return self.target.crt_static_default;391 }392393 let requested_features = self.opts.cg.target_feature.split(',');394 let found_negative = requested_features.clone().any(|r| r == "-crt-static");395 let found_positive = requested_features.clone().any(|r| r == "+crt-static");396397 // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)398 #[allow(rustc::bad_opt_access)]399 if found_positive || found_negative {400 found_positive401 } else if crate_type == Some(CrateType::ProcMacro)402 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)403 {404 // FIXME: When crate_type is not available,405 // we use compiler options to determine the crate_type.406 // We can't check `#![crate_type = "proc-macro"]` here.407 false408 } else {409 self.target.crt_static_default410 }411 }412413 pub fn is_wasi_reactor(&self) -> bool {414 self.target.options.os == Os::Wasi415 && matches!(416 self.opts.unstable_opts.wasi_exec_model,417 Some(config::WasiExecModel::Reactor)418 )419 }420421 /// Returns `true` if the target can use the current split debuginfo configuration.422 pub fn target_can_use_split_dwarf(&self) -> bool {423 self.target.debuginfo_kind == DebuginfoKind::Dwarf424 }425426 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {427 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())428 }429430 pub fn target_filesearch(&self) -> &filesearch::FileSearch {431 &self.target_filesearch432 }433 pub fn host_filesearch(&self) -> &filesearch::FileSearch {434 &self.host_filesearch435 }436437 /// Returns a list of directories where target-specific tool binaries are located. Some fallback438 /// directories are also returned, for example if `--sysroot` is used but tools are missing439 /// (#125246): we also add the bin directories to the sysroot where rustc is located.440 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {441 let search_paths = self442 .opts443 .sysroot444 .all_paths()445 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));446447 if self_contained {448 // The self-contained tools are expected to be e.g. in `bin/self-contained` in the449 // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the450 // fallback paths.451 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()452 } else {453 search_paths.collect()454 }455 }456457 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {458 let mut incr_comp_session = self.incr_comp_session.borrow_mut();459460 if let IncrCompSession::NotInitialized = *incr_comp_session {461 } else {462 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)463 }464465 *incr_comp_session =466 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };467 }468469 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {470 let mut incr_comp_session = self.incr_comp_session.borrow_mut();471472 if let IncrCompSession::Active { .. } = *incr_comp_session {473 } else {474 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);475 }476477 // Note: this will also drop the lock file, thus unlocking the directory.478 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };479 }480481 pub fn mark_incr_comp_session_as_invalid(&self) {482 let mut incr_comp_session = self.incr_comp_session.borrow_mut();483484 let session_directory = match *incr_comp_session {485 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),486 IncrCompSession::InvalidBecauseOfErrors { .. } => return,487 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),488 };489490 // Note: this will also drop the lock file, thus unlocking the directory.491 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };492 }493494 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {495 let incr_comp_session = self.incr_comp_session.borrow();496 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {497 IncrCompSession::NotInitialized => panic!(498 "trying to get session directory from `IncrCompSession`: {:?}",499 *incr_comp_session,500 ),501 IncrCompSession::Active { ref session_directory, .. }502 | IncrCompSession::Finalized { ref session_directory }503 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {504 session_directory505 }506 })507 }508509 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {510 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())511 }512513 /// Is this edition 2015?514 pub fn is_rust_2015(&self) -> bool {515 self.edition().is_rust_2015()516 }517518 /// Are we allowed to use features from the Rust 2018 edition?519 pub fn at_least_rust_2018(&self) -> bool {520 self.edition().at_least_rust_2018()521 }522523 /// Are we allowed to use features from the Rust 2021 edition?524 pub fn at_least_rust_2021(&self) -> bool {525 self.edition().at_least_rust_2021()526 }527528 /// Are we allowed to use features from the Rust 2024 edition?529 pub fn at_least_rust_2024(&self) -> bool {530 self.edition().at_least_rust_2024()531 }532533 /// Returns `true` if we should use the PLT for shared library calls.534 pub fn needs_plt(&self) -> bool {535 // Check if the current target usually wants PLT to be enabled.536 // The user can use the command line flag to override it.537 let want_plt = self.target.plt_by_default;538539 let dbg_opts = &self.opts.unstable_opts;540541 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);542543 // Only enable this optimization by default if full relro is also enabled.544 // In this case, lazy binding was already unavailable, so nothing is lost.545 // This also ensures `-Wl,-z,now` is supported by the linker.546 let full_relro = RelroLevel::Full == relro_level;547548 // If user didn't explicitly forced us to use / skip the PLT,549 // then use it unless the target doesn't want it by default or the full relro forces it on.550 dbg_opts.plt.unwrap_or(want_plt || !full_relro)551 }552553 /// Checks if LLVM lifetime markers should be emitted.554 pub fn emit_lifetime_markers(&self) -> bool {555 self.opts.optimize != config::OptLevel::No556 // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.557 //558 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.559 //560 // HWAddressSanitizer and KernelHWAddressSanitizer will use lifetimes to detect use after561 // scope bugs in the future.562 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)563 }564565 pub fn diagnostic_width(&self) -> usize {566 let default_column_width = 140;567 if let Some(width) = self.opts.diagnostic_width {568 width569 } else if self.opts.unstable_opts.ui_testing {570 default_column_width571 } else {572 termize::dimensions().map_or(default_column_width, |(w, _)| w)573 }574 }575576 /// Returns the default symbol visibility.577 pub fn default_visibility(&self) -> SymbolVisibility {578 self.opts579 .unstable_opts580 .default_visibility581 .or(self.target.options.default_visibility)582 .unwrap_or(SymbolVisibility::Interposable)583 }584585 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {586 if verbatim {587 ("", "")588 } else {589 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)590 }591 }592593 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {594 match self.lint_store {595 Some(ref lint_store) => lint_store.lint_groups_iter(),596 None => Box::new(std::iter::empty()),597 }598 }599}600601// JUSTIFICATION: defn of the suggested wrapper fns602#[allow(rustc::bad_opt_access)]603impl Session {604 pub fn verbose_internals(&self) -> bool {605 self.opts.unstable_opts.verbose_internals606 }607608 pub fn print_llvm_stats(&self) -> bool {609 self.opts.unstable_opts.print_codegen_stats610 }611612 pub fn verify_llvm_ir(&self) -> bool {613 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()614 }615616 pub fn binary_dep_depinfo(&self) -> bool {617 self.opts.unstable_opts.binary_dep_depinfo618 }619620 pub fn mir_opt_level(&self) -> usize {621 self.opts622 .unstable_opts623 .mir_opt_level624 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })625 }626627 /// Calculates the flavor of LTO to use for this compilation.628 pub fn lto(&self) -> config::Lto {629 // If our target has codegen requirements ignore the command line630 if self.target.requires_lto {631 return config::Lto::Fat;632 }633634 // If the user specified something, return that. If they only said `-C635 // lto` and we've for whatever reason forced off ThinLTO via the CLI,636 // then ensure we can't use a ThinLTO.637 match self.opts.cg.lto {638 config::LtoCli::Unspecified => {639 // The compiler was invoked without the `-Clto` flag. Fall640 // through to the default handling641 }642 config::LtoCli::No => {643 // The user explicitly opted out of any kind of LTO644 return config::Lto::No;645 }646 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {647 // All of these mean fat LTO648 return config::Lto::Fat;649 }650 config::LtoCli::Thin => {651 // The user explicitly asked for ThinLTO652 if !self.thin_lto_supported {653 // Backend doesn't support ThinLTO, fallback to fat LTO.654 self.dcx().emit_warn(errors::ThinLtoNotSupportedByBackend);655 return config::Lto::Fat;656 }657 return config::Lto::Thin;658 }659 }660661 if !self.thin_lto_supported {662 return config::Lto::No;663 }664665 // Ok at this point the target doesn't require anything and the user666 // hasn't asked for anything. Our next decision is whether or not667 // we enable "auto" ThinLTO where we use multiple codegen units and668 // then do ThinLTO over those codegen units. The logic below will669 // either return `No` or `ThinLocal`.670671 // If processing command line options determined that we're incompatible672 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.673 if self.opts.cli_forced_local_thinlto_off {674 return config::Lto::No;675 }676677 // If `-Z thinlto` specified process that, but note that this is mostly678 // a deprecated option now that `-C lto=thin` exists.679 if let Some(enabled) = self.opts.unstable_opts.thinlto {680 if enabled {681 return config::Lto::ThinLocal;682 } else {683 return config::Lto::No;684 }685 }686687 // If there's only one codegen unit and LTO isn't enabled then there's688 // no need for ThinLTO so just return false.689 if self.codegen_units().as_usize() == 1 {690 return config::Lto::No;691 }692693 // Now we're in "defaults" territory. By default we enable ThinLTO for694 // optimized compiles (anything greater than O0).695 match self.opts.optimize {696 config::OptLevel::No => config::Lto::No,697 _ => config::Lto::ThinLocal,698 }699 }700701 /// Returns the panic strategy for this compile session. If the user explicitly selected one702 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.703 pub fn panic_strategy(&self) -> PanicStrategy {704 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)705 }706707 pub fn fewer_names(&self) -> bool {708 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {709 fewer_names710 } else {711 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)712 || self.opts.output_types.contains_key(&OutputType::Bitcode)713 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.714 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);715 !more_names716 }717 }718719 pub fn unstable_options(&self) -> bool {720 self.opts.unstable_opts.unstable_options721 }722723 pub fn is_nightly_build(&self) -> bool {724 self.opts.unstable_features.is_nightly_build()725 }726727 pub fn overflow_checks(&self) -> bool {728 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)729 }730731 pub fn ub_checks(&self) -> bool {732 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)733 }734735 pub fn contract_checks(&self) -> bool {736 self.opts.unstable_opts.contract_checks.unwrap_or(false)737 }738739 pub fn relocation_model(&self) -> RelocModel {740 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)741 }742743 pub fn code_model(&self) -> Option<CodeModel> {744 self.opts.cg.code_model.or(self.target.code_model)745 }746747 pub fn tls_model(&self) -> TlsModel {748 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)749 }750751 pub fn direct_access_external_data(&self) -> Option<bool> {752 self.opts753 .unstable_opts754 .direct_access_external_data755 .or(self.target.direct_access_external_data)756 }757758 pub fn split_debuginfo(&self) -> SplitDebuginfo {759 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)760 }761762 /// Returns the DWARF version passed on the CLI or the default for the target.763 pub fn dwarf_version(&self) -> u32 {764 self.opts765 .cg766 .dwarf_version767 .or(self.opts.unstable_opts.dwarf_version)768 .unwrap_or(self.target.default_dwarf_version)769 }770771 pub fn stack_protector(&self) -> StackProtector {772 if self.target.options.supports_stack_protector {773 self.opts.unstable_opts.stack_protector774 } else {775 StackProtector::None776 }777 }778779 pub fn must_emit_unwind_tables(&self) -> bool {780 // This is used to control the emission of the `uwtable` attribute on781 // LLVM functions. The `uwtable` attribute according to LLVM is:782 //783 // This attribute indicates that the ABI being targeted requires that an784 // unwind table entry be produced for this function even if we can show785 // that no exceptions passes by it. This is normally the case for the786 // ELF x86-64 abi, but it can be disabled for some compilation units.787 //788 // Typically when we're compiling with `-C panic=abort` we don't need789 // `uwtable` because we can't generate any exceptions! But note that790 // some targets require unwind tables to generate backtraces.791 // Unwind tables are needed when compiling with `-C panic=unwind`, but792 // LLVM won't omit unwind tables unless the function is also marked as793 // `nounwind`, so users are allowed to disable `uwtable` emission.794 // Historically rustc always emits `uwtable` attributes by default, so795 // even they can be disabled, they're still emitted by default.796 //797 // On some targets (including windows), however, exceptions include798 // other events such as illegal instructions, segfaults, etc. This means799 // that on Windows we end up still needing unwind tables even if the `-C800 // panic=abort` flag is passed.801 //802 // You can also find more info on why Windows needs unwind tables in:803 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078804 //805 // If a target requires unwind tables, then they must be emitted.806 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`807 // value, if it is provided, or disable them, if not.808 self.target.requires_uwtable809 || self810 .opts811 .cg812 .force_unwind_tables813 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)814 }815816 /// Returns the number of query threads that should be used for this817 /// compilation818 #[inline]819 pub fn threads(&self) -> usize {820 self.opts.unstable_opts.threads821 }822823 /// Returns the number of codegen units that should be used for this824 /// compilation825 pub fn codegen_units(&self) -> CodegenUnits {826 if let Some(n) = self.opts.cli_forced_codegen_units {827 return CodegenUnits::User(n);828 }829 if let Some(n) = self.target.default_codegen_units {830 return CodegenUnits::Default(n as usize);831 }832833 // If incremental compilation is turned on, we default to a high number834 // codegen units in order to reduce the "collateral damage" small835 // changes cause.836 if self.opts.incremental.is_some() {837 return CodegenUnits::Default(256);838 }839840 // Why is 16 codegen units the default all the time?841 //842 // The main reason for enabling multiple codegen units by default is to843 // leverage the ability for the codegen backend to do codegen and844 // optimization in parallel. This allows us, especially for large crates, to845 // make good use of all available resources on the machine once we've846 // hit that stage of compilation. Large crates especially then often847 // take a long time in codegen/optimization and this helps us amortize that848 // cost.849 //850 // Note that a high number here doesn't mean that we'll be spawning a851 // large number of threads in parallel. The backend of rustc contains852 // global rate limiting through the `jobserver` crate so we'll never853 // overload the system with too much work, but rather we'll only be854 // optimizing when we're otherwise cooperating with other instances of855 // rustc.856 //857 // Rather a high number here means that we should be able to keep a lot858 // of idle cpus busy. By ensuring that no codegen unit takes *too* long859 // to build we'll be guaranteed that all cpus will finish pretty closely860 // to one another and we should make relatively optimal use of system861 // resources862 //863 // Note that the main cost of codegen units is that it prevents LLVM864 // from inlining across codegen units. Users in general don't have a lot865 // of control over how codegen units are split up so it's our job in the866 // compiler to ensure that undue performance isn't lost when using867 // codegen units (aka we can't require everyone to slap `#[inline]` on868 // everything).869 //870 // If we're compiling at `-O0` then the number doesn't really matter too871 // much because performance doesn't matter and inlining is ok to lose.872 // In debug mode we just want to try to guarantee that no cpu is stuck873 // doing work that could otherwise be farmed to others.874 //875 // In release mode, however (O1 and above) performance does indeed876 // matter! To recover the loss in performance due to inlining we'll be877 // enabling ThinLTO by default (the function for which is just below).878 // This will ensure that we recover any inlining wins we otherwise lost879 // through codegen unit partitioning.880 //881 // ---882 //883 // Ok that's a lot of words but the basic tl;dr; is that we want a high884 // number here -- but not too high. Additionally we're "safe" to have it885 // always at the same number at all optimization levels.886 //887 // As a result 16 was chosen here! Mostly because it was a power of 2888 // and most benchmarks agreed it was roughly a local optimum. Not very889 // scientific.890 CodegenUnits::Default(16)891 }892893 pub fn teach(&self, code: ErrCode) -> bool {894 self.opts.unstable_opts.teach && self.dcx().must_teach(code)895 }896897 pub fn edition(&self) -> Edition {898 self.opts.edition899 }900901 pub fn link_dead_code(&self) -> bool {902 self.opts.cg.link_dead_code.unwrap_or(false)903 }904905 /// Get the deployment target on Apple platforms based on the standard environment variables,906 /// or fall back to the minimum version supported by `rustc`.907 ///908 /// This should be guarded behind `if sess.target.is_like_darwin`.909 pub fn apple_deployment_target(&self) -> apple::OSVersion {910 let min = apple::OSVersion::minimum_deployment_target(&self.target);911 let env_var = apple::deployment_target_env_var(&self.target.os);912913 // FIXME(madsmtm): Track changes to this.914 if let Ok(deployment_target) = env::var(env_var) {915 match apple::OSVersion::from_str(&deployment_target) {916 Ok(version) => {917 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);918 // It is common that the deployment target is set a bit too low, for example on919 // macOS Aarch64 to also target older x86_64. So we only want to warn when variable920 // is lower than the minimum OS supported by rustc, not when the variable is lower921 // than the minimum for a specific target.922 if version < os_min {923 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {924 env_var,925 version: version.fmt_pretty().to_string(),926 os_min: os_min.fmt_pretty().to_string(),927 });928 }929930 // Raise the deployment target to the minimum supported.931 version.max(min)932 }933 Err(error) => {934 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });935 min936 }937 }938 } else {939 // If no deployment target variable is set, default to the minimum found above.940 min941 }942 }943944 pub fn sanitizers(&self) -> SanitizerSet {945 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;946 }947}948949// JUSTIFICATION: part of session construction950#[allow(rustc::bad_opt_access)]951fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {952 let macro_backtrace = sopts.unstable_opts.macro_backtrace;953 let track_diagnostics = sopts.unstable_opts.track_diagnostics;954 let terminal_url = match sopts.unstable_opts.terminal_urls {955 TerminalUrl::Auto => {956 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {957 (Ok("truecolor"), Ok("xterm-256color"))958 if sopts.unstable_features.is_nightly_build() =>959 {960 TerminalUrl::Yes961 }962 _ => TerminalUrl::No,963 }964 }965 t => t,966 };967968 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };969970 match sopts.error_format {971 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {972 HumanReadableErrorType { short, unicode } => {973 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))974 .sm(source_map)975 .short_message(short)976 .diagnostic_width(sopts.diagnostic_width)977 .macro_backtrace(macro_backtrace)978 .track_diagnostics(track_diagnostics)979 .terminal_url(terminal_url)980 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })981 .ignored_directories_in_source_blocks(982 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),983 );984 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))985 }986 },987 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(988 JsonEmitter::new(989 Box::new(io::BufWriter::new(io::stderr())),990 source_map,991 pretty,992 json_rendered,993 color_config,994 )995 .ui_testing(sopts.unstable_opts.ui_testing)996 .ignored_directories_in_source_blocks(997 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),998 )999 .diagnostic_width(sopts.diagnostic_width)1000 .macro_backtrace(macro_backtrace)1001 .track_diagnostics(track_diagnostics)1002 .terminal_url(terminal_url),1003 ),1004 }1005}10061007// JUSTIFICATION: literally session construction1008#[allow(rustc::bad_opt_access)]1009pub fn build_session(1010 sopts: config::Options,1011 io: CompilerIO,1012 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,1013 target: Target,1014 cfg_version: &'static str,1015 ice_file: Option<PathBuf>,1016 using_internal_features: &'static AtomicBool,1017) -> Session {1018 // FIXME: This is not general enough to make the warning lint completely override1019 // normal diagnostic warnings, since the warning lint can also be denied and changed1020 // later via the source code.1021 let warnings_allow = sopts1022 .lint_opts1023 .iter()1024 .rfind(|&(key, _)| *key == "warnings")1025 .is_some_and(|&(_, level)| level == lint::Allow);1026 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);1027 let can_emit_warnings = !(warnings_allow || cap_lints_allow);10281029 let source_map = rustc_span::source_map::get_source_map().unwrap();1030 let emitter = default_emitter(&sopts, Arc::clone(&source_map));10311032 let mut dcx =1033 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));1034 if let Some(ice_file) = ice_file {1035 dcx = dcx.with_ice_file(ice_file);1036 }10371038 let host_triple = TargetTuple::from_tuple(config::host_tuple());1039 let (host, target_warnings) =1040 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)1041 .unwrap_or_else(|e| {1042 dcx.handle().fatal(format!("Error loading host specification: {e}"))1043 });1044 for warning in target_warnings.warning_messages() {1045 dcx.handle().warn(warning)1046 }10471048 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile1049 {1050 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };10511052 let profiler = SelfProfiler::new(1053 directory,1054 sopts.crate_name.as_deref(),1055 sopts.unstable_opts.self_profile_events.as_deref(),1056 &sopts.unstable_opts.self_profile_counter,1057 );1058 match profiler {1059 Ok(profiler) => Some(Arc::new(profiler)),1060 Err(e) => {1061 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });1062 None1063 }1064 }1065 } else {1066 None1067 };10681069 let psess = ParseSess::with_dcx(dcx, source_map);10701071 let host_triple = config::host_tuple();1072 let target_triple = sopts.target_triple.tuple();1073 // FIXME use host sysroot?1074 let host_tlib_path =1075 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));1076 let target_tlib_path = if host_triple == target_triple {1077 // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary1078 // rescanning of the target lib path and an unnecessary allocation.1079 Arc::clone(&host_tlib_path)1080 } else {1081 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))1082 };10831084 let prof = SelfProfilerRef::new(1085 self_profiler,1086 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),1087 );10881089 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {1090 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,1091 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,1092 _ => CtfeBacktrace::Disabled,1093 });10941095 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };1096 let target_filesearch =1097 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);1098 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);10991100 let invocation_temp = sopts1101 .incremental1102 .as_ref()1103 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());11041105 let timings = TimingSectionHandler::new(sopts.json_timings);11061107 let sess = Session {1108 target,1109 host,1110 opts: sopts,1111 target_tlib_path,1112 psess,1113 unstable_features: UnstableFeatures::from_environment(None),1114 config: Cfg::default(),1115 check_config: CheckCfg::default(),1116 proc_macro_quoted_spans: Default::default(),1117 io,1118 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),1119 prof,1120 timings,1121 code_stats: Default::default(),1122 lint_store: None,1123 driver_lint_caps,1124 ctfe_backtrace,1125 miri_unleashed_features: Lock::new(Default::default()),1126 asm_arch,1127 target_features: Default::default(),1128 unstable_target_features: Default::default(),1129 cfg_version,1130 using_internal_features,1131 env_depinfo: Default::default(),1132 file_depinfo: Default::default(),1133 target_filesearch,1134 host_filesearch,1135 invocation_temp,1136 replaced_intrinsics: FxHashSet::default(), // filled by `run_compiler`1137 thin_lto_supported: true, // filled by `run_compiler`1138 mir_opt_bisect_eval_count: AtomicUsize::new(0),1139 used_features: Lock::default(),1140 };11411142 validate_commandline_args_with_session_available(&sess);11431144 sess1145}11461147/// Validate command line arguments with a `Session`.1148///1149/// If it is useful to have a Session available already for validating a commandline argument, you1150/// can do so here.1151// JUSTIFICATION: needs to access args to validate them1152#[allow(rustc::bad_opt_access)]1153fn validate_commandline_args_with_session_available(sess: &Session) {1154 // Since we don't know if code in an rlib will be linked to statically or1155 // dynamically downstream, rustc generates `__imp_` symbols that help linkers1156 // on Windows deal with this lack of knowledge (#27438). Unfortunately,1157 // these manually generated symbols confuse LLD when it tries to merge1158 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows1159 // when compiling for LLD ThinLTO. This way we can validly just not generate1160 // the `dllimport` attributes and `__imp_` symbols in that case.1161 if sess.opts.cg.linker_plugin_lto.enabled()1162 && sess.opts.cg.prefer_dynamic1163 && sess.target.is_like_windows1164 {1165 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);1166 }11671168 // Make sure that any given profiling data actually exists so LLVM can't1169 // decide to silently skip PGO.1170 if let Some(ref path) = sess.opts.cg.profile_use {1171 if !path.exists() {1172 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });1173 }1174 }11751176 // Do the same for sample profile data.1177 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {1178 if !path.exists() {1179 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });1180 }1181 }11821183 // Unwind tables cannot be disabled if the target requires them.1184 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {1185 if sess.target.requires_uwtable && !include_uwtables {1186 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);1187 }1188 }11891190 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.1191 let supported_sanitizers = sess.target.options.supported_sanitizers;1192 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;1193 // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled1194 // we should allow Shadow Call Stack sanitizer.1195 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {1196 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;1197 }1198 match unsupported_sanitizers.into_iter().count() {1199 0 => {}1200 1 => {1201 sess.dcx()1202 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });1203 }1204 _ => {1205 sess.dcx().emit_err(errors::SanitizersNotSupported {1206 us: unsupported_sanitizers.to_string(),1207 });1208 }1209 }12101211 // Cannot mix and match mutually-exclusive sanitizers.1212 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {1213 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {1214 first: first.to_string(),1215 second: second.to_string(),1216 });1217 }12181219 // Cannot enable crt-static with sanitizers on Linux1220 if sess.crt_static(None)1221 && !sess.opts.unstable_opts.sanitizer.is_empty()1222 && !sess.target.is_like_msvc1223 {1224 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);1225 }12261227 // LLVM CFI requires LTO.1228 if sess.is_sanitizer_cfi_enabled()1229 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())1230 {1231 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);1232 }12331234 // KCFI requires panic=abort1235 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {1236 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);1237 }12381239 // LLVM CFI using rustc LTO requires a single codegen unit.1240 if sess.is_sanitizer_cfi_enabled()1241 && sess.lto() == config::Lto::Fat1242 && (sess.codegen_units().as_usize() != 1)1243 {1244 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);1245 }12461247 // Canonical jump tables requires CFI.1248 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {1249 if !sess.is_sanitizer_cfi_enabled() {1250 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);1251 }1252 }12531254 // KCFI arity indicator requires KCFI.1255 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {1256 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);1257 }12581259 // LLVM CFI pointer generalization requires CFI or KCFI.1260 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {1261 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {1262 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);1263 }1264 }12651266 // LLVM CFI integer normalization requires CFI or KCFI.1267 if sess.is_sanitizer_cfi_normalize_integers_enabled() {1268 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {1269 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);1270 }1271 }12721273 // LTO unit splitting requires LTO.1274 if sess.is_split_lto_unit_enabled()1275 && !(sess.lto() == config::Lto::Fat1276 || sess.lto() == config::Lto::Thin1277 || sess.opts.cg.linker_plugin_lto.enabled())1278 {1279 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);1280 }12811282 // VFE requires LTO.1283 if sess.lto() != config::Lto::Fat {1284 if sess.opts.unstable_opts.virtual_function_elimination {1285 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);1286 }1287 }12881289 if sess.opts.unstable_opts.stack_protector != StackProtector::None {1290 if !sess.target.options.supports_stack_protector {1291 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {1292 stack_protector: sess.opts.unstable_opts.stack_protector,1293 target_triple: &sess.opts.target_triple,1294 });1295 }1296 }12971298 if sess.opts.unstable_opts.small_data_threshold.is_some() {1299 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {1300 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {1301 target_triple: &sess.opts.target_triple,1302 })1303 }1304 }13051306 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {1307 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);1308 }13091310 if let Some(dwarf_version) =1311 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)1312 {1313 // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.1314 if dwarf_version < 2 || dwarf_version > 5 {1315 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });1316 }1317 }13181319 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())1320 && !sess.opts.unstable_opts.unstable_options1321 {1322 sess.dcx()1323 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });1324 }13251326 if sess.opts.unstable_opts.embed_source {1327 let dwarf_version = sess.dwarf_version();13281329 if dwarf_version < 5 {1330 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });1331 }13321333 if sess.opts.debuginfo == DebugInfo::None {1334 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);1335 }1336 }13371338 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {1339 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });1340 }13411342 if let Some(flavor) = sess.opts.cg.linker_flavor1343 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)1344 {1345 let flavor = flavor.desc();1346 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });1347 }13481349 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {1350 if !matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {1351 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);1352 }1353 }13541355 if sess.opts.unstable_opts.indirect_branch_cs_prefix {1356 if !matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {1357 sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);1358 }1359 }13601361 if let Some(regparm) = sess.opts.unstable_opts.regparm {1362 if regparm > 3 {1363 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });1364 }1365 if sess.target.arch != Arch::X86 {1366 sess.dcx().emit_err(errors::UnsupportedRegparmArch);1367 }1368 }1369 if sess.opts.unstable_opts.reg_struct_return {1370 if sess.target.arch != Arch::X86 {1371 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);1372 }1373 }13741375 // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is1376 // kept as a `match` to force a change if new ones are added, even if we currently only support1377 // `thunk-extern` like Clang.1378 match sess.opts.unstable_opts.function_return {1379 FunctionReturn::Keep => (),1380 FunctionReturn::ThunkExtern => {1381 // FIXME: In principle, the inherited base LLVM target code model could be large,1382 // but this only checks whether we were passed one explicitly (like Clang does).1383 if let Some(code_model) = sess.code_model()1384 && code_model == CodeModel::Large1385 {1386 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);1387 }1388 }1389 }13901391 if sess.opts.unstable_opts.packed_stack {1392 if sess.target.arch != Arch::S390x {1393 sess.dcx().emit_err(errors::UnsupportedPackedStack);1394 }1395 }1396}13971398/// Holds data on the current incremental compilation session, if there is one.1399#[derive(Debug)]1400enum IncrCompSession {1401 /// This is the state the session will be in until the incr. comp. dir is1402 /// needed.1403 NotInitialized,1404 /// This is the state during which the session directory is private and can1405 /// be modified. `_lock_file` is never directly used, but its presence1406 /// alone has an effect, because the file will unlock when the session is1407 /// dropped.1408 Active { session_directory: PathBuf, _lock_file: flock::Lock },1409 /// This is the state after the session directory has been finalized. In this1410 /// state, the contents of the directory must not be modified any more.1411 Finalized { session_directory: PathBuf },1412 /// This is an error state that is reached when some compilation error has1413 /// occurred. It indicates that the contents of the session directory must1414 /// not be used, since they might be invalid.1415 InvalidBecauseOfErrors { session_directory: PathBuf },1416}14171418/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.1419pub struct EarlyDiagCtxt {1420 dcx: DiagCtxt,1421}14221423impl EarlyDiagCtxt {1424 pub fn new(output: ErrorOutputType) -> Self {1425 let emitter = mk_emitter(output);1426 Self { dcx: DiagCtxt::new(emitter) }1427 }14281429 /// Swap out the underlying dcx once we acquire the user's preference on error emission1430 /// format. If `early_err` was previously called this will panic.1431 pub fn set_error_format(&mut self, output: ErrorOutputType) {1432 assert!(self.dcx.handle().has_errors().is_none());14331434 let emitter = mk_emitter(output);1435 self.dcx = DiagCtxt::new(emitter);1436 }14371438 pub fn early_note(&self, msg: impl Into<DiagMessage>) {1439 self.dcx.handle().note(msg)1440 }14411442 pub fn early_help(&self, msg: impl Into<DiagMessage>) {1443 self.dcx.handle().struct_help(msg).emit()1444 }14451446 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]1447 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {1448 self.dcx.handle().err(msg)1449 }14501451 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {1452 self.dcx.handle().fatal(msg)1453 }14541455 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {1456 self.dcx.handle().struct_fatal(msg)1457 }14581459 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {1460 self.dcx.handle().warn(msg)1461 }14621463 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {1464 self.dcx.handle().struct_warn(msg)1465 }1466}14671468fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {1469 let emitter: Box<DynEmitter> = match output {1470 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {1471 HumanReadableErrorType { short, unicode } => Box::new(1472 AnnotateSnippetEmitter::new(stderr_destination(color_config))1473 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })1474 .short_message(short),1475 ),1476 },1477 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {1478 Box::new(JsonEmitter::new(1479 Box::new(io::BufWriter::new(io::stderr())),1480 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),1481 pretty,1482 json_rendered,1483 color_config,1484 ))1485 }1486 };1487 emitter1488}