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;
22 use rustc_errors::{DiagnosticBuilder, DiagnosticId, ErrorReported};
23 use rustc_macros::HashStable_Generic;
24 pub use rustc_span::def_id::StableCrateId;
25 use rustc_span::edition::Edition;
26 use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
27 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
28 use rustc_target::asm::InlineAsmArch;
29 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
30 use rustc_target::spec::{SanitizerSet, SplitDebuginfo, Target, TargetTriple, TlsModel};
32 use std::cell::{self, RefCell};
36 use std::num::NonZeroU32;
37 use std::ops::{Div, Mul};
38 use std::path::{Path, PathBuf};
39 use std::str::FromStr;
41 use std::time::Duration;
43 pub struct OptimizationFuel {
44 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
46 /// We're rejecting all further optimizations.
50 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
51 #[derive(Clone, Copy)]
52 pub enum CtfeBacktrace {
53 /// Do nothing special, return the error as usual without a backtrace.
55 /// Capture a backtrace at the point the error is created and return it in the error
56 /// (to be printed later if/when the error ever actually gets shown to the user).
58 /// Capture a backtrace at the point the error is created and immediately print it out.
62 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
63 /// limits are consistent throughout the compiler.
64 #[derive(Clone, Copy, Debug, HashStable_Generic)]
65 pub struct Limit(pub usize);
68 /// Create a new limit from a `usize`.
69 pub fn new(value: usize) -> Self {
73 /// Check that `value` is within the limit. Ensures that the same comparisons are used
74 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
76 pub fn value_within_limit(&self, value: usize) -> bool {
81 impl From<usize> for Limit {
82 fn from(value: usize) -> Self {
87 impl fmt::Display for Limit {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 write!(f, "{}", self.0)
93 impl Div<usize> for Limit {
96 fn div(self, rhs: usize) -> Self::Output {
97 Limit::new(self.0 / rhs)
101 impl Mul<usize> for Limit {
104 fn mul(self, rhs: usize) -> Self::Output {
105 Limit::new(self.0 * rhs)
109 #[derive(Clone, Copy, Debug, HashStable_Generic)]
111 /// The maximum recursion limit for potentially infinitely recursive
112 /// operations such as auto-dereference and monomorphization.
113 pub recursion_limit: Limit,
114 /// The size at which the `large_assignments` lint starts
116 pub move_size_limit: Limit,
117 /// The maximum length of types during monomorphization.
118 pub type_length_limit: Limit,
119 /// The maximum blocks a const expression can evaluate.
120 pub const_eval_limit: Limit,
123 /// Represents the data associated with a compilation
124 /// session for a single crate.
128 pub opts: config::Options,
129 pub host_tlib_path: Lrc<SearchPath>,
130 pub target_tlib_path: Lrc<SearchPath>,
131 pub parse_sess: ParseSess,
132 pub sysroot: PathBuf,
133 /// The name of the root source file of the crate, in the local file system.
134 /// `None` means that there is no source file.
135 pub local_crate_source_file: Option<PathBuf>,
137 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
138 /// (sub)diagnostics that have been set once, but should not be set again,
139 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
140 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
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 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
211 enum DiagnosticBuilderMethod {
214 // Add more variants as needed to support one-time diagnostics.
217 /// Trait implemented by error types. This should not be implemented manually. Instead, use
218 /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic].
219 pub trait SessionDiagnostic<'a> {
220 /// Write out as a diagnostic out of `sess`.
222 fn into_diagnostic(self, sess: &'a Session) -> DiagnosticBuilder<'a>;
225 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
226 /// emitting the same message more than once.
227 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
228 pub enum DiagnosticMessageId {
229 ErrorId(u16), // EXXXX error code as integer
230 LintId(lint::LintId),
231 StabilityId(Option<NonZeroU32>), // issue number
234 impl From<&'static lint::Lint> for DiagnosticMessageId {
235 fn from(lint: &'static lint::Lint) -> Self {
236 DiagnosticMessageId::LintId(lint::LintId::of(lint))
241 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
242 self.miri_unleashed_features.lock().push((span, feature_gate));
245 fn check_miri_unleashed_features(&self) {
246 let unleashed_features = self.miri_unleashed_features.lock();
247 if !unleashed_features.is_empty() {
248 let mut must_err = false;
249 // Create a diagnostic pointing at where things got unleashed.
250 let mut diag = self.struct_warn("skipping const checks");
251 for &(span, feature_gate) in unleashed_features.iter() {
252 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
253 if let Some(feature_gate) = feature_gate {
254 diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate));
255 // The unleash flag must *not* be used to just "hack around" feature gates.
258 diag.span_help(span, "skipping check that does not even have a feature gate");
262 // If we should err, make sure we did.
263 if must_err && !self.has_errors() {
264 // We have skipped a feature gate, and not run into other errors... reject.
266 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
267 gates, except when testing error paths in the CTFE engine",
273 /// Invoked all the way at the end to finish off diagnostics printing.
274 pub fn finish_diagnostics(&self, registry: &Registry) {
275 self.check_miri_unleashed_features();
276 self.diagnostic().print_error_count(registry);
277 self.emit_future_breakage();
280 fn emit_future_breakage(&self) {
281 if !self.opts.debugging_opts.emit_future_incompat_report {
285 let diags = self.diagnostic().take_future_breakage_diagnostics();
286 if diags.is_empty() {
289 self.parse_sess.span_diagnostic.emit_future_breakage_report(diags);
292 pub fn local_stable_crate_id(&self) -> StableCrateId {
293 self.stable_crate_id.get().copied().unwrap()
296 pub fn crate_types(&self) -> &[CrateType] {
297 self.crate_types.get().unwrap().as_slice()
300 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
301 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
304 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
305 self.diagnostic().struct_span_warn(sp, msg)
307 pub fn struct_span_force_warn<S: Into<MultiSpan>>(
311 ) -> DiagnosticBuilder<'_> {
312 self.diagnostic().struct_span_force_warn(sp, msg)
314 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
319 ) -> DiagnosticBuilder<'_> {
320 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
322 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
323 self.diagnostic().struct_warn(msg)
325 pub fn struct_force_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
326 self.diagnostic().struct_force_warn(msg)
328 pub fn struct_span_allow<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
329 self.diagnostic().struct_span_allow(sp, msg)
331 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
332 self.diagnostic().struct_allow(msg)
334 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
335 self.diagnostic().struct_span_err(sp, msg)
337 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
342 ) -> DiagnosticBuilder<'_> {
343 self.diagnostic().struct_span_err_with_code(sp, msg, code)
345 // FIXME: This method should be removed (every error should have an associated error code).
346 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
347 self.diagnostic().struct_err(msg)
349 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
350 self.diagnostic().struct_err_with_code(msg, code)
352 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
353 self.diagnostic().struct_span_fatal(sp, msg)
355 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
360 ) -> DiagnosticBuilder<'_> {
361 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
363 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
364 self.diagnostic().struct_fatal(msg)
367 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
368 self.diagnostic().span_fatal(sp, msg)
370 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
376 self.diagnostic().span_fatal_with_code(sp, msg, code)
378 pub fn fatal(&self, msg: &str) -> ! {
379 self.diagnostic().fatal(msg).raise()
381 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
383 self.span_warn(sp, msg);
385 self.span_err(sp, msg);
388 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
389 self.diagnostic().span_err(sp, msg)
391 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
392 self.diagnostic().span_err_with_code(sp, &msg, code)
394 pub fn err(&self, msg: &str) {
395 self.diagnostic().err(msg)
397 pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) {
398 err.into_diagnostic(self).emit()
401 pub fn err_count(&self) -> usize {
402 self.diagnostic().err_count()
404 pub fn has_errors(&self) -> bool {
405 self.diagnostic().has_errors()
407 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
408 self.diagnostic().has_errors_or_delayed_span_bugs()
410 pub fn abort_if_errors(&self) {
411 self.diagnostic().abort_if_errors();
413 pub fn compile_status(&self) -> Result<(), ErrorReported> {
414 if self.has_errors() {
415 self.diagnostic().emit_stashed_diagnostics();
421 // FIXME(matthewjasper) Remove this method, it should never be needed.
422 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
426 let old_count = self.err_count();
428 if self.err_count() == old_count { Ok(result) } else { Err(ErrorReported) }
430 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
431 self.diagnostic().span_warn(sp, msg)
433 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
434 self.diagnostic().span_warn_with_code(sp, msg, code)
436 pub fn warn(&self, msg: &str) {
437 self.diagnostic().warn(msg)
439 /// Delay a span_bug() call until abort_if_errors()
441 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
442 self.diagnostic().delay_span_bug(sp, msg)
445 /// Used for code paths of expensive computations that should only take place when
446 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
447 /// it's likely a bug.
448 pub fn delay_good_path_bug(&self, msg: &str) {
449 if self.opts.debugging_opts.print_type_sizes
450 || self.opts.debugging_opts.query_dep_graph
451 || self.opts.debugging_opts.dump_mir.is_some()
452 || self.opts.debugging_opts.unpretty.is_some()
453 || self.opts.output_types.contains_key(&OutputType::Mir)
454 || std::env::var_os("RUSTC_LOG").is_some()
459 self.diagnostic().delay_good_path_bug(msg)
462 pub fn note_without_error(&self, msg: &str) {
463 self.diagnostic().note_without_error(msg)
465 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
466 self.diagnostic().span_note_without_error(sp, msg)
468 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
469 self.diagnostic().struct_note_without_error(msg)
473 pub fn diagnostic(&self) -> &rustc_errors::Handler {
474 &self.parse_sess.span_diagnostic
477 pub fn with_disabled_diagnostic<T, F: FnOnce() -> T>(&self, f: F) -> T {
478 self.parse_sess.span_diagnostic.with_disabled_diagnostic(f)
481 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
482 /// deduplicates on lint ID, span (if any), and message for this `Session`
483 fn diag_once<'a, 'b>(
485 diag_builder: &'b mut DiagnosticBuilder<'a>,
486 method: DiagnosticBuilderMethod,
487 msg_id: DiagnosticMessageId,
489 span_maybe: Option<Span>,
491 let id_span_message = (msg_id, span_maybe, message.to_owned());
492 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
495 DiagnosticBuilderMethod::Note => {
496 diag_builder.note(message);
498 DiagnosticBuilderMethod::SpanNote => {
499 let span = span_maybe.expect("`span_note` needs a span");
500 diag_builder.span_note(span, message);
506 pub fn diag_span_note_once<'a, 'b>(
508 diag_builder: &'b mut DiagnosticBuilder<'a>,
509 msg_id: DiagnosticMessageId,
515 DiagnosticBuilderMethod::SpanNote,
522 pub fn diag_note_once<'a, 'b>(
524 diag_builder: &'b mut DiagnosticBuilder<'a>,
525 msg_id: DiagnosticMessageId,
528 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
532 pub fn source_map(&self) -> &SourceMap {
533 self.parse_sess.source_map()
535 pub fn verbose(&self) -> bool {
536 self.opts.debugging_opts.verbose
538 pub fn time_passes(&self) -> bool {
539 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
541 pub fn instrument_mcount(&self) -> bool {
542 self.opts.debugging_opts.instrument_mcount
544 pub fn time_llvm_passes(&self) -> bool {
545 self.opts.debugging_opts.time_llvm_passes
547 pub fn meta_stats(&self) -> bool {
548 self.opts.debugging_opts.meta_stats
550 pub fn asm_comments(&self) -> bool {
551 self.opts.debugging_opts.asm_comments
553 pub fn verify_llvm_ir(&self) -> bool {
554 self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
556 pub fn print_llvm_passes(&self) -> bool {
557 self.opts.debugging_opts.print_llvm_passes
559 pub fn binary_dep_depinfo(&self) -> bool {
560 self.opts.debugging_opts.binary_dep_depinfo
562 pub fn mir_opt_level(&self) -> usize {
566 .unwrap_or_else(|| if self.opts.optimize != config::OptLevel::No { 2 } else { 1 })
569 /// Gets the features enabled for the current compilation session.
570 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
571 /// dependency tracking. Use tcx.features() instead.
573 pub fn features_untracked(&self) -> &rustc_feature::Features {
574 self.features.get().unwrap()
577 pub fn init_features(&self, features: rustc_feature::Features) {
578 match self.features.set(features) {
580 Err(_) => panic!("`features` was initialized twice"),
584 /// Calculates the flavor of LTO to use for this compilation.
585 pub fn lto(&self) -> config::Lto {
586 // If our target has codegen requirements ignore the command line
587 if self.target.requires_lto {
588 return config::Lto::Fat;
591 // If the user specified something, return that. If they only said `-C
592 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
593 // then ensure we can't use a ThinLTO.
594 match self.opts.cg.lto {
595 config::LtoCli::Unspecified => {
596 // The compiler was invoked without the `-Clto` flag. Fall
597 // through to the default handling
599 config::LtoCli::No => {
600 // The user explicitly opted out of any kind of LTO
601 return config::Lto::No;
603 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
604 // All of these mean fat LTO
605 return config::Lto::Fat;
607 config::LtoCli::Thin => {
608 return if self.opts.cli_forced_thinlto_off {
616 // Ok at this point the target doesn't require anything and the user
617 // hasn't asked for anything. Our next decision is whether or not
618 // we enable "auto" ThinLTO where we use multiple codegen units and
619 // then do ThinLTO over those codegen units. The logic below will
620 // either return `No` or `ThinLocal`.
622 // If processing command line options determined that we're incompatible
623 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
624 if self.opts.cli_forced_thinlto_off {
625 return config::Lto::No;
628 // If `-Z thinlto` specified process that, but note that this is mostly
629 // a deprecated option now that `-C lto=thin` exists.
630 if let Some(enabled) = self.opts.debugging_opts.thinlto {
632 return config::Lto::ThinLocal;
634 return config::Lto::No;
638 // If there's only one codegen unit and LTO isn't enabled then there's
639 // no need for ThinLTO so just return false.
640 if self.codegen_units() == 1 {
641 return config::Lto::No;
644 // Now we're in "defaults" territory. By default we enable ThinLTO for
645 // optimized compiles (anything greater than O0).
646 match self.opts.optimize {
647 config::OptLevel::No => config::Lto::No,
648 _ => config::Lto::ThinLocal,
652 /// Returns the panic strategy for this compile session. If the user explicitly selected one
653 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
654 pub fn panic_strategy(&self) -> PanicStrategy {
655 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
657 pub fn fewer_names(&self) -> bool {
658 if let Some(fewer_names) = self.opts.debugging_opts.fewer_names {
661 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
662 || self.opts.output_types.contains_key(&OutputType::Bitcode)
663 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
664 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
669 pub fn unstable_options(&self) -> bool {
670 self.opts.debugging_opts.unstable_options
672 pub fn is_nightly_build(&self) -> bool {
673 self.opts.unstable_features.is_nightly_build()
675 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
676 self.opts.debugging_opts.sanitizer.contains(SanitizerSet::CFI)
678 pub fn overflow_checks(&self) -> bool {
682 .or(self.opts.debugging_opts.force_overflow_checks)
683 .unwrap_or(self.opts.debug_assertions)
686 /// Check whether this compile session and crate type use static crt.
687 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
688 if !self.target.crt_static_respected {
689 // If the target does not opt in to crt-static support, use its default.
690 return self.target.crt_static_default;
693 let requested_features = self.opts.cg.target_feature.split(',');
694 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
695 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
697 if found_positive || found_negative {
699 } else if crate_type == Some(CrateType::ProcMacro)
700 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
702 // FIXME: When crate_type is not available,
703 // we use compiler options to determine the crate_type.
704 // We can't check `#![crate_type = "proc-macro"]` here.
707 self.target.crt_static_default
711 pub fn relocation_model(&self) -> RelocModel {
712 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
715 pub fn code_model(&self) -> Option<CodeModel> {
716 self.opts.cg.code_model.or(self.target.code_model)
719 pub fn tls_model(&self) -> TlsModel {
720 self.opts.debugging_opts.tls_model.unwrap_or(self.target.tls_model)
723 pub fn is_wasi_reactor(&self) -> bool {
724 self.target.options.os == "wasi"
726 self.opts.debugging_opts.wasi_exec_model,
727 Some(config::WasiExecModel::Reactor)
731 pub fn split_debuginfo(&self) -> SplitDebuginfo {
732 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
735 pub fn target_can_use_split_dwarf(&self) -> bool {
736 !self.target.is_like_windows && !self.target.is_like_osx
739 pub fn must_emit_unwind_tables(&self) -> bool {
740 // This is used to control the emission of the `uwtable` attribute on
743 // Unwind tables are needed when compiling with `-C panic=unwind`, but
744 // LLVM won't omit unwind tables unless the function is also marked as
745 // `nounwind`, so users are allowed to disable `uwtable` emission.
746 // Historically rustc always emits `uwtable` attributes by default, so
747 // even they can be disabled, they're still emitted by default.
749 // On some targets (including windows), however, exceptions include
750 // other events such as illegal instructions, segfaults, etc. This means
751 // that on Windows we end up still needing unwind tables even if the `-C
752 // panic=abort` flag is passed.
754 // You can also find more info on why Windows needs unwind tables in:
755 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
757 // If a target requires unwind tables, then they must be emitted.
758 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
759 // value, if it is provided, or disable them, if not.
760 self.target.requires_uwtable
761 || self.opts.cg.force_unwind_tables.unwrap_or(
762 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
766 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
767 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.to_u64())
770 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
771 filesearch::FileSearch::new(
773 self.opts.target_triple.triple(),
774 &self.opts.search_paths,
775 &self.target_tlib_path,
779 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
780 filesearch::FileSearch::new(
782 config::host_triple(),
783 &self.opts.search_paths,
784 &self.host_tlib_path,
789 /// Returns a list of directories where target-specific tool binaries are located.
790 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
791 let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple());
792 let p = std::array::IntoIter::new([
793 Path::new(&self.sysroot),
794 Path::new(&rustlib_path),
797 .collect::<PathBuf>();
798 if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
801 pub fn init_incr_comp_session(
803 session_dir: PathBuf,
804 lock_file: flock::Lock,
805 load_dep_graph: bool,
807 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
809 if let IncrCompSession::NotInitialized = *incr_comp_session {
811 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
815 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
818 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
819 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
821 if let IncrCompSession::Active { .. } = *incr_comp_session {
823 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
826 // Note: this will also drop the lock file, thus unlocking the directory.
827 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
830 pub fn mark_incr_comp_session_as_invalid(&self) {
831 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
833 let session_directory = match *incr_comp_session {
834 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
835 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
836 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
839 // Note: this will also drop the lock file, thus unlocking the directory.
840 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
843 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
844 let incr_comp_session = self.incr_comp_session.borrow();
845 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
846 IncrCompSession::NotInitialized => panic!(
847 "trying to get session directory from `IncrCompSession`: {:?}",
850 IncrCompSession::Active { ref session_directory, .. }
851 | IncrCompSession::Finalized { ref session_directory }
852 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
858 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
859 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
862 pub fn print_perf_stats(&self) {
864 "Total time spent computing symbol hashes: {}",
865 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
868 "Total queries canonicalized: {}",
869 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
872 "normalize_generic_arg_after_erasing_regions: {}",
873 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
876 "normalize_projection_ty: {}",
877 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
881 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
882 /// This expends fuel if applicable, and records fuel if applicable.
883 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
885 if let Some((ref c, _)) = self.opts.debugging_opts.fuel {
887 assert_eq!(self.threads(), 1);
888 let mut fuel = self.optimization_fuel.lock();
889 ret = fuel.remaining != 0;
890 if fuel.remaining == 0 && !fuel.out_of_fuel {
891 if self.diagnostic().can_emit_warnings() {
892 // We only call `msg` in case we can actually emit warnings.
893 // Otherwise, this could cause a `delay_good_path_bug` to
894 // trigger (issue #79546).
895 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
897 fuel.out_of_fuel = true;
898 } else if fuel.remaining > 0 {
903 if let Some(ref c) = self.opts.debugging_opts.print_fuel {
905 assert_eq!(self.threads(), 1);
906 self.print_fuel.fetch_add(1, SeqCst);
912 /// Returns the number of query threads that should be used for this
914 pub fn threads(&self) -> usize {
915 self.opts.debugging_opts.threads
918 /// Returns the number of codegen units that should be used for this
920 pub fn codegen_units(&self) -> usize {
921 if let Some(n) = self.opts.cli_forced_codegen_units {
924 if let Some(n) = self.target.default_codegen_units {
928 // If incremental compilation is turned on, we default to a high number
929 // codegen units in order to reduce the "collateral damage" small
931 if self.opts.incremental.is_some() {
935 // Why is 16 codegen units the default all the time?
937 // The main reason for enabling multiple codegen units by default is to
938 // leverage the ability for the codegen backend to do codegen and
939 // optimization in parallel. This allows us, especially for large crates, to
940 // make good use of all available resources on the machine once we've
941 // hit that stage of compilation. Large crates especially then often
942 // take a long time in codegen/optimization and this helps us amortize that
945 // Note that a high number here doesn't mean that we'll be spawning a
946 // large number of threads in parallel. The backend of rustc contains
947 // global rate limiting through the `jobserver` crate so we'll never
948 // overload the system with too much work, but rather we'll only be
949 // optimizing when we're otherwise cooperating with other instances of
952 // Rather a high number here means that we should be able to keep a lot
953 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
954 // to build we'll be guaranteed that all cpus will finish pretty closely
955 // to one another and we should make relatively optimal use of system
958 // Note that the main cost of codegen units is that it prevents LLVM
959 // from inlining across codegen units. Users in general don't have a lot
960 // of control over how codegen units are split up so it's our job in the
961 // compiler to ensure that undue performance isn't lost when using
962 // codegen units (aka we can't require everyone to slap `#[inline]` on
965 // If we're compiling at `-O0` then the number doesn't really matter too
966 // much because performance doesn't matter and inlining is ok to lose.
967 // In debug mode we just want to try to guarantee that no cpu is stuck
968 // doing work that could otherwise be farmed to others.
970 // In release mode, however (O1 and above) performance does indeed
971 // matter! To recover the loss in performance due to inlining we'll be
972 // enabling ThinLTO by default (the function for which is just below).
973 // This will ensure that we recover any inlining wins we otherwise lost
974 // through codegen unit partitioning.
978 // Ok that's a lot of words but the basic tl;dr; is that we want a high
979 // number here -- but not too high. Additionally we're "safe" to have it
980 // always at the same number at all optimization levels.
982 // As a result 16 was chosen here! Mostly because it was a power of 2
983 // and most benchmarks agreed it was roughly a local optimum. Not very
988 pub fn teach(&self, code: &DiagnosticId) -> bool {
989 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
992 pub fn rust_2015(&self) -> bool {
993 self.opts.edition == Edition::Edition2015
996 /// Are we allowed to use features from the Rust 2018 edition?
997 pub fn rust_2018(&self) -> bool {
998 self.opts.edition >= Edition::Edition2018
1001 /// Are we allowed to use features from the Rust 2021 edition?
1002 pub fn rust_2021(&self) -> bool {
1003 self.opts.edition >= Edition::Edition2021
1006 pub fn edition(&self) -> Edition {
1010 /// Returns `true` if we cannot skip the PLT for shared library calls.
1011 pub fn needs_plt(&self) -> bool {
1012 // Check if the current target usually needs PLT to be enabled.
1013 // The user can use the command line flag to override it.
1014 let needs_plt = self.target.needs_plt;
1016 let dbg_opts = &self.opts.debugging_opts;
1018 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
1020 // Only enable this optimization by default if full relro is also enabled.
1021 // In this case, lazy binding was already unavailable, so nothing is lost.
1022 // This also ensures `-Wl,-z,now` is supported by the linker.
1023 let full_relro = RelroLevel::Full == relro_level;
1025 // If user didn't explicitly forced us to use / skip the PLT,
1026 // then try to skip it where possible.
1027 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1030 /// Checks if LLVM lifetime markers should be emitted.
1031 pub fn emit_lifetime_markers(&self) -> bool {
1032 self.opts.optimize != config::OptLevel::No
1033 // AddressSanitizer uses lifetimes to detect use after scope bugs.
1034 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1035 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
1036 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
1039 pub fn link_dead_code(&self) -> bool {
1040 self.opts.cg.link_dead_code.unwrap_or(false)
1043 pub fn instrument_coverage(&self) -> bool {
1044 self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1045 != config::InstrumentCoverage::Off
1048 pub fn instrument_coverage_except_unused_generics(&self) -> bool {
1049 self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1050 == config::InstrumentCoverage::ExceptUnusedGenerics
1053 pub fn instrument_coverage_except_unused_functions(&self) -> bool {
1054 self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1055 == config::InstrumentCoverage::ExceptUnusedFunctions
1058 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1059 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1061 .any(|kind| attr.has_name(*kind))
1064 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1065 attrs.iter().any(|item| item.has_name(name))
1068 pub fn find_by_name<'a>(
1070 attrs: &'a [Attribute],
1072 ) -> Option<&'a Attribute> {
1073 attrs.iter().find(|attr| attr.has_name(name))
1076 pub fn filter_by_name<'a>(
1078 attrs: &'a [Attribute],
1080 ) -> impl Iterator<Item = &'a Attribute> {
1081 attrs.iter().filter(move |attr| attr.has_name(name))
1084 pub fn first_attr_value_str_by_name(
1086 attrs: &[Attribute],
1088 ) -> Option<Symbol> {
1089 attrs.iter().find(|at| at.has_name(name)).and_then(|at| at.value_str())
1094 sopts: &config::Options,
1095 registry: rustc_errors::registry::Registry,
1096 source_map: Lrc<SourceMap>,
1097 emitter_dest: Option<Box<dyn Write + Send>>,
1098 ) -> Box<dyn Emitter + sync::Send> {
1099 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1100 match (sopts.error_format, emitter_dest) {
1101 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1102 let (short, color_config) = kind.unzip();
1104 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1106 AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1107 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1109 let emitter = match dst {
1110 None => EmitterWriter::stderr(
1114 sopts.debugging_opts.teach,
1115 sopts.debugging_opts.terminal_width,
1118 Some(dst) => EmitterWriter::new(
1122 false, // no teach messages when writing to a buffer
1123 false, // no colors when writing to a buffer
1124 None, // no terminal width
1128 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1131 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1132 JsonEmitter::stderr(
1137 sopts.debugging_opts.terminal_width,
1140 .ui_testing(sopts.debugging_opts.ui_testing),
1142 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1149 sopts.debugging_opts.terminal_width,
1152 .ui_testing(sopts.debugging_opts.ui_testing),
1157 pub enum DiagnosticOutput {
1159 Raw(Box<dyn Write + Send>),
1162 pub fn build_session(
1163 sopts: config::Options,
1164 local_crate_source_file: Option<PathBuf>,
1165 registry: rustc_errors::registry::Registry,
1166 diagnostics_output: DiagnosticOutput,
1167 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1168 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1169 target_override: Option<Target>,
1171 // FIXME: This is not general enough to make the warning lint completely override
1172 // normal diagnostic warnings, since the warning lint can also be denied and changed
1173 // later via the source code.
1174 let warnings_allow = sopts
1177 .filter(|&&(ref key, _)| *key == "warnings")
1178 .map(|&(_, ref level)| *level == lint::Allow)
1181 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1182 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1184 let write_dest = match diagnostics_output {
1185 DiagnosticOutput::Default => None,
1186 DiagnosticOutput::Raw(write) => Some(write),
1189 let sysroot = match &sopts.maybe_sysroot {
1190 Some(sysroot) => sysroot.clone(),
1191 None => filesearch::get_or_default_sysroot(),
1194 let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
1195 let host_triple = TargetTriple::from_triple(config::host_triple());
1196 let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1197 early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1199 for warning in target_warnings.warning_messages() {
1200 early_warn(sopts.error_format, &warning)
1203 let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1204 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1205 if target_cfg.is_like_msvc {
1206 SourceFileHashAlgorithm::Sha1
1208 SourceFileHashAlgorithm::Md5
1211 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1213 sopts.file_path_mapping(),
1216 let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1218 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1220 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1223 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1226 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1228 let profiler = SelfProfiler::new(
1230 sopts.crate_name.as_deref(),
1231 &sopts.debugging_opts.self_profile_events,
1234 Ok(profiler) => Some(Arc::new(profiler)),
1236 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1244 let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1245 parse_sess.assume_incomplete_release = sopts.debugging_opts.assume_incomplete_release;
1247 let host_triple = config::host_triple();
1248 let target_triple = sopts.target_triple.triple();
1249 let host_tlib_path = Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1250 let target_tlib_path = if host_triple == target_triple {
1251 // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1252 // rescanning of the target lib path and an unnecessary allocation.
1253 host_tlib_path.clone()
1255 Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1258 let file_path_mapping = sopts.file_path_mapping();
1260 let local_crate_source_file =
1261 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1263 let optimization_fuel = Lock::new(OptimizationFuel {
1264 remaining: sopts.debugging_opts.fuel.as_ref().map_or(0, |i| i.1),
1267 let print_fuel = AtomicU64::new(0);
1269 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1270 CguReuseTracker::new()
1272 CguReuseTracker::new_disabled()
1275 let prof = SelfProfilerRef::new(
1277 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1278 sopts.debugging_opts.time_passes,
1281 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1282 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1283 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1284 _ => CtfeBacktrace::Disabled,
1288 if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1290 let sess = Session {
1298 local_crate_source_file,
1299 one_time_diagnostics: Default::default(),
1300 crate_types: OnceCell::new(),
1301 stable_crate_id: OnceCell::new(),
1302 features: OnceCell::new(),
1303 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1306 perf_stats: PerfStats {
1307 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1308 queries_canonicalized: AtomicUsize::new(0),
1309 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1310 normalize_projection_ty: AtomicUsize::new(0),
1312 code_stats: Default::default(),
1315 jobserver: jobserver::client(),
1318 miri_unleashed_features: Lock::new(Default::default()),
1320 target_features: FxHashSet::default(),
1323 validate_commandline_args_with_session_available(&sess);
1328 // If it is useful to have a Session available already for validating a
1329 // commandline argument, you can do so here.
1330 fn validate_commandline_args_with_session_available(sess: &Session) {
1331 // Since we don't know if code in an rlib will be linked to statically or
1332 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1333 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1334 // these manually generated symbols confuse LLD when it tries to merge
1335 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1336 // when compiling for LLD ThinLTO. This way we can validly just not generate
1337 // the `dllimport` attributes and `__imp_` symbols in that case.
1338 if sess.opts.cg.linker_plugin_lto.enabled()
1339 && sess.opts.cg.prefer_dynamic
1340 && sess.target.is_like_windows
1343 "Linker plugin based LTO is not supported together with \
1344 `-C prefer-dynamic` when targeting Windows-like targets",
1348 // Make sure that any given profiling data actually exists so LLVM can't
1349 // decide to silently skip PGO.
1350 if let Some(ref path) = sess.opts.cg.profile_use {
1353 "File `{}` passed to `-C profile-use` does not exist.",
1359 // Do the same for sample profile data.
1360 if let Some(ref path) = sess.opts.debugging_opts.profile_sample_use {
1363 "File `{}` passed to `-C profile-sample-use` does not exist.",
1369 // Unwind tables cannot be disabled if the target requires them.
1370 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1371 if sess.target.requires_uwtable && !include_uwtables {
1373 "target requires unwind tables, they cannot be disabled with \
1374 `-C force-unwind-tables=no`.",
1379 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1380 let supported_sanitizers = sess.target.options.supported_sanitizers;
1381 let unsupported_sanitizers = sess.opts.debugging_opts.sanitizer - supported_sanitizers;
1382 match unsupported_sanitizers.into_iter().count() {
1385 .err(&format!("{} sanitizer is not supported for this target", unsupported_sanitizers)),
1386 _ => sess.err(&format!(
1387 "{} sanitizers are not supported for this target",
1388 unsupported_sanitizers
1391 // Cannot mix and match sanitizers.
1392 let mut sanitizer_iter = sess.opts.debugging_opts.sanitizer.into_iter();
1393 if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1394 sess.err(&format!("`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`", first, second));
1397 // Cannot enable crt-static with sanitizers on Linux
1398 if sess.crt_static(None) && !sess.opts.debugging_opts.sanitizer.is_empty() {
1400 "sanitizer is incompatible with statically linked libc, \
1401 disable it using `-C target-feature=-crt-static`",
1405 // LLVM CFI requires LTO.
1406 if sess.is_sanitizer_cfi_enabled() {
1407 if sess.opts.cg.lto == config::LtoCli::Unspecified
1408 || sess.opts.cg.lto == config::LtoCli::No
1409 || sess.opts.cg.lto == config::LtoCli::Thin
1411 sess.err("`-Zsanitizer=cfi` requires `-Clto`");
1416 /// Holds data on the current incremental compilation session, if there is one.
1418 pub enum IncrCompSession {
1419 /// This is the state the session will be in until the incr. comp. dir is
1422 /// This is the state during which the session directory is private and can
1424 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1425 /// This is the state after the session directory has been finalized. In this
1426 /// state, the contents of the directory must not be modified any more.
1427 Finalized { session_directory: PathBuf },
1428 /// This is an error state that is reached when some compilation error has
1429 /// occurred. It indicates that the contents of the session directory must
1430 /// not be used, since they might be invalid.
1431 InvalidBecauseOfErrors { session_directory: PathBuf },
1434 pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) {
1435 let emitter: Box<dyn Emitter + sync::Send> = match output {
1436 config::ErrorOutputType::HumanReadable(kind) => {
1437 let (short, color_config) = kind.unzip();
1438 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1440 config::ErrorOutputType::Json { pretty, json_rendered } => {
1441 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1444 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1445 handler.struct_fatal(msg).emit();
1448 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1449 early_error_no_abort(output, msg);
1450 rustc_errors::FatalError.raise();
1453 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1454 let emitter: Box<dyn Emitter + sync::Send> = match output {
1455 config::ErrorOutputType::HumanReadable(kind) => {
1456 let (short, color_config) = kind.unzip();
1457 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1459 config::ErrorOutputType::Json { pretty, json_rendered } => {
1460 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1463 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1464 handler.struct_warn(msg).emit();