1 use crate::code_stats::CodeStats;
2 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::cgu_reuse_tracker::CguReuseTracker;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use crate::config::{self, OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
11 use crate::search_paths::{PathKind, SearchPath};
12 use rustc_data_structures::profiling::duration_to_secs_str;
13 use rustc_errors::ErrorReported;
15 use rustc_data_structures::base_n;
16 use rustc_data_structures::impl_stable_hash_via_hash;
17 use rustc_data_structures::sync::{
18 self, AtomicU64, AtomicUsize, Lock, Lrc, Once, OneThread, Ordering, Ordering::SeqCst,
21 use crate::parse::ParseSess;
22 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
23 use rustc_errors::emitter::HumanReadableErrorType;
24 use rustc_errors::emitter::{Emitter, EmitterWriter};
25 use rustc_errors::json::JsonEmitter;
26 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId};
27 use rustc_span::edition::Edition;
28 use rustc_span::source_map;
29 use rustc_span::{MultiSpan, Span};
31 use rustc_data_structures::flock;
32 use rustc_data_structures::jobserver::{self, Client};
33 use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
34 use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
36 use std::cell::{self, RefCell};
40 use std::num::NonZeroU32;
41 use std::path::PathBuf;
43 use std::time::Duration;
45 pub struct OptimizationFuel {
46 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
48 /// We're rejecting all further optimizations.
52 /// Represents the data associated with a compilation
53 /// session for a single crate.
55 pub target: config::Config,
57 pub opts: config::Options,
58 pub host_tlib_path: SearchPath,
59 /// `None` if the host and target are the same.
60 pub target_tlib_path: Option<SearchPath>,
61 pub parse_sess: ParseSess,
63 /// The name of the root source file of the crate, in the local file system.
64 /// `None` means that there is no source file.
65 pub local_crate_source_file: Option<PathBuf>,
66 /// The directory the compiler has been executed in plus a flag indicating
67 /// if the value stored here has been affected by path remapping.
68 pub working_dir: (PathBuf, bool),
70 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
71 /// (sub)diagnostics that have been set once, but should not be set again,
72 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
73 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
74 pub crate_types: Once<Vec<config::CrateType>>,
75 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
76 /// arguments passed to the compiler. Its value together with the crate-name
77 /// forms a unique global identifier for the crate. It is used to allow
78 /// multiple crates with the same name to coexist. See the
79 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
80 pub crate_disambiguator: Once<CrateDisambiguator>,
82 features: Once<rustc_feature::Features>,
84 /// The maximum recursion limit for potentially infinitely recursive
85 /// operations such as auto-dereference and monomorphization.
86 pub recursion_limit: Once<usize>,
88 /// The maximum length of types during monomorphization.
89 pub type_length_limit: Once<usize>,
91 /// Map from imported macro spans (which consist of
92 /// the localized span for the macro body) to the
93 /// macro name and definition span in the source crate.
94 pub imported_macro_spans: OneThread<RefCell<FxHashMap<Span, (String, Span)>>>,
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>>>>,
141 pub struct PerfStats {
142 /// The accumulated time spent on computing symbol hashes.
143 pub symbol_hash_time: Lock<Duration>,
144 /// The accumulated time spent decoding def path tables from metadata.
145 pub decode_def_path_tables_time: Lock<Duration>,
146 /// Total number of values canonicalized queries constructed.
147 pub queries_canonicalized: AtomicUsize,
148 /// Number of times this query is invoked.
149 pub normalize_ty_after_erasing_regions: AtomicUsize,
150 /// Number of times this query is invoked.
151 pub normalize_projection_ty: AtomicUsize,
154 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
155 enum DiagnosticBuilderMethod {
158 SpanSuggestion(String), // suggestion
159 // Add more variants as needed to support one-time diagnostics.
162 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
163 /// emitting the same message more than once.
164 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
165 pub enum DiagnosticMessageId {
166 ErrorId(u16), // EXXXX error code as integer
167 LintId(lint::LintId),
168 StabilityId(Option<NonZeroU32>), // issue number
171 impl From<&'static lint::Lint> for DiagnosticMessageId {
172 fn from(lint: &'static lint::Lint) -> Self {
173 DiagnosticMessageId::LintId(lint::LintId::of(lint))
178 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
179 *self.crate_disambiguator.get()
182 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
183 self.diagnostic().struct_span_warn(sp, msg)
185 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
190 ) -> DiagnosticBuilder<'_> {
191 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
193 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
194 self.diagnostic().struct_warn(msg)
196 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
197 self.diagnostic().struct_span_err(sp, msg)
199 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
204 ) -> DiagnosticBuilder<'_> {
205 self.diagnostic().struct_span_err_with_code(sp, msg, code)
207 // FIXME: This method should be removed (every error should have an associated error code).
208 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
209 self.diagnostic().struct_err(msg)
211 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
212 self.diagnostic().struct_err_with_code(msg, code)
214 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
215 self.diagnostic().struct_span_fatal(sp, msg)
217 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
222 ) -> DiagnosticBuilder<'_> {
223 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
225 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
226 self.diagnostic().struct_fatal(msg)
229 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
230 self.diagnostic().span_fatal(sp, msg).raise()
232 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
238 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
240 pub fn fatal(&self, msg: &str) -> ! {
241 self.diagnostic().fatal(msg).raise()
243 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
245 self.span_warn(sp, msg);
247 self.span_err(sp, msg);
250 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
251 self.diagnostic().span_err(sp, msg)
253 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
254 self.diagnostic().span_err_with_code(sp, &msg, code)
256 pub fn err(&self, msg: &str) {
257 self.diagnostic().err(msg)
259 pub fn err_count(&self) -> usize {
260 self.diagnostic().err_count()
262 pub fn has_errors(&self) -> bool {
263 self.diagnostic().has_errors()
265 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
266 self.diagnostic().has_errors_or_delayed_span_bugs()
268 pub fn abort_if_errors(&self) {
269 self.diagnostic().abort_if_errors();
271 pub fn compile_status(&self) -> Result<(), ErrorReported> {
272 if self.has_errors() {
273 self.diagnostic().emit_stashed_diagnostics();
279 // FIXME(matthewjasper) Remove this method, it should never be needed.
280 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
284 let old_count = self.err_count();
286 let errors = self.err_count() - old_count;
287 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
289 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
290 self.diagnostic().span_warn(sp, msg)
292 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
293 self.diagnostic().span_warn_with_code(sp, msg, code)
295 pub fn warn(&self, msg: &str) {
296 self.diagnostic().warn(msg)
298 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
300 Some(sp) => self.span_warn(sp, msg),
301 None => self.warn(msg),
304 /// Delay a span_bug() call until abort_if_errors()
305 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
306 self.diagnostic().delay_span_bug(sp, msg)
308 pub fn note_without_error(&self, msg: &str) {
309 self.diagnostic().note_without_error(msg)
311 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
312 self.diagnostic().span_note_without_error(sp, msg)
315 pub fn diagnostic(&self) -> &rustc_errors::Handler {
316 &self.parse_sess.span_diagnostic
319 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
320 /// deduplicates on lint ID, span (if any), and message for this `Session`
321 fn diag_once<'a, 'b>(
323 diag_builder: &'b mut DiagnosticBuilder<'a>,
324 method: DiagnosticBuilderMethod,
325 msg_id: DiagnosticMessageId,
327 span_maybe: Option<Span>,
329 let id_span_message = (msg_id, span_maybe, message.to_owned());
330 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
333 DiagnosticBuilderMethod::Note => {
334 diag_builder.note(message);
336 DiagnosticBuilderMethod::SpanNote => {
337 let span = span_maybe.expect("`span_note` needs a span");
338 diag_builder.span_note(span, message);
340 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
341 let span = span_maybe.expect("`span_suggestion_*` needs a span");
342 diag_builder.span_suggestion(
346 Applicability::Unspecified,
353 pub fn diag_span_note_once<'a, 'b>(
355 diag_builder: &'b mut DiagnosticBuilder<'a>,
356 msg_id: DiagnosticMessageId,
362 DiagnosticBuilderMethod::SpanNote,
369 pub fn diag_note_once<'a, 'b>(
371 diag_builder: &'b mut DiagnosticBuilder<'a>,
372 msg_id: DiagnosticMessageId,
375 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
378 pub fn diag_span_suggestion_once<'a, 'b>(
380 diag_builder: &'b mut DiagnosticBuilder<'a>,
381 msg_id: DiagnosticMessageId,
388 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
396 pub fn source_map(&self) -> &source_map::SourceMap {
397 self.parse_sess.source_map()
399 pub fn verbose(&self) -> bool {
400 self.opts.debugging_opts.verbose
402 pub fn time_passes(&self) -> bool {
403 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
405 pub fn instrument_mcount(&self) -> bool {
406 self.opts.debugging_opts.instrument_mcount
408 pub fn time_llvm_passes(&self) -> bool {
409 self.opts.debugging_opts.time_llvm_passes
411 pub fn meta_stats(&self) -> bool {
412 self.opts.debugging_opts.meta_stats
414 pub fn asm_comments(&self) -> bool {
415 self.opts.debugging_opts.asm_comments
417 pub fn verify_llvm_ir(&self) -> bool {
418 self.opts.debugging_opts.verify_llvm_ir || cfg!(always_verify_llvm_ir)
420 pub fn borrowck_stats(&self) -> bool {
421 self.opts.debugging_opts.borrowck_stats
423 pub fn print_llvm_passes(&self) -> bool {
424 self.opts.debugging_opts.print_llvm_passes
426 pub fn binary_dep_depinfo(&self) -> bool {
427 self.opts.debugging_opts.binary_dep_depinfo
430 /// Gets the features enabled for the current compilation session.
431 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
432 /// dependency tracking. Use tcx.features() instead.
434 pub fn features_untracked(&self) -> &rustc_feature::Features {
438 pub fn init_features(&self, features: rustc_feature::Features) {
439 self.features.set(features);
442 /// Calculates the flavor of LTO to use for this compilation.
443 pub fn lto(&self) -> config::Lto {
444 // If our target has codegen requirements ignore the command line
445 if self.target.target.options.requires_lto {
446 return config::Lto::Fat;
449 // If the user specified something, return that. If they only said `-C
450 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
451 // then ensure we can't use a ThinLTO.
452 match self.opts.cg.lto {
453 config::LtoCli::Unspecified => {
454 // The compiler was invoked without the `-Clto` flag. Fall
455 // through to the default handling
457 config::LtoCli::No => {
458 // The user explicitly opted out of any kind of LTO
459 return config::Lto::No;
461 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
462 // All of these mean fat LTO
463 return config::Lto::Fat;
465 config::LtoCli::Thin => {
466 return if self.opts.cli_forced_thinlto_off {
474 // Ok at this point the target doesn't require anything and the user
475 // hasn't asked for anything. Our next decision is whether or not
476 // we enable "auto" ThinLTO where we use multiple codegen units and
477 // then do ThinLTO over those codegen units. The logic below will
478 // either return `No` or `ThinLocal`.
480 // If processing command line options determined that we're incompatible
481 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
482 if self.opts.cli_forced_thinlto_off {
483 return config::Lto::No;
486 // If `-Z thinlto` specified process that, but note that this is mostly
487 // a deprecated option now that `-C lto=thin` exists.
488 if let Some(enabled) = self.opts.debugging_opts.thinlto {
490 return config::Lto::ThinLocal;
492 return config::Lto::No;
496 // If there's only one codegen unit and LTO isn't enabled then there's
497 // no need for ThinLTO so just return false.
498 if self.codegen_units() == 1 {
499 return config::Lto::No;
502 // Now we're in "defaults" territory. By default we enable ThinLTO for
503 // optimized compiles (anything greater than O0).
504 match self.opts.optimize {
505 config::OptLevel::No => config::Lto::No,
506 _ => config::Lto::ThinLocal,
510 /// Returns the panic strategy for this compile session. If the user explicitly selected one
511 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
512 pub fn panic_strategy(&self) -> PanicStrategy {
513 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
515 pub fn fewer_names(&self) -> bool {
516 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
517 || self.opts.output_types.contains_key(&OutputType::Bitcode);
519 // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
520 let more_names = match self.opts.debugging_opts.sanitizer {
521 Some(Sanitizer::Address) => true,
522 Some(Sanitizer::Memory) => true,
526 self.opts.debugging_opts.fewer_names || !more_names
529 pub fn no_landing_pads(&self) -> bool {
530 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
532 pub fn unstable_options(&self) -> bool {
533 self.opts.debugging_opts.unstable_options
535 pub fn overflow_checks(&self) -> bool {
539 .or(self.opts.debugging_opts.force_overflow_checks)
540 .unwrap_or(self.opts.debug_assertions)
543 pub fn crt_static(&self) -> bool {
544 // If the target does not opt in to crt-static support, use its default.
545 if self.target.target.options.crt_static_respected {
546 self.crt_static_feature()
548 self.target.target.options.crt_static_default
552 pub fn crt_static_feature(&self) -> bool {
553 let requested_features = self.opts.cg.target_feature.split(',');
554 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
555 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
557 // If the target we're compiling for requests a static crt by default,
558 // then see if the `-crt-static` feature was passed to disable that.
559 // Otherwise if we don't have a static crt by default then see if the
560 // `+crt-static` feature was passed.
561 if self.target.target.options.crt_static_default { !found_negative } else { found_positive }
564 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
565 // "mcount" function relies on stack pointer.
566 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
567 if self.instrument_mcount() {
569 } else if let Some(x) = self.opts.cg.force_frame_pointers {
572 !self.target.target.options.eliminate_frame_pointer
576 /// Returns the symbol name for the registrar function,
577 /// given the crate `Svh` and the function `DefIndex`.
578 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
579 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
582 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
583 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
586 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
587 filesearch::FileSearch::new(
589 self.opts.target_triple.triple(),
590 &self.opts.search_paths,
591 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
592 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
596 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
597 filesearch::FileSearch::new(
599 config::host_triple(),
600 &self.opts.search_paths,
601 &self.host_tlib_path,
606 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
607 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
609 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
610 *load_dep_graph = load;
614 pub fn incr_session_load_dep_graph(&self) -> bool {
615 let incr_comp_session = self.incr_comp_session.borrow();
616 match *incr_comp_session {
617 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
622 pub fn init_incr_comp_session(
624 session_dir: PathBuf,
625 lock_file: flock::Lock,
626 load_dep_graph: bool,
628 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
630 if let IncrCompSession::NotInitialized = *incr_comp_session {
632 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
636 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
639 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
640 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
642 if let IncrCompSession::Active { .. } = *incr_comp_session {
644 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
647 // Note: this will also drop the lock file, thus unlocking the directory.
648 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
651 pub fn mark_incr_comp_session_as_invalid(&self) {
652 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
654 let session_directory = match *incr_comp_session {
655 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
656 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
657 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
660 // Note: this will also drop the lock file, thus unlocking the directory.
661 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
664 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
665 let incr_comp_session = self.incr_comp_session.borrow();
666 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
667 IncrCompSession::NotInitialized => panic!(
668 "trying to get session directory from `IncrCompSession`: {:?}",
671 IncrCompSession::Active { ref session_directory, .. }
672 | IncrCompSession::Finalized { ref session_directory }
673 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
679 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
680 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
683 pub fn print_perf_stats(&self) {
685 "Total time spent computing symbol hashes: {}",
686 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
689 "Total time spent decoding DefPath tables: {}",
690 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
693 "Total queries canonicalized: {}",
694 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
697 "normalize_ty_after_erasing_regions: {}",
698 self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed)
701 "normalize_projection_ty: {}",
702 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
706 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
707 /// This expends fuel if applicable, and records fuel if applicable.
708 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
710 if let Some(ref c) = self.optimization_fuel_crate {
712 assert_eq!(self.threads(), 1);
713 let mut fuel = self.optimization_fuel.lock();
714 ret = fuel.remaining != 0;
715 if fuel.remaining == 0 && !fuel.out_of_fuel {
716 eprintln!("optimization-fuel-exhausted: {}", msg());
717 fuel.out_of_fuel = true;
718 } else if fuel.remaining > 0 {
723 if let Some(ref c) = self.print_fuel_crate {
725 assert_eq!(self.threads(), 1);
726 self.print_fuel.fetch_add(1, SeqCst);
732 /// Returns the number of query threads that should be used for this
734 pub fn threads(&self) -> usize {
735 self.opts.debugging_opts.threads
738 /// Returns the number of codegen units that should be used for this
740 pub fn codegen_units(&self) -> usize {
741 if let Some(n) = self.opts.cli_forced_codegen_units {
744 if let Some(n) = self.target.target.options.default_codegen_units {
748 // Why is 16 codegen units the default all the time?
750 // The main reason for enabling multiple codegen units by default is to
751 // leverage the ability for the codegen backend to do codegen and
752 // optimization in parallel. This allows us, especially for large crates, to
753 // make good use of all available resources on the machine once we've
754 // hit that stage of compilation. Large crates especially then often
755 // take a long time in codegen/optimization and this helps us amortize that
758 // Note that a high number here doesn't mean that we'll be spawning a
759 // large number of threads in parallel. The backend of rustc contains
760 // global rate limiting through the `jobserver` crate so we'll never
761 // overload the system with too much work, but rather we'll only be
762 // optimizing when we're otherwise cooperating with other instances of
765 // Rather a high number here means that we should be able to keep a lot
766 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
767 // to build we'll be guaranteed that all cpus will finish pretty closely
768 // to one another and we should make relatively optimal use of system
771 // Note that the main cost of codegen units is that it prevents LLVM
772 // from inlining across codegen units. Users in general don't have a lot
773 // of control over how codegen units are split up so it's our job in the
774 // compiler to ensure that undue performance isn't lost when using
775 // codegen units (aka we can't require everyone to slap `#[inline]` on
778 // If we're compiling at `-O0` then the number doesn't really matter too
779 // much because performance doesn't matter and inlining is ok to lose.
780 // In debug mode we just want to try to guarantee that no cpu is stuck
781 // doing work that could otherwise be farmed to others.
783 // In release mode, however (O1 and above) performance does indeed
784 // matter! To recover the loss in performance due to inlining we'll be
785 // enabling ThinLTO by default (the function for which is just below).
786 // This will ensure that we recover any inlining wins we otherwise lost
787 // through codegen unit partitioning.
791 // Ok that's a lot of words but the basic tl;dr; is that we want a high
792 // number here -- but not too high. Additionally we're "safe" to have it
793 // always at the same number at all optimization levels.
795 // As a result 16 was chosen here! Mostly because it was a power of 2
796 // and most benchmarks agreed it was roughly a local optimum. Not very
801 pub fn teach(&self, code: &DiagnosticId) -> bool {
802 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
805 pub fn rust_2015(&self) -> bool {
806 self.opts.edition == Edition::Edition2015
809 /// Are we allowed to use features from the Rust 2018 edition?
810 pub fn rust_2018(&self) -> bool {
811 self.opts.edition >= Edition::Edition2018
814 pub fn edition(&self) -> Edition {
818 /// Returns `true` if we cannot skip the PLT for shared library calls.
819 pub fn needs_plt(&self) -> bool {
820 // Check if the current target usually needs PLT to be enabled.
821 // The user can use the command line flag to override it.
822 let needs_plt = self.target.target.options.needs_plt;
824 let dbg_opts = &self.opts.debugging_opts;
826 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
828 // Only enable this optimization by default if full relro is also enabled.
829 // In this case, lazy binding was already unavailable, so nothing is lost.
830 // This also ensures `-Wl,-z,now` is supported by the linker.
831 let full_relro = RelroLevel::Full == relro_level;
833 // If user didn't explicitly forced us to use / skip the PLT,
834 // then try to skip it where possible.
835 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
839 pub fn build_session(
840 sopts: config::Options,
841 local_crate_source_file: Option<PathBuf>,
842 registry: rustc_errors::registry::Registry,
844 let file_path_mapping = sopts.file_path_mapping();
846 build_session_with_source_map(
848 local_crate_source_file,
850 Lrc::new(source_map::SourceMap::new(file_path_mapping)),
851 DiagnosticOutput::Default,
857 sopts: &config::Options,
858 registry: rustc_errors::registry::Registry,
859 source_map: &Lrc<source_map::SourceMap>,
860 emitter_dest: Option<Box<dyn Write + Send>>,
861 ) -> Box<dyn Emitter + sync::Send> {
862 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
863 match (sopts.error_format, emitter_dest) {
864 (config::ErrorOutputType::HumanReadable(kind), dst) => {
865 let (short, color_config) = kind.unzip();
867 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
868 let emitter = AnnotateSnippetEmitterWriter::new(
869 Some(source_map.clone()),
873 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing()))
875 let emitter = match dst {
876 None => EmitterWriter::stderr(
878 Some(source_map.clone()),
880 sopts.debugging_opts.teach,
881 sopts.debugging_opts.terminal_width,
884 Some(dst) => EmitterWriter::new(
886 Some(source_map.clone()),
888 false, // no teach messages when writing to a buffer
889 false, // no colors when writing to a buffer
890 None, // no terminal width
894 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing()))
897 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
905 .ui_testing(sopts.debugging_opts.ui_testing()),
907 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
916 .ui_testing(sopts.debugging_opts.ui_testing()),
921 pub enum DiagnosticOutput {
923 Raw(Box<dyn Write + Send>),
926 pub fn build_session_with_source_map(
927 sopts: config::Options,
928 local_crate_source_file: Option<PathBuf>,
929 registry: rustc_errors::registry::Registry,
930 source_map: Lrc<source_map::SourceMap>,
931 diagnostics_output: DiagnosticOutput,
932 lint_caps: FxHashMap<lint::LintId, lint::Level>,
934 // FIXME: This is not general enough to make the warning lint completely override
935 // normal diagnostic warnings, since the warning lint can also be denied and changed
936 // later via the source code.
937 let warnings_allow = sopts
940 .filter(|&&(ref key, _)| *key == "warnings")
941 .map(|&(_, ref level)| *level == lint::Allow)
944 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
945 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
947 let write_dest = match diagnostics_output {
948 DiagnosticOutput::Default => None,
949 DiagnosticOutput::Raw(write) => Some(write),
951 let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
953 let diagnostic_handler = rustc_errors::Handler::with_emitter_and_flags(
955 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
958 build_session_(sopts, local_crate_source_file, diagnostic_handler, source_map, lint_caps)
962 sopts: config::Options,
963 local_crate_source_file: Option<PathBuf>,
964 span_diagnostic: rustc_errors::Handler,
965 source_map: Lrc<source_map::SourceMap>,
966 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
968 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
971 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
973 let profiler = SelfProfiler::new(
975 sopts.crate_name.as_ref().map(|s| &s[..]),
976 &sopts.debugging_opts.self_profile_events,
979 Ok(profiler) => Some(Arc::new(profiler)),
981 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
989 let host_triple = TargetTriple::from_triple(config::host_triple());
990 let host = Target::search(&host_triple).unwrap_or_else(|e| {
991 span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise()
993 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
995 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
996 let sysroot = match &sopts.maybe_sysroot {
997 Some(sysroot) => sysroot.clone(),
998 None => filesearch::get_or_default_sysroot(),
1001 let host_triple = config::host_triple();
1002 let target_triple = sopts.target_triple.triple();
1003 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1004 let target_tlib_path = if host_triple == target_triple {
1007 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1010 let file_path_mapping = sopts.file_path_mapping();
1012 let local_crate_source_file =
1013 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1015 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1016 let optimization_fuel = Lock::new(OptimizationFuel {
1017 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1020 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1021 let print_fuel = AtomicU64::new(0);
1023 let working_dir = env::current_dir().unwrap_or_else(|e| {
1024 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1026 let working_dir = file_path_mapping.map_prefix(working_dir);
1028 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1029 CguReuseTracker::new()
1031 CguReuseTracker::new_disabled()
1034 let prof = SelfProfilerRef::new(
1036 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1037 sopts.debugging_opts.time_passes,
1040 let sess = Session {
1048 local_crate_source_file,
1050 one_time_diagnostics: Default::default(),
1051 crate_types: Once::new(),
1052 crate_disambiguator: Once::new(),
1053 features: Once::new(),
1054 recursion_limit: Once::new(),
1055 type_length_limit: Once::new(),
1056 imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())),
1057 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1060 perf_stats: PerfStats {
1061 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1062 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1063 queries_canonicalized: AtomicUsize::new(0),
1064 normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1065 normalize_projection_ty: AtomicUsize::new(0),
1067 code_stats: Default::default(),
1068 optimization_fuel_crate,
1072 jobserver: jobserver::client(),
1074 trait_methods_not_found: Lock::new(Default::default()),
1075 confused_type_with_std_module: Lock::new(Default::default()),
1076 system_library_path: OneThread::new(RefCell::new(Default::default())),
1079 validate_commandline_args_with_session_available(&sess);
1084 // If it is useful to have a Session available already for validating a
1085 // commandline argument, you can do so here.
1086 fn validate_commandline_args_with_session_available(sess: &Session) {
1087 // Since we don't know if code in an rlib will be linked to statically or
1088 // dynamically downstream, rustc generates `__imp_` symbols that help the
1089 // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1090 // these manually generated symbols confuse LLD when it tries to merge
1091 // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1092 // when compiling for LLD ThinLTO. This way we can validly just not generate
1093 // the `dllimport` attributes and `__imp_` symbols in that case.
1094 if sess.opts.cg.linker_plugin_lto.enabled()
1095 && sess.opts.cg.prefer_dynamic
1096 && sess.target.target.options.is_like_msvc
1099 "Linker plugin based LTO is not supported together with \
1100 `-C prefer-dynamic` when targeting MSVC",
1104 // Make sure that any given profiling data actually exists so LLVM can't
1105 // decide to silently skip PGO.
1106 if let Some(ref path) = sess.opts.cg.profile_use {
1109 "File `{}` passed to `-C profile-use` does not exist.",
1115 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1116 // an error to combine the two for now. It always runs into an assertions
1117 // if LLVM is built with assertions, but without assertions it sometimes
1118 // does not crash and will probably generate a corrupted binary.
1119 // We should only display this error if we're actually going to run PGO.
1120 // If we're just supposed to print out some data, don't show the error (#61002).
1121 if sess.opts.cg.profile_generate.enabled()
1122 && sess.target.target.options.is_like_msvc
1123 && sess.panic_strategy() == PanicStrategy::Unwind
1124 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1127 "Profile-guided optimization does not yet work in conjunction \
1128 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1129 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1130 for more information.",
1134 // Sanitizers can only be used on some tested platforms.
1135 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
1136 const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1137 "x86_64-unknown-linux-gnu",
1138 "x86_64-apple-darwin",
1142 const TSAN_SUPPORTED_TARGETS: &[&str] =
1143 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1144 const LSAN_SUPPORTED_TARGETS: &[&str] =
1145 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1146 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
1148 let supported_targets = match *sanitizer {
1149 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
1150 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
1151 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
1152 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
1155 if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1157 "{:?}Sanitizer only works with the `{}` target",
1159 supported_targets.join("` or `")
1165 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1166 /// compiler. Together with the crate-name forms a unique global identifier for
1168 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1169 pub struct CrateDisambiguator(Fingerprint);
1171 impl CrateDisambiguator {
1172 pub fn to_fingerprint(self) -> Fingerprint {
1177 impl fmt::Display for CrateDisambiguator {
1178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1179 let (a, b) = self.0.as_value();
1180 let as_u128 = a as u128 | ((b as u128) << 64);
1181 f.write_str(&base_n::encode(as_u128, base_n::CASE_INSENSITIVE))
1185 impl From<Fingerprint> for CrateDisambiguator {
1186 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1187 CrateDisambiguator(fingerprint)
1191 impl_stable_hash_via_hash!(CrateDisambiguator);
1193 /// Holds data on the current incremental compilation session, if there is one.
1195 pub enum IncrCompSession {
1196 /// This is the state the session will be in until the incr. comp. dir is
1199 /// This is the state during which the session directory is private and can
1201 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1202 /// This is the state after the session directory has been finalized. In this
1203 /// state, the contents of the directory must not be modified any more.
1204 Finalized { session_directory: PathBuf },
1205 /// This is an error state that is reached when some compilation error has
1206 /// occurred. It indicates that the contents of the session directory must
1207 /// not be used, since they might be invalid.
1208 InvalidBecauseOfErrors { session_directory: PathBuf },
1211 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1212 let emitter: Box<dyn Emitter + sync::Send> = match output {
1213 config::ErrorOutputType::HumanReadable(kind) => {
1214 let (short, color_config) = kind.unzip();
1215 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1217 config::ErrorOutputType::Json { pretty, json_rendered } => {
1218 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1221 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1222 handler.struct_fatal(msg).emit();
1223 rustc_errors::FatalError.raise();
1226 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1227 let emitter: Box<dyn Emitter + sync::Send> = match output {
1228 config::ErrorOutputType::HumanReadable(kind) => {
1229 let (short, color_config) = kind.unzip();
1230 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1232 config::ErrorOutputType::Json { pretty, json_rendered } => {
1233 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1236 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1237 handler.struct_warn(msg).emit();
1240 pub type CompileResult = Result<(), ErrorReported>;