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