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, OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
10 pub use rustc_ast::crate_disambiguator::CrateDisambiguator;
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, Once, 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::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported};
22 use rustc_span::edition::Edition;
23 use rustc_span::source_map::{self, FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
24 use rustc_span::SourceFileHashAlgorithm;
25 use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
27 use std::cell::{self, RefCell};
30 use std::num::NonZeroU32;
31 use std::path::PathBuf;
33 use std::time::Duration;
35 pub struct OptimizationFuel {
36 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
38 /// We're rejecting all further optimizations.
42 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
43 #[derive(Clone, Copy)]
44 pub enum CtfeBacktrace {
45 /// Do nothing special, return the error as usual without a backtrace.
47 /// Capture a backtrace at the point the error is created and return it in the error
48 /// (to be printed later if/when the error ever actually gets shown to the user).
50 /// Capture a backtrace at the point the error is created and immediately print it out.
54 /// Represents the data associated with a compilation
55 /// session for a single crate.
57 pub target: config::Config,
59 pub opts: config::Options,
60 pub host_tlib_path: SearchPath,
61 /// `None` if the host and target are the same.
62 pub target_tlib_path: Option<SearchPath>,
63 pub parse_sess: ParseSess,
65 /// The name of the root source file of the crate, in the local file system.
66 /// `None` means that there is no source file.
67 pub local_crate_source_file: Option<PathBuf>,
68 /// The directory the compiler has been executed in plus a flag indicating
69 /// if the value stored here has been affected by path remapping.
70 pub working_dir: (PathBuf, bool),
72 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
73 /// (sub)diagnostics that have been set once, but should not be set again,
74 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
75 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
76 pub crate_types: Once<Vec<config::CrateType>>,
77 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
78 /// arguments passed to the compiler. Its value together with the crate-name
79 /// forms a unique global identifier for the crate. It is used to allow
80 /// multiple crates with the same name to coexist. See the
81 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
82 pub crate_disambiguator: Once<CrateDisambiguator>,
84 features: Once<rustc_feature::Features>,
86 /// The maximum recursion limit for potentially infinitely recursive
87 /// operations such as auto-dereference and monomorphization.
88 pub recursion_limit: Once<usize>,
90 /// The maximum length of types during monomorphization.
91 pub type_length_limit: Once<usize>,
93 /// The maximum blocks a const expression can evaluate.
94 pub const_eval_limit: Once<usize>,
96 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
97 /// Used for incremental compilation tests. Will only be populated if
98 /// `-Zquery-dep-graph` is specified.
99 pub cgu_reuse_tracker: CguReuseTracker,
101 /// Used by `-Z self-profile`.
102 pub prof: SelfProfilerRef,
104 /// Some measurements that are being gathered during compilation.
105 pub perf_stats: PerfStats,
107 /// Data about code being compiled, gathered during compilation.
108 pub code_stats: CodeStats,
110 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
111 optimization_fuel_crate: Option<String>,
113 /// Tracks fuel info if `-zfuel=crate=n` is specified.
114 optimization_fuel: Lock<OptimizationFuel>,
116 // The next two are public because the driver needs to read them.
117 /// If `-zprint-fuel=crate`, `Some(crate)`.
118 pub print_fuel_crate: Option<String>,
119 /// Always set to zero and incremented so that we can print fuel expended by a crate.
120 pub print_fuel: AtomicU64,
122 /// Loaded up early on in the initialization of this `Session` to avoid
123 /// false positives about a job server in our environment.
124 pub jobserver: Client,
126 /// Cap lint level specified by a driver specifically.
127 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
129 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
130 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
132 /// Mapping from ident span to path span for paths that don't exist as written, but that
133 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
134 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
136 /// Path for libraries that will take preference over libraries shipped by Rust.
137 /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
138 pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
140 /// Tracks the current behavior of the CTFE engine when an error occurs.
141 /// Options range from returning the error without a backtrace to returning an error
142 /// and immediately printing the backtrace to stderr.
143 pub ctfe_backtrace: Lock<CtfeBacktrace>,
145 /// Base directory containing the `src/` for the Rust standard library, and
146 /// potentially `rustc` as well, if we can can find it. Right now it's always
147 /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
149 /// This directory is what the virtual `/rustc/$hash` is translated back to,
150 /// if Rust was built with path remapping to `/rustc/$hash` enabled
151 /// (the `rust.remap-debuginfo` option in `config.toml`).
152 pub real_rust_source_base_dir: Option<PathBuf>,
155 pub struct PerfStats {
156 /// The accumulated time spent on computing symbol hashes.
157 pub symbol_hash_time: Lock<Duration>,
158 /// The accumulated time spent decoding def path tables from metadata.
159 pub decode_def_path_tables_time: Lock<Duration>,
160 /// Total number of values canonicalized queries constructed.
161 pub queries_canonicalized: AtomicUsize,
162 /// Number of times this query is invoked.
163 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
164 /// Number of times this query is invoked.
165 pub normalize_projection_ty: AtomicUsize,
168 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
169 enum DiagnosticBuilderMethod {
172 SpanSuggestion(String), // suggestion
173 // Add more variants as needed to support one-time diagnostics.
176 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
177 /// emitting the same message more than once.
178 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
179 pub enum DiagnosticMessageId {
180 ErrorId(u16), // EXXXX error code as integer
181 LintId(lint::LintId),
182 StabilityId(Option<NonZeroU32>), // issue number
185 impl From<&'static lint::Lint> for DiagnosticMessageId {
186 fn from(lint: &'static lint::Lint) -> Self {
187 DiagnosticMessageId::LintId(lint::LintId::of(lint))
192 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
193 *self.crate_disambiguator.get()
196 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
197 self.diagnostic().struct_span_warn(sp, msg)
199 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
204 ) -> DiagnosticBuilder<'_> {
205 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
207 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
208 self.diagnostic().struct_warn(msg)
210 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
211 self.diagnostic().struct_span_err(sp, msg)
213 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
218 ) -> DiagnosticBuilder<'_> {
219 self.diagnostic().struct_span_err_with_code(sp, msg, code)
221 // FIXME: This method should be removed (every error should have an associated error code).
222 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
223 self.diagnostic().struct_err(msg)
225 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
226 self.diagnostic().struct_err_with_code(msg, code)
228 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
229 self.diagnostic().struct_span_fatal(sp, msg)
231 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
236 ) -> DiagnosticBuilder<'_> {
237 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
239 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
240 self.diagnostic().struct_fatal(msg)
243 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
244 self.diagnostic().span_fatal(sp, msg).raise()
246 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
252 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
254 pub fn fatal(&self, msg: &str) -> ! {
255 self.diagnostic().fatal(msg).raise()
257 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
259 self.span_warn(sp, msg);
261 self.span_err(sp, msg);
264 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
265 self.diagnostic().span_err(sp, msg)
267 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
268 self.diagnostic().span_err_with_code(sp, &msg, code)
270 pub fn err(&self, msg: &str) {
271 self.diagnostic().err(msg)
273 pub fn err_count(&self) -> usize {
274 self.diagnostic().err_count()
276 pub fn has_errors(&self) -> bool {
277 self.diagnostic().has_errors()
279 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
280 self.diagnostic().has_errors_or_delayed_span_bugs()
282 pub fn abort_if_errors(&self) {
283 self.diagnostic().abort_if_errors();
285 pub fn compile_status(&self) -> Result<(), ErrorReported> {
286 if self.has_errors() {
287 self.diagnostic().emit_stashed_diagnostics();
293 // FIXME(matthewjasper) Remove this method, it should never be needed.
294 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
298 let old_count = self.err_count();
300 let errors = self.err_count() - old_count;
301 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
303 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
304 self.diagnostic().span_warn(sp, msg)
306 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
307 self.diagnostic().span_warn_with_code(sp, msg, code)
309 pub fn warn(&self, msg: &str) {
310 self.diagnostic().warn(msg)
312 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
314 Some(sp) => self.span_warn(sp, msg),
315 None => self.warn(msg),
318 /// Delay a span_bug() call until abort_if_errors()
319 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
320 self.diagnostic().delay_span_bug(sp, msg)
322 pub fn note_without_error(&self, msg: &str) {
323 self.diagnostic().note_without_error(msg)
325 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
326 self.diagnostic().span_note_without_error(sp, msg)
329 pub fn diagnostic(&self) -> &rustc_errors::Handler {
330 &self.parse_sess.span_diagnostic
333 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
334 /// deduplicates on lint ID, span (if any), and message for this `Session`
335 fn diag_once<'a, 'b>(
337 diag_builder: &'b mut DiagnosticBuilder<'a>,
338 method: DiagnosticBuilderMethod,
339 msg_id: DiagnosticMessageId,
341 span_maybe: Option<Span>,
343 let id_span_message = (msg_id, span_maybe, message.to_owned());
344 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
347 DiagnosticBuilderMethod::Note => {
348 diag_builder.note(message);
350 DiagnosticBuilderMethod::SpanNote => {
351 let span = span_maybe.expect("`span_note` needs a span");
352 diag_builder.span_note(span, message);
354 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
355 let span = span_maybe.expect("`span_suggestion_*` needs a span");
356 diag_builder.span_suggestion(
360 Applicability::Unspecified,
367 pub fn diag_span_note_once<'a, 'b>(
369 diag_builder: &'b mut DiagnosticBuilder<'a>,
370 msg_id: DiagnosticMessageId,
376 DiagnosticBuilderMethod::SpanNote,
383 pub fn diag_note_once<'a, 'b>(
385 diag_builder: &'b mut DiagnosticBuilder<'a>,
386 msg_id: DiagnosticMessageId,
389 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
392 pub fn diag_span_suggestion_once<'a, 'b>(
394 diag_builder: &'b mut DiagnosticBuilder<'a>,
395 msg_id: DiagnosticMessageId,
402 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
410 pub fn source_map(&self) -> &source_map::SourceMap {
411 self.parse_sess.source_map()
413 pub fn verbose(&self) -> bool {
414 self.opts.debugging_opts.verbose
416 pub fn time_passes(&self) -> bool {
417 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
419 pub fn instrument_mcount(&self) -> bool {
420 self.opts.debugging_opts.instrument_mcount
422 pub fn time_llvm_passes(&self) -> bool {
423 self.opts.debugging_opts.time_llvm_passes
425 pub fn meta_stats(&self) -> bool {
426 self.opts.debugging_opts.meta_stats
428 pub fn asm_comments(&self) -> bool {
429 self.opts.debugging_opts.asm_comments
431 pub fn verify_llvm_ir(&self) -> bool {
432 self.opts.debugging_opts.verify_llvm_ir || cfg!(always_verify_llvm_ir)
434 pub fn borrowck_stats(&self) -> bool {
435 self.opts.debugging_opts.borrowck_stats
437 pub fn print_llvm_passes(&self) -> bool {
438 self.opts.debugging_opts.print_llvm_passes
440 pub fn binary_dep_depinfo(&self) -> bool {
441 self.opts.debugging_opts.binary_dep_depinfo
444 /// Gets the features enabled for the current compilation session.
445 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
446 /// dependency tracking. Use tcx.features() instead.
448 pub fn features_untracked(&self) -> &rustc_feature::Features {
452 pub fn init_features(&self, features: rustc_feature::Features) {
453 self.features.set(features);
456 /// Calculates the flavor of LTO to use for this compilation.
457 pub fn lto(&self) -> config::Lto {
458 // If our target has codegen requirements ignore the command line
459 if self.target.target.options.requires_lto {
460 return config::Lto::Fat;
463 // If the user specified something, return that. If they only said `-C
464 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
465 // then ensure we can't use a ThinLTO.
466 match self.opts.cg.lto {
467 config::LtoCli::Unspecified => {
468 // The compiler was invoked without the `-Clto` flag. Fall
469 // through to the default handling
471 config::LtoCli::No => {
472 // The user explicitly opted out of any kind of LTO
473 return config::Lto::No;
475 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
476 // All of these mean fat LTO
477 return config::Lto::Fat;
479 config::LtoCli::Thin => {
480 return if self.opts.cli_forced_thinlto_off {
488 // Ok at this point the target doesn't require anything and the user
489 // hasn't asked for anything. Our next decision is whether or not
490 // we enable "auto" ThinLTO where we use multiple codegen units and
491 // then do ThinLTO over those codegen units. The logic below will
492 // either return `No` or `ThinLocal`.
494 // If processing command line options determined that we're incompatible
495 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
496 if self.opts.cli_forced_thinlto_off {
497 return config::Lto::No;
500 // If `-Z thinlto` specified process that, but note that this is mostly
501 // a deprecated option now that `-C lto=thin` exists.
502 if let Some(enabled) = self.opts.debugging_opts.thinlto {
504 return config::Lto::ThinLocal;
506 return config::Lto::No;
510 // If there's only one codegen unit and LTO isn't enabled then there's
511 // no need for ThinLTO so just return false.
512 if self.codegen_units() == 1 {
513 return config::Lto::No;
516 // Now we're in "defaults" territory. By default we enable ThinLTO for
517 // optimized compiles (anything greater than O0).
518 match self.opts.optimize {
519 config::OptLevel::No => config::Lto::No,
520 _ => config::Lto::ThinLocal,
524 /// Returns the panic strategy for this compile session. If the user explicitly selected one
525 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
526 pub fn panic_strategy(&self) -> PanicStrategy {
527 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
529 pub fn fewer_names(&self) -> bool {
530 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
531 || self.opts.output_types.contains_key(&OutputType::Bitcode);
533 // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
534 let more_names = match self.opts.debugging_opts.sanitizer {
535 Some(Sanitizer::Address) => true,
536 Some(Sanitizer::Memory) => true,
540 self.opts.debugging_opts.fewer_names || !more_names
543 pub fn no_landing_pads(&self) -> bool {
544 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
546 pub fn unstable_options(&self) -> bool {
547 self.opts.debugging_opts.unstable_options
549 pub fn overflow_checks(&self) -> bool {
553 .or(self.opts.debugging_opts.force_overflow_checks)
554 .unwrap_or(self.opts.debug_assertions)
557 /// Check whether this compile session and crate type use static crt.
558 pub fn crt_static(&self, crate_type: Option<config::CrateType>) -> bool {
559 // If the target does not opt in to crt-static support, use its default.
560 if self.target.target.options.crt_static_respected {
561 self.crt_static_feature(crate_type)
563 self.target.target.options.crt_static_default
567 /// Check whether this compile session and crate type use `crt-static` feature.
568 pub fn crt_static_feature(&self, crate_type: Option<config::CrateType>) -> bool {
569 let requested_features = self.opts.cg.target_feature.split(',');
570 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
571 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
573 if found_positive || found_negative {
575 } else if crate_type == Some(config::CrateType::ProcMacro)
576 || crate_type == None && self.opts.crate_types.contains(&config::CrateType::ProcMacro)
578 // FIXME: When crate_type is not available,
579 // we use compiler options to determine the crate_type.
580 // We can't check `#![crate_type = "proc-macro"]` here.
583 self.target.target.options.crt_static_default
587 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
588 // "mcount" function relies on stack pointer.
589 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
590 if self.instrument_mcount() {
592 } else if let Some(x) = self.opts.cg.force_frame_pointers {
595 !self.target.target.options.eliminate_frame_pointer
599 /// Returns the symbol name for the registrar function,
600 /// given the crate `Svh` and the function `DefIndex`.
601 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
602 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
605 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
606 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
609 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
610 filesearch::FileSearch::new(
612 self.opts.target_triple.triple(),
613 &self.opts.search_paths,
614 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
615 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
619 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
620 filesearch::FileSearch::new(
622 config::host_triple(),
623 &self.opts.search_paths,
624 &self.host_tlib_path,
629 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
630 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
632 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
633 *load_dep_graph = load;
637 pub fn incr_session_load_dep_graph(&self) -> bool {
638 let incr_comp_session = self.incr_comp_session.borrow();
639 match *incr_comp_session {
640 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
645 pub fn init_incr_comp_session(
647 session_dir: PathBuf,
648 lock_file: flock::Lock,
649 load_dep_graph: bool,
651 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
653 if let IncrCompSession::NotInitialized = *incr_comp_session {
655 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
659 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
662 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
663 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
665 if let IncrCompSession::Active { .. } = *incr_comp_session {
667 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
670 // Note: this will also drop the lock file, thus unlocking the directory.
671 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
674 pub fn mark_incr_comp_session_as_invalid(&self) {
675 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
677 let session_directory = match *incr_comp_session {
678 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
679 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
680 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
683 // Note: this will also drop the lock file, thus unlocking the directory.
684 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
687 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
688 let incr_comp_session = self.incr_comp_session.borrow();
689 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
690 IncrCompSession::NotInitialized => panic!(
691 "trying to get session directory from `IncrCompSession`: {:?}",
694 IncrCompSession::Active { ref session_directory, .. }
695 | IncrCompSession::Finalized { ref session_directory }
696 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
702 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
703 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
706 pub fn print_perf_stats(&self) {
708 "Total time spent computing symbol hashes: {}",
709 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
712 "Total time spent decoding DefPath tables: {}",
713 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
716 "Total queries canonicalized: {}",
717 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
720 "normalize_generic_arg_after_erasing_regions: {}",
721 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
724 "normalize_projection_ty: {}",
725 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
729 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
730 /// This expends fuel if applicable, and records fuel if applicable.
731 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
733 if let Some(ref c) = self.optimization_fuel_crate {
735 assert_eq!(self.threads(), 1);
736 let mut fuel = self.optimization_fuel.lock();
737 ret = fuel.remaining != 0;
738 if fuel.remaining == 0 && !fuel.out_of_fuel {
739 eprintln!("optimization-fuel-exhausted: {}", msg());
740 fuel.out_of_fuel = true;
741 } else if fuel.remaining > 0 {
746 if let Some(ref c) = self.print_fuel_crate {
748 assert_eq!(self.threads(), 1);
749 self.print_fuel.fetch_add(1, SeqCst);
755 /// Returns the number of query threads that should be used for this
757 pub fn threads(&self) -> usize {
758 self.opts.debugging_opts.threads
761 /// Returns the number of codegen units that should be used for this
763 pub fn codegen_units(&self) -> usize {
764 if let Some(n) = self.opts.cli_forced_codegen_units {
767 if let Some(n) = self.target.target.options.default_codegen_units {
771 // If incremental compilation is turned on, we default to a high number
772 // codegen units in order to reduce the "collateral damage" small
774 if self.opts.incremental.is_some() {
778 // Why is 16 codegen units the default all the time?
780 // The main reason for enabling multiple codegen units by default is to
781 // leverage the ability for the codegen backend to do codegen and
782 // optimization in parallel. This allows us, especially for large crates, to
783 // make good use of all available resources on the machine once we've
784 // hit that stage of compilation. Large crates especially then often
785 // take a long time in codegen/optimization and this helps us amortize that
788 // Note that a high number here doesn't mean that we'll be spawning a
789 // large number of threads in parallel. The backend of rustc contains
790 // global rate limiting through the `jobserver` crate so we'll never
791 // overload the system with too much work, but rather we'll only be
792 // optimizing when we're otherwise cooperating with other instances of
795 // Rather a high number here means that we should be able to keep a lot
796 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
797 // to build we'll be guaranteed that all cpus will finish pretty closely
798 // to one another and we should make relatively optimal use of system
801 // Note that the main cost of codegen units is that it prevents LLVM
802 // from inlining across codegen units. Users in general don't have a lot
803 // of control over how codegen units are split up so it's our job in the
804 // compiler to ensure that undue performance isn't lost when using
805 // codegen units (aka we can't require everyone to slap `#[inline]` on
808 // If we're compiling at `-O0` then the number doesn't really matter too
809 // much because performance doesn't matter and inlining is ok to lose.
810 // In debug mode we just want to try to guarantee that no cpu is stuck
811 // doing work that could otherwise be farmed to others.
813 // In release mode, however (O1 and above) performance does indeed
814 // matter! To recover the loss in performance due to inlining we'll be
815 // enabling ThinLTO by default (the function for which is just below).
816 // This will ensure that we recover any inlining wins we otherwise lost
817 // through codegen unit partitioning.
821 // Ok that's a lot of words but the basic tl;dr; is that we want a high
822 // number here -- but not too high. Additionally we're "safe" to have it
823 // always at the same number at all optimization levels.
825 // As a result 16 was chosen here! Mostly because it was a power of 2
826 // and most benchmarks agreed it was roughly a local optimum. Not very
831 pub fn teach(&self, code: &DiagnosticId) -> bool {
832 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
835 pub fn rust_2015(&self) -> bool {
836 self.opts.edition == Edition::Edition2015
839 /// Are we allowed to use features from the Rust 2018 edition?
840 pub fn rust_2018(&self) -> bool {
841 self.opts.edition >= Edition::Edition2018
844 pub fn edition(&self) -> Edition {
848 /// Returns `true` if we cannot skip the PLT for shared library calls.
849 pub fn needs_plt(&self) -> bool {
850 // Check if the current target usually needs PLT to be enabled.
851 // The user can use the command line flag to override it.
852 let needs_plt = self.target.target.options.needs_plt;
854 let dbg_opts = &self.opts.debugging_opts;
856 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
858 // Only enable this optimization by default if full relro is also enabled.
859 // In this case, lazy binding was already unavailable, so nothing is lost.
860 // This also ensures `-Wl,-z,now` is supported by the linker.
861 let full_relro = RelroLevel::Full == relro_level;
863 // If user didn't explicitly forced us to use / skip the PLT,
864 // then try to skip it where possible.
865 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
869 pub fn build_session(
870 sopts: config::Options,
871 local_crate_source_file: Option<PathBuf>,
872 registry: rustc_errors::registry::Registry,
874 build_session_with_source_map(
876 local_crate_source_file,
878 DiagnosticOutput::Default,
886 sopts: &config::Options,
887 registry: rustc_errors::registry::Registry,
888 source_map: &Lrc<source_map::SourceMap>,
889 emitter_dest: Option<Box<dyn Write + Send>>,
890 ) -> Box<dyn Emitter + sync::Send> {
891 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
892 match (sopts.error_format, emitter_dest) {
893 (config::ErrorOutputType::HumanReadable(kind), dst) => {
894 let (short, color_config) = kind.unzip();
896 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
897 let emitter = AnnotateSnippetEmitterWriter::new(
898 Some(source_map.clone()),
902 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
904 let emitter = match dst {
905 None => EmitterWriter::stderr(
907 Some(source_map.clone()),
909 sopts.debugging_opts.teach,
910 sopts.debugging_opts.terminal_width,
913 Some(dst) => EmitterWriter::new(
915 Some(source_map.clone()),
917 false, // no teach messages when writing to a buffer
918 false, // no colors when writing to a buffer
919 None, // no terminal width
923 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
926 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
934 .ui_testing(sopts.debugging_opts.ui_testing),
936 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
945 .ui_testing(sopts.debugging_opts.ui_testing),
950 pub enum DiagnosticOutput {
952 Raw(Box<dyn Write + Send>),
955 pub fn build_session_with_source_map(
956 sopts: config::Options,
957 local_crate_source_file: Option<PathBuf>,
958 registry: rustc_errors::registry::Registry,
959 diagnostics_output: DiagnosticOutput,
960 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
961 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
962 ) -> (Session, Lrc<SourceMap>) {
963 // FIXME: This is not general enough to make the warning lint completely override
964 // normal diagnostic warnings, since the warning lint can also be denied and changed
965 // later via the source code.
966 let warnings_allow = sopts
969 .filter(|&&(ref key, _)| *key == "warnings")
970 .map(|&(_, ref level)| *level == lint::Allow)
973 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
974 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
976 let write_dest = match diagnostics_output {
977 DiagnosticOutput::Default => None,
978 DiagnosticOutput::Raw(write) => Some(write),
981 let target_cfg = config::build_target_config(&sopts, sopts.error_format);
982 let host_triple = TargetTriple::from_triple(config::host_triple());
983 let host = Target::search(&host_triple).unwrap_or_else(|e| {
984 early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
987 let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
988 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
989 if target_cfg.target.options.is_like_msvc {
990 SourceFileHashAlgorithm::Sha1
992 SourceFileHashAlgorithm::Md5
995 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
997 sopts.file_path_mapping(),
1000 let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
1002 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1004 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1007 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1010 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1012 let profiler = SelfProfiler::new(
1014 sopts.crate_name.as_ref().map(|s| &s[..]),
1015 &sopts.debugging_opts.self_profile_events,
1018 Ok(profiler) => Some(Arc::new(profiler)),
1020 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1028 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map.clone());
1029 let sysroot = match &sopts.maybe_sysroot {
1030 Some(sysroot) => sysroot.clone(),
1031 None => filesearch::get_or_default_sysroot(),
1034 let host_triple = config::host_triple();
1035 let target_triple = sopts.target_triple.triple();
1036 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1037 let target_tlib_path = if host_triple == target_triple {
1040 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1043 let file_path_mapping = sopts.file_path_mapping();
1045 let local_crate_source_file =
1046 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1048 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1049 let optimization_fuel = Lock::new(OptimizationFuel {
1050 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1053 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1054 let print_fuel = AtomicU64::new(0);
1056 let working_dir = env::current_dir().unwrap_or_else(|e| {
1057 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1059 let working_dir = file_path_mapping.map_prefix(working_dir);
1061 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1062 CguReuseTracker::new()
1064 CguReuseTracker::new_disabled()
1067 let prof = SelfProfilerRef::new(
1069 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1070 sopts.debugging_opts.time_passes,
1073 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1074 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1075 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1076 _ => CtfeBacktrace::Disabled,
1079 // Try to find a directory containing the Rust `src`, for more details see
1080 // the doc comment on the `real_rust_source_base_dir` field.
1081 let real_rust_source_base_dir = {
1082 // This is the location used by the `rust-src` `rustup` component.
1083 let mut candidate = sysroot.join("lib/rustlib/src/rust");
1084 if let Ok(metadata) = candidate.symlink_metadata() {
1085 // Replace the symlink rustbuild creates, with its destination.
1086 // We could try to use `fs::canonicalize` instead, but that might
1087 // produce unnecessarily verbose path.
1088 if metadata.file_type().is_symlink() {
1089 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1090 candidate = symlink_dest;
1095 // Only use this directory if it has a file we can expect to always find.
1096 if candidate.join("src/libstd/lib.rs").is_file() { Some(candidate) } else { None }
1099 let sess = Session {
1107 local_crate_source_file,
1109 one_time_diagnostics: Default::default(),
1110 crate_types: Once::new(),
1111 crate_disambiguator: Once::new(),
1112 features: Once::new(),
1113 recursion_limit: Once::new(),
1114 type_length_limit: Once::new(),
1115 const_eval_limit: Once::new(),
1116 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1119 perf_stats: PerfStats {
1120 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1121 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1122 queries_canonicalized: AtomicUsize::new(0),
1123 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1124 normalize_projection_ty: AtomicUsize::new(0),
1126 code_stats: Default::default(),
1127 optimization_fuel_crate,
1131 jobserver: jobserver::client(),
1133 trait_methods_not_found: Lock::new(Default::default()),
1134 confused_type_with_std_module: Lock::new(Default::default()),
1135 system_library_path: OneThread::new(RefCell::new(Default::default())),
1137 real_rust_source_base_dir,
1140 validate_commandline_args_with_session_available(&sess);
1145 // If it is useful to have a Session available already for validating a
1146 // commandline argument, you can do so here.
1147 fn validate_commandline_args_with_session_available(sess: &Session) {
1148 // Since we don't know if code in an rlib will be linked to statically or
1149 // dynamically downstream, rustc generates `__imp_` symbols that help the
1150 // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1151 // these manually generated symbols confuse LLD when it tries to merge
1152 // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1153 // when compiling for LLD ThinLTO. This way we can validly just not generate
1154 // the `dllimport` attributes and `__imp_` symbols in that case.
1155 if sess.opts.cg.linker_plugin_lto.enabled()
1156 && sess.opts.cg.prefer_dynamic
1157 && sess.target.target.options.is_like_msvc
1160 "Linker plugin based LTO is not supported together with \
1161 `-C prefer-dynamic` when targeting MSVC",
1165 // Make sure that any given profiling data actually exists so LLVM can't
1166 // decide to silently skip PGO.
1167 if let Some(ref path) = sess.opts.cg.profile_use {
1170 "File `{}` passed to `-C profile-use` does not exist.",
1176 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1177 // an error to combine the two for now. It always runs into an assertions
1178 // if LLVM is built with assertions, but without assertions it sometimes
1179 // does not crash and will probably generate a corrupted binary.
1180 // We should only display this error if we're actually going to run PGO.
1181 // If we're just supposed to print out some data, don't show the error (#61002).
1182 if sess.opts.cg.profile_generate.enabled()
1183 && sess.target.target.options.is_like_msvc
1184 && sess.panic_strategy() == PanicStrategy::Unwind
1185 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1188 "Profile-guided optimization does not yet work in conjunction \
1189 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1190 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1191 for more information.",
1195 // Sanitizers can only be used on some tested platforms.
1196 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
1197 const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1198 "x86_64-unknown-linux-gnu",
1199 "x86_64-apple-darwin",
1203 const TSAN_SUPPORTED_TARGETS: &[&str] =
1204 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1205 const LSAN_SUPPORTED_TARGETS: &[&str] =
1206 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1207 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
1209 let supported_targets = match *sanitizer {
1210 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
1211 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
1212 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
1213 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
1216 if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1218 "{:?}Sanitizer only works with the `{}` target",
1220 supported_targets.join("` or `")
1226 /// Holds data on the current incremental compilation session, if there is one.
1228 pub enum IncrCompSession {
1229 /// This is the state the session will be in until the incr. comp. dir is
1232 /// This is the state during which the session directory is private and can
1234 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1235 /// This is the state after the session directory has been finalized. In this
1236 /// state, the contents of the directory must not be modified any more.
1237 Finalized { session_directory: PathBuf },
1238 /// This is an error state that is reached when some compilation error has
1239 /// occurred. It indicates that the contents of the session directory must
1240 /// not be used, since they might be invalid.
1241 InvalidBecauseOfErrors { session_directory: PathBuf },
1244 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1245 let emitter: Box<dyn Emitter + sync::Send> = match output {
1246 config::ErrorOutputType::HumanReadable(kind) => {
1247 let (short, color_config) = kind.unzip();
1248 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1250 config::ErrorOutputType::Json { pretty, json_rendered } => {
1251 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1254 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1255 handler.struct_fatal(msg).emit();
1256 rustc_errors::FatalError.raise();
1259 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1260 let emitter: Box<dyn Emitter + sync::Send> = match output {
1261 config::ErrorOutputType::HumanReadable(kind) => {
1262 let (short, color_config) = kind.unzip();
1263 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1265 config::ErrorOutputType::Json { pretty, json_rendered } => {
1266 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1269 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1270 handler.struct_warn(msg).emit();
1273 pub type CompileResult = Result<(), ErrorReported>;