1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
12 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
14 use hir::def_id::CrateNum;
19 use lint::builtin::BuiltinLintDiagnostics;
20 use middle::allocator::AllocatorKind;
21 use middle::dependency_format;
22 use session::search_paths::PathKind;
23 use session::config::{OutputType};
25 use util::nodemap::{FxHashMap, FxHashSet};
26 use util::common::{duration_to_secs_str, ErrorReported};
27 use util::common::ProfileQueriesMsg;
29 use rustc_data_structures::sync::{self, Lrc, Lock, LockCell, OneThread, Once, RwLock};
31 use syntax::ast::NodeId;
32 use errors::{self, DiagnosticBuilder, DiagnosticId};
33 use errors::emitter::{Emitter, EmitterWriter};
34 use syntax::edition::Edition;
35 use syntax::json::JsonEmitter;
36 use syntax::feature_gate;
37 use syntax::symbol::Symbol;
39 use syntax::parse::ParseSess;
40 use syntax::{ast, codemap};
41 use syntax::feature_gate::AttributeType;
42 use syntax_pos::{MultiSpan, Span};
43 use util::profiling::SelfProfiler;
45 use rustc_target::spec::{LinkerFlavor, PanicStrategy};
46 use rustc_target::spec::{Target, TargetTriple};
47 use rustc_data_structures::flock;
48 use jobserver::Client;
51 use std::cell::{self, Cell, RefCell};
52 use std::collections::HashMap;
56 use std::path::{Path, PathBuf};
57 use std::time::Duration;
59 use std::sync::atomic::{AtomicUsize, Ordering};
66 /// Represents the data associated with a compilation
67 /// session for a single crate.
69 pub target: config::Config,
71 pub opts: config::Options,
72 pub parse_sess: ParseSess,
73 /// For a library crate, this is always none
74 pub entry_fn: Once<Option<(NodeId, Span, config::EntryFnType)>>,
75 pub plugin_registrar_fn: Once<Option<ast::NodeId>>,
76 pub derive_registrar_fn: Once<Option<ast::NodeId>>,
77 pub default_sysroot: Option<PathBuf>,
78 /// The name of the root source file of the crate, in the local file system.
79 /// `None` means that there is no source file.
80 pub local_crate_source_file: Option<PathBuf>,
81 /// The directory the compiler has been executed in plus a flag indicating
82 /// if the value stored here has been affected by path remapping.
83 pub working_dir: (PathBuf, bool),
85 // FIXME: lint_store and buffered_lints are not thread-safe,
86 // but are only used in a single thread
87 pub lint_store: RwLock<lint::LintStore>,
88 pub buffered_lints: Lock<Option<lint::LintBuffer>>,
90 /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
91 /// (sub)diagnostics that have been set once, but should not be set again,
92 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
93 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
94 pub plugin_llvm_passes: OneThread<RefCell<Vec<String>>>,
95 pub plugin_attributes: OneThread<RefCell<Vec<(String, AttributeType)>>>,
96 pub crate_types: Once<Vec<config::CrateType>>,
97 pub dependency_formats: Once<dependency_format::Dependencies>,
98 /// The crate_disambiguator is constructed out of all the `-C metadata`
99 /// arguments passed to the compiler. Its value together with the crate-name
100 /// forms a unique global identifier for the crate. It is used to allow
101 /// multiple crates with the same name to coexist. See the
102 /// rustc_codegen_llvm::back::symbol_names module for more information.
103 pub crate_disambiguator: Once<CrateDisambiguator>,
105 features: Once<feature_gate::Features>,
107 /// The maximum recursion limit for potentially infinitely recursive
108 /// operations such as auto-dereference and monomorphization.
109 pub recursion_limit: Once<usize>,
111 /// The maximum length of types during monomorphization.
112 pub type_length_limit: Once<usize>,
114 /// The maximum number of stackframes allowed in const eval
115 pub const_eval_stack_frame_limit: usize,
117 /// The metadata::creader module may inject an allocator/panic_runtime
118 /// dependency if it didn't already find one, and this tracks what was
120 pub injected_allocator: Once<Option<CrateNum>>,
121 pub allocator_kind: Once<Option<AllocatorKind>>,
122 pub injected_panic_runtime: Once<Option<CrateNum>>,
124 /// Map from imported macro spans (which consist of
125 /// the localized span for the macro body) to the
126 /// macro name and definition span in the source crate.
127 pub imported_macro_spans: OneThread<RefCell<HashMap<Span, (String, Span)>>>,
129 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
131 /// A cache of attributes ignored by StableHashingContext
132 pub ignored_attr_names: FxHashSet<Symbol>,
134 /// Used by -Z profile-queries in util::common
135 pub profile_channel: Lock<Option<mpsc::Sender<ProfileQueriesMsg>>>,
137 /// Used by -Z self-profile
138 pub self_profiling: Lock<SelfProfiler>,
140 /// Some measurements that are being gathered during compilation.
141 pub perf_stats: PerfStats,
143 /// Data about code being compiled, gathered during compilation.
144 pub code_stats: Lock<CodeStats>,
146 next_node_id: OneThread<Cell<ast::NodeId>>,
148 /// If -zfuel=crate=n is specified, Some(crate).
149 optimization_fuel_crate: Option<String>,
150 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
151 optimization_fuel_limit: LockCell<u64>,
152 /// We're rejecting all further optimizations.
153 out_of_fuel: LockCell<bool>,
155 // The next two are public because the driver needs to read them.
156 /// If -zprint-fuel=crate, Some(crate).
157 pub print_fuel_crate: Option<String>,
158 /// Always set to zero and incremented so that we can print fuel expended by a crate.
159 pub print_fuel: LockCell<u64>,
161 /// Loaded up early on in the initialization of this `Session` to avoid
162 /// false positives about a job server in our environment.
163 pub jobserver: Client,
165 /// Metadata about the allocators for the current crate being compiled
166 pub has_global_allocator: Once<bool>,
168 /// Cap lint level specified by a driver specifically.
169 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
172 pub struct PerfStats {
173 /// The accumulated time spent on computing symbol hashes
174 pub symbol_hash_time: Lock<Duration>,
175 /// The accumulated time spent decoding def path tables from metadata
176 pub decode_def_path_tables_time: Lock<Duration>,
177 /// Total number of values canonicalized queries constructed.
178 pub queries_canonicalized: AtomicUsize,
179 /// Number of times this query is invoked.
180 pub normalize_ty_after_erasing_regions: AtomicUsize,
181 /// Number of times this query is invoked.
182 pub normalize_projection_ty: AtomicUsize,
185 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
186 enum DiagnosticBuilderMethod {
189 SpanSuggestion(String), // suggestion
190 // add more variants as needed to support one-time diagnostics
193 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
194 /// emitting the same message more than once
195 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
196 pub enum DiagnosticMessageId {
197 ErrorId(u16), // EXXXX error code as integer
198 LintId(lint::LintId),
199 StabilityId(u32), // issue number
202 impl From<&'static lint::Lint> for DiagnosticMessageId {
203 fn from(lint: &'static lint::Lint) -> Self {
204 DiagnosticMessageId::LintId(lint::LintId::of(lint))
209 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
210 *self.crate_disambiguator.get()
213 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(
217 ) -> DiagnosticBuilder<'a> {
218 self.diagnostic().struct_span_warn(sp, msg)
220 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(
225 ) -> DiagnosticBuilder<'a> {
226 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
228 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
229 self.diagnostic().struct_warn(msg)
231 pub fn struct_span_err<'a, S: Into<MultiSpan>>(
235 ) -> DiagnosticBuilder<'a> {
236 self.diagnostic().struct_span_err(sp, msg)
238 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(
243 ) -> DiagnosticBuilder<'a> {
244 self.diagnostic().struct_span_err_with_code(sp, msg, code)
246 // FIXME: This method should be removed (every error should have an associated error code).
247 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
248 self.diagnostic().struct_err(msg)
250 pub fn struct_err_with_code<'a>(
254 ) -> DiagnosticBuilder<'a> {
255 self.diagnostic().struct_err_with_code(msg, code)
257 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(
261 ) -> DiagnosticBuilder<'a> {
262 self.diagnostic().struct_span_fatal(sp, msg)
264 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(
269 ) -> DiagnosticBuilder<'a> {
270 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
272 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
273 self.diagnostic().struct_fatal(msg)
276 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
277 self.diagnostic().span_fatal(sp, msg).raise()
279 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
286 .span_fatal_with_code(sp, msg, code)
289 pub fn fatal(&self, msg: &str) -> ! {
290 self.diagnostic().fatal(msg).raise()
292 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
294 self.span_warn(sp, msg);
296 self.span_err(sp, msg);
299 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
300 self.diagnostic().span_err(sp, msg)
302 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
303 self.diagnostic().span_err_with_code(sp, &msg, code)
305 pub fn err(&self, msg: &str) {
306 self.diagnostic().err(msg)
308 pub fn err_count(&self) -> usize {
309 self.diagnostic().err_count()
311 pub fn has_errors(&self) -> bool {
312 self.diagnostic().has_errors()
314 pub fn abort_if_errors(&self) {
315 self.diagnostic().abort_if_errors();
317 pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
318 compile_result_from_err_count(self.err_count())
320 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
324 let old_count = self.err_count();
326 let errors = self.err_count() - old_count;
333 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
334 self.diagnostic().span_warn(sp, msg)
336 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
337 self.diagnostic().span_warn_with_code(sp, msg, code)
339 pub fn warn(&self, msg: &str) {
340 self.diagnostic().warn(msg)
342 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
344 Some(sp) => self.span_warn(sp, msg),
345 None => self.warn(msg),
348 /// Delay a span_bug() call until abort_if_errors()
349 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
350 self.diagnostic().delay_span_bug(sp, msg)
352 pub fn note_without_error(&self, msg: &str) {
353 self.diagnostic().note_without_error(msg)
355 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
356 self.diagnostic().span_note_without_error(sp, msg)
358 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
359 self.diagnostic().span_unimpl(sp, msg)
361 pub fn unimpl(&self, msg: &str) -> ! {
362 self.diagnostic().unimpl(msg)
365 pub fn buffer_lint<S: Into<MultiSpan>>(
367 lint: &'static lint::Lint,
372 match *self.buffered_lints.borrow_mut() {
373 Some(ref mut buffer) => {
374 buffer.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
376 None => bug!("can't buffer lints after HIR lowering"),
380 pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(
382 lint: &'static lint::Lint,
386 diagnostic: BuiltinLintDiagnostics,
388 match *self.buffered_lints.borrow_mut() {
389 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg, diagnostic),
390 None => bug!("can't buffer lints after HIR lowering"),
394 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
395 let id = self.next_node_id.get();
397 match id.as_usize().checked_add(count) {
399 self.next_node_id.set(ast::NodeId::new(next));
401 None => bug!("Input too large, ran out of node ids!"),
406 pub fn next_node_id(&self) -> NodeId {
407 self.reserve_node_ids(1)
409 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
410 &self.parse_sess.span_diagnostic
413 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
414 /// deduplicates on lint ID, span (if any), and message for this `Session`
415 fn diag_once<'a, 'b>(
417 diag_builder: &'b mut DiagnosticBuilder<'a>,
418 method: DiagnosticBuilderMethod,
419 msg_id: DiagnosticMessageId,
421 span_maybe: Option<Span>,
423 let id_span_message = (msg_id, span_maybe, message.to_owned());
424 let fresh = self.one_time_diagnostics
426 .insert(id_span_message);
429 DiagnosticBuilderMethod::Note => {
430 diag_builder.note(message);
432 DiagnosticBuilderMethod::SpanNote => {
433 let span = span_maybe.expect("span_note needs a span");
434 diag_builder.span_note(span, message);
436 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
437 let span = span_maybe.expect("span_suggestion needs a span");
438 diag_builder.span_suggestion(span, message, suggestion);
444 pub fn diag_span_note_once<'a, 'b>(
446 diag_builder: &'b mut DiagnosticBuilder<'a>,
447 msg_id: DiagnosticMessageId,
453 DiagnosticBuilderMethod::SpanNote,
460 pub fn diag_note_once<'a, 'b>(
462 diag_builder: &'b mut DiagnosticBuilder<'a>,
463 msg_id: DiagnosticMessageId,
468 DiagnosticBuilderMethod::Note,
475 pub fn diag_span_suggestion_once<'a, 'b>(
477 diag_builder: &'b mut DiagnosticBuilder<'a>,
478 msg_id: DiagnosticMessageId,
485 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
492 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
493 self.parse_sess.codemap()
495 pub fn verbose(&self) -> bool {
496 self.opts.debugging_opts.verbose
498 pub fn time_passes(&self) -> bool {
499 self.opts.debugging_opts.time_passes
501 pub fn profile_queries(&self) -> bool {
502 self.opts.debugging_opts.profile_queries
503 || self.opts.debugging_opts.profile_queries_and_keys
505 pub fn profile_queries_and_keys(&self) -> bool {
506 self.opts.debugging_opts.profile_queries_and_keys
508 pub fn count_llvm_insns(&self) -> bool {
509 self.opts.debugging_opts.count_llvm_insns
511 pub fn time_llvm_passes(&self) -> bool {
512 self.opts.debugging_opts.time_llvm_passes
514 pub fn codegen_stats(&self) -> bool {
515 self.opts.debugging_opts.codegen_stats
517 pub fn meta_stats(&self) -> bool {
518 self.opts.debugging_opts.meta_stats
520 pub fn asm_comments(&self) -> bool {
521 self.opts.debugging_opts.asm_comments
523 pub fn verify_llvm_ir(&self) -> bool {
524 self.opts.debugging_opts.verify_llvm_ir
526 pub fn borrowck_stats(&self) -> bool {
527 self.opts.debugging_opts.borrowck_stats
529 pub fn print_llvm_passes(&self) -> bool {
530 self.opts.debugging_opts.print_llvm_passes
533 /// Get the features enabled for the current compilation session.
534 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
535 /// dependency tracking. Use tcx.features() instead.
537 pub fn features_untracked(&self) -> &feature_gate::Features {
541 pub fn init_features(&self, features: feature_gate::Features) {
542 self.features.set(features);
545 /// Calculates the flavor of LTO to use for this compilation.
546 pub fn lto(&self) -> config::Lto {
547 // If our target has codegen requirements ignore the command line
548 if self.target.target.options.requires_lto {
549 return config::Lto::Fat;
552 // If the user specified something, return that. If they only said `-C
553 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
554 // then ensure we can't use a ThinLTO.
555 match self.opts.cg.lto {
556 config::Lto::No => {}
557 config::Lto::Yes if self.opts.cli_forced_thinlto_off => return config::Lto::Fat,
558 other => return other,
561 // Ok at this point the target doesn't require anything and the user
562 // hasn't asked for anything. Our next decision is whether or not
563 // we enable "auto" ThinLTO where we use multiple codegen units and
564 // then do ThinLTO over those codegen units. The logic below will
565 // either return `No` or `ThinLocal`.
567 // If processing command line options determined that we're incompatible
568 // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
569 if self.opts.cli_forced_thinlto_off {
570 return config::Lto::No;
573 // If `-Z thinlto` specified process that, but note that this is mostly
574 // a deprecated option now that `-C lto=thin` exists.
575 if let Some(enabled) = self.opts.debugging_opts.thinlto {
577 return config::Lto::ThinLocal;
579 return config::Lto::No;
583 // If there's only one codegen unit and LTO isn't enabled then there's
584 // no need for ThinLTO so just return false.
585 if self.codegen_units() == 1 {
586 return config::Lto::No;
589 // Right now ThinLTO isn't compatible with incremental compilation.
590 if self.opts.incremental.is_some() {
591 return config::Lto::No;
594 // Now we're in "defaults" territory. By default we enable ThinLTO for
595 // optimized compiles (anything greater than O0).
596 match self.opts.optimize {
597 config::OptLevel::No => config::Lto::No,
598 _ => config::Lto::ThinLocal,
602 /// Returns the panic strategy for this compile session. If the user explicitly selected one
603 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
604 pub fn panic_strategy(&self) -> PanicStrategy {
608 .unwrap_or(self.target.target.options.panic_strategy)
610 pub fn linker_flavor(&self) -> LinkerFlavor {
614 .unwrap_or(self.target.target.linker_flavor)
617 pub fn fewer_names(&self) -> bool {
618 let more_names = self.opts
620 .contains_key(&OutputType::LlvmAssembly)
621 || self.opts.output_types.contains_key(&OutputType::Bitcode);
622 self.opts.debugging_opts.fewer_names || !more_names
625 pub fn no_landing_pads(&self) -> bool {
626 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
628 pub fn unstable_options(&self) -> bool {
629 self.opts.debugging_opts.unstable_options
631 pub fn overflow_checks(&self) -> bool {
635 .or(self.opts.debugging_opts.force_overflow_checks)
636 .unwrap_or(self.opts.debug_assertions)
639 pub fn crt_static(&self) -> bool {
640 // If the target does not opt in to crt-static support, use its default.
641 if self.target.target.options.crt_static_respected {
642 self.crt_static_feature()
644 self.target.target.options.crt_static_default
648 pub fn crt_static_feature(&self) -> bool {
649 let requested_features = self.opts.cg.target_feature.split(',');
650 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
651 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
653 // If the target we're compiling for requests a static crt by default,
654 // then see if the `-crt-static` feature was passed to disable that.
655 // Otherwise if we don't have a static crt by default then see if the
656 // `+crt-static` feature was passed.
657 if self.target.target.options.crt_static_default {
664 pub fn target_cpu(&self) -> &str {
665 match self.opts.cg.target_cpu {
667 None => &*self.target.target.options.cpu
671 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
672 if let Some(x) = self.opts.cg.force_frame_pointers {
675 !self.target.target.options.eliminate_frame_pointer
679 /// Returns the symbol name for the registrar function,
680 /// given the crate Svh and the function DefIndex.
681 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
683 "__rustc_plugin_registrar_{}__",
684 disambiguator.to_fingerprint().to_hex()
688 pub fn generate_derive_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
690 "__rustc_derive_registrar_{}__",
691 disambiguator.to_fingerprint().to_hex()
695 pub fn sysroot<'a>(&'a self) -> &'a Path {
696 match self.opts.maybe_sysroot {
697 Some(ref sysroot) => sysroot,
698 None => self.default_sysroot
700 .expect("missing sysroot and default_sysroot in Session"),
703 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
704 filesearch::FileSearch::new(
706 self.opts.target_triple.triple(),
707 &self.opts.search_paths,
711 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
712 filesearch::FileSearch::new(
714 config::host_triple(),
715 &self.opts.search_paths,
720 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
721 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
723 match *incr_comp_session {
724 IncrCompSession::Active {
725 ref mut load_dep_graph,
728 *load_dep_graph = load;
734 pub fn incr_session_load_dep_graph(&self) -> bool {
735 let incr_comp_session = self.incr_comp_session.borrow();
736 match *incr_comp_session {
737 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
742 pub fn init_incr_comp_session(
744 session_dir: PathBuf,
745 lock_file: flock::Lock,
746 load_dep_graph: bool,
748 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
750 if let IncrCompSession::NotInitialized = *incr_comp_session {
753 "Trying to initialize IncrCompSession `{:?}`",
758 *incr_comp_session = IncrCompSession::Active {
759 session_directory: session_dir,
765 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
766 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
768 if let IncrCompSession::Active { .. } = *incr_comp_session {
771 "Trying to finalize IncrCompSession `{:?}`",
776 // Note: This will also drop the lock file, thus unlocking the directory
777 *incr_comp_session = IncrCompSession::Finalized {
778 session_directory: new_directory_path,
782 pub fn mark_incr_comp_session_as_invalid(&self) {
783 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
785 let session_directory = match *incr_comp_session {
786 IncrCompSession::Active {
787 ref session_directory,
789 } => session_directory.clone(),
790 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
792 "Trying to invalidate IncrCompSession `{:?}`",
797 // Note: This will also drop the lock file, thus unlocking the directory
798 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
801 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
802 let incr_comp_session = self.incr_comp_session.borrow();
805 |incr_comp_session| match *incr_comp_session {
806 IncrCompSession::NotInitialized => bug!(
807 "Trying to get session directory from IncrCompSession `{:?}`",
810 IncrCompSession::Active {
811 ref session_directory,
814 | IncrCompSession::Finalized {
815 ref session_directory,
817 | IncrCompSession::InvalidBecauseOfErrors {
818 ref session_directory,
819 } => session_directory,
824 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
825 if self.opts.incremental.is_some() {
826 Some(self.incr_comp_session_dir())
832 pub fn profiler<F: FnOnce(&mut SelfProfiler) -> ()>(&self, f: F) {
833 let mut profiler = self.self_profiling.borrow_mut();
837 pub fn print_profiler_results(&self) {
838 let mut profiler = self.self_profiling.borrow_mut();
839 profiler.print_results(&self.opts);
842 pub fn save_json_results(&self) {
843 let profiler = self.self_profiling.borrow();
844 profiler.save_results(&self.opts);
847 pub fn print_perf_stats(&self) {
849 "Total time spent computing symbol hashes: {}",
850 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
853 "Total time spent decoding DefPath tables: {}",
854 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
856 println!("Total queries canonicalized: {}",
857 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed));
858 println!("normalize_ty_after_erasing_regions: {}",
859 self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed));
860 println!("normalize_projection_ty: {}",
861 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed));
864 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
865 /// This expends fuel if applicable, and records fuel if applicable.
866 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
868 match self.optimization_fuel_crate {
869 Some(ref c) if c == crate_name => {
870 assert!(self.query_threads() == 1);
871 let fuel = self.optimization_fuel_limit.get();
873 if fuel == 0 && !self.out_of_fuel.get() {
874 println!("optimization-fuel-exhausted: {}", msg());
875 self.out_of_fuel.set(true);
877 self.optimization_fuel_limit.set(fuel - 1);
882 match self.print_fuel_crate {
883 Some(ref c) if c == crate_name => {
884 assert!(self.query_threads() == 1);
885 self.print_fuel.set(self.print_fuel.get() + 1);
892 /// Returns the number of query threads that should be used for this
894 pub fn query_threads_from_opts(opts: &config::Options) -> usize {
895 opts.debugging_opts.query_threads.unwrap_or(1)
898 /// Returns the number of query threads that should be used for this
900 pub fn query_threads(&self) -> usize {
901 Self::query_threads_from_opts(&self.opts)
904 /// Returns the number of codegen units that should be used for this
906 pub fn codegen_units(&self) -> usize {
907 if let Some(n) = self.opts.cli_forced_codegen_units {
910 if let Some(n) = self.target.target.options.default_codegen_units {
914 // Why is 16 codegen units the default all the time?
916 // The main reason for enabling multiple codegen units by default is to
917 // leverage the ability for the codegen backend to do codegen and
918 // optimization in parallel. This allows us, especially for large crates, to
919 // make good use of all available resources on the machine once we've
920 // hit that stage of compilation. Large crates especially then often
921 // take a long time in codegen/optimization and this helps us amortize that
924 // Note that a high number here doesn't mean that we'll be spawning a
925 // large number of threads in parallel. The backend of rustc contains
926 // global rate limiting through the `jobserver` crate so we'll never
927 // overload the system with too much work, but rather we'll only be
928 // optimizing when we're otherwise cooperating with other instances of
931 // Rather a high number here means that we should be able to keep a lot
932 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
933 // to build we'll be guaranteed that all cpus will finish pretty closely
934 // to one another and we should make relatively optimal use of system
937 // Note that the main cost of codegen units is that it prevents LLVM
938 // from inlining across codegen units. Users in general don't have a lot
939 // of control over how codegen units are split up so it's our job in the
940 // compiler to ensure that undue performance isn't lost when using
941 // codegen units (aka we can't require everyone to slap `#[inline]` on
944 // If we're compiling at `-O0` then the number doesn't really matter too
945 // much because performance doesn't matter and inlining is ok to lose.
946 // In debug mode we just want to try to guarantee that no cpu is stuck
947 // doing work that could otherwise be farmed to others.
949 // In release mode, however (O1 and above) performance does indeed
950 // matter! To recover the loss in performance due to inlining we'll be
951 // enabling ThinLTO by default (the function for which is just below).
952 // This will ensure that we recover any inlining wins we otherwise lost
953 // through codegen unit partitioning.
957 // Ok that's a lot of words but the basic tl;dr; is that we want a high
958 // number here -- but not too high. Additionally we're "safe" to have it
959 // always at the same number at all optimization levels.
961 // As a result 16 was chosen here! Mostly because it was a power of 2
962 // and most benchmarks agreed it was roughly a local optimum. Not very
967 pub fn teach(&self, code: &DiagnosticId) -> bool {
968 self.opts.debugging_opts.teach && self.parse_sess.span_diagnostic.must_teach(code)
971 /// Are we allowed to use features from the Rust 2018 edition?
972 pub fn rust_2018(&self) -> bool {
973 self.opts.edition >= Edition::Edition2018
976 pub fn edition(&self) -> Edition {
981 pub fn build_session(
982 sopts: config::Options,
983 local_crate_source_file: Option<PathBuf>,
984 registry: errors::registry::Registry,
986 let file_path_mapping = sopts.file_path_mapping();
988 build_session_with_codemap(
990 local_crate_source_file,
992 Lrc::new(codemap::CodeMap::new(file_path_mapping)),
997 pub fn build_session_with_codemap(
998 sopts: config::Options,
999 local_crate_source_file: Option<PathBuf>,
1000 registry: errors::registry::Registry,
1001 codemap: Lrc<codemap::CodeMap>,
1002 emitter_dest: Option<Box<dyn Write + Send>>,
1004 // FIXME: This is not general enough to make the warning lint completely override
1005 // normal diagnostic warnings, since the warning lint can also be denied and changed
1006 // later via the source code.
1007 let warnings_allow = sopts
1010 .filter(|&&(ref key, _)| *key == "warnings")
1011 .map(|&(_, ref level)| *level == lint::Allow)
1014 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1016 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1018 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
1019 let report_delayed_bugs = sopts.debugging_opts.report_delayed_bugs;
1021 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
1023 let emitter: Box<dyn Emitter + sync::Send> =
1024 match (sopts.error_format, emitter_dest) {
1025 (config::ErrorOutputType::HumanReadable(color_config), None) => Box::new(
1026 EmitterWriter::stderr(
1028 Some(codemap.clone()),
1030 sopts.debugging_opts.teach,
1031 ).ui_testing(sopts.debugging_opts.ui_testing),
1033 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => Box::new(
1034 EmitterWriter::new(dst, Some(codemap.clone()), false, false)
1035 .ui_testing(sopts.debugging_opts.ui_testing),
1037 (config::ErrorOutputType::Json(pretty), None) => Box::new(
1038 JsonEmitter::stderr(
1042 ).ui_testing(sopts.debugging_opts.ui_testing),
1044 (config::ErrorOutputType::Json(pretty), Some(dst)) => Box::new(
1050 ).ui_testing(sopts.debugging_opts.ui_testing),
1052 (config::ErrorOutputType::Short(color_config), None) => Box::new(
1053 EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false),
1055 (config::ErrorOutputType::Short(_), Some(dst)) => {
1056 Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
1060 let diagnostic_handler = errors::Handler::with_emitter_and_flags(
1062 errors::HandlerFlags {
1065 report_delayed_bugs,
1066 external_macro_backtrace,
1067 ..Default::default()
1071 build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap)
1074 pub fn build_session_(
1075 sopts: config::Options,
1076 local_crate_source_file: Option<PathBuf>,
1077 span_diagnostic: errors::Handler,
1078 codemap: Lrc<codemap::CodeMap>,
1080 let host_triple = TargetTriple::from_triple(config::host_triple());
1081 let host = match Target::search(&host_triple) {
1085 .fatal(&format!("Error loading host specification: {}", e))
1089 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
1091 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
1092 let default_sysroot = match sopts.maybe_sysroot {
1094 None => Some(filesearch::get_or_default_sysroot()),
1097 let file_path_mapping = sopts.file_path_mapping();
1099 let local_crate_source_file =
1100 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1102 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1103 let optimization_fuel_limit =
1104 LockCell::new(sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0));
1105 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1106 let print_fuel = LockCell::new(0);
1108 let working_dir = match env::current_dir() {
1110 Err(e) => p_s.span_diagnostic
1111 .fatal(&format!("Current directory is invalid: {}", e))
1114 let working_dir = file_path_mapping.map_prefix(working_dir);
1116 let sess = Session {
1121 // For a library crate, this is always none
1122 entry_fn: Once::new(),
1123 plugin_registrar_fn: Once::new(),
1124 derive_registrar_fn: Once::new(),
1126 local_crate_source_file,
1128 lint_store: RwLock::new(lint::LintStore::new()),
1129 buffered_lints: Lock::new(Some(lint::LintBuffer::new())),
1130 one_time_diagnostics: Lock::new(FxHashSet()),
1131 plugin_llvm_passes: OneThread::new(RefCell::new(Vec::new())),
1132 plugin_attributes: OneThread::new(RefCell::new(Vec::new())),
1133 crate_types: Once::new(),
1134 dependency_formats: Once::new(),
1135 crate_disambiguator: Once::new(),
1136 features: Once::new(),
1137 recursion_limit: Once::new(),
1138 type_length_limit: Once::new(),
1139 const_eval_stack_frame_limit: 100,
1140 next_node_id: OneThread::new(Cell::new(NodeId::new(1))),
1141 injected_allocator: Once::new(),
1142 allocator_kind: Once::new(),
1143 injected_panic_runtime: Once::new(),
1144 imported_macro_spans: OneThread::new(RefCell::new(HashMap::new())),
1145 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1146 ignored_attr_names: ich::compute_ignored_attr_names(),
1147 self_profiling: Lock::new(SelfProfiler::new()),
1148 profile_channel: Lock::new(None),
1149 perf_stats: PerfStats {
1150 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1151 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1152 queries_canonicalized: AtomicUsize::new(0),
1153 normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1154 normalize_projection_ty: AtomicUsize::new(0),
1156 code_stats: Lock::new(CodeStats::new()),
1157 optimization_fuel_crate,
1158 optimization_fuel_limit,
1161 out_of_fuel: LockCell::new(false),
1162 // Note that this is unsafe because it may misinterpret file descriptors
1163 // on Unix as jobserver file descriptors. We hopefully execute this near
1164 // the beginning of the process though to ensure we don't get false
1165 // positives, or in other words we try to execute this before we open
1166 // any file descriptors ourselves.
1168 // Pick a "reasonable maximum" if we don't otherwise have
1169 // a jobserver in our environment, capping out at 32 so we
1170 // don't take everything down by hogging the process run queue.
1171 // The fixed number is used to have deterministic compilation
1174 // Also note that we stick this in a global because there could be
1175 // multiple `Session` instances in this process, and the jobserver is
1178 static mut GLOBAL_JOBSERVER: *mut Client = 0 as *mut _;
1179 static INIT: std::sync::Once = std::sync::ONCE_INIT;
1181 let client = Client::from_env().unwrap_or_else(|| {
1182 Client::new(32).expect("failed to create jobserver")
1184 GLOBAL_JOBSERVER = Box::into_raw(Box::new(client));
1186 (*GLOBAL_JOBSERVER).clone()
1188 has_global_allocator: Once::new(),
1189 driver_lint_caps: FxHashMap(),
1195 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1196 /// compiler. Together with the crate-name forms a unique global identifier for
1198 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1199 pub struct CrateDisambiguator(Fingerprint);
1201 impl CrateDisambiguator {
1202 pub fn to_fingerprint(self) -> Fingerprint {
1207 impl From<Fingerprint> for CrateDisambiguator {
1208 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1209 CrateDisambiguator(fingerprint)
1213 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1215 /// Holds data on the current incremental compilation session, if there is one.
1217 pub enum IncrCompSession {
1218 /// This is the state the session will be in until the incr. comp. dir is
1221 /// This is the state during which the session directory is private and can
1224 session_directory: PathBuf,
1225 lock_file: flock::Lock,
1226 load_dep_graph: bool,
1228 /// This is the state after the session directory has been finalized. In this
1229 /// state, the contents of the directory must not be modified any more.
1230 Finalized { session_directory: PathBuf },
1231 /// This is an error state that is reached when some compilation error has
1232 /// occurred. It indicates that the contents of the session directory must
1233 /// not be used, since they might be invalid.
1234 InvalidBecauseOfErrors { session_directory: PathBuf },
1237 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1238 let emitter: Box<dyn Emitter + sync::Send> = match output {
1239 config::ErrorOutputType::HumanReadable(color_config) => {
1240 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1242 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1243 config::ErrorOutputType::Short(color_config) => {
1244 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1247 let handler = errors::Handler::with_emitter(true, false, emitter);
1248 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1249 errors::FatalError.raise();
1252 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1253 let emitter: Box<dyn Emitter + sync::Send> = match output {
1254 config::ErrorOutputType::HumanReadable(color_config) => {
1255 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1257 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1258 config::ErrorOutputType::Short(color_config) => {
1259 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1262 let handler = errors::Handler::with_emitter(true, false, emitter);
1263 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1266 #[derive(Copy, Clone, Debug)]
1267 pub enum CompileIncomplete {
1269 Errored(ErrorReported),
1271 impl From<ErrorReported> for CompileIncomplete {
1272 fn from(err: ErrorReported) -> CompileIncomplete {
1273 CompileIncomplete::Errored(err)
1276 pub type CompileResult = Result<(), CompileIncomplete>;
1278 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1282 Err(CompileIncomplete::Errored(ErrorReported))
1288 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1289 // this wrapper mostly exists so I don't have to write a fully
1290 // qualified path of None::<Span> inside the bug!() macro definition
1291 opt_span_bug_fmt(file, line, None::<Span>, args);
1296 pub fn span_bug_fmt<S: Into<MultiSpan>>(
1300 args: fmt::Arguments,
1302 opt_span_bug_fmt(file, line, Some(span), args);
1305 fn opt_span_bug_fmt<S: Into<MultiSpan>>(
1309 args: fmt::Arguments,
1311 tls::with_opt(move |tcx| {
1312 let msg = format!("{}:{}: {}", file, line, args);
1314 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1315 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1316 (None, _) => panic!(msg),