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::ast::Attribute;
11 pub use rustc_ast::attr::MarkedAttrs;
12 pub use rustc_ast::crate_disambiguator::CrateDisambiguator;
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>,
218 pub struct PerfStats {
219 /// The accumulated time spent on computing symbol hashes.
220 pub symbol_hash_time: Lock<Duration>,
221 /// The accumulated time spent decoding def path tables from metadata.
222 pub decode_def_path_tables_time: Lock<Duration>,
223 /// Total number of values canonicalized queries constructed.
224 pub queries_canonicalized: AtomicUsize,
225 /// Number of times this query is invoked.
226 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
227 /// Number of times this query is invoked.
228 pub normalize_projection_ty: AtomicUsize,
231 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
232 enum DiagnosticBuilderMethod {
235 SpanSuggestion(String), // suggestion
236 // Add more variants as needed to support one-time diagnostics.
239 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
240 /// emitting the same message more than once.
241 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
242 pub enum DiagnosticMessageId {
243 ErrorId(u16), // EXXXX error code as integer
244 LintId(lint::LintId),
245 StabilityId(Option<NonZeroU32>), // issue number
248 impl From<&'static lint::Lint> for DiagnosticMessageId {
249 fn from(lint: &'static lint::Lint) -> Self {
250 DiagnosticMessageId::LintId(lint::LintId::of(lint))
255 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
256 self.miri_unleashed_features.lock().push((span, feature_gate));
259 fn check_miri_unleashed_features(&self) {
260 let unleashed_features = self.miri_unleashed_features.lock();
261 if !unleashed_features.is_empty() {
262 let mut must_err = false;
263 // Create a diagnostic pointing at where things got unleashed.
264 let mut diag = self.struct_warn("skipping const checks");
265 for &(span, feature_gate) in unleashed_features.iter() {
266 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
267 if let Some(feature_gate) = feature_gate {
268 diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate));
269 // The unleash flag must *not* be used to just "hack around" feature gates.
272 diag.span_help(span, "skipping check that does not even have a feature gate");
276 // If we should err, make sure we did.
277 if must_err && !self.has_errors() {
278 // We have skipped a feature gate, and not run into other errors... reject.
280 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
281 gates, except when testing error paths in the CTFE engine",
287 /// Invoked all the way at the end to finish off diagnostics printing.
288 pub fn finish_diagnostics(&self, registry: &Registry) {
289 self.check_miri_unleashed_features();
290 self.diagnostic().print_error_count(registry);
293 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
294 self.crate_disambiguator.get().copied().unwrap()
297 pub fn crate_types(&self) -> &[CrateType] {
298 self.crate_types.get().unwrap().as_slice()
301 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
302 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
305 pub fn recursion_limit(&self) -> Limit {
306 self.recursion_limit.get().copied().unwrap()
309 pub fn type_length_limit(&self) -> Limit {
310 self.type_length_limit.get().copied().unwrap()
313 pub fn const_eval_limit(&self) -> Limit {
314 self.const_eval_limit.get().copied().unwrap()
317 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
318 self.diagnostic().struct_span_warn(sp, msg)
320 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
325 ) -> DiagnosticBuilder<'_> {
326 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
328 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
329 self.diagnostic().struct_warn(msg)
331 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
332 self.diagnostic().struct_span_err(sp, msg)
334 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
339 ) -> DiagnosticBuilder<'_> {
340 self.diagnostic().struct_span_err_with_code(sp, msg, code)
342 // FIXME: This method should be removed (every error should have an associated error code).
343 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
344 self.diagnostic().struct_err(msg)
346 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
347 self.diagnostic().struct_err_with_code(msg, code)
349 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
350 self.diagnostic().struct_span_fatal(sp, msg)
352 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
357 ) -> DiagnosticBuilder<'_> {
358 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
360 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
361 self.diagnostic().struct_fatal(msg)
364 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
365 self.diagnostic().span_fatal(sp, msg).raise()
367 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
373 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
375 pub fn fatal(&self, msg: &str) -> ! {
376 self.diagnostic().fatal(msg).raise()
378 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
380 self.span_warn(sp, msg);
382 self.span_err(sp, msg);
385 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
386 self.diagnostic().span_err(sp, msg)
388 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
389 self.diagnostic().span_err_with_code(sp, &msg, code)
391 pub fn err(&self, msg: &str) {
392 self.diagnostic().err(msg)
394 pub fn err_count(&self) -> usize {
395 self.diagnostic().err_count()
397 pub fn has_errors(&self) -> bool {
398 self.diagnostic().has_errors()
400 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
401 self.diagnostic().has_errors_or_delayed_span_bugs()
403 pub fn abort_if_errors(&self) {
404 self.diagnostic().abort_if_errors();
406 pub fn compile_status(&self) -> Result<(), ErrorReported> {
407 if self.has_errors() {
408 self.diagnostic().emit_stashed_diagnostics();
414 // FIXME(matthewjasper) Remove this method, it should never be needed.
415 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
419 let old_count = self.err_count();
421 let errors = self.err_count() - old_count;
422 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
424 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
425 self.diagnostic().span_warn(sp, msg)
427 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
428 self.diagnostic().span_warn_with_code(sp, msg, code)
430 pub fn warn(&self, msg: &str) {
431 self.diagnostic().warn(msg)
433 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
435 Some(sp) => self.span_warn(sp, msg),
436 None => self.warn(msg),
439 /// Delay a span_bug() call until abort_if_errors()
440 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
441 self.diagnostic().delay_span_bug(sp, msg)
443 pub fn note_without_error(&self, msg: &str) {
444 self.diagnostic().note_without_error(msg)
446 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
447 self.diagnostic().span_note_without_error(sp, msg)
449 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
450 self.diagnostic().struct_note_without_error(msg)
453 pub fn diagnostic(&self) -> &rustc_errors::Handler {
454 &self.parse_sess.span_diagnostic
457 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
458 /// deduplicates on lint ID, span (if any), and message for this `Session`
459 fn diag_once<'a, 'b>(
461 diag_builder: &'b mut DiagnosticBuilder<'a>,
462 method: DiagnosticBuilderMethod,
463 msg_id: DiagnosticMessageId,
465 span_maybe: Option<Span>,
467 let id_span_message = (msg_id, span_maybe, message.to_owned());
468 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
471 DiagnosticBuilderMethod::Note => {
472 diag_builder.note(message);
474 DiagnosticBuilderMethod::SpanNote => {
475 let span = span_maybe.expect("`span_note` needs a span");
476 diag_builder.span_note(span, message);
478 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
479 let span = span_maybe.expect("`span_suggestion_*` needs a span");
480 diag_builder.span_suggestion(
484 Applicability::Unspecified,
491 pub fn diag_span_note_once<'a, 'b>(
493 diag_builder: &'b mut DiagnosticBuilder<'a>,
494 msg_id: DiagnosticMessageId,
500 DiagnosticBuilderMethod::SpanNote,
507 pub fn diag_note_once<'a, 'b>(
509 diag_builder: &'b mut DiagnosticBuilder<'a>,
510 msg_id: DiagnosticMessageId,
513 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
516 pub fn diag_span_suggestion_once<'a, 'b>(
518 diag_builder: &'b mut DiagnosticBuilder<'a>,
519 msg_id: DiagnosticMessageId,
526 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
534 pub fn source_map(&self) -> &SourceMap {
535 self.parse_sess.source_map()
537 pub fn verbose(&self) -> bool {
538 self.opts.debugging_opts.verbose
540 pub fn time_passes(&self) -> bool {
541 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
543 pub fn instrument_mcount(&self) -> bool {
544 self.opts.debugging_opts.instrument_mcount
546 pub fn time_llvm_passes(&self) -> bool {
547 self.opts.debugging_opts.time_llvm_passes
549 pub fn meta_stats(&self) -> bool {
550 self.opts.debugging_opts.meta_stats
552 pub fn asm_comments(&self) -> bool {
553 self.opts.debugging_opts.asm_comments
555 pub fn verify_llvm_ir(&self) -> bool {
556 self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
558 pub fn borrowck_stats(&self) -> bool {
559 self.opts.debugging_opts.borrowck_stats
561 pub fn print_llvm_passes(&self) -> bool {
562 self.opts.debugging_opts.print_llvm_passes
564 pub fn binary_dep_depinfo(&self) -> bool {
565 self.opts.debugging_opts.binary_dep_depinfo
568 /// Gets the features enabled for the current compilation session.
569 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
570 /// dependency tracking. Use tcx.features() instead.
572 pub fn features_untracked(&self) -> &rustc_feature::Features {
573 self.features.get().unwrap()
576 pub fn init_features(&self, features: rustc_feature::Features) {
577 match self.features.set(features) {
579 Err(_) => panic!("`features` was initialized twice"),
583 /// Calculates the flavor of LTO to use for this compilation.
584 pub fn lto(&self) -> config::Lto {
585 // If our target has codegen requirements ignore the command line
586 if self.target.target.options.requires_lto {
587 return config::Lto::Fat;
590 // If the user specified something, return that. If they only said `-C
591 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
592 // then ensure we can't use a ThinLTO.
593 match self.opts.cg.lto {
594 config::LtoCli::Unspecified => {
595 // The compiler was invoked without the `-Clto` flag. Fall
596 // through to the default handling
598 config::LtoCli::No => {
599 // The user explicitly opted out of any kind of LTO
600 return config::Lto::No;
602 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
603 // All of these mean fat LTO
604 return config::Lto::Fat;
606 config::LtoCli::Thin => {
607 return if self.opts.cli_forced_thinlto_off {
615 // Ok at this point the target doesn't require anything and the user
616 // hasn't asked for anything. Our next decision is whether or not
617 // we enable "auto" ThinLTO where we use multiple codegen units and
618 // then do ThinLTO over those codegen units. The logic below will
619 // either return `No` or `ThinLocal`.
621 // If processing command line options determined that we're incompatible
622 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
623 if self.opts.cli_forced_thinlto_off {
624 return config::Lto::No;
627 // If `-Z thinlto` specified process that, but note that this is mostly
628 // a deprecated option now that `-C lto=thin` exists.
629 if let Some(enabled) = self.opts.debugging_opts.thinlto {
631 return config::Lto::ThinLocal;
633 return config::Lto::No;
637 // If there's only one codegen unit and LTO isn't enabled then there's
638 // no need for ThinLTO so just return false.
639 if self.codegen_units() == 1 {
640 return config::Lto::No;
643 // Now we're in "defaults" territory. By default we enable ThinLTO for
644 // optimized compiles (anything greater than O0).
645 match self.opts.optimize {
646 config::OptLevel::No => config::Lto::No,
647 _ => config::Lto::ThinLocal,
651 /// Returns the panic strategy for this compile session. If the user explicitly selected one
652 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
653 pub fn panic_strategy(&self) -> PanicStrategy {
654 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
656 pub fn fewer_names(&self) -> bool {
657 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
658 || self.opts.output_types.contains_key(&OutputType::Bitcode)
659 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
660 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
662 self.opts.debugging_opts.fewer_names || !more_names
665 pub fn unstable_options(&self) -> bool {
666 self.opts.debugging_opts.unstable_options
668 pub fn overflow_checks(&self) -> bool {
672 .or(self.opts.debugging_opts.force_overflow_checks)
673 .unwrap_or(self.opts.debug_assertions)
676 /// Check whether this compile session and crate type use static crt.
677 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
678 if !self.target.target.options.crt_static_respected {
679 // If the target does not opt in to crt-static support, use its default.
680 return self.target.target.options.crt_static_default;
683 let requested_features = self.opts.cg.target_feature.split(',');
684 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
685 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
687 if found_positive || found_negative {
689 } else if crate_type == Some(CrateType::ProcMacro)
690 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
692 // FIXME: When crate_type is not available,
693 // we use compiler options to determine the crate_type.
694 // We can't check `#![crate_type = "proc-macro"]` here.
697 self.target.target.options.crt_static_default
701 pub fn relocation_model(&self) -> RelocModel {
702 self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
705 pub fn code_model(&self) -> Option<CodeModel> {
706 self.opts.cg.code_model.or(self.target.target.options.code_model)
709 pub fn tls_model(&self) -> TlsModel {
710 self.opts.debugging_opts.tls_model.unwrap_or(self.target.target.options.tls_model)
713 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
714 // "mcount" function relies on stack pointer.
715 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
716 if self.instrument_mcount() {
718 } else if let Some(x) = self.opts.cg.force_frame_pointers {
721 !self.target.target.options.eliminate_frame_pointer
725 pub fn must_emit_unwind_tables(&self) -> bool {
726 // This is used to control the emission of the `uwtable` attribute on
729 // At the very least, unwind tables are needed when compiling with
730 // `-C panic=unwind`.
732 // On some targets (including windows), however, exceptions include
733 // other events such as illegal instructions, segfaults, etc. This means
734 // that on Windows we end up still needing unwind tables even if the `-C
735 // panic=abort` flag is passed.
737 // You can also find more info on why Windows needs unwind tables in:
738 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
740 // If a target requires unwind tables, then they must be emitted.
741 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
742 // value, if it is provided, or disable them, if not.
743 if self.panic_strategy() == PanicStrategy::Unwind {
745 } else if self.target.target.options.requires_uwtable {
748 self.opts.cg.force_unwind_tables.unwrap_or(false)
752 /// Returns the symbol name for the registrar function,
753 /// given the crate `Svh` and the function `DefIndex`.
754 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
755 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
758 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
759 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
762 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
763 filesearch::FileSearch::new(
765 self.opts.target_triple.triple(),
766 &self.opts.search_paths,
767 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
768 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
772 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
773 filesearch::FileSearch::new(
775 config::host_triple(),
776 &self.opts.search_paths,
777 &self.host_tlib_path,
782 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
783 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
785 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
786 *load_dep_graph = load;
790 pub fn incr_session_load_dep_graph(&self) -> bool {
791 let incr_comp_session = self.incr_comp_session.borrow();
792 match *incr_comp_session {
793 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
798 pub fn init_incr_comp_session(
800 session_dir: PathBuf,
801 lock_file: flock::Lock,
802 load_dep_graph: bool,
804 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
806 if let IncrCompSession::NotInitialized = *incr_comp_session {
808 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
812 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
815 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
816 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
818 if let IncrCompSession::Active { .. } = *incr_comp_session {
820 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
823 // Note: this will also drop the lock file, thus unlocking the directory.
824 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
827 pub fn mark_incr_comp_session_as_invalid(&self) {
828 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
830 let session_directory = match *incr_comp_session {
831 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
832 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
833 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
836 // Note: this will also drop the lock file, thus unlocking the directory.
837 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
840 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
841 let incr_comp_session = self.incr_comp_session.borrow();
842 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
843 IncrCompSession::NotInitialized => panic!(
844 "trying to get session directory from `IncrCompSession`: {:?}",
847 IncrCompSession::Active { ref session_directory, .. }
848 | IncrCompSession::Finalized { ref session_directory }
849 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
855 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
856 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
859 pub fn print_perf_stats(&self) {
861 "Total time spent computing symbol hashes: {}",
862 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
865 "Total time spent decoding DefPath tables: {}",
866 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
869 "Total queries canonicalized: {}",
870 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
873 "normalize_generic_arg_after_erasing_regions: {}",
874 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
877 "normalize_projection_ty: {}",
878 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
882 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
883 /// This expends fuel if applicable, and records fuel if applicable.
884 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
886 if let Some(ref c) = self.optimization_fuel_crate {
888 assert_eq!(self.threads(), 1);
889 let mut fuel = self.optimization_fuel.lock();
890 ret = fuel.remaining != 0;
891 if fuel.remaining == 0 && !fuel.out_of_fuel {
892 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
893 fuel.out_of_fuel = true;
894 } else if fuel.remaining > 0 {
899 if let Some(ref c) = self.print_fuel_crate {
901 assert_eq!(self.threads(), 1);
902 self.print_fuel.fetch_add(1, SeqCst);
908 /// Returns the number of query threads that should be used for this
910 pub fn threads(&self) -> usize {
911 self.opts.debugging_opts.threads
914 /// Returns the number of codegen units that should be used for this
916 pub fn codegen_units(&self) -> usize {
917 if let Some(n) = self.opts.cli_forced_codegen_units {
920 if let Some(n) = self.target.target.options.default_codegen_units {
924 // If incremental compilation is turned on, we default to a high number
925 // codegen units in order to reduce the "collateral damage" small
927 if self.opts.incremental.is_some() {
931 // Why is 16 codegen units the default all the time?
933 // The main reason for enabling multiple codegen units by default is to
934 // leverage the ability for the codegen backend to do codegen and
935 // optimization in parallel. This allows us, especially for large crates, to
936 // make good use of all available resources on the machine once we've
937 // hit that stage of compilation. Large crates especially then often
938 // take a long time in codegen/optimization and this helps us amortize that
941 // Note that a high number here doesn't mean that we'll be spawning a
942 // large number of threads in parallel. The backend of rustc contains
943 // global rate limiting through the `jobserver` crate so we'll never
944 // overload the system with too much work, but rather we'll only be
945 // optimizing when we're otherwise cooperating with other instances of
948 // Rather a high number here means that we should be able to keep a lot
949 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
950 // to build we'll be guaranteed that all cpus will finish pretty closely
951 // to one another and we should make relatively optimal use of system
954 // Note that the main cost of codegen units is that it prevents LLVM
955 // from inlining across codegen units. Users in general don't have a lot
956 // of control over how codegen units are split up so it's our job in the
957 // compiler to ensure that undue performance isn't lost when using
958 // codegen units (aka we can't require everyone to slap `#[inline]` on
961 // If we're compiling at `-O0` then the number doesn't really matter too
962 // much because performance doesn't matter and inlining is ok to lose.
963 // In debug mode we just want to try to guarantee that no cpu is stuck
964 // doing work that could otherwise be farmed to others.
966 // In release mode, however (O1 and above) performance does indeed
967 // matter! To recover the loss in performance due to inlining we'll be
968 // enabling ThinLTO by default (the function for which is just below).
969 // This will ensure that we recover any inlining wins we otherwise lost
970 // through codegen unit partitioning.
974 // Ok that's a lot of words but the basic tl;dr; is that we want a high
975 // number here -- but not too high. Additionally we're "safe" to have it
976 // always at the same number at all optimization levels.
978 // As a result 16 was chosen here! Mostly because it was a power of 2
979 // and most benchmarks agreed it was roughly a local optimum. Not very
984 pub fn teach(&self, code: &DiagnosticId) -> bool {
985 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
988 pub fn rust_2015(&self) -> bool {
989 self.opts.edition == Edition::Edition2015
992 /// Are we allowed to use features from the Rust 2018 edition?
993 pub fn rust_2018(&self) -> bool {
994 self.opts.edition >= Edition::Edition2018
997 pub fn edition(&self) -> Edition {
1001 /// Returns `true` if we cannot skip the PLT for shared library calls.
1002 pub fn needs_plt(&self) -> bool {
1003 // Check if the current target usually needs PLT to be enabled.
1004 // The user can use the command line flag to override it.
1005 let needs_plt = self.target.target.options.needs_plt;
1007 let dbg_opts = &self.opts.debugging_opts;
1009 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
1011 // Only enable this optimization by default if full relro is also enabled.
1012 // In this case, lazy binding was already unavailable, so nothing is lost.
1013 // This also ensures `-Wl,-z,now` is supported by the linker.
1014 let full_relro = RelroLevel::Full == relro_level;
1016 // If user didn't explicitly forced us to use / skip the PLT,
1017 // then try to skip it where possible.
1018 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1021 /// Checks if LLVM lifetime markers should be emitted.
1022 pub fn emit_lifetime_markers(&self) -> bool {
1023 self.opts.optimize != config::OptLevel::No
1024 // AddressSanitizer uses lifetimes to detect use after scope bugs.
1025 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1026 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY)
1029 pub fn mark_attr_known(&self, attr: &Attribute) {
1030 self.known_attrs.lock().mark(attr)
1033 pub fn is_attr_known(&self, attr: &Attribute) -> bool {
1034 self.known_attrs.lock().is_marked(attr)
1037 pub fn mark_attr_used(&self, attr: &Attribute) {
1038 self.used_attrs.lock().mark(attr)
1041 pub fn is_attr_used(&self, attr: &Attribute) -> bool {
1042 self.used_attrs.lock().is_marked(attr)
1045 /// Returns `true` if the attribute's path matches the argument. If it matches, then the
1046 /// attribute is marked as used.
1048 /// Returns `true` if the attribute's path matches the argument. If it
1049 /// matches, then the attribute is marked as used.
1051 /// This method should only be used by rustc, other tools can use
1052 /// `Attribute::has_name` instead, because only rustc is supposed to report
1053 /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1054 /// produced by lowering an `Attribute` and don't have identity, so they
1055 /// only have the `has_name` method, and you need to mark the original
1056 /// `Attribute` as used when necessary.)
1057 pub fn check_name(&self, attr: &Attribute, name: Symbol) -> bool {
1058 let matches = attr.has_name(name);
1060 self.mark_attr_used(attr);
1065 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1066 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1068 .any(|kind| self.check_name(attr, *kind))
1071 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1072 attrs.iter().any(|item| self.check_name(item, name))
1075 pub fn find_by_name<'a>(
1077 attrs: &'a [Attribute],
1079 ) -> Option<&'a Attribute> {
1080 attrs.iter().find(|attr| self.check_name(attr, name))
1083 pub fn filter_by_name<'a>(
1085 attrs: &'a [Attribute],
1087 ) -> impl Iterator<Item = &'a Attribute> {
1088 attrs.iter().filter(move |attr| self.check_name(attr, name))
1091 pub fn first_attr_value_str_by_name(
1093 attrs: &[Attribute],
1095 ) -> Option<Symbol> {
1096 attrs.iter().find(|at| self.check_name(at, name)).and_then(|at| at.value_str())
1101 sopts: &config::Options,
1102 registry: rustc_errors::registry::Registry,
1103 source_map: Lrc<SourceMap>,
1104 emitter_dest: Option<Box<dyn Write + Send>>,
1105 ) -> Box<dyn Emitter + sync::Send> {
1106 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1107 match (sopts.error_format, emitter_dest) {
1108 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1109 let (short, color_config) = kind.unzip();
1111 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1113 AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1114 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1116 let emitter = match dst {
1117 None => EmitterWriter::stderr(
1121 sopts.debugging_opts.teach,
1122 sopts.debugging_opts.terminal_width,
1125 Some(dst) => EmitterWriter::new(
1129 false, // no teach messages when writing to a buffer
1130 false, // no colors when writing to a buffer
1131 None, // no terminal width
1135 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1138 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1139 JsonEmitter::stderr(
1144 sopts.debugging_opts.terminal_width,
1147 .ui_testing(sopts.debugging_opts.ui_testing),
1149 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1156 sopts.debugging_opts.terminal_width,
1159 .ui_testing(sopts.debugging_opts.ui_testing),
1164 pub enum DiagnosticOutput {
1166 Raw(Box<dyn Write + Send>),
1169 pub fn build_session(
1170 sopts: config::Options,
1171 local_crate_source_file: Option<PathBuf>,
1172 registry: rustc_errors::registry::Registry,
1173 diagnostics_output: DiagnosticOutput,
1174 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1175 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1177 // FIXME: This is not general enough to make the warning lint completely override
1178 // normal diagnostic warnings, since the warning lint can also be denied and changed
1179 // later via the source code.
1180 let warnings_allow = sopts
1183 .filter(|&&(ref key, _)| *key == "warnings")
1184 .map(|&(_, ref level)| *level == lint::Allow)
1187 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1188 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1190 let write_dest = match diagnostics_output {
1191 DiagnosticOutput::Default => None,
1192 DiagnosticOutput::Raw(write) => Some(write),
1195 let target_cfg = config::build_target_config(&sopts, sopts.error_format);
1196 let host_triple = TargetTriple::from_triple(config::host_triple());
1197 let host = Target::search(&host_triple).unwrap_or_else(|e| {
1198 early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1201 let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
1202 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1203 if target_cfg.target.options.is_like_msvc {
1204 SourceFileHashAlgorithm::Sha1
1206 SourceFileHashAlgorithm::Md5
1209 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1211 sopts.file_path_mapping(),
1214 let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1216 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1218 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1221 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1224 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1226 let profiler = SelfProfiler::new(
1228 sopts.crate_name.as_ref().map(|s| &s[..]),
1229 &sopts.debugging_opts.self_profile_events,
1232 Ok(profiler) => Some(Arc::new(profiler)),
1234 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1242 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1243 let sysroot = match &sopts.maybe_sysroot {
1244 Some(sysroot) => sysroot.clone(),
1245 None => filesearch::get_or_default_sysroot(),
1248 let host_triple = config::host_triple();
1249 let target_triple = sopts.target_triple.triple();
1250 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1251 let target_tlib_path = if host_triple == target_triple {
1254 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1257 let file_path_mapping = sopts.file_path_mapping();
1259 let local_crate_source_file =
1260 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1262 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1263 let optimization_fuel = Lock::new(OptimizationFuel {
1264 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1267 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1268 let print_fuel = AtomicU64::new(0);
1270 let working_dir = env::current_dir().unwrap_or_else(|e| {
1271 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1273 let working_dir = file_path_mapping.map_prefix(working_dir);
1275 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1276 CguReuseTracker::new()
1278 CguReuseTracker::new_disabled()
1281 let prof = SelfProfilerRef::new(
1283 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1284 sopts.debugging_opts.time_passes,
1287 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1288 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1289 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1290 _ => CtfeBacktrace::Disabled,
1293 // Try to find a directory containing the Rust `src`, for more details see
1294 // the doc comment on the `real_rust_source_base_dir` field.
1295 let real_rust_source_base_dir = {
1296 // This is the location used by the `rust-src` `rustup` component.
1297 let mut candidate = sysroot.join("lib/rustlib/src/rust");
1298 if let Ok(metadata) = candidate.symlink_metadata() {
1299 // Replace the symlink rustbuild creates, with its destination.
1300 // We could try to use `fs::canonicalize` instead, but that might
1301 // produce unnecessarily verbose path.
1302 if metadata.file_type().is_symlink() {
1303 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1304 candidate = symlink_dest;
1309 // Only use this directory if it has a file we can expect to always find.
1310 if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None }
1313 let asm_arch = if target_cfg.target.options.allow_asm {
1314 InlineAsmArch::from_str(&target_cfg.target.arch).ok()
1319 let sess = Session {
1327 local_crate_source_file,
1329 one_time_diagnostics: Default::default(),
1330 crate_types: OnceCell::new(),
1331 crate_disambiguator: OnceCell::new(),
1332 features: OnceCell::new(),
1333 recursion_limit: OnceCell::new(),
1334 type_length_limit: OnceCell::new(),
1335 const_eval_limit: OnceCell::new(),
1336 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1339 perf_stats: PerfStats {
1340 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1341 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1342 queries_canonicalized: AtomicUsize::new(0),
1343 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1344 normalize_projection_ty: AtomicUsize::new(0),
1346 code_stats: Default::default(),
1347 optimization_fuel_crate,
1351 jobserver: jobserver::client(),
1353 trait_methods_not_found: Lock::new(Default::default()),
1354 confused_type_with_std_module: Lock::new(Default::default()),
1355 system_library_path: OneThread::new(RefCell::new(Default::default())),
1357 miri_unleashed_features: Lock::new(Default::default()),
1358 real_rust_source_base_dir,
1360 target_features: FxHashSet::default(),
1361 known_attrs: Lock::new(MarkedAttrs::new()),
1362 used_attrs: Lock::new(MarkedAttrs::new()),
1365 validate_commandline_args_with_session_available(&sess);
1370 // If it is useful to have a Session available already for validating a
1371 // commandline argument, you can do so here.
1372 fn validate_commandline_args_with_session_available(sess: &Session) {
1373 // Since we don't know if code in an rlib will be linked to statically or
1374 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1375 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1376 // these manually generated symbols confuse LLD when it tries to merge
1377 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1378 // when compiling for LLD ThinLTO. This way we can validly just not generate
1379 // the `dllimport` attributes and `__imp_` symbols in that case.
1380 if sess.opts.cg.linker_plugin_lto.enabled()
1381 && sess.opts.cg.prefer_dynamic
1382 && sess.target.target.options.is_like_windows
1385 "Linker plugin based LTO is not supported together with \
1386 `-C prefer-dynamic` when targeting Windows-like targets",
1390 // Make sure that any given profiling data actually exists so LLVM can't
1391 // decide to silently skip PGO.
1392 if let Some(ref path) = sess.opts.cg.profile_use {
1395 "File `{}` passed to `-C profile-use` does not exist.",
1401 // Unwind tables cannot be disabled if the target requires them.
1402 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1403 if sess.panic_strategy() == PanicStrategy::Unwind && !include_uwtables {
1405 "panic=unwind requires unwind tables, they cannot be disabled \
1406 with `-C force-unwind-tables=no`.",
1410 if sess.target.target.options.requires_uwtable && !include_uwtables {
1412 "target requires unwind tables, they cannot be disabled with \
1413 `-C force-unwind-tables=no`.",
1418 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1419 // an error to combine the two for now. It always runs into an assertions
1420 // if LLVM is built with assertions, but without assertions it sometimes
1421 // does not crash and will probably generate a corrupted binary.
1422 // We should only display this error if we're actually going to run PGO.
1423 // If we're just supposed to print out some data, don't show the error (#61002).
1424 if sess.opts.cg.profile_generate.enabled()
1425 && sess.target.target.options.is_like_msvc
1426 && sess.panic_strategy() == PanicStrategy::Unwind
1427 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1430 "Profile-guided optimization does not yet work in conjunction \
1431 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1432 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1433 for more information.",
1437 // FIXME(richkadel): See `src/test/run-make-fulldeps/instrument-coverage/Makefile`. After
1438 // compiling with `-Zinstrument-coverage`, the resulting binary generates a segfault during
1439 // the program's exit process (likely while attempting to generate the coverage stats in
1440 // the "*.profraw" file). An investigation to resolve the problem on Windows is ongoing,
1441 // but until this is resolved, the option is disabled on Windows, and the test is skipped
1442 // when targeting `MSVC`.
1443 if sess.opts.debugging_opts.instrument_coverage && sess.target.target.options.is_like_msvc {
1445 "Rust source-based code coverage instrumentation (with `-Z instrument-coverage`) \
1446 is not yet supported on Windows when targeting MSVC. The resulting binaries will \
1447 still be instrumented for experimentation purposes, but may not execute correctly.",
1451 const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1453 "aarch64-unknown-linux-gnu",
1454 "x86_64-apple-darwin",
1456 "x86_64-unknown-linux-gnu",
1458 const LSAN_SUPPORTED_TARGETS: &[&str] =
1459 &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1460 const MSAN_SUPPORTED_TARGETS: &[&str] =
1461 &["aarch64-unknown-linux-gnu", "x86_64-unknown-linux-gnu"];
1462 const TSAN_SUPPORTED_TARGETS: &[&str] =
1463 &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1465 // Sanitizers can only be used on some tested platforms.
1466 for s in sess.opts.debugging_opts.sanitizer {
1467 let supported_targets = match s {
1468 SanitizerSet::ADDRESS => ASAN_SUPPORTED_TARGETS,
1469 SanitizerSet::LEAK => LSAN_SUPPORTED_TARGETS,
1470 SanitizerSet::MEMORY => MSAN_SUPPORTED_TARGETS,
1471 SanitizerSet::THREAD => TSAN_SUPPORTED_TARGETS,
1472 _ => panic!("unrecognized sanitizer {}", s),
1474 if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1476 "`-Zsanitizer={}` only works with targets: {}",
1478 supported_targets.join(", ")
1481 let conflicting = sess.opts.debugging_opts.sanitizer - s;
1482 if !conflicting.is_empty() {
1484 "`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`",
1487 // Don't report additional errors.
1493 /// Holds data on the current incremental compilation session, if there is one.
1495 pub enum IncrCompSession {
1496 /// This is the state the session will be in until the incr. comp. dir is
1499 /// This is the state during which the session directory is private and can
1501 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1502 /// This is the state after the session directory has been finalized. In this
1503 /// state, the contents of the directory must not be modified any more.
1504 Finalized { session_directory: PathBuf },
1505 /// This is an error state that is reached when some compilation error has
1506 /// occurred. It indicates that the contents of the session directory must
1507 /// not be used, since they might be invalid.
1508 InvalidBecauseOfErrors { session_directory: PathBuf },
1511 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1512 let emitter: Box<dyn Emitter + sync::Send> = match output {
1513 config::ErrorOutputType::HumanReadable(kind) => {
1514 let (short, color_config) = kind.unzip();
1515 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1517 config::ErrorOutputType::Json { pretty, json_rendered } => {
1518 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1521 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1522 handler.struct_fatal(msg).emit();
1523 rustc_errors::FatalError.raise();
1526 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1527 let emitter: Box<dyn Emitter + sync::Send> = match output {
1528 config::ErrorOutputType::HumanReadable(kind) => {
1529 let (short, color_config) = kind.unzip();
1530 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1532 config::ErrorOutputType::Json { pretty, json_rendered } => {
1533 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1536 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1537 handler.struct_warn(msg).emit();
1540 pub type CompileResult = Result<(), ErrorReported>;