1 pub use self::code_stats::{DataTypeKind, SizeKind, FieldInfo, VariantInfo};
2 use self::code_stats::CodeStats;
4 use crate::dep_graph::cgu_reuse_tracker::CguReuseTracker;
5 use crate::hir::def_id::CrateNum;
6 use rustc_data_structures::fingerprint::Fingerprint;
9 use crate::lint::builtin::BuiltinLintDiagnostics;
10 use crate::middle::allocator::AllocatorKind;
11 use crate::middle::dependency_format;
12 use crate::session::config::{OutputType, SwitchWithOptPath};
13 use crate::session::search_paths::{PathKind, SearchPath};
14 use crate::util::nodemap::{FxHashMap, FxHashSet};
15 use crate::util::common::{duration_to_secs_str, ErrorReported};
16 use crate::util::common::ProfileQueriesMsg;
18 use rustc_data_structures::base_n;
19 use rustc_data_structures::sync::{
20 self, Lrc, Lock, OneThread, Once, RwLock, AtomicU64, AtomicUsize, Ordering,
24 use errors::{DiagnosticBuilder, DiagnosticId, Applicability};
25 use errors::emitter::{Emitter, EmitterWriter};
26 use errors::emitter::HumanReadableErrorType;
27 use errors::annotate_snippet_emitter_writer::{AnnotateSnippetEmitterWriter};
28 use syntax::ast::{self, NodeId};
29 use syntax::edition::Edition;
30 use syntax::feature_gate::{self, AttributeType};
31 use syntax::json::JsonEmitter;
32 use syntax::source_map;
33 use syntax::parse::{self, ParseSess};
34 use syntax::symbol::Symbol;
35 use syntax_pos::{MultiSpan, Span};
36 use crate::util::profiling::SelfProfiler;
38 use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
39 use rustc_data_structures::flock;
40 use rustc_data_structures::jobserver;
41 use ::jobserver::Client;
44 use std::cell::{self, Cell, RefCell};
48 use std::path::PathBuf;
49 use std::time::Duration;
50 use std::sync::{Arc, mpsc};
57 pub struct OptimizationFuel {
58 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
60 /// We're rejecting all further optimizations.
64 /// Represents the data associated with a compilation
65 /// session for a single crate.
67 pub target: config::Config,
69 pub opts: config::Options,
70 pub host_tlib_path: SearchPath,
71 /// `None` if the host and target are the same.
72 pub target_tlib_path: Option<SearchPath>,
73 pub parse_sess: ParseSess,
75 /// The name of the root source file of the crate, in the local file system.
76 /// `None` means that there is no source file.
77 pub local_crate_source_file: Option<PathBuf>,
78 /// The directory the compiler has been executed in plus a flag indicating
79 /// if the value stored here has been affected by path remapping.
80 pub working_dir: (PathBuf, bool),
82 // FIXME: lint_store and buffered_lints are not thread-safe,
83 // but are only used in a single thread
84 pub lint_store: RwLock<lint::LintStore>,
85 pub buffered_lints: Lock<Option<lint::LintBuffer>>,
87 /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
88 /// (sub)diagnostics that have been set once, but should not be set again,
89 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
90 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
91 pub plugin_llvm_passes: OneThread<RefCell<Vec<String>>>,
92 pub plugin_attributes: Lock<Vec<(Symbol, AttributeType)>>,
93 pub crate_types: Once<Vec<config::CrateType>>,
94 pub dependency_formats: Once<dependency_format::Dependencies>,
95 /// The crate_disambiguator is constructed out of all the `-C metadata`
96 /// arguments passed to the compiler. Its value together with the crate-name
97 /// forms a unique global identifier for the crate. It is used to allow
98 /// multiple crates with the same name to coexist. See the
99 /// rustc_codegen_llvm::back::symbol_names module for more information.
100 pub crate_disambiguator: Once<CrateDisambiguator>,
102 features: Once<feature_gate::Features>,
104 /// The maximum recursion limit for potentially infinitely recursive
105 /// operations such as auto-dereference and monomorphization.
106 pub recursion_limit: Once<usize>,
108 /// The maximum length of types during monomorphization.
109 pub type_length_limit: Once<usize>,
111 /// The maximum number of stackframes allowed in const eval.
112 pub const_eval_stack_frame_limit: usize,
114 /// The metadata::creader module may inject an allocator/panic_runtime
115 /// dependency if it didn't already find one, and this tracks what was
117 pub allocator_kind: Once<Option<AllocatorKind>>,
118 pub injected_panic_runtime: Once<Option<CrateNum>>,
120 /// Map from imported macro spans (which consist of
121 /// the localized span for the macro body) to the
122 /// macro name and definition span in the source crate.
123 pub imported_macro_spans: OneThread<RefCell<FxHashMap<Span, (String, Span)>>>,
125 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
126 /// Used for incremental compilation tests. Will only be populated if
127 /// `-Zquery-dep-graph` is specified.
128 pub cgu_reuse_tracker: CguReuseTracker,
130 /// Used by `-Z profile-queries` in `util::common`.
131 pub profile_channel: Lock<Option<mpsc::Sender<ProfileQueriesMsg>>>,
133 /// Used by -Z self-profile
134 pub self_profiling: Option<Arc<SelfProfiler>>,
136 /// Some measurements that are being gathered during compilation.
137 pub perf_stats: PerfStats,
139 /// Data about code being compiled, gathered during compilation.
140 pub code_stats: Lock<CodeStats>,
142 next_node_id: OneThread<Cell<ast::NodeId>>,
144 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
145 optimization_fuel_crate: Option<String>,
147 /// Tracks fuel info if `-zfuel=crate=n` is specified.
148 optimization_fuel: Lock<OptimizationFuel>,
150 // The next two are public because the driver needs to read them.
151 /// If `-zprint-fuel=crate`, `Some(crate)`.
152 pub print_fuel_crate: Option<String>,
153 /// Always set to zero and incremented so that we can print fuel expended by a crate.
154 pub print_fuel: AtomicU64,
156 /// Loaded up early on in the initialization of this `Session` to avoid
157 /// false positives about a job server in our environment.
158 pub jobserver: Client,
160 /// Metadata about the allocators for the current crate being compiled.
161 pub has_global_allocator: Once<bool>,
163 /// Metadata about the panic handlers for the current crate being compiled.
164 pub has_panic_handler: Once<bool>,
166 /// Cap lint level specified by a driver specifically.
167 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
169 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
170 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
172 /// Mapping from ident span to path span for paths that don't exist as written, but that
173 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
174 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
177 pub struct PerfStats {
178 /// The accumulated time spent on computing symbol hashes.
179 pub symbol_hash_time: Lock<Duration>,
180 /// The accumulated time spent decoding def path tables from metadata.
181 pub decode_def_path_tables_time: Lock<Duration>,
182 /// Total number of values canonicalized queries constructed.
183 pub queries_canonicalized: AtomicUsize,
184 /// Number of times this query is invoked.
185 pub normalize_ty_after_erasing_regions: AtomicUsize,
186 /// Number of times this query is invoked.
187 pub normalize_projection_ty: AtomicUsize,
190 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
191 enum DiagnosticBuilderMethod {
194 SpanSuggestion(String), // suggestion
195 // add more variants as needed to support one-time diagnostics
198 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
199 /// emitting the same message more than once
200 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
201 pub enum DiagnosticMessageId {
202 ErrorId(u16), // EXXXX error code as integer
203 LintId(lint::LintId),
204 StabilityId(u32), // issue number
207 impl From<&'static lint::Lint> for DiagnosticMessageId {
208 fn from(lint: &'static lint::Lint) -> Self {
209 DiagnosticMessageId::LintId(lint::LintId::of(lint))
214 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
215 *self.crate_disambiguator.get()
218 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(
222 ) -> DiagnosticBuilder<'a> {
223 self.diagnostic().struct_span_warn(sp, msg)
225 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(
230 ) -> DiagnosticBuilder<'a> {
231 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
233 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
234 self.diagnostic().struct_warn(msg)
236 pub fn struct_span_err<'a, S: Into<MultiSpan>>(
240 ) -> DiagnosticBuilder<'a> {
241 self.diagnostic().struct_span_err(sp, msg)
243 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(
248 ) -> DiagnosticBuilder<'a> {
249 self.diagnostic().struct_span_err_with_code(sp, msg, code)
251 // FIXME: This method should be removed (every error should have an associated error code).
252 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
253 self.diagnostic().struct_err(msg)
255 pub fn struct_err_with_code<'a>(
259 ) -> DiagnosticBuilder<'a> {
260 self.diagnostic().struct_err_with_code(msg, code)
262 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(
266 ) -> DiagnosticBuilder<'a> {
267 self.diagnostic().struct_span_fatal(sp, msg)
269 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(
274 ) -> DiagnosticBuilder<'a> {
275 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
277 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
278 self.diagnostic().struct_fatal(msg)
281 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
282 self.diagnostic().span_fatal(sp, msg).raise()
284 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
291 .span_fatal_with_code(sp, msg, code)
294 pub fn fatal(&self, msg: &str) -> ! {
295 self.diagnostic().fatal(msg).raise()
297 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
299 self.span_warn(sp, msg);
301 self.span_err(sp, msg);
304 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
305 self.diagnostic().span_err(sp, msg)
307 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
308 self.diagnostic().span_err_with_code(sp, &msg, code)
310 pub fn err(&self, msg: &str) {
311 self.diagnostic().err(msg)
313 pub fn err_count(&self) -> usize {
314 self.diagnostic().err_count()
316 pub fn has_errors(&self) -> bool {
317 self.diagnostic().has_errors()
319 pub fn abort_if_errors(&self) {
320 self.diagnostic().abort_if_errors();
322 pub fn compile_status(&self) -> Result<(), ErrorReported> {
323 if self.has_errors() {
329 // FIXME(matthewjasper) Remove this method, it should never be needed.
330 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
334 let old_count = self.err_count();
336 let errors = self.err_count() - old_count;
343 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
344 self.diagnostic().span_warn(sp, msg)
346 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
347 self.diagnostic().span_warn_with_code(sp, msg, code)
349 pub fn warn(&self, msg: &str) {
350 self.diagnostic().warn(msg)
352 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
354 Some(sp) => self.span_warn(sp, msg),
355 None => self.warn(msg),
358 /// Delay a span_bug() call until abort_if_errors()
359 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
360 self.diagnostic().delay_span_bug(sp, msg)
362 pub fn note_without_error(&self, msg: &str) {
363 self.diagnostic().note_without_error(msg)
365 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
366 self.diagnostic().span_note_without_error(sp, msg)
368 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
369 self.diagnostic().span_unimpl(sp, msg)
371 pub fn unimpl(&self, msg: &str) -> ! {
372 self.diagnostic().unimpl(msg)
375 pub fn buffer_lint<S: Into<MultiSpan>>(
377 lint: &'static lint::Lint,
382 match *self.buffered_lints.borrow_mut() {
383 Some(ref mut buffer) => {
384 buffer.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
386 None => bug!("can't buffer lints after HIR lowering"),
390 pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(
392 lint: &'static lint::Lint,
396 diagnostic: BuiltinLintDiagnostics,
398 match *self.buffered_lints.borrow_mut() {
399 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg, diagnostic),
400 None => bug!("can't buffer lints after HIR lowering"),
404 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
405 let id = self.next_node_id.get();
407 match id.as_usize().checked_add(count) {
409 self.next_node_id.set(ast::NodeId::from_usize(next));
411 None => bug!("Input too large, ran out of node ids!"),
416 pub fn next_node_id(&self) -> NodeId {
417 self.reserve_node_ids(1)
419 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
420 &self.parse_sess.span_diagnostic
423 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
424 /// deduplicates on lint ID, span (if any), and message for this `Session`
425 fn diag_once<'a, 'b>(
427 diag_builder: &'b mut DiagnosticBuilder<'a>,
428 method: DiagnosticBuilderMethod,
429 msg_id: DiagnosticMessageId,
431 span_maybe: Option<Span>,
433 let id_span_message = (msg_id, span_maybe, message.to_owned());
434 let fresh = self.one_time_diagnostics
436 .insert(id_span_message);
439 DiagnosticBuilderMethod::Note => {
440 diag_builder.note(message);
442 DiagnosticBuilderMethod::SpanNote => {
443 let span = span_maybe.expect("span_note needs a span");
444 diag_builder.span_note(span, message);
446 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
447 let span = span_maybe.expect("span_suggestion_* needs a span");
448 diag_builder.span_suggestion(
452 Applicability::Unspecified,
459 pub fn diag_span_note_once<'a, 'b>(
461 diag_builder: &'b mut DiagnosticBuilder<'a>,
462 msg_id: DiagnosticMessageId,
468 DiagnosticBuilderMethod::SpanNote,
475 pub fn diag_note_once<'a, 'b>(
477 diag_builder: &'b mut DiagnosticBuilder<'a>,
478 msg_id: DiagnosticMessageId,
483 DiagnosticBuilderMethod::Note,
490 pub fn diag_span_suggestion_once<'a, 'b>(
492 diag_builder: &'b mut DiagnosticBuilder<'a>,
493 msg_id: DiagnosticMessageId,
500 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
507 pub fn source_map<'a>(&'a self) -> &'a source_map::SourceMap {
508 self.parse_sess.source_map()
510 pub fn verbose(&self) -> bool {
511 self.opts.debugging_opts.verbose
513 pub fn time_passes(&self) -> bool {
514 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
516 pub fn time_extended(&self) -> bool {
517 self.opts.debugging_opts.time_passes
519 pub fn profile_queries(&self) -> bool {
520 self.opts.debugging_opts.profile_queries
521 || self.opts.debugging_opts.profile_queries_and_keys
523 pub fn profile_queries_and_keys(&self) -> bool {
524 self.opts.debugging_opts.profile_queries_and_keys
526 pub fn instrument_mcount(&self) -> bool {
527 self.opts.debugging_opts.instrument_mcount
529 pub fn time_llvm_passes(&self) -> bool {
530 self.opts.debugging_opts.time_llvm_passes
532 pub fn meta_stats(&self) -> bool {
533 self.opts.debugging_opts.meta_stats
535 pub fn asm_comments(&self) -> bool {
536 self.opts.debugging_opts.asm_comments
538 pub fn verify_llvm_ir(&self) -> bool {
539 self.opts.debugging_opts.verify_llvm_ir
540 || cfg!(always_verify_llvm_ir)
542 pub fn borrowck_stats(&self) -> bool {
543 self.opts.debugging_opts.borrowck_stats
545 pub fn print_llvm_passes(&self) -> bool {
546 self.opts.debugging_opts.print_llvm_passes
549 /// Gets the features enabled for the current compilation session.
550 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
551 /// dependency tracking. Use tcx.features() instead.
553 pub fn features_untracked(&self) -> &feature_gate::Features {
557 pub fn init_features(&self, features: feature_gate::Features) {
558 self.features.set(features);
561 /// Calculates the flavor of LTO to use for this compilation.
562 pub fn lto(&self) -> config::Lto {
563 // If our target has codegen requirements ignore the command line
564 if self.target.target.options.requires_lto {
565 return config::Lto::Fat;
568 // If the user specified something, return that. If they only said `-C
569 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
570 // then ensure we can't use a ThinLTO.
571 match self.opts.cg.lto {
572 config::LtoCli::Unspecified => {
573 // The compiler was invoked without the `-Clto` flag. Fall
574 // through to the default handling
576 config::LtoCli::No => {
577 // The user explicitly opted out of any kind of LTO
578 return config::Lto::No;
580 config::LtoCli::Yes |
581 config::LtoCli::Fat |
582 config::LtoCli::NoParam => {
583 // All of these mean fat LTO
584 return config::Lto::Fat;
586 config::LtoCli::Thin => {
587 return if self.opts.cli_forced_thinlto_off {
595 // Ok at this point the target doesn't require anything and the user
596 // hasn't asked for anything. Our next decision is whether or not
597 // we enable "auto" ThinLTO where we use multiple codegen units and
598 // then do ThinLTO over those codegen units. The logic below will
599 // either return `No` or `ThinLocal`.
601 // If processing command line options determined that we're incompatible
602 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
603 if self.opts.cli_forced_thinlto_off {
604 return config::Lto::No;
607 // If `-Z thinlto` specified process that, but note that this is mostly
608 // a deprecated option now that `-C lto=thin` exists.
609 if let Some(enabled) = self.opts.debugging_opts.thinlto {
611 return config::Lto::ThinLocal;
613 return config::Lto::No;
617 // If there's only one codegen unit and LTO isn't enabled then there's
618 // no need for ThinLTO so just return false.
619 if self.codegen_units() == 1 {
620 return config::Lto::No;
623 // Now we're in "defaults" territory. By default we enable ThinLTO for
624 // optimized compiles (anything greater than O0).
625 match self.opts.optimize {
626 config::OptLevel::No => config::Lto::No,
627 _ => config::Lto::ThinLocal,
631 /// Returns the panic strategy for this compile session. If the user explicitly selected one
632 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
633 pub fn panic_strategy(&self) -> PanicStrategy {
637 .unwrap_or(self.target.target.options.panic_strategy)
639 pub fn fewer_names(&self) -> bool {
640 let more_names = self.opts
642 .contains_key(&OutputType::LlvmAssembly)
643 || self.opts.output_types.contains_key(&OutputType::Bitcode);
644 self.opts.debugging_opts.fewer_names || !more_names
647 pub fn no_landing_pads(&self) -> bool {
648 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
650 pub fn unstable_options(&self) -> bool {
651 self.opts.debugging_opts.unstable_options
653 pub fn overflow_checks(&self) -> bool {
657 .or(self.opts.debugging_opts.force_overflow_checks)
658 .unwrap_or(self.opts.debug_assertions)
661 pub fn crt_static(&self) -> bool {
662 // If the target does not opt in to crt-static support, use its default.
663 if self.target.target.options.crt_static_respected {
664 self.crt_static_feature()
666 self.target.target.options.crt_static_default
670 pub fn crt_static_feature(&self) -> bool {
671 let requested_features = self.opts.cg.target_feature.split(',');
672 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
673 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
675 // If the target we're compiling for requests a static crt by default,
676 // then see if the `-crt-static` feature was passed to disable that.
677 // Otherwise if we don't have a static crt by default then see if the
678 // `+crt-static` feature was passed.
679 if self.target.target.options.crt_static_default {
686 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
687 // "mcount" function relies on stack pointer.
688 // See https://sourceware.org/binutils/docs/gprof/Implementation.html
689 if self.instrument_mcount() {
691 } else if let Some(x) = self.opts.cg.force_frame_pointers {
694 !self.target.target.options.eliminate_frame_pointer
698 /// Returns the symbol name for the registrar function,
699 /// given the crate Svh and the function DefIndex.
700 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
702 "__rustc_plugin_registrar_{}__",
703 disambiguator.to_fingerprint().to_hex()
707 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
709 "__rustc_proc_macro_decls_{}__",
710 disambiguator.to_fingerprint().to_hex()
714 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
715 filesearch::FileSearch::new(
717 self.opts.target_triple.triple(),
718 &self.opts.search_paths,
719 // target_tlib_path==None means it's the same as host_tlib_path.
720 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
724 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
725 filesearch::FileSearch::new(
727 config::host_triple(),
728 &self.opts.search_paths,
729 &self.host_tlib_path,
734 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
735 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
737 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
738 *load_dep_graph = load;
742 pub fn incr_session_load_dep_graph(&self) -> bool {
743 let incr_comp_session = self.incr_comp_session.borrow();
744 match *incr_comp_session {
745 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
750 pub fn init_incr_comp_session(
752 session_dir: PathBuf,
753 lock_file: flock::Lock,
754 load_dep_graph: bool,
756 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
758 if let IncrCompSession::NotInitialized = *incr_comp_session {
761 "Trying to initialize IncrCompSession `{:?}`",
766 *incr_comp_session = IncrCompSession::Active {
767 session_directory: session_dir,
773 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
774 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
776 if let IncrCompSession::Active { .. } = *incr_comp_session {
779 "Trying to finalize IncrCompSession `{:?}`",
784 // Note: This will also drop the lock file, thus unlocking the directory
785 *incr_comp_session = IncrCompSession::Finalized {
786 session_directory: new_directory_path,
790 pub fn mark_incr_comp_session_as_invalid(&self) {
791 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
793 let session_directory = match *incr_comp_session {
794 IncrCompSession::Active {
795 ref session_directory,
797 } => session_directory.clone(),
798 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
800 "Trying to invalidate IncrCompSession `{:?}`",
805 // Note: This will also drop the lock file, thus unlocking the directory
806 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
809 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
810 let incr_comp_session = self.incr_comp_session.borrow();
813 |incr_comp_session| match *incr_comp_session {
814 IncrCompSession::NotInitialized => bug!(
815 "Trying to get session directory from IncrCompSession `{:?}`",
818 IncrCompSession::Active {
819 ref session_directory,
822 | IncrCompSession::Finalized {
823 ref session_directory,
825 | IncrCompSession::InvalidBecauseOfErrors {
826 ref session_directory,
827 } => session_directory,
832 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
833 if self.opts.incremental.is_some() {
834 Some(self.incr_comp_session_dir())
842 fn profiler_active<F: FnOnce(&SelfProfiler) -> ()>(&self, f: F) {
843 match &self.self_profiling {
844 None => bug!("profiler_active() called but there was no profiler active"),
852 pub fn profiler<F: FnOnce(&SelfProfiler) -> ()>(&self, f: F) {
853 if unlikely!(self.self_profiling.is_some()) {
854 self.profiler_active(f)
858 pub fn print_perf_stats(&self) {
860 "Total time spent computing symbol hashes: {}",
861 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
864 "Total time spent decoding DefPath tables: {}",
865 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
867 println!("Total queries canonicalized: {}",
868 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed));
869 println!("normalize_ty_after_erasing_regions: {}",
870 self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed));
871 println!("normalize_projection_ty: {}",
872 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed));
875 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
876 /// This expends fuel if applicable, and records fuel if applicable.
877 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
879 if let Some(ref c) = self.optimization_fuel_crate {
881 assert_eq!(self.threads(), 1);
882 let mut fuel = self.optimization_fuel.lock();
883 ret = fuel.remaining != 0;
884 if fuel.remaining == 0 && !fuel.out_of_fuel {
885 eprintln!("optimization-fuel-exhausted: {}", msg());
886 fuel.out_of_fuel = true;
887 } else if fuel.remaining > 0 {
892 if let Some(ref c) = self.print_fuel_crate {
894 assert_eq!(self.threads(), 1);
895 self.print_fuel.fetch_add(1, SeqCst);
901 /// Returns the number of query threads that should be used for this
903 pub fn threads_from_count(query_threads: Option<usize>) -> usize {
904 query_threads.unwrap_or(::num_cpus::get())
907 /// Returns the number of query threads that should be used for this
909 pub fn threads(&self) -> usize {
910 Self::threads_from_count(self.opts.debugging_opts.threads)
913 /// Returns the number of codegen units that should be used for this
915 pub fn codegen_units(&self) -> usize {
916 if let Some(n) = self.opts.cli_forced_codegen_units {
919 if let Some(n) = self.target.target.options.default_codegen_units {
923 // Why is 16 codegen units the default all the time?
925 // The main reason for enabling multiple codegen units by default is to
926 // leverage the ability for the codegen backend to do codegen and
927 // optimization in parallel. This allows us, especially for large crates, to
928 // make good use of all available resources on the machine once we've
929 // hit that stage of compilation. Large crates especially then often
930 // take a long time in codegen/optimization and this helps us amortize that
933 // Note that a high number here doesn't mean that we'll be spawning a
934 // large number of threads in parallel. The backend of rustc contains
935 // global rate limiting through the `jobserver` crate so we'll never
936 // overload the system with too much work, but rather we'll only be
937 // optimizing when we're otherwise cooperating with other instances of
940 // Rather a high number here means that we should be able to keep a lot
941 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
942 // to build we'll be guaranteed that all cpus will finish pretty closely
943 // to one another and we should make relatively optimal use of system
946 // Note that the main cost of codegen units is that it prevents LLVM
947 // from inlining across codegen units. Users in general don't have a lot
948 // of control over how codegen units are split up so it's our job in the
949 // compiler to ensure that undue performance isn't lost when using
950 // codegen units (aka we can't require everyone to slap `#[inline]` on
953 // If we're compiling at `-O0` then the number doesn't really matter too
954 // much because performance doesn't matter and inlining is ok to lose.
955 // In debug mode we just want to try to guarantee that no cpu is stuck
956 // doing work that could otherwise be farmed to others.
958 // In release mode, however (O1 and above) performance does indeed
959 // matter! To recover the loss in performance due to inlining we'll be
960 // enabling ThinLTO by default (the function for which is just below).
961 // This will ensure that we recover any inlining wins we otherwise lost
962 // through codegen unit partitioning.
966 // Ok that's a lot of words but the basic tl;dr; is that we want a high
967 // number here -- but not too high. Additionally we're "safe" to have it
968 // always at the same number at all optimization levels.
970 // As a result 16 was chosen here! Mostly because it was a power of 2
971 // and most benchmarks agreed it was roughly a local optimum. Not very
976 pub fn teach(&self, code: &DiagnosticId) -> bool {
977 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
980 pub fn rust_2015(&self) -> bool {
981 self.opts.edition == Edition::Edition2015
984 /// Are we allowed to use features from the Rust 2018 edition?
985 pub fn rust_2018(&self) -> bool {
986 self.opts.edition >= Edition::Edition2018
989 pub fn edition(&self) -> Edition {
993 /// Returns `true` if we cannot skip the PLT for shared library calls.
994 pub fn needs_plt(&self) -> bool {
995 // Check if the current target usually needs PLT to be enabled.
996 // The user can use the command line flag to override it.
997 let needs_plt = self.target.target.options.needs_plt;
999 let dbg_opts = &self.opts.debugging_opts;
1001 let relro_level = dbg_opts.relro_level
1002 .unwrap_or(self.target.target.options.relro_level);
1004 // Only enable this optimization by default if full relro is also enabled.
1005 // In this case, lazy binding was already unavailable, so nothing is lost.
1006 // This also ensures `-Wl,-z,now` is supported by the linker.
1007 let full_relro = RelroLevel::Full == relro_level;
1009 // If user didn't explicitly forced us to use / skip the PLT,
1010 // then try to skip it where possible.
1011 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1015 pub fn build_session(
1016 sopts: config::Options,
1017 local_crate_source_file: Option<PathBuf>,
1018 registry: errors::registry::Registry,
1020 let file_path_mapping = sopts.file_path_mapping();
1022 build_session_with_source_map(
1024 local_crate_source_file,
1026 Lrc::new(source_map::SourceMap::new(file_path_mapping)),
1027 DiagnosticOutput::Default,
1033 sopts: &config::Options,
1034 registry: errors::registry::Registry,
1035 source_map: &Lrc<source_map::SourceMap>,
1036 emitter_dest: Option<Box<dyn Write + Send>>,
1037 ) -> Box<dyn Emitter + sync::Send> {
1038 match (sopts.error_format, emitter_dest) {
1039 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1040 let (short, color_config) = kind.unzip();
1042 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1043 let emitter = AnnotateSnippetEmitterWriter::new(
1044 Some(source_map.clone()),
1047 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1049 let emitter = match dst {
1050 None => EmitterWriter::stderr(
1052 Some(source_map.clone()),
1054 sopts.debugging_opts.teach,
1056 Some(dst) => EmitterWriter::new(
1058 Some(source_map.clone()),
1060 false, // no teach messages when writing to a buffer
1061 false, // no colors when writing to a buffer
1064 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1067 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1068 JsonEmitter::stderr(
1073 ).ui_testing(sopts.debugging_opts.ui_testing),
1075 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1082 ).ui_testing(sopts.debugging_opts.ui_testing),
1087 pub enum DiagnosticOutput {
1089 Raw(Box<dyn Write + Send>)
1092 pub fn build_session_with_source_map(
1093 sopts: config::Options,
1094 local_crate_source_file: Option<PathBuf>,
1095 registry: errors::registry::Registry,
1096 source_map: Lrc<source_map::SourceMap>,
1097 diagnostics_output: DiagnosticOutput,
1098 lint_caps: FxHashMap<lint::LintId, lint::Level>,
1100 // FIXME: This is not general enough to make the warning lint completely override
1101 // normal diagnostic warnings, since the warning lint can also be denied and changed
1102 // later via the source code.
1103 let warnings_allow = sopts
1106 .filter(|&&(ref key, _)| *key == "warnings")
1107 .map(|&(_, ref level)| *level == lint::Allow)
1110 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1112 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1114 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
1115 let dont_buffer_diagnostics = sopts.debugging_opts.dont_buffer_diagnostics;
1116 let report_delayed_bugs = sopts.debugging_opts.report_delayed_bugs;
1118 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
1120 let emitter = match diagnostics_output {
1121 DiagnosticOutput::Default => default_emitter(&sopts, registry, &source_map, None),
1122 DiagnosticOutput::Raw(write) => {
1123 default_emitter(&sopts, registry, &source_map, Some(write))
1127 let diagnostic_handler = errors::Handler::with_emitter_and_flags(
1129 errors::HandlerFlags {
1132 report_delayed_bugs,
1133 dont_buffer_diagnostics,
1134 external_macro_backtrace,
1135 ..Default::default()
1139 build_session_(sopts, local_crate_source_file, diagnostic_handler, source_map, lint_caps)
1143 sopts: config::Options,
1144 local_crate_source_file: Option<PathBuf>,
1145 span_diagnostic: errors::Handler,
1146 source_map: Lrc<source_map::SourceMap>,
1147 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1150 if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile {
1151 let directory = if let Some(ref directory) = d {
1154 std::path::Path::new(".")
1157 let profiler = SelfProfiler::new(
1159 sopts.crate_name.as_ref().map(|s| &s[..]),
1160 &sopts.debugging_opts.self_profile_events
1164 crate::ty::query::QueryName::register_with_profiler(&profiler);
1165 Some(Arc::new(profiler))
1168 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1175 let host_triple = TargetTriple::from_triple(config::host_triple());
1176 let host = Target::search(&host_triple).unwrap_or_else(|e|
1178 .fatal(&format!("Error loading host specification: {}", e))
1181 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
1183 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, source_map);
1184 let sysroot = match &sopts.maybe_sysroot {
1185 Some(sysroot) => sysroot.clone(),
1186 None => filesearch::get_or_default_sysroot(),
1189 let host_triple = config::host_triple();
1190 let target_triple = sopts.target_triple.triple();
1191 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1192 let target_tlib_path = if host_triple == target_triple {
1195 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1198 let file_path_mapping = sopts.file_path_mapping();
1200 let local_crate_source_file =
1201 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1203 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1204 let optimization_fuel = Lock::new(OptimizationFuel {
1205 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1208 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1209 let print_fuel = AtomicU64::new(0);
1211 let working_dir = env::current_dir().unwrap_or_else(|e|
1213 .fatal(&format!("Current directory is invalid: {}", e))
1216 let working_dir = file_path_mapping.map_prefix(working_dir);
1218 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1219 CguReuseTracker::new()
1221 CguReuseTracker::new_disabled()
1224 let sess = Session {
1232 local_crate_source_file,
1234 lint_store: RwLock::new(lint::LintStore::new()),
1235 buffered_lints: Lock::new(Some(Default::default())),
1236 one_time_diagnostics: Default::default(),
1237 plugin_llvm_passes: OneThread::new(RefCell::new(Vec::new())),
1238 plugin_attributes: Lock::new(Vec::new()),
1239 crate_types: Once::new(),
1240 dependency_formats: Once::new(),
1241 crate_disambiguator: Once::new(),
1242 features: Once::new(),
1243 recursion_limit: Once::new(),
1244 type_length_limit: Once::new(),
1245 const_eval_stack_frame_limit: 100,
1246 next_node_id: OneThread::new(Cell::new(NodeId::from_u32(1))),
1247 allocator_kind: Once::new(),
1248 injected_panic_runtime: Once::new(),
1249 imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())),
1250 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1252 self_profiling: self_profiler,
1253 profile_channel: Lock::new(None),
1254 perf_stats: PerfStats {
1255 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1256 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1257 queries_canonicalized: AtomicUsize::new(0),
1258 normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1259 normalize_projection_ty: AtomicUsize::new(0),
1261 code_stats: Default::default(),
1262 optimization_fuel_crate,
1266 jobserver: jobserver::client(),
1267 has_global_allocator: Once::new(),
1268 has_panic_handler: Once::new(),
1270 trait_methods_not_found: Lock::new(Default::default()),
1271 confused_type_with_std_module: Lock::new(Default::default()),
1274 validate_commandline_args_with_session_available(&sess);
1279 // If it is useful to have a Session available already for validating a
1280 // commandline argument, you can do so here.
1281 fn validate_commandline_args_with_session_available(sess: &Session) {
1282 // Since we don't know if code in an rlib will be linked to statically or
1283 // dynamically downstream, rustc generates `__imp_` symbols that help the
1284 // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1285 // these manually generated symbols confuse LLD when it tries to merge
1286 // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1287 // when compiling for LLD ThinLTO. This way we can validly just not generate
1288 // the `dllimport` attributes and `__imp_` symbols in that case.
1289 if sess.opts.cg.linker_plugin_lto.enabled() &&
1290 sess.opts.cg.prefer_dynamic &&
1291 sess.target.target.options.is_like_msvc {
1292 sess.err("Linker plugin based LTO is not supported together with \
1293 `-C prefer-dynamic` when targeting MSVC");
1296 // Make sure that any given profiling data actually exists so LLVM can't
1297 // decide to silently skip PGO.
1298 if let Some(ref path) = sess.opts.debugging_opts.pgo_use {
1300 sess.err(&format!("File `{}` passed to `-Zpgo-use` does not exist.",
1305 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1306 // an error to combine the two for now. It always runs into an assertions
1307 // if LLVM is built with assertions, but without assertions it sometimes
1308 // does not crash and will probably generate a corrupted binary.
1309 if sess.opts.debugging_opts.pgo_gen.enabled() &&
1310 sess.target.target.options.is_like_msvc &&
1311 sess.panic_strategy() == PanicStrategy::Unwind {
1312 sess.err("Profile-guided optimization does not yet work in conjunction \
1313 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1314 See https://github.com/rust-lang/rust/issues/61002 for details.");
1318 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1319 /// compiler. Together with the crate-name forms a unique global identifier for
1321 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1322 pub struct CrateDisambiguator(Fingerprint);
1324 impl CrateDisambiguator {
1325 pub fn to_fingerprint(self) -> Fingerprint {
1330 impl fmt::Display for CrateDisambiguator {
1331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1332 let (a, b) = self.0.as_value();
1333 let as_u128 = a as u128 | ((b as u128) << 64);
1334 f.write_str(&base_n::encode(as_u128, base_n::CASE_INSENSITIVE))
1338 impl From<Fingerprint> for CrateDisambiguator {
1339 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1340 CrateDisambiguator(fingerprint)
1344 impl_stable_hash_via_hash!(CrateDisambiguator);
1346 /// Holds data on the current incremental compilation session, if there is one.
1348 pub enum IncrCompSession {
1349 /// This is the state the session will be in until the incr. comp. dir is
1352 /// This is the state during which the session directory is private and can
1355 session_directory: PathBuf,
1356 lock_file: flock::Lock,
1357 load_dep_graph: bool,
1359 /// This is the state after the session directory has been finalized. In this
1360 /// state, the contents of the directory must not be modified any more.
1361 Finalized { session_directory: PathBuf },
1362 /// This is an error state that is reached when some compilation error has
1363 /// occurred. It indicates that the contents of the session directory must
1364 /// not be used, since they might be invalid.
1365 InvalidBecauseOfErrors { session_directory: PathBuf },
1368 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1369 let emitter: Box<dyn Emitter + sync::Send> = match output {
1370 config::ErrorOutputType::HumanReadable(kind) => {
1371 let (short, color_config) = kind.unzip();
1372 Box::new(EmitterWriter::stderr(color_config, None, short, false))
1374 config::ErrorOutputType::Json { pretty, json_rendered } =>
1375 Box::new(JsonEmitter::basic(pretty, json_rendered)),
1377 let handler = errors::Handler::with_emitter(true, None, emitter);
1378 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1379 errors::FatalError.raise();
1382 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1383 let emitter: Box<dyn Emitter + sync::Send> = match output {
1384 config::ErrorOutputType::HumanReadable(kind) => {
1385 let (short, color_config) = kind.unzip();
1386 Box::new(EmitterWriter::stderr(color_config, None, short, false))
1388 config::ErrorOutputType::Json { pretty, json_rendered } =>
1389 Box::new(JsonEmitter::basic(pretty, json_rendered)),
1391 let handler = errors::Handler::with_emitter(true, None, emitter);
1392 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1395 pub type CompileResult = Result<(), ErrorReported>;