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, SanitizerSet, SwitchWithOptPath};
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
10 pub use rustc_ast::attr::MarkedAttrs;
11 pub use rustc_ast::crate_disambiguator::CrateDisambiguator;
12 pub use rustc_ast::Attribute;
13 use rustc_data_structures::flock;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_data_structures::jobserver::{self, Client};
16 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
17 use rustc_data_structures::sync::{
18 self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
20 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
21 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
22 use rustc_errors::json::JsonEmitter;
23 use rustc_errors::registry::Registry;
24 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported};
25 use rustc_span::edition::Edition;
26 use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
27 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
28 use rustc_target::asm::InlineAsmArch;
29 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
30 use rustc_target::spec::{Target, TargetTriple, TlsModel};
32 use std::cell::{self, RefCell};
36 use std::num::NonZeroU32;
37 use std::ops::{Div, Mul};
38 use std::path::PathBuf;
39 use std::str::FromStr;
41 use std::time::Duration;
43 pub struct OptimizationFuel {
44 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
46 /// We're rejecting all further optimizations.
50 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
51 #[derive(Clone, Copy)]
52 pub enum CtfeBacktrace {
53 /// Do nothing special, return the error as usual without a backtrace.
55 /// Capture a backtrace at the point the error is created and return it in the error
56 /// (to be printed later if/when the error ever actually gets shown to the user).
58 /// Capture a backtrace at the point the error is created and immediately print it out.
62 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
63 /// limits are consistent throughout the compiler.
64 #[derive(Clone, Copy, Debug)]
65 pub struct Limit(pub usize);
68 /// Create a new limit from a `usize`.
69 pub fn new(value: usize) -> Self {
73 /// Check that `value` is within the limit. Ensures that the same comparisons are used
74 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
75 pub fn value_within_limit(&self, value: usize) -> bool {
80 impl fmt::Display for Limit {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 write!(f, "{}", self.0)
86 impl Div<usize> for Limit {
89 fn div(self, rhs: usize) -> Self::Output {
90 Limit::new(self.0 / rhs)
94 impl Mul<usize> for Limit {
97 fn mul(self, rhs: usize) -> Self::Output {
98 Limit::new(self.0 * rhs)
102 /// Represents the data associated with a compilation
103 /// session for a single crate.
105 pub target: config::Config,
107 pub opts: config::Options,
108 pub host_tlib_path: SearchPath,
109 /// `None` if the host and target are the same.
110 pub target_tlib_path: Option<SearchPath>,
111 pub parse_sess: ParseSess,
112 pub sysroot: PathBuf,
113 /// The name of the root source file of the crate, in the local file system.
114 /// `None` means that there is no source file.
115 pub local_crate_source_file: Option<PathBuf>,
116 /// The directory the compiler has been executed in plus a flag indicating
117 /// if the value stored here has been affected by path remapping.
118 pub working_dir: (PathBuf, bool),
120 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
121 /// (sub)diagnostics that have been set once, but should not be set again,
122 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
123 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
124 crate_types: OnceCell<Vec<CrateType>>,
125 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
126 /// arguments passed to the compiler. Its value together with the crate-name
127 /// forms a unique global identifier for the crate. It is used to allow
128 /// multiple crates with the same name to coexist. See the
129 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
130 pub crate_disambiguator: OnceCell<CrateDisambiguator>,
132 features: OnceCell<rustc_feature::Features>,
134 /// The maximum recursion limit for potentially infinitely recursive
135 /// operations such as auto-dereference and monomorphization.
136 pub recursion_limit: OnceCell<Limit>,
138 /// The maximum length of types during monomorphization.
139 pub type_length_limit: OnceCell<Limit>,
141 /// The maximum blocks a const expression can evaluate.
142 pub const_eval_limit: OnceCell<Limit>,
144 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
145 /// Used for incremental compilation tests. Will only be populated if
146 /// `-Zquery-dep-graph` is specified.
147 pub cgu_reuse_tracker: CguReuseTracker,
149 /// Used by `-Z self-profile`.
150 pub prof: SelfProfilerRef,
152 /// Some measurements that are being gathered during compilation.
153 pub perf_stats: PerfStats,
155 /// Data about code being compiled, gathered during compilation.
156 pub code_stats: CodeStats,
158 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
159 optimization_fuel_crate: Option<String>,
161 /// Tracks fuel info if `-zfuel=crate=n` is specified.
162 optimization_fuel: Lock<OptimizationFuel>,
164 // The next two are public because the driver needs to read them.
165 /// If `-zprint-fuel=crate`, `Some(crate)`.
166 pub print_fuel_crate: Option<String>,
167 /// Always set to zero and incremented so that we can print fuel expended by a crate.
168 pub print_fuel: AtomicU64,
170 /// Loaded up early on in the initialization of this `Session` to avoid
171 /// false positives about a job server in our environment.
172 pub jobserver: Client,
174 /// Cap lint level specified by a driver specifically.
175 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
177 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
178 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
180 /// Mapping from ident span to path span for paths that don't exist as written, but that
181 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
182 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
184 /// Path for libraries that will take preference over libraries shipped by Rust.
185 /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
186 pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
188 /// Tracks the current behavior of the CTFE engine when an error occurs.
189 /// Options range from returning the error without a backtrace to returning an error
190 /// and immediately printing the backtrace to stderr.
191 pub ctfe_backtrace: Lock<CtfeBacktrace>,
193 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
194 /// const check, optionally with the relevant feature gate. We use this to
195 /// warn about unleashing, but with a single diagnostic instead of dozens that
196 /// drown everything else in noise.
197 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
199 /// Base directory containing the `src/` for the Rust standard library, and
200 /// potentially `rustc` as well, if we can can find it. Right now it's always
201 /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
203 /// This directory is what the virtual `/rustc/$hash` is translated back to,
204 /// if Rust was built with path remapping to `/rustc/$hash` enabled
205 /// (the `rust.remap-debuginfo` option in `config.toml`).
206 pub real_rust_source_base_dir: Option<PathBuf>,
208 /// Architecture to use for interpreting asm!.
209 pub asm_arch: Option<InlineAsmArch>,
211 /// Set of enabled features for the current target.
212 pub target_features: FxHashSet<Symbol>,
214 known_attrs: Lock<MarkedAttrs>,
215 used_attrs: Lock<MarkedAttrs>,
217 /// `Span`s for `if` conditions that we have suggested turning into `if let`.
218 pub if_let_suggestions: Lock<FxHashSet<Span>>,
221 pub struct PerfStats {
222 /// The accumulated time spent on computing symbol hashes.
223 pub symbol_hash_time: Lock<Duration>,
224 /// Total number of values canonicalized queries constructed.
225 pub queries_canonicalized: AtomicUsize,
226 /// Number of times this query is invoked.
227 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
228 /// Number of times this query is invoked.
229 pub normalize_projection_ty: AtomicUsize,
232 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
233 enum DiagnosticBuilderMethod {
236 SpanSuggestion(String), // suggestion
237 // Add more variants as needed to support one-time diagnostics.
240 /// Trait implemented by error types. This should not be implemented manually. Instead, use
241 /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic].
242 pub trait SessionDiagnostic<'a> {
243 /// Write out as a diagnostic out of `sess`.
245 fn into_diagnostic(self, sess: &'a Session) -> DiagnosticBuilder<'a>;
248 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
249 /// emitting the same message more than once.
250 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
251 pub enum DiagnosticMessageId {
252 ErrorId(u16), // EXXXX error code as integer
253 LintId(lint::LintId),
254 StabilityId(Option<NonZeroU32>), // issue number
257 impl From<&'static lint::Lint> for DiagnosticMessageId {
258 fn from(lint: &'static lint::Lint) -> Self {
259 DiagnosticMessageId::LintId(lint::LintId::of(lint))
264 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
265 self.miri_unleashed_features.lock().push((span, feature_gate));
268 fn check_miri_unleashed_features(&self) {
269 let unleashed_features = self.miri_unleashed_features.lock();
270 if !unleashed_features.is_empty() {
271 let mut must_err = false;
272 // Create a diagnostic pointing at where things got unleashed.
273 let mut diag = self.struct_warn("skipping const checks");
274 for &(span, feature_gate) in unleashed_features.iter() {
275 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
276 if let Some(feature_gate) = feature_gate {
277 diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate));
278 // The unleash flag must *not* be used to just "hack around" feature gates.
281 diag.span_help(span, "skipping check that does not even have a feature gate");
285 // If we should err, make sure we did.
286 if must_err && !self.has_errors() {
287 // We have skipped a feature gate, and not run into other errors... reject.
289 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
290 gates, except when testing error paths in the CTFE engine",
296 /// Invoked all the way at the end to finish off diagnostics printing.
297 pub fn finish_diagnostics(&self, registry: &Registry) {
298 self.check_miri_unleashed_features();
299 self.diagnostic().print_error_count(registry);
302 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
303 self.crate_disambiguator.get().copied().unwrap()
306 pub fn crate_types(&self) -> &[CrateType] {
307 self.crate_types.get().unwrap().as_slice()
310 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
311 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
314 pub fn recursion_limit(&self) -> Limit {
315 self.recursion_limit.get().copied().unwrap()
318 pub fn type_length_limit(&self) -> Limit {
319 self.type_length_limit.get().copied().unwrap()
322 pub fn const_eval_limit(&self) -> Limit {
323 self.const_eval_limit.get().copied().unwrap()
326 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
327 self.diagnostic().struct_span_warn(sp, msg)
329 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
334 ) -> DiagnosticBuilder<'_> {
335 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
337 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
338 self.diagnostic().struct_warn(msg)
340 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
341 self.diagnostic().struct_span_err(sp, msg)
343 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
348 ) -> DiagnosticBuilder<'_> {
349 self.diagnostic().struct_span_err_with_code(sp, msg, code)
351 // FIXME: This method should be removed (every error should have an associated error code).
352 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
353 self.diagnostic().struct_err(msg)
355 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
356 self.diagnostic().struct_err_with_code(msg, code)
358 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
359 self.diagnostic().struct_span_fatal(sp, msg)
361 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
366 ) -> DiagnosticBuilder<'_> {
367 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
369 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
370 self.diagnostic().struct_fatal(msg)
373 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
374 self.diagnostic().span_fatal(sp, msg).raise()
376 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
382 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
384 pub fn fatal(&self, msg: &str) -> ! {
385 self.diagnostic().fatal(msg).raise()
387 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
389 self.span_warn(sp, msg);
391 self.span_err(sp, msg);
394 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
395 self.diagnostic().span_err(sp, msg)
397 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
398 self.diagnostic().span_err_with_code(sp, &msg, code)
400 pub fn err(&self, msg: &str) {
401 self.diagnostic().err(msg)
403 pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) {
404 err.into_diagnostic(self).emit()
406 pub fn err_count(&self) -> usize {
407 self.diagnostic().err_count()
409 pub fn has_errors(&self) -> bool {
410 self.diagnostic().has_errors()
412 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
413 self.diagnostic().has_errors_or_delayed_span_bugs()
415 pub fn abort_if_errors(&self) {
416 self.diagnostic().abort_if_errors();
418 pub fn compile_status(&self) -> Result<(), ErrorReported> {
419 if self.has_errors() {
420 self.diagnostic().emit_stashed_diagnostics();
426 // FIXME(matthewjasper) Remove this method, it should never be needed.
427 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
431 let old_count = self.err_count();
433 let errors = self.err_count() - old_count;
434 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
436 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
437 self.diagnostic().span_warn(sp, msg)
439 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
440 self.diagnostic().span_warn_with_code(sp, msg, code)
442 pub fn warn(&self, msg: &str) {
443 self.diagnostic().warn(msg)
445 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
447 Some(sp) => self.span_warn(sp, msg),
448 None => self.warn(msg),
451 /// Delay a span_bug() call until abort_if_errors()
453 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
454 self.diagnostic().delay_span_bug(sp, msg)
457 /// Used for code paths of expensive computations that should only take place when
458 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
459 /// it's likely a bug.
460 pub fn delay_good_path_bug(&self, msg: &str) {
461 if self.opts.debugging_opts.print_type_sizes
462 || self.opts.debugging_opts.query_dep_graph
463 || self.opts.debugging_opts.dump_mir.is_some()
464 || self.opts.debugging_opts.unpretty.is_some()
465 || self.opts.output_types.contains_key(&OutputType::Mir)
466 || std::env::var_os("RUSTC_LOG").is_some()
471 self.diagnostic().delay_good_path_bug(msg)
474 pub fn note_without_error(&self, msg: &str) {
475 self.diagnostic().note_without_error(msg)
477 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
478 self.diagnostic().span_note_without_error(sp, msg)
480 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
481 self.diagnostic().struct_note_without_error(msg)
484 pub fn diagnostic(&self) -> &rustc_errors::Handler {
485 &self.parse_sess.span_diagnostic
488 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
489 /// deduplicates on lint ID, span (if any), and message for this `Session`
490 fn diag_once<'a, 'b>(
492 diag_builder: &'b mut DiagnosticBuilder<'a>,
493 method: DiagnosticBuilderMethod,
494 msg_id: DiagnosticMessageId,
496 span_maybe: Option<Span>,
498 let id_span_message = (msg_id, span_maybe, message.to_owned());
499 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
502 DiagnosticBuilderMethod::Note => {
503 diag_builder.note(message);
505 DiagnosticBuilderMethod::SpanNote => {
506 let span = span_maybe.expect("`span_note` needs a span");
507 diag_builder.span_note(span, message);
509 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
510 let span = span_maybe.expect("`span_suggestion_*` needs a span");
511 diag_builder.span_suggestion(
515 Applicability::Unspecified,
522 pub fn diag_span_note_once<'a, 'b>(
524 diag_builder: &'b mut DiagnosticBuilder<'a>,
525 msg_id: DiagnosticMessageId,
531 DiagnosticBuilderMethod::SpanNote,
538 pub fn diag_note_once<'a, 'b>(
540 diag_builder: &'b mut DiagnosticBuilder<'a>,
541 msg_id: DiagnosticMessageId,
544 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
547 pub fn diag_span_suggestion_once<'a, 'b>(
549 diag_builder: &'b mut DiagnosticBuilder<'a>,
550 msg_id: DiagnosticMessageId,
557 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
565 pub fn source_map(&self) -> &SourceMap {
566 self.parse_sess.source_map()
568 pub fn verbose(&self) -> bool {
569 self.opts.debugging_opts.verbose
571 pub fn time_passes(&self) -> bool {
572 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
574 pub fn instrument_mcount(&self) -> bool {
575 self.opts.debugging_opts.instrument_mcount
577 pub fn time_llvm_passes(&self) -> bool {
578 self.opts.debugging_opts.time_llvm_passes
580 pub fn meta_stats(&self) -> bool {
581 self.opts.debugging_opts.meta_stats
583 pub fn asm_comments(&self) -> bool {
584 self.opts.debugging_opts.asm_comments
586 pub fn verify_llvm_ir(&self) -> bool {
587 self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
589 pub fn borrowck_stats(&self) -> bool {
590 self.opts.debugging_opts.borrowck_stats
592 pub fn print_llvm_passes(&self) -> bool {
593 self.opts.debugging_opts.print_llvm_passes
595 pub fn binary_dep_depinfo(&self) -> bool {
596 self.opts.debugging_opts.binary_dep_depinfo
599 /// Gets the features enabled for the current compilation session.
600 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
601 /// dependency tracking. Use tcx.features() instead.
603 pub fn features_untracked(&self) -> &rustc_feature::Features {
604 self.features.get().unwrap()
607 pub fn init_features(&self, features: rustc_feature::Features) {
608 match self.features.set(features) {
610 Err(_) => panic!("`features` was initialized twice"),
614 /// Calculates the flavor of LTO to use for this compilation.
615 pub fn lto(&self) -> config::Lto {
616 // If our target has codegen requirements ignore the command line
617 if self.target.target.options.requires_lto {
618 return config::Lto::Fat;
621 // If the user specified something, return that. If they only said `-C
622 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
623 // then ensure we can't use a ThinLTO.
624 match self.opts.cg.lto {
625 config::LtoCli::Unspecified => {
626 // The compiler was invoked without the `-Clto` flag. Fall
627 // through to the default handling
629 config::LtoCli::No => {
630 // The user explicitly opted out of any kind of LTO
631 return config::Lto::No;
633 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
634 // All of these mean fat LTO
635 return config::Lto::Fat;
637 config::LtoCli::Thin => {
638 return if self.opts.cli_forced_thinlto_off {
646 // Ok at this point the target doesn't require anything and the user
647 // hasn't asked for anything. Our next decision is whether or not
648 // we enable "auto" ThinLTO where we use multiple codegen units and
649 // then do ThinLTO over those codegen units. The logic below will
650 // either return `No` or `ThinLocal`.
652 // If processing command line options determined that we're incompatible
653 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
654 if self.opts.cli_forced_thinlto_off {
655 return config::Lto::No;
658 // If `-Z thinlto` specified process that, but note that this is mostly
659 // a deprecated option now that `-C lto=thin` exists.
660 if let Some(enabled) = self.opts.debugging_opts.thinlto {
662 return config::Lto::ThinLocal;
664 return config::Lto::No;
668 // If there's only one codegen unit and LTO isn't enabled then there's
669 // no need for ThinLTO so just return false.
670 if self.codegen_units() == 1 {
671 return config::Lto::No;
674 // Now we're in "defaults" territory. By default we enable ThinLTO for
675 // optimized compiles (anything greater than O0).
676 match self.opts.optimize {
677 config::OptLevel::No => config::Lto::No,
678 _ => config::Lto::ThinLocal,
682 /// Returns the panic strategy for this compile session. If the user explicitly selected one
683 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
684 pub fn panic_strategy(&self) -> PanicStrategy {
685 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
687 pub fn fewer_names(&self) -> bool {
688 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
689 || self.opts.output_types.contains_key(&OutputType::Bitcode)
690 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
691 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
693 self.opts.debugging_opts.fewer_names || !more_names
696 pub fn unstable_options(&self) -> bool {
697 self.opts.debugging_opts.unstable_options
699 pub fn overflow_checks(&self) -> bool {
703 .or(self.opts.debugging_opts.force_overflow_checks)
704 .unwrap_or(self.opts.debug_assertions)
707 /// Check whether this compile session and crate type use static crt.
708 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
709 if !self.target.target.options.crt_static_respected {
710 // If the target does not opt in to crt-static support, use its default.
711 return self.target.target.options.crt_static_default;
714 let requested_features = self.opts.cg.target_feature.split(',');
715 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
716 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
718 if found_positive || found_negative {
720 } else if crate_type == Some(CrateType::ProcMacro)
721 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
723 // FIXME: When crate_type is not available,
724 // we use compiler options to determine the crate_type.
725 // We can't check `#![crate_type = "proc-macro"]` here.
728 self.target.target.options.crt_static_default
732 pub fn relocation_model(&self) -> RelocModel {
733 self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
736 pub fn code_model(&self) -> Option<CodeModel> {
737 self.opts.cg.code_model.or(self.target.target.options.code_model)
740 pub fn tls_model(&self) -> TlsModel {
741 self.opts.debugging_opts.tls_model.unwrap_or(self.target.target.options.tls_model)
744 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
745 // "mcount" function relies on stack pointer.
746 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
747 if self.instrument_mcount() {
749 } else if let Some(x) = self.opts.cg.force_frame_pointers {
752 !self.target.target.options.eliminate_frame_pointer
756 pub fn must_emit_unwind_tables(&self) -> bool {
757 // This is used to control the emission of the `uwtable` attribute on
760 // At the very least, unwind tables are needed when compiling with
761 // `-C panic=unwind`.
763 // On some targets (including windows), however, exceptions include
764 // other events such as illegal instructions, segfaults, etc. This means
765 // that on Windows we end up still needing unwind tables even if the `-C
766 // panic=abort` flag is passed.
768 // You can also find more info on why Windows needs unwind tables in:
769 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
771 // If a target requires unwind tables, then they must be emitted.
772 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
773 // value, if it is provided, or disable them, if not.
774 if self.panic_strategy() == PanicStrategy::Unwind {
776 } else if self.target.target.options.requires_uwtable {
779 self.opts.cg.force_unwind_tables.unwrap_or(false)
783 /// Returns the symbol name for the registrar function,
784 /// given the crate `Svh` and the function `DefIndex`.
785 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
786 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
789 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
790 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
793 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
794 filesearch::FileSearch::new(
796 self.opts.target_triple.triple(),
797 &self.opts.search_paths,
798 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
799 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
803 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
804 filesearch::FileSearch::new(
806 config::host_triple(),
807 &self.opts.search_paths,
808 &self.host_tlib_path,
813 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
814 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
816 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
817 *load_dep_graph = load;
821 pub fn incr_session_load_dep_graph(&self) -> bool {
822 let incr_comp_session = self.incr_comp_session.borrow();
823 match *incr_comp_session {
824 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
829 pub fn init_incr_comp_session(
831 session_dir: PathBuf,
832 lock_file: flock::Lock,
833 load_dep_graph: bool,
835 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
837 if let IncrCompSession::NotInitialized = *incr_comp_session {
839 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
843 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
846 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
847 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
849 if let IncrCompSession::Active { .. } = *incr_comp_session {
851 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
854 // Note: this will also drop the lock file, thus unlocking the directory.
855 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
858 pub fn mark_incr_comp_session_as_invalid(&self) {
859 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
861 let session_directory = match *incr_comp_session {
862 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
863 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
864 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
867 // Note: this will also drop the lock file, thus unlocking the directory.
868 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
871 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
872 let incr_comp_session = self.incr_comp_session.borrow();
873 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
874 IncrCompSession::NotInitialized => panic!(
875 "trying to get session directory from `IncrCompSession`: {:?}",
878 IncrCompSession::Active { ref session_directory, .. }
879 | IncrCompSession::Finalized { ref session_directory }
880 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
886 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
887 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
890 pub fn print_perf_stats(&self) {
892 "Total time spent computing symbol hashes: {}",
893 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
896 "Total queries canonicalized: {}",
897 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
900 "normalize_generic_arg_after_erasing_regions: {}",
901 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
904 "normalize_projection_ty: {}",
905 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
909 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
910 /// This expends fuel if applicable, and records fuel if applicable.
911 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
913 if let Some(ref c) = self.optimization_fuel_crate {
915 assert_eq!(self.threads(), 1);
916 let mut fuel = self.optimization_fuel.lock();
917 ret = fuel.remaining != 0;
918 if fuel.remaining == 0 && !fuel.out_of_fuel {
919 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
920 fuel.out_of_fuel = true;
921 } else if fuel.remaining > 0 {
926 if let Some(ref c) = self.print_fuel_crate {
928 assert_eq!(self.threads(), 1);
929 self.print_fuel.fetch_add(1, SeqCst);
935 /// Returns the number of query threads that should be used for this
937 pub fn threads(&self) -> usize {
938 self.opts.debugging_opts.threads
941 /// Returns the number of codegen units that should be used for this
943 pub fn codegen_units(&self) -> usize {
944 if let Some(n) = self.opts.cli_forced_codegen_units {
947 if let Some(n) = self.target.target.options.default_codegen_units {
951 // If incremental compilation is turned on, we default to a high number
952 // codegen units in order to reduce the "collateral damage" small
954 if self.opts.incremental.is_some() {
958 // Why is 16 codegen units the default all the time?
960 // The main reason for enabling multiple codegen units by default is to
961 // leverage the ability for the codegen backend to do codegen and
962 // optimization in parallel. This allows us, especially for large crates, to
963 // make good use of all available resources on the machine once we've
964 // hit that stage of compilation. Large crates especially then often
965 // take a long time in codegen/optimization and this helps us amortize that
968 // Note that a high number here doesn't mean that we'll be spawning a
969 // large number of threads in parallel. The backend of rustc contains
970 // global rate limiting through the `jobserver` crate so we'll never
971 // overload the system with too much work, but rather we'll only be
972 // optimizing when we're otherwise cooperating with other instances of
975 // Rather a high number here means that we should be able to keep a lot
976 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
977 // to build we'll be guaranteed that all cpus will finish pretty closely
978 // to one another and we should make relatively optimal use of system
981 // Note that the main cost of codegen units is that it prevents LLVM
982 // from inlining across codegen units. Users in general don't have a lot
983 // of control over how codegen units are split up so it's our job in the
984 // compiler to ensure that undue performance isn't lost when using
985 // codegen units (aka we can't require everyone to slap `#[inline]` on
988 // If we're compiling at `-O0` then the number doesn't really matter too
989 // much because performance doesn't matter and inlining is ok to lose.
990 // In debug mode we just want to try to guarantee that no cpu is stuck
991 // doing work that could otherwise be farmed to others.
993 // In release mode, however (O1 and above) performance does indeed
994 // matter! To recover the loss in performance due to inlining we'll be
995 // enabling ThinLTO by default (the function for which is just below).
996 // This will ensure that we recover any inlining wins we otherwise lost
997 // through codegen unit partitioning.
1001 // Ok that's a lot of words but the basic tl;dr; is that we want a high
1002 // number here -- but not too high. Additionally we're "safe" to have it
1003 // always at the same number at all optimization levels.
1005 // As a result 16 was chosen here! Mostly because it was a power of 2
1006 // and most benchmarks agreed it was roughly a local optimum. Not very
1011 pub fn teach(&self, code: &DiagnosticId) -> bool {
1012 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
1015 pub fn rust_2015(&self) -> bool {
1016 self.opts.edition == Edition::Edition2015
1019 /// Are we allowed to use features from the Rust 2018 edition?
1020 pub fn rust_2018(&self) -> bool {
1021 self.opts.edition >= Edition::Edition2018
1024 pub fn edition(&self) -> Edition {
1028 /// Returns `true` if we cannot skip the PLT for shared library calls.
1029 pub fn needs_plt(&self) -> bool {
1030 // Check if the current target usually needs PLT to be enabled.
1031 // The user can use the command line flag to override it.
1032 let needs_plt = self.target.target.options.needs_plt;
1034 let dbg_opts = &self.opts.debugging_opts;
1036 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
1038 // Only enable this optimization by default if full relro is also enabled.
1039 // In this case, lazy binding was already unavailable, so nothing is lost.
1040 // This also ensures `-Wl,-z,now` is supported by the linker.
1041 let full_relro = RelroLevel::Full == relro_level;
1043 // If user didn't explicitly forced us to use / skip the PLT,
1044 // then try to skip it where possible.
1045 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1048 /// Checks if LLVM lifetime markers should be emitted.
1049 pub fn emit_lifetime_markers(&self) -> bool {
1050 self.opts.optimize != config::OptLevel::No
1051 // AddressSanitizer uses lifetimes to detect use after scope bugs.
1052 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1053 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY)
1056 pub fn link_dead_code(&self) -> bool {
1057 match self.opts.cg.link_dead_code {
1058 Some(explicitly_set) => explicitly_set,
1060 self.opts.debugging_opts.instrument_coverage
1061 && !self.target.target.options.is_like_msvc
1062 // Issue #76038: (rustc `-Clink-dead-code` causes MSVC linker to produce invalid
1063 // binaries when LLVM InstrProf counters are enabled). As described by this issue,
1064 // the "link dead code" option produces incorrect binaries when compiled and linked
1065 // under MSVC. The resulting Rust programs typically crash with a segmentation
1066 // fault, or produce an empty "*.profraw" file (profiling counter results normally
1067 // generated during program exit).
1069 // If not targeting MSVC, `-Z instrument-coverage` implies `-C link-dead-code`, so
1070 // unexecuted code is still counted as zero, rather than be optimized out. Note that
1071 // instrumenting dead code can be explicitly disabled with:
1073 // `-Z instrument-coverage -C link-dead-code=no`.
1075 // FIXME(richkadel): Investigate if `instrument-coverage` implementation can inject
1076 // [zero counters](https://llvm.org/docs/CoverageMappingFormat.html#counter) in the
1077 // coverage map when "dead code" is removed, rather than forcing `link-dead-code`.
1078 // This may not be possible, however, if (as it seems to appear) the "dead code"
1079 // that would otherwise not be linked is only identified as "dead" by the native
1080 // linker. If that's the case, I believe it is too late for the Rust compiler to
1081 // leverage any information it might be able to get from the linker regarding what
1082 // code is dead, to be able to add those counters.
1084 // On the other hand, if any Rust compiler passes are optimizing out dead code blocks
1085 // we should inject "zero" counters for those code regions.
1090 pub fn mark_attr_known(&self, attr: &Attribute) {
1091 self.known_attrs.lock().mark(attr)
1094 pub fn is_attr_known(&self, attr: &Attribute) -> bool {
1095 self.known_attrs.lock().is_marked(attr)
1098 pub fn mark_attr_used(&self, attr: &Attribute) {
1099 self.used_attrs.lock().mark(attr)
1102 pub fn is_attr_used(&self, attr: &Attribute) -> bool {
1103 self.used_attrs.lock().is_marked(attr)
1106 /// Returns `true` if the attribute's path matches the argument. If it
1107 /// matches, then the attribute is marked as used.
1109 /// This method should only be used by rustc, other tools can use
1110 /// `Attribute::has_name` instead, because only rustc is supposed to report
1111 /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1112 /// produced by lowering an `Attribute` and don't have identity, so they
1113 /// only have the `has_name` method, and you need to mark the original
1114 /// `Attribute` as used when necessary.)
1115 pub fn check_name(&self, attr: &Attribute, name: Symbol) -> bool {
1116 let matches = attr.has_name(name);
1118 self.mark_attr_used(attr);
1123 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1124 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1126 .any(|kind| self.check_name(attr, *kind))
1129 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1130 attrs.iter().any(|item| self.check_name(item, name))
1133 pub fn find_by_name<'a>(
1135 attrs: &'a [Attribute],
1137 ) -> Option<&'a Attribute> {
1138 attrs.iter().find(|attr| self.check_name(attr, name))
1141 pub fn filter_by_name<'a>(
1143 attrs: &'a [Attribute],
1145 ) -> impl Iterator<Item = &'a Attribute> {
1146 attrs.iter().filter(move |attr| self.check_name(attr, name))
1149 pub fn first_attr_value_str_by_name(
1151 attrs: &[Attribute],
1153 ) -> Option<Symbol> {
1154 attrs.iter().find(|at| self.check_name(at, name)).and_then(|at| at.value_str())
1159 sopts: &config::Options,
1160 registry: rustc_errors::registry::Registry,
1161 source_map: Lrc<SourceMap>,
1162 emitter_dest: Option<Box<dyn Write + Send>>,
1163 ) -> Box<dyn Emitter + sync::Send> {
1164 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1165 match (sopts.error_format, emitter_dest) {
1166 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1167 let (short, color_config) = kind.unzip();
1169 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1171 AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1172 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1174 let emitter = match dst {
1175 None => EmitterWriter::stderr(
1179 sopts.debugging_opts.teach,
1180 sopts.debugging_opts.terminal_width,
1183 Some(dst) => EmitterWriter::new(
1187 false, // no teach messages when writing to a buffer
1188 false, // no colors when writing to a buffer
1189 None, // no terminal width
1193 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1196 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1197 JsonEmitter::stderr(
1202 sopts.debugging_opts.terminal_width,
1205 .ui_testing(sopts.debugging_opts.ui_testing),
1207 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1214 sopts.debugging_opts.terminal_width,
1217 .ui_testing(sopts.debugging_opts.ui_testing),
1222 pub enum DiagnosticOutput {
1224 Raw(Box<dyn Write + Send>),
1227 pub fn build_session(
1228 sopts: config::Options,
1229 local_crate_source_file: Option<PathBuf>,
1230 registry: rustc_errors::registry::Registry,
1231 diagnostics_output: DiagnosticOutput,
1232 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1233 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1234 target_override: Option<Target>,
1236 // FIXME: This is not general enough to make the warning lint completely override
1237 // normal diagnostic warnings, since the warning lint can also be denied and changed
1238 // later via the source code.
1239 let warnings_allow = sopts
1242 .filter(|&&(ref key, _)| *key == "warnings")
1243 .map(|&(_, ref level)| *level == lint::Allow)
1246 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1247 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1249 let write_dest = match diagnostics_output {
1250 DiagnosticOutput::Default => None,
1251 DiagnosticOutput::Raw(write) => Some(write),
1254 let target_cfg = config::build_target_config(&sopts, target_override);
1255 let host_triple = TargetTriple::from_triple(config::host_triple());
1256 let host = Target::search(&host_triple).unwrap_or_else(|e| {
1257 early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1260 let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
1261 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1262 if target_cfg.target.options.is_like_msvc {
1263 SourceFileHashAlgorithm::Sha1
1265 SourceFileHashAlgorithm::Md5
1268 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1270 sopts.file_path_mapping(),
1273 let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1275 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1277 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1280 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1283 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1285 let profiler = SelfProfiler::new(
1287 sopts.crate_name.as_ref().map(|s| &s[..]),
1288 &sopts.debugging_opts.self_profile_events,
1291 Ok(profiler) => Some(Arc::new(profiler)),
1293 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1301 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1302 let sysroot = match &sopts.maybe_sysroot {
1303 Some(sysroot) => sysroot.clone(),
1304 None => filesearch::get_or_default_sysroot(),
1307 let host_triple = config::host_triple();
1308 let target_triple = sopts.target_triple.triple();
1309 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1310 let target_tlib_path = if host_triple == target_triple {
1313 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1316 let file_path_mapping = sopts.file_path_mapping();
1318 let local_crate_source_file =
1319 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1321 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1322 let optimization_fuel = Lock::new(OptimizationFuel {
1323 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1326 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1327 let print_fuel = AtomicU64::new(0);
1329 let working_dir = env::current_dir().unwrap_or_else(|e| {
1330 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1332 let working_dir = file_path_mapping.map_prefix(working_dir);
1334 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1335 CguReuseTracker::new()
1337 CguReuseTracker::new_disabled()
1340 let prof = SelfProfilerRef::new(
1342 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1343 sopts.debugging_opts.time_passes,
1346 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1347 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1348 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1349 _ => CtfeBacktrace::Disabled,
1352 // Try to find a directory containing the Rust `src`, for more details see
1353 // the doc comment on the `real_rust_source_base_dir` field.
1354 let real_rust_source_base_dir = {
1355 // This is the location used by the `rust-src` `rustup` component.
1356 let mut candidate = sysroot.join("lib/rustlib/src/rust");
1357 if let Ok(metadata) = candidate.symlink_metadata() {
1358 // Replace the symlink rustbuild creates, with its destination.
1359 // We could try to use `fs::canonicalize` instead, but that might
1360 // produce unnecessarily verbose path.
1361 if metadata.file_type().is_symlink() {
1362 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1363 candidate = symlink_dest;
1368 // Only use this directory if it has a file we can expect to always find.
1369 if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None }
1372 let asm_arch = if target_cfg.target.options.allow_asm {
1373 InlineAsmArch::from_str(&target_cfg.target.arch).ok()
1378 let sess = Session {
1386 local_crate_source_file,
1388 one_time_diagnostics: Default::default(),
1389 crate_types: OnceCell::new(),
1390 crate_disambiguator: OnceCell::new(),
1391 features: OnceCell::new(),
1392 recursion_limit: OnceCell::new(),
1393 type_length_limit: OnceCell::new(),
1394 const_eval_limit: OnceCell::new(),
1395 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1398 perf_stats: PerfStats {
1399 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1400 queries_canonicalized: AtomicUsize::new(0),
1401 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1402 normalize_projection_ty: AtomicUsize::new(0),
1404 code_stats: Default::default(),
1405 optimization_fuel_crate,
1409 jobserver: jobserver::client(),
1411 trait_methods_not_found: Lock::new(Default::default()),
1412 confused_type_with_std_module: Lock::new(Default::default()),
1413 system_library_path: OneThread::new(RefCell::new(Default::default())),
1415 miri_unleashed_features: Lock::new(Default::default()),
1416 real_rust_source_base_dir,
1418 target_features: FxHashSet::default(),
1419 known_attrs: Lock::new(MarkedAttrs::new()),
1420 used_attrs: Lock::new(MarkedAttrs::new()),
1421 if_let_suggestions: Default::default(),
1424 validate_commandline_args_with_session_available(&sess);
1429 // If it is useful to have a Session available already for validating a
1430 // commandline argument, you can do so here.
1431 fn validate_commandline_args_with_session_available(sess: &Session) {
1432 // Since we don't know if code in an rlib will be linked to statically or
1433 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1434 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1435 // these manually generated symbols confuse LLD when it tries to merge
1436 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1437 // when compiling for LLD ThinLTO. This way we can validly just not generate
1438 // the `dllimport` attributes and `__imp_` symbols in that case.
1439 if sess.opts.cg.linker_plugin_lto.enabled()
1440 && sess.opts.cg.prefer_dynamic
1441 && sess.target.target.options.is_like_windows
1444 "Linker plugin based LTO is not supported together with \
1445 `-C prefer-dynamic` when targeting Windows-like targets",
1449 // Make sure that any given profiling data actually exists so LLVM can't
1450 // decide to silently skip PGO.
1451 if let Some(ref path) = sess.opts.cg.profile_use {
1454 "File `{}` passed to `-C profile-use` does not exist.",
1460 // Unwind tables cannot be disabled if the target requires them.
1461 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1462 if sess.panic_strategy() == PanicStrategy::Unwind && !include_uwtables {
1464 "panic=unwind requires unwind tables, they cannot be disabled \
1465 with `-C force-unwind-tables=no`.",
1469 if sess.target.target.options.requires_uwtable && !include_uwtables {
1471 "target requires unwind tables, they cannot be disabled with \
1472 `-C force-unwind-tables=no`.",
1477 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1478 // an error to combine the two for now. It always runs into an assertions
1479 // if LLVM is built with assertions, but without assertions it sometimes
1480 // does not crash and will probably generate a corrupted binary.
1481 // We should only display this error if we're actually going to run PGO.
1482 // If we're just supposed to print out some data, don't show the error (#61002).
1483 if sess.opts.cg.profile_generate.enabled()
1484 && sess.target.target.options.is_like_msvc
1485 && sess.panic_strategy() == PanicStrategy::Unwind
1486 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1489 "Profile-guided optimization does not yet work in conjunction \
1490 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1491 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1492 for more information.",
1496 const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1498 "aarch64-unknown-linux-gnu",
1499 "x86_64-apple-darwin",
1501 "x86_64-unknown-freebsd",
1502 "x86_64-unknown-linux-gnu",
1504 const LSAN_SUPPORTED_TARGETS: &[&str] =
1505 &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1506 const MSAN_SUPPORTED_TARGETS: &[&str] =
1507 &["aarch64-unknown-linux-gnu", "x86_64-unknown-freebsd", "x86_64-unknown-linux-gnu"];
1508 const TSAN_SUPPORTED_TARGETS: &[&str] = &[
1509 "aarch64-unknown-linux-gnu",
1510 "x86_64-apple-darwin",
1511 "x86_64-unknown-freebsd",
1512 "x86_64-unknown-linux-gnu",
1515 // Sanitizers can only be used on some tested platforms.
1516 for s in sess.opts.debugging_opts.sanitizer {
1517 let supported_targets = match s {
1518 SanitizerSet::ADDRESS => ASAN_SUPPORTED_TARGETS,
1519 SanitizerSet::LEAK => LSAN_SUPPORTED_TARGETS,
1520 SanitizerSet::MEMORY => MSAN_SUPPORTED_TARGETS,
1521 SanitizerSet::THREAD => TSAN_SUPPORTED_TARGETS,
1522 _ => panic!("unrecognized sanitizer {}", s),
1524 if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1526 "`-Zsanitizer={}` only works with targets: {}",
1528 supported_targets.join(", ")
1531 let conflicting = sess.opts.debugging_opts.sanitizer - s;
1532 if !conflicting.is_empty() {
1534 "`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`",
1537 // Don't report additional errors.
1543 /// Holds data on the current incremental compilation session, if there is one.
1545 pub enum IncrCompSession {
1546 /// This is the state the session will be in until the incr. comp. dir is
1549 /// This is the state during which the session directory is private and can
1551 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1552 /// This is the state after the session directory has been finalized. In this
1553 /// state, the contents of the directory must not be modified any more.
1554 Finalized { session_directory: PathBuf },
1555 /// This is an error state that is reached when some compilation error has
1556 /// occurred. It indicates that the contents of the session directory must
1557 /// not be used, since they might be invalid.
1558 InvalidBecauseOfErrors { session_directory: PathBuf },
1561 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1562 let emitter: Box<dyn Emitter + sync::Send> = match output {
1563 config::ErrorOutputType::HumanReadable(kind) => {
1564 let (short, color_config) = kind.unzip();
1565 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1567 config::ErrorOutputType::Json { pretty, json_rendered } => {
1568 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1571 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1572 handler.struct_fatal(msg).emit();
1573 rustc_errors::FatalError.raise();
1576 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1577 let emitter: Box<dyn Emitter + sync::Send> = match output {
1578 config::ErrorOutputType::HumanReadable(kind) => {
1579 let (short, color_config) = kind.unzip();
1580 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1582 config::ErrorOutputType::Json { pretty, json_rendered } => {
1583 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1586 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1587 handler.struct_warn(msg).emit();
1590 pub type CompileResult = Result<(), ErrorReported>;