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, SwitchWithOptPath}
;
6 use crate::lint
::{self, LintId}
;
7 use crate::parse
::ParseSess
;
8 use crate::search_paths
::{PathKind, SearchPath}
;
10 pub use rustc_ast
::attr
::MarkedAttrs
;
11 pub use rustc_ast
::Attribute
;
12 use rustc_data_structures
::flock
;
13 use rustc_data_structures
::fx
::{FxHashMap, FxHashSet}
;
14 use rustc_data_structures
::jobserver
::{self, Client}
;
15 use rustc_data_structures
::profiling
::{duration_to_secs_str, SelfProfiler, SelfProfilerRef}
;
16 use rustc_data_structures
::sync
::{
17 self, AtomicU64
, AtomicUsize
, Lock
, Lrc
, OnceCell
, OneThread
, Ordering
, Ordering
::SeqCst
,
19 use rustc_errors
::annotate_snippet_emitter_writer
::AnnotateSnippetEmitterWriter
;
20 use rustc_errors
::emitter
::{Emitter, EmitterWriter, HumanReadableErrorType}
;
21 use rustc_errors
::json
::JsonEmitter
;
22 use rustc_errors
::registry
::Registry
;
23 use rustc_errors
::{Diagnostic, DiagnosticBuilder, DiagnosticId, ErrorReported}
;
24 use rustc_lint_defs
::FutureBreakage
;
25 pub use rustc_span
::crate_disambiguator
::CrateDisambiguator
;
26 use rustc_span
::source_map
::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span}
;
27 use rustc_span
::{edition::Edition, RealFileName}
;
28 use rustc_span
::{sym, SourceFileHashAlgorithm, Symbol}
;
29 use rustc_target
::asm
::InlineAsmArch
;
30 use rustc_target
::spec
::{CodeModel, PanicStrategy, RelocModel, RelroLevel}
;
31 use rustc_target
::spec
::{SanitizerSet, SplitDebuginfo, Target, TargetTriple, TlsModel}
;
33 use std
::cell
::{self, RefCell}
;
37 use std
::num
::NonZeroU32
;
38 use std
::ops
::{Div, Mul}
;
39 use std
::path
::PathBuf
;
40 use std
::str::FromStr
;
42 use std
::time
::Duration
;
44 pub trait SessionLintStore
: sync
::Send
+ sync
::Sync
{
45 fn name_to_lint(&self, lint_name
: &str) -> LintId
;
48 pub struct OptimizationFuel
{
49 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
51 /// We're rejecting all further optimizations.
55 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
56 #[derive(Clone, Copy)]
57 pub enum CtfeBacktrace
{
58 /// Do nothing special, return the error as usual without a backtrace.
60 /// Capture a backtrace at the point the error is created and return it in the error
61 /// (to be printed later if/when the error ever actually gets shown to the user).
63 /// Capture a backtrace at the point the error is created and immediately print it out.
67 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
68 /// limits are consistent throughout the compiler.
69 #[derive(Clone, Copy, Debug)]
70 pub struct Limit(pub usize);
73 /// Create a new limit from a `usize`.
74 pub fn new(value
: usize) -> Self {
78 /// Check that `value` is within the limit. Ensures that the same comparisons are used
79 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
81 pub fn value_within_limit(&self, value
: usize) -> bool
{
86 impl From
<usize> for Limit
{
87 fn from(value
: usize) -> Self {
92 impl fmt
::Display
for Limit
{
93 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
94 write
!(f
, "{}", self.0)
98 impl Div
<usize> for Limit
{
101 fn div(self, rhs
: usize) -> Self::Output
{
102 Limit
::new(self.0 / rhs
)
106 impl Mul
<usize> for Limit
{
109 fn mul(self, rhs
: usize) -> Self::Output
{
110 Limit
::new(self.0 * rhs
)
114 /// Represents the data associated with a compilation
115 /// session for a single crate.
119 pub opts
: config
::Options
,
120 pub host_tlib_path
: SearchPath
,
121 /// `None` if the host and target are the same.
122 pub target_tlib_path
: Option
<SearchPath
>,
123 pub parse_sess
: ParseSess
,
124 pub sysroot
: PathBuf
,
125 /// The name of the root source file of the crate, in the local file system.
126 /// `None` means that there is no source file.
127 pub local_crate_source_file
: Option
<PathBuf
>,
128 /// The directory the compiler has been executed in
129 pub working_dir
: RealFileName
,
131 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
132 /// (sub)diagnostics that have been set once, but should not be set again,
133 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
134 pub one_time_diagnostics
: Lock
<FxHashSet
<(DiagnosticMessageId
, Option
<Span
>, String
)>>,
135 crate_types
: OnceCell
<Vec
<CrateType
>>,
136 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
137 /// arguments passed to the compiler. Its value together with the crate-name
138 /// forms a unique global identifier for the crate. It is used to allow
139 /// multiple crates with the same name to coexist. See the
140 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
141 pub crate_disambiguator
: OnceCell
<CrateDisambiguator
>,
143 features
: OnceCell
<rustc_feature
::Features
>,
145 lint_store
: OnceCell
<Lrc
<dyn SessionLintStore
>>,
147 /// The maximum recursion limit for potentially infinitely recursive
148 /// operations such as auto-dereference and monomorphization.
149 pub recursion_limit
: OnceCell
<Limit
>,
151 /// The size at which the `large_assignments` lint starts
153 pub move_size_limit
: OnceCell
<usize>,
155 /// The maximum length of types during monomorphization.
156 pub type_length_limit
: OnceCell
<Limit
>,
158 /// The maximum blocks a const expression can evaluate.
159 pub const_eval_limit
: OnceCell
<Limit
>,
161 incr_comp_session
: OneThread
<RefCell
<IncrCompSession
>>,
162 /// Used for incremental compilation tests. Will only be populated if
163 /// `-Zquery-dep-graph` is specified.
164 pub cgu_reuse_tracker
: CguReuseTracker
,
166 /// Used by `-Z self-profile`.
167 pub prof
: SelfProfilerRef
,
169 /// Some measurements that are being gathered during compilation.
170 pub perf_stats
: PerfStats
,
172 /// Data about code being compiled, gathered during compilation.
173 pub code_stats
: CodeStats
,
175 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
176 optimization_fuel_crate
: Option
<String
>,
178 /// Tracks fuel info if `-zfuel=crate=n` is specified.
179 optimization_fuel
: Lock
<OptimizationFuel
>,
181 // The next two are public because the driver needs to read them.
182 /// If `-zprint-fuel=crate`, `Some(crate)`.
183 pub print_fuel_crate
: Option
<String
>,
184 /// Always set to zero and incremented so that we can print fuel expended by a crate.
185 pub print_fuel
: AtomicU64
,
187 /// Loaded up early on in the initialization of this `Session` to avoid
188 /// false positives about a job server in our environment.
189 pub jobserver
: Client
,
191 /// Cap lint level specified by a driver specifically.
192 pub driver_lint_caps
: FxHashMap
<lint
::LintId
, lint
::Level
>,
194 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
195 pub trait_methods_not_found
: Lock
<FxHashSet
<Span
>>,
197 /// Mapping from ident span to path span for paths that don't exist as written, but that
198 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
199 pub confused_type_with_std_module
: Lock
<FxHashMap
<Span
, Span
>>,
201 /// Path for libraries that will take preference over libraries shipped by Rust.
202 /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
203 pub system_library_path
: OneThread
<RefCell
<Option
<Option
<PathBuf
>>>>,
205 /// Tracks the current behavior of the CTFE engine when an error occurs.
206 /// Options range from returning the error without a backtrace to returning an error
207 /// and immediately printing the backtrace to stderr.
208 pub ctfe_backtrace
: Lock
<CtfeBacktrace
>,
210 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
211 /// const check, optionally with the relevant feature gate. We use this to
212 /// warn about unleashing, but with a single diagnostic instead of dozens that
213 /// drown everything else in noise.
214 miri_unleashed_features
: Lock
<Vec
<(Span
, Option
<Symbol
>)>>,
216 /// Architecture to use for interpreting asm!.
217 pub asm_arch
: Option
<InlineAsmArch
>,
219 /// Set of enabled features for the current target.
220 pub target_features
: FxHashSet
<Symbol
>,
222 known_attrs
: Lock
<MarkedAttrs
>,
223 used_attrs
: Lock
<MarkedAttrs
>,
225 /// `Span`s for `if` conditions that we have suggested turning into `if let`.
226 pub if_let_suggestions
: Lock
<FxHashSet
<Span
>>,
229 pub struct PerfStats
{
230 /// The accumulated time spent on computing symbol hashes.
231 pub symbol_hash_time
: Lock
<Duration
>,
232 /// Total number of values canonicalized queries constructed.
233 pub queries_canonicalized
: AtomicUsize
,
234 /// Number of times this query is invoked.
235 pub normalize_generic_arg_after_erasing_regions
: AtomicUsize
,
236 /// Number of times this query is invoked.
237 pub normalize_projection_ty
: AtomicUsize
,
240 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
241 enum DiagnosticBuilderMethod
{
244 // Add more variants as needed to support one-time diagnostics.
247 /// Trait implemented by error types. This should not be implemented manually. Instead, use
248 /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic].
249 pub trait SessionDiagnostic
<'a
> {
250 /// Write out as a diagnostic out of `sess`.
252 fn into_diagnostic(self, sess
: &'a Session
) -> DiagnosticBuilder
<'a
>;
255 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
256 /// emitting the same message more than once.
257 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
258 pub enum DiagnosticMessageId
{
259 ErrorId(u16), // EXXXX error code as integer
260 LintId(lint
::LintId
),
261 StabilityId(Option
<NonZeroU32
>), // issue number
264 impl From
<&'
static lint
::Lint
> for DiagnosticMessageId
{
265 fn from(lint
: &'
static lint
::Lint
) -> Self {
266 DiagnosticMessageId
::LintId(lint
::LintId
::of(lint
))
271 pub fn miri_unleashed_feature(&self, span
: Span
, feature_gate
: Option
<Symbol
>) {
272 self.miri_unleashed_features
.lock().push((span
, feature_gate
));
275 fn check_miri_unleashed_features(&self) {
276 let unleashed_features
= self.miri_unleashed_features
.lock();
277 if !unleashed_features
.is_empty() {
278 let mut must_err
= false;
279 // Create a diagnostic pointing at where things got unleashed.
280 let mut diag
= self.struct_warn("skipping const checks");
281 for &(span
, feature_gate
) in unleashed_features
.iter() {
282 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
283 if let Some(feature_gate
) = feature_gate
{
284 diag
.span_help(span
, &format
!("skipping check for `{}` feature", feature_gate
));
285 // The unleash flag must *not* be used to just "hack around" feature gates.
288 diag
.span_help(span
, "skipping check that does not even have a feature gate");
292 // If we should err, make sure we did.
293 if must_err
&& !self.has_errors() {
294 // We have skipped a feature gate, and not run into other errors... reject.
296 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
297 gates, except when testing error paths in the CTFE engine",
303 /// Invoked all the way at the end to finish off diagnostics printing.
304 pub fn finish_diagnostics(&self, registry
: &Registry
) {
305 self.check_miri_unleashed_features();
306 self.diagnostic().print_error_count(registry
);
307 self.emit_future_breakage();
310 fn emit_future_breakage(&self) {
311 if !self.opts
.debugging_opts
.emit_future_incompat_report
{
315 let diags
= self.diagnostic().take_future_breakage_diagnostics();
316 if diags
.is_empty() {
319 // If any future-breakage lints were registered, this lint store
320 // should be available
321 let lint_store
= self.lint_store
.get().expect("`lint_store` not initialized!");
322 let diags_and_breakage
: Vec
<(FutureBreakage
, Diagnostic
)> = diags
325 let lint_name
= match &diag
.code
{
326 Some(DiagnosticId
::Lint { name, has_future_breakage: true }
) => name
,
327 _
=> panic
!("Unexpected code in diagnostic {:?}", diag
),
329 let lint
= lint_store
.name_to_lint(&lint_name
);
330 let future_breakage
=
331 lint
.lint
.future_incompatible
.unwrap().future_breakage
.unwrap();
332 (future_breakage
, diag
)
335 self.parse_sess
.span_diagnostic
.emit_future_breakage_report(diags_and_breakage
);
338 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator
{
339 self.crate_disambiguator
.get().copied().unwrap()
342 pub fn crate_types(&self) -> &[CrateType
] {
343 self.crate_types
.get().unwrap().as_slice()
346 pub fn init_crate_types(&self, crate_types
: Vec
<CrateType
>) {
347 self.crate_types
.set(crate_types
).expect("`crate_types` was initialized twice")
351 pub fn recursion_limit(&self) -> Limit
{
352 self.recursion_limit
.get().copied().unwrap()
356 pub fn move_size_limit(&self) -> usize {
357 self.move_size_limit
.get().copied().unwrap()
361 pub fn type_length_limit(&self) -> Limit
{
362 self.type_length_limit
.get().copied().unwrap()
365 pub fn const_eval_limit(&self) -> Limit
{
366 self.const_eval_limit
.get().copied().unwrap()
369 pub fn struct_span_warn
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> DiagnosticBuilder
<'_
> {
370 self.diagnostic().struct_span_warn(sp
, msg
)
372 pub fn struct_span_warn_with_code
<S
: Into
<MultiSpan
>>(
377 ) -> DiagnosticBuilder
<'_
> {
378 self.diagnostic().struct_span_warn_with_code(sp
, msg
, code
)
380 pub fn struct_warn(&self, msg
: &str) -> DiagnosticBuilder
<'_
> {
381 self.diagnostic().struct_warn(msg
)
383 pub fn struct_span_allow
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> DiagnosticBuilder
<'_
> {
384 self.diagnostic().struct_span_allow(sp
, msg
)
386 pub fn struct_allow(&self, msg
: &str) -> DiagnosticBuilder
<'_
> {
387 self.diagnostic().struct_allow(msg
)
389 pub fn struct_span_err
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> DiagnosticBuilder
<'_
> {
390 self.diagnostic().struct_span_err(sp
, msg
)
392 pub fn struct_span_err_with_code
<S
: Into
<MultiSpan
>>(
397 ) -> DiagnosticBuilder
<'_
> {
398 self.diagnostic().struct_span_err_with_code(sp
, msg
, code
)
400 // FIXME: This method should be removed (every error should have an associated error code).
401 pub fn struct_err(&self, msg
: &str) -> DiagnosticBuilder
<'_
> {
402 self.diagnostic().struct_err(msg
)
404 pub fn struct_err_with_code(&self, msg
: &str, code
: DiagnosticId
) -> DiagnosticBuilder
<'_
> {
405 self.diagnostic().struct_err_with_code(msg
, code
)
407 pub fn struct_span_fatal
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> DiagnosticBuilder
<'_
> {
408 self.diagnostic().struct_span_fatal(sp
, msg
)
410 pub fn struct_span_fatal_with_code
<S
: Into
<MultiSpan
>>(
415 ) -> DiagnosticBuilder
<'_
> {
416 self.diagnostic().struct_span_fatal_with_code(sp
, msg
, code
)
418 pub fn struct_fatal(&self, msg
: &str) -> DiagnosticBuilder
<'_
> {
419 self.diagnostic().struct_fatal(msg
)
422 pub fn span_fatal
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> ! {
423 self.diagnostic().span_fatal(sp
, msg
)
425 pub fn span_fatal_with_code
<S
: Into
<MultiSpan
>>(
431 self.diagnostic().span_fatal_with_code(sp
, msg
, code
)
433 pub fn fatal(&self, msg
: &str) -> ! {
434 self.diagnostic().fatal(msg
).raise()
436 pub fn span_err_or_warn
<S
: Into
<MultiSpan
>>(&self, is_warning
: bool
, sp
: S
, msg
: &str) {
438 self.span_warn(sp
, msg
);
440 self.span_err(sp
, msg
);
443 pub fn span_err
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
444 self.diagnostic().span_err(sp
, msg
)
446 pub fn span_err_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: DiagnosticId
) {
447 self.diagnostic().span_err_with_code(sp
, &msg
, code
)
449 pub fn err(&self, msg
: &str) {
450 self.diagnostic().err(msg
)
452 pub fn emit_err
<'a
>(&'a
self, err
: impl SessionDiagnostic
<'a
>) {
453 err
.into_diagnostic(self).emit()
456 pub fn err_count(&self) -> usize {
457 self.diagnostic().err_count()
459 pub fn has_errors(&self) -> bool
{
460 self.diagnostic().has_errors()
462 pub fn has_errors_or_delayed_span_bugs(&self) -> bool
{
463 self.diagnostic().has_errors_or_delayed_span_bugs()
465 pub fn abort_if_errors(&self) {
466 self.diagnostic().abort_if_errors();
468 pub fn compile_status(&self) -> Result
<(), ErrorReported
> {
469 if self.has_errors() {
470 self.diagnostic().emit_stashed_diagnostics();
476 // FIXME(matthewjasper) Remove this method, it should never be needed.
477 pub fn track_errors
<F
, T
>(&self, f
: F
) -> Result
<T
, ErrorReported
>
481 let old_count
= self.err_count();
483 let errors
= self.err_count() - old_count
;
484 if errors
== 0 { Ok(result) }
else { Err(ErrorReported) }
486 pub fn span_warn
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
487 self.diagnostic().span_warn(sp
, msg
)
489 pub fn span_warn_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: DiagnosticId
) {
490 self.diagnostic().span_warn_with_code(sp
, msg
, code
)
492 pub fn warn(&self, msg
: &str) {
493 self.diagnostic().warn(msg
)
495 /// Delay a span_bug() call until abort_if_errors()
497 pub fn delay_span_bug
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
498 self.diagnostic().delay_span_bug(sp
, msg
)
501 /// Used for code paths of expensive computations that should only take place when
502 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
503 /// it's likely a bug.
504 pub fn delay_good_path_bug(&self, msg
: &str) {
505 if self.opts
.debugging_opts
.print_type_sizes
506 || self.opts
.debugging_opts
.query_dep_graph
507 || self.opts
.debugging_opts
.dump_mir
.is_some()
508 || self.opts
.debugging_opts
.unpretty
.is_some()
509 || self.opts
.output_types
.contains_key(&OutputType
::Mir
)
510 || std
::env
::var_os("RUSTC_LOG").is_some()
515 self.diagnostic().delay_good_path_bug(msg
)
518 pub fn note_without_error(&self, msg
: &str) {
519 self.diagnostic().note_without_error(msg
)
521 pub fn span_note_without_error
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
522 self.diagnostic().span_note_without_error(sp
, msg
)
524 pub fn struct_note_without_error(&self, msg
: &str) -> DiagnosticBuilder
<'_
> {
525 self.diagnostic().struct_note_without_error(msg
)
529 pub fn diagnostic(&self) -> &rustc_errors
::Handler
{
530 &self.parse_sess
.span_diagnostic
533 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
534 /// deduplicates on lint ID, span (if any), and message for this `Session`
535 fn diag_once
<'a
, 'b
>(
537 diag_builder
: &'b
mut DiagnosticBuilder
<'a
>,
538 method
: DiagnosticBuilderMethod
,
539 msg_id
: DiagnosticMessageId
,
541 span_maybe
: Option
<Span
>,
543 let id_span_message
= (msg_id
, span_maybe
, message
.to_owned());
544 let fresh
= self.one_time_diagnostics
.borrow_mut().insert(id_span_message
);
547 DiagnosticBuilderMethod
::Note
=> {
548 diag_builder
.note(message
);
550 DiagnosticBuilderMethod
::SpanNote
=> {
551 let span
= span_maybe
.expect("`span_note` needs a span");
552 diag_builder
.span_note(span
, message
);
558 pub fn diag_span_note_once
<'a
, 'b
>(
560 diag_builder
: &'b
mut DiagnosticBuilder
<'a
>,
561 msg_id
: DiagnosticMessageId
,
567 DiagnosticBuilderMethod
::SpanNote
,
574 pub fn diag_note_once
<'a
, 'b
>(
576 diag_builder
: &'b
mut DiagnosticBuilder
<'a
>,
577 msg_id
: DiagnosticMessageId
,
580 self.diag_once(diag_builder
, DiagnosticBuilderMethod
::Note
, msg_id
, message
, None
);
584 pub fn source_map(&self) -> &SourceMap
{
585 self.parse_sess
.source_map()
587 pub fn verbose(&self) -> bool
{
588 self.opts
.debugging_opts
.verbose
590 pub fn time_passes(&self) -> bool
{
591 self.opts
.debugging_opts
.time_passes
|| self.opts
.debugging_opts
.time
593 pub fn instrument_mcount(&self) -> bool
{
594 self.opts
.debugging_opts
.instrument_mcount
596 pub fn time_llvm_passes(&self) -> bool
{
597 self.opts
.debugging_opts
.time_llvm_passes
599 pub fn meta_stats(&self) -> bool
{
600 self.opts
.debugging_opts
.meta_stats
602 pub fn asm_comments(&self) -> bool
{
603 self.opts
.debugging_opts
.asm_comments
605 pub fn verify_llvm_ir(&self) -> bool
{
606 self.opts
.debugging_opts
.verify_llvm_ir
|| option_env
!("RUSTC_VERIFY_LLVM_IR").is_some()
608 pub fn print_llvm_passes(&self) -> bool
{
609 self.opts
.debugging_opts
.print_llvm_passes
611 pub fn binary_dep_depinfo(&self) -> bool
{
612 self.opts
.debugging_opts
.binary_dep_depinfo
614 pub fn mir_opt_level(&self) -> usize {
618 .unwrap_or_else(|| if self.opts
.optimize
!= config
::OptLevel
::No { 2 }
else { 1 }
)
621 /// Gets the features enabled for the current compilation session.
622 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
623 /// dependency tracking. Use tcx.features() instead.
625 pub fn features_untracked(&self) -> &rustc_feature
::Features
{
626 self.features
.get().unwrap()
629 pub fn init_features(&self, features
: rustc_feature
::Features
) {
630 match self.features
.set(features
) {
632 Err(_
) => panic
!("`features` was initialized twice"),
636 pub fn init_lint_store(&self, lint_store
: Lrc
<dyn SessionLintStore
>) {
640 .expect("`lint_store` was initialized twice");
643 /// Calculates the flavor of LTO to use for this compilation.
644 pub fn lto(&self) -> config
::Lto
{
645 // If our target has codegen requirements ignore the command line
646 if self.target
.requires_lto
{
647 return config
::Lto
::Fat
;
650 // If the user specified something, return that. If they only said `-C
651 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
652 // then ensure we can't use a ThinLTO.
653 match self.opts
.cg
.lto
{
654 config
::LtoCli
::Unspecified
=> {
655 // The compiler was invoked without the `-Clto` flag. Fall
656 // through to the default handling
658 config
::LtoCli
::No
=> {
659 // The user explicitly opted out of any kind of LTO
660 return config
::Lto
::No
;
662 config
::LtoCli
::Yes
| config
::LtoCli
::Fat
| config
::LtoCli
::NoParam
=> {
663 // All of these mean fat LTO
664 return config
::Lto
::Fat
;
666 config
::LtoCli
::Thin
=> {
667 return if self.opts
.cli_forced_thinlto_off
{
675 // Ok at this point the target doesn't require anything and the user
676 // hasn't asked for anything. Our next decision is whether or not
677 // we enable "auto" ThinLTO where we use multiple codegen units and
678 // then do ThinLTO over those codegen units. The logic below will
679 // either return `No` or `ThinLocal`.
681 // If processing command line options determined that we're incompatible
682 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
683 if self.opts
.cli_forced_thinlto_off
{
684 return config
::Lto
::No
;
687 // If `-Z thinlto` specified process that, but note that this is mostly
688 // a deprecated option now that `-C lto=thin` exists.
689 if let Some(enabled
) = self.opts
.debugging_opts
.thinlto
{
691 return config
::Lto
::ThinLocal
;
693 return config
::Lto
::No
;
697 // If there's only one codegen unit and LTO isn't enabled then there's
698 // no need for ThinLTO so just return false.
699 if self.codegen_units() == 1 {
700 return config
::Lto
::No
;
703 // Now we're in "defaults" territory. By default we enable ThinLTO for
704 // optimized compiles (anything greater than O0).
705 match self.opts
.optimize
{
706 config
::OptLevel
::No
=> config
::Lto
::No
,
707 _
=> config
::Lto
::ThinLocal
,
711 /// Returns the panic strategy for this compile session. If the user explicitly selected one
712 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
713 pub fn panic_strategy(&self) -> PanicStrategy
{
714 self.opts
.cg
.panic
.unwrap_or(self.target
.panic_strategy
)
716 pub fn fewer_names(&self) -> bool
{
717 if let Some(fewer_names
) = self.opts
.debugging_opts
.fewer_names
{
720 let more_names
= self.opts
.output_types
.contains_key(&OutputType
::LlvmAssembly
)
721 || self.opts
.output_types
.contains_key(&OutputType
::Bitcode
)
722 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
723 || self.opts
.debugging_opts
.sanitizer
.intersects(SanitizerSet
::ADDRESS
| SanitizerSet
::MEMORY
);
728 pub fn unstable_options(&self) -> bool
{
729 self.opts
.debugging_opts
.unstable_options
731 pub fn is_nightly_build(&self) -> bool
{
732 self.opts
.unstable_features
.is_nightly_build()
734 pub fn overflow_checks(&self) -> bool
{
738 .or(self.opts
.debugging_opts
.force_overflow_checks
)
739 .unwrap_or(self.opts
.debug_assertions
)
742 /// Check whether this compile session and crate type use static crt.
743 pub fn crt_static(&self, crate_type
: Option
<CrateType
>) -> bool
{
744 if !self.target
.crt_static_respected
{
745 // If the target does not opt in to crt-static support, use its default.
746 return self.target
.crt_static_default
;
749 let requested_features
= self.opts
.cg
.target_feature
.split('
,'
);
750 let found_negative
= requested_features
.clone().any(|r
| r
== "-crt-static");
751 let found_positive
= requested_features
.clone().any(|r
| r
== "+crt-static");
753 if found_positive
|| found_negative
{
755 } else if crate_type
== Some(CrateType
::ProcMacro
)
756 || crate_type
== None
&& self.opts
.crate_types
.contains(&CrateType
::ProcMacro
)
758 // FIXME: When crate_type is not available,
759 // we use compiler options to determine the crate_type.
760 // We can't check `#![crate_type = "proc-macro"]` here.
763 self.target
.crt_static_default
767 pub fn relocation_model(&self) -> RelocModel
{
768 self.opts
.cg
.relocation_model
.unwrap_or(self.target
.relocation_model
)
771 pub fn code_model(&self) -> Option
<CodeModel
> {
772 self.opts
.cg
.code_model
.or(self.target
.code_model
)
775 pub fn tls_model(&self) -> TlsModel
{
776 self.opts
.debugging_opts
.tls_model
.unwrap_or(self.target
.tls_model
)
779 pub fn is_wasi_reactor(&self) -> bool
{
780 self.target
.options
.os
== "wasi"
782 self.opts
.debugging_opts
.wasi_exec_model
,
783 Some(config
::WasiExecModel
::Reactor
)
787 pub fn split_debuginfo(&self) -> SplitDebuginfo
{
788 self.opts
.cg
.split_debuginfo
.unwrap_or(self.target
.split_debuginfo
)
791 pub fn target_can_use_split_dwarf(&self) -> bool
{
792 !self.target
.is_like_windows
&& !self.target
.is_like_osx
795 pub fn must_not_eliminate_frame_pointers(&self) -> bool
{
796 // "mcount" function relies on stack pointer.
797 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
798 if self.instrument_mcount() {
800 } else if let Some(x
) = self.opts
.cg
.force_frame_pointers
{
803 !self.target
.eliminate_frame_pointer
807 pub fn must_emit_unwind_tables(&self) -> bool
{
808 // This is used to control the emission of the `uwtable` attribute on
811 // Unwind tables are needed when compiling with `-C panic=unwind`, but
812 // LLVM won't omit unwind tables unless the function is also marked as
813 // `nounwind`, so users are allowed to disable `uwtable` emission.
814 // Historically rustc always emits `uwtable` attributes by default, so
815 // even they can be disabled, they're still emitted by default.
817 // On some targets (including windows), however, exceptions include
818 // other events such as illegal instructions, segfaults, etc. This means
819 // that on Windows we end up still needing unwind tables even if the `-C
820 // panic=abort` flag is passed.
822 // You can also find more info on why Windows needs unwind tables in:
823 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
825 // If a target requires unwind tables, then they must be emitted.
826 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
827 // value, if it is provided, or disable them, if not.
828 self.target
.requires_uwtable
829 || self.opts
.cg
.force_unwind_tables
.unwrap_or(
830 self.panic_strategy() == PanicStrategy
::Unwind
|| self.target
.default_uwtable
,
834 /// Returns the symbol name for the registrar function,
835 /// given the crate `Svh` and the function `DefIndex`.
836 pub fn generate_plugin_registrar_symbol(&self, disambiguator
: CrateDisambiguator
) -> String
{
837 format
!("__rustc_plugin_registrar_{}__", disambiguator
.to_fingerprint().to_hex())
840 pub fn generate_proc_macro_decls_symbol(&self, disambiguator
: CrateDisambiguator
) -> String
{
841 format
!("__rustc_proc_macro_decls_{}__", disambiguator
.to_fingerprint().to_hex())
844 pub fn target_filesearch(&self, kind
: PathKind
) -> filesearch
::FileSearch
<'_
> {
845 filesearch
::FileSearch
::new(
847 self.opts
.target_triple
.triple(),
848 &self.opts
.search_paths
,
849 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
850 self.target_tlib_path
.as_ref().unwrap_or(&self.host_tlib_path
),
854 pub fn host_filesearch(&self, kind
: PathKind
) -> filesearch
::FileSearch
<'_
> {
855 filesearch
::FileSearch
::new(
857 config
::host_triple(),
858 &self.opts
.search_paths
,
859 &self.host_tlib_path
,
864 pub fn init_incr_comp_session(
866 session_dir
: PathBuf
,
867 lock_file
: flock
::Lock
,
868 load_dep_graph
: bool
,
870 let mut incr_comp_session
= self.incr_comp_session
.borrow_mut();
872 if let IncrCompSession
::NotInitialized
= *incr_comp_session
{
874 panic
!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session
)
878 IncrCompSession
::Active { session_directory: session_dir, lock_file, load_dep_graph }
;
881 pub fn finalize_incr_comp_session(&self, new_directory_path
: PathBuf
) {
882 let mut incr_comp_session
= self.incr_comp_session
.borrow_mut();
884 if let IncrCompSession
::Active { .. }
= *incr_comp_session
{
886 panic
!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session
);
889 // Note: this will also drop the lock file, thus unlocking the directory.
890 *incr_comp_session
= IncrCompSession
::Finalized { session_directory: new_directory_path }
;
893 pub fn mark_incr_comp_session_as_invalid(&self) {
894 let mut incr_comp_session
= self.incr_comp_session
.borrow_mut();
896 let session_directory
= match *incr_comp_session
{
897 IncrCompSession
::Active { ref session_directory, .. }
=> session_directory
.clone(),
898 IncrCompSession
::InvalidBecauseOfErrors { .. }
=> return,
899 _
=> panic
!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session
),
902 // Note: this will also drop the lock file, thus unlocking the directory.
903 *incr_comp_session
= IncrCompSession
::InvalidBecauseOfErrors { session_directory }
;
906 pub fn incr_comp_session_dir(&self) -> cell
::Ref
<'_
, PathBuf
> {
907 let incr_comp_session
= self.incr_comp_session
.borrow();
908 cell
::Ref
::map(incr_comp_session
, |incr_comp_session
| match *incr_comp_session
{
909 IncrCompSession
::NotInitialized
=> panic
!(
910 "trying to get session directory from `IncrCompSession`: {:?}",
913 IncrCompSession
::Active { ref session_directory, .. }
914 | IncrCompSession
::Finalized { ref session_directory }
915 | IncrCompSession
::InvalidBecauseOfErrors { ref session_directory }
=> {
921 pub fn incr_comp_session_dir_opt(&self) -> Option
<cell
::Ref
<'_
, PathBuf
>> {
922 self.opts
.incremental
.as_ref().map(|_
| self.incr_comp_session_dir())
925 pub fn print_perf_stats(&self) {
927 "Total time spent computing symbol hashes: {}",
928 duration_to_secs_str(*self.perf_stats
.symbol_hash_time
.lock())
931 "Total queries canonicalized: {}",
932 self.perf_stats
.queries_canonicalized
.load(Ordering
::Relaxed
)
935 "normalize_generic_arg_after_erasing_regions: {}",
936 self.perf_stats
.normalize_generic_arg_after_erasing_regions
.load(Ordering
::Relaxed
)
939 "normalize_projection_ty: {}",
940 self.perf_stats
.normalize_projection_ty
.load(Ordering
::Relaxed
)
944 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
945 /// This expends fuel if applicable, and records fuel if applicable.
946 pub fn consider_optimizing
<T
: Fn() -> String
>(&self, crate_name
: &str, msg
: T
) -> bool
{
948 if let Some(ref c
) = self.optimization_fuel_crate
{
950 assert_eq
!(self.threads(), 1);
951 let mut fuel
= self.optimization_fuel
.lock();
952 ret
= fuel
.remaining
!= 0;
953 if fuel
.remaining
== 0 && !fuel
.out_of_fuel
{
954 self.warn(&format
!("optimization-fuel-exhausted: {}", msg()));
955 fuel
.out_of_fuel
= true;
956 } else if fuel
.remaining
> 0 {
961 if let Some(ref c
) = self.print_fuel_crate
{
963 assert_eq
!(self.threads(), 1);
964 self.print_fuel
.fetch_add(1, SeqCst
);
970 /// Returns the number of query threads that should be used for this
972 pub fn threads(&self) -> usize {
973 self.opts
.debugging_opts
.threads
976 /// Returns the number of codegen units that should be used for this
978 pub fn codegen_units(&self) -> usize {
979 if let Some(n
) = self.opts
.cli_forced_codegen_units
{
982 if let Some(n
) = self.target
.default_codegen_units
{
986 // If incremental compilation is turned on, we default to a high number
987 // codegen units in order to reduce the "collateral damage" small
989 if self.opts
.incremental
.is_some() {
993 // Why is 16 codegen units the default all the time?
995 // The main reason for enabling multiple codegen units by default is to
996 // leverage the ability for the codegen backend to do codegen and
997 // optimization in parallel. This allows us, especially for large crates, to
998 // make good use of all available resources on the machine once we've
999 // hit that stage of compilation. Large crates especially then often
1000 // take a long time in codegen/optimization and this helps us amortize that
1003 // Note that a high number here doesn't mean that we'll be spawning a
1004 // large number of threads in parallel. The backend of rustc contains
1005 // global rate limiting through the `jobserver` crate so we'll never
1006 // overload the system with too much work, but rather we'll only be
1007 // optimizing when we're otherwise cooperating with other instances of
1010 // Rather a high number here means that we should be able to keep a lot
1011 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1012 // to build we'll be guaranteed that all cpus will finish pretty closely
1013 // to one another and we should make relatively optimal use of system
1016 // Note that the main cost of codegen units is that it prevents LLVM
1017 // from inlining across codegen units. Users in general don't have a lot
1018 // of control over how codegen units are split up so it's our job in the
1019 // compiler to ensure that undue performance isn't lost when using
1020 // codegen units (aka we can't require everyone to slap `#[inline]` on
1023 // If we're compiling at `-O0` then the number doesn't really matter too
1024 // much because performance doesn't matter and inlining is ok to lose.
1025 // In debug mode we just want to try to guarantee that no cpu is stuck
1026 // doing work that could otherwise be farmed to others.
1028 // In release mode, however (O1 and above) performance does indeed
1029 // matter! To recover the loss in performance due to inlining we'll be
1030 // enabling ThinLTO by default (the function for which is just below).
1031 // This will ensure that we recover any inlining wins we otherwise lost
1032 // through codegen unit partitioning.
1036 // Ok that's a lot of words but the basic tl;dr; is that we want a high
1037 // number here -- but not too high. Additionally we're "safe" to have it
1038 // always at the same number at all optimization levels.
1040 // As a result 16 was chosen here! Mostly because it was a power of 2
1041 // and most benchmarks agreed it was roughly a local optimum. Not very
1046 pub fn teach(&self, code
: &DiagnosticId
) -> bool
{
1047 self.opts
.debugging_opts
.teach
&& self.diagnostic().must_teach(code
)
1050 pub fn rust_2015(&self) -> bool
{
1051 self.opts
.edition
== Edition
::Edition2015
1054 /// Are we allowed to use features from the Rust 2018 edition?
1055 pub fn rust_2018(&self) -> bool
{
1056 self.opts
.edition
>= Edition
::Edition2018
1059 /// Are we allowed to use features from the Rust 2021 edition?
1060 pub fn rust_2021(&self) -> bool
{
1061 self.opts
.edition
>= Edition
::Edition2021
1064 pub fn edition(&self) -> Edition
{
1068 /// Returns `true` if we cannot skip the PLT for shared library calls.
1069 pub fn needs_plt(&self) -> bool
{
1070 // Check if the current target usually needs PLT to be enabled.
1071 // The user can use the command line flag to override it.
1072 let needs_plt
= self.target
.needs_plt
;
1074 let dbg_opts
= &self.opts
.debugging_opts
;
1076 let relro_level
= dbg_opts
.relro_level
.unwrap_or(self.target
.relro_level
);
1078 // Only enable this optimization by default if full relro is also enabled.
1079 // In this case, lazy binding was already unavailable, so nothing is lost.
1080 // This also ensures `-Wl,-z,now` is supported by the linker.
1081 let full_relro
= RelroLevel
::Full
== relro_level
;
1083 // If user didn't explicitly forced us to use / skip the PLT,
1084 // then try to skip it where possible.
1085 dbg_opts
.plt
.unwrap_or(needs_plt
|| !full_relro
)
1088 /// Checks if LLVM lifetime markers should be emitted.
1089 pub fn emit_lifetime_markers(&self) -> bool
{
1090 self.opts
.optimize
!= config
::OptLevel
::No
1091 // AddressSanitizer uses lifetimes to detect use after scope bugs.
1092 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1093 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
1094 || self.opts
.debugging_opts
.sanitizer
.intersects(SanitizerSet
::ADDRESS
| SanitizerSet
::MEMORY
| SanitizerSet
::HWADDRESS
)
1097 pub fn link_dead_code(&self) -> bool
{
1098 self.opts
.cg
.link_dead_code
.unwrap_or(false)
1101 pub fn instrument_coverage(&self) -> bool
{
1102 self.opts
.debugging_opts
.instrument_coverage
.unwrap_or(config
::InstrumentCoverage
::Off
)
1103 != config
::InstrumentCoverage
::Off
1106 pub fn instrument_coverage_except_unused_generics(&self) -> bool
{
1107 self.opts
.debugging_opts
.instrument_coverage
.unwrap_or(config
::InstrumentCoverage
::Off
)
1108 == config
::InstrumentCoverage
::ExceptUnusedGenerics
1111 pub fn instrument_coverage_except_unused_functions(&self) -> bool
{
1112 self.opts
.debugging_opts
.instrument_coverage
.unwrap_or(config
::InstrumentCoverage
::Off
)
1113 == config
::InstrumentCoverage
::ExceptUnusedFunctions
1116 pub fn mark_attr_known(&self, attr
: &Attribute
) {
1117 self.known_attrs
.lock().mark(attr
)
1120 pub fn is_attr_known(&self, attr
: &Attribute
) -> bool
{
1121 self.known_attrs
.lock().is_marked(attr
)
1124 pub fn mark_attr_used(&self, attr
: &Attribute
) {
1125 self.used_attrs
.lock().mark(attr
)
1128 pub fn is_attr_used(&self, attr
: &Attribute
) -> bool
{
1129 self.used_attrs
.lock().is_marked(attr
)
1132 /// Returns `true` if the attribute's path matches the argument. If it
1133 /// matches, then the attribute is marked as used.
1135 /// This method should only be used by rustc, other tools can use
1136 /// `Attribute::has_name` instead, because only rustc is supposed to report
1137 /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1138 /// produced by lowering an `Attribute` and don't have identity, so they
1139 /// only have the `has_name` method, and you need to mark the original
1140 /// `Attribute` as used when necessary.)
1141 pub fn check_name(&self, attr
: &Attribute
, name
: Symbol
) -> bool
{
1142 let matches
= attr
.has_name(name
);
1144 self.mark_attr_used(attr
);
1149 pub fn is_proc_macro_attr(&self, attr
: &Attribute
) -> bool
{
1150 [sym
::proc_macro
, sym
::proc_macro_attribute
, sym
::proc_macro_derive
]
1152 .any(|kind
| self.check_name(attr
, *kind
))
1155 pub fn contains_name(&self, attrs
: &[Attribute
], name
: Symbol
) -> bool
{
1156 attrs
.iter().any(|item
| self.check_name(item
, name
))
1159 pub fn find_by_name
<'a
>(
1161 attrs
: &'a
[Attribute
],
1163 ) -> Option
<&'a Attribute
> {
1164 attrs
.iter().find(|attr
| self.check_name(attr
, name
))
1167 pub fn filter_by_name
<'a
>(
1169 attrs
: &'a
[Attribute
],
1171 ) -> impl Iterator
<Item
= &'a Attribute
> {
1172 attrs
.iter().filter(move |attr
| self.check_name(attr
, name
))
1175 pub fn first_attr_value_str_by_name(
1177 attrs
: &[Attribute
],
1179 ) -> Option
<Symbol
> {
1180 attrs
.iter().find(|at
| self.check_name(at
, name
)).and_then(|at
| at
.value_str())
1185 sopts
: &config
::Options
,
1186 registry
: rustc_errors
::registry
::Registry
,
1187 source_map
: Lrc
<SourceMap
>,
1188 emitter_dest
: Option
<Box
<dyn Write
+ Send
>>,
1189 ) -> Box
<dyn Emitter
+ sync
::Send
> {
1190 let macro_backtrace
= sopts
.debugging_opts
.macro_backtrace
;
1191 match (sopts
.error_format
, emitter_dest
) {
1192 (config
::ErrorOutputType
::HumanReadable(kind
), dst
) => {
1193 let (short
, color_config
) = kind
.unzip();
1195 if let HumanReadableErrorType
::AnnotateSnippet(_
) = kind
{
1197 AnnotateSnippetEmitterWriter
::new(Some(source_map
), short
, macro_backtrace
);
1198 Box
::new(emitter
.ui_testing(sopts
.debugging_opts
.ui_testing
))
1200 let emitter
= match dst
{
1201 None
=> EmitterWriter
::stderr(
1205 sopts
.debugging_opts
.teach
,
1206 sopts
.debugging_opts
.terminal_width
,
1209 Some(dst
) => EmitterWriter
::new(
1213 false, // no teach messages when writing to a buffer
1214 false, // no colors when writing to a buffer
1215 None
, // no terminal width
1219 Box
::new(emitter
.ui_testing(sopts
.debugging_opts
.ui_testing
))
1222 (config
::ErrorOutputType
::Json { pretty, json_rendered }
, None
) => Box
::new(
1223 JsonEmitter
::stderr(
1228 sopts
.debugging_opts
.terminal_width
,
1231 .ui_testing(sopts
.debugging_opts
.ui_testing
),
1233 (config
::ErrorOutputType
::Json { pretty, json_rendered }
, Some(dst
)) => Box
::new(
1240 sopts
.debugging_opts
.terminal_width
,
1243 .ui_testing(sopts
.debugging_opts
.ui_testing
),
1248 pub enum DiagnosticOutput
{
1250 Raw(Box
<dyn Write
+ Send
>),
1253 pub fn build_session(
1254 sopts
: config
::Options
,
1255 local_crate_source_file
: Option
<PathBuf
>,
1256 registry
: rustc_errors
::registry
::Registry
,
1257 diagnostics_output
: DiagnosticOutput
,
1258 driver_lint_caps
: FxHashMap
<lint
::LintId
, lint
::Level
>,
1259 file_loader
: Option
<Box
<dyn FileLoader
+ Send
+ Sync
+ '
static>>,
1260 target_override
: Option
<Target
>,
1262 // FIXME: This is not general enough to make the warning lint completely override
1263 // normal diagnostic warnings, since the warning lint can also be denied and changed
1264 // later via the source code.
1265 let warnings_allow
= sopts
1268 .filter(|&&(ref key
, _
)| *key
== "warnings")
1269 .map(|&(_
, ref level
)| *level
== lint
::Allow
)
1272 let cap_lints_allow
= sopts
.lint_cap
.map_or(false, |cap
| cap
== lint
::Allow
);
1273 let can_emit_warnings
= !(warnings_allow
|| cap_lints_allow
);
1275 let write_dest
= match diagnostics_output
{
1276 DiagnosticOutput
::Default
=> None
,
1277 DiagnosticOutput
::Raw(write
) => Some(write
),
1280 let sysroot
= match &sopts
.maybe_sysroot
{
1281 Some(sysroot
) => sysroot
.clone(),
1282 None
=> filesearch
::get_or_default_sysroot(),
1285 let target_cfg
= config
::build_target_config(&sopts
, target_override
, &sysroot
);
1286 let host_triple
= TargetTriple
::from_triple(config
::host_triple());
1287 let host
= Target
::search(&host_triple
, &sysroot
).unwrap_or_else(|e
| {
1288 early_error(sopts
.error_format
, &format
!("Error loading host specification: {}", e
))
1291 let loader
= file_loader
.unwrap_or_else(|| Box
::new(RealFileLoader
));
1292 let hash_kind
= sopts
.debugging_opts
.src_hash_algorithm
.unwrap_or_else(|| {
1293 if target_cfg
.is_like_msvc
{
1294 SourceFileHashAlgorithm
::Sha1
1296 SourceFileHashAlgorithm
::Md5
1299 let source_map
= Lrc
::new(SourceMap
::with_file_loader_and_hash_kind(
1301 sopts
.file_path_mapping(),
1304 let emitter
= default_emitter(&sopts
, registry
, source_map
.clone(), write_dest
);
1306 let span_diagnostic
= rustc_errors
::Handler
::with_emitter_and_flags(
1308 sopts
.debugging_opts
.diagnostic_handler_flags(can_emit_warnings
),
1311 let self_profiler
= if let SwitchWithOptPath
::Enabled(ref d
) = sopts
.debugging_opts
.self_profile
1314 if let Some(ref directory
) = d { directory }
else { std::path::Path::new(".") }
;
1316 let profiler
= SelfProfiler
::new(
1318 sopts
.crate_name
.as_deref(),
1319 &sopts
.debugging_opts
.self_profile_events
,
1322 Ok(profiler
) => Some(Arc
::new(profiler
)),
1324 early_warn(sopts
.error_format
, &format
!("failed to create profiler: {}", e
));
1332 let mut parse_sess
= ParseSess
::with_span_handler(span_diagnostic
, source_map
);
1333 parse_sess
.assume_incomplete_release
= sopts
.debugging_opts
.assume_incomplete_release
;
1335 let host_triple
= config
::host_triple();
1336 let target_triple
= sopts
.target_triple
.triple();
1337 let host_tlib_path
= SearchPath
::from_sysroot_and_triple(&sysroot
, host_triple
);
1338 let target_tlib_path
= if host_triple
== target_triple
{
1341 Some(SearchPath
::from_sysroot_and_triple(&sysroot
, target_triple
))
1344 let file_path_mapping
= sopts
.file_path_mapping();
1346 let local_crate_source_file
=
1347 local_crate_source_file
.map(|path
| file_path_mapping
.map_prefix(path
).0);
1349 let optimization_fuel_crate
= sopts
.debugging_opts
.fuel
.as_ref().map(|i
| i
.0.clone());
1350 let optimization_fuel
= Lock
::new(OptimizationFuel
{
1351 remaining
: sopts
.debugging_opts
.fuel
.as_ref().map_or(0, |i
| i
.1),
1354 let print_fuel_crate
= sopts
.debugging_opts
.print_fuel
.clone();
1355 let print_fuel
= AtomicU64
::new(0);
1357 let working_dir
= env
::current_dir().unwrap_or_else(|e
| {
1358 parse_sess
.span_diagnostic
.fatal(&format
!("Current directory is invalid: {}", e
)).raise()
1360 let (path
, remapped
) = file_path_mapping
.map_prefix(working_dir
.clone());
1361 let working_dir
= if remapped
{
1362 RealFileName
::Remapped { local_path: Some(working_dir), virtual_name: path }
1364 RealFileName
::LocalPath(path
)
1367 let cgu_reuse_tracker
= if sopts
.debugging_opts
.query_dep_graph
{
1368 CguReuseTracker
::new()
1370 CguReuseTracker
::new_disabled()
1373 let prof
= SelfProfilerRef
::new(
1375 sopts
.debugging_opts
.time_passes
|| sopts
.debugging_opts
.time
,
1376 sopts
.debugging_opts
.time_passes
,
1379 let ctfe_backtrace
= Lock
::new(match env
::var("RUSTC_CTFE_BACKTRACE") {
1380 Ok(ref val
) if val
== "immediate" => CtfeBacktrace
::Immediate
,
1381 Ok(ref val
) if val
!= "0" => CtfeBacktrace
::Capture
,
1382 _
=> CtfeBacktrace
::Disabled
,
1386 if target_cfg
.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() }
else { None }
;
1388 let sess
= Session
{
1396 local_crate_source_file
,
1398 one_time_diagnostics
: Default
::default(),
1399 crate_types
: OnceCell
::new(),
1400 crate_disambiguator
: OnceCell
::new(),
1401 features
: OnceCell
::new(),
1402 lint_store
: OnceCell
::new(),
1403 recursion_limit
: OnceCell
::new(),
1404 move_size_limit
: OnceCell
::new(),
1405 type_length_limit
: OnceCell
::new(),
1406 const_eval_limit
: OnceCell
::new(),
1407 incr_comp_session
: OneThread
::new(RefCell
::new(IncrCompSession
::NotInitialized
)),
1410 perf_stats
: PerfStats
{
1411 symbol_hash_time
: Lock
::new(Duration
::from_secs(0)),
1412 queries_canonicalized
: AtomicUsize
::new(0),
1413 normalize_generic_arg_after_erasing_regions
: AtomicUsize
::new(0),
1414 normalize_projection_ty
: AtomicUsize
::new(0),
1416 code_stats
: Default
::default(),
1417 optimization_fuel_crate
,
1421 jobserver
: jobserver
::client(),
1423 trait_methods_not_found
: Lock
::new(Default
::default()),
1424 confused_type_with_std_module
: Lock
::new(Default
::default()),
1425 system_library_path
: OneThread
::new(RefCell
::new(Default
::default())),
1427 miri_unleashed_features
: Lock
::new(Default
::default()),
1429 target_features
: FxHashSet
::default(),
1430 known_attrs
: Lock
::new(MarkedAttrs
::new()),
1431 used_attrs
: Lock
::new(MarkedAttrs
::new()),
1432 if_let_suggestions
: Default
::default(),
1435 validate_commandline_args_with_session_available(&sess
);
1440 // If it is useful to have a Session available already for validating a
1441 // commandline argument, you can do so here.
1442 fn validate_commandline_args_with_session_available(sess
: &Session
) {
1443 // Since we don't know if code in an rlib will be linked to statically or
1444 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1445 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1446 // these manually generated symbols confuse LLD when it tries to merge
1447 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1448 // when compiling for LLD ThinLTO. This way we can validly just not generate
1449 // the `dllimport` attributes and `__imp_` symbols in that case.
1450 if sess
.opts
.cg
.linker_plugin_lto
.enabled()
1451 && sess
.opts
.cg
.prefer_dynamic
1452 && sess
.target
.is_like_windows
1455 "Linker plugin based LTO is not supported together with \
1456 `-C prefer-dynamic` when targeting Windows-like targets",
1460 // Make sure that any given profiling data actually exists so LLVM can't
1461 // decide to silently skip PGO.
1462 if let Some(ref path
) = sess
.opts
.cg
.profile_use
{
1465 "File `{}` passed to `-C profile-use` does not exist.",
1471 // Unwind tables cannot be disabled if the target requires them.
1472 if let Some(include_uwtables
) = sess
.opts
.cg
.force_unwind_tables
{
1473 if sess
.target
.requires_uwtable
&& !include_uwtables
{
1475 "target requires unwind tables, they cannot be disabled with \
1476 `-C force-unwind-tables=no`.",
1481 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1482 // an error to combine the two for now. It always runs into an assertions
1483 // if LLVM is built with assertions, but without assertions it sometimes
1484 // does not crash and will probably generate a corrupted binary.
1485 // We should only display this error if we're actually going to run PGO.
1486 // If we're just supposed to print out some data, don't show the error (#61002).
1487 if sess
.opts
.cg
.profile_generate
.enabled()
1488 && sess
.target
.is_like_msvc
1489 && sess
.panic_strategy() == PanicStrategy
::Unwind
1490 && sess
.opts
.prints
.iter().all(|&p
| p
== PrintRequest
::NativeStaticLibs
)
1493 "Profile-guided optimization does not yet work in conjunction \
1494 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1495 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1496 for more information.",
1500 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1501 let supported_sanitizers
= sess
.target
.options
.supported_sanitizers
;
1502 let unsupported_sanitizers
= sess
.opts
.debugging_opts
.sanitizer
- supported_sanitizers
;
1503 match unsupported_sanitizers
.into_iter().count() {
1506 .err(&format
!("{} sanitizer is not supported for this target", unsupported_sanitizers
)),
1507 _
=> sess
.err(&format
!(
1508 "{} sanitizers are not supported for this target",
1509 unsupported_sanitizers
1512 // Cannot mix and match sanitizers.
1513 let mut sanitizer_iter
= sess
.opts
.debugging_opts
.sanitizer
.into_iter();
1514 if let (Some(first
), Some(second
)) = (sanitizer_iter
.next(), sanitizer_iter
.next()) {
1515 sess
.err(&format
!("`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`", first
, second
));
1518 // Cannot enable crt-static with sanitizers on Linux
1519 if sess
.crt_static(None
) && !sess
.opts
.debugging_opts
.sanitizer
.is_empty() {
1521 "Sanitizer is incompatible with statically linked libc, \
1522 disable it using `-C target-feature=-crt-static`",
1527 /// Holds data on the current incremental compilation session, if there is one.
1529 pub enum IncrCompSession
{
1530 /// This is the state the session will be in until the incr. comp. dir is
1533 /// This is the state during which the session directory is private and can
1535 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool }
,
1536 /// This is the state after the session directory has been finalized. In this
1537 /// state, the contents of the directory must not be modified any more.
1538 Finalized { session_directory: PathBuf }
,
1539 /// This is an error state that is reached when some compilation error has
1540 /// occurred. It indicates that the contents of the session directory must
1541 /// not be used, since they might be invalid.
1542 InvalidBecauseOfErrors { session_directory: PathBuf }
,
1545 pub fn early_error_no_abort(output
: config
::ErrorOutputType
, msg
: &str) {
1546 let emitter
: Box
<dyn Emitter
+ sync
::Send
> = match output
{
1547 config
::ErrorOutputType
::HumanReadable(kind
) => {
1548 let (short
, color_config
) = kind
.unzip();
1549 Box
::new(EmitterWriter
::stderr(color_config
, None
, short
, false, None
, false))
1551 config
::ErrorOutputType
::Json { pretty, json_rendered }
=> {
1552 Box
::new(JsonEmitter
::basic(pretty
, json_rendered
, None
, false))
1555 let handler
= rustc_errors
::Handler
::with_emitter(true, None
, emitter
);
1556 handler
.struct_fatal(msg
).emit();
1559 pub fn early_error(output
: config
::ErrorOutputType
, msg
: &str) -> ! {
1560 early_error_no_abort(output
, msg
);
1561 rustc_errors
::FatalError
.raise();
1564 pub fn early_warn(output
: config
::ErrorOutputType
, msg
: &str) {
1565 let emitter
: Box
<dyn Emitter
+ sync
::Send
> = match output
{
1566 config
::ErrorOutputType
::HumanReadable(kind
) => {
1567 let (short
, color_config
) = kind
.unzip();
1568 Box
::new(EmitterWriter
::stderr(color_config
, None
, short
, false, None
, false))
1570 config
::ErrorOutputType
::Json { pretty, json_rendered }
=> {
1571 Box
::new(JsonEmitter
::basic(pretty
, json_rendered
, None
, false))
1574 let handler
= rustc_errors
::Handler
::with_emitter(true, None
, emitter
);
1575 handler
.struct_warn(msg
).emit();