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