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::{DebugInfoLevel, OutputType, Epoch};
25 use util::nodemap::{FxHashMap, FxHashSet};
26 use util::common::{duration_to_secs_str, ErrorReported};
28 use rustc_data_structures::sync::Lrc;
30 use syntax::ast::NodeId;
31 use errors::{self, DiagnosticBuilder, DiagnosticId};
32 use errors::emitter::{Emitter, EmitterWriter};
33 use syntax::json::JsonEmitter;
34 use syntax::feature_gate;
35 use syntax::symbol::Symbol;
37 use syntax::parse::ParseSess;
38 use syntax::{ast, codemap};
39 use syntax::feature_gate::AttributeType;
40 use syntax_pos::{Span, MultiSpan};
42 use rustc_back::{LinkerFlavor, PanicStrategy};
43 use rustc_back::target::Target;
44 use rustc_data_structures::flock;
45 use jobserver::Client;
47 use std::cell::{self, Cell, RefCell};
48 use std::collections::HashMap;
52 use std::path::{Path, PathBuf};
53 use std::sync::{Once, ONCE_INIT};
54 use std::time::Duration;
61 /// Represents the data associated with a compilation
62 /// session for a single crate.
64 pub target: config::Config,
66 pub opts: config::Options,
67 pub parse_sess: ParseSess,
68 /// For a library crate, this is always none
69 pub entry_fn: RefCell<Option<(NodeId, Span)>>,
70 pub entry_type: Cell<Option<config::EntryFnType>>,
71 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
72 pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
73 pub default_sysroot: Option<PathBuf>,
74 /// The name of the root source file of the crate, in the local file system.
75 /// `None` means that there is no source file.
76 pub local_crate_source_file: Option<PathBuf>,
77 /// The directory the compiler has been executed in plus a flag indicating
78 /// if the value stored here has been affected by path remapping.
79 pub working_dir: (PathBuf, bool),
80 pub lint_store: RefCell<lint::LintStore>,
81 pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
82 /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
83 /// (sub)diagnostics that have been set once, but should not be set again,
84 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
85 pub one_time_diagnostics: RefCell<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
86 pub plugin_llvm_passes: RefCell<Vec<String>>,
87 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
88 pub crate_types: RefCell<Vec<config::CrateType>>,
89 pub dependency_formats: RefCell<dependency_format::Dependencies>,
90 /// The crate_disambiguator is constructed out of all the `-C metadata`
91 /// arguments passed to the compiler. Its value together with the crate-name
92 /// forms a unique global identifier for the crate. It is used to allow
93 /// multiple crates with the same name to coexist. See the
94 /// trans::back::symbol_names module for more information.
95 pub crate_disambiguator: RefCell<Option<CrateDisambiguator>>,
97 features: RefCell<Option<feature_gate::Features>>,
99 /// The maximum recursion limit for potentially infinitely recursive
100 /// operations such as auto-dereference and monomorphization.
101 pub recursion_limit: Cell<usize>,
103 /// The maximum length of types during monomorphization.
104 pub type_length_limit: Cell<usize>,
106 /// The metadata::creader module may inject an allocator/panic_runtime
107 /// dependency if it didn't already find one, and this tracks what was
109 pub injected_allocator: Cell<Option<CrateNum>>,
110 pub allocator_kind: Cell<Option<AllocatorKind>>,
111 pub injected_panic_runtime: Cell<Option<CrateNum>>,
113 /// Map from imported macro spans (which consist of
114 /// the localized span for the macro body) to the
115 /// macro name and definition span in the source crate.
116 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
118 incr_comp_session: RefCell<IncrCompSession>,
120 /// A cache of attributes ignored by StableHashingContext
121 pub ignored_attr_names: FxHashSet<Symbol>,
123 /// Some measurements that are being gathered during compilation.
124 pub perf_stats: PerfStats,
126 /// Data about code being compiled, gathered during compilation.
127 pub code_stats: RefCell<CodeStats>,
129 next_node_id: Cell<ast::NodeId>,
131 /// If -zfuel=crate=n is specified, Some(crate).
132 optimization_fuel_crate: Option<String>,
133 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
134 optimization_fuel_limit: Cell<u64>,
135 /// We're rejecting all further optimizations.
136 out_of_fuel: Cell<bool>,
138 // The next two are public because the driver needs to read them.
140 /// If -zprint-fuel=crate, Some(crate).
141 pub print_fuel_crate: Option<String>,
142 /// Always set to zero and incremented so that we can print fuel expended by a crate.
143 pub print_fuel: Cell<u64>,
145 /// Loaded up early on in the initialization of this `Session` to avoid
146 /// false positives about a job server in our environment.
147 pub jobserver_from_env: Option<Client>,
149 /// Metadata about the allocators for the current crate being compiled
150 pub has_global_allocator: Cell<bool>,
153 pub struct PerfStats {
154 /// The accumulated time needed for computing the SVH of the crate
155 pub svh_time: Cell<Duration>,
156 /// The accumulated time spent on computing incr. comp. hashes
157 pub incr_comp_hashes_time: Cell<Duration>,
158 /// The number of incr. comp. hash computations performed
159 pub incr_comp_hashes_count: Cell<u64>,
160 /// The number of bytes hashed when computing ICH values
161 pub incr_comp_bytes_hashed: Cell<u64>,
162 /// The accumulated time spent on computing symbol hashes
163 pub symbol_hash_time: Cell<Duration>,
164 /// The accumulated time spent decoding def path tables from metadata
165 pub decode_def_path_tables_time: Cell<Duration>,
168 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
169 enum DiagnosticBuilderMethod {
172 SpanSuggestion(String), // suggestion
173 // add more variants as needed to support one-time diagnostics
176 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
177 /// emitting the same message more than once
178 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
179 pub enum DiagnosticMessageId {
180 ErrorId(u16), // EXXXX error code as integer
181 LintId(lint::LintId),
182 StabilityId(u32) // issue number
185 impl From<&'static lint::Lint> for DiagnosticMessageId {
186 fn from(lint: &'static lint::Lint) -> Self {
187 DiagnosticMessageId::LintId(lint::LintId::of(lint))
192 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
193 match *self.crate_disambiguator.borrow() {
194 Some(value) => value,
195 None => bug!("accessing disambiguator before initialization"),
199 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
202 -> DiagnosticBuilder<'a> {
203 self.diagnostic().struct_span_warn(sp, msg)
205 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
209 -> DiagnosticBuilder<'a> {
210 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
212 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
213 self.diagnostic().struct_warn(msg)
215 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
218 -> DiagnosticBuilder<'a> {
219 self.diagnostic().struct_span_err(sp, msg)
221 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
225 -> DiagnosticBuilder<'a> {
226 self.diagnostic().struct_span_err_with_code(sp, msg, code)
228 // FIXME: This method should be removed (every error should have an associated error code).
229 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
230 self.diagnostic().struct_err(msg)
232 pub fn struct_err_with_code<'a>(
236 ) -> DiagnosticBuilder<'a> {
237 self.diagnostic().struct_err_with_code(msg, code)
239 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
242 -> DiagnosticBuilder<'a> {
243 self.diagnostic().struct_span_fatal(sp, msg)
245 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
249 -> DiagnosticBuilder<'a> {
250 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
252 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
253 self.diagnostic().struct_fatal(msg)
256 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
257 self.diagnostic().span_fatal(sp, msg).raise()
259 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
265 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
267 pub fn fatal(&self, msg: &str) -> ! {
268 self.diagnostic().fatal(msg).raise()
270 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
272 self.span_warn(sp, msg);
274 self.span_err(sp, msg);
277 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
278 self.diagnostic().span_err(sp, msg)
280 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
281 self.diagnostic().span_err_with_code(sp, &msg, code)
283 pub fn err(&self, msg: &str) {
284 self.diagnostic().err(msg)
286 pub fn err_count(&self) -> usize {
287 self.diagnostic().err_count()
289 pub fn has_errors(&self) -> bool {
290 self.diagnostic().has_errors()
292 pub fn abort_if_errors(&self) {
293 self.diagnostic().abort_if_errors();
295 pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
296 compile_result_from_err_count(self.err_count())
298 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
299 where F: FnOnce() -> T
301 let old_count = self.err_count();
303 let errors = self.err_count() - old_count;
310 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
311 self.diagnostic().span_warn(sp, msg)
313 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
314 self.diagnostic().span_warn_with_code(sp, msg, code)
316 pub fn warn(&self, msg: &str) {
317 self.diagnostic().warn(msg)
319 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
321 Some(sp) => self.span_warn(sp, msg),
322 None => self.warn(msg),
325 /// Delay a span_bug() call until abort_if_errors()
326 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
327 self.diagnostic().delay_span_bug(sp, msg)
329 pub fn note_without_error(&self, msg: &str) {
330 self.diagnostic().note_without_error(msg)
332 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
333 self.diagnostic().span_note_without_error(sp, msg)
335 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
336 self.diagnostic().span_unimpl(sp, msg)
338 pub fn unimpl(&self, msg: &str) -> ! {
339 self.diagnostic().unimpl(msg)
342 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
343 lint: &'static lint::Lint,
347 match *self.buffered_lints.borrow_mut() {
348 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
349 msg, BuiltinLintDiagnostics::Normal),
350 None => bug!("can't buffer lints after HIR lowering"),
354 pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(&self,
355 lint: &'static lint::Lint, id: ast::NodeId, sp: S,
356 msg: &str, diagnostic: BuiltinLintDiagnostics) {
357 match *self.buffered_lints.borrow_mut() {
358 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
360 None => bug!("can't buffer lints after HIR lowering"),
364 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
365 let id = self.next_node_id.get();
367 match id.as_usize().checked_add(count) {
369 self.next_node_id.set(ast::NodeId::new(next));
371 None => bug!("Input too large, ran out of node ids!")
376 pub fn next_node_id(&self) -> NodeId {
377 self.reserve_node_ids(1)
379 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
380 &self.parse_sess.span_diagnostic
383 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
384 /// deduplicates on lint ID, span (if any), and message for this `Session`
385 fn diag_once<'a, 'b>(&'a self,
386 diag_builder: &'b mut DiagnosticBuilder<'a>,
387 method: DiagnosticBuilderMethod,
388 msg_id: DiagnosticMessageId,
390 span_maybe: Option<Span>) {
392 let id_span_message = (msg_id, span_maybe, message.to_owned());
393 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
396 DiagnosticBuilderMethod::Note => {
397 diag_builder.note(message);
399 DiagnosticBuilderMethod::SpanNote => {
400 let span = span_maybe.expect("span_note needs a span");
401 diag_builder.span_note(span, message);
403 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
404 let span = span_maybe.expect("span_suggestion needs a span");
405 diag_builder.span_suggestion(span, message, suggestion);
411 pub fn diag_span_note_once<'a, 'b>(&'a self,
412 diag_builder: &'b mut DiagnosticBuilder<'a>,
413 msg_id: DiagnosticMessageId, span: Span, message: &str) {
414 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote,
415 msg_id, message, Some(span));
418 pub fn diag_note_once<'a, 'b>(&'a self,
419 diag_builder: &'b mut DiagnosticBuilder<'a>,
420 msg_id: DiagnosticMessageId, message: &str) {
421 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
424 pub fn diag_span_suggestion_once<'a, 'b>(&'a self,
425 diag_builder: &'b mut DiagnosticBuilder<'a>,
426 msg_id: DiagnosticMessageId,
429 suggestion: String) {
430 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanSuggestion(suggestion),
431 msg_id, message, Some(span));
434 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
435 self.parse_sess.codemap()
437 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
438 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
439 pub fn profile_queries(&self) -> bool {
440 self.opts.debugging_opts.profile_queries ||
441 self.opts.debugging_opts.profile_queries_and_keys
443 pub fn profile_queries_and_keys(&self) -> bool {
444 self.opts.debugging_opts.profile_queries_and_keys
446 pub fn count_llvm_insns(&self) -> bool {
447 self.opts.debugging_opts.count_llvm_insns
449 pub fn time_llvm_passes(&self) -> bool {
450 self.opts.debugging_opts.time_llvm_passes
452 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
453 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
454 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
455 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
456 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
457 pub fn print_llvm_passes(&self) -> bool {
458 self.opts.debugging_opts.print_llvm_passes
461 /// Get the features enabled for the current compilation session.
462 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
463 /// dependency tracking. Use tcx.features() instead.
465 pub fn features_untracked(&self) -> cell::Ref<feature_gate::Features> {
466 let features = self.features.borrow();
468 if features.is_none() {
469 bug!("Access to Session::features before it is initialized");
472 cell::Ref::map(features, |r| r.as_ref().unwrap())
475 pub fn init_features(&self, features: feature_gate::Features) {
476 *(self.features.borrow_mut()) = Some(features);
479 /// If true, we should gather causal information during NLL
480 /// checking. This will eventually be the normal thing, but right
481 /// now it is too unoptimized.
482 pub fn nll_dump_cause(&self) -> bool {
483 self.opts.debugging_opts.nll_dump_cause
486 /// Calculates the flavor of LTO to use for this compilation.
487 pub fn lto(&self) -> config::Lto {
488 // If our target has codegen requirements ignore the command line
489 if self.target.target.options.requires_lto {
490 return config::Lto::Fat
493 // If the user specified something, return that. If they only said `-C
494 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
495 // then ensure we can't use a ThinLTO.
496 match self.opts.cg.lto {
497 config::Lto::No => {}
498 config::Lto::Yes if self.opts.cli_forced_thinlto_off => {
499 return config::Lto::Fat
501 other => return other,
504 // Ok at this point the target doesn't require anything and the user
505 // hasn't asked for anything. Our next decision is whether or not
506 // we enable "auto" ThinLTO where we use multiple codegen units and
507 // then do ThinLTO over those codegen units. The logic below will
508 // either return `No` or `ThinLocal`.
510 // If processing command line options determined that we're incompatible
511 // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
512 if self.opts.cli_forced_thinlto_off {
513 return config::Lto::No
516 // If `-Z thinlto` specified process that, but note that this is mostly
517 // a deprecated option now that `-C lto=thin` exists.
518 if let Some(enabled) = self.opts.debugging_opts.thinlto {
520 return config::Lto::ThinLocal
522 return config::Lto::No
526 // If there's only one codegen unit and LTO isn't enabled then there's
527 // no need for ThinLTO so just return false.
528 if self.codegen_units() == 1 {
529 return config::Lto::No
532 // Right now ThinLTO isn't compatible with incremental compilation.
533 if self.opts.incremental.is_some() {
534 return config::Lto::No
537 // Now we're in "defaults" territory. By default we enable ThinLTO for
538 // optimized compiles (anything greater than O0).
539 match self.opts.optimize {
540 config::OptLevel::No => config::Lto::No,
541 _ => config::Lto::ThinLocal,
545 /// Returns the panic strategy for this compile session. If the user explicitly selected one
546 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
547 pub fn panic_strategy(&self) -> PanicStrategy {
548 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
550 pub fn linker_flavor(&self) -> LinkerFlavor {
551 self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
554 pub fn fewer_names(&self) -> bool {
555 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly) ||
556 self.opts.output_types.contains_key(&OutputType::Bitcode);
557 self.opts.debugging_opts.fewer_names || !more_names
560 pub fn no_landing_pads(&self) -> bool {
561 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
563 pub fn unstable_options(&self) -> bool {
564 self.opts.debugging_opts.unstable_options
566 pub fn nonzeroing_move_hints(&self) -> bool {
567 self.opts.debugging_opts.enable_nonzeroing_move_hints
569 pub fn overflow_checks(&self) -> bool {
570 self.opts.cg.overflow_checks
571 .or(self.opts.debugging_opts.force_overflow_checks)
572 .unwrap_or(self.opts.debug_assertions)
575 pub fn crt_static(&self) -> bool {
576 // If the target does not opt in to crt-static support, use its default.
577 if self.target.target.options.crt_static_respected {
578 self.crt_static_feature()
580 self.target.target.options.crt_static_default
584 pub fn crt_static_feature(&self) -> bool {
585 let requested_features = self.opts.cg.target_feature.split(',');
586 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
587 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
589 // If the target we're compiling for requests a static crt by default,
590 // then see if the `-crt-static` feature was passed to disable that.
591 // Otherwise if we don't have a static crt by default then see if the
592 // `+crt-static` feature was passed.
593 if self.target.target.options.crt_static_default {
600 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
601 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
602 !self.target.target.options.eliminate_frame_pointer
605 /// Returns the symbol name for the registrar function,
606 /// given the crate Svh and the function DefIndex.
607 pub fn generate_plugin_registrar_symbol(&self,
608 disambiguator: CrateDisambiguator)
610 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
613 pub fn generate_derive_registrar_symbol(&self,
614 disambiguator: CrateDisambiguator)
616 format!("__rustc_derive_registrar_{}__", disambiguator.to_fingerprint().to_hex())
619 pub fn sysroot<'a>(&'a self) -> &'a Path {
620 match self.opts.maybe_sysroot {
621 Some (ref sysroot) => sysroot,
622 None => self.default_sysroot.as_ref()
623 .expect("missing sysroot and default_sysroot in Session")
626 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
627 filesearch::FileSearch::new(self.sysroot(),
628 &self.opts.target_triple,
629 &self.opts.search_paths,
632 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
633 filesearch::FileSearch::new(
635 config::host_triple(),
636 &self.opts.search_paths,
640 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
641 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
643 match *incr_comp_session {
644 IncrCompSession::Active { ref mut load_dep_graph, .. } => {
645 *load_dep_graph = load;
651 pub fn incr_session_load_dep_graph(&self) -> bool {
652 let incr_comp_session = self.incr_comp_session.borrow();
653 match *incr_comp_session {
654 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
659 pub fn init_incr_comp_session(&self,
660 session_dir: PathBuf,
661 lock_file: flock::Lock,
662 load_dep_graph: bool) {
663 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
665 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
666 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
669 *incr_comp_session = IncrCompSession::Active {
670 session_directory: session_dir,
676 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
677 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
679 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
680 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
683 // Note: This will also drop the lock file, thus unlocking the directory
684 *incr_comp_session = IncrCompSession::Finalized {
685 session_directory: new_directory_path,
689 pub fn mark_incr_comp_session_as_invalid(&self) {
690 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
692 let session_directory = match *incr_comp_session {
693 IncrCompSession::Active { ref session_directory, .. } => {
694 session_directory.clone()
696 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
697 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
701 // Note: This will also drop the lock file, thus unlocking the directory
702 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
707 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
708 let incr_comp_session = self.incr_comp_session.borrow();
709 cell::Ref::map(incr_comp_session, |incr_comp_session| {
710 match *incr_comp_session {
711 IncrCompSession::NotInitialized => {
712 bug!("Trying to get session directory from IncrCompSession `{:?}`",
715 IncrCompSession::Active { ref session_directory, .. } |
716 IncrCompSession::Finalized { ref session_directory } |
717 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
724 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
725 if self.opts.incremental.is_some() {
726 Some(self.incr_comp_session_dir())
732 pub fn print_perf_stats(&self) {
733 println!("Total time spent computing SVHs: {}",
734 duration_to_secs_str(self.perf_stats.svh_time.get()));
735 println!("Total time spent computing incr. comp. hashes: {}",
736 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
737 println!("Total number of incr. comp. hashes computed: {}",
738 self.perf_stats.incr_comp_hashes_count.get());
739 println!("Total number of bytes hashed for incr. comp.: {}",
740 self.perf_stats.incr_comp_bytes_hashed.get());
741 if self.perf_stats.incr_comp_hashes_count.get() != 0 {
742 println!("Average bytes hashed per incr. comp. HIR node: {}",
743 self.perf_stats.incr_comp_bytes_hashed.get() /
744 self.perf_stats.incr_comp_hashes_count.get());
746 println!("Average bytes hashed per incr. comp. HIR node: N/A");
748 println!("Total time spent computing symbol hashes: {}",
749 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
750 println!("Total time spent decoding DefPath tables: {}",
751 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
754 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
755 /// This expends fuel if applicable, and records fuel if applicable.
756 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
758 match self.optimization_fuel_crate {
759 Some(ref c) if c == crate_name => {
760 let fuel = self.optimization_fuel_limit.get();
762 if fuel == 0 && !self.out_of_fuel.get() {
763 println!("optimization-fuel-exhausted: {}", msg());
764 self.out_of_fuel.set(true);
766 self.optimization_fuel_limit.set(fuel-1);
771 match self.print_fuel_crate {
772 Some(ref c) if c == crate_name=> {
773 self.print_fuel.set(self.print_fuel.get()+1);
780 /// Returns the number of query threads that should be used for this
782 pub fn query_threads(&self) -> usize {
783 self.opts.debugging_opts.query_threads.unwrap_or(1)
786 /// Returns the number of codegen units that should be used for this
788 pub fn codegen_units(&self) -> usize {
789 if let Some(n) = self.opts.cli_forced_codegen_units {
792 if let Some(n) = self.target.target.options.default_codegen_units {
796 // Why is 16 codegen units the default all the time?
798 // The main reason for enabling multiple codegen units by default is to
799 // leverage the ability for the trans backend to do translation and
800 // codegen in parallel. This allows us, especially for large crates, to
801 // make good use of all available resources on the machine once we've
802 // hit that stage of compilation. Large crates especially then often
803 // take a long time in trans/codegen and this helps us amortize that
806 // Note that a high number here doesn't mean that we'll be spawning a
807 // large number of threads in parallel. The backend of rustc contains
808 // global rate limiting through the `jobserver` crate so we'll never
809 // overload the system with too much work, but rather we'll only be
810 // optimizing when we're otherwise cooperating with other instances of
813 // Rather a high number here means that we should be able to keep a lot
814 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
815 // to build we'll be guaranteed that all cpus will finish pretty closely
816 // to one another and we should make relatively optimal use of system
819 // Note that the main cost of codegen units is that it prevents LLVM
820 // from inlining across codegen units. Users in general don't have a lot
821 // of control over how codegen units are split up so it's our job in the
822 // compiler to ensure that undue performance isn't lost when using
823 // codegen units (aka we can't require everyone to slap `#[inline]` on
826 // If we're compiling at `-O0` then the number doesn't really matter too
827 // much because performance doesn't matter and inlining is ok to lose.
828 // In debug mode we just want to try to guarantee that no cpu is stuck
829 // doing work that could otherwise be farmed to others.
831 // In release mode, however (O1 and above) performance does indeed
832 // matter! To recover the loss in performance due to inlining we'll be
833 // enabling ThinLTO by default (the function for which is just below).
834 // This will ensure that we recover any inlining wins we otherwise lost
835 // through codegen unit partitioning.
839 // Ok that's a lot of words but the basic tl;dr; is that we want a high
840 // number here -- but not too high. Additionally we're "safe" to have it
841 // always at the same number at all optimization levels.
843 // As a result 16 was chosen here! Mostly because it was a power of 2
844 // and most benchmarks agreed it was roughly a local optimum. Not very
849 pub fn teach(&self, code: &DiagnosticId) -> bool {
850 self.opts.debugging_opts.teach && !self.parse_sess.span_diagnostic.code_emitted(code)
853 /// Are we allowed to use features from the Rust 2018 epoch?
854 pub fn rust_2018(&self) -> bool {
855 self.opts.debugging_opts.epoch >= Epoch::Epoch2018
858 pub fn epoch(&self) -> Epoch {
859 self.opts.debugging_opts.epoch
863 pub fn build_session(sopts: config::Options,
864 local_crate_source_file: Option<PathBuf>,
865 registry: errors::registry::Registry)
867 let file_path_mapping = sopts.file_path_mapping();
869 build_session_with_codemap(sopts,
870 local_crate_source_file,
872 Lrc::new(codemap::CodeMap::new(file_path_mapping)),
876 pub fn build_session_with_codemap(sopts: config::Options,
877 local_crate_source_file: Option<PathBuf>,
878 registry: errors::registry::Registry,
879 codemap: Lrc<codemap::CodeMap>,
880 emitter_dest: Option<Box<dyn Write + Send>>)
882 // FIXME: This is not general enough to make the warning lint completely override
883 // normal diagnostic warnings, since the warning lint can also be denied and changed
884 // later via the source code.
885 let warnings_allow = sopts.lint_opts
887 .filter(|&&(ref key, _)| *key == "warnings")
888 .map(|&(_, ref level)| *level == lint::Allow)
891 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
893 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
895 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
897 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
899 let emitter: Box<dyn Emitter> = match (sopts.error_format, emitter_dest) {
900 (config::ErrorOutputType::HumanReadable(color_config), None) => {
901 Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()),
902 false, sopts.debugging_opts.teach)
903 .ui_testing(sopts.debugging_opts.ui_testing))
905 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
906 Box::new(EmitterWriter::new(dst, Some(codemap.clone()),
908 .ui_testing(sopts.debugging_opts.ui_testing))
910 (config::ErrorOutputType::Json(pretty), None) => {
911 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone(),
912 pretty, sopts.debugging_opts.approximate_suggestions)
913 .ui_testing(sopts.debugging_opts.ui_testing))
915 (config::ErrorOutputType::Json(pretty), Some(dst)) => {
916 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone(),
917 pretty, sopts.debugging_opts.approximate_suggestions)
918 .ui_testing(sopts.debugging_opts.ui_testing))
920 (config::ErrorOutputType::Short(color_config), None) => {
921 Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false))
923 (config::ErrorOutputType::Short(_), Some(dst)) => {
924 Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
928 let diagnostic_handler =
929 errors::Handler::with_emitter_and_flags(
931 errors::HandlerFlags {
934 external_macro_backtrace,
935 .. Default::default()
938 build_session_(sopts,
939 local_crate_source_file,
944 pub fn build_session_(sopts: config::Options,
945 local_crate_source_file: Option<PathBuf>,
946 span_diagnostic: errors::Handler,
947 codemap: Lrc<codemap::CodeMap>)
949 let host = match Target::search(config::host_triple()) {
952 span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise();
955 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
957 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
958 let default_sysroot = match sopts.maybe_sysroot {
960 None => Some(filesearch::get_or_default_sysroot())
963 let file_path_mapping = sopts.file_path_mapping();
965 let local_crate_source_file = local_crate_source_file.map(|path| {
966 file_path_mapping.map_prefix(path).0
969 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
970 let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
971 .map(|i| i.1).unwrap_or(0));
972 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
973 let print_fuel = Cell::new(0);
975 let working_dir = match env::current_dir() {
978 p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
981 let working_dir = file_path_mapping.map_prefix(working_dir);
988 // For a library crate, this is always none
989 entry_fn: RefCell::new(None),
990 entry_type: Cell::new(None),
991 plugin_registrar_fn: Cell::new(None),
992 derive_registrar_fn: Cell::new(None),
994 local_crate_source_file,
996 lint_store: RefCell::new(lint::LintStore::new()),
997 buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
998 one_time_diagnostics: RefCell::new(FxHashSet()),
999 plugin_llvm_passes: RefCell::new(Vec::new()),
1000 plugin_attributes: RefCell::new(Vec::new()),
1001 crate_types: RefCell::new(Vec::new()),
1002 dependency_formats: RefCell::new(FxHashMap()),
1003 crate_disambiguator: RefCell::new(None),
1004 features: RefCell::new(None),
1005 recursion_limit: Cell::new(64),
1006 type_length_limit: Cell::new(1048576),
1007 next_node_id: Cell::new(NodeId::new(1)),
1008 injected_allocator: Cell::new(None),
1009 allocator_kind: Cell::new(None),
1010 injected_panic_runtime: Cell::new(None),
1011 imported_macro_spans: RefCell::new(HashMap::new()),
1012 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
1013 ignored_attr_names: ich::compute_ignored_attr_names(),
1014 perf_stats: PerfStats {
1015 svh_time: Cell::new(Duration::from_secs(0)),
1016 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
1017 incr_comp_hashes_count: Cell::new(0),
1018 incr_comp_bytes_hashed: Cell::new(0),
1019 symbol_hash_time: Cell::new(Duration::from_secs(0)),
1020 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
1022 code_stats: RefCell::new(CodeStats::new()),
1023 optimization_fuel_crate,
1024 optimization_fuel_limit,
1027 out_of_fuel: Cell::new(false),
1028 // Note that this is unsafe because it may misinterpret file descriptors
1029 // on Unix as jobserver file descriptors. We hopefully execute this near
1030 // the beginning of the process though to ensure we don't get false
1031 // positives, or in other words we try to execute this before we open
1032 // any file descriptors ourselves.
1034 // Also note that we stick this in a global because there could be
1035 // multiple `Session` instances in this process, and the jobserver is
1037 jobserver_from_env: unsafe {
1038 static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
1039 static INIT: Once = ONCE_INIT;
1041 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
1043 (*GLOBAL_JOBSERVER).clone()
1045 has_global_allocator: Cell::new(false),
1051 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1052 /// compiler. Together with the crate-name forms a unique global identifier for
1054 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1055 pub struct CrateDisambiguator(Fingerprint);
1057 impl CrateDisambiguator {
1058 pub fn to_fingerprint(self) -> Fingerprint {
1063 impl From<Fingerprint> for CrateDisambiguator {
1064 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1065 CrateDisambiguator(fingerprint)
1069 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1071 /// Holds data on the current incremental compilation session, if there is one.
1073 pub enum IncrCompSession {
1074 /// This is the state the session will be in until the incr. comp. dir is
1077 /// This is the state during which the session directory is private and can
1080 session_directory: PathBuf,
1081 lock_file: flock::Lock,
1082 load_dep_graph: bool,
1084 /// This is the state after the session directory has been finalized. In this
1085 /// state, the contents of the directory must not be modified any more.
1087 session_directory: PathBuf,
1089 /// This is an error state that is reached when some compilation error has
1090 /// occurred. It indicates that the contents of the session directory must
1091 /// not be used, since they might be invalid.
1092 InvalidBecauseOfErrors {
1093 session_directory: PathBuf,
1097 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1098 let emitter: Box<dyn Emitter> = match output {
1099 config::ErrorOutputType::HumanReadable(color_config) => {
1100 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1102 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1103 config::ErrorOutputType::Short(color_config) => {
1104 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1107 let handler = errors::Handler::with_emitter(true, false, emitter);
1108 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1109 errors::FatalError.raise();
1112 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1113 let emitter: Box<dyn Emitter> = match output {
1114 config::ErrorOutputType::HumanReadable(color_config) => {
1115 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1117 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1118 config::ErrorOutputType::Short(color_config) => {
1119 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1122 let handler = errors::Handler::with_emitter(true, false, emitter);
1123 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1126 #[derive(Copy, Clone, Debug)]
1127 pub enum CompileIncomplete {
1129 Errored(ErrorReported)
1131 impl From<ErrorReported> for CompileIncomplete {
1132 fn from(err: ErrorReported) -> CompileIncomplete {
1133 CompileIncomplete::Errored(err)
1136 pub type CompileResult = Result<(), CompileIncomplete>;
1138 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1142 Err(CompileIncomplete::Errored(ErrorReported))
1148 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1149 // this wrapper mostly exists so I don't have to write a fully
1150 // qualified path of None::<Span> inside the bug!() macro definition
1151 opt_span_bug_fmt(file, line, None::<Span>, args);
1156 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1159 args: fmt::Arguments) -> ! {
1160 opt_span_bug_fmt(file, line, Some(span), args);
1163 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1166 args: fmt::Arguments) -> ! {
1167 tls::with_opt(move |tcx| {
1168 let msg = format!("{}:{}: {}", file, line, args);
1170 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1171 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1172 (None, _) => panic!(msg)