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