1 use crate::cgu_reuse_tracker::CguReuseTracker;
2 use crate::code_stats::CodeStats;
3 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::config::{self, CrateType, OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
10 pub use rustc_ast::crate_disambiguator::CrateDisambiguator;
11 use rustc_data_structures::flock;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::jobserver::{self, Client};
14 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
15 use rustc_data_structures::sync::{
16 self, AtomicU64, AtomicUsize, Lock, Lrc, Once, OneThread, Ordering, Ordering::SeqCst,
18 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
19 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
20 use rustc_errors::json::JsonEmitter;
21 use rustc_errors::registry::Registry;
22 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported};
23 use rustc_span::edition::Edition;
24 use rustc_span::source_map::{self, FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
25 use rustc_span::{SourceFileHashAlgorithm, Symbol};
26 use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, Target, TargetTriple, TlsModel};
28 use std::cell::{self, RefCell};
31 use std::num::NonZeroU32;
32 use std::path::PathBuf;
34 use std::time::Duration;
36 pub struct OptimizationFuel {
37 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
39 /// We're rejecting all further optimizations.
43 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
44 #[derive(Clone, Copy)]
45 pub enum CtfeBacktrace {
46 /// Do nothing special, return the error as usual without a backtrace.
48 /// Capture a backtrace at the point the error is created and return it in the error
49 /// (to be printed later if/when the error ever actually gets shown to the user).
51 /// Capture a backtrace at the point the error is created and immediately print it out.
55 /// Represents the data associated with a compilation
56 /// session for a single crate.
58 pub target: config::Config,
60 pub opts: config::Options,
61 pub host_tlib_path: SearchPath,
62 /// `None` if the host and target are the same.
63 pub target_tlib_path: Option<SearchPath>,
64 pub parse_sess: ParseSess,
66 /// The name of the root source file of the crate, in the local file system.
67 /// `None` means that there is no source file.
68 pub local_crate_source_file: Option<PathBuf>,
69 /// The directory the compiler has been executed in plus a flag indicating
70 /// if the value stored here has been affected by path remapping.
71 pub working_dir: (PathBuf, bool),
73 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
74 /// (sub)diagnostics that have been set once, but should not be set again,
75 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
76 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
77 pub crate_types: Once<Vec<CrateType>>,
78 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
79 /// arguments passed to the compiler. Its value together with the crate-name
80 /// forms a unique global identifier for the crate. It is used to allow
81 /// multiple crates with the same name to coexist. See the
82 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
83 pub crate_disambiguator: Once<CrateDisambiguator>,
85 features: Once<rustc_feature::Features>,
87 /// The maximum recursion limit for potentially infinitely recursive
88 /// operations such as auto-dereference and monomorphization.
89 pub recursion_limit: Once<usize>,
91 /// The maximum length of types during monomorphization.
92 pub type_length_limit: Once<usize>,
94 /// The maximum blocks a const expression can evaluate.
95 pub const_eval_limit: Once<usize>,
97 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
98 /// Used for incremental compilation tests. Will only be populated if
99 /// `-Zquery-dep-graph` is specified.
100 pub cgu_reuse_tracker: CguReuseTracker,
102 /// Used by `-Z self-profile`.
103 pub prof: SelfProfilerRef,
105 /// Some measurements that are being gathered during compilation.
106 pub perf_stats: PerfStats,
108 /// Data about code being compiled, gathered during compilation.
109 pub code_stats: CodeStats,
111 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
112 optimization_fuel_crate: Option<String>,
114 /// Tracks fuel info if `-zfuel=crate=n` is specified.
115 optimization_fuel: Lock<OptimizationFuel>,
117 // The next two are public because the driver needs to read them.
118 /// If `-zprint-fuel=crate`, `Some(crate)`.
119 pub print_fuel_crate: Option<String>,
120 /// Always set to zero and incremented so that we can print fuel expended by a crate.
121 pub print_fuel: AtomicU64,
123 /// Loaded up early on in the initialization of this `Session` to avoid
124 /// false positives about a job server in our environment.
125 pub jobserver: Client,
127 /// Cap lint level specified by a driver specifically.
128 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
130 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
131 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
133 /// Mapping from ident span to path span for paths that don't exist as written, but that
134 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
135 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
137 /// Path for libraries that will take preference over libraries shipped by Rust.
138 /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
139 pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
141 /// Tracks the current behavior of the CTFE engine when an error occurs.
142 /// Options range from returning the error without a backtrace to returning an error
143 /// and immediately printing the backtrace to stderr.
144 pub ctfe_backtrace: Lock<CtfeBacktrace>,
146 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
147 /// const check, optionally with the relevant feature gate. We use this to
148 /// warn about unleashing, but with a single diagnostic instead of dozens that
149 /// drown everything else in noise.
150 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
152 /// Base directory containing the `src/` for the Rust standard library, and
153 /// potentially `rustc` as well, if we can can find it. Right now it's always
154 /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
156 /// This directory is what the virtual `/rustc/$hash` is translated back to,
157 /// if Rust was built with path remapping to `/rustc/$hash` enabled
158 /// (the `rust.remap-debuginfo` option in `config.toml`).
159 pub real_rust_source_base_dir: Option<PathBuf>,
162 pub struct PerfStats {
163 /// The accumulated time spent on computing symbol hashes.
164 pub symbol_hash_time: Lock<Duration>,
165 /// The accumulated time spent decoding def path tables from metadata.
166 pub decode_def_path_tables_time: Lock<Duration>,
167 /// Total number of values canonicalized queries constructed.
168 pub queries_canonicalized: AtomicUsize,
169 /// Number of times this query is invoked.
170 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
171 /// Number of times this query is invoked.
172 pub normalize_projection_ty: AtomicUsize,
175 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
176 enum DiagnosticBuilderMethod {
179 SpanSuggestion(String), // suggestion
180 // Add more variants as needed to support one-time diagnostics.
183 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
184 /// emitting the same message more than once.
185 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
186 pub enum DiagnosticMessageId {
187 ErrorId(u16), // EXXXX error code as integer
188 LintId(lint::LintId),
189 StabilityId(Option<NonZeroU32>), // issue number
192 impl From<&'static lint::Lint> for DiagnosticMessageId {
193 fn from(lint: &'static lint::Lint) -> Self {
194 DiagnosticMessageId::LintId(lint::LintId::of(lint))
199 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
200 self.miri_unleashed_features.lock().push((span, feature_gate));
203 fn check_miri_unleashed_features(&self) {
204 let unleashed_features = self.miri_unleashed_features.lock();
205 if !unleashed_features.is_empty() {
206 let mut must_err = false;
207 // Create a diagnostic pointing at where things got unleashed.
208 let mut diag = self.struct_warn("skipping const checks");
209 for &(span, feature_gate) in unleashed_features.iter() {
210 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
211 if let Some(feature_gate) = feature_gate {
212 diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate));
213 // The unleash flag must *not* be used to just "hack around" feature gates.
216 diag.span_help(span, "skipping check that does not even have a feature gate");
220 // If we should err, make sure we did.
221 if must_err && !self.has_errors() {
222 // We have skipped a feature gate, and not run into other errors... reject.
224 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
225 gates, except when testing error paths in the CTFE engine",
231 /// Invoked all the way at the end to finish off diagnostics printing.
232 pub fn finish_diagnostics(&self, registry: &Registry) {
233 self.check_miri_unleashed_features();
234 self.diagnostic().print_error_count(registry);
237 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
238 *self.crate_disambiguator.get()
241 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
242 self.diagnostic().struct_span_warn(sp, msg)
244 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
249 ) -> DiagnosticBuilder<'_> {
250 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
252 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
253 self.diagnostic().struct_warn(msg)
255 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
256 self.diagnostic().struct_span_err(sp, msg)
258 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
263 ) -> DiagnosticBuilder<'_> {
264 self.diagnostic().struct_span_err_with_code(sp, msg, code)
266 // FIXME: This method should be removed (every error should have an associated error code).
267 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
268 self.diagnostic().struct_err(msg)
270 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
271 self.diagnostic().struct_err_with_code(msg, code)
273 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
274 self.diagnostic().struct_span_fatal(sp, msg)
276 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
281 ) -> DiagnosticBuilder<'_> {
282 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
284 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
285 self.diagnostic().struct_fatal(msg)
288 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
289 self.diagnostic().span_fatal(sp, msg).raise()
291 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
297 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
299 pub fn fatal(&self, msg: &str) -> ! {
300 self.diagnostic().fatal(msg).raise()
302 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
304 self.span_warn(sp, msg);
306 self.span_err(sp, msg);
309 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
310 self.diagnostic().span_err(sp, msg)
312 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
313 self.diagnostic().span_err_with_code(sp, &msg, code)
315 pub fn err(&self, msg: &str) {
316 self.diagnostic().err(msg)
318 pub fn err_count(&self) -> usize {
319 self.diagnostic().err_count()
321 pub fn has_errors(&self) -> bool {
322 self.diagnostic().has_errors()
324 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
325 self.diagnostic().has_errors_or_delayed_span_bugs()
327 pub fn abort_if_errors(&self) {
328 self.diagnostic().abort_if_errors();
330 pub fn compile_status(&self) -> Result<(), ErrorReported> {
331 if self.has_errors() {
332 self.diagnostic().emit_stashed_diagnostics();
338 // FIXME(matthewjasper) Remove this method, it should never be needed.
339 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
343 let old_count = self.err_count();
345 let errors = self.err_count() - old_count;
346 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
348 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
349 self.diagnostic().span_warn(sp, msg)
351 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
352 self.diagnostic().span_warn_with_code(sp, msg, code)
354 pub fn warn(&self, msg: &str) {
355 self.diagnostic().warn(msg)
357 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
359 Some(sp) => self.span_warn(sp, msg),
360 None => self.warn(msg),
363 /// Delay a span_bug() call until abort_if_errors()
364 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
365 self.diagnostic().delay_span_bug(sp, msg)
367 pub fn note_without_error(&self, msg: &str) {
368 self.diagnostic().note_without_error(msg)
370 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
371 self.diagnostic().span_note_without_error(sp, msg)
374 pub fn diagnostic(&self) -> &rustc_errors::Handler {
375 &self.parse_sess.span_diagnostic
378 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
379 /// deduplicates on lint ID, span (if any), and message for this `Session`
380 fn diag_once<'a, 'b>(
382 diag_builder: &'b mut DiagnosticBuilder<'a>,
383 method: DiagnosticBuilderMethod,
384 msg_id: DiagnosticMessageId,
386 span_maybe: Option<Span>,
388 let id_span_message = (msg_id, span_maybe, message.to_owned());
389 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
392 DiagnosticBuilderMethod::Note => {
393 diag_builder.note(message);
395 DiagnosticBuilderMethod::SpanNote => {
396 let span = span_maybe.expect("`span_note` needs a span");
397 diag_builder.span_note(span, message);
399 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
400 let span = span_maybe.expect("`span_suggestion_*` needs a span");
401 diag_builder.span_suggestion(
405 Applicability::Unspecified,
412 pub fn diag_span_note_once<'a, 'b>(
414 diag_builder: &'b mut DiagnosticBuilder<'a>,
415 msg_id: DiagnosticMessageId,
421 DiagnosticBuilderMethod::SpanNote,
428 pub fn diag_note_once<'a, 'b>(
430 diag_builder: &'b mut DiagnosticBuilder<'a>,
431 msg_id: DiagnosticMessageId,
434 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
437 pub fn diag_span_suggestion_once<'a, 'b>(
439 diag_builder: &'b mut DiagnosticBuilder<'a>,
440 msg_id: DiagnosticMessageId,
447 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
455 pub fn source_map(&self) -> &source_map::SourceMap {
456 self.parse_sess.source_map()
458 pub fn verbose(&self) -> bool {
459 self.opts.debugging_opts.verbose
461 pub fn time_passes(&self) -> bool {
462 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
464 pub fn instrument_mcount(&self) -> bool {
465 self.opts.debugging_opts.instrument_mcount
467 pub fn time_llvm_passes(&self) -> bool {
468 self.opts.debugging_opts.time_llvm_passes
470 pub fn meta_stats(&self) -> bool {
471 self.opts.debugging_opts.meta_stats
473 pub fn asm_comments(&self) -> bool {
474 self.opts.debugging_opts.asm_comments
476 pub fn verify_llvm_ir(&self) -> bool {
477 self.opts.debugging_opts.verify_llvm_ir || cfg!(always_verify_llvm_ir)
479 pub fn borrowck_stats(&self) -> bool {
480 self.opts.debugging_opts.borrowck_stats
482 pub fn print_llvm_passes(&self) -> bool {
483 self.opts.debugging_opts.print_llvm_passes
485 pub fn binary_dep_depinfo(&self) -> bool {
486 self.opts.debugging_opts.binary_dep_depinfo
489 /// Gets the features enabled for the current compilation session.
490 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
491 /// dependency tracking. Use tcx.features() instead.
493 pub fn features_untracked(&self) -> &rustc_feature::Features {
497 pub fn init_features(&self, features: rustc_feature::Features) {
498 self.features.set(features);
501 /// Calculates the flavor of LTO to use for this compilation.
502 pub fn lto(&self) -> config::Lto {
503 // If our target has codegen requirements ignore the command line
504 if self.target.target.options.requires_lto {
505 return config::Lto::Fat;
508 // If the user specified something, return that. If they only said `-C
509 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
510 // then ensure we can't use a ThinLTO.
511 match self.opts.cg.lto {
512 config::LtoCli::Unspecified => {
513 // The compiler was invoked without the `-Clto` flag. Fall
514 // through to the default handling
516 config::LtoCli::No => {
517 // The user explicitly opted out of any kind of LTO
518 return config::Lto::No;
520 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
521 // All of these mean fat LTO
522 return config::Lto::Fat;
524 config::LtoCli::Thin => {
525 return if self.opts.cli_forced_thinlto_off {
533 // Ok at this point the target doesn't require anything and the user
534 // hasn't asked for anything. Our next decision is whether or not
535 // we enable "auto" ThinLTO where we use multiple codegen units and
536 // then do ThinLTO over those codegen units. The logic below will
537 // either return `No` or `ThinLocal`.
539 // If processing command line options determined that we're incompatible
540 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
541 if self.opts.cli_forced_thinlto_off {
542 return config::Lto::No;
545 // If `-Z thinlto` specified process that, but note that this is mostly
546 // a deprecated option now that `-C lto=thin` exists.
547 if let Some(enabled) = self.opts.debugging_opts.thinlto {
549 return config::Lto::ThinLocal;
551 return config::Lto::No;
555 // If there's only one codegen unit and LTO isn't enabled then there's
556 // no need for ThinLTO so just return false.
557 if self.codegen_units() == 1 {
558 return config::Lto::No;
561 // Now we're in "defaults" territory. By default we enable ThinLTO for
562 // optimized compiles (anything greater than O0).
563 match self.opts.optimize {
564 config::OptLevel::No => config::Lto::No,
565 _ => config::Lto::ThinLocal,
569 /// Returns the panic strategy for this compile session. If the user explicitly selected one
570 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
571 pub fn panic_strategy(&self) -> PanicStrategy {
572 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
574 pub fn fewer_names(&self) -> bool {
575 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
576 || self.opts.output_types.contains_key(&OutputType::Bitcode);
578 // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
579 let more_names = match self.opts.debugging_opts.sanitizer {
580 Some(Sanitizer::Address) => true,
581 Some(Sanitizer::Memory) => true,
585 self.opts.debugging_opts.fewer_names || !more_names
588 pub fn unstable_options(&self) -> bool {
589 self.opts.debugging_opts.unstable_options
591 pub fn overflow_checks(&self) -> bool {
595 .or(self.opts.debugging_opts.force_overflow_checks)
596 .unwrap_or(self.opts.debug_assertions)
599 /// Check whether this compile session and crate type use static crt.
600 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
601 // If the target does not opt in to crt-static support, use its default.
602 if self.target.target.options.crt_static_respected {
603 self.crt_static_feature(crate_type)
605 self.target.target.options.crt_static_default
609 /// Check whether this compile session and crate type use `crt-static` feature.
610 pub fn crt_static_feature(&self, crate_type: Option<CrateType>) -> bool {
611 let requested_features = self.opts.cg.target_feature.split(',');
612 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
613 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
615 if found_positive || found_negative {
617 } else if crate_type == Some(CrateType::ProcMacro)
618 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
620 // FIXME: When crate_type is not available,
621 // we use compiler options to determine the crate_type.
622 // We can't check `#![crate_type = "proc-macro"]` here.
625 self.target.target.options.crt_static_default
629 pub fn relocation_model(&self) -> RelocModel {
630 self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
633 pub fn tls_model(&self) -> TlsModel {
634 self.opts.debugging_opts.tls_model.unwrap_or(self.target.target.options.tls_model)
637 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
638 // "mcount" function relies on stack pointer.
639 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
640 if self.instrument_mcount() {
642 } else if let Some(x) = self.opts.cg.force_frame_pointers {
645 !self.target.target.options.eliminate_frame_pointer
649 /// Returns the symbol name for the registrar function,
650 /// given the crate `Svh` and the function `DefIndex`.
651 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
652 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
655 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
656 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
659 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
660 filesearch::FileSearch::new(
662 self.opts.target_triple.triple(),
663 &self.opts.search_paths,
664 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
665 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
669 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
670 filesearch::FileSearch::new(
672 config::host_triple(),
673 &self.opts.search_paths,
674 &self.host_tlib_path,
679 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
680 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
682 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
683 *load_dep_graph = load;
687 pub fn incr_session_load_dep_graph(&self) -> bool {
688 let incr_comp_session = self.incr_comp_session.borrow();
689 match *incr_comp_session {
690 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
695 pub fn init_incr_comp_session(
697 session_dir: PathBuf,
698 lock_file: flock::Lock,
699 load_dep_graph: bool,
701 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
703 if let IncrCompSession::NotInitialized = *incr_comp_session {
705 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
709 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
712 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
713 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
715 if let IncrCompSession::Active { .. } = *incr_comp_session {
717 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
720 // Note: this will also drop the lock file, thus unlocking the directory.
721 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
724 pub fn mark_incr_comp_session_as_invalid(&self) {
725 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
727 let session_directory = match *incr_comp_session {
728 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
729 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
730 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
733 // Note: this will also drop the lock file, thus unlocking the directory.
734 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
737 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
738 let incr_comp_session = self.incr_comp_session.borrow();
739 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
740 IncrCompSession::NotInitialized => panic!(
741 "trying to get session directory from `IncrCompSession`: {:?}",
744 IncrCompSession::Active { ref session_directory, .. }
745 | IncrCompSession::Finalized { ref session_directory }
746 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
752 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
753 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
756 pub fn print_perf_stats(&self) {
758 "Total time spent computing symbol hashes: {}",
759 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
762 "Total time spent decoding DefPath tables: {}",
763 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
766 "Total queries canonicalized: {}",
767 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
770 "normalize_generic_arg_after_erasing_regions: {}",
771 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
774 "normalize_projection_ty: {}",
775 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
779 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
780 /// This expends fuel if applicable, and records fuel if applicable.
781 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
783 if let Some(ref c) = self.optimization_fuel_crate {
785 assert_eq!(self.threads(), 1);
786 let mut fuel = self.optimization_fuel.lock();
787 ret = fuel.remaining != 0;
788 if fuel.remaining == 0 && !fuel.out_of_fuel {
789 eprintln!("optimization-fuel-exhausted: {}", msg());
790 fuel.out_of_fuel = true;
791 } else if fuel.remaining > 0 {
796 if let Some(ref c) = self.print_fuel_crate {
798 assert_eq!(self.threads(), 1);
799 self.print_fuel.fetch_add(1, SeqCst);
805 /// Returns the number of query threads that should be used for this
807 pub fn threads(&self) -> usize {
808 self.opts.debugging_opts.threads
811 /// Returns the number of codegen units that should be used for this
813 pub fn codegen_units(&self) -> usize {
814 if let Some(n) = self.opts.cli_forced_codegen_units {
817 if let Some(n) = self.target.target.options.default_codegen_units {
821 // If incremental compilation is turned on, we default to a high number
822 // codegen units in order to reduce the "collateral damage" small
824 if self.opts.incremental.is_some() {
828 // Why is 16 codegen units the default all the time?
830 // The main reason for enabling multiple codegen units by default is to
831 // leverage the ability for the codegen backend to do codegen and
832 // optimization in parallel. This allows us, especially for large crates, to
833 // make good use of all available resources on the machine once we've
834 // hit that stage of compilation. Large crates especially then often
835 // take a long time in codegen/optimization and this helps us amortize that
838 // Note that a high number here doesn't mean that we'll be spawning a
839 // large number of threads in parallel. The backend of rustc contains
840 // global rate limiting through the `jobserver` crate so we'll never
841 // overload the system with too much work, but rather we'll only be
842 // optimizing when we're otherwise cooperating with other instances of
845 // Rather a high number here means that we should be able to keep a lot
846 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
847 // to build we'll be guaranteed that all cpus will finish pretty closely
848 // to one another and we should make relatively optimal use of system
851 // Note that the main cost of codegen units is that it prevents LLVM
852 // from inlining across codegen units. Users in general don't have a lot
853 // of control over how codegen units are split up so it's our job in the
854 // compiler to ensure that undue performance isn't lost when using
855 // codegen units (aka we can't require everyone to slap `#[inline]` on
858 // If we're compiling at `-O0` then the number doesn't really matter too
859 // much because performance doesn't matter and inlining is ok to lose.
860 // In debug mode we just want to try to guarantee that no cpu is stuck
861 // doing work that could otherwise be farmed to others.
863 // In release mode, however (O1 and above) performance does indeed
864 // matter! To recover the loss in performance due to inlining we'll be
865 // enabling ThinLTO by default (the function for which is just below).
866 // This will ensure that we recover any inlining wins we otherwise lost
867 // through codegen unit partitioning.
871 // Ok that's a lot of words but the basic tl;dr; is that we want a high
872 // number here -- but not too high. Additionally we're "safe" to have it
873 // always at the same number at all optimization levels.
875 // As a result 16 was chosen here! Mostly because it was a power of 2
876 // and most benchmarks agreed it was roughly a local optimum. Not very
881 pub fn teach(&self, code: &DiagnosticId) -> bool {
882 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
885 pub fn rust_2015(&self) -> bool {
886 self.opts.edition == Edition::Edition2015
889 /// Are we allowed to use features from the Rust 2018 edition?
890 pub fn rust_2018(&self) -> bool {
891 self.opts.edition >= Edition::Edition2018
894 pub fn edition(&self) -> Edition {
898 /// Returns `true` if we cannot skip the PLT for shared library calls.
899 pub fn needs_plt(&self) -> bool {
900 // Check if the current target usually needs PLT to be enabled.
901 // The user can use the command line flag to override it.
902 let needs_plt = self.target.target.options.needs_plt;
904 let dbg_opts = &self.opts.debugging_opts;
906 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
908 // Only enable this optimization by default if full relro is also enabled.
909 // In this case, lazy binding was already unavailable, so nothing is lost.
910 // This also ensures `-Wl,-z,now` is supported by the linker.
911 let full_relro = RelroLevel::Full == relro_level;
913 // If user didn't explicitly forced us to use / skip the PLT,
914 // then try to skip it where possible.
915 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
919 pub fn build_session(
920 sopts: config::Options,
921 local_crate_source_file: Option<PathBuf>,
922 registry: rustc_errors::registry::Registry,
924 build_session_with_source_map(
926 local_crate_source_file,
928 DiagnosticOutput::Default,
936 sopts: &config::Options,
937 registry: rustc_errors::registry::Registry,
938 source_map: &Lrc<source_map::SourceMap>,
939 emitter_dest: Option<Box<dyn Write + Send>>,
940 ) -> Box<dyn Emitter + sync::Send> {
941 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
942 match (sopts.error_format, emitter_dest) {
943 (config::ErrorOutputType::HumanReadable(kind), dst) => {
944 let (short, color_config) = kind.unzip();
946 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
947 let emitter = AnnotateSnippetEmitterWriter::new(
948 Some(source_map.clone()),
952 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
954 let emitter = match dst {
955 None => EmitterWriter::stderr(
957 Some(source_map.clone()),
959 sopts.debugging_opts.teach,
960 sopts.debugging_opts.terminal_width,
963 Some(dst) => EmitterWriter::new(
965 Some(source_map.clone()),
967 false, // no teach messages when writing to a buffer
968 false, // no colors when writing to a buffer
969 None, // no terminal width
973 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
976 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
984 .ui_testing(sopts.debugging_opts.ui_testing),
986 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
995 .ui_testing(sopts.debugging_opts.ui_testing),
1000 pub enum DiagnosticOutput {
1002 Raw(Box<dyn Write + Send>),
1005 pub fn build_session_with_source_map(
1006 sopts: config::Options,
1007 local_crate_source_file: Option<PathBuf>,
1008 registry: rustc_errors::registry::Registry,
1009 diagnostics_output: DiagnosticOutput,
1010 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1011 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1012 ) -> (Session, Lrc<SourceMap>) {
1013 // FIXME: This is not general enough to make the warning lint completely override
1014 // normal diagnostic warnings, since the warning lint can also be denied and changed
1015 // later via the source code.
1016 let warnings_allow = sopts
1019 .filter(|&&(ref key, _)| *key == "warnings")
1020 .map(|&(_, ref level)| *level == lint::Allow)
1023 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1024 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1026 let write_dest = match diagnostics_output {
1027 DiagnosticOutput::Default => None,
1028 DiagnosticOutput::Raw(write) => Some(write),
1031 let target_cfg = config::build_target_config(&sopts, sopts.error_format);
1032 let host_triple = TargetTriple::from_triple(config::host_triple());
1033 let host = Target::search(&host_triple).unwrap_or_else(|e| {
1034 early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1037 let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
1038 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1039 if target_cfg.target.options.is_like_msvc {
1040 SourceFileHashAlgorithm::Sha1
1042 SourceFileHashAlgorithm::Md5
1045 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1047 sopts.file_path_mapping(),
1050 let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
1052 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1054 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1057 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1060 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1062 let profiler = SelfProfiler::new(
1064 sopts.crate_name.as_ref().map(|s| &s[..]),
1065 &sopts.debugging_opts.self_profile_events,
1068 Ok(profiler) => Some(Arc::new(profiler)),
1070 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1078 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map.clone());
1079 let sysroot = match &sopts.maybe_sysroot {
1080 Some(sysroot) => sysroot.clone(),
1081 None => filesearch::get_or_default_sysroot(),
1084 let host_triple = config::host_triple();
1085 let target_triple = sopts.target_triple.triple();
1086 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1087 let target_tlib_path = if host_triple == target_triple {
1090 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1093 let file_path_mapping = sopts.file_path_mapping();
1095 let local_crate_source_file =
1096 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1098 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1099 let optimization_fuel = Lock::new(OptimizationFuel {
1100 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1103 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1104 let print_fuel = AtomicU64::new(0);
1106 let working_dir = env::current_dir().unwrap_or_else(|e| {
1107 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1109 let working_dir = file_path_mapping.map_prefix(working_dir);
1111 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1112 CguReuseTracker::new()
1114 CguReuseTracker::new_disabled()
1117 let prof = SelfProfilerRef::new(
1119 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1120 sopts.debugging_opts.time_passes,
1123 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1124 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1125 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1126 _ => CtfeBacktrace::Disabled,
1129 // Try to find a directory containing the Rust `src`, for more details see
1130 // the doc comment on the `real_rust_source_base_dir` field.
1131 let real_rust_source_base_dir = {
1132 // This is the location used by the `rust-src` `rustup` component.
1133 let mut candidate = sysroot.join("lib/rustlib/src/rust");
1134 if let Ok(metadata) = candidate.symlink_metadata() {
1135 // Replace the symlink rustbuild creates, with its destination.
1136 // We could try to use `fs::canonicalize` instead, but that might
1137 // produce unnecessarily verbose path.
1138 if metadata.file_type().is_symlink() {
1139 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1140 candidate = symlink_dest;
1145 // Only use this directory if it has a file we can expect to always find.
1146 if candidate.join("src/libstd/lib.rs").is_file() { Some(candidate) } else { None }
1149 let sess = Session {
1157 local_crate_source_file,
1159 one_time_diagnostics: Default::default(),
1160 crate_types: Once::new(),
1161 crate_disambiguator: Once::new(),
1162 features: Once::new(),
1163 recursion_limit: Once::new(),
1164 type_length_limit: Once::new(),
1165 const_eval_limit: Once::new(),
1166 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1169 perf_stats: PerfStats {
1170 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1171 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1172 queries_canonicalized: AtomicUsize::new(0),
1173 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1174 normalize_projection_ty: AtomicUsize::new(0),
1176 code_stats: Default::default(),
1177 optimization_fuel_crate,
1181 jobserver: jobserver::client(),
1183 trait_methods_not_found: Lock::new(Default::default()),
1184 confused_type_with_std_module: Lock::new(Default::default()),
1185 system_library_path: OneThread::new(RefCell::new(Default::default())),
1187 miri_unleashed_features: Lock::new(Default::default()),
1188 real_rust_source_base_dir,
1191 validate_commandline_args_with_session_available(&sess);
1196 // If it is useful to have a Session available already for validating a
1197 // commandline argument, you can do so here.
1198 fn validate_commandline_args_with_session_available(sess: &Session) {
1199 // Since we don't know if code in an rlib will be linked to statically or
1200 // dynamically downstream, rustc generates `__imp_` symbols that help the
1201 // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1202 // these manually generated symbols confuse LLD when it tries to merge
1203 // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1204 // when compiling for LLD ThinLTO. This way we can validly just not generate
1205 // the `dllimport` attributes and `__imp_` symbols in that case.
1206 if sess.opts.cg.linker_plugin_lto.enabled()
1207 && sess.opts.cg.prefer_dynamic
1208 && sess.target.target.options.is_like_msvc
1211 "Linker plugin based LTO is not supported together with \
1212 `-C prefer-dynamic` when targeting MSVC",
1216 // Make sure that any given profiling data actually exists so LLVM can't
1217 // decide to silently skip PGO.
1218 if let Some(ref path) = sess.opts.cg.profile_use {
1221 "File `{}` passed to `-C profile-use` does not exist.",
1227 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1228 // an error to combine the two for now. It always runs into an assertions
1229 // if LLVM is built with assertions, but without assertions it sometimes
1230 // does not crash and will probably generate a corrupted binary.
1231 // We should only display this error if we're actually going to run PGO.
1232 // If we're just supposed to print out some data, don't show the error (#61002).
1233 if sess.opts.cg.profile_generate.enabled()
1234 && sess.target.target.options.is_like_msvc
1235 && sess.panic_strategy() == PanicStrategy::Unwind
1236 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1239 "Profile-guided optimization does not yet work in conjunction \
1240 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1241 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1242 for more information.",
1246 // Sanitizers can only be used on some tested platforms.
1247 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
1248 const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1249 "x86_64-unknown-linux-gnu",
1250 "x86_64-apple-darwin",
1254 const TSAN_SUPPORTED_TARGETS: &[&str] =
1255 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1256 const LSAN_SUPPORTED_TARGETS: &[&str] =
1257 &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1258 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
1260 let supported_targets = match *sanitizer {
1261 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
1262 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
1263 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
1264 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
1267 if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1269 "{:?}Sanitizer only works with the `{}` target",
1271 supported_targets.join("` or `")
1277 /// Holds data on the current incremental compilation session, if there is one.
1279 pub enum IncrCompSession {
1280 /// This is the state the session will be in until the incr. comp. dir is
1283 /// This is the state during which the session directory is private and can
1285 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1286 /// This is the state after the session directory has been finalized. In this
1287 /// state, the contents of the directory must not be modified any more.
1288 Finalized { session_directory: PathBuf },
1289 /// This is an error state that is reached when some compilation error has
1290 /// occurred. It indicates that the contents of the session directory must
1291 /// not be used, since they might be invalid.
1292 InvalidBecauseOfErrors { session_directory: PathBuf },
1295 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1296 let emitter: Box<dyn Emitter + sync::Send> = match output {
1297 config::ErrorOutputType::HumanReadable(kind) => {
1298 let (short, color_config) = kind.unzip();
1299 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1301 config::ErrorOutputType::Json { pretty, json_rendered } => {
1302 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1305 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1306 handler.struct_fatal(msg).emit();
1307 rustc_errors::FatalError.raise();
1310 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1311 let emitter: Box<dyn Emitter + sync::Send> = match output {
1312 config::ErrorOutputType::HumanReadable(kind) => {
1313 let (short, color_config) = kind.unzip();
1314 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1316 config::ErrorOutputType::Json { pretty, json_rendered } => {
1317 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1320 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1321 handler.struct_warn(msg).emit();
1324 pub type CompileResult = Result<(), ErrorReported>;