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