1 pub use crate::code_stats::{DataTypeKind, SizeKind, FieldInfo, VariantInfo};
2 use crate::code_stats::CodeStats;
4 use crate::cgu_reuse_tracker::CguReuseTracker;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use crate::config::{self, OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
11 use crate::search_paths::{PathKind, SearchPath};
12 use crate::utils::duration_to_secs_str;
13 use rustc_errors::ErrorReported;
15 use rustc_data_structures::base_n;
16 use rustc_data_structures::sync::{
17 self, Lrc, Lock, OneThread, Once, AtomicU64, AtomicUsize, Ordering,
20 use rustc_data_structures::impl_stable_hash_via_hash;
22 use rustc_errors::{DiagnosticBuilder, DiagnosticId, Applicability};
23 use rustc_errors::emitter::{Emitter, EmitterWriter};
24 use rustc_errors::emitter::HumanReadableErrorType;
25 use rustc_errors::annotate_snippet_emitter_writer::{AnnotateSnippetEmitterWriter};
26 use syntax_pos::edition::Edition;
27 use rustc_errors::json::JsonEmitter;
28 use syntax_pos::source_map;
29 use crate::parse::ParseSess;
30 use syntax_pos::{MultiSpan, Span};
32 use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
33 use rustc_data_structures::flock;
34 use rustc_data_structures::jobserver::{self, Client};
35 use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
38 use std::cell::{self, RefCell};
42 use std::num::NonZeroU32;
43 use std::path::PathBuf;
44 use std::time::Duration;
47 pub struct OptimizationFuel {
48 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
50 /// We're rejecting all further optimizations.
54 /// Represents the data associated with a compilation
55 /// session for a single crate.
57 pub target: config::Config,
59 pub opts: config::Options,
60 pub host_tlib_path: SearchPath,
61 /// `None` if the host and target are the same.
62 pub target_tlib_path: Option<SearchPath>,
63 pub parse_sess: ParseSess,
65 /// The name of the root source file of the crate, in the local file system.
66 /// `None` means that there is no source file.
67 pub local_crate_source_file: Option<PathBuf>,
68 /// The directory the compiler has been executed in plus a flag indicating
69 /// if the value stored here has been affected by path remapping.
70 pub working_dir: (PathBuf, bool),
72 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
73 /// (sub)diagnostics that have been set once, but should not be set again,
74 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
75 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
76 pub crate_types: Once<Vec<config::CrateType>>,
77 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
78 /// arguments passed to the compiler. Its value together with the crate-name
79 /// forms a unique global identifier for the crate. It is used to allow
80 /// multiple crates with the same name to coexist. See the
81 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
82 pub crate_disambiguator: Once<CrateDisambiguator>,
84 features: Once<rustc_feature::Features>,
86 /// The maximum recursion limit for potentially infinitely recursive
87 /// operations such as auto-dereference and monomorphization.
88 pub recursion_limit: Once<usize>,
90 /// The maximum length of types during monomorphization.
91 pub type_length_limit: Once<usize>,
93 /// Map from imported macro spans (which consist of
94 /// the localized span for the macro body) to the
95 /// macro name and definition span in the source crate.
96 pub imported_macro_spans: OneThread<RefCell<FxHashMap<Span, (String, Span)>>>,
98 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
99 /// Used for incremental compilation tests. Will only be populated if
100 /// `-Zquery-dep-graph` is specified.
101 pub cgu_reuse_tracker: CguReuseTracker,
103 /// Used by `-Z self-profile`.
104 pub prof: SelfProfilerRef,
106 /// Some measurements that are being gathered during compilation.
107 pub perf_stats: PerfStats,
109 /// Data about code being compiled, gathered during compilation.
110 pub code_stats: CodeStats,
112 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
113 optimization_fuel_crate: Option<String>,
115 /// Tracks fuel info if `-zfuel=crate=n` is specified.
116 optimization_fuel: Lock<OptimizationFuel>,
118 // The next two are public because the driver needs to read them.
119 /// If `-zprint-fuel=crate`, `Some(crate)`.
120 pub print_fuel_crate: Option<String>,
121 /// Always set to zero and incremented so that we can print fuel expended by a crate.
122 pub print_fuel: AtomicU64,
124 /// Loaded up early on in the initialization of this `Session` to avoid
125 /// false positives about a job server in our environment.
126 pub jobserver: Client,
128 /// Cap lint level specified by a driver specifically.
129 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
131 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
132 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
134 /// Mapping from ident span to path span for paths that don't exist as written, but that
135 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
136 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
139 pub struct PerfStats {
140 /// The accumulated time spent on computing symbol hashes.
141 pub symbol_hash_time: Lock<Duration>,
142 /// The accumulated time spent decoding def path tables from metadata.
143 pub decode_def_path_tables_time: Lock<Duration>,
144 /// Total number of values canonicalized queries constructed.
145 pub queries_canonicalized: AtomicUsize,
146 /// Number of times this query is invoked.
147 pub normalize_ty_after_erasing_regions: AtomicUsize,
148 /// Number of times this query is invoked.
149 pub normalize_projection_ty: AtomicUsize,
152 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
153 enum DiagnosticBuilderMethod {
156 SpanSuggestion(String), // suggestion
157 // Add more variants as needed to support one-time diagnostics.
160 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
161 /// emitting the same message more than once.
162 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
163 pub enum DiagnosticMessageId {
164 ErrorId(u16), // EXXXX error code as integer
165 LintId(lint::LintId),
166 StabilityId(Option<NonZeroU32>), // issue number
169 impl From<&'static lint::Lint> for DiagnosticMessageId {
170 fn from(lint: &'static lint::Lint) -> Self {
171 DiagnosticMessageId::LintId(lint::LintId::of(lint))
176 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
177 *self.crate_disambiguator.get()
180 pub fn struct_span_warn<S: Into<MultiSpan>>(
184 ) -> DiagnosticBuilder<'_> {
185 self.diagnostic().struct_span_warn(sp, msg)
187 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
192 ) -> DiagnosticBuilder<'_> {
193 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
195 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
196 self.diagnostic().struct_warn(msg)
198 pub fn struct_span_err<S: Into<MultiSpan>>(
202 ) -> DiagnosticBuilder<'_> {
203 self.diagnostic().struct_span_err(sp, msg)
205 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
210 ) -> DiagnosticBuilder<'_> {
211 self.diagnostic().struct_span_err_with_code(sp, msg, code)
213 // FIXME: This method should be removed (every error should have an associated error code).
214 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
215 self.diagnostic().struct_err(msg)
217 pub fn struct_err_with_code(
221 ) -> DiagnosticBuilder<'_> {
222 self.diagnostic().struct_err_with_code(msg, code)
224 pub fn struct_span_fatal<S: Into<MultiSpan>>(
228 ) -> DiagnosticBuilder<'_> {
229 self.diagnostic().struct_span_fatal(sp, msg)
231 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
236 ) -> DiagnosticBuilder<'_> {
237 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
239 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
240 self.diagnostic().struct_fatal(msg)
243 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
244 self.diagnostic().span_fatal(sp, msg).raise()
246 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
253 .span_fatal_with_code(sp, msg, code)
256 pub fn fatal(&self, msg: &str) -> ! {
257 self.diagnostic().fatal(msg).raise()
259 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
261 self.span_warn(sp, msg);
263 self.span_err(sp, msg);
266 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
267 self.diagnostic().span_err(sp, msg)
269 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
270 self.diagnostic().span_err_with_code(sp, &msg, code)
272 pub fn err(&self, msg: &str) {
273 self.diagnostic().err(msg)
275 pub fn err_count(&self) -> usize {
276 self.diagnostic().err_count()
278 pub fn has_errors(&self) -> bool {
279 self.diagnostic().has_errors()
281 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
282 self.diagnostic().has_errors_or_delayed_span_bugs()
284 pub fn abort_if_errors(&self) {
285 self.diagnostic().abort_if_errors();
287 pub fn compile_status(&self) -> Result<(), ErrorReported> {
288 if self.has_errors() {
289 self.diagnostic().emit_stashed_diagnostics();
295 // FIXME(matthewjasper) Remove this method, it should never be needed.
296 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
300 let old_count = self.err_count();
302 let errors = self.err_count() - old_count;
309 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
310 self.diagnostic().span_warn(sp, msg)
312 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
313 self.diagnostic().span_warn_with_code(sp, msg, code)
315 pub fn warn(&self, msg: &str) {
316 self.diagnostic().warn(msg)
318 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
320 Some(sp) => self.span_warn(sp, msg),
321 None => self.warn(msg),
324 /// Delay a span_bug() call until abort_if_errors()
325 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
326 self.diagnostic().delay_span_bug(sp, msg)
328 pub fn note_without_error(&self, msg: &str) {
329 self.diagnostic().note_without_error(msg)
331 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
332 self.diagnostic().span_note_without_error(sp, msg)
335 pub fn diagnostic(&self) -> &rustc_errors::Handler {
336 &self.parse_sess.span_diagnostic
339 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
340 /// deduplicates on lint ID, span (if any), and message for this `Session`
341 fn diag_once<'a, 'b>(
343 diag_builder: &'b mut DiagnosticBuilder<'a>,
344 method: DiagnosticBuilderMethod,
345 msg_id: DiagnosticMessageId,
347 span_maybe: Option<Span>,
349 let id_span_message = (msg_id, span_maybe, message.to_owned());
350 let fresh = self.one_time_diagnostics
352 .insert(id_span_message);
355 DiagnosticBuilderMethod::Note => {
356 diag_builder.note(message);
358 DiagnosticBuilderMethod::SpanNote => {
359 let span = span_maybe.expect("`span_note` needs a span");
360 diag_builder.span_note(span, message);
362 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
363 let span = span_maybe.expect("`span_suggestion_*` needs a span");
364 diag_builder.span_suggestion(
368 Applicability::Unspecified,
375 pub fn diag_span_note_once<'a, 'b>(
377 diag_builder: &'b mut DiagnosticBuilder<'a>,
378 msg_id: DiagnosticMessageId,
384 DiagnosticBuilderMethod::SpanNote,
391 pub fn diag_note_once<'a, 'b>(
393 diag_builder: &'b mut DiagnosticBuilder<'a>,
394 msg_id: DiagnosticMessageId,
399 DiagnosticBuilderMethod::Note,
406 pub fn diag_span_suggestion_once<'a, 'b>(
408 diag_builder: &'b mut DiagnosticBuilder<'a>,
409 msg_id: DiagnosticMessageId,
416 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
423 pub fn source_map(&self) -> &source_map::SourceMap {
424 self.parse_sess.source_map()
426 pub fn verbose(&self) -> bool {
427 self.opts.debugging_opts.verbose
429 pub fn time_passes(&self) -> bool {
430 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
432 pub fn time_extended(&self) -> bool {
433 self.opts.debugging_opts.time_passes
435 pub fn instrument_mcount(&self) -> bool {
436 self.opts.debugging_opts.instrument_mcount
438 pub fn time_llvm_passes(&self) -> bool {
439 self.opts.debugging_opts.time_llvm_passes
441 pub fn meta_stats(&self) -> bool {
442 self.opts.debugging_opts.meta_stats
444 pub fn asm_comments(&self) -> bool {
445 self.opts.debugging_opts.asm_comments
447 pub fn verify_llvm_ir(&self) -> bool {
448 self.opts.debugging_opts.verify_llvm_ir
449 || cfg!(always_verify_llvm_ir)
451 pub fn borrowck_stats(&self) -> bool {
452 self.opts.debugging_opts.borrowck_stats
454 pub fn print_llvm_passes(&self) -> bool {
455 self.opts.debugging_opts.print_llvm_passes
457 pub fn binary_dep_depinfo(&self) -> bool {
458 self.opts.debugging_opts.binary_dep_depinfo
461 /// Gets the features enabled for the current compilation session.
462 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
463 /// dependency tracking. Use tcx.features() instead.
465 pub fn features_untracked(&self) -> &rustc_feature::Features {
469 pub fn init_features(&self, features: rustc_feature::Features) {
470 self.features.set(features);
473 /// Calculates the flavor of LTO to use for this compilation.
474 pub fn lto(&self) -> config::Lto {
475 // If our target has codegen requirements ignore the command line
476 if self.target.target.options.requires_lto {
477 return config::Lto::Fat;
480 // If the user specified something, return that. If they only said `-C
481 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
482 // then ensure we can't use a ThinLTO.
483 match self.opts.cg.lto {
484 config::LtoCli::Unspecified => {
485 // The compiler was invoked without the `-Clto` flag. Fall
486 // through to the default handling
488 config::LtoCli::No => {
489 // The user explicitly opted out of any kind of LTO
490 return config::Lto::No;
492 config::LtoCli::Yes |
493 config::LtoCli::Fat |
494 config::LtoCli::NoParam => {
495 // All of these mean fat LTO
496 return config::Lto::Fat;
498 config::LtoCli::Thin => {
499 return if self.opts.cli_forced_thinlto_off {
507 // Ok at this point the target doesn't require anything and the user
508 // hasn't asked for anything. Our next decision is whether or not
509 // we enable "auto" ThinLTO where we use multiple codegen units and
510 // then do ThinLTO over those codegen units. The logic below will
511 // either return `No` or `ThinLocal`.
513 // If processing command line options determined that we're incompatible
514 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
515 if self.opts.cli_forced_thinlto_off {
516 return config::Lto::No;
519 // If `-Z thinlto` specified process that, but note that this is mostly
520 // a deprecated option now that `-C lto=thin` exists.
521 if let Some(enabled) = self.opts.debugging_opts.thinlto {
523 return config::Lto::ThinLocal;
525 return config::Lto::No;
529 // If there's only one codegen unit and LTO isn't enabled then there's
530 // no need for ThinLTO so just return false.
531 if self.codegen_units() == 1 {
532 return config::Lto::No;
535 // Now we're in "defaults" territory. By default we enable ThinLTO for
536 // optimized compiles (anything greater than O0).
537 match self.opts.optimize {
538 config::OptLevel::No => config::Lto::No,
539 _ => config::Lto::ThinLocal,
543 /// Returns the panic strategy for this compile session. If the user explicitly selected one
544 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
545 pub fn panic_strategy(&self) -> PanicStrategy {
549 .unwrap_or(self.target.target.options.panic_strategy)
551 pub fn fewer_names(&self) -> bool {
552 let more_names = self.opts
554 .contains_key(&OutputType::LlvmAssembly)
555 || self.opts.output_types.contains_key(&OutputType::Bitcode);
557 // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
558 let more_names = match self.opts.debugging_opts.sanitizer {
559 Some(Sanitizer::Address) => true,
560 Some(Sanitizer::Memory) => true,
564 self.opts.debugging_opts.fewer_names || !more_names
567 pub fn no_landing_pads(&self) -> bool {
568 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
570 pub fn unstable_options(&self) -> bool {
571 self.opts.debugging_opts.unstable_options
573 pub fn overflow_checks(&self) -> bool {
577 .or(self.opts.debugging_opts.force_overflow_checks)
578 .unwrap_or(self.opts.debug_assertions)
581 pub fn crt_static(&self) -> bool {
582 // If the target does not opt in to crt-static support, use its default.
583 if self.target.target.options.crt_static_respected {
584 self.crt_static_feature()
586 self.target.target.options.crt_static_default
590 pub fn crt_static_feature(&self) -> bool {
591 let requested_features = self.opts.cg.target_feature.split(',');
592 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
593 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
595 // If the target we're compiling for requests a static crt by default,
596 // then see if the `-crt-static` feature was passed to disable that.
597 // Otherwise if we don't have a static crt by default then see if the
598 // `+crt-static` feature was passed.
599 if self.target.target.options.crt_static_default {
606 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
607 // "mcount" function relies on stack pointer.
608 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
609 if self.instrument_mcount() {
611 } else if let Some(x) = self.opts.cg.force_frame_pointers {
614 !self.target.target.options.eliminate_frame_pointer
618 /// Returns the symbol name for the registrar function,
619 /// given the crate `Svh` and the function `DefIndex`.
620 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
622 "__rustc_plugin_registrar_{}__",
623 disambiguator.to_fingerprint().to_hex()
627 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
629 "__rustc_proc_macro_decls_{}__",
630 disambiguator.to_fingerprint().to_hex()
634 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
635 filesearch::FileSearch::new(
637 self.opts.target_triple.triple(),
638 &self.opts.search_paths,
639 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
640 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
644 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
645 filesearch::FileSearch::new(
647 config::host_triple(),
648 &self.opts.search_paths,
649 &self.host_tlib_path,
654 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
655 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
657 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
658 *load_dep_graph = load;
662 pub fn incr_session_load_dep_graph(&self) -> bool {
663 let incr_comp_session = self.incr_comp_session.borrow();
664 match *incr_comp_session {
665 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
670 pub fn init_incr_comp_session(
672 session_dir: PathBuf,
673 lock_file: flock::Lock,
674 load_dep_graph: bool,
676 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
678 if let IncrCompSession::NotInitialized = *incr_comp_session {
681 "Trying to initialize IncrCompSession `{:?}`",
686 *incr_comp_session = IncrCompSession::Active {
687 session_directory: session_dir,
693 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
694 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
696 if let IncrCompSession::Active { .. } = *incr_comp_session {
699 "trying to finalize `IncrCompSession` `{:?}`",
704 // Note: this will also drop the lock file, thus unlocking the directory.
705 *incr_comp_session = IncrCompSession::Finalized {
706 session_directory: new_directory_path,
710 pub fn mark_incr_comp_session_as_invalid(&self) {
711 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
713 let session_directory = match *incr_comp_session {
714 IncrCompSession::Active {
715 ref session_directory,
717 } => session_directory.clone(),
718 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
720 "trying to invalidate `IncrCompSession` `{:?}`",
725 // Note: this will also drop the lock file, thus unlocking the directory.
726 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
731 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
732 let incr_comp_session = self.incr_comp_session.borrow();
735 |incr_comp_session| match *incr_comp_session {
736 IncrCompSession::NotInitialized => panic!(
737 "trying to get session directory from `IncrCompSession`: {:?}",
740 IncrCompSession::Active {
741 ref session_directory,
744 | IncrCompSession::Finalized {
745 ref session_directory,
747 | IncrCompSession::InvalidBecauseOfErrors {
748 ref session_directory,
749 } => session_directory,
754 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
755 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
758 pub fn print_perf_stats(&self) {
760 "Total time spent computing symbol hashes: {}",
761 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
764 "Total time spent decoding DefPath tables: {}",
765 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
767 println!("Total queries canonicalized: {}",
768 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed));
769 println!("normalize_ty_after_erasing_regions: {}",
770 self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed));
771 println!("normalize_projection_ty: {}",
772 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed));
775 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
776 /// This expends fuel if applicable, and records fuel if applicable.
777 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
779 if let Some(ref c) = self.optimization_fuel_crate {
781 assert_eq!(self.threads(), 1);
782 let mut fuel = self.optimization_fuel.lock();
783 ret = fuel.remaining != 0;
784 if fuel.remaining == 0 && !fuel.out_of_fuel {
785 eprintln!("optimization-fuel-exhausted: {}", msg());
786 fuel.out_of_fuel = true;
787 } else if fuel.remaining > 0 {
792 if let Some(ref c) = self.print_fuel_crate {
794 assert_eq!(self.threads(), 1);
795 self.print_fuel.fetch_add(1, SeqCst);
801 /// Returns the number of query threads that should be used for this
803 pub fn threads(&self) -> usize {
804 self.opts.debugging_opts.threads
807 /// Returns the number of codegen units that should be used for this
809 pub fn codegen_units(&self) -> usize {
810 if let Some(n) = self.opts.cli_forced_codegen_units {
813 if let Some(n) = self.target.target.options.default_codegen_units {
817 // Why is 16 codegen units the default all the time?
819 // The main reason for enabling multiple codegen units by default is to
820 // leverage the ability for the codegen backend to do codegen and
821 // optimization in parallel. This allows us, especially for large crates, to
822 // make good use of all available resources on the machine once we've
823 // hit that stage of compilation. Large crates especially then often
824 // take a long time in codegen/optimization and this helps us amortize that
827 // Note that a high number here doesn't mean that we'll be spawning a
828 // large number of threads in parallel. The backend of rustc contains
829 // global rate limiting through the `jobserver` crate so we'll never
830 // overload the system with too much work, but rather we'll only be
831 // optimizing when we're otherwise cooperating with other instances of
834 // Rather a high number here means that we should be able to keep a lot
835 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
836 // to build we'll be guaranteed that all cpus will finish pretty closely
837 // to one another and we should make relatively optimal use of system
840 // Note that the main cost of codegen units is that it prevents LLVM
841 // from inlining across codegen units. Users in general don't have a lot
842 // of control over how codegen units are split up so it's our job in the
843 // compiler to ensure that undue performance isn't lost when using
844 // codegen units (aka we can't require everyone to slap `#[inline]` on
847 // If we're compiling at `-O0` then the number doesn't really matter too
848 // much because performance doesn't matter and inlining is ok to lose.
849 // In debug mode we just want to try to guarantee that no cpu is stuck
850 // doing work that could otherwise be farmed to others.
852 // In release mode, however (O1 and above) performance does indeed
853 // matter! To recover the loss in performance due to inlining we'll be
854 // enabling ThinLTO by default (the function for which is just below).
855 // This will ensure that we recover any inlining wins we otherwise lost
856 // through codegen unit partitioning.
860 // Ok that's a lot of words but the basic tl;dr; is that we want a high
861 // number here -- but not too high. Additionally we're "safe" to have it
862 // always at the same number at all optimization levels.
864 // As a result 16 was chosen here! Mostly because it was a power of 2
865 // and most benchmarks agreed it was roughly a local optimum. Not very
870 pub fn teach(&self, code: &DiagnosticId) -> bool {
871 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
874 pub fn rust_2015(&self) -> bool {
875 self.opts.edition == Edition::Edition2015
878 /// Are we allowed to use features from the Rust 2018 edition?
879 pub fn rust_2018(&self) -> bool {
880 self.opts.edition >= Edition::Edition2018
883 pub fn edition(&self) -> Edition {
887 /// Returns `true` if we cannot skip the PLT for shared library calls.
888 pub fn needs_plt(&self) -> bool {
889 // Check if the current target usually needs PLT to be enabled.
890 // The user can use the command line flag to override it.
891 let needs_plt = self.target.target.options.needs_plt;
893 let dbg_opts = &self.opts.debugging_opts;
895 let relro_level = dbg_opts.relro_level
896 .unwrap_or(self.target.target.options.relro_level);
898 // Only enable this optimization by default if full relro is also enabled.
899 // In this case, lazy binding was already unavailable, so nothing is lost.
900 // This also ensures `-Wl,-z,now` is supported by the linker.
901 let full_relro = RelroLevel::Full == relro_level;
903 // If user didn't explicitly forced us to use / skip the PLT,
904 // then try to skip it where possible.
905 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
909 pub fn build_session(
910 sopts: config::Options,
911 local_crate_source_file: Option<PathBuf>,
912 registry: rustc_errors::registry::Registry,
914 let file_path_mapping = sopts.file_path_mapping();
916 build_session_with_source_map(
918 local_crate_source_file,
920 Lrc::new(source_map::SourceMap::new(file_path_mapping)),
921 DiagnosticOutput::Default,
927 sopts: &config::Options,
928 registry: rustc_errors::registry::Registry,
929 source_map: &Lrc<source_map::SourceMap>,
930 emitter_dest: Option<Box<dyn Write + Send>>,
931 ) -> Box<dyn Emitter + sync::Send> {
932 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
933 match (sopts.error_format, emitter_dest) {
934 (config::ErrorOutputType::HumanReadable(kind), dst) => {
935 let (short, color_config) = kind.unzip();
937 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
938 let emitter = AnnotateSnippetEmitterWriter::new(
939 Some(source_map.clone()),
941 external_macro_backtrace,
943 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
945 let emitter = match dst {
946 None => EmitterWriter::stderr(
948 Some(source_map.clone()),
950 sopts.debugging_opts.teach,
951 sopts.debugging_opts.terminal_width,
952 external_macro_backtrace,
954 Some(dst) => EmitterWriter::new(
956 Some(source_map.clone()),
958 false, // no teach messages when writing to a buffer
959 false, // no colors when writing to a buffer
960 None, // no terminal width
961 external_macro_backtrace,
964 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
967 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
973 external_macro_backtrace,
974 ).ui_testing(sopts.debugging_opts.ui_testing),
976 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
983 external_macro_backtrace,
984 ).ui_testing(sopts.debugging_opts.ui_testing),
989 pub enum DiagnosticOutput {
991 Raw(Box<dyn Write + Send>)
994 pub fn build_session_with_source_map(
995 sopts: config::Options,
996 local_crate_source_file: Option<PathBuf>,
997 registry: rustc_errors::registry::Registry,
998 source_map: Lrc<source_map::SourceMap>,
999 diagnostics_output: DiagnosticOutput,
1000 lint_caps: FxHashMap<lint::LintId, lint::Level>,
1002 // FIXME: This is not general enough to make the warning lint completely override
1003 // normal diagnostic warnings, since the warning lint can also be denied and changed
1004 // later via the source code.
1005 let warnings_allow = sopts
1008 .filter(|&&(ref key, _)| *key == "warnings")
1009 .map(|&(_, ref level)| *level == lint::Allow)
1012 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1014 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1016 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
1017 let dont_buffer_diagnostics = sopts.debugging_opts.dont_buffer_diagnostics;
1018 let report_delayed_bugs = sopts.debugging_opts.report_delayed_bugs;
1020 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
1022 let write_dest = match diagnostics_output {
1023 DiagnosticOutput::Default => None,
1024 DiagnosticOutput::Raw(write) => Some(write),
1026 let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
1028 let diagnostic_handler = rustc_errors::Handler::with_emitter_and_flags(
1030 rustc_errors::HandlerFlags {
1033 report_delayed_bugs,
1034 dont_buffer_diagnostics,
1035 external_macro_backtrace,
1036 ..Default::default()
1042 local_crate_source_file,
1050 sopts: config::Options,
1051 local_crate_source_file: Option<PathBuf>,
1052 span_diagnostic: rustc_errors::Handler,
1053 source_map: Lrc<source_map::SourceMap>,
1054 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1057 if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile {
1058 let directory = if let Some(ref directory) = d {
1061 std::path::Path::new(".")
1064 let profiler = SelfProfiler::new(
1066 sopts.crate_name.as_ref().map(|s| &s[..]),
1067 &sopts.debugging_opts.self_profile_events
1071 Some(Arc::new(profiler))
1074 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1082 let host_triple = TargetTriple::from_triple(config::host_triple());
1083 let host = Target::search(&host_triple).unwrap_or_else(|e|
1085 .fatal(&format!("Error loading host specification: {}", e))
1088 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
1090 let parse_sess = ParseSess::with_span_handler(
1094 let sysroot = match &sopts.maybe_sysroot {
1095 Some(sysroot) => sysroot.clone(),
1096 None => filesearch::get_or_default_sysroot(),
1099 let host_triple = config::host_triple();
1100 let target_triple = sopts.target_triple.triple();
1101 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1102 let target_tlib_path = if host_triple == target_triple {
1105 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1108 let file_path_mapping = sopts.file_path_mapping();
1110 let local_crate_source_file =
1111 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1113 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1114 let optimization_fuel = Lock::new(OptimizationFuel {
1115 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1118 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1119 let print_fuel = AtomicU64::new(0);
1121 let working_dir = env::current_dir().unwrap_or_else(|e|
1122 parse_sess.span_diagnostic
1123 .fatal(&format!("Current directory is invalid: {}", e))
1126 let working_dir = file_path_mapping.map_prefix(working_dir);
1128 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1129 CguReuseTracker::new()
1131 CguReuseTracker::new_disabled()
1134 let sess = Session {
1142 local_crate_source_file,
1144 one_time_diagnostics: Default::default(),
1145 crate_types: Once::new(),
1146 crate_disambiguator: Once::new(),
1147 features: Once::new(),
1148 recursion_limit: Once::new(),
1149 type_length_limit: Once::new(),
1150 imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())),
1151 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1153 prof: SelfProfilerRef::new(self_profiler),
1154 perf_stats: PerfStats {
1155 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1156 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1157 queries_canonicalized: AtomicUsize::new(0),
1158 normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1159 normalize_projection_ty: AtomicUsize::new(0),
1161 code_stats: Default::default(),
1162 optimization_fuel_crate,
1166 jobserver: jobserver::client(),
1168 trait_methods_not_found: Lock::new(Default::default()),
1169 confused_type_with_std_module: Lock::new(Default::default()),
1172 validate_commandline_args_with_session_available(&sess);
1177 // If it is useful to have a Session available already for validating a
1178 // commandline argument, you can do so here.
1179 fn validate_commandline_args_with_session_available(sess: &Session) {
1180 // Since we don't know if code in an rlib will be linked to statically or
1181 // dynamically downstream, rustc generates `__imp_` symbols that help the
1182 // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1183 // these manually generated symbols confuse LLD when it tries to merge
1184 // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1185 // when compiling for LLD ThinLTO. This way we can validly just not generate
1186 // the `dllimport` attributes and `__imp_` symbols in that case.
1187 if sess.opts.cg.linker_plugin_lto.enabled() &&
1188 sess.opts.cg.prefer_dynamic &&
1189 sess.target.target.options.is_like_msvc {
1190 sess.err("Linker plugin based LTO is not supported together with \
1191 `-C prefer-dynamic` when targeting MSVC");
1194 // Make sure that any given profiling data actually exists so LLVM can't
1195 // decide to silently skip PGO.
1196 if let Some(ref path) = sess.opts.cg.profile_use {
1198 sess.err(&format!("File `{}` passed to `-C profile-use` does not exist.",
1203 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1204 // an error to combine the two for now. It always runs into an assertions
1205 // if LLVM is built with assertions, but without assertions it sometimes
1206 // does not crash and will probably generate a corrupted binary.
1207 // We should only display this error if we're actually going to run PGO.
1208 // If we're just supposed to print out some data, don't show the error (#61002).
1209 if sess.opts.cg.profile_generate.enabled() &&
1210 sess.target.target.options.is_like_msvc &&
1211 sess.panic_strategy() == PanicStrategy::Unwind &&
1212 sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
1213 sess.err("Profile-guided optimization does not yet work in conjunction \
1214 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1215 See https://github.com/rust-lang/rust/issues/61002 for details.");
1219 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1220 /// compiler. Together with the crate-name forms a unique global identifier for
1222 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1223 pub struct CrateDisambiguator(Fingerprint);
1225 impl CrateDisambiguator {
1226 pub fn to_fingerprint(self) -> Fingerprint {
1231 impl fmt::Display for CrateDisambiguator {
1232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1233 let (a, b) = self.0.as_value();
1234 let as_u128 = a as u128 | ((b as u128) << 64);
1235 f.write_str(&base_n::encode(as_u128, base_n::CASE_INSENSITIVE))
1239 impl From<Fingerprint> for CrateDisambiguator {
1240 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1241 CrateDisambiguator(fingerprint)
1245 impl_stable_hash_via_hash!(CrateDisambiguator);
1247 /// Holds data on the current incremental compilation session, if there is one.
1249 pub enum IncrCompSession {
1250 /// This is the state the session will be in until the incr. comp. dir is
1253 /// This is the state during which the session directory is private and can
1256 session_directory: PathBuf,
1257 lock_file: flock::Lock,
1258 load_dep_graph: bool,
1260 /// This is the state after the session directory has been finalized. In this
1261 /// state, the contents of the directory must not be modified any more.
1262 Finalized { session_directory: PathBuf },
1263 /// This is an error state that is reached when some compilation error has
1264 /// occurred. It indicates that the contents of the session directory must
1265 /// not be used, since they might be invalid.
1266 InvalidBecauseOfErrors { session_directory: PathBuf },
1269 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1270 let emitter: Box<dyn Emitter + sync::Send> = match output {
1271 config::ErrorOutputType::HumanReadable(kind) => {
1272 let (short, color_config) = kind.unzip();
1273 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1275 config::ErrorOutputType::Json { pretty, json_rendered } =>
1276 Box::new(JsonEmitter::basic(pretty, json_rendered, false)),
1278 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1279 handler.struct_fatal(msg).emit();
1280 rustc_errors::FatalError.raise();
1283 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1284 let emitter: Box<dyn Emitter + sync::Send> = match output {
1285 config::ErrorOutputType::HumanReadable(kind) => {
1286 let (short, color_config) = kind.unzip();
1287 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1289 config::ErrorOutputType::Json { pretty, json_rendered } =>
1290 Box::new(JsonEmitter::basic(pretty, json_rendered, false)),
1292 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1293 handler.struct_warn(msg).emit();
1296 pub type CompileResult = Result<(), ErrorReported>;