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