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 rustc_data_structures::fingerprint::Fingerprint;
8 use crate::session::config::{OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
9 use crate::session::search_paths::{PathKind, SearchPath};
10 use crate::util::nodemap::{FxHashMap, FxHashSet};
11 use crate::util::common::{duration_to_secs_str, ErrorReported};
13 use rustc_data_structures::base_n;
14 use rustc_data_structures::sync::{
15 self, Lrc, Lock, OneThread, Once, AtomicU64, AtomicUsize, Ordering,
19 use errors::{DiagnosticBuilder, DiagnosticId, Applicability};
20 use errors::emitter::{Emitter, EmitterWriter};
21 use errors::emitter::HumanReadableErrorType;
22 use errors::annotate_snippet_emitter_writer::{AnnotateSnippetEmitterWriter};
23 use syntax::edition::Edition;
24 use errors::json::JsonEmitter;
25 use syntax::source_map;
26 use syntax::sess::ParseSess;
27 use syntax_pos::{MultiSpan, Span};
29 use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
30 use rustc_data_structures::flock;
31 use rustc_data_structures::jobserver;
32 use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
33 use ::jobserver::Client;
36 use std::cell::{self, RefCell};
40 use std::num::NonZeroU32;
41 use std::path::PathBuf;
42 use std::time::Duration;
50 pub struct OptimizationFuel {
51 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
53 /// We're rejecting all further optimizations.
57 /// Represents the data associated with a compilation
58 /// session for a single crate.
60 pub target: config::Config,
62 pub opts: config::Options,
63 pub host_tlib_path: SearchPath,
64 /// `None` if the host and target are the same.
65 pub target_tlib_path: Option<SearchPath>,
66 pub parse_sess: ParseSess,
68 /// The name of the root source file of the crate, in the local file system.
69 /// `None` means that there is no source file.
70 pub local_crate_source_file: Option<PathBuf>,
71 /// The directory the compiler has been executed in plus a flag indicating
72 /// if the value stored here has been affected by path remapping.
73 pub working_dir: (PathBuf, bool),
75 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
76 /// (sub)diagnostics that have been set once, but should not be set again,
77 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
78 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
79 pub plugin_llvm_passes: OneThread<RefCell<Vec<String>>>,
80 pub crate_types: Once<Vec<config::CrateType>>,
81 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
82 /// arguments passed to the compiler. Its value together with the crate-name
83 /// forms a unique global identifier for the crate. It is used to allow
84 /// multiple crates with the same name to coexist. See the
85 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
86 pub crate_disambiguator: Once<CrateDisambiguator>,
88 features: Once<rustc_feature::Features>,
90 /// The maximum recursion limit for potentially infinitely recursive
91 /// operations such as auto-dereference and monomorphization.
92 pub recursion_limit: Once<usize>,
94 /// The maximum length of types during monomorphization.
95 pub type_length_limit: Once<usize>,
97 /// Map from imported macro spans (which consist of
98 /// the localized span for the macro body) to the
99 /// macro name and definition span in the source crate.
100 pub imported_macro_spans: OneThread<RefCell<FxHashMap<Span, (String, Span)>>>,
102 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
103 /// Used for incremental compilation tests. Will only be populated if
104 /// `-Zquery-dep-graph` is specified.
105 pub cgu_reuse_tracker: CguReuseTracker,
107 /// Used by `-Z self-profile`.
108 pub prof: SelfProfilerRef,
110 /// Some measurements that are being gathered during compilation.
111 pub perf_stats: PerfStats,
113 /// Data about code being compiled, gathered during compilation.
114 pub code_stats: CodeStats,
116 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
117 optimization_fuel_crate: Option<String>,
119 /// Tracks fuel info if `-zfuel=crate=n` is specified.
120 optimization_fuel: Lock<OptimizationFuel>,
122 // The next two are public because the driver needs to read them.
123 /// If `-zprint-fuel=crate`, `Some(crate)`.
124 pub print_fuel_crate: Option<String>,
125 /// Always set to zero and incremented so that we can print fuel expended by a crate.
126 pub print_fuel: AtomicU64,
128 /// Loaded up early on in the initialization of this `Session` to avoid
129 /// false positives about a job server in our environment.
130 pub jobserver: Client,
132 /// Cap lint level specified by a driver specifically.
133 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
135 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
136 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
138 /// Mapping from ident span to path span for paths that don't exist as written, but that
139 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
140 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
143 pub struct PerfStats {
144 /// The accumulated time spent on computing symbol hashes.
145 pub symbol_hash_time: Lock<Duration>,
146 /// The accumulated time spent decoding def path tables from metadata.
147 pub decode_def_path_tables_time: Lock<Duration>,
148 /// Total number of values canonicalized queries constructed.
149 pub queries_canonicalized: AtomicUsize,
150 /// Number of times this query is invoked.
151 pub normalize_ty_after_erasing_regions: AtomicUsize,
152 /// Number of times this query is invoked.
153 pub normalize_projection_ty: AtomicUsize,
156 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
157 enum DiagnosticBuilderMethod {
160 SpanSuggestion(String), // suggestion
161 // Add more variants as needed to support one-time diagnostics.
164 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
165 /// emitting the same message more than once.
166 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
167 pub enum DiagnosticMessageId {
168 ErrorId(u16), // EXXXX error code as integer
169 LintId(lint::LintId),
170 StabilityId(Option<NonZeroU32>), // issue number
173 impl From<&'static lint::Lint> for DiagnosticMessageId {
174 fn from(lint: &'static lint::Lint) -> Self {
175 DiagnosticMessageId::LintId(lint::LintId::of(lint))
180 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
181 *self.crate_disambiguator.get()
184 pub fn struct_span_warn<S: Into<MultiSpan>>(
188 ) -> DiagnosticBuilder<'_> {
189 self.diagnostic().struct_span_warn(sp, msg)
191 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
196 ) -> DiagnosticBuilder<'_> {
197 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
199 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
200 self.diagnostic().struct_warn(msg)
202 pub fn struct_span_err<S: Into<MultiSpan>>(
206 ) -> DiagnosticBuilder<'_> {
207 self.diagnostic().struct_span_err(sp, msg)
209 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
214 ) -> DiagnosticBuilder<'_> {
215 self.diagnostic().struct_span_err_with_code(sp, msg, code)
217 // FIXME: This method should be removed (every error should have an associated error code).
218 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
219 self.diagnostic().struct_err(msg)
221 pub fn struct_err_with_code(
225 ) -> DiagnosticBuilder<'_> {
226 self.diagnostic().struct_err_with_code(msg, code)
228 pub fn struct_span_fatal<S: Into<MultiSpan>>(
232 ) -> DiagnosticBuilder<'_> {
233 self.diagnostic().struct_span_fatal(sp, msg)
235 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
240 ) -> DiagnosticBuilder<'_> {
241 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
243 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
244 self.diagnostic().struct_fatal(msg)
247 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
248 self.diagnostic().span_fatal(sp, msg).raise()
250 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
257 .span_fatal_with_code(sp, msg, code)
260 pub fn fatal(&self, msg: &str) -> ! {
261 self.diagnostic().fatal(msg).raise()
263 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
265 self.span_warn(sp, msg);
267 self.span_err(sp, msg);
270 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
271 self.diagnostic().span_err(sp, msg)
273 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
274 self.diagnostic().span_err_with_code(sp, &msg, code)
276 pub fn err(&self, msg: &str) {
277 self.diagnostic().err(msg)
279 pub fn err_count(&self) -> usize {
280 self.diagnostic().err_count()
282 pub fn has_errors(&self) -> bool {
283 self.diagnostic().has_errors()
285 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
286 self.diagnostic().has_errors_or_delayed_span_bugs()
288 pub fn abort_if_errors(&self) {
289 self.diagnostic().abort_if_errors();
291 pub fn compile_status(&self) -> Result<(), ErrorReported> {
292 if self.has_errors() {
293 self.diagnostic().emit_stashed_diagnostics();
299 // FIXME(matthewjasper) Remove this method, it should never be needed.
300 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
304 let old_count = self.err_count();
306 let errors = self.err_count() - old_count;
313 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
314 self.diagnostic().span_warn(sp, msg)
316 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
317 self.diagnostic().span_warn_with_code(sp, msg, code)
319 pub fn warn(&self, msg: &str) {
320 self.diagnostic().warn(msg)
322 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
324 Some(sp) => self.span_warn(sp, msg),
325 None => self.warn(msg),
328 /// Delay a span_bug() call until abort_if_errors()
329 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
330 self.diagnostic().delay_span_bug(sp, msg)
332 pub fn note_without_error(&self, msg: &str) {
333 self.diagnostic().note_without_error(msg)
335 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
336 self.diagnostic().span_note_without_error(sp, msg)
339 pub fn diagnostic(&self) -> &errors::Handler {
340 &self.parse_sess.span_diagnostic
343 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
344 /// deduplicates on lint ID, span (if any), and message for this `Session`
345 fn diag_once<'a, 'b>(
347 diag_builder: &'b mut DiagnosticBuilder<'a>,
348 method: DiagnosticBuilderMethod,
349 msg_id: DiagnosticMessageId,
351 span_maybe: Option<Span>,
353 let id_span_message = (msg_id, span_maybe, message.to_owned());
354 let fresh = self.one_time_diagnostics
356 .insert(id_span_message);
359 DiagnosticBuilderMethod::Note => {
360 diag_builder.note(message);
362 DiagnosticBuilderMethod::SpanNote => {
363 let span = span_maybe.expect("`span_note` needs a span");
364 diag_builder.span_note(span, message);
366 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
367 let span = span_maybe.expect("`span_suggestion_*` needs a span");
368 diag_builder.span_suggestion(
372 Applicability::Unspecified,
379 pub fn diag_span_note_once<'a, 'b>(
381 diag_builder: &'b mut DiagnosticBuilder<'a>,
382 msg_id: DiagnosticMessageId,
388 DiagnosticBuilderMethod::SpanNote,
395 pub fn diag_note_once<'a, 'b>(
397 diag_builder: &'b mut DiagnosticBuilder<'a>,
398 msg_id: DiagnosticMessageId,
403 DiagnosticBuilderMethod::Note,
410 pub fn diag_span_suggestion_once<'a, 'b>(
412 diag_builder: &'b mut DiagnosticBuilder<'a>,
413 msg_id: DiagnosticMessageId,
420 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
427 pub fn source_map(&self) -> &source_map::SourceMap {
428 self.parse_sess.source_map()
430 pub fn verbose(&self) -> bool {
431 self.opts.debugging_opts.verbose
433 pub fn time_passes(&self) -> bool {
434 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
436 pub fn time_extended(&self) -> bool {
437 self.opts.debugging_opts.time_passes
439 pub fn instrument_mcount(&self) -> bool {
440 self.opts.debugging_opts.instrument_mcount
442 pub fn time_llvm_passes(&self) -> bool {
443 self.opts.debugging_opts.time_llvm_passes
445 pub fn meta_stats(&self) -> bool {
446 self.opts.debugging_opts.meta_stats
448 pub fn asm_comments(&self) -> bool {
449 self.opts.debugging_opts.asm_comments
451 pub fn verify_llvm_ir(&self) -> bool {
452 self.opts.debugging_opts.verify_llvm_ir
453 || cfg!(always_verify_llvm_ir)
455 pub fn borrowck_stats(&self) -> bool {
456 self.opts.debugging_opts.borrowck_stats
458 pub fn print_llvm_passes(&self) -> bool {
459 self.opts.debugging_opts.print_llvm_passes
461 pub fn binary_dep_depinfo(&self) -> bool {
462 self.opts.debugging_opts.binary_dep_depinfo
465 /// Gets the features enabled for the current compilation session.
466 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
467 /// dependency tracking. Use tcx.features() instead.
469 pub fn features_untracked(&self) -> &rustc_feature::Features {
473 pub fn init_features(&self, features: rustc_feature::Features) {
474 self.features.set(features);
477 /// Calculates the flavor of LTO to use for this compilation.
478 pub fn lto(&self) -> config::Lto {
479 // If our target has codegen requirements ignore the command line
480 if self.target.target.options.requires_lto {
481 return config::Lto::Fat;
484 // If the user specified something, return that. If they only said `-C
485 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
486 // then ensure we can't use a ThinLTO.
487 match self.opts.cg.lto {
488 config::LtoCli::Unspecified => {
489 // The compiler was invoked without the `-Clto` flag. Fall
490 // through to the default handling
492 config::LtoCli::No => {
493 // The user explicitly opted out of any kind of LTO
494 return config::Lto::No;
496 config::LtoCli::Yes |
497 config::LtoCli::Fat |
498 config::LtoCli::NoParam => {
499 // All of these mean fat LTO
500 return config::Lto::Fat;
502 config::LtoCli::Thin => {
503 return if self.opts.cli_forced_thinlto_off {
511 // Ok at this point the target doesn't require anything and the user
512 // hasn't asked for anything. Our next decision is whether or not
513 // we enable "auto" ThinLTO where we use multiple codegen units and
514 // then do ThinLTO over those codegen units. The logic below will
515 // either return `No` or `ThinLocal`.
517 // If processing command line options determined that we're incompatible
518 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
519 if self.opts.cli_forced_thinlto_off {
520 return config::Lto::No;
523 // If `-Z thinlto` specified process that, but note that this is mostly
524 // a deprecated option now that `-C lto=thin` exists.
525 if let Some(enabled) = self.opts.debugging_opts.thinlto {
527 return config::Lto::ThinLocal;
529 return config::Lto::No;
533 // If there's only one codegen unit and LTO isn't enabled then there's
534 // no need for ThinLTO so just return false.
535 if self.codegen_units() == 1 {
536 return config::Lto::No;
539 // Now we're in "defaults" territory. By default we enable ThinLTO for
540 // optimized compiles (anything greater than O0).
541 match self.opts.optimize {
542 config::OptLevel::No => config::Lto::No,
543 _ => config::Lto::ThinLocal,
547 /// Returns the panic strategy for this compile session. If the user explicitly selected one
548 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
549 pub fn panic_strategy(&self) -> PanicStrategy {
553 .unwrap_or(self.target.target.options.panic_strategy)
555 pub fn fewer_names(&self) -> bool {
556 let more_names = self.opts
558 .contains_key(&OutputType::LlvmAssembly)
559 || self.opts.output_types.contains_key(&OutputType::Bitcode);
561 // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
562 let more_names = match self.opts.debugging_opts.sanitizer {
563 Some(Sanitizer::Address) => true,
564 Some(Sanitizer::Memory) => true,
568 self.opts.debugging_opts.fewer_names || !more_names
571 pub fn no_landing_pads(&self) -> bool {
572 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
574 pub fn unstable_options(&self) -> bool {
575 self.opts.debugging_opts.unstable_options
577 pub fn overflow_checks(&self) -> bool {
581 .or(self.opts.debugging_opts.force_overflow_checks)
582 .unwrap_or(self.opts.debug_assertions)
585 pub fn crt_static(&self) -> bool {
586 // If the target does not opt in to crt-static support, use its default.
587 if self.target.target.options.crt_static_respected {
588 self.crt_static_feature()
590 self.target.target.options.crt_static_default
594 pub fn crt_static_feature(&self) -> bool {
595 let requested_features = self.opts.cg.target_feature.split(',');
596 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
597 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
599 // If the target we're compiling for requests a static crt by default,
600 // then see if the `-crt-static` feature was passed to disable that.
601 // Otherwise if we don't have a static crt by default then see if the
602 // `+crt-static` feature was passed.
603 if self.target.target.options.crt_static_default {
610 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
611 // "mcount" function relies on stack pointer.
612 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
613 if self.instrument_mcount() {
615 } else if let Some(x) = self.opts.cg.force_frame_pointers {
618 !self.target.target.options.eliminate_frame_pointer
622 /// Returns the symbol name for the registrar function,
623 /// given the crate `Svh` and the function `DefIndex`.
624 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
626 "__rustc_plugin_registrar_{}__",
627 disambiguator.to_fingerprint().to_hex()
631 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
633 "__rustc_proc_macro_decls_{}__",
634 disambiguator.to_fingerprint().to_hex()
638 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
639 filesearch::FileSearch::new(
641 self.opts.target_triple.triple(),
642 &self.opts.search_paths,
643 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
644 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
648 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
649 filesearch::FileSearch::new(
651 config::host_triple(),
652 &self.opts.search_paths,
653 &self.host_tlib_path,
658 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
659 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
661 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
662 *load_dep_graph = load;
666 pub fn incr_session_load_dep_graph(&self) -> bool {
667 let incr_comp_session = self.incr_comp_session.borrow();
668 match *incr_comp_session {
669 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
674 pub fn init_incr_comp_session(
676 session_dir: PathBuf,
677 lock_file: flock::Lock,
678 load_dep_graph: bool,
680 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
682 if let IncrCompSession::NotInitialized = *incr_comp_session {
685 "Trying to initialize IncrCompSession `{:?}`",
690 *incr_comp_session = IncrCompSession::Active {
691 session_directory: session_dir,
697 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
698 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
700 if let IncrCompSession::Active { .. } = *incr_comp_session {
703 "trying to finalize `IncrCompSession` `{:?}`",
708 // Note: this will also drop the lock file, thus unlocking the directory.
709 *incr_comp_session = IncrCompSession::Finalized {
710 session_directory: new_directory_path,
714 pub fn mark_incr_comp_session_as_invalid(&self) {
715 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
717 let session_directory = match *incr_comp_session {
718 IncrCompSession::Active {
719 ref session_directory,
721 } => session_directory.clone(),
722 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
724 "trying to invalidate `IncrCompSession` `{:?}`",
729 // Note: this will also drop the lock file, thus unlocking the directory.
730 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
735 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
736 let incr_comp_session = self.incr_comp_session.borrow();
739 |incr_comp_session| match *incr_comp_session {
740 IncrCompSession::NotInitialized => bug!(
741 "trying to get session directory from `IncrCompSession`: {:?}",
744 IncrCompSession::Active {
745 ref session_directory,
748 | IncrCompSession::Finalized {
749 ref session_directory,
751 | IncrCompSession::InvalidBecauseOfErrors {
752 ref session_directory,
753 } => session_directory,
758 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
759 if self.opts.incremental.is_some() {
760 Some(self.incr_comp_session_dir())
766 pub fn print_perf_stats(&self) {
768 "Total time spent computing symbol hashes: {}",
769 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
772 "Total time spent decoding DefPath tables: {}",
773 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
775 println!("Total queries canonicalized: {}",
776 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed));
777 println!("normalize_ty_after_erasing_regions: {}",
778 self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed));
779 println!("normalize_projection_ty: {}",
780 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed));
783 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
784 /// This expends fuel if applicable, and records fuel if applicable.
785 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
787 if let Some(ref c) = self.optimization_fuel_crate {
789 assert_eq!(self.threads(), 1);
790 let mut fuel = self.optimization_fuel.lock();
791 ret = fuel.remaining != 0;
792 if fuel.remaining == 0 && !fuel.out_of_fuel {
793 eprintln!("optimization-fuel-exhausted: {}", msg());
794 fuel.out_of_fuel = true;
795 } else if fuel.remaining > 0 {
800 if let Some(ref c) = self.print_fuel_crate {
802 assert_eq!(self.threads(), 1);
803 self.print_fuel.fetch_add(1, SeqCst);
809 /// Returns the number of query threads that should be used for this
811 pub fn threads(&self) -> usize {
812 self.opts.debugging_opts.threads
815 /// Returns the number of codegen units that should be used for this
817 pub fn codegen_units(&self) -> usize {
818 if let Some(n) = self.opts.cli_forced_codegen_units {
821 if let Some(n) = self.target.target.options.default_codegen_units {
825 // Why is 16 codegen units the default all the time?
827 // The main reason for enabling multiple codegen units by default is to
828 // leverage the ability for the codegen backend to do codegen and
829 // optimization in parallel. This allows us, especially for large crates, to
830 // make good use of all available resources on the machine once we've
831 // hit that stage of compilation. Large crates especially then often
832 // take a long time in codegen/optimization and this helps us amortize that
835 // Note that a high number here doesn't mean that we'll be spawning a
836 // large number of threads in parallel. The backend of rustc contains
837 // global rate limiting through the `jobserver` crate so we'll never
838 // overload the system with too much work, but rather we'll only be
839 // optimizing when we're otherwise cooperating with other instances of
842 // Rather a high number here means that we should be able to keep a lot
843 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
844 // to build we'll be guaranteed that all cpus will finish pretty closely
845 // to one another and we should make relatively optimal use of system
848 // Note that the main cost of codegen units is that it prevents LLVM
849 // from inlining across codegen units. Users in general don't have a lot
850 // of control over how codegen units are split up so it's our job in the
851 // compiler to ensure that undue performance isn't lost when using
852 // codegen units (aka we can't require everyone to slap `#[inline]` on
855 // If we're compiling at `-O0` then the number doesn't really matter too
856 // much because performance doesn't matter and inlining is ok to lose.
857 // In debug mode we just want to try to guarantee that no cpu is stuck
858 // doing work that could otherwise be farmed to others.
860 // In release mode, however (O1 and above) performance does indeed
861 // matter! To recover the loss in performance due to inlining we'll be
862 // enabling ThinLTO by default (the function for which is just below).
863 // This will ensure that we recover any inlining wins we otherwise lost
864 // through codegen unit partitioning.
868 // Ok that's a lot of words but the basic tl;dr; is that we want a high
869 // number here -- but not too high. Additionally we're "safe" to have it
870 // always at the same number at all optimization levels.
872 // As a result 16 was chosen here! Mostly because it was a power of 2
873 // and most benchmarks agreed it was roughly a local optimum. Not very
878 pub fn teach(&self, code: &DiagnosticId) -> bool {
879 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
882 pub fn rust_2015(&self) -> bool {
883 self.opts.edition == Edition::Edition2015
886 /// Are we allowed to use features from the Rust 2018 edition?
887 pub fn rust_2018(&self) -> bool {
888 self.opts.edition >= Edition::Edition2018
891 pub fn edition(&self) -> Edition {
895 /// Returns `true` if we cannot skip the PLT for shared library calls.
896 pub fn needs_plt(&self) -> bool {
897 // Check if the current target usually needs PLT to be enabled.
898 // The user can use the command line flag to override it.
899 let needs_plt = self.target.target.options.needs_plt;
901 let dbg_opts = &self.opts.debugging_opts;
903 let relro_level = dbg_opts.relro_level
904 .unwrap_or(self.target.target.options.relro_level);
906 // Only enable this optimization by default if full relro is also enabled.
907 // In this case, lazy binding was already unavailable, so nothing is lost.
908 // This also ensures `-Wl,-z,now` is supported by the linker.
909 let full_relro = RelroLevel::Full == relro_level;
911 // If user didn't explicitly forced us to use / skip the PLT,
912 // then try to skip it where possible.
913 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
917 pub fn build_session(
918 sopts: config::Options,
919 local_crate_source_file: Option<PathBuf>,
920 registry: errors::registry::Registry,
922 let file_path_mapping = sopts.file_path_mapping();
924 build_session_with_source_map(
926 local_crate_source_file,
928 Lrc::new(source_map::SourceMap::new(file_path_mapping)),
929 DiagnosticOutput::Default,
935 sopts: &config::Options,
936 registry: errors::registry::Registry,
937 source_map: &Lrc<source_map::SourceMap>,
938 emitter_dest: Option<Box<dyn Write + Send>>,
939 ) -> Box<dyn Emitter + sync::Send> {
940 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
941 match (sopts.error_format, emitter_dest) {
942 (config::ErrorOutputType::HumanReadable(kind), dst) => {
943 let (short, color_config) = kind.unzip();
945 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
946 let emitter = AnnotateSnippetEmitterWriter::new(
947 Some(source_map.clone()),
949 external_macro_backtrace,
951 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
953 let emitter = match dst {
954 None => EmitterWriter::stderr(
956 Some(source_map.clone()),
958 sopts.debugging_opts.teach,
959 sopts.debugging_opts.terminal_width,
960 external_macro_backtrace,
962 Some(dst) => EmitterWriter::new(
964 Some(source_map.clone()),
966 false, // no teach messages when writing to a buffer
967 false, // no colors when writing to a buffer
968 None, // no terminal width
969 external_macro_backtrace,
972 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
975 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
981 external_macro_backtrace,
982 ).ui_testing(sopts.debugging_opts.ui_testing),
984 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
991 external_macro_backtrace,
992 ).ui_testing(sopts.debugging_opts.ui_testing),
997 pub enum DiagnosticOutput {
999 Raw(Box<dyn Write + Send>)
1002 pub fn build_session_with_source_map(
1003 sopts: config::Options,
1004 local_crate_source_file: Option<PathBuf>,
1005 registry: errors::registry::Registry,
1006 source_map: Lrc<source_map::SourceMap>,
1007 diagnostics_output: DiagnosticOutput,
1008 lint_caps: FxHashMap<lint::LintId, lint::Level>,
1010 // FIXME: This is not general enough to make the warning lint completely override
1011 // normal diagnostic warnings, since the warning lint can also be denied and changed
1012 // later via the source code.
1013 let warnings_allow = sopts
1016 .filter(|&&(ref key, _)| *key == "warnings")
1017 .map(|&(_, ref level)| *level == lint::Allow)
1020 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1022 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1024 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
1025 let dont_buffer_diagnostics = sopts.debugging_opts.dont_buffer_diagnostics;
1026 let report_delayed_bugs = sopts.debugging_opts.report_delayed_bugs;
1028 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
1030 let write_dest = match diagnostics_output {
1031 DiagnosticOutput::Default => None,
1032 DiagnosticOutput::Raw(write) => Some(write),
1034 let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
1036 let diagnostic_handler = errors::Handler::with_emitter_and_flags(
1038 errors::HandlerFlags {
1041 report_delayed_bugs,
1042 dont_buffer_diagnostics,
1043 external_macro_backtrace,
1044 ..Default::default()
1050 local_crate_source_file,
1058 sopts: config::Options,
1059 local_crate_source_file: Option<PathBuf>,
1060 span_diagnostic: errors::Handler,
1061 source_map: Lrc<source_map::SourceMap>,
1062 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1065 if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile {
1066 let directory = if let Some(ref directory) = d {
1069 std::path::Path::new(".")
1072 let profiler = SelfProfiler::new(
1074 sopts.crate_name.as_ref().map(|s| &s[..]),
1075 &sopts.debugging_opts.self_profile_events
1079 Some(Arc::new(profiler))
1082 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1089 let host_triple = TargetTriple::from_triple(config::host_triple());
1090 let host = Target::search(&host_triple).unwrap_or_else(|e|
1092 .fatal(&format!("Error loading host specification: {}", e))
1095 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
1097 let parse_sess = ParseSess::with_span_handler(
1101 let sysroot = match &sopts.maybe_sysroot {
1102 Some(sysroot) => sysroot.clone(),
1103 None => filesearch::get_or_default_sysroot(),
1106 let host_triple = config::host_triple();
1107 let target_triple = sopts.target_triple.triple();
1108 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1109 let target_tlib_path = if host_triple == target_triple {
1112 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1115 let file_path_mapping = sopts.file_path_mapping();
1117 let local_crate_source_file =
1118 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1120 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1121 let optimization_fuel = Lock::new(OptimizationFuel {
1122 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1125 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1126 let print_fuel = AtomicU64::new(0);
1128 let working_dir = env::current_dir().unwrap_or_else(|e|
1129 parse_sess.span_diagnostic
1130 .fatal(&format!("Current directory is invalid: {}", e))
1133 let working_dir = file_path_mapping.map_prefix(working_dir);
1135 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1136 CguReuseTracker::new()
1138 CguReuseTracker::new_disabled()
1141 let sess = Session {
1149 local_crate_source_file,
1151 one_time_diagnostics: Default::default(),
1152 plugin_llvm_passes: OneThread::new(RefCell::new(Vec::new())),
1153 crate_types: Once::new(),
1154 crate_disambiguator: Once::new(),
1155 features: Once::new(),
1156 recursion_limit: Once::new(),
1157 type_length_limit: Once::new(),
1158 imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())),
1159 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1161 prof: SelfProfilerRef::new(self_profiler),
1162 perf_stats: PerfStats {
1163 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1164 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1165 queries_canonicalized: AtomicUsize::new(0),
1166 normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1167 normalize_projection_ty: AtomicUsize::new(0),
1169 code_stats: Default::default(),
1170 optimization_fuel_crate,
1174 jobserver: jobserver::client(),
1176 trait_methods_not_found: Lock::new(Default::default()),
1177 confused_type_with_std_module: Lock::new(Default::default()),
1180 validate_commandline_args_with_session_available(&sess);
1185 // If it is useful to have a Session available already for validating a
1186 // commandline argument, you can do so here.
1187 fn validate_commandline_args_with_session_available(sess: &Session) {
1188 // Since we don't know if code in an rlib will be linked to statically or
1189 // dynamically downstream, rustc generates `__imp_` symbols that help the
1190 // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1191 // these manually generated symbols confuse LLD when it tries to merge
1192 // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1193 // when compiling for LLD ThinLTO. This way we can validly just not generate
1194 // the `dllimport` attributes and `__imp_` symbols in that case.
1195 if sess.opts.cg.linker_plugin_lto.enabled() &&
1196 sess.opts.cg.prefer_dynamic &&
1197 sess.target.target.options.is_like_msvc {
1198 sess.err("Linker plugin based LTO is not supported together with \
1199 `-C prefer-dynamic` when targeting MSVC");
1202 // Make sure that any given profiling data actually exists so LLVM can't
1203 // decide to silently skip PGO.
1204 if let Some(ref path) = sess.opts.cg.profile_use {
1206 sess.err(&format!("File `{}` passed to `-C profile-use` does not exist.",
1211 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1212 // an error to combine the two for now. It always runs into an assertions
1213 // if LLVM is built with assertions, but without assertions it sometimes
1214 // does not crash and will probably generate a corrupted binary.
1215 // We should only display this error if we're actually going to run PGO.
1216 // If we're just supposed to print out some data, don't show the error (#61002).
1217 if sess.opts.cg.profile_generate.enabled() &&
1218 sess.target.target.options.is_like_msvc &&
1219 sess.panic_strategy() == PanicStrategy::Unwind &&
1220 sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
1221 sess.err("Profile-guided optimization does not yet work in conjunction \
1222 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1223 See https://github.com/rust-lang/rust/issues/61002 for details.");
1227 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1228 /// compiler. Together with the crate-name forms a unique global identifier for
1230 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1231 pub struct CrateDisambiguator(Fingerprint);
1233 impl CrateDisambiguator {
1234 pub fn to_fingerprint(self) -> Fingerprint {
1239 impl fmt::Display for CrateDisambiguator {
1240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1241 let (a, b) = self.0.as_value();
1242 let as_u128 = a as u128 | ((b as u128) << 64);
1243 f.write_str(&base_n::encode(as_u128, base_n::CASE_INSENSITIVE))
1247 impl From<Fingerprint> for CrateDisambiguator {
1248 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1249 CrateDisambiguator(fingerprint)
1253 impl_stable_hash_via_hash!(CrateDisambiguator);
1255 /// Holds data on the current incremental compilation session, if there is one.
1257 pub enum IncrCompSession {
1258 /// This is the state the session will be in until the incr. comp. dir is
1261 /// This is the state during which the session directory is private and can
1264 session_directory: PathBuf,
1265 lock_file: flock::Lock,
1266 load_dep_graph: bool,
1268 /// This is the state after the session directory has been finalized. In this
1269 /// state, the contents of the directory must not be modified any more.
1270 Finalized { session_directory: PathBuf },
1271 /// This is an error state that is reached when some compilation error has
1272 /// occurred. It indicates that the contents of the session directory must
1273 /// not be used, since they might be invalid.
1274 InvalidBecauseOfErrors { session_directory: PathBuf },
1277 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1278 let emitter: Box<dyn Emitter + sync::Send> = match output {
1279 config::ErrorOutputType::HumanReadable(kind) => {
1280 let (short, color_config) = kind.unzip();
1281 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1283 config::ErrorOutputType::Json { pretty, json_rendered } =>
1284 Box::new(JsonEmitter::basic(pretty, json_rendered, false)),
1286 let handler = errors::Handler::with_emitter(true, None, emitter);
1287 handler.struct_fatal(msg).emit();
1288 errors::FatalError.raise();
1291 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1292 let emitter: Box<dyn Emitter + sync::Send> = match output {
1293 config::ErrorOutputType::HumanReadable(kind) => {
1294 let (short, color_config) = kind.unzip();
1295 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1297 config::ErrorOutputType::Json { pretty, json_rendered } =>
1298 Box::new(JsonEmitter::basic(pretty, json_rendered, false)),
1300 let handler = errors::Handler::with_emitter(true, None, emitter);
1301 handler.struct_warn(msg).emit();
1304 pub type CompileResult = Result<(), ErrorReported>;