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