1 use crate::cgu_reuse_tracker::CguReuseTracker;
2 use crate::code_stats::CodeStats;
3 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::config::{self, CrateType, InstrumentCoverage, OptLevel, OutputType, SwitchWithOptPath};
5 use crate::parse::{add_feature_diagnostics, ParseSess};
6 use crate::search_paths::{PathKind, SearchPath};
7 use crate::{filesearch, lint};
9 pub use rustc_ast::attr::MarkedAttrs;
10 pub use rustc_ast::Attribute;
11 use rustc_data_structures::flock;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::jobserver::{self, Client};
14 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
15 use rustc_data_structures::sync::{
16 self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
18 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
19 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
20 use rustc_errors::json::JsonEmitter;
21 use rustc_errors::registry::Registry;
23 fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, EmissionGuarantee,
24 ErrorGuaranteed, FluentBundle, LazyFallbackBundle, MultiSpan,
26 use rustc_macros::HashStable_Generic;
27 pub use rustc_span::def_id::StableCrateId;
28 use rustc_span::edition::Edition;
29 use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMap, Span};
30 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
31 use rustc_target::asm::InlineAsmArch;
32 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
33 use rustc_target::spec::{
34 SanitizerSet, SplitDebuginfo, StackProtector, Target, TargetTriple, TlsModel,
37 use std::cell::{self, RefCell};
41 use std::ops::{Div, Mul};
42 use std::path::{Path, PathBuf};
43 use std::str::FromStr;
45 use std::time::Duration;
47 pub struct OptimizationFuel {
48 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
50 /// We're rejecting all further optimizations.
54 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
55 #[derive(Clone, Copy)]
56 pub enum CtfeBacktrace {
57 /// Do nothing special, return the error as usual without a backtrace.
59 /// Capture a backtrace at the point the error is created and return it in the error
60 /// (to be printed later if/when the error ever actually gets shown to the user).
62 /// Capture a backtrace at the point the error is created and immediately print it out.
66 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
67 /// limits are consistent throughout the compiler.
68 #[derive(Clone, Copy, Debug, HashStable_Generic)]
69 pub struct Limit(pub usize);
72 /// Create a new limit from a `usize`.
73 pub fn new(value: usize) -> Self {
77 /// Check that `value` is within the limit. Ensures that the same comparisons are used
78 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
80 pub fn value_within_limit(&self, value: usize) -> bool {
85 impl From<usize> for Limit {
86 fn from(value: usize) -> Self {
91 impl fmt::Display for Limit {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 impl Div<usize> for Limit {
100 fn div(self, rhs: usize) -> Self::Output {
101 Limit::new(self.0 / rhs)
105 impl Mul<usize> for Limit {
108 fn mul(self, rhs: usize) -> Self::Output {
109 Limit::new(self.0 * rhs)
113 #[derive(Clone, Copy, Debug, HashStable_Generic)]
115 /// The maximum recursion limit for potentially infinitely recursive
116 /// operations such as auto-dereference and monomorphization.
117 pub recursion_limit: Limit,
118 /// The size at which the `large_assignments` lint starts
120 pub move_size_limit: Limit,
121 /// The maximum length of types during monomorphization.
122 pub type_length_limit: Limit,
123 /// The maximum blocks a const expression can evaluate.
124 pub const_eval_limit: Limit,
127 /// Represents the data associated with a compilation
128 /// session for a single crate.
132 pub opts: config::Options,
133 pub host_tlib_path: Lrc<SearchPath>,
134 pub target_tlib_path: Lrc<SearchPath>,
135 pub parse_sess: ParseSess,
136 pub sysroot: PathBuf,
137 /// The name of the root source file of the crate, in the local file system.
138 /// `None` means that there is no source file.
139 pub local_crate_source_file: Option<PathBuf>,
141 crate_types: OnceCell<Vec<CrateType>>,
142 /// The `stable_crate_id` is constructed out of the crate name and all the
143 /// `-C metadata` arguments passed to the compiler. Its value forms a unique
144 /// global identifier for the crate. It is used to allow multiple crates
145 /// with the same name to coexist. See the
146 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
147 pub stable_crate_id: OnceCell<StableCrateId>,
149 features: OnceCell<rustc_feature::Features>,
151 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
152 /// Used for incremental compilation tests. Will only be populated if
153 /// `-Zquery-dep-graph` is specified.
154 pub cgu_reuse_tracker: CguReuseTracker,
156 /// Used by `-Z self-profile`.
157 pub prof: SelfProfilerRef,
159 /// Some measurements that are being gathered during compilation.
160 pub perf_stats: PerfStats,
162 /// Data about code being compiled, gathered during compilation.
163 pub code_stats: CodeStats,
165 /// Tracks fuel info if `-zfuel=crate=n` is specified.
166 optimization_fuel: Lock<OptimizationFuel>,
168 /// Always set to zero and incremented so that we can print fuel expended by a crate.
169 pub print_fuel: AtomicU64,
171 /// Loaded up early on in the initialization of this `Session` to avoid
172 /// false positives about a job server in our environment.
173 pub jobserver: Client,
175 /// Cap lint level specified by a driver specifically.
176 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
178 /// Tracks the current behavior of the CTFE engine when an error occurs.
179 /// Options range from returning the error without a backtrace to returning an error
180 /// and immediately printing the backtrace to stderr.
181 /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
182 /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
184 pub ctfe_backtrace: Lock<CtfeBacktrace>,
186 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
187 /// const check, optionally with the relevant feature gate. We use this to
188 /// warn about unleashing, but with a single diagnostic instead of dozens that
189 /// drown everything else in noise.
190 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
192 /// Architecture to use for interpreting asm!.
193 pub asm_arch: Option<InlineAsmArch>,
195 /// Set of enabled features for the current target.
196 pub target_features: FxHashSet<Symbol>,
198 /// Set of enabled features for the current target, including unstable ones.
199 pub unstable_target_features: FxHashSet<Symbol>,
202 pub struct PerfStats {
203 /// The accumulated time spent on computing symbol hashes.
204 pub symbol_hash_time: Lock<Duration>,
205 /// Total number of values canonicalized queries constructed.
206 pub queries_canonicalized: AtomicUsize,
207 /// Number of times this query is invoked.
208 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
209 /// Number of times this query is invoked.
210 pub normalize_projection_ty: AtomicUsize,
213 /// Trait implemented by error types. This should not be implemented manually. Instead, use
214 /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic].
215 #[rustc_diagnostic_item = "SessionDiagnostic"]
216 pub trait SessionDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> {
217 /// Write out as a diagnostic out of `sess`.
219 fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, T>;
223 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
224 self.miri_unleashed_features.lock().push((span, feature_gate));
227 fn check_miri_unleashed_features(&self) {
228 let unleashed_features = self.miri_unleashed_features.lock();
229 if !unleashed_features.is_empty() {
230 let mut must_err = false;
231 // Create a diagnostic pointing at where things got unleashed.
232 let mut diag = self.struct_warn("skipping const checks");
233 for &(span, feature_gate) in unleashed_features.iter() {
234 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
235 if let Some(gate) = feature_gate {
236 diag.span_help(span, &format!("skipping check for `{gate}` feature"));
237 // The unleash flag must *not* be used to just "hack around" feature gates.
240 diag.span_help(span, "skipping check that does not even have a feature gate");
244 // If we should err, make sure we did.
245 if must_err && self.has_errors().is_none() {
246 // We have skipped a feature gate, and not run into other errors... reject.
248 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
249 gates, except when testing error paths in the CTFE engine",
255 /// Invoked all the way at the end to finish off diagnostics printing.
256 pub fn finish_diagnostics(&self, registry: &Registry) {
257 self.check_miri_unleashed_features();
258 self.diagnostic().print_error_count(registry);
259 self.emit_future_breakage();
262 fn emit_future_breakage(&self) {
263 if !self.opts.json_future_incompat {
267 let diags = self.diagnostic().take_future_breakage_diagnostics();
268 if diags.is_empty() {
271 self.parse_sess.span_diagnostic.emit_future_breakage_report(diags);
274 pub fn local_stable_crate_id(&self) -> StableCrateId {
275 self.stable_crate_id.get().copied().unwrap()
278 pub fn crate_types(&self) -> &[CrateType] {
279 self.crate_types.get().unwrap().as_slice()
282 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
283 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
286 #[rustc_lint_diagnostics]
287 pub fn struct_span_warn<S: Into<MultiSpan>>(
290 msg: impl Into<DiagnosticMessage>,
291 ) -> DiagnosticBuilder<'_, ()> {
292 self.diagnostic().struct_span_warn(sp, msg)
294 #[rustc_lint_diagnostics]
295 pub fn struct_span_warn_with_expectation<S: Into<MultiSpan>>(
298 msg: impl Into<DiagnosticMessage>,
299 id: lint::LintExpectationId,
300 ) -> DiagnosticBuilder<'_, ()> {
301 self.diagnostic().struct_span_warn_with_expectation(sp, msg, id)
303 #[rustc_lint_diagnostics]
304 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
307 msg: impl Into<DiagnosticMessage>,
309 ) -> DiagnosticBuilder<'_, ()> {
310 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
312 #[rustc_lint_diagnostics]
313 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
314 self.diagnostic().struct_warn(msg)
316 #[rustc_lint_diagnostics]
317 pub fn struct_warn_with_expectation(
319 msg: impl Into<DiagnosticMessage>,
320 id: lint::LintExpectationId,
321 ) -> DiagnosticBuilder<'_, ()> {
322 self.diagnostic().struct_warn_with_expectation(msg, id)
324 #[rustc_lint_diagnostics]
325 pub fn struct_span_allow<S: Into<MultiSpan>>(
328 msg: impl Into<DiagnosticMessage>,
329 ) -> DiagnosticBuilder<'_, ()> {
330 self.diagnostic().struct_span_allow(sp, msg)
332 #[rustc_lint_diagnostics]
333 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
334 self.diagnostic().struct_allow(msg)
336 #[rustc_lint_diagnostics]
337 pub fn struct_expect(
339 msg: impl Into<DiagnosticMessage>,
340 id: lint::LintExpectationId,
341 ) -> DiagnosticBuilder<'_, ()> {
342 self.diagnostic().struct_expect(msg, id)
344 #[rustc_lint_diagnostics]
345 pub fn struct_span_err<S: Into<MultiSpan>>(
348 msg: impl Into<DiagnosticMessage>,
349 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
350 self.diagnostic().struct_span_err(sp, msg)
352 #[rustc_lint_diagnostics]
353 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
356 msg: impl Into<DiagnosticMessage>,
358 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
359 self.diagnostic().struct_span_err_with_code(sp, msg, code)
361 // FIXME: This method should be removed (every error should have an associated error code).
362 #[rustc_lint_diagnostics]
365 msg: impl Into<DiagnosticMessage>,
366 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
367 self.parse_sess.struct_err(msg)
369 #[rustc_lint_diagnostics]
370 pub fn struct_err_with_code(
372 msg: impl Into<DiagnosticMessage>,
374 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
375 self.diagnostic().struct_err_with_code(msg, code)
377 #[rustc_lint_diagnostics]
378 pub fn struct_warn_with_code(
380 msg: impl Into<DiagnosticMessage>,
382 ) -> DiagnosticBuilder<'_, ()> {
383 self.diagnostic().struct_warn_with_code(msg, code)
385 #[rustc_lint_diagnostics]
386 pub fn struct_span_fatal<S: Into<MultiSpan>>(
389 msg: impl Into<DiagnosticMessage>,
390 ) -> DiagnosticBuilder<'_, !> {
391 self.diagnostic().struct_span_fatal(sp, msg)
393 #[rustc_lint_diagnostics]
394 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
397 msg: impl Into<DiagnosticMessage>,
399 ) -> DiagnosticBuilder<'_, !> {
400 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
402 #[rustc_lint_diagnostics]
403 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
404 self.diagnostic().struct_fatal(msg)
407 #[rustc_lint_diagnostics]
408 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
409 self.diagnostic().span_fatal(sp, msg)
411 #[rustc_lint_diagnostics]
412 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
415 msg: impl Into<DiagnosticMessage>,
418 self.diagnostic().span_fatal_with_code(sp, msg, code)
420 #[rustc_lint_diagnostics]
421 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! {
422 self.diagnostic().fatal(msg).raise()
424 #[rustc_lint_diagnostics]
425 pub fn span_err_or_warn<S: Into<MultiSpan>>(
429 msg: impl Into<DiagnosticMessage>,
432 self.span_warn(sp, msg);
434 self.span_err(sp, msg);
437 #[rustc_lint_diagnostics]
438 pub fn span_err<S: Into<MultiSpan>>(
441 msg: impl Into<DiagnosticMessage>,
442 ) -> ErrorGuaranteed {
443 self.diagnostic().span_err(sp, msg)
445 #[rustc_lint_diagnostics]
446 pub fn span_err_with_code<S: Into<MultiSpan>>(
449 msg: impl Into<DiagnosticMessage>,
452 self.diagnostic().span_err_with_code(sp, msg, code)
454 #[rustc_lint_diagnostics]
455 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
456 self.diagnostic().err(msg)
458 pub fn create_err<'a>(
460 err: impl SessionDiagnostic<'a>,
461 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
462 self.parse_sess.create_err(err)
464 pub fn create_feature_err<'a>(
466 err: impl SessionDiagnostic<'a>,
468 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
469 let mut err = self.parse_sess.create_err(err);
470 add_feature_diagnostics(&mut err, &self.parse_sess, feature);
473 pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed {
474 self.parse_sess.emit_err(err)
476 pub fn create_warning<'a>(
478 err: impl SessionDiagnostic<'a, ()>,
479 ) -> DiagnosticBuilder<'a, ()> {
480 self.parse_sess.create_warning(err)
482 pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) {
483 self.parse_sess.emit_warning(warning)
486 pub fn err_count(&self) -> usize {
487 self.diagnostic().err_count()
489 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
490 self.diagnostic().has_errors()
492 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
493 self.diagnostic().has_errors_or_delayed_span_bugs()
495 pub fn abort_if_errors(&self) {
496 self.diagnostic().abort_if_errors();
498 pub fn compile_status(&self) -> Result<(), ErrorGuaranteed> {
499 if let Some(reported) = self.diagnostic().has_errors_or_lint_errors() {
500 let _ = self.diagnostic().emit_stashed_diagnostics();
506 // FIXME(matthewjasper) Remove this method, it should never be needed.
507 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorGuaranteed>
511 let old_count = self.err_count();
513 if self.err_count() == old_count {
516 Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
519 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
520 self.diagnostic().span_warn(sp, msg)
522 pub fn span_warn_with_code<S: Into<MultiSpan>>(
525 msg: impl Into<DiagnosticMessage>,
528 self.diagnostic().span_warn_with_code(sp, msg, code)
530 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
531 self.diagnostic().warn(msg)
533 /// Delay a span_bug() call until abort_if_errors()
535 pub fn delay_span_bug<S: Into<MultiSpan>>(
538 msg: impl Into<DiagnosticMessage>,
539 ) -> ErrorGuaranteed {
540 self.diagnostic().delay_span_bug(sp, msg)
543 /// Used for code paths of expensive computations that should only take place when
544 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
545 /// it's likely a bug.
546 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
547 if self.opts.unstable_opts.print_type_sizes
548 || self.opts.unstable_opts.query_dep_graph
549 || self.opts.unstable_opts.dump_mir.is_some()
550 || self.opts.unstable_opts.unpretty.is_some()
551 || self.opts.output_types.contains_key(&OutputType::Mir)
552 || std::env::var_os("RUSTC_LOG").is_some()
557 self.diagnostic().delay_good_path_bug(msg)
560 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
561 self.diagnostic().note_without_error(msg)
563 pub fn span_note_without_error<S: Into<MultiSpan>>(
566 msg: impl Into<DiagnosticMessage>,
568 self.diagnostic().span_note_without_error(sp, msg)
570 pub fn struct_note_without_error(
572 msg: impl Into<DiagnosticMessage>,
573 ) -> DiagnosticBuilder<'_, ()> {
574 self.diagnostic().struct_note_without_error(msg)
578 pub fn diagnostic(&self) -> &rustc_errors::Handler {
579 &self.parse_sess.span_diagnostic
583 pub fn source_map(&self) -> &SourceMap {
584 self.parse_sess.source_map()
587 pub fn time_passes(&self) -> bool {
588 self.opts.time_passes()
591 /// Returns `true` if internal lints should be added to the lint store - i.e. if
592 /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
593 /// to be emitted under rustdoc).
594 pub fn enable_internal_lints(&self) -> bool {
595 self.unstable_options() && !self.opts.actually_rustdoc
598 pub fn instrument_coverage(&self) -> bool {
599 self.opts.cg.instrument_coverage() != InstrumentCoverage::Off
602 pub fn instrument_coverage_except_unused_generics(&self) -> bool {
603 self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedGenerics
606 pub fn instrument_coverage_except_unused_functions(&self) -> bool {
607 self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedFunctions
610 /// Gets the features enabled for the current compilation session.
611 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
612 /// dependency tracking. Use tcx.features() instead.
614 pub fn features_untracked(&self) -> &rustc_feature::Features {
615 self.features.get().unwrap()
618 pub fn init_features(&self, features: rustc_feature::Features) {
619 match self.features.set(features) {
621 Err(_) => panic!("`features` was initialized twice"),
625 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
626 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
629 /// Check whether this compile session and crate type use static crt.
630 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
631 if !self.target.crt_static_respected {
632 // If the target does not opt in to crt-static support, use its default.
633 return self.target.crt_static_default;
636 let requested_features = self.opts.cg.target_feature.split(',');
637 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
638 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
640 // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
641 #[allow(rustc::bad_opt_access)]
642 if found_positive || found_negative {
644 } else if crate_type == Some(CrateType::ProcMacro)
645 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
647 // FIXME: When crate_type is not available,
648 // we use compiler options to determine the crate_type.
649 // We can't check `#![crate_type = "proc-macro"]` here.
652 self.target.crt_static_default
656 pub fn is_wasi_reactor(&self) -> bool {
657 self.target.options.os == "wasi"
659 self.opts.unstable_opts.wasi_exec_model,
660 Some(config::WasiExecModel::Reactor)
664 pub fn target_can_use_split_dwarf(&self) -> bool {
665 !self.target.is_like_windows && !self.target.is_like_osx
668 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
669 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.to_u64())
672 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
673 filesearch::FileSearch::new(
675 self.opts.target_triple.triple(),
676 &self.opts.search_paths,
677 &self.target_tlib_path,
681 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
682 filesearch::FileSearch::new(
684 config::host_triple(),
685 &self.opts.search_paths,
686 &self.host_tlib_path,
691 /// Returns a list of directories where target-specific tool binaries are located.
692 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
693 let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple());
694 let p = PathBuf::from_iter([
695 Path::new(&self.sysroot),
696 Path::new(&rustlib_path),
699 if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
702 pub fn init_incr_comp_session(
704 session_dir: PathBuf,
705 lock_file: flock::Lock,
706 load_dep_graph: bool,
708 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
710 if let IncrCompSession::NotInitialized = *incr_comp_session {
712 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
716 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
719 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
720 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
722 if let IncrCompSession::Active { .. } = *incr_comp_session {
724 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
727 // Note: this will also drop the lock file, thus unlocking the directory.
728 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
731 pub fn mark_incr_comp_session_as_invalid(&self) {
732 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
734 let session_directory = match *incr_comp_session {
735 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
736 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
737 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
740 // Note: this will also drop the lock file, thus unlocking the directory.
741 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
744 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
745 let incr_comp_session = self.incr_comp_session.borrow();
746 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
747 IncrCompSession::NotInitialized => panic!(
748 "trying to get session directory from `IncrCompSession`: {:?}",
751 IncrCompSession::Active { ref session_directory, .. }
752 | IncrCompSession::Finalized { ref session_directory }
753 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
759 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
760 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
763 pub fn print_perf_stats(&self) {
765 "Total time spent computing symbol hashes: {}",
766 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
769 "Total queries canonicalized: {}",
770 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
773 "normalize_generic_arg_after_erasing_regions: {}",
774 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
777 "normalize_projection_ty: {}",
778 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
782 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
783 /// This expends fuel if applicable, and records fuel if applicable.
784 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
786 if let Some((ref c, _)) = self.opts.unstable_opts.fuel {
788 assert_eq!(self.threads(), 1);
789 let mut fuel = self.optimization_fuel.lock();
790 ret = fuel.remaining != 0;
791 if fuel.remaining == 0 && !fuel.out_of_fuel {
792 if self.diagnostic().can_emit_warnings() {
793 // We only call `msg` in case we can actually emit warnings.
794 // Otherwise, this could cause a `delay_good_path_bug` to
795 // trigger (issue #79546).
796 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
798 fuel.out_of_fuel = true;
799 } else if fuel.remaining > 0 {
804 if let Some(ref c) = self.opts.unstable_opts.print_fuel {
806 assert_eq!(self.threads(), 1);
807 self.print_fuel.fetch_add(1, SeqCst);
813 pub fn rust_2015(&self) -> bool {
814 self.edition() == Edition::Edition2015
817 /// Are we allowed to use features from the Rust 2018 edition?
818 pub fn rust_2018(&self) -> bool {
819 self.edition() >= Edition::Edition2018
822 /// Are we allowed to use features from the Rust 2021 edition?
823 pub fn rust_2021(&self) -> bool {
824 self.edition() >= Edition::Edition2021
827 /// Are we allowed to use features from the Rust 2024 edition?
828 pub fn rust_2024(&self) -> bool {
829 self.edition() >= Edition::Edition2024
832 /// Returns `true` if we cannot skip the PLT for shared library calls.
833 pub fn needs_plt(&self) -> bool {
834 // Check if the current target usually needs PLT to be enabled.
835 // The user can use the command line flag to override it.
836 let needs_plt = self.target.needs_plt;
838 let dbg_opts = &self.opts.unstable_opts;
840 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
842 // Only enable this optimization by default if full relro is also enabled.
843 // In this case, lazy binding was already unavailable, so nothing is lost.
844 // This also ensures `-Wl,-z,now` is supported by the linker.
845 let full_relro = RelroLevel::Full == relro_level;
847 // If user didn't explicitly forced us to use / skip the PLT,
848 // then try to skip it where possible.
849 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
852 /// Checks if LLVM lifetime markers should be emitted.
853 pub fn emit_lifetime_markers(&self) -> bool {
854 self.opts.optimize != config::OptLevel::No
855 // AddressSanitizer uses lifetimes to detect use after scope bugs.
856 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
857 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
858 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
861 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
862 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
864 .any(|kind| attr.has_name(*kind))
867 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
868 attrs.iter().any(|item| item.has_name(name))
871 pub fn find_by_name<'a>(
873 attrs: &'a [Attribute],
875 ) -> Option<&'a Attribute> {
876 attrs.iter().find(|attr| attr.has_name(name))
879 pub fn filter_by_name<'a>(
881 attrs: &'a [Attribute],
883 ) -> impl Iterator<Item = &'a Attribute> {
884 attrs.iter().filter(move |attr| attr.has_name(name))
887 pub fn first_attr_value_str_by_name(
891 ) -> Option<Symbol> {
892 attrs.iter().find(|at| at.has_name(name)).and_then(|at| at.value_str())
896 // JUSTIFICATION: defn of the suggested wrapper fns
897 #[allow(rustc::bad_opt_access)]
899 pub fn verbose(&self) -> bool {
900 self.opts.unstable_opts.verbose
903 pub fn instrument_mcount(&self) -> bool {
904 self.opts.unstable_opts.instrument_mcount
907 pub fn time_llvm_passes(&self) -> bool {
908 self.opts.unstable_opts.time_llvm_passes
911 pub fn meta_stats(&self) -> bool {
912 self.opts.unstable_opts.meta_stats
915 pub fn asm_comments(&self) -> bool {
916 self.opts.unstable_opts.asm_comments
919 pub fn verify_llvm_ir(&self) -> bool {
920 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
923 pub fn print_llvm_passes(&self) -> bool {
924 self.opts.unstable_opts.print_llvm_passes
927 pub fn binary_dep_depinfo(&self) -> bool {
928 self.opts.unstable_opts.binary_dep_depinfo
931 pub fn mir_opt_level(&self) -> usize {
935 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
938 /// Calculates the flavor of LTO to use for this compilation.
939 pub fn lto(&self) -> config::Lto {
940 // If our target has codegen requirements ignore the command line
941 if self.target.requires_lto {
942 return config::Lto::Fat;
945 // If the user specified something, return that. If they only said `-C
946 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
947 // then ensure we can't use a ThinLTO.
948 match self.opts.cg.lto {
949 config::LtoCli::Unspecified => {
950 // The compiler was invoked without the `-Clto` flag. Fall
951 // through to the default handling
953 config::LtoCli::No => {
954 // The user explicitly opted out of any kind of LTO
955 return config::Lto::No;
957 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
958 // All of these mean fat LTO
959 return config::Lto::Fat;
961 config::LtoCli::Thin => {
962 return if self.opts.cli_forced_thinlto_off {
970 // Ok at this point the target doesn't require anything and the user
971 // hasn't asked for anything. Our next decision is whether or not
972 // we enable "auto" ThinLTO where we use multiple codegen units and
973 // then do ThinLTO over those codegen units. The logic below will
974 // either return `No` or `ThinLocal`.
976 // If processing command line options determined that we're incompatible
977 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
978 if self.opts.cli_forced_thinlto_off {
979 return config::Lto::No;
982 // If `-Z thinlto` specified process that, but note that this is mostly
983 // a deprecated option now that `-C lto=thin` exists.
984 if let Some(enabled) = self.opts.unstable_opts.thinlto {
986 return config::Lto::ThinLocal;
988 return config::Lto::No;
992 // If there's only one codegen unit and LTO isn't enabled then there's
993 // no need for ThinLTO so just return false.
994 if self.codegen_units() == 1 {
995 return config::Lto::No;
998 // Now we're in "defaults" territory. By default we enable ThinLTO for
999 // optimized compiles (anything greater than O0).
1000 match self.opts.optimize {
1001 config::OptLevel::No => config::Lto::No,
1002 _ => config::Lto::ThinLocal,
1006 /// Returns the panic strategy for this compile session. If the user explicitly selected one
1007 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
1008 pub fn panic_strategy(&self) -> PanicStrategy {
1009 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
1012 pub fn fewer_names(&self) -> bool {
1013 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1016 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1017 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1018 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1019 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1024 pub fn unstable_options(&self) -> bool {
1025 self.opts.unstable_opts.unstable_options
1028 pub fn is_nightly_build(&self) -> bool {
1029 self.opts.unstable_features.is_nightly_build()
1032 pub fn overflow_checks(&self) -> bool {
1033 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1036 pub fn relocation_model(&self) -> RelocModel {
1037 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
1040 pub fn code_model(&self) -> Option<CodeModel> {
1041 self.opts.cg.code_model.or(self.target.code_model)
1044 pub fn tls_model(&self) -> TlsModel {
1045 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
1048 pub fn split_debuginfo(&self) -> SplitDebuginfo {
1049 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1052 pub fn stack_protector(&self) -> StackProtector {
1053 if self.target.options.supports_stack_protector {
1054 self.opts.unstable_opts.stack_protector
1056 StackProtector::None
1060 pub fn must_emit_unwind_tables(&self) -> bool {
1061 // This is used to control the emission of the `uwtable` attribute on
1064 // Unwind tables are needed when compiling with `-C panic=unwind`, but
1065 // LLVM won't omit unwind tables unless the function is also marked as
1066 // `nounwind`, so users are allowed to disable `uwtable` emission.
1067 // Historically rustc always emits `uwtable` attributes by default, so
1068 // even they can be disabled, they're still emitted by default.
1070 // On some targets (including windows), however, exceptions include
1071 // other events such as illegal instructions, segfaults, etc. This means
1072 // that on Windows we end up still needing unwind tables even if the `-C
1073 // panic=abort` flag is passed.
1075 // You can also find more info on why Windows needs unwind tables in:
1076 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1078 // If a target requires unwind tables, then they must be emitted.
1079 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1080 // value, if it is provided, or disable them, if not.
1081 self.target.requires_uwtable
1082 || self.opts.cg.force_unwind_tables.unwrap_or(
1083 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
1087 /// Returns the number of query threads that should be used for this
1089 pub fn threads(&self) -> usize {
1090 self.opts.unstable_opts.threads
1093 /// Returns the number of codegen units that should be used for this
1095 pub fn codegen_units(&self) -> usize {
1096 if let Some(n) = self.opts.cli_forced_codegen_units {
1099 if let Some(n) = self.target.default_codegen_units {
1103 // If incremental compilation is turned on, we default to a high number
1104 // codegen units in order to reduce the "collateral damage" small
1106 if self.opts.incremental.is_some() {
1110 // Why is 16 codegen units the default all the time?
1112 // The main reason for enabling multiple codegen units by default is to
1113 // leverage the ability for the codegen backend to do codegen and
1114 // optimization in parallel. This allows us, especially for large crates, to
1115 // make good use of all available resources on the machine once we've
1116 // hit that stage of compilation. Large crates especially then often
1117 // take a long time in codegen/optimization and this helps us amortize that
1120 // Note that a high number here doesn't mean that we'll be spawning a
1121 // large number of threads in parallel. The backend of rustc contains
1122 // global rate limiting through the `jobserver` crate so we'll never
1123 // overload the system with too much work, but rather we'll only be
1124 // optimizing when we're otherwise cooperating with other instances of
1127 // Rather a high number here means that we should be able to keep a lot
1128 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1129 // to build we'll be guaranteed that all cpus will finish pretty closely
1130 // to one another and we should make relatively optimal use of system
1133 // Note that the main cost of codegen units is that it prevents LLVM
1134 // from inlining across codegen units. Users in general don't have a lot
1135 // of control over how codegen units are split up so it's our job in the
1136 // compiler to ensure that undue performance isn't lost when using
1137 // codegen units (aka we can't require everyone to slap `#[inline]` on
1140 // If we're compiling at `-O0` then the number doesn't really matter too
1141 // much because performance doesn't matter and inlining is ok to lose.
1142 // In debug mode we just want to try to guarantee that no cpu is stuck
1143 // doing work that could otherwise be farmed to others.
1145 // In release mode, however (O1 and above) performance does indeed
1146 // matter! To recover the loss in performance due to inlining we'll be
1147 // enabling ThinLTO by default (the function for which is just below).
1148 // This will ensure that we recover any inlining wins we otherwise lost
1149 // through codegen unit partitioning.
1153 // Ok that's a lot of words but the basic tl;dr; is that we want a high
1154 // number here -- but not too high. Additionally we're "safe" to have it
1155 // always at the same number at all optimization levels.
1157 // As a result 16 was chosen here! Mostly because it was a power of 2
1158 // and most benchmarks agreed it was roughly a local optimum. Not very
1163 pub fn teach(&self, code: &DiagnosticId) -> bool {
1164 self.opts.unstable_opts.teach && self.diagnostic().must_teach(code)
1167 pub fn edition(&self) -> Edition {
1171 pub fn link_dead_code(&self) -> bool {
1172 self.opts.cg.link_dead_code.unwrap_or(false)
1176 // JUSTIFICATION: part of session construction
1177 #[allow(rustc::bad_opt_access)]
1179 sopts: &config::Options,
1180 registry: rustc_errors::registry::Registry,
1181 source_map: Lrc<SourceMap>,
1182 bundle: Option<Lrc<FluentBundle>>,
1183 fallback_bundle: LazyFallbackBundle,
1184 emitter_dest: Option<Box<dyn Write + Send>>,
1185 ) -> Box<dyn Emitter + sync::Send> {
1186 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1187 match (sopts.error_format, emitter_dest) {
1188 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1189 let (short, color_config) = kind.unzip();
1191 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1192 let emitter = AnnotateSnippetEmitterWriter::new(
1199 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1201 let emitter = match dst {
1202 None => EmitterWriter::stderr(
1208 sopts.unstable_opts.teach,
1209 sopts.diagnostic_width,
1212 Some(dst) => EmitterWriter::new(
1218 false, // no teach messages when writing to a buffer
1219 false, // no colors when writing to a buffer
1220 None, // no diagnostic width
1224 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1227 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1228 JsonEmitter::stderr(
1235 sopts.diagnostic_width,
1238 .ui_testing(sopts.unstable_opts.ui_testing),
1240 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1249 sopts.diagnostic_width,
1252 .ui_testing(sopts.unstable_opts.ui_testing),
1257 pub enum DiagnosticOutput {
1259 Raw(Box<dyn Write + Send>),
1262 // JUSTIFICATION: literally session construction
1263 #[allow(rustc::bad_opt_access)]
1264 pub fn build_session(
1265 sopts: config::Options,
1266 local_crate_source_file: Option<PathBuf>,
1267 bundle: Option<Lrc<rustc_errors::FluentBundle>>,
1268 registry: rustc_errors::registry::Registry,
1269 diagnostics_output: DiagnosticOutput,
1270 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1271 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1272 target_override: Option<Target>,
1274 // FIXME: This is not general enough to make the warning lint completely override
1275 // normal diagnostic warnings, since the warning lint can also be denied and changed
1276 // later via the source code.
1277 let warnings_allow = sopts
1280 .filter(|&&(ref key, _)| *key == "warnings")
1281 .map(|&(_, ref level)| *level == lint::Allow)
1284 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1285 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1287 let write_dest = match diagnostics_output {
1288 DiagnosticOutput::Default => None,
1289 DiagnosticOutput::Raw(write) => Some(write),
1292 let sysroot = match &sopts.maybe_sysroot {
1293 Some(sysroot) => sysroot.clone(),
1294 None => filesearch::get_or_default_sysroot(),
1297 let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
1298 let host_triple = TargetTriple::from_triple(config::host_triple());
1299 let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1300 early_error(sopts.error_format, &format!("Error loading host specification: {e}"))
1302 for warning in target_warnings.warning_messages() {
1303 early_warn(sopts.error_format, &warning)
1306 let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1307 let hash_kind = sopts.unstable_opts.src_hash_algorithm.unwrap_or_else(|| {
1308 if target_cfg.is_like_msvc {
1309 SourceFileHashAlgorithm::Sha1
1311 SourceFileHashAlgorithm::Md5
1314 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1316 sopts.file_path_mapping(),
1320 let fallback_bundle = fallback_fluent_bundle(
1321 rustc_errors::DEFAULT_LOCALE_RESOURCES,
1322 sopts.unstable_opts.translate_directionality_markers,
1325 default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle, write_dest);
1327 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1329 sopts.unstable_opts.diagnostic_handler_flags(can_emit_warnings),
1332 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1335 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1337 let profiler = SelfProfiler::new(
1339 sopts.crate_name.as_deref(),
1340 sopts.unstable_opts.self_profile_events.as_ref().map(|xs| &xs[..]),
1341 &sopts.unstable_opts.self_profile_counter,
1344 Ok(profiler) => Some(Arc::new(profiler)),
1346 early_warn(sopts.error_format, &format!("failed to create profiler: {e}"));
1354 let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1355 parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1357 let host_triple = config::host_triple();
1358 let target_triple = sopts.target_triple.triple();
1359 let host_tlib_path = Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1360 let target_tlib_path = if host_triple == target_triple {
1361 // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1362 // rescanning of the target lib path and an unnecessary allocation.
1363 host_tlib_path.clone()
1365 Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1368 let file_path_mapping = sopts.file_path_mapping();
1370 let local_crate_source_file =
1371 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1373 let optimization_fuel = Lock::new(OptimizationFuel {
1374 remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |i| i.1),
1377 let print_fuel = AtomicU64::new(0);
1379 let cgu_reuse_tracker = if sopts.unstable_opts.query_dep_graph {
1380 CguReuseTracker::new()
1382 CguReuseTracker::new_disabled()
1386 SelfProfilerRef::new(self_profiler, sopts.time_passes(), sopts.unstable_opts.time_passes);
1388 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1389 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1390 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1391 _ => CtfeBacktrace::Disabled,
1395 if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1397 let sess = Session {
1405 local_crate_source_file,
1406 crate_types: OnceCell::new(),
1407 stable_crate_id: OnceCell::new(),
1408 features: OnceCell::new(),
1409 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1412 perf_stats: PerfStats {
1413 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1414 queries_canonicalized: AtomicUsize::new(0),
1415 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1416 normalize_projection_ty: AtomicUsize::new(0),
1418 code_stats: Default::default(),
1421 jobserver: jobserver::client(),
1424 miri_unleashed_features: Lock::new(Default::default()),
1426 target_features: FxHashSet::default(),
1427 unstable_target_features: FxHashSet::default(),
1430 validate_commandline_args_with_session_available(&sess);
1435 /// Validate command line arguments with a `Session`.
1437 /// If it is useful to have a Session available already for validating a commandline argument, you
1439 // JUSTIFICATION: needs to access args to validate them
1440 #[allow(rustc::bad_opt_access)]
1441 fn validate_commandline_args_with_session_available(sess: &Session) {
1442 // Since we don't know if code in an rlib will be linked to statically or
1443 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1444 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1445 // these manually generated symbols confuse LLD when it tries to merge
1446 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1447 // when compiling for LLD ThinLTO. This way we can validly just not generate
1448 // the `dllimport` attributes and `__imp_` symbols in that case.
1449 if sess.opts.cg.linker_plugin_lto.enabled()
1450 && sess.opts.cg.prefer_dynamic
1451 && sess.target.is_like_windows
1454 "Linker plugin based LTO is not supported together with \
1455 `-C prefer-dynamic` when targeting Windows-like targets",
1459 // Make sure that any given profiling data actually exists so LLVM can't
1460 // decide to silently skip PGO.
1461 if let Some(ref path) = sess.opts.cg.profile_use {
1464 "File `{}` passed to `-C profile-use` does not exist.",
1470 // Do the same for sample profile data.
1471 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1474 "File `{}` passed to `-C profile-sample-use` does not exist.",
1480 // Unwind tables cannot be disabled if the target requires them.
1481 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1482 if sess.target.requires_uwtable && !include_uwtables {
1484 "target requires unwind tables, they cannot be disabled with \
1485 `-C force-unwind-tables=no`.",
1490 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1491 let supported_sanitizers = sess.target.options.supported_sanitizers;
1492 let unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1493 match unsupported_sanitizers.into_iter().count() {
1497 "{} sanitizer is not supported for this target",
1498 unsupported_sanitizers
1503 "{} sanitizers are not supported for this target",
1504 unsupported_sanitizers
1508 // Cannot mix and match sanitizers.
1509 let mut sanitizer_iter = sess.opts.unstable_opts.sanitizer.into_iter();
1510 if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1511 sess.err(&format!("`-Zsanitizer={first}` is incompatible with `-Zsanitizer={second}`"));
1514 // Cannot enable crt-static with sanitizers on Linux
1515 if sess.crt_static(None) && !sess.opts.unstable_opts.sanitizer.is_empty() {
1517 "sanitizer is incompatible with statically linked libc, \
1518 disable it using `-C target-feature=-crt-static`",
1522 // LLVM CFI and VFE both require LTO.
1523 if sess.lto() != config::Lto::Fat {
1524 if sess.is_sanitizer_cfi_enabled() {
1525 sess.err("`-Zsanitizer=cfi` requires `-Clto`");
1527 if sess.opts.unstable_opts.virtual_function_elimination {
1528 sess.err("`-Zvirtual-function-elimination` requires `-Clto`");
1532 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1533 if !sess.target.options.supports_stack_protector {
1535 "`-Z stack-protector={}` is not supported for target {} and will be ignored",
1536 sess.opts.unstable_opts.stack_protector, sess.opts.target_triple
1541 if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version {
1542 if dwarf_version > 5 {
1543 sess.err(&format!("requested DWARF version {} is greater than 5", dwarf_version));
1548 /// Holds data on the current incremental compilation session, if there is one.
1550 pub enum IncrCompSession {
1551 /// This is the state the session will be in until the incr. comp. dir is
1554 /// This is the state during which the session directory is private and can
1556 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1557 /// This is the state after the session directory has been finalized. In this
1558 /// state, the contents of the directory must not be modified any more.
1559 Finalized { session_directory: PathBuf },
1560 /// This is an error state that is reached when some compilation error has
1561 /// occurred. It indicates that the contents of the session directory must
1562 /// not be used, since they might be invalid.
1563 InvalidBecauseOfErrors { session_directory: PathBuf },
1566 fn early_error_handler(output: config::ErrorOutputType) -> rustc_errors::Handler {
1567 let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1568 let emitter: Box<dyn Emitter + sync::Send> = match output {
1569 config::ErrorOutputType::HumanReadable(kind) => {
1570 let (short, color_config) = kind.unzip();
1571 Box::new(EmitterWriter::stderr(
1582 config::ErrorOutputType::Json { pretty, json_rendered } => {
1583 Box::new(JsonEmitter::basic(pretty, json_rendered, None, fallback_bundle, None, false))
1586 rustc_errors::Handler::with_emitter(true, None, emitter)
1589 pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) -> ErrorGuaranteed {
1590 early_error_handler(output).struct_err(msg).emit()
1593 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1594 early_error_handler(output).struct_fatal(msg).emit()
1597 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1598 early_error_handler(output).struct_warn(msg).emit()