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};
37 use std::cell::{self, RefCell};
41 use std::num::NonZeroU32;
42 use std::path::PathBuf;
44 use std::time::Duration;
46 pub struct OptimizationFuel {
47 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
49 /// We're rejecting all further optimizations.
53 /// Represents the data associated with a compilation
54 /// session for a single crate.
56 pub target: config::Config,
58 pub opts: config::Options,
59 pub host_tlib_path: SearchPath,
60 /// `None` if the host and target are the same.
61 pub target_tlib_path: Option<SearchPath>,
62 pub parse_sess: ParseSess,
64 /// The name of the root source file of the crate, in the local file system.
65 /// `None` means that there is no source file.
66 pub local_crate_source_file: Option<PathBuf>,
67 /// The directory the compiler has been executed in plus a flag indicating
68 /// if the value stored here has been affected by path remapping.
69 pub working_dir: (PathBuf, bool),
71 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
72 /// (sub)diagnostics that have been set once, but should not be set again,
73 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
74 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
75 pub crate_types: Once<Vec<config::CrateType>>,
76 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
77 /// arguments passed to the compiler. Its value together with the crate-name
78 /// forms a unique global identifier for the crate. It is used to allow
79 /// multiple crates with the same name to coexist. See the
80 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
81 pub crate_disambiguator: Once<CrateDisambiguator>,
83 features: Once<rustc_feature::Features>,
85 /// The maximum recursion limit for potentially infinitely recursive
86 /// operations such as auto-dereference and monomorphization.
87 pub recursion_limit: Once<usize>,
89 /// The maximum length of types during monomorphization.
90 pub type_length_limit: Once<usize>,
92 /// Map from imported macro spans (which consist of
93 /// the localized span for the macro body) to the
94 /// macro name and definition span in the source crate.
95 pub imported_macro_spans: OneThread<RefCell<FxHashMap<Span, (String, Span)>>>,
97 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
98 /// Used for incremental compilation tests. Will only be populated if
99 /// `-Zquery-dep-graph` is specified.
100 pub cgu_reuse_tracker: CguReuseTracker,
102 /// Used by `-Z self-profile`.
103 pub prof: SelfProfilerRef,
105 /// Some measurements that are being gathered during compilation.
106 pub perf_stats: PerfStats,
108 /// Data about code being compiled, gathered during compilation.
109 pub code_stats: CodeStats,
111 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
112 optimization_fuel_crate: Option<String>,
114 /// Tracks fuel info if `-zfuel=crate=n` is specified.
115 optimization_fuel: Lock<OptimizationFuel>,
117 // The next two are public because the driver needs to read them.
118 /// If `-zprint-fuel=crate`, `Some(crate)`.
119 pub print_fuel_crate: Option<String>,
120 /// Always set to zero and incremented so that we can print fuel expended by a crate.
121 pub print_fuel: AtomicU64,
123 /// Loaded up early on in the initialization of this `Session` to avoid
124 /// false positives about a job server in our environment.
125 pub jobserver: Client,
127 /// Cap lint level specified by a driver specifically.
128 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
130 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
131 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
133 /// Mapping from ident span to path span for paths that don't exist as written, but that
134 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
135 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
138 pub struct PerfStats {
139 /// The accumulated time spent on computing symbol hashes.
140 pub symbol_hash_time: Lock<Duration>,
141 /// The accumulated time spent decoding def path tables from metadata.
142 pub decode_def_path_tables_time: Lock<Duration>,
143 /// Total number of values canonicalized queries constructed.
144 pub queries_canonicalized: AtomicUsize,
145 /// Number of times this query is invoked.
146 pub normalize_ty_after_erasing_regions: AtomicUsize,
147 /// Number of times this query is invoked.
148 pub normalize_projection_ty: AtomicUsize,
151 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
152 enum DiagnosticBuilderMethod {
155 SpanSuggestion(String), // suggestion
156 // Add more variants as needed to support one-time diagnostics.
159 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
160 /// emitting the same message more than once.
161 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
162 pub enum DiagnosticMessageId {
163 ErrorId(u16), // EXXXX error code as integer
164 LintId(lint::LintId),
165 StabilityId(Option<NonZeroU32>), // issue number
168 impl From<&'static lint::Lint> for DiagnosticMessageId {
169 fn from(lint: &'static lint::Lint) -> Self {
170 DiagnosticMessageId::LintId(lint::LintId::of(lint))
175 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
176 *self.crate_disambiguator.get()
179 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
180 self.diagnostic().struct_span_warn(sp, msg)
182 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
187 ) -> DiagnosticBuilder<'_> {
188 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
190 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
191 self.diagnostic().struct_warn(msg)
193 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
194 self.diagnostic().struct_span_err(sp, msg)
196 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
201 ) -> DiagnosticBuilder<'_> {
202 self.diagnostic().struct_span_err_with_code(sp, msg, code)
204 // FIXME: This method should be removed (every error should have an associated error code).
205 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
206 self.diagnostic().struct_err(msg)
208 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
209 self.diagnostic().struct_err_with_code(msg, code)
211 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
212 self.diagnostic().struct_span_fatal(sp, msg)
214 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
219 ) -> DiagnosticBuilder<'_> {
220 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
222 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
223 self.diagnostic().struct_fatal(msg)
226 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
227 self.diagnostic().span_fatal(sp, msg).raise()
229 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
235 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
237 pub fn fatal(&self, msg: &str) -> ! {
238 self.diagnostic().fatal(msg).raise()
240 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
242 self.span_warn(sp, msg);
244 self.span_err(sp, msg);
247 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
248 self.diagnostic().span_err(sp, msg)
250 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
251 self.diagnostic().span_err_with_code(sp, &msg, code)
253 pub fn err(&self, msg: &str) {
254 self.diagnostic().err(msg)
256 pub fn err_count(&self) -> usize {
257 self.diagnostic().err_count()
259 pub fn has_errors(&self) -> bool {
260 self.diagnostic().has_errors()
262 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
263 self.diagnostic().has_errors_or_delayed_span_bugs()
265 pub fn abort_if_errors(&self) {
266 self.diagnostic().abort_if_errors();
268 pub fn compile_status(&self) -> Result<(), ErrorReported> {
269 if self.has_errors() {
270 self.diagnostic().emit_stashed_diagnostics();
276 // FIXME(matthewjasper) Remove this method, it should never be needed.
277 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
281 let old_count = self.err_count();
283 let errors = self.err_count() - old_count;
284 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
286 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
287 self.diagnostic().span_warn(sp, msg)
289 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
290 self.diagnostic().span_warn_with_code(sp, msg, code)
292 pub fn warn(&self, msg: &str) {
293 self.diagnostic().warn(msg)
295 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
297 Some(sp) => self.span_warn(sp, msg),
298 None => self.warn(msg),
301 /// Delay a span_bug() call until abort_if_errors()
302 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
303 self.diagnostic().delay_span_bug(sp, msg)
305 pub fn note_without_error(&self, msg: &str) {
306 self.diagnostic().note_without_error(msg)
308 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
309 self.diagnostic().span_note_without_error(sp, msg)
312 pub fn diagnostic(&self) -> &rustc_errors::Handler {
313 &self.parse_sess.span_diagnostic
316 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
317 /// deduplicates on lint ID, span (if any), and message for this `Session`
318 fn diag_once<'a, 'b>(
320 diag_builder: &'b mut DiagnosticBuilder<'a>,
321 method: DiagnosticBuilderMethod,
322 msg_id: DiagnosticMessageId,
324 span_maybe: Option<Span>,
326 let id_span_message = (msg_id, span_maybe, message.to_owned());
327 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
330 DiagnosticBuilderMethod::Note => {
331 diag_builder.note(message);
333 DiagnosticBuilderMethod::SpanNote => {
334 let span = span_maybe.expect("`span_note` needs a span");
335 diag_builder.span_note(span, message);
337 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
338 let span = span_maybe.expect("`span_suggestion_*` needs a span");
339 diag_builder.span_suggestion(
343 Applicability::Unspecified,
350 pub fn diag_span_note_once<'a, 'b>(
352 diag_builder: &'b mut DiagnosticBuilder<'a>,
353 msg_id: DiagnosticMessageId,
359 DiagnosticBuilderMethod::SpanNote,
366 pub fn diag_note_once<'a, 'b>(
368 diag_builder: &'b mut DiagnosticBuilder<'a>,
369 msg_id: DiagnosticMessageId,
372 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
375 pub fn diag_span_suggestion_once<'a, 'b>(
377 diag_builder: &'b mut DiagnosticBuilder<'a>,
378 msg_id: DiagnosticMessageId,
385 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
392 pub fn source_map(&self) -> &source_map::SourceMap {
393 self.parse_sess.source_map()
395 pub fn verbose(&self) -> bool {
396 self.opts.debugging_opts.verbose
398 pub fn time_passes(&self) -> bool {
399 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
401 pub fn instrument_mcount(&self) -> bool {
402 self.opts.debugging_opts.instrument_mcount
404 pub fn time_llvm_passes(&self) -> bool {
405 self.opts.debugging_opts.time_llvm_passes
407 pub fn meta_stats(&self) -> bool {
408 self.opts.debugging_opts.meta_stats
410 pub fn asm_comments(&self) -> bool {
411 self.opts.debugging_opts.asm_comments
413 pub fn verify_llvm_ir(&self) -> bool {
414 self.opts.debugging_opts.verify_llvm_ir || cfg!(always_verify_llvm_ir)
416 pub fn borrowck_stats(&self) -> bool {
417 self.opts.debugging_opts.borrowck_stats
419 pub fn print_llvm_passes(&self) -> bool {
420 self.opts.debugging_opts.print_llvm_passes
422 pub fn binary_dep_depinfo(&self) -> bool {
423 self.opts.debugging_opts.binary_dep_depinfo
426 /// Gets the features enabled for the current compilation session.
427 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
428 /// dependency tracking. Use tcx.features() instead.
430 pub fn features_untracked(&self) -> &rustc_feature::Features {
434 pub fn init_features(&self, features: rustc_feature::Features) {
435 self.features.set(features);
438 /// Calculates the flavor of LTO to use for this compilation.
439 pub fn lto(&self) -> config::Lto {
440 // If our target has codegen requirements ignore the command line
441 if self.target.target.options.requires_lto {
442 return config::Lto::Fat;
445 // If the user specified something, return that. If they only said `-C
446 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
447 // then ensure we can't use a ThinLTO.
448 match self.opts.cg.lto {
449 config::LtoCli::Unspecified => {
450 // The compiler was invoked without the `-Clto` flag. Fall
451 // through to the default handling
453 config::LtoCli::No => {
454 // The user explicitly opted out of any kind of LTO
455 return config::Lto::No;
457 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
458 // All of these mean fat LTO
459 return config::Lto::Fat;
461 config::LtoCli::Thin => {
462 return if self.opts.cli_forced_thinlto_off {
470 // Ok at this point the target doesn't require anything and the user
471 // hasn't asked for anything. Our next decision is whether or not
472 // we enable "auto" ThinLTO where we use multiple codegen units and
473 // then do ThinLTO over those codegen units. The logic below will
474 // either return `No` or `ThinLocal`.
476 // If processing command line options determined that we're incompatible
477 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
478 if self.opts.cli_forced_thinlto_off {
479 return config::Lto::No;
482 // If `-Z thinlto` specified process that, but note that this is mostly
483 // a deprecated option now that `-C lto=thin` exists.
484 if let Some(enabled) = self.opts.debugging_opts.thinlto {
486 return config::Lto::ThinLocal;
488 return config::Lto::No;
492 // If there's only one codegen unit and LTO isn't enabled then there's
493 // no need for ThinLTO so just return false.
494 if self.codegen_units() == 1 {
495 return config::Lto::No;
498 // Now we're in "defaults" territory. By default we enable ThinLTO for
499 // optimized compiles (anything greater than O0).
500 match self.opts.optimize {
501 config::OptLevel::No => config::Lto::No,
502 _ => config::Lto::ThinLocal,
506 /// Returns the panic strategy for this compile session. If the user explicitly selected one
507 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
508 pub fn panic_strategy(&self) -> PanicStrategy {
509 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
511 pub fn fewer_names(&self) -> bool {
512 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
513 || self.opts.output_types.contains_key(&OutputType::Bitcode);
515 // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
516 let more_names = match self.opts.debugging_opts.sanitizer {
517 Some(Sanitizer::Address) => true,
518 Some(Sanitizer::Memory) => true,
522 self.opts.debugging_opts.fewer_names || !more_names
525 pub fn no_landing_pads(&self) -> bool {
526 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
528 pub fn unstable_options(&self) -> bool {
529 self.opts.debugging_opts.unstable_options
531 pub fn overflow_checks(&self) -> bool {
535 .or(self.opts.debugging_opts.force_overflow_checks)
536 .unwrap_or(self.opts.debug_assertions)
539 pub fn crt_static(&self) -> bool {
540 // If the target does not opt in to crt-static support, use its default.
541 if self.target.target.options.crt_static_respected {
542 self.crt_static_feature()
544 self.target.target.options.crt_static_default
548 pub fn crt_static_feature(&self) -> bool {
549 let requested_features = self.opts.cg.target_feature.split(',');
550 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
551 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
553 // If the target we're compiling for requests a static crt by default,
554 // then see if the `-crt-static` feature was passed to disable that.
555 // Otherwise if we don't have a static crt by default then see if the
556 // `+crt-static` feature was passed.
557 if self.target.target.options.crt_static_default { !found_negative } else { found_positive }
560 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
561 // "mcount" function relies on stack pointer.
562 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
563 if self.instrument_mcount() {
565 } else if let Some(x) = self.opts.cg.force_frame_pointers {
568 !self.target.target.options.eliminate_frame_pointer
572 /// Returns the symbol name for the registrar function,
573 /// given the crate `Svh` and the function `DefIndex`.
574 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
575 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
578 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
579 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
582 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
583 filesearch::FileSearch::new(
585 self.opts.target_triple.triple(),
586 &self.opts.search_paths,
587 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
588 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
592 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
593 filesearch::FileSearch::new(
595 config::host_triple(),
596 &self.opts.search_paths,
597 &self.host_tlib_path,
602 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
603 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
605 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
606 *load_dep_graph = load;
610 pub fn incr_session_load_dep_graph(&self) -> bool {
611 let incr_comp_session = self.incr_comp_session.borrow();
612 match *incr_comp_session {
613 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
618 pub fn init_incr_comp_session(
620 session_dir: PathBuf,
621 lock_file: flock::Lock,
622 load_dep_graph: bool,
624 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
626 if let IncrCompSession::NotInitialized = *incr_comp_session {
628 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
632 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
635 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
636 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
638 if let IncrCompSession::Active { .. } = *incr_comp_session {
640 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
643 // Note: this will also drop the lock file, thus unlocking the directory.
644 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
647 pub fn mark_incr_comp_session_as_invalid(&self) {
648 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
650 let session_directory = match *incr_comp_session {
651 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
652 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
653 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
656 // Note: this will also drop the lock file, thus unlocking the directory.
657 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
660 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
661 let incr_comp_session = self.incr_comp_session.borrow();
662 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
663 IncrCompSession::NotInitialized => panic!(
664 "trying to get session directory from `IncrCompSession`: {:?}",
667 IncrCompSession::Active { ref session_directory, .. }
668 | IncrCompSession::Finalized { ref session_directory }
669 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
675 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
676 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
679 pub fn print_perf_stats(&self) {
681 "Total time spent computing symbol hashes: {}",
682 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
685 "Total time spent decoding DefPath tables: {}",
686 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
689 "Total queries canonicalized: {}",
690 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
693 "normalize_ty_after_erasing_regions: {}",
694 self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed)
697 "normalize_projection_ty: {}",
698 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
702 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
703 /// This expends fuel if applicable, and records fuel if applicable.
704 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
706 if let Some(ref c) = self.optimization_fuel_crate {
708 assert_eq!(self.threads(), 1);
709 let mut fuel = self.optimization_fuel.lock();
710 ret = fuel.remaining != 0;
711 if fuel.remaining == 0 && !fuel.out_of_fuel {
712 eprintln!("optimization-fuel-exhausted: {}", msg());
713 fuel.out_of_fuel = true;
714 } else if fuel.remaining > 0 {
719 if let Some(ref c) = self.print_fuel_crate {
721 assert_eq!(self.threads(), 1);
722 self.print_fuel.fetch_add(1, SeqCst);
728 /// Returns the number of query threads that should be used for this
730 pub fn threads(&self) -> usize {
731 self.opts.debugging_opts.threads
734 /// Returns the number of codegen units that should be used for this
736 pub fn codegen_units(&self) -> usize {
737 if let Some(n) = self.opts.cli_forced_codegen_units {
740 if let Some(n) = self.target.target.options.default_codegen_units {
744 // Why is 16 codegen units the default all the time?
746 // The main reason for enabling multiple codegen units by default is to
747 // leverage the ability for the codegen backend to do codegen and
748 // optimization in parallel. This allows us, especially for large crates, to
749 // make good use of all available resources on the machine once we've
750 // hit that stage of compilation. Large crates especially then often
751 // take a long time in codegen/optimization and this helps us amortize that
754 // Note that a high number here doesn't mean that we'll be spawning a
755 // large number of threads in parallel. The backend of rustc contains
756 // global rate limiting through the `jobserver` crate so we'll never
757 // overload the system with too much work, but rather we'll only be
758 // optimizing when we're otherwise cooperating with other instances of
761 // Rather a high number here means that we should be able to keep a lot
762 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
763 // to build we'll be guaranteed that all cpus will finish pretty closely
764 // to one another and we should make relatively optimal use of system
767 // Note that the main cost of codegen units is that it prevents LLVM
768 // from inlining across codegen units. Users in general don't have a lot
769 // of control over how codegen units are split up so it's our job in the
770 // compiler to ensure that undue performance isn't lost when using
771 // codegen units (aka we can't require everyone to slap `#[inline]` on
774 // If we're compiling at `-O0` then the number doesn't really matter too
775 // much because performance doesn't matter and inlining is ok to lose.
776 // In debug mode we just want to try to guarantee that no cpu is stuck
777 // doing work that could otherwise be farmed to others.
779 // In release mode, however (O1 and above) performance does indeed
780 // matter! To recover the loss in performance due to inlining we'll be
781 // enabling ThinLTO by default (the function for which is just below).
782 // This will ensure that we recover any inlining wins we otherwise lost
783 // through codegen unit partitioning.
787 // Ok that's a lot of words but the basic tl;dr; is that we want a high
788 // number here -- but not too high. Additionally we're "safe" to have it
789 // always at the same number at all optimization levels.
791 // As a result 16 was chosen here! Mostly because it was a power of 2
792 // and most benchmarks agreed it was roughly a local optimum. Not very
797 pub fn teach(&self, code: &DiagnosticId) -> bool {
798 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
801 pub fn rust_2015(&self) -> bool {
802 self.opts.edition == Edition::Edition2015
805 /// Are we allowed to use features from the Rust 2018 edition?
806 pub fn rust_2018(&self) -> bool {
807 self.opts.edition >= Edition::Edition2018
810 pub fn edition(&self) -> Edition {
814 /// Returns `true` if we cannot skip the PLT for shared library calls.
815 pub fn needs_plt(&self) -> bool {
816 // Check if the current target usually needs PLT to be enabled.
817 // The user can use the command line flag to override it.
818 let needs_plt = self.target.target.options.needs_plt;
820 let dbg_opts = &self.opts.debugging_opts;
822 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
824 // Only enable this optimization by default if full relro is also enabled.
825 // In this case, lazy binding was already unavailable, so nothing is lost.
826 // This also ensures `-Wl,-z,now` is supported by the linker.
827 let full_relro = RelroLevel::Full == relro_level;
829 // If user didn't explicitly forced us to use / skip the PLT,
830 // then try to skip it where possible.
831 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
835 pub fn build_session(
836 sopts: config::Options,
837 local_crate_source_file: Option<PathBuf>,
838 registry: rustc_errors::registry::Registry,
840 let file_path_mapping = sopts.file_path_mapping();
842 build_session_with_source_map(
844 local_crate_source_file,
846 Lrc::new(source_map::SourceMap::new(file_path_mapping)),
847 DiagnosticOutput::Default,
853 sopts: &config::Options,
854 registry: rustc_errors::registry::Registry,
855 source_map: &Lrc<source_map::SourceMap>,
856 emitter_dest: Option<Box<dyn Write + Send>>,
857 ) -> Box<dyn Emitter + sync::Send> {
858 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
859 match (sopts.error_format, emitter_dest) {
860 (config::ErrorOutputType::HumanReadable(kind), dst) => {
861 let (short, color_config) = kind.unzip();
863 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
864 let emitter = AnnotateSnippetEmitterWriter::new(
865 Some(source_map.clone()),
867 external_macro_backtrace,
869 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing()))
871 let emitter = match dst {
872 None => EmitterWriter::stderr(
874 Some(source_map.clone()),
876 sopts.debugging_opts.teach,
877 sopts.debugging_opts.terminal_width,
878 external_macro_backtrace,
880 Some(dst) => EmitterWriter::new(
882 Some(source_map.clone()),
884 false, // no teach messages when writing to a buffer
885 false, // no colors when writing to a buffer
886 None, // no terminal width
887 external_macro_backtrace,
890 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing()))
893 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
899 external_macro_backtrace,
901 .ui_testing(sopts.debugging_opts.ui_testing()),
903 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
910 external_macro_backtrace,
912 .ui_testing(sopts.debugging_opts.ui_testing()),
917 pub enum DiagnosticOutput {
919 Raw(Box<dyn Write + Send>),
922 pub fn build_session_with_source_map(
923 sopts: config::Options,
924 local_crate_source_file: Option<PathBuf>,
925 registry: rustc_errors::registry::Registry,
926 source_map: Lrc<source_map::SourceMap>,
927 diagnostics_output: DiagnosticOutput,
928 lint_caps: FxHashMap<lint::LintId, lint::Level>,
930 // FIXME: This is not general enough to make the warning lint completely override
931 // normal diagnostic warnings, since the warning lint can also be denied and changed
932 // later via the source code.
933 let warnings_allow = sopts
936 .filter(|&&(ref key, _)| *key == "warnings")
937 .map(|&(_, ref level)| *level == lint::Allow)
940 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
941 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
943 let write_dest = match diagnostics_output {
944 DiagnosticOutput::Default => None,
945 DiagnosticOutput::Raw(write) => Some(write),
947 let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
949 let diagnostic_handler = rustc_errors::Handler::with_emitter_and_flags(
951 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
954 build_session_(sopts, local_crate_source_file, diagnostic_handler, source_map, lint_caps)
958 sopts: config::Options,
959 local_crate_source_file: Option<PathBuf>,
960 span_diagnostic: rustc_errors::Handler,
961 source_map: Lrc<source_map::SourceMap>,
962 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
964 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
967 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
969 let profiler = SelfProfiler::new(
971 sopts.crate_name.as_ref().map(|s| &s[..]),
972 &sopts.debugging_opts.self_profile_events,
975 Ok(profiler) => Some(Arc::new(profiler)),
977 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
985 let host_triple = TargetTriple::from_triple(config::host_triple());
986 let host = Target::search(&host_triple).unwrap_or_else(|e| {
987 span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise()
989 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
991 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
992 let sysroot = match &sopts.maybe_sysroot {
993 Some(sysroot) => sysroot.clone(),
994 None => filesearch::get_or_default_sysroot(),
997 let host_triple = config::host_triple();
998 let target_triple = sopts.target_triple.triple();
999 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1000 let target_tlib_path = if host_triple == target_triple {
1003 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1006 let file_path_mapping = sopts.file_path_mapping();
1008 let local_crate_source_file =
1009 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1011 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1012 let optimization_fuel = Lock::new(OptimizationFuel {
1013 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1016 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1017 let print_fuel = AtomicU64::new(0);
1019 let working_dir = env::current_dir().unwrap_or_else(|e| {
1020 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1022 let working_dir = file_path_mapping.map_prefix(working_dir);
1024 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1025 CguReuseTracker::new()
1027 CguReuseTracker::new_disabled()
1030 let prof = SelfProfilerRef::new(
1032 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1033 sopts.debugging_opts.time_passes,
1036 let sess = Session {
1044 local_crate_source_file,
1046 one_time_diagnostics: Default::default(),
1047 crate_types: Once::new(),
1048 crate_disambiguator: Once::new(),
1049 features: Once::new(),
1050 recursion_limit: Once::new(),
1051 type_length_limit: Once::new(),
1052 imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())),
1053 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1056 perf_stats: PerfStats {
1057 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1058 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1059 queries_canonicalized: AtomicUsize::new(0),
1060 normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1061 normalize_projection_ty: AtomicUsize::new(0),
1063 code_stats: Default::default(),
1064 optimization_fuel_crate,
1068 jobserver: jobserver::client(),
1070 trait_methods_not_found: Lock::new(Default::default()),
1071 confused_type_with_std_module: Lock::new(Default::default()),
1074 validate_commandline_args_with_session_available(&sess);
1079 // If it is useful to have a Session available already for validating a
1080 // commandline argument, you can do so here.
1081 fn validate_commandline_args_with_session_available(sess: &Session) {
1082 // Since we don't know if code in an rlib will be linked to statically or
1083 // dynamically downstream, rustc generates `__imp_` symbols that help the
1084 // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1085 // these manually generated symbols confuse LLD when it tries to merge
1086 // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1087 // when compiling for LLD ThinLTO. This way we can validly just not generate
1088 // the `dllimport` attributes and `__imp_` symbols in that case.
1089 if sess.opts.cg.linker_plugin_lto.enabled()
1090 && sess.opts.cg.prefer_dynamic
1091 && sess.target.target.options.is_like_msvc
1094 "Linker plugin based LTO is not supported together with \
1095 `-C prefer-dynamic` when targeting MSVC",
1099 // Make sure that any given profiling data actually exists so LLVM can't
1100 // decide to silently skip PGO.
1101 if let Some(ref path) = sess.opts.cg.profile_use {
1104 "File `{}` passed to `-C profile-use` does not exist.",
1110 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1111 // an error to combine the two for now. It always runs into an assertions
1112 // if LLVM is built with assertions, but without assertions it sometimes
1113 // does not crash and will probably generate a corrupted binary.
1114 // We should only display this error if we're actually going to run PGO.
1115 // If we're just supposed to print out some data, don't show the error (#61002).
1116 if sess.opts.cg.profile_generate.enabled()
1117 && sess.target.target.options.is_like_msvc
1118 && sess.panic_strategy() == PanicStrategy::Unwind
1119 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1122 "Profile-guided optimization does not yet work in conjunction \
1123 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1124 See https://github.com/rust-lang/rust/issues/61002 for details.",
1128 // Sanitizers can only be used on some tested platforms.
1129 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
1130 const ASAN_SUPPORTED_TARGETS: &[&str] =
1131 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1132 const TSAN_SUPPORTED_TARGETS: &[&str] =
1133 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1134 const LSAN_SUPPORTED_TARGETS: &[&str] =
1135 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1136 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
1138 let supported_targets = match *sanitizer {
1139 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
1140 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
1141 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
1142 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
1145 if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1147 "{:?}Sanitizer only works with the `{}` target",
1149 supported_targets.join("` or `")
1155 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1156 /// compiler. Together with the crate-name forms a unique global identifier for
1158 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1159 pub struct CrateDisambiguator(Fingerprint);
1161 impl CrateDisambiguator {
1162 pub fn to_fingerprint(self) -> Fingerprint {
1167 impl fmt::Display for CrateDisambiguator {
1168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1169 let (a, b) = self.0.as_value();
1170 let as_u128 = a as u128 | ((b as u128) << 64);
1171 f.write_str(&base_n::encode(as_u128, base_n::CASE_INSENSITIVE))
1175 impl From<Fingerprint> for CrateDisambiguator {
1176 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1177 CrateDisambiguator(fingerprint)
1181 impl_stable_hash_via_hash!(CrateDisambiguator);
1183 /// Holds data on the current incremental compilation session, if there is one.
1185 pub enum IncrCompSession {
1186 /// This is the state the session will be in until the incr. comp. dir is
1189 /// This is the state during which the session directory is private and can
1191 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1192 /// This is the state after the session directory has been finalized. In this
1193 /// state, the contents of the directory must not be modified any more.
1194 Finalized { session_directory: PathBuf },
1195 /// This is an error state that is reached when some compilation error has
1196 /// occurred. It indicates that the contents of the session directory must
1197 /// not be used, since they might be invalid.
1198 InvalidBecauseOfErrors { session_directory: PathBuf },
1201 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1202 let emitter: Box<dyn Emitter + sync::Send> = match output {
1203 config::ErrorOutputType::HumanReadable(kind) => {
1204 let (short, color_config) = kind.unzip();
1205 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1207 config::ErrorOutputType::Json { pretty, json_rendered } => {
1208 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1211 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1212 handler.struct_fatal(msg).emit();
1213 rustc_errors::FatalError.raise();
1216 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1217 let emitter: Box<dyn Emitter + sync::Send> = match output {
1218 config::ErrorOutputType::HumanReadable(kind) => {
1219 let (short, color_config) = kind.unzip();
1220 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1222 config::ErrorOutputType::Json { pretty, json_rendered } => {
1223 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1226 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1227 handler.struct_warn(msg).emit();
1230 pub type CompileResult = Result<(), ErrorReported>;