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, OutputType, SwitchWithOptPath};
5 use crate::parse::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>,
199 pub struct PerfStats {
200 /// The accumulated time spent on computing symbol hashes.
201 pub symbol_hash_time: Lock<Duration>,
202 /// Total number of values canonicalized queries constructed.
203 pub queries_canonicalized: AtomicUsize,
204 /// Number of times this query is invoked.
205 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
206 /// Number of times this query is invoked.
207 pub normalize_projection_ty: AtomicUsize,
210 /// Trait implemented by error types. This should not be implemented manually. Instead, use
211 /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic].
212 #[rustc_diagnostic_item = "SessionDiagnostic"]
213 pub trait SessionDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> {
214 /// Write out as a diagnostic out of `sess`.
216 fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, T>;
220 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
221 self.miri_unleashed_features.lock().push((span, feature_gate));
224 fn check_miri_unleashed_features(&self) {
225 let unleashed_features = self.miri_unleashed_features.lock();
226 if !unleashed_features.is_empty() {
227 let mut must_err = false;
228 // Create a diagnostic pointing at where things got unleashed.
229 let mut diag = self.struct_warn("skipping const checks");
230 for &(span, feature_gate) in unleashed_features.iter() {
231 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
232 if let Some(gate) = feature_gate {
233 diag.span_help(span, &format!("skipping check for `{gate}` feature"));
234 // The unleash flag must *not* be used to just "hack around" feature gates.
237 diag.span_help(span, "skipping check that does not even have a feature gate");
241 // If we should err, make sure we did.
242 if must_err && self.has_errors().is_none() {
243 // We have skipped a feature gate, and not run into other errors... reject.
245 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
246 gates, except when testing error paths in the CTFE engine",
252 /// Invoked all the way at the end to finish off diagnostics printing.
253 pub fn finish_diagnostics(&self, registry: &Registry) {
254 self.check_miri_unleashed_features();
255 self.diagnostic().print_error_count(registry);
256 self.emit_future_breakage();
259 fn emit_future_breakage(&self) {
260 if !self.opts.json_future_incompat {
264 let diags = self.diagnostic().take_future_breakage_diagnostics();
265 if diags.is_empty() {
268 self.parse_sess.span_diagnostic.emit_future_breakage_report(diags);
271 pub fn local_stable_crate_id(&self) -> StableCrateId {
272 self.stable_crate_id.get().copied().unwrap()
275 pub fn crate_types(&self) -> &[CrateType] {
276 self.crate_types.get().unwrap().as_slice()
279 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
280 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
283 pub fn struct_span_warn<S: Into<MultiSpan>>(
286 msg: impl Into<DiagnosticMessage>,
287 ) -> DiagnosticBuilder<'_, ()> {
288 self.diagnostic().struct_span_warn(sp, msg)
290 pub fn struct_span_warn_with_expectation<S: Into<MultiSpan>>(
293 msg: impl Into<DiagnosticMessage>,
294 id: lint::LintExpectationId,
295 ) -> DiagnosticBuilder<'_, ()> {
296 self.diagnostic().struct_span_warn_with_expectation(sp, msg, id)
298 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
301 msg: impl Into<DiagnosticMessage>,
303 ) -> DiagnosticBuilder<'_, ()> {
304 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
306 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
307 self.diagnostic().struct_warn(msg)
309 pub fn struct_warn_with_expectation(
311 msg: impl Into<DiagnosticMessage>,
312 id: lint::LintExpectationId,
313 ) -> DiagnosticBuilder<'_, ()> {
314 self.diagnostic().struct_warn_with_expectation(msg, id)
316 pub fn struct_span_allow<S: Into<MultiSpan>>(
319 msg: impl Into<DiagnosticMessage>,
320 ) -> DiagnosticBuilder<'_, ()> {
321 self.diagnostic().struct_span_allow(sp, msg)
323 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
324 self.diagnostic().struct_allow(msg)
326 pub fn struct_expect(
328 msg: impl Into<DiagnosticMessage>,
329 id: lint::LintExpectationId,
330 ) -> DiagnosticBuilder<'_, ()> {
331 self.diagnostic().struct_expect(msg, id)
333 pub fn struct_span_err<S: Into<MultiSpan>>(
336 msg: impl Into<DiagnosticMessage>,
337 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
338 self.diagnostic().struct_span_err(sp, msg)
340 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
343 msg: impl Into<DiagnosticMessage>,
345 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
346 self.diagnostic().struct_span_err_with_code(sp, msg, code)
348 // FIXME: This method should be removed (every error should have an associated error code).
351 msg: impl Into<DiagnosticMessage>,
352 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
353 self.parse_sess.struct_err(msg)
355 pub fn struct_err_with_code(
357 msg: impl Into<DiagnosticMessage>,
359 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
360 self.diagnostic().struct_err_with_code(msg, code)
362 pub fn struct_warn_with_code(
364 msg: impl Into<DiagnosticMessage>,
366 ) -> DiagnosticBuilder<'_, ()> {
367 self.diagnostic().struct_warn_with_code(msg, code)
369 pub fn struct_span_fatal<S: Into<MultiSpan>>(
372 msg: impl Into<DiagnosticMessage>,
373 ) -> DiagnosticBuilder<'_, !> {
374 self.diagnostic().struct_span_fatal(sp, msg)
376 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
379 msg: impl Into<DiagnosticMessage>,
381 ) -> DiagnosticBuilder<'_, !> {
382 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
384 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
385 self.diagnostic().struct_fatal(msg)
388 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
389 self.diagnostic().span_fatal(sp, msg)
391 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
394 msg: impl Into<DiagnosticMessage>,
397 self.diagnostic().span_fatal_with_code(sp, msg, code)
399 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! {
400 self.diagnostic().fatal(msg).raise()
402 pub fn span_err_or_warn<S: Into<MultiSpan>>(
406 msg: impl Into<DiagnosticMessage>,
409 self.span_warn(sp, msg);
411 self.span_err(sp, msg);
414 pub fn span_err<S: Into<MultiSpan>>(
417 msg: impl Into<DiagnosticMessage>,
418 ) -> ErrorGuaranteed {
419 self.diagnostic().span_err(sp, msg)
421 pub fn span_err_with_code<S: Into<MultiSpan>>(
424 msg: impl Into<DiagnosticMessage>,
427 self.diagnostic().span_err_with_code(sp, msg, code)
429 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
430 self.diagnostic().err(msg)
432 pub fn create_err<'a>(
434 err: impl SessionDiagnostic<'a>,
435 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
436 self.parse_sess.create_err(err)
438 pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed {
439 self.parse_sess.emit_err(err)
441 pub fn create_warning<'a>(
443 err: impl SessionDiagnostic<'a, ()>,
444 ) -> DiagnosticBuilder<'a, ()> {
445 self.parse_sess.create_warning(err)
447 pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) {
448 self.parse_sess.emit_warning(warning)
451 pub fn err_count(&self) -> usize {
452 self.diagnostic().err_count()
454 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
455 self.diagnostic().has_errors()
457 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
458 self.diagnostic().has_errors_or_delayed_span_bugs()
460 pub fn abort_if_errors(&self) {
461 self.diagnostic().abort_if_errors();
463 pub fn compile_status(&self) -> Result<(), ErrorGuaranteed> {
464 if let Some(reported) = self.diagnostic().has_errors_or_lint_errors() {
465 let _ = self.diagnostic().emit_stashed_diagnostics();
471 // FIXME(matthewjasper) Remove this method, it should never be needed.
472 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorGuaranteed>
476 let old_count = self.err_count();
478 if self.err_count() == old_count {
481 Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
484 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
485 self.diagnostic().span_warn(sp, msg)
487 pub fn span_warn_with_code<S: Into<MultiSpan>>(
490 msg: impl Into<DiagnosticMessage>,
493 self.diagnostic().span_warn_with_code(sp, msg, code)
495 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
496 self.diagnostic().warn(msg)
498 /// Delay a span_bug() call until abort_if_errors()
500 pub fn delay_span_bug<S: Into<MultiSpan>>(
503 msg: impl Into<DiagnosticMessage>,
504 ) -> ErrorGuaranteed {
505 self.diagnostic().delay_span_bug(sp, msg)
508 /// Used for code paths of expensive computations that should only take place when
509 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
510 /// it's likely a bug.
511 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
512 if self.opts.debugging_opts.print_type_sizes
513 || self.opts.debugging_opts.query_dep_graph
514 || self.opts.debugging_opts.dump_mir.is_some()
515 || self.opts.debugging_opts.unpretty.is_some()
516 || self.opts.output_types.contains_key(&OutputType::Mir)
517 || std::env::var_os("RUSTC_LOG").is_some()
522 self.diagnostic().delay_good_path_bug(msg)
525 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
526 self.diagnostic().note_without_error(msg)
528 pub fn span_note_without_error<S: Into<MultiSpan>>(
531 msg: impl Into<DiagnosticMessage>,
533 self.diagnostic().span_note_without_error(sp, msg)
535 pub fn struct_note_without_error(
537 msg: impl Into<DiagnosticMessage>,
538 ) -> DiagnosticBuilder<'_, ()> {
539 self.diagnostic().struct_note_without_error(msg)
543 pub fn diagnostic(&self) -> &rustc_errors::Handler {
544 &self.parse_sess.span_diagnostic
548 pub fn source_map(&self) -> &SourceMap {
549 self.parse_sess.source_map()
551 pub fn verbose(&self) -> bool {
552 self.opts.debugging_opts.verbose
554 pub fn time_passes(&self) -> bool {
555 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
557 pub fn instrument_mcount(&self) -> bool {
558 self.opts.debugging_opts.instrument_mcount
560 pub fn time_llvm_passes(&self) -> bool {
561 self.opts.debugging_opts.time_llvm_passes
563 pub fn meta_stats(&self) -> bool {
564 self.opts.debugging_opts.meta_stats
566 pub fn asm_comments(&self) -> bool {
567 self.opts.debugging_opts.asm_comments
569 pub fn verify_llvm_ir(&self) -> bool {
570 self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
572 pub fn print_llvm_passes(&self) -> bool {
573 self.opts.debugging_opts.print_llvm_passes
575 pub fn binary_dep_depinfo(&self) -> bool {
576 self.opts.debugging_opts.binary_dep_depinfo
578 pub fn mir_opt_level(&self) -> usize {
579 self.opts.mir_opt_level()
582 /// Gets the features enabled for the current compilation session.
583 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
584 /// dependency tracking. Use tcx.features() instead.
586 pub fn features_untracked(&self) -> &rustc_feature::Features {
587 self.features.get().unwrap()
590 pub fn init_features(&self, features: rustc_feature::Features) {
591 match self.features.set(features) {
593 Err(_) => panic!("`features` was initialized twice"),
597 /// Calculates the flavor of LTO to use for this compilation.
598 pub fn lto(&self) -> config::Lto {
599 // If our target has codegen requirements ignore the command line
600 if self.target.requires_lto {
601 return config::Lto::Fat;
604 // If the user specified something, return that. If they only said `-C
605 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
606 // then ensure we can't use a ThinLTO.
607 match self.opts.cg.lto {
608 config::LtoCli::Unspecified => {
609 // The compiler was invoked without the `-Clto` flag. Fall
610 // through to the default handling
612 config::LtoCli::No => {
613 // The user explicitly opted out of any kind of LTO
614 return config::Lto::No;
616 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
617 // All of these mean fat LTO
618 return config::Lto::Fat;
620 config::LtoCli::Thin => {
621 return if self.opts.cli_forced_thinlto_off {
629 // Ok at this point the target doesn't require anything and the user
630 // hasn't asked for anything. Our next decision is whether or not
631 // we enable "auto" ThinLTO where we use multiple codegen units and
632 // then do ThinLTO over those codegen units. The logic below will
633 // either return `No` or `ThinLocal`.
635 // If processing command line options determined that we're incompatible
636 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
637 if self.opts.cli_forced_thinlto_off {
638 return config::Lto::No;
641 // If `-Z thinlto` specified process that, but note that this is mostly
642 // a deprecated option now that `-C lto=thin` exists.
643 if let Some(enabled) = self.opts.debugging_opts.thinlto {
645 return config::Lto::ThinLocal;
647 return config::Lto::No;
651 // If there's only one codegen unit and LTO isn't enabled then there's
652 // no need for ThinLTO so just return false.
653 if self.codegen_units() == 1 {
654 return config::Lto::No;
657 // Now we're in "defaults" territory. By default we enable ThinLTO for
658 // optimized compiles (anything greater than O0).
659 match self.opts.optimize {
660 config::OptLevel::No => config::Lto::No,
661 _ => config::Lto::ThinLocal,
665 /// Returns the panic strategy for this compile session. If the user explicitly selected one
666 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
667 pub fn panic_strategy(&self) -> PanicStrategy {
668 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
670 pub fn fewer_names(&self) -> bool {
671 if let Some(fewer_names) = self.opts.debugging_opts.fewer_names {
674 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
675 || self.opts.output_types.contains_key(&OutputType::Bitcode)
676 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
677 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
682 pub fn unstable_options(&self) -> bool {
683 self.opts.debugging_opts.unstable_options
685 pub fn is_nightly_build(&self) -> bool {
686 self.opts.unstable_features.is_nightly_build()
688 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
689 self.opts.debugging_opts.sanitizer.contains(SanitizerSet::CFI)
691 pub fn overflow_checks(&self) -> bool {
692 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
695 /// Check whether this compile session and crate type use static crt.
696 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
697 if !self.target.crt_static_respected {
698 // If the target does not opt in to crt-static support, use its default.
699 return self.target.crt_static_default;
702 let requested_features = self.opts.cg.target_feature.split(',');
703 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
704 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
706 if found_positive || found_negative {
708 } else if crate_type == Some(CrateType::ProcMacro)
709 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
711 // FIXME: When crate_type is not available,
712 // we use compiler options to determine the crate_type.
713 // We can't check `#![crate_type = "proc-macro"]` here.
716 self.target.crt_static_default
720 pub fn relocation_model(&self) -> RelocModel {
721 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
724 pub fn code_model(&self) -> Option<CodeModel> {
725 self.opts.cg.code_model.or(self.target.code_model)
728 pub fn tls_model(&self) -> TlsModel {
729 self.opts.debugging_opts.tls_model.unwrap_or(self.target.tls_model)
732 pub fn is_wasi_reactor(&self) -> bool {
733 self.target.options.os == "wasi"
735 self.opts.debugging_opts.wasi_exec_model,
736 Some(config::WasiExecModel::Reactor)
740 pub fn split_debuginfo(&self) -> SplitDebuginfo {
741 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
744 pub fn stack_protector(&self) -> StackProtector {
745 if self.target.options.supports_stack_protector {
746 self.opts.debugging_opts.stack_protector
752 pub fn target_can_use_split_dwarf(&self) -> bool {
753 !self.target.is_like_windows && !self.target.is_like_osx
756 pub fn must_emit_unwind_tables(&self) -> bool {
757 // This is used to control the emission of the `uwtable` attribute on
760 // Unwind tables are needed when compiling with `-C panic=unwind`, but
761 // LLVM won't omit unwind tables unless the function is also marked as
762 // `nounwind`, so users are allowed to disable `uwtable` emission.
763 // Historically rustc always emits `uwtable` attributes by default, so
764 // even they can be disabled, they're still emitted by default.
766 // On some targets (including windows), however, exceptions include
767 // other events such as illegal instructions, segfaults, etc. This means
768 // that on Windows we end up still needing unwind tables even if the `-C
769 // panic=abort` flag is passed.
771 // You can also find more info on why Windows needs unwind tables in:
772 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
774 // If a target requires unwind tables, then they must be emitted.
775 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
776 // value, if it is provided, or disable them, if not.
777 self.target.requires_uwtable
778 || self.opts.cg.force_unwind_tables.unwrap_or(
779 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
783 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
784 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.to_u64())
787 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
788 filesearch::FileSearch::new(
790 self.opts.target_triple.triple(),
791 &self.opts.search_paths,
792 &self.target_tlib_path,
796 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
797 filesearch::FileSearch::new(
799 config::host_triple(),
800 &self.opts.search_paths,
801 &self.host_tlib_path,
806 /// Returns a list of directories where target-specific tool binaries are located.
807 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
808 let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple());
809 let p = PathBuf::from_iter([
810 Path::new(&self.sysroot),
811 Path::new(&rustlib_path),
814 if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
817 pub fn init_incr_comp_session(
819 session_dir: PathBuf,
820 lock_file: flock::Lock,
821 load_dep_graph: bool,
823 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
825 if let IncrCompSession::NotInitialized = *incr_comp_session {
827 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
831 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
834 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
835 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
837 if let IncrCompSession::Active { .. } = *incr_comp_session {
839 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
842 // Note: this will also drop the lock file, thus unlocking the directory.
843 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
846 pub fn mark_incr_comp_session_as_invalid(&self) {
847 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
849 let session_directory = match *incr_comp_session {
850 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
851 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
852 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
855 // Note: this will also drop the lock file, thus unlocking the directory.
856 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
859 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
860 let incr_comp_session = self.incr_comp_session.borrow();
861 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
862 IncrCompSession::NotInitialized => panic!(
863 "trying to get session directory from `IncrCompSession`: {:?}",
866 IncrCompSession::Active { ref session_directory, .. }
867 | IncrCompSession::Finalized { ref session_directory }
868 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
874 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
875 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
878 pub fn print_perf_stats(&self) {
880 "Total time spent computing symbol hashes: {}",
881 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
884 "Total queries canonicalized: {}",
885 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
888 "normalize_generic_arg_after_erasing_regions: {}",
889 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
892 "normalize_projection_ty: {}",
893 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
897 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
898 /// This expends fuel if applicable, and records fuel if applicable.
899 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
901 if let Some((ref c, _)) = self.opts.debugging_opts.fuel {
903 assert_eq!(self.threads(), 1);
904 let mut fuel = self.optimization_fuel.lock();
905 ret = fuel.remaining != 0;
906 if fuel.remaining == 0 && !fuel.out_of_fuel {
907 if self.diagnostic().can_emit_warnings() {
908 // We only call `msg` in case we can actually emit warnings.
909 // Otherwise, this could cause a `delay_good_path_bug` to
910 // trigger (issue #79546).
911 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
913 fuel.out_of_fuel = true;
914 } else if fuel.remaining > 0 {
919 if let Some(ref c) = self.opts.debugging_opts.print_fuel {
921 assert_eq!(self.threads(), 1);
922 self.print_fuel.fetch_add(1, SeqCst);
928 /// Returns the number of query threads that should be used for this
930 pub fn threads(&self) -> usize {
931 self.opts.debugging_opts.threads
934 /// Returns the number of codegen units that should be used for this
936 pub fn codegen_units(&self) -> usize {
937 if let Some(n) = self.opts.cli_forced_codegen_units {
940 if let Some(n) = self.target.default_codegen_units {
944 // If incremental compilation is turned on, we default to a high number
945 // codegen units in order to reduce the "collateral damage" small
947 if self.opts.incremental.is_some() {
951 // Why is 16 codegen units the default all the time?
953 // The main reason for enabling multiple codegen units by default is to
954 // leverage the ability for the codegen backend to do codegen and
955 // optimization in parallel. This allows us, especially for large crates, to
956 // make good use of all available resources on the machine once we've
957 // hit that stage of compilation. Large crates especially then often
958 // take a long time in codegen/optimization and this helps us amortize that
961 // Note that a high number here doesn't mean that we'll be spawning a
962 // large number of threads in parallel. The backend of rustc contains
963 // global rate limiting through the `jobserver` crate so we'll never
964 // overload the system with too much work, but rather we'll only be
965 // optimizing when we're otherwise cooperating with other instances of
968 // Rather a high number here means that we should be able to keep a lot
969 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
970 // to build we'll be guaranteed that all cpus will finish pretty closely
971 // to one another and we should make relatively optimal use of system
974 // Note that the main cost of codegen units is that it prevents LLVM
975 // from inlining across codegen units. Users in general don't have a lot
976 // of control over how codegen units are split up so it's our job in the
977 // compiler to ensure that undue performance isn't lost when using
978 // codegen units (aka we can't require everyone to slap `#[inline]` on
981 // If we're compiling at `-O0` then the number doesn't really matter too
982 // much because performance doesn't matter and inlining is ok to lose.
983 // In debug mode we just want to try to guarantee that no cpu is stuck
984 // doing work that could otherwise be farmed to others.
986 // In release mode, however (O1 and above) performance does indeed
987 // matter! To recover the loss in performance due to inlining we'll be
988 // enabling ThinLTO by default (the function for which is just below).
989 // This will ensure that we recover any inlining wins we otherwise lost
990 // through codegen unit partitioning.
994 // Ok that's a lot of words but the basic tl;dr; is that we want a high
995 // number here -- but not too high. Additionally we're "safe" to have it
996 // always at the same number at all optimization levels.
998 // As a result 16 was chosen here! Mostly because it was a power of 2
999 // and most benchmarks agreed it was roughly a local optimum. Not very
1004 pub fn teach(&self, code: &DiagnosticId) -> bool {
1005 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
1008 pub fn rust_2015(&self) -> bool {
1009 self.opts.edition == Edition::Edition2015
1012 /// Are we allowed to use features from the Rust 2018 edition?
1013 pub fn rust_2018(&self) -> bool {
1014 self.opts.edition >= Edition::Edition2018
1017 /// Are we allowed to use features from the Rust 2021 edition?
1018 pub fn rust_2021(&self) -> bool {
1019 self.opts.edition >= Edition::Edition2021
1022 /// Are we allowed to use features from the Rust 2024 edition?
1023 pub fn rust_2024(&self) -> bool {
1024 self.opts.edition >= Edition::Edition2024
1027 pub fn edition(&self) -> Edition {
1031 /// Returns `true` if we cannot skip the PLT for shared library calls.
1032 pub fn needs_plt(&self) -> bool {
1033 // Check if the current target usually needs PLT to be enabled.
1034 // The user can use the command line flag to override it.
1035 let needs_plt = self.target.needs_plt;
1037 let dbg_opts = &self.opts.debugging_opts;
1039 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
1041 // Only enable this optimization by default if full relro is also enabled.
1042 // In this case, lazy binding was already unavailable, so nothing is lost.
1043 // This also ensures `-Wl,-z,now` is supported by the linker.
1044 let full_relro = RelroLevel::Full == relro_level;
1046 // If user didn't explicitly forced us to use / skip the PLT,
1047 // then try to skip it where possible.
1048 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1051 /// Checks if LLVM lifetime markers should be emitted.
1052 pub fn emit_lifetime_markers(&self) -> bool {
1053 self.opts.optimize != config::OptLevel::No
1054 // AddressSanitizer uses lifetimes to detect use after scope bugs.
1055 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1056 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
1057 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
1060 pub fn link_dead_code(&self) -> bool {
1061 self.opts.cg.link_dead_code.unwrap_or(false)
1064 pub fn instrument_coverage(&self) -> bool {
1065 self.opts.instrument_coverage()
1068 pub fn instrument_coverage_except_unused_generics(&self) -> bool {
1069 self.opts.instrument_coverage_except_unused_generics()
1072 pub fn instrument_coverage_except_unused_functions(&self) -> bool {
1073 self.opts.instrument_coverage_except_unused_functions()
1076 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1077 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1079 .any(|kind| attr.has_name(*kind))
1082 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1083 attrs.iter().any(|item| item.has_name(name))
1086 pub fn find_by_name<'a>(
1088 attrs: &'a [Attribute],
1090 ) -> Option<&'a Attribute> {
1091 attrs.iter().find(|attr| attr.has_name(name))
1094 pub fn filter_by_name<'a>(
1096 attrs: &'a [Attribute],
1098 ) -> impl Iterator<Item = &'a Attribute> {
1099 attrs.iter().filter(move |attr| attr.has_name(name))
1102 pub fn first_attr_value_str_by_name(
1104 attrs: &[Attribute],
1106 ) -> Option<Symbol> {
1107 attrs.iter().find(|at| at.has_name(name)).and_then(|at| at.value_str())
1112 sopts: &config::Options,
1113 registry: rustc_errors::registry::Registry,
1114 source_map: Lrc<SourceMap>,
1115 bundle: Option<Lrc<FluentBundle>>,
1116 fallback_bundle: LazyFallbackBundle,
1117 emitter_dest: Option<Box<dyn Write + Send>>,
1118 ) -> Box<dyn Emitter + sync::Send> {
1119 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1120 match (sopts.error_format, emitter_dest) {
1121 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1122 let (short, color_config) = kind.unzip();
1124 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1125 let emitter = AnnotateSnippetEmitterWriter::new(
1132 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1134 let emitter = match dst {
1135 None => EmitterWriter::stderr(
1141 sopts.debugging_opts.teach,
1142 sopts.debugging_opts.terminal_width,
1145 Some(dst) => EmitterWriter::new(
1151 false, // no teach messages when writing to a buffer
1152 false, // no colors when writing to a buffer
1153 None, // no terminal width
1157 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1160 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1161 JsonEmitter::stderr(
1168 sopts.debugging_opts.terminal_width,
1171 .ui_testing(sopts.debugging_opts.ui_testing),
1173 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1182 sopts.debugging_opts.terminal_width,
1185 .ui_testing(sopts.debugging_opts.ui_testing),
1190 pub enum DiagnosticOutput {
1192 Raw(Box<dyn Write + Send>),
1195 pub fn build_session(
1196 sopts: config::Options,
1197 local_crate_source_file: Option<PathBuf>,
1198 bundle: Option<Lrc<rustc_errors::FluentBundle>>,
1199 registry: rustc_errors::registry::Registry,
1200 diagnostics_output: DiagnosticOutput,
1201 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1202 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1203 target_override: Option<Target>,
1205 // FIXME: This is not general enough to make the warning lint completely override
1206 // normal diagnostic warnings, since the warning lint can also be denied and changed
1207 // later via the source code.
1208 let warnings_allow = sopts
1211 .filter(|&&(ref key, _)| *key == "warnings")
1212 .map(|&(_, ref level)| *level == lint::Allow)
1215 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1216 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1218 let write_dest = match diagnostics_output {
1219 DiagnosticOutput::Default => None,
1220 DiagnosticOutput::Raw(write) => Some(write),
1223 let sysroot = match &sopts.maybe_sysroot {
1224 Some(sysroot) => sysroot.clone(),
1225 None => filesearch::get_or_default_sysroot(),
1228 let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
1229 let host_triple = TargetTriple::from_triple(config::host_triple());
1230 let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1231 early_error(sopts.error_format, &format!("Error loading host specification: {e}"))
1233 for warning in target_warnings.warning_messages() {
1234 early_warn(sopts.error_format, &warning)
1237 let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1238 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1239 if target_cfg.is_like_msvc {
1240 SourceFileHashAlgorithm::Sha1
1242 SourceFileHashAlgorithm::Md5
1245 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1247 sopts.file_path_mapping(),
1251 let fallback_bundle = fallback_fluent_bundle(
1252 rustc_errors::DEFAULT_LOCALE_RESOURCES,
1253 sopts.debugging_opts.translate_directionality_markers,
1256 default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle, write_dest);
1258 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1260 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1263 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1266 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1268 let profiler = SelfProfiler::new(
1270 sopts.crate_name.as_deref(),
1271 sopts.debugging_opts.self_profile_events.as_ref().map(|xs| &xs[..]),
1272 &sopts.debugging_opts.self_profile_counter,
1275 Ok(profiler) => Some(Arc::new(profiler)),
1277 early_warn(sopts.error_format, &format!("failed to create profiler: {e}"));
1285 let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1286 parse_sess.assume_incomplete_release = sopts.debugging_opts.assume_incomplete_release;
1288 let host_triple = config::host_triple();
1289 let target_triple = sopts.target_triple.triple();
1290 let host_tlib_path = Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1291 let target_tlib_path = if host_triple == target_triple {
1292 // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1293 // rescanning of the target lib path and an unnecessary allocation.
1294 host_tlib_path.clone()
1296 Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1299 let file_path_mapping = sopts.file_path_mapping();
1301 let local_crate_source_file =
1302 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1304 let optimization_fuel = Lock::new(OptimizationFuel {
1305 remaining: sopts.debugging_opts.fuel.as_ref().map_or(0, |i| i.1),
1308 let print_fuel = AtomicU64::new(0);
1310 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1311 CguReuseTracker::new()
1313 CguReuseTracker::new_disabled()
1316 let prof = SelfProfilerRef::new(
1318 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1319 sopts.debugging_opts.time_passes,
1322 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1323 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1324 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1325 _ => CtfeBacktrace::Disabled,
1329 if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1331 let sess = Session {
1339 local_crate_source_file,
1340 crate_types: OnceCell::new(),
1341 stable_crate_id: OnceCell::new(),
1342 features: OnceCell::new(),
1343 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1346 perf_stats: PerfStats {
1347 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1348 queries_canonicalized: AtomicUsize::new(0),
1349 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1350 normalize_projection_ty: AtomicUsize::new(0),
1352 code_stats: Default::default(),
1355 jobserver: jobserver::client(),
1358 miri_unleashed_features: Lock::new(Default::default()),
1360 target_features: FxHashSet::default(),
1363 validate_commandline_args_with_session_available(&sess);
1368 // If it is useful to have a Session available already for validating a
1369 // commandline argument, you can do so here.
1370 fn validate_commandline_args_with_session_available(sess: &Session) {
1371 // Since we don't know if code in an rlib will be linked to statically or
1372 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1373 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1374 // these manually generated symbols confuse LLD when it tries to merge
1375 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1376 // when compiling for LLD ThinLTO. This way we can validly just not generate
1377 // the `dllimport` attributes and `__imp_` symbols in that case.
1378 if sess.opts.cg.linker_plugin_lto.enabled()
1379 && sess.opts.cg.prefer_dynamic
1380 && sess.target.is_like_windows
1383 "Linker plugin based LTO is not supported together with \
1384 `-C prefer-dynamic` when targeting Windows-like targets",
1388 // Make sure that any given profiling data actually exists so LLVM can't
1389 // decide to silently skip PGO.
1390 if let Some(ref path) = sess.opts.cg.profile_use {
1393 "File `{}` passed to `-C profile-use` does not exist.",
1399 // Do the same for sample profile data.
1400 if let Some(ref path) = sess.opts.debugging_opts.profile_sample_use {
1403 "File `{}` passed to `-C profile-sample-use` does not exist.",
1409 // Unwind tables cannot be disabled if the target requires them.
1410 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1411 if sess.target.requires_uwtable && !include_uwtables {
1413 "target requires unwind tables, they cannot be disabled with \
1414 `-C force-unwind-tables=no`.",
1419 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1420 let supported_sanitizers = sess.target.options.supported_sanitizers;
1421 let unsupported_sanitizers = sess.opts.debugging_opts.sanitizer - supported_sanitizers;
1422 match unsupported_sanitizers.into_iter().count() {
1426 "{} sanitizer is not supported for this target",
1427 unsupported_sanitizers
1432 "{} sanitizers are not supported for this target",
1433 unsupported_sanitizers
1437 // Cannot mix and match sanitizers.
1438 let mut sanitizer_iter = sess.opts.debugging_opts.sanitizer.into_iter();
1439 if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1440 sess.err(&format!("`-Zsanitizer={first}` is incompatible with `-Zsanitizer={second}`"));
1443 // Cannot enable crt-static with sanitizers on Linux
1444 if sess.crt_static(None) && !sess.opts.debugging_opts.sanitizer.is_empty() {
1446 "sanitizer is incompatible with statically linked libc, \
1447 disable it using `-C target-feature=-crt-static`",
1451 // LLVM CFI and VFE both require LTO.
1452 if sess.lto() != config::Lto::Fat {
1453 if sess.is_sanitizer_cfi_enabled() {
1454 sess.err("`-Zsanitizer=cfi` requires `-Clto`");
1456 if sess.opts.debugging_opts.virtual_function_elimination {
1457 sess.err("`-Zvirtual-function-elimination` requires `-Clto`");
1461 if sess.opts.debugging_opts.stack_protector != StackProtector::None {
1462 if !sess.target.options.supports_stack_protector {
1464 "`-Z stack-protector={}` is not supported for target {} and will be ignored",
1465 sess.opts.debugging_opts.stack_protector, sess.opts.target_triple
1471 /// Holds data on the current incremental compilation session, if there is one.
1473 pub enum IncrCompSession {
1474 /// This is the state the session will be in until the incr. comp. dir is
1477 /// This is the state during which the session directory is private and can
1479 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1480 /// This is the state after the session directory has been finalized. In this
1481 /// state, the contents of the directory must not be modified any more.
1482 Finalized { session_directory: PathBuf },
1483 /// This is an error state that is reached when some compilation error has
1484 /// occurred. It indicates that the contents of the session directory must
1485 /// not be used, since they might be invalid.
1486 InvalidBecauseOfErrors { session_directory: PathBuf },
1489 fn early_error_handler(output: config::ErrorOutputType) -> rustc_errors::Handler {
1490 let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1491 let emitter: Box<dyn Emitter + sync::Send> = match output {
1492 config::ErrorOutputType::HumanReadable(kind) => {
1493 let (short, color_config) = kind.unzip();
1494 Box::new(EmitterWriter::stderr(
1505 config::ErrorOutputType::Json { pretty, json_rendered } => {
1506 Box::new(JsonEmitter::basic(pretty, json_rendered, None, fallback_bundle, None, false))
1509 rustc_errors::Handler::with_emitter(true, None, emitter)
1512 pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) -> ErrorGuaranteed {
1513 early_error_handler(output).struct_err(msg).emit()
1516 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1517 early_error_handler(output).struct_fatal(msg).emit()
1520 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1521 early_error_handler(output).struct_warn(msg).emit()