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