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