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>,
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()
441 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
442 self.diagnostic().delay_span_bug(sp, msg)
444 pub fn note_without_error(&self, msg: &str) {
445 self.diagnostic().note_without_error(msg)
447 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
448 self.diagnostic().span_note_without_error(sp, msg)
450 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
451 self.diagnostic().struct_note_without_error(msg)
454 pub fn diagnostic(&self) -> &rustc_errors::Handler {
455 &self.parse_sess.span_diagnostic
458 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
459 /// deduplicates on lint ID, span (if any), and message for this `Session`
460 fn diag_once<'a, 'b>(
462 diag_builder: &'b mut DiagnosticBuilder<'a>,
463 method: DiagnosticBuilderMethod,
464 msg_id: DiagnosticMessageId,
466 span_maybe: Option<Span>,
468 let id_span_message = (msg_id, span_maybe, message.to_owned());
469 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
472 DiagnosticBuilderMethod::Note => {
473 diag_builder.note(message);
475 DiagnosticBuilderMethod::SpanNote => {
476 let span = span_maybe.expect("`span_note` needs a span");
477 diag_builder.span_note(span, message);
479 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
480 let span = span_maybe.expect("`span_suggestion_*` needs a span");
481 diag_builder.span_suggestion(
485 Applicability::Unspecified,
492 pub fn diag_span_note_once<'a, 'b>(
494 diag_builder: &'b mut DiagnosticBuilder<'a>,
495 msg_id: DiagnosticMessageId,
501 DiagnosticBuilderMethod::SpanNote,
508 pub fn diag_note_once<'a, 'b>(
510 diag_builder: &'b mut DiagnosticBuilder<'a>,
511 msg_id: DiagnosticMessageId,
514 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
517 pub fn diag_span_suggestion_once<'a, 'b>(
519 diag_builder: &'b mut DiagnosticBuilder<'a>,
520 msg_id: DiagnosticMessageId,
527 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
535 pub fn source_map(&self) -> &SourceMap {
536 self.parse_sess.source_map()
538 pub fn verbose(&self) -> bool {
539 self.opts.debugging_opts.verbose
541 pub fn time_passes(&self) -> bool {
542 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
544 pub fn instrument_mcount(&self) -> bool {
545 self.opts.debugging_opts.instrument_mcount
547 pub fn time_llvm_passes(&self) -> bool {
548 self.opts.debugging_opts.time_llvm_passes
550 pub fn meta_stats(&self) -> bool {
551 self.opts.debugging_opts.meta_stats
553 pub fn asm_comments(&self) -> bool {
554 self.opts.debugging_opts.asm_comments
556 pub fn verify_llvm_ir(&self) -> bool {
557 self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
559 pub fn borrowck_stats(&self) -> bool {
560 self.opts.debugging_opts.borrowck_stats
562 pub fn print_llvm_passes(&self) -> bool {
563 self.opts.debugging_opts.print_llvm_passes
565 pub fn binary_dep_depinfo(&self) -> bool {
566 self.opts.debugging_opts.binary_dep_depinfo
569 /// Gets the features enabled for the current compilation session.
570 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
571 /// dependency tracking. Use tcx.features() instead.
573 pub fn features_untracked(&self) -> &rustc_feature::Features {
574 self.features.get().unwrap()
577 pub fn init_features(&self, features: rustc_feature::Features) {
578 match self.features.set(features) {
580 Err(_) => panic!("`features` was initialized twice"),
584 /// Calculates the flavor of LTO to use for this compilation.
585 pub fn lto(&self) -> config::Lto {
586 // If our target has codegen requirements ignore the command line
587 if self.target.target.options.requires_lto {
588 return config::Lto::Fat;
591 // If the user specified something, return that. If they only said `-C
592 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
593 // then ensure we can't use a ThinLTO.
594 match self.opts.cg.lto {
595 config::LtoCli::Unspecified => {
596 // The compiler was invoked without the `-Clto` flag. Fall
597 // through to the default handling
599 config::LtoCli::No => {
600 // The user explicitly opted out of any kind of LTO
601 return config::Lto::No;
603 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
604 // All of these mean fat LTO
605 return config::Lto::Fat;
607 config::LtoCli::Thin => {
608 return if self.opts.cli_forced_thinlto_off {
616 // Ok at this point the target doesn't require anything and the user
617 // hasn't asked for anything. Our next decision is whether or not
618 // we enable "auto" ThinLTO where we use multiple codegen units and
619 // then do ThinLTO over those codegen units. The logic below will
620 // either return `No` or `ThinLocal`.
622 // If processing command line options determined that we're incompatible
623 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
624 if self.opts.cli_forced_thinlto_off {
625 return config::Lto::No;
628 // If `-Z thinlto` specified process that, but note that this is mostly
629 // a deprecated option now that `-C lto=thin` exists.
630 if let Some(enabled) = self.opts.debugging_opts.thinlto {
632 return config::Lto::ThinLocal;
634 return config::Lto::No;
638 // If there's only one codegen unit and LTO isn't enabled then there's
639 // no need for ThinLTO so just return false.
640 if self.codegen_units() == 1 {
641 return config::Lto::No;
644 // Now we're in "defaults" territory. By default we enable ThinLTO for
645 // optimized compiles (anything greater than O0).
646 match self.opts.optimize {
647 config::OptLevel::No => config::Lto::No,
648 _ => config::Lto::ThinLocal,
652 /// Returns the panic strategy for this compile session. If the user explicitly selected one
653 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
654 pub fn panic_strategy(&self) -> PanicStrategy {
655 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
657 pub fn fewer_names(&self) -> bool {
658 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
659 || self.opts.output_types.contains_key(&OutputType::Bitcode)
660 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
661 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
663 self.opts.debugging_opts.fewer_names || !more_names
666 pub fn unstable_options(&self) -> bool {
667 self.opts.debugging_opts.unstable_options
669 pub fn overflow_checks(&self) -> bool {
673 .or(self.opts.debugging_opts.force_overflow_checks)
674 .unwrap_or(self.opts.debug_assertions)
677 /// Check whether this compile session and crate type use static crt.
678 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
679 if !self.target.target.options.crt_static_respected {
680 // If the target does not opt in to crt-static support, use its default.
681 return self.target.target.options.crt_static_default;
684 let requested_features = self.opts.cg.target_feature.split(',');
685 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
686 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
688 if found_positive || found_negative {
690 } else if crate_type == Some(CrateType::ProcMacro)
691 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
693 // FIXME: When crate_type is not available,
694 // we use compiler options to determine the crate_type.
695 // We can't check `#![crate_type = "proc-macro"]` here.
698 self.target.target.options.crt_static_default
702 pub fn relocation_model(&self) -> RelocModel {
703 self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
706 pub fn code_model(&self) -> Option<CodeModel> {
707 self.opts.cg.code_model.or(self.target.target.options.code_model)
710 pub fn tls_model(&self) -> TlsModel {
711 self.opts.debugging_opts.tls_model.unwrap_or(self.target.target.options.tls_model)
714 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
715 // "mcount" function relies on stack pointer.
716 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
717 if self.instrument_mcount() {
719 } else if let Some(x) = self.opts.cg.force_frame_pointers {
722 !self.target.target.options.eliminate_frame_pointer
726 pub fn must_emit_unwind_tables(&self) -> bool {
727 // This is used to control the emission of the `uwtable` attribute on
730 // At the very least, unwind tables are needed when compiling with
731 // `-C panic=unwind`.
733 // On some targets (including windows), however, exceptions include
734 // other events such as illegal instructions, segfaults, etc. This means
735 // that on Windows we end up still needing unwind tables even if the `-C
736 // panic=abort` flag is passed.
738 // You can also find more info on why Windows needs unwind tables in:
739 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
741 // If a target requires unwind tables, then they must be emitted.
742 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
743 // value, if it is provided, or disable them, if not.
744 if self.panic_strategy() == PanicStrategy::Unwind {
746 } else if self.target.target.options.requires_uwtable {
749 self.opts.cg.force_unwind_tables.unwrap_or(false)
753 /// Returns the symbol name for the registrar function,
754 /// given the crate `Svh` and the function `DefIndex`.
755 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
756 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
759 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
760 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
763 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
764 filesearch::FileSearch::new(
766 self.opts.target_triple.triple(),
767 &self.opts.search_paths,
768 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
769 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
773 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
774 filesearch::FileSearch::new(
776 config::host_triple(),
777 &self.opts.search_paths,
778 &self.host_tlib_path,
783 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
784 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
786 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
787 *load_dep_graph = load;
791 pub fn incr_session_load_dep_graph(&self) -> bool {
792 let incr_comp_session = self.incr_comp_session.borrow();
793 match *incr_comp_session {
794 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
799 pub fn init_incr_comp_session(
801 session_dir: PathBuf,
802 lock_file: flock::Lock,
803 load_dep_graph: bool,
805 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
807 if let IncrCompSession::NotInitialized = *incr_comp_session {
809 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
813 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
816 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
817 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
819 if let IncrCompSession::Active { .. } = *incr_comp_session {
821 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
824 // Note: this will also drop the lock file, thus unlocking the directory.
825 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
828 pub fn mark_incr_comp_session_as_invalid(&self) {
829 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
831 let session_directory = match *incr_comp_session {
832 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
833 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
834 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
837 // Note: this will also drop the lock file, thus unlocking the directory.
838 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
841 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
842 let incr_comp_session = self.incr_comp_session.borrow();
843 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
844 IncrCompSession::NotInitialized => panic!(
845 "trying to get session directory from `IncrCompSession`: {:?}",
848 IncrCompSession::Active { ref session_directory, .. }
849 | IncrCompSession::Finalized { ref session_directory }
850 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
856 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
857 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
860 pub fn print_perf_stats(&self) {
862 "Total time spent computing symbol hashes: {}",
863 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
866 "Total time spent decoding DefPath tables: {}",
867 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
870 "Total queries canonicalized: {}",
871 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
874 "normalize_generic_arg_after_erasing_regions: {}",
875 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
878 "normalize_projection_ty: {}",
879 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
883 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
884 /// This expends fuel if applicable, and records fuel if applicable.
885 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
887 if let Some(ref c) = self.optimization_fuel_crate {
889 assert_eq!(self.threads(), 1);
890 let mut fuel = self.optimization_fuel.lock();
891 ret = fuel.remaining != 0;
892 if fuel.remaining == 0 && !fuel.out_of_fuel {
893 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
894 fuel.out_of_fuel = true;
895 } else if fuel.remaining > 0 {
900 if let Some(ref c) = self.print_fuel_crate {
902 assert_eq!(self.threads(), 1);
903 self.print_fuel.fetch_add(1, SeqCst);
909 /// Returns the number of query threads that should be used for this
911 pub fn threads(&self) -> usize {
912 self.opts.debugging_opts.threads
915 /// Returns the number of codegen units that should be used for this
917 pub fn codegen_units(&self) -> usize {
918 if let Some(n) = self.opts.cli_forced_codegen_units {
921 if let Some(n) = self.target.target.options.default_codegen_units {
925 // If incremental compilation is turned on, we default to a high number
926 // codegen units in order to reduce the "collateral damage" small
928 if self.opts.incremental.is_some() {
932 // Why is 16 codegen units the default all the time?
934 // The main reason for enabling multiple codegen units by default is to
935 // leverage the ability for the codegen backend to do codegen and
936 // optimization in parallel. This allows us, especially for large crates, to
937 // make good use of all available resources on the machine once we've
938 // hit that stage of compilation. Large crates especially then often
939 // take a long time in codegen/optimization and this helps us amortize that
942 // Note that a high number here doesn't mean that we'll be spawning a
943 // large number of threads in parallel. The backend of rustc contains
944 // global rate limiting through the `jobserver` crate so we'll never
945 // overload the system with too much work, but rather we'll only be
946 // optimizing when we're otherwise cooperating with other instances of
949 // Rather a high number here means that we should be able to keep a lot
950 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
951 // to build we'll be guaranteed that all cpus will finish pretty closely
952 // to one another and we should make relatively optimal use of system
955 // Note that the main cost of codegen units is that it prevents LLVM
956 // from inlining across codegen units. Users in general don't have a lot
957 // of control over how codegen units are split up so it's our job in the
958 // compiler to ensure that undue performance isn't lost when using
959 // codegen units (aka we can't require everyone to slap `#[inline]` on
962 // If we're compiling at `-O0` then the number doesn't really matter too
963 // much because performance doesn't matter and inlining is ok to lose.
964 // In debug mode we just want to try to guarantee that no cpu is stuck
965 // doing work that could otherwise be farmed to others.
967 // In release mode, however (O1 and above) performance does indeed
968 // matter! To recover the loss in performance due to inlining we'll be
969 // enabling ThinLTO by default (the function for which is just below).
970 // This will ensure that we recover any inlining wins we otherwise lost
971 // through codegen unit partitioning.
975 // Ok that's a lot of words but the basic tl;dr; is that we want a high
976 // number here -- but not too high. Additionally we're "safe" to have it
977 // always at the same number at all optimization levels.
979 // As a result 16 was chosen here! Mostly because it was a power of 2
980 // and most benchmarks agreed it was roughly a local optimum. Not very
985 pub fn teach(&self, code: &DiagnosticId) -> bool {
986 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
989 pub fn rust_2015(&self) -> bool {
990 self.opts.edition == Edition::Edition2015
993 /// Are we allowed to use features from the Rust 2018 edition?
994 pub fn rust_2018(&self) -> bool {
995 self.opts.edition >= Edition::Edition2018
998 pub fn edition(&self) -> Edition {
1002 /// Returns `true` if we cannot skip the PLT for shared library calls.
1003 pub fn needs_plt(&self) -> bool {
1004 // Check if the current target usually needs PLT to be enabled.
1005 // The user can use the command line flag to override it.
1006 let needs_plt = self.target.target.options.needs_plt;
1008 let dbg_opts = &self.opts.debugging_opts;
1010 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
1012 // Only enable this optimization by default if full relro is also enabled.
1013 // In this case, lazy binding was already unavailable, so nothing is lost.
1014 // This also ensures `-Wl,-z,now` is supported by the linker.
1015 let full_relro = RelroLevel::Full == relro_level;
1017 // If user didn't explicitly forced us to use / skip the PLT,
1018 // then try to skip it where possible.
1019 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1022 /// Checks if LLVM lifetime markers should be emitted.
1023 pub fn emit_lifetime_markers(&self) -> bool {
1024 self.opts.optimize != config::OptLevel::No
1025 // AddressSanitizer uses lifetimes to detect use after scope bugs.
1026 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1027 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY)
1030 pub fn mark_attr_known(&self, attr: &Attribute) {
1031 self.known_attrs.lock().mark(attr)
1034 pub fn is_attr_known(&self, attr: &Attribute) -> bool {
1035 self.known_attrs.lock().is_marked(attr)
1038 pub fn mark_attr_used(&self, attr: &Attribute) {
1039 self.used_attrs.lock().mark(attr)
1042 pub fn is_attr_used(&self, attr: &Attribute) -> bool {
1043 self.used_attrs.lock().is_marked(attr)
1046 /// Returns `true` if the attribute's path matches the argument. If it matches, then the
1047 /// attribute is marked as used.
1049 /// Returns `true` if the attribute's path matches the argument. If it
1050 /// matches, then the attribute is marked as used.
1052 /// This method should only be used by rustc, other tools can use
1053 /// `Attribute::has_name` instead, because only rustc is supposed to report
1054 /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1055 /// produced by lowering an `Attribute` and don't have identity, so they
1056 /// only have the `has_name` method, and you need to mark the original
1057 /// `Attribute` as used when necessary.)
1058 pub fn check_name(&self, attr: &Attribute, name: Symbol) -> bool {
1059 let matches = attr.has_name(name);
1061 self.mark_attr_used(attr);
1066 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1067 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1069 .any(|kind| self.check_name(attr, *kind))
1072 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1073 attrs.iter().any(|item| self.check_name(item, name))
1076 pub fn find_by_name<'a>(
1078 attrs: &'a [Attribute],
1080 ) -> Option<&'a Attribute> {
1081 attrs.iter().find(|attr| self.check_name(attr, name))
1084 pub fn filter_by_name<'a>(
1086 attrs: &'a [Attribute],
1088 ) -> impl Iterator<Item = &'a Attribute> {
1089 attrs.iter().filter(move |attr| self.check_name(attr, name))
1092 pub fn first_attr_value_str_by_name(
1094 attrs: &[Attribute],
1096 ) -> Option<Symbol> {
1097 attrs.iter().find(|at| self.check_name(at, name)).and_then(|at| at.value_str())
1102 sopts: &config::Options,
1103 registry: rustc_errors::registry::Registry,
1104 source_map: Lrc<SourceMap>,
1105 emitter_dest: Option<Box<dyn Write + Send>>,
1106 ) -> Box<dyn Emitter + sync::Send> {
1107 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1108 match (sopts.error_format, emitter_dest) {
1109 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1110 let (short, color_config) = kind.unzip();
1112 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1114 AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1115 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1117 let emitter = match dst {
1118 None => EmitterWriter::stderr(
1122 sopts.debugging_opts.teach,
1123 sopts.debugging_opts.terminal_width,
1126 Some(dst) => EmitterWriter::new(
1130 false, // no teach messages when writing to a buffer
1131 false, // no colors when writing to a buffer
1132 None, // no terminal width
1136 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1139 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1140 JsonEmitter::stderr(
1145 sopts.debugging_opts.terminal_width,
1148 .ui_testing(sopts.debugging_opts.ui_testing),
1150 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1157 sopts.debugging_opts.terminal_width,
1160 .ui_testing(sopts.debugging_opts.ui_testing),
1165 pub enum DiagnosticOutput {
1167 Raw(Box<dyn Write + Send>),
1170 pub fn build_session(
1171 sopts: config::Options,
1172 local_crate_source_file: Option<PathBuf>,
1173 registry: rustc_errors::registry::Registry,
1174 diagnostics_output: DiagnosticOutput,
1175 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1176 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1178 // FIXME: This is not general enough to make the warning lint completely override
1179 // normal diagnostic warnings, since the warning lint can also be denied and changed
1180 // later via the source code.
1181 let warnings_allow = sopts
1184 .filter(|&&(ref key, _)| *key == "warnings")
1185 .map(|&(_, ref level)| *level == lint::Allow)
1188 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1189 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1191 let write_dest = match diagnostics_output {
1192 DiagnosticOutput::Default => None,
1193 DiagnosticOutput::Raw(write) => Some(write),
1196 let target_cfg = config::build_target_config(&sopts, sopts.error_format);
1197 let host_triple = TargetTriple::from_triple(config::host_triple());
1198 let host = Target::search(&host_triple).unwrap_or_else(|e| {
1199 early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1202 let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
1203 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1204 if target_cfg.target.options.is_like_msvc {
1205 SourceFileHashAlgorithm::Sha1
1207 SourceFileHashAlgorithm::Md5
1210 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1212 sopts.file_path_mapping(),
1215 let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1217 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1219 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1222 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1225 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1227 let profiler = SelfProfiler::new(
1229 sopts.crate_name.as_ref().map(|s| &s[..]),
1230 &sopts.debugging_opts.self_profile_events,
1233 Ok(profiler) => Some(Arc::new(profiler)),
1235 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1243 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1244 let sysroot = match &sopts.maybe_sysroot {
1245 Some(sysroot) => sysroot.clone(),
1246 None => filesearch::get_or_default_sysroot(),
1249 let host_triple = config::host_triple();
1250 let target_triple = sopts.target_triple.triple();
1251 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1252 let target_tlib_path = if host_triple == target_triple {
1255 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1258 let file_path_mapping = sopts.file_path_mapping();
1260 let local_crate_source_file =
1261 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1263 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1264 let optimization_fuel = Lock::new(OptimizationFuel {
1265 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1268 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1269 let print_fuel = AtomicU64::new(0);
1271 let working_dir = env::current_dir().unwrap_or_else(|e| {
1272 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1274 let working_dir = file_path_mapping.map_prefix(working_dir);
1276 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1277 CguReuseTracker::new()
1279 CguReuseTracker::new_disabled()
1282 let prof = SelfProfilerRef::new(
1284 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1285 sopts.debugging_opts.time_passes,
1288 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1289 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1290 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1291 _ => CtfeBacktrace::Disabled,
1294 // Try to find a directory containing the Rust `src`, for more details see
1295 // the doc comment on the `real_rust_source_base_dir` field.
1296 let real_rust_source_base_dir = {
1297 // This is the location used by the `rust-src` `rustup` component.
1298 let mut candidate = sysroot.join("lib/rustlib/src/rust");
1299 if let Ok(metadata) = candidate.symlink_metadata() {
1300 // Replace the symlink rustbuild creates, with its destination.
1301 // We could try to use `fs::canonicalize` instead, but that might
1302 // produce unnecessarily verbose path.
1303 if metadata.file_type().is_symlink() {
1304 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1305 candidate = symlink_dest;
1310 // Only use this directory if it has a file we can expect to always find.
1311 if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None }
1314 let asm_arch = if target_cfg.target.options.allow_asm {
1315 InlineAsmArch::from_str(&target_cfg.target.arch).ok()
1320 let sess = Session {
1328 local_crate_source_file,
1330 one_time_diagnostics: Default::default(),
1331 crate_types: OnceCell::new(),
1332 crate_disambiguator: OnceCell::new(),
1333 features: OnceCell::new(),
1334 recursion_limit: OnceCell::new(),
1335 type_length_limit: OnceCell::new(),
1336 const_eval_limit: OnceCell::new(),
1337 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1340 perf_stats: PerfStats {
1341 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1342 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1343 queries_canonicalized: AtomicUsize::new(0),
1344 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1345 normalize_projection_ty: AtomicUsize::new(0),
1347 code_stats: Default::default(),
1348 optimization_fuel_crate,
1352 jobserver: jobserver::client(),
1354 trait_methods_not_found: Lock::new(Default::default()),
1355 confused_type_with_std_module: Lock::new(Default::default()),
1356 system_library_path: OneThread::new(RefCell::new(Default::default())),
1358 miri_unleashed_features: Lock::new(Default::default()),
1359 real_rust_source_base_dir,
1361 target_features: FxHashSet::default(),
1362 known_attrs: Lock::new(MarkedAttrs::new()),
1363 used_attrs: Lock::new(MarkedAttrs::new()),
1366 validate_commandline_args_with_session_available(&sess);
1371 // If it is useful to have a Session available already for validating a
1372 // commandline argument, you can do so here.
1373 fn validate_commandline_args_with_session_available(sess: &Session) {
1374 // Since we don't know if code in an rlib will be linked to statically or
1375 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1376 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1377 // these manually generated symbols confuse LLD when it tries to merge
1378 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1379 // when compiling for LLD ThinLTO. This way we can validly just not generate
1380 // the `dllimport` attributes and `__imp_` symbols in that case.
1381 if sess.opts.cg.linker_plugin_lto.enabled()
1382 && sess.opts.cg.prefer_dynamic
1383 && sess.target.target.options.is_like_windows
1386 "Linker plugin based LTO is not supported together with \
1387 `-C prefer-dynamic` when targeting Windows-like targets",
1391 // Make sure that any given profiling data actually exists so LLVM can't
1392 // decide to silently skip PGO.
1393 if let Some(ref path) = sess.opts.cg.profile_use {
1396 "File `{}` passed to `-C profile-use` does not exist.",
1402 // Unwind tables cannot be disabled if the target requires them.
1403 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1404 if sess.panic_strategy() == PanicStrategy::Unwind && !include_uwtables {
1406 "panic=unwind requires unwind tables, they cannot be disabled \
1407 with `-C force-unwind-tables=no`.",
1411 if sess.target.target.options.requires_uwtable && !include_uwtables {
1413 "target requires unwind tables, they cannot be disabled with \
1414 `-C force-unwind-tables=no`.",
1419 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1420 // an error to combine the two for now. It always runs into an assertions
1421 // if LLVM is built with assertions, but without assertions it sometimes
1422 // does not crash and will probably generate a corrupted binary.
1423 // We should only display this error if we're actually going to run PGO.
1424 // If we're just supposed to print out some data, don't show the error (#61002).
1425 if sess.opts.cg.profile_generate.enabled()
1426 && sess.target.target.options.is_like_msvc
1427 && sess.panic_strategy() == PanicStrategy::Unwind
1428 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1431 "Profile-guided optimization does not yet work in conjunction \
1432 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1433 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1434 for more information.",
1438 // FIXME(richkadel): See `src/test/run-make-fulldeps/instrument-coverage/Makefile`. After
1439 // compiling with `-Zinstrument-coverage`, the resulting binary generates a segfault during
1440 // the program's exit process (likely while attempting to generate the coverage stats in
1441 // the "*.profraw" file). An investigation to resolve the problem on Windows is ongoing,
1442 // but until this is resolved, the option is disabled on Windows, and the test is skipped
1443 // when targeting `MSVC`.
1444 if sess.opts.debugging_opts.instrument_coverage && sess.target.target.options.is_like_msvc {
1446 "Rust source-based code coverage instrumentation (with `-Z instrument-coverage`) \
1447 is not yet supported on Windows when targeting MSVC. The resulting binaries will \
1448 still be instrumented for experimentation purposes, but may not execute correctly.",
1452 const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1454 "aarch64-unknown-linux-gnu",
1455 "x86_64-apple-darwin",
1457 "x86_64-unknown-freebsd",
1458 "x86_64-unknown-linux-gnu",
1460 const LSAN_SUPPORTED_TARGETS: &[&str] =
1461 &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1462 const MSAN_SUPPORTED_TARGETS: &[&str] =
1463 &["aarch64-unknown-linux-gnu", "x86_64-unknown-freebsd", "x86_64-unknown-linux-gnu"];
1464 const TSAN_SUPPORTED_TARGETS: &[&str] = &[
1465 "aarch64-unknown-linux-gnu",
1466 "x86_64-apple-darwin",
1467 "x86_64-unknown-freebsd",
1468 "x86_64-unknown-linux-gnu",
1471 // Sanitizers can only be used on some tested platforms.
1472 for s in sess.opts.debugging_opts.sanitizer {
1473 let supported_targets = match s {
1474 SanitizerSet::ADDRESS => ASAN_SUPPORTED_TARGETS,
1475 SanitizerSet::LEAK => LSAN_SUPPORTED_TARGETS,
1476 SanitizerSet::MEMORY => MSAN_SUPPORTED_TARGETS,
1477 SanitizerSet::THREAD => TSAN_SUPPORTED_TARGETS,
1478 _ => panic!("unrecognized sanitizer {}", s),
1480 if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1482 "`-Zsanitizer={}` only works with targets: {}",
1484 supported_targets.join(", ")
1487 let conflicting = sess.opts.debugging_opts.sanitizer - s;
1488 if !conflicting.is_empty() {
1490 "`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`",
1493 // Don't report additional errors.
1499 /// Holds data on the current incremental compilation session, if there is one.
1501 pub enum IncrCompSession {
1502 /// This is the state the session will be in until the incr. comp. dir is
1505 /// This is the state during which the session directory is private and can
1507 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1508 /// This is the state after the session directory has been finalized. In this
1509 /// state, the contents of the directory must not be modified any more.
1510 Finalized { session_directory: PathBuf },
1511 /// This is an error state that is reached when some compilation error has
1512 /// occurred. It indicates that the contents of the session directory must
1513 /// not be used, since they might be invalid.
1514 InvalidBecauseOfErrors { session_directory: PathBuf },
1517 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1518 let emitter: Box<dyn Emitter + sync::Send> = match output {
1519 config::ErrorOutputType::HumanReadable(kind) => {
1520 let (short, color_config) = kind.unzip();
1521 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1523 config::ErrorOutputType::Json { pretty, json_rendered } => {
1524 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1527 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1528 handler.struct_fatal(msg).emit();
1529 rustc_errors::FatalError.raise();
1532 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1533 let emitter: Box<dyn Emitter + sync::Send> = match output {
1534 config::ErrorOutputType::HumanReadable(kind) => {
1535 let (short, color_config) = kind.unzip();
1536 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1538 config::ErrorOutputType::Json { pretty, json_rendered } => {
1539 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1542 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1543 handler.struct_warn(msg).emit();
1546 pub type CompileResult = Result<(), ErrorReported>;