]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/session.rs
Rollup merge of #84406 - m-ou-se:drop-delete-alias, r=dtolnay
[rust.git] / compiler / rustc_session / src / session.rs
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};
5 use crate::filesearch;
6 use crate::lint::{self, LintId};
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
9
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,
18 };
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::edition::Edition;
27 use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
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};
32
33 use std::cell::{self, RefCell};
34 use std::env;
35 use std::fmt;
36 use std::io::Write;
37 use std::num::NonZeroU32;
38 use std::ops::{Div, Mul};
39 use std::path::PathBuf;
40 use std::str::FromStr;
41 use std::sync::Arc;
42 use std::time::Duration;
43
44 pub trait SessionLintStore: sync::Send + sync::Sync {
45     fn name_to_lint(&self, lint_name: &str) -> LintId;
46 }
47
48 pub struct OptimizationFuel {
49     /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
50     remaining: u64,
51     /// We're rejecting all further optimizations.
52     out_of_fuel: bool,
53 }
54
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.
59     Disabled,
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).
62     Capture,
63     /// Capture a backtrace at the point the error is created and immediately print it out.
64     Immediate,
65 }
66
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);
71
72 impl Limit {
73     /// Create a new limit from a `usize`.
74     pub fn new(value: usize) -> Self {
75         Limit(value)
76     }
77
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.
80     #[inline]
81     pub fn value_within_limit(&self, value: usize) -> bool {
82         value <= self.0
83     }
84 }
85
86 impl fmt::Display for Limit {
87     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88         write!(f, "{}", self.0)
89     }
90 }
91
92 impl Div<usize> for Limit {
93     type Output = Limit;
94
95     fn div(self, rhs: usize) -> Self::Output {
96         Limit::new(self.0 / rhs)
97     }
98 }
99
100 impl Mul<usize> for Limit {
101     type Output = Limit;
102
103     fn mul(self, rhs: usize) -> Self::Output {
104         Limit::new(self.0 * rhs)
105     }
106 }
107
108 /// Represents the data associated with a compilation
109 /// session for a single crate.
110 pub struct Session {
111     pub target: Target,
112     pub host: Target,
113     pub opts: config::Options,
114     pub host_tlib_path: SearchPath,
115     /// `None` if the host and target are the same.
116     pub target_tlib_path: Option<SearchPath>,
117     pub parse_sess: ParseSess,
118     pub sysroot: PathBuf,
119     /// The name of the root source file of the crate, in the local file system.
120     /// `None` means that there is no source file.
121     pub local_crate_source_file: Option<PathBuf>,
122     /// The directory the compiler has been executed in plus a flag indicating
123     /// if the value stored here has been affected by path remapping.
124     pub working_dir: (PathBuf, bool),
125
126     /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
127     /// (sub)diagnostics that have been set once, but should not be set again,
128     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
129     pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
130     crate_types: OnceCell<Vec<CrateType>>,
131     /// The `crate_disambiguator` is constructed out of all the `-C metadata`
132     /// arguments passed to the compiler. Its value together with the crate-name
133     /// forms a unique global identifier for the crate. It is used to allow
134     /// multiple crates with the same name to coexist. See the
135     /// `rustc_codegen_llvm::back::symbol_names` module for more information.
136     pub crate_disambiguator: OnceCell<CrateDisambiguator>,
137
138     features: OnceCell<rustc_feature::Features>,
139
140     lint_store: OnceCell<Lrc<dyn SessionLintStore>>,
141
142     /// The maximum recursion limit for potentially infinitely recursive
143     /// operations such as auto-dereference and monomorphization.
144     pub recursion_limit: OnceCell<Limit>,
145
146     /// The maximum length of types during monomorphization.
147     pub type_length_limit: OnceCell<Limit>,
148
149     /// The maximum blocks a const expression can evaluate.
150     pub const_eval_limit: OnceCell<Limit>,
151
152     incr_comp_session: OneThread<RefCell<IncrCompSession>>,
153     /// Used for incremental compilation tests. Will only be populated if
154     /// `-Zquery-dep-graph` is specified.
155     pub cgu_reuse_tracker: CguReuseTracker,
156
157     /// Used by `-Z self-profile`.
158     pub prof: SelfProfilerRef,
159
160     /// Some measurements that are being gathered during compilation.
161     pub perf_stats: PerfStats,
162
163     /// Data about code being compiled, gathered during compilation.
164     pub code_stats: CodeStats,
165
166     /// If `-zfuel=crate=n` is specified, `Some(crate)`.
167     optimization_fuel_crate: Option<String>,
168
169     /// Tracks fuel info if `-zfuel=crate=n` is specified.
170     optimization_fuel: Lock<OptimizationFuel>,
171
172     // The next two are public because the driver needs to read them.
173     /// If `-zprint-fuel=crate`, `Some(crate)`.
174     pub print_fuel_crate: Option<String>,
175     /// Always set to zero and incremented so that we can print fuel expended by a crate.
176     pub print_fuel: AtomicU64,
177
178     /// Loaded up early on in the initialization of this `Session` to avoid
179     /// false positives about a job server in our environment.
180     pub jobserver: Client,
181
182     /// Cap lint level specified by a driver specifically.
183     pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
184
185     /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
186     pub trait_methods_not_found: Lock<FxHashSet<Span>>,
187
188     /// Mapping from ident span to path span for paths that don't exist as written, but that
189     /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
190     pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
191
192     /// Path for libraries that will take preference over libraries shipped by Rust.
193     /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
194     pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
195
196     /// Tracks the current behavior of the CTFE engine when an error occurs.
197     /// Options range from returning the error without a backtrace to returning an error
198     /// and immediately printing the backtrace to stderr.
199     pub ctfe_backtrace: Lock<CtfeBacktrace>,
200
201     /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
202     /// const check, optionally with the relevant feature gate.  We use this to
203     /// warn about unleashing, but with a single diagnostic instead of dozens that
204     /// drown everything else in noise.
205     miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
206
207     /// Base directory containing the `src/` for the Rust standard library, and
208     /// potentially `rustc` as well, if we can can find it. Right now it's always
209     /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
210     ///
211     /// This directory is what the virtual `/rustc/$hash` is translated back to,
212     /// if Rust was built with path remapping to `/rustc/$hash` enabled
213     /// (the `rust.remap-debuginfo` option in `config.toml`).
214     pub real_rust_source_base_dir: Option<PathBuf>,
215
216     /// Architecture to use for interpreting asm!.
217     pub asm_arch: Option<InlineAsmArch>,
218
219     /// Set of enabled features for the current target.
220     pub target_features: FxHashSet<Symbol>,
221
222     known_attrs: Lock<MarkedAttrs>,
223     used_attrs: Lock<MarkedAttrs>,
224
225     /// `Span`s for `if` conditions that we have suggested turning into `if let`.
226     pub if_let_suggestions: Lock<FxHashSet<Span>>,
227 }
228
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,
238 }
239
240 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
241 enum DiagnosticBuilderMethod {
242     Note,
243     SpanNote,
244     // Add more variants as needed to support one-time diagnostics.
245 }
246
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`.
251     #[must_use]
252     fn into_diagnostic(self, sess: &'a Session) -> DiagnosticBuilder<'a>;
253 }
254
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
262 }
263
264 impl From<&'static lint::Lint> for DiagnosticMessageId {
265     fn from(lint: &'static lint::Lint) -> Self {
266         DiagnosticMessageId::LintId(lint::LintId::of(lint))
267     }
268 }
269
270 impl Session {
271     pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
272         self.miri_unleashed_features.lock().push((span, feature_gate));
273     }
274
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.
286                     must_err = true;
287                 } else {
288                     diag.span_help(span, "skipping check that does not even have a feature gate");
289                 }
290             }
291             diag.emit();
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.
295                 self.err(
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",
298                 );
299             }
300         }
301     }
302
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();
308     }
309
310     fn emit_future_breakage(&self) {
311         if !self.opts.debugging_opts.emit_future_incompat_report {
312             return;
313         }
314
315         let diags = self.diagnostic().take_future_breakage_diagnostics();
316         if diags.is_empty() {
317             return;
318         }
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
323             .into_iter()
324             .map(|diag| {
325                 let lint_name = match &diag.code {
326                     Some(DiagnosticId::Lint { name, has_future_breakage: true }) => name,
327                     _ => panic!("Unexpected code in diagnostic {:?}", diag),
328                 };
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)
333             })
334             .collect();
335         self.parse_sess.span_diagnostic.emit_future_breakage_report(diags_and_breakage);
336     }
337
338     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
339         self.crate_disambiguator.get().copied().unwrap()
340     }
341
342     pub fn crate_types(&self) -> &[CrateType] {
343         self.crate_types.get().unwrap().as_slice()
344     }
345
346     pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
347         self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
348     }
349
350     #[inline]
351     pub fn recursion_limit(&self) -> Limit {
352         self.recursion_limit.get().copied().unwrap()
353     }
354
355     #[inline]
356     pub fn type_length_limit(&self) -> Limit {
357         self.type_length_limit.get().copied().unwrap()
358     }
359
360     pub fn const_eval_limit(&self) -> Limit {
361         self.const_eval_limit.get().copied().unwrap()
362     }
363
364     pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
365         self.diagnostic().struct_span_warn(sp, msg)
366     }
367     pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
368         &self,
369         sp: S,
370         msg: &str,
371         code: DiagnosticId,
372     ) -> DiagnosticBuilder<'_> {
373         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
374     }
375     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
376         self.diagnostic().struct_warn(msg)
377     }
378     pub fn struct_span_allow<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
379         self.diagnostic().struct_span_allow(sp, msg)
380     }
381     pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
382         self.diagnostic().struct_allow(msg)
383     }
384     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
385         self.diagnostic().struct_span_err(sp, msg)
386     }
387     pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
388         &self,
389         sp: S,
390         msg: &str,
391         code: DiagnosticId,
392     ) -> DiagnosticBuilder<'_> {
393         self.diagnostic().struct_span_err_with_code(sp, msg, code)
394     }
395     // FIXME: This method should be removed (every error should have an associated error code).
396     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
397         self.diagnostic().struct_err(msg)
398     }
399     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
400         self.diagnostic().struct_err_with_code(msg, code)
401     }
402     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
403         self.diagnostic().struct_span_fatal(sp, msg)
404     }
405     pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
406         &self,
407         sp: S,
408         msg: &str,
409         code: DiagnosticId,
410     ) -> DiagnosticBuilder<'_> {
411         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
412     }
413     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
414         self.diagnostic().struct_fatal(msg)
415     }
416
417     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
418         self.diagnostic().span_fatal(sp, msg).raise()
419     }
420     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
421         &self,
422         sp: S,
423         msg: &str,
424         code: DiagnosticId,
425     ) -> ! {
426         self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
427     }
428     pub fn fatal(&self, msg: &str) -> ! {
429         self.diagnostic().fatal(msg).raise()
430     }
431     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
432         if is_warning {
433             self.span_warn(sp, msg);
434         } else {
435             self.span_err(sp, msg);
436         }
437     }
438     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
439         self.diagnostic().span_err(sp, msg)
440     }
441     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
442         self.diagnostic().span_err_with_code(sp, &msg, code)
443     }
444     pub fn err(&self, msg: &str) {
445         self.diagnostic().err(msg)
446     }
447     pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) {
448         err.into_diagnostic(self).emit()
449     }
450     pub fn err_count(&self) -> usize {
451         self.diagnostic().err_count()
452     }
453     pub fn has_errors(&self) -> bool {
454         self.diagnostic().has_errors()
455     }
456     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
457         self.diagnostic().has_errors_or_delayed_span_bugs()
458     }
459     pub fn abort_if_errors(&self) {
460         self.diagnostic().abort_if_errors();
461     }
462     pub fn compile_status(&self) -> Result<(), ErrorReported> {
463         if self.has_errors() {
464             self.diagnostic().emit_stashed_diagnostics();
465             Err(ErrorReported)
466         } else {
467             Ok(())
468         }
469     }
470     // FIXME(matthewjasper) Remove this method, it should never be needed.
471     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
472     where
473         F: FnOnce() -> T,
474     {
475         let old_count = self.err_count();
476         let result = f();
477         let errors = self.err_count() - old_count;
478         if errors == 0 { Ok(result) } else { Err(ErrorReported) }
479     }
480     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
481         self.diagnostic().span_warn(sp, msg)
482     }
483     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
484         self.diagnostic().span_warn_with_code(sp, msg, code)
485     }
486     pub fn warn(&self, msg: &str) {
487         self.diagnostic().warn(msg)
488     }
489     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
490         match opt_sp {
491             Some(sp) => self.span_warn(sp, msg),
492             None => self.warn(msg),
493         }
494     }
495     /// Delay a span_bug() call until abort_if_errors()
496     #[track_caller]
497     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
498         self.diagnostic().delay_span_bug(sp, msg)
499     }
500
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()
511         {
512             return;
513         }
514
515         self.diagnostic().delay_good_path_bug(msg)
516     }
517
518     pub fn note_without_error(&self, msg: &str) {
519         self.diagnostic().note_without_error(msg)
520     }
521     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
522         self.diagnostic().span_note_without_error(sp, msg)
523     }
524     pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
525         self.diagnostic().struct_note_without_error(msg)
526     }
527
528     pub fn diagnostic(&self) -> &rustc_errors::Handler {
529         &self.parse_sess.span_diagnostic
530     }
531
532     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
533     /// deduplicates on lint ID, span (if any), and message for this `Session`
534     fn diag_once<'a, 'b>(
535         &'a self,
536         diag_builder: &'b mut DiagnosticBuilder<'a>,
537         method: DiagnosticBuilderMethod,
538         msg_id: DiagnosticMessageId,
539         message: &str,
540         span_maybe: Option<Span>,
541     ) {
542         let id_span_message = (msg_id, span_maybe, message.to_owned());
543         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
544         if fresh {
545             match method {
546                 DiagnosticBuilderMethod::Note => {
547                     diag_builder.note(message);
548                 }
549                 DiagnosticBuilderMethod::SpanNote => {
550                     let span = span_maybe.expect("`span_note` needs a span");
551                     diag_builder.span_note(span, message);
552                 }
553             }
554         }
555     }
556
557     pub fn diag_span_note_once<'a, 'b>(
558         &'a self,
559         diag_builder: &'b mut DiagnosticBuilder<'a>,
560         msg_id: DiagnosticMessageId,
561         span: Span,
562         message: &str,
563     ) {
564         self.diag_once(
565             diag_builder,
566             DiagnosticBuilderMethod::SpanNote,
567             msg_id,
568             message,
569             Some(span),
570         );
571     }
572
573     pub fn diag_note_once<'a, 'b>(
574         &'a self,
575         diag_builder: &'b mut DiagnosticBuilder<'a>,
576         msg_id: DiagnosticMessageId,
577         message: &str,
578     ) {
579         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
580     }
581
582     #[inline]
583     pub fn source_map(&self) -> &SourceMap {
584         self.parse_sess.source_map()
585     }
586     pub fn verbose(&self) -> bool {
587         self.opts.debugging_opts.verbose
588     }
589     pub fn time_passes(&self) -> bool {
590         self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
591     }
592     pub fn instrument_mcount(&self) -> bool {
593         self.opts.debugging_opts.instrument_mcount
594     }
595     pub fn time_llvm_passes(&self) -> bool {
596         self.opts.debugging_opts.time_llvm_passes
597     }
598     pub fn meta_stats(&self) -> bool {
599         self.opts.debugging_opts.meta_stats
600     }
601     pub fn asm_comments(&self) -> bool {
602         self.opts.debugging_opts.asm_comments
603     }
604     pub fn verify_llvm_ir(&self) -> bool {
605         self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
606     }
607     pub fn print_llvm_passes(&self) -> bool {
608         self.opts.debugging_opts.print_llvm_passes
609     }
610     pub fn binary_dep_depinfo(&self) -> bool {
611         self.opts.debugging_opts.binary_dep_depinfo
612     }
613     pub fn mir_opt_level(&self) -> usize {
614         self.opts
615             .debugging_opts
616             .mir_opt_level
617             .unwrap_or_else(|| if self.opts.optimize != config::OptLevel::No { 2 } else { 1 })
618     }
619
620     /// Gets the features enabled for the current compilation session.
621     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
622     /// dependency tracking. Use tcx.features() instead.
623     #[inline]
624     pub fn features_untracked(&self) -> &rustc_feature::Features {
625         self.features.get().unwrap()
626     }
627
628     pub fn init_features(&self, features: rustc_feature::Features) {
629         match self.features.set(features) {
630             Ok(()) => {}
631             Err(_) => panic!("`features` was initialized twice"),
632         }
633     }
634
635     pub fn init_lint_store(&self, lint_store: Lrc<dyn SessionLintStore>) {
636         self.lint_store
637             .set(lint_store)
638             .map_err(|_| ())
639             .expect("`lint_store` was initialized twice");
640     }
641
642     /// Calculates the flavor of LTO to use for this compilation.
643     pub fn lto(&self) -> config::Lto {
644         // If our target has codegen requirements ignore the command line
645         if self.target.requires_lto {
646             return config::Lto::Fat;
647         }
648
649         // If the user specified something, return that. If they only said `-C
650         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
651         // then ensure we can't use a ThinLTO.
652         match self.opts.cg.lto {
653             config::LtoCli::Unspecified => {
654                 // The compiler was invoked without the `-Clto` flag. Fall
655                 // through to the default handling
656             }
657             config::LtoCli::No => {
658                 // The user explicitly opted out of any kind of LTO
659                 return config::Lto::No;
660             }
661             config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
662                 // All of these mean fat LTO
663                 return config::Lto::Fat;
664             }
665             config::LtoCli::Thin => {
666                 return if self.opts.cli_forced_thinlto_off {
667                     config::Lto::Fat
668                 } else {
669                     config::Lto::Thin
670                 };
671             }
672         }
673
674         // Ok at this point the target doesn't require anything and the user
675         // hasn't asked for anything. Our next decision is whether or not
676         // we enable "auto" ThinLTO where we use multiple codegen units and
677         // then do ThinLTO over those codegen units. The logic below will
678         // either return `No` or `ThinLocal`.
679
680         // If processing command line options determined that we're incompatible
681         // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
682         if self.opts.cli_forced_thinlto_off {
683             return config::Lto::No;
684         }
685
686         // If `-Z thinlto` specified process that, but note that this is mostly
687         // a deprecated option now that `-C lto=thin` exists.
688         if let Some(enabled) = self.opts.debugging_opts.thinlto {
689             if enabled {
690                 return config::Lto::ThinLocal;
691             } else {
692                 return config::Lto::No;
693             }
694         }
695
696         // If there's only one codegen unit and LTO isn't enabled then there's
697         // no need for ThinLTO so just return false.
698         if self.codegen_units() == 1 {
699             return config::Lto::No;
700         }
701
702         // Now we're in "defaults" territory. By default we enable ThinLTO for
703         // optimized compiles (anything greater than O0).
704         match self.opts.optimize {
705             config::OptLevel::No => config::Lto::No,
706             _ => config::Lto::ThinLocal,
707         }
708     }
709
710     /// Returns the panic strategy for this compile session. If the user explicitly selected one
711     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
712     pub fn panic_strategy(&self) -> PanicStrategy {
713         self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
714     }
715     pub fn fewer_names(&self) -> bool {
716         if let Some(fewer_names) = self.opts.debugging_opts.fewer_names {
717             fewer_names
718         } else {
719             let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
720                 || self.opts.output_types.contains_key(&OutputType::Bitcode)
721                 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
722                 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
723             !more_names
724         }
725     }
726
727     pub fn unstable_options(&self) -> bool {
728         self.opts.debugging_opts.unstable_options
729     }
730     pub fn is_nightly_build(&self) -> bool {
731         self.opts.unstable_features.is_nightly_build()
732     }
733     pub fn overflow_checks(&self) -> bool {
734         self.opts
735             .cg
736             .overflow_checks
737             .or(self.opts.debugging_opts.force_overflow_checks)
738             .unwrap_or(self.opts.debug_assertions)
739     }
740
741     /// Check whether this compile session and crate type use static crt.
742     pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
743         if !self.target.crt_static_respected {
744             // If the target does not opt in to crt-static support, use its default.
745             return self.target.crt_static_default;
746         }
747
748         let requested_features = self.opts.cg.target_feature.split(',');
749         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
750         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
751
752         if found_positive || found_negative {
753             found_positive
754         } else if crate_type == Some(CrateType::ProcMacro)
755             || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
756         {
757             // FIXME: When crate_type is not available,
758             // we use compiler options to determine the crate_type.
759             // We can't check `#![crate_type = "proc-macro"]` here.
760             false
761         } else {
762             self.target.crt_static_default
763         }
764     }
765
766     pub fn relocation_model(&self) -> RelocModel {
767         self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
768     }
769
770     pub fn code_model(&self) -> Option<CodeModel> {
771         self.opts.cg.code_model.or(self.target.code_model)
772     }
773
774     pub fn tls_model(&self) -> TlsModel {
775         self.opts.debugging_opts.tls_model.unwrap_or(self.target.tls_model)
776     }
777
778     pub fn is_wasi_reactor(&self) -> bool {
779         self.target.options.os == "wasi"
780             && matches!(
781                 self.opts.debugging_opts.wasi_exec_model,
782                 Some(config::WasiExecModel::Reactor)
783             )
784     }
785
786     pub fn split_debuginfo(&self) -> SplitDebuginfo {
787         self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
788     }
789
790     pub fn target_can_use_split_dwarf(&self) -> bool {
791         !self.target.is_like_windows && !self.target.is_like_osx
792     }
793
794     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
795         // "mcount" function relies on stack pointer.
796         // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
797         if self.instrument_mcount() {
798             true
799         } else if let Some(x) = self.opts.cg.force_frame_pointers {
800             x
801         } else {
802             !self.target.eliminate_frame_pointer
803         }
804     }
805
806     pub fn must_emit_unwind_tables(&self) -> bool {
807         // This is used to control the emission of the `uwtable` attribute on
808         // LLVM functions.
809         //
810         // Unwind tables are needed when compiling with `-C panic=unwind`, but
811         // LLVM won't omit unwind tables unless the function is also marked as
812         // `nounwind`, so users are allowed to disable `uwtable` emission.
813         // Historically rustc always emits `uwtable` attributes by default, so
814         // even they can be disabled, they're still emitted by default.
815         //
816         // On some targets (including windows), however, exceptions include
817         // other events such as illegal instructions, segfaults, etc. This means
818         // that on Windows we end up still needing unwind tables even if the `-C
819         // panic=abort` flag is passed.
820         //
821         // You can also find more info on why Windows needs unwind tables in:
822         //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
823         //
824         // If a target requires unwind tables, then they must be emitted.
825         // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
826         // value, if it is provided, or disable them, if not.
827         self.target.requires_uwtable
828             || self.opts.cg.force_unwind_tables.unwrap_or(
829                 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
830             )
831     }
832
833     /// Returns the symbol name for the registrar function,
834     /// given the crate `Svh` and the function `DefIndex`.
835     pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
836         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
837     }
838
839     pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
840         format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
841     }
842
843     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
844         filesearch::FileSearch::new(
845             &self.sysroot,
846             self.opts.target_triple.triple(),
847             &self.opts.search_paths,
848             // `target_tlib_path == None` means it's the same as `host_tlib_path`.
849             self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
850             kind,
851         )
852     }
853     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
854         filesearch::FileSearch::new(
855             &self.sysroot,
856             config::host_triple(),
857             &self.opts.search_paths,
858             &self.host_tlib_path,
859             kind,
860         )
861     }
862
863     pub fn init_incr_comp_session(
864         &self,
865         session_dir: PathBuf,
866         lock_file: flock::Lock,
867         load_dep_graph: bool,
868     ) {
869         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
870
871         if let IncrCompSession::NotInitialized = *incr_comp_session {
872         } else {
873             panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
874         }
875
876         *incr_comp_session =
877             IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
878     }
879
880     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
881         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
882
883         if let IncrCompSession::Active { .. } = *incr_comp_session {
884         } else {
885             panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
886         }
887
888         // Note: this will also drop the lock file, thus unlocking the directory.
889         *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
890     }
891
892     pub fn mark_incr_comp_session_as_invalid(&self) {
893         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
894
895         let session_directory = match *incr_comp_session {
896             IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
897             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
898             _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
899         };
900
901         // Note: this will also drop the lock file, thus unlocking the directory.
902         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
903     }
904
905     pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
906         let incr_comp_session = self.incr_comp_session.borrow();
907         cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
908             IncrCompSession::NotInitialized => panic!(
909                 "trying to get session directory from `IncrCompSession`: {:?}",
910                 *incr_comp_session,
911             ),
912             IncrCompSession::Active { ref session_directory, .. }
913             | IncrCompSession::Finalized { ref session_directory }
914             | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
915                 session_directory
916             }
917         })
918     }
919
920     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
921         self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
922     }
923
924     pub fn print_perf_stats(&self) {
925         eprintln!(
926             "Total time spent computing symbol hashes:      {}",
927             duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
928         );
929         eprintln!(
930             "Total queries canonicalized:                   {}",
931             self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
932         );
933         eprintln!(
934             "normalize_generic_arg_after_erasing_regions:   {}",
935             self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
936         );
937         eprintln!(
938             "normalize_projection_ty:                       {}",
939             self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
940         );
941     }
942
943     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
944     /// This expends fuel if applicable, and records fuel if applicable.
945     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
946         let mut ret = true;
947         if let Some(ref c) = self.optimization_fuel_crate {
948             if c == crate_name {
949                 assert_eq!(self.threads(), 1);
950                 let mut fuel = self.optimization_fuel.lock();
951                 ret = fuel.remaining != 0;
952                 if fuel.remaining == 0 && !fuel.out_of_fuel {
953                     self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
954                     fuel.out_of_fuel = true;
955                 } else if fuel.remaining > 0 {
956                     fuel.remaining -= 1;
957                 }
958             }
959         }
960         if let Some(ref c) = self.print_fuel_crate {
961             if c == crate_name {
962                 assert_eq!(self.threads(), 1);
963                 self.print_fuel.fetch_add(1, SeqCst);
964             }
965         }
966         ret
967     }
968
969     /// Returns the number of query threads that should be used for this
970     /// compilation
971     pub fn threads(&self) -> usize {
972         self.opts.debugging_opts.threads
973     }
974
975     /// Returns the number of codegen units that should be used for this
976     /// compilation
977     pub fn codegen_units(&self) -> usize {
978         if let Some(n) = self.opts.cli_forced_codegen_units {
979             return n;
980         }
981         if let Some(n) = self.target.default_codegen_units {
982             return n as usize;
983         }
984
985         // If incremental compilation is turned on, we default to a high number
986         // codegen units in order to reduce the "collateral damage" small
987         // changes cause.
988         if self.opts.incremental.is_some() {
989             return 256;
990         }
991
992         // Why is 16 codegen units the default all the time?
993         //
994         // The main reason for enabling multiple codegen units by default is to
995         // leverage the ability for the codegen backend to do codegen and
996         // optimization in parallel. This allows us, especially for large crates, to
997         // make good use of all available resources on the machine once we've
998         // hit that stage of compilation. Large crates especially then often
999         // take a long time in codegen/optimization and this helps us amortize that
1000         // cost.
1001         //
1002         // Note that a high number here doesn't mean that we'll be spawning a
1003         // large number of threads in parallel. The backend of rustc contains
1004         // global rate limiting through the `jobserver` crate so we'll never
1005         // overload the system with too much work, but rather we'll only be
1006         // optimizing when we're otherwise cooperating with other instances of
1007         // rustc.
1008         //
1009         // Rather a high number here means that we should be able to keep a lot
1010         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1011         // to build we'll be guaranteed that all cpus will finish pretty closely
1012         // to one another and we should make relatively optimal use of system
1013         // resources
1014         //
1015         // Note that the main cost of codegen units is that it prevents LLVM
1016         // from inlining across codegen units. Users in general don't have a lot
1017         // of control over how codegen units are split up so it's our job in the
1018         // compiler to ensure that undue performance isn't lost when using
1019         // codegen units (aka we can't require everyone to slap `#[inline]` on
1020         // everything).
1021         //
1022         // If we're compiling at `-O0` then the number doesn't really matter too
1023         // much because performance doesn't matter and inlining is ok to lose.
1024         // In debug mode we just want to try to guarantee that no cpu is stuck
1025         // doing work that could otherwise be farmed to others.
1026         //
1027         // In release mode, however (O1 and above) performance does indeed
1028         // matter! To recover the loss in performance due to inlining we'll be
1029         // enabling ThinLTO by default (the function for which is just below).
1030         // This will ensure that we recover any inlining wins we otherwise lost
1031         // through codegen unit partitioning.
1032         //
1033         // ---
1034         //
1035         // Ok that's a lot of words but the basic tl;dr; is that we want a high
1036         // number here -- but not too high. Additionally we're "safe" to have it
1037         // always at the same number at all optimization levels.
1038         //
1039         // As a result 16 was chosen here! Mostly because it was a power of 2
1040         // and most benchmarks agreed it was roughly a local optimum. Not very
1041         // scientific.
1042         16
1043     }
1044
1045     pub fn teach(&self, code: &DiagnosticId) -> bool {
1046         self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
1047     }
1048
1049     pub fn rust_2015(&self) -> bool {
1050         self.opts.edition == Edition::Edition2015
1051     }
1052
1053     /// Are we allowed to use features from the Rust 2018 edition?
1054     pub fn rust_2018(&self) -> bool {
1055         self.opts.edition >= Edition::Edition2018
1056     }
1057
1058     /// Are we allowed to use features from the Rust 2021 edition?
1059     pub fn rust_2021(&self) -> bool {
1060         self.opts.edition >= Edition::Edition2021
1061     }
1062
1063     pub fn edition(&self) -> Edition {
1064         self.opts.edition
1065     }
1066
1067     /// Returns `true` if we cannot skip the PLT for shared library calls.
1068     pub fn needs_plt(&self) -> bool {
1069         // Check if the current target usually needs PLT to be enabled.
1070         // The user can use the command line flag to override it.
1071         let needs_plt = self.target.needs_plt;
1072
1073         let dbg_opts = &self.opts.debugging_opts;
1074
1075         let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
1076
1077         // Only enable this optimization by default if full relro is also enabled.
1078         // In this case, lazy binding was already unavailable, so nothing is lost.
1079         // This also ensures `-Wl,-z,now` is supported by the linker.
1080         let full_relro = RelroLevel::Full == relro_level;
1081
1082         // If user didn't explicitly forced us to use / skip the PLT,
1083         // then try to skip it where possible.
1084         dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1085     }
1086
1087     /// Checks if LLVM lifetime markers should be emitted.
1088     pub fn emit_lifetime_markers(&self) -> bool {
1089         self.opts.optimize != config::OptLevel::No
1090         // AddressSanitizer uses lifetimes to detect use after scope bugs.
1091         // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1092         // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
1093         || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
1094     }
1095
1096     pub fn link_dead_code(&self) -> bool {
1097         self.opts.cg.link_dead_code.unwrap_or(false)
1098     }
1099
1100     pub fn instrument_coverage(&self) -> bool {
1101         self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1102             != config::InstrumentCoverage::Off
1103     }
1104
1105     pub fn instrument_coverage_except_unused_generics(&self) -> bool {
1106         self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1107             == config::InstrumentCoverage::ExceptUnusedGenerics
1108     }
1109
1110     pub fn instrument_coverage_except_unused_functions(&self) -> bool {
1111         self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1112             == config::InstrumentCoverage::ExceptUnusedFunctions
1113     }
1114
1115     pub fn mark_attr_known(&self, attr: &Attribute) {
1116         self.known_attrs.lock().mark(attr)
1117     }
1118
1119     pub fn is_attr_known(&self, attr: &Attribute) -> bool {
1120         self.known_attrs.lock().is_marked(attr)
1121     }
1122
1123     pub fn mark_attr_used(&self, attr: &Attribute) {
1124         self.used_attrs.lock().mark(attr)
1125     }
1126
1127     pub fn is_attr_used(&self, attr: &Attribute) -> bool {
1128         self.used_attrs.lock().is_marked(attr)
1129     }
1130
1131     /// Returns `true` if the attribute's path matches the argument. If it
1132     /// matches, then the attribute is marked as used.
1133     ///
1134     /// This method should only be used by rustc, other tools can use
1135     /// `Attribute::has_name` instead, because only rustc is supposed to report
1136     /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1137     /// produced by lowering an `Attribute` and don't have identity, so they
1138     /// only have the `has_name` method, and you need to mark the original
1139     /// `Attribute` as used when necessary.)
1140     pub fn check_name(&self, attr: &Attribute, name: Symbol) -> bool {
1141         let matches = attr.has_name(name);
1142         if matches {
1143             self.mark_attr_used(attr);
1144         }
1145         matches
1146     }
1147
1148     pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1149         [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1150             .iter()
1151             .any(|kind| self.check_name(attr, *kind))
1152     }
1153
1154     pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1155         attrs.iter().any(|item| self.check_name(item, name))
1156     }
1157
1158     pub fn find_by_name<'a>(
1159         &'a self,
1160         attrs: &'a [Attribute],
1161         name: Symbol,
1162     ) -> Option<&'a Attribute> {
1163         attrs.iter().find(|attr| self.check_name(attr, name))
1164     }
1165
1166     pub fn filter_by_name<'a>(
1167         &'a self,
1168         attrs: &'a [Attribute],
1169         name: Symbol,
1170     ) -> impl Iterator<Item = &'a Attribute> {
1171         attrs.iter().filter(move |attr| self.check_name(attr, name))
1172     }
1173
1174     pub fn first_attr_value_str_by_name(
1175         &self,
1176         attrs: &[Attribute],
1177         name: Symbol,
1178     ) -> Option<Symbol> {
1179         attrs.iter().find(|at| self.check_name(at, name)).and_then(|at| at.value_str())
1180     }
1181 }
1182
1183 fn default_emitter(
1184     sopts: &config::Options,
1185     registry: rustc_errors::registry::Registry,
1186     source_map: Lrc<SourceMap>,
1187     emitter_dest: Option<Box<dyn Write + Send>>,
1188 ) -> Box<dyn Emitter + sync::Send> {
1189     let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1190     match (sopts.error_format, emitter_dest) {
1191         (config::ErrorOutputType::HumanReadable(kind), dst) => {
1192             let (short, color_config) = kind.unzip();
1193
1194             if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1195                 let emitter =
1196                     AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1197                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1198             } else {
1199                 let emitter = match dst {
1200                     None => EmitterWriter::stderr(
1201                         color_config,
1202                         Some(source_map),
1203                         short,
1204                         sopts.debugging_opts.teach,
1205                         sopts.debugging_opts.terminal_width,
1206                         macro_backtrace,
1207                     ),
1208                     Some(dst) => EmitterWriter::new(
1209                         dst,
1210                         Some(source_map),
1211                         short,
1212                         false, // no teach messages when writing to a buffer
1213                         false, // no colors when writing to a buffer
1214                         None,  // no terminal width
1215                         macro_backtrace,
1216                     ),
1217                 };
1218                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1219             }
1220         }
1221         (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1222             JsonEmitter::stderr(
1223                 Some(registry),
1224                 source_map,
1225                 pretty,
1226                 json_rendered,
1227                 sopts.debugging_opts.terminal_width,
1228                 macro_backtrace,
1229             )
1230             .ui_testing(sopts.debugging_opts.ui_testing),
1231         ),
1232         (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1233             JsonEmitter::new(
1234                 dst,
1235                 Some(registry),
1236                 source_map,
1237                 pretty,
1238                 json_rendered,
1239                 sopts.debugging_opts.terminal_width,
1240                 macro_backtrace,
1241             )
1242             .ui_testing(sopts.debugging_opts.ui_testing),
1243         ),
1244     }
1245 }
1246
1247 pub enum DiagnosticOutput {
1248     Default,
1249     Raw(Box<dyn Write + Send>),
1250 }
1251
1252 pub fn build_session(
1253     sopts: config::Options,
1254     local_crate_source_file: Option<PathBuf>,
1255     registry: rustc_errors::registry::Registry,
1256     diagnostics_output: DiagnosticOutput,
1257     driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1258     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1259     target_override: Option<Target>,
1260 ) -> Session {
1261     // FIXME: This is not general enough to make the warning lint completely override
1262     // normal diagnostic warnings, since the warning lint can also be denied and changed
1263     // later via the source code.
1264     let warnings_allow = sopts
1265         .lint_opts
1266         .iter()
1267         .filter(|&&(ref key, _)| *key == "warnings")
1268         .map(|&(_, ref level)| *level == lint::Allow)
1269         .last()
1270         .unwrap_or(false);
1271     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1272     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1273
1274     let write_dest = match diagnostics_output {
1275         DiagnosticOutput::Default => None,
1276         DiagnosticOutput::Raw(write) => Some(write),
1277     };
1278
1279     let target_cfg = config::build_target_config(&sopts, target_override);
1280     let host_triple = TargetTriple::from_triple(config::host_triple());
1281     let host = Target::search(&host_triple).unwrap_or_else(|e| {
1282         early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1283     });
1284
1285     let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1286     let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1287         if target_cfg.is_like_msvc {
1288             SourceFileHashAlgorithm::Sha1
1289         } else {
1290             SourceFileHashAlgorithm::Md5
1291         }
1292     });
1293     let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1294         loader,
1295         sopts.file_path_mapping(),
1296         hash_kind,
1297     ));
1298     let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1299
1300     let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1301         emitter,
1302         sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1303     );
1304
1305     let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1306     {
1307         let directory =
1308             if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1309
1310         let profiler = SelfProfiler::new(
1311             directory,
1312             sopts.crate_name.as_deref(),
1313             &sopts.debugging_opts.self_profile_events,
1314         );
1315         match profiler {
1316             Ok(profiler) => Some(Arc::new(profiler)),
1317             Err(e) => {
1318                 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1319                 None
1320             }
1321         }
1322     } else {
1323         None
1324     };
1325
1326     let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1327     parse_sess.assume_incomplete_release = sopts.debugging_opts.assume_incomplete_release;
1328     let sysroot = match &sopts.maybe_sysroot {
1329         Some(sysroot) => sysroot.clone(),
1330         None => filesearch::get_or_default_sysroot(),
1331     };
1332
1333     let host_triple = config::host_triple();
1334     let target_triple = sopts.target_triple.triple();
1335     let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1336     let target_tlib_path = if host_triple == target_triple {
1337         None
1338     } else {
1339         Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1340     };
1341
1342     let file_path_mapping = sopts.file_path_mapping();
1343
1344     let local_crate_source_file =
1345         local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1346
1347     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1348     let optimization_fuel = Lock::new(OptimizationFuel {
1349         remaining: sopts.debugging_opts.fuel.as_ref().map_or(0, |i| i.1),
1350         out_of_fuel: false,
1351     });
1352     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1353     let print_fuel = AtomicU64::new(0);
1354
1355     let working_dir = env::current_dir().unwrap_or_else(|e| {
1356         parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1357     });
1358     let working_dir = file_path_mapping.map_prefix(working_dir);
1359
1360     let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1361         CguReuseTracker::new()
1362     } else {
1363         CguReuseTracker::new_disabled()
1364     };
1365
1366     let prof = SelfProfilerRef::new(
1367         self_profiler,
1368         sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1369         sopts.debugging_opts.time_passes,
1370     );
1371
1372     let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1373         Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1374         Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1375         _ => CtfeBacktrace::Disabled,
1376     });
1377
1378     // Try to find a directory containing the Rust `src`, for more details see
1379     // the doc comment on the `real_rust_source_base_dir` field.
1380     let real_rust_source_base_dir = {
1381         // This is the location used by the `rust-src` `rustup` component.
1382         let mut candidate = sysroot.join("lib/rustlib/src/rust");
1383         if let Ok(metadata) = candidate.symlink_metadata() {
1384             // Replace the symlink rustbuild creates, with its destination.
1385             // We could try to use `fs::canonicalize` instead, but that might
1386             // produce unnecessarily verbose path.
1387             if metadata.file_type().is_symlink() {
1388                 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1389                     candidate = symlink_dest;
1390                 }
1391             }
1392         }
1393
1394         // Only use this directory if it has a file we can expect to always find.
1395         if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None }
1396     };
1397
1398     let asm_arch =
1399         if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1400
1401     let sess = Session {
1402         target: target_cfg,
1403         host,
1404         opts: sopts,
1405         host_tlib_path,
1406         target_tlib_path,
1407         parse_sess,
1408         sysroot,
1409         local_crate_source_file,
1410         working_dir,
1411         one_time_diagnostics: Default::default(),
1412         crate_types: OnceCell::new(),
1413         crate_disambiguator: OnceCell::new(),
1414         features: OnceCell::new(),
1415         lint_store: OnceCell::new(),
1416         recursion_limit: OnceCell::new(),
1417         type_length_limit: OnceCell::new(),
1418         const_eval_limit: OnceCell::new(),
1419         incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1420         cgu_reuse_tracker,
1421         prof,
1422         perf_stats: PerfStats {
1423             symbol_hash_time: Lock::new(Duration::from_secs(0)),
1424             queries_canonicalized: AtomicUsize::new(0),
1425             normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1426             normalize_projection_ty: AtomicUsize::new(0),
1427         },
1428         code_stats: Default::default(),
1429         optimization_fuel_crate,
1430         optimization_fuel,
1431         print_fuel_crate,
1432         print_fuel,
1433         jobserver: jobserver::client(),
1434         driver_lint_caps,
1435         trait_methods_not_found: Lock::new(Default::default()),
1436         confused_type_with_std_module: Lock::new(Default::default()),
1437         system_library_path: OneThread::new(RefCell::new(Default::default())),
1438         ctfe_backtrace,
1439         miri_unleashed_features: Lock::new(Default::default()),
1440         real_rust_source_base_dir,
1441         asm_arch,
1442         target_features: FxHashSet::default(),
1443         known_attrs: Lock::new(MarkedAttrs::new()),
1444         used_attrs: Lock::new(MarkedAttrs::new()),
1445         if_let_suggestions: Default::default(),
1446     };
1447
1448     validate_commandline_args_with_session_available(&sess);
1449
1450     sess
1451 }
1452
1453 // If it is useful to have a Session available already for validating a
1454 // commandline argument, you can do so here.
1455 fn validate_commandline_args_with_session_available(sess: &Session) {
1456     // Since we don't know if code in an rlib will be linked to statically or
1457     // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1458     // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1459     // these manually generated symbols confuse LLD when it tries to merge
1460     // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1461     // when compiling for LLD ThinLTO. This way we can validly just not generate
1462     // the `dllimport` attributes and `__imp_` symbols in that case.
1463     if sess.opts.cg.linker_plugin_lto.enabled()
1464         && sess.opts.cg.prefer_dynamic
1465         && sess.target.is_like_windows
1466     {
1467         sess.err(
1468             "Linker plugin based LTO is not supported together with \
1469                   `-C prefer-dynamic` when targeting Windows-like targets",
1470         );
1471     }
1472
1473     // Make sure that any given profiling data actually exists so LLVM can't
1474     // decide to silently skip PGO.
1475     if let Some(ref path) = sess.opts.cg.profile_use {
1476         if !path.exists() {
1477             sess.err(&format!(
1478                 "File `{}` passed to `-C profile-use` does not exist.",
1479                 path.display()
1480             ));
1481         }
1482     }
1483
1484     // Unwind tables cannot be disabled if the target requires them.
1485     if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1486         if sess.target.requires_uwtable && !include_uwtables {
1487             sess.err(
1488                 "target requires unwind tables, they cannot be disabled with \
1489                      `-C force-unwind-tables=no`.",
1490             );
1491         }
1492     }
1493
1494     // PGO does not work reliably with panic=unwind on Windows. Let's make it
1495     // an error to combine the two for now. It always runs into an assertions
1496     // if LLVM is built with assertions, but without assertions it sometimes
1497     // does not crash and will probably generate a corrupted binary.
1498     // We should only display this error if we're actually going to run PGO.
1499     // If we're just supposed to print out some data, don't show the error (#61002).
1500     if sess.opts.cg.profile_generate.enabled()
1501         && sess.target.is_like_msvc
1502         && sess.panic_strategy() == PanicStrategy::Unwind
1503         && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1504     {
1505         sess.err(
1506             "Profile-guided optimization does not yet work in conjunction \
1507                   with `-Cpanic=unwind` on Windows when targeting MSVC. \
1508                   See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1509                   for more information.",
1510         );
1511     }
1512
1513     // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1514     let supported_sanitizers = sess.target.options.supported_sanitizers;
1515     let unsupported_sanitizers = sess.opts.debugging_opts.sanitizer - supported_sanitizers;
1516     match unsupported_sanitizers.into_iter().count() {
1517         0 => {}
1518         1 => sess
1519             .err(&format!("{} sanitizer is not supported for this target", unsupported_sanitizers)),
1520         _ => sess.err(&format!(
1521             "{} sanitizers are not supported for this target",
1522             unsupported_sanitizers
1523         )),
1524     }
1525     // Cannot mix and match sanitizers.
1526     let mut sanitizer_iter = sess.opts.debugging_opts.sanitizer.into_iter();
1527     if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1528         sess.err(&format!("`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`", first, second));
1529     }
1530 }
1531
1532 /// Holds data on the current incremental compilation session, if there is one.
1533 #[derive(Debug)]
1534 pub enum IncrCompSession {
1535     /// This is the state the session will be in until the incr. comp. dir is
1536     /// needed.
1537     NotInitialized,
1538     /// This is the state during which the session directory is private and can
1539     /// be modified.
1540     Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1541     /// This is the state after the session directory has been finalized. In this
1542     /// state, the contents of the directory must not be modified any more.
1543     Finalized { session_directory: PathBuf },
1544     /// This is an error state that is reached when some compilation error has
1545     /// occurred. It indicates that the contents of the session directory must
1546     /// not be used, since they might be invalid.
1547     InvalidBecauseOfErrors { session_directory: PathBuf },
1548 }
1549
1550 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1551     let emitter: Box<dyn Emitter + sync::Send> = match output {
1552         config::ErrorOutputType::HumanReadable(kind) => {
1553             let (short, color_config) = kind.unzip();
1554             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1555         }
1556         config::ErrorOutputType::Json { pretty, json_rendered } => {
1557             Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1558         }
1559     };
1560     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1561     handler.struct_fatal(msg).emit();
1562     rustc_errors::FatalError.raise();
1563 }
1564
1565 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1566     let emitter: Box<dyn Emitter + sync::Send> = match output {
1567         config::ErrorOutputType::HumanReadable(kind) => {
1568             let (short, color_config) = kind.unzip();
1569             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1570         }
1571         config::ErrorOutputType::Json { pretty, json_rendered } => {
1572             Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1573         }
1574     };
1575     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1576     handler.struct_warn(msg).emit();
1577 }