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