]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
rustc: Add `-C lto=val` option
[rust.git] / src / librustc / session / mod.rs
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.
4 //
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.
10
11 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
12 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
13
14 use hir::def_id::CrateNum;
15 use ich::Fingerprint;
16
17 use ich;
18 use lint;
19 use middle::allocator::AllocatorKind;
20 use middle::dependency_format;
21 use session::search_paths::PathKind;
22 use session::config::{BorrowckMode, DebugInfoLevel, OutputType};
23 use ty::tls;
24 use util::nodemap::{FxHashMap, FxHashSet};
25 use util::common::{duration_to_secs_str, ErrorReported};
26
27 use syntax::ast::NodeId;
28 use errors::{self, DiagnosticBuilder, DiagnosticId};
29 use errors::emitter::{Emitter, EmitterWriter};
30 use syntax::json::JsonEmitter;
31 use syntax::feature_gate;
32 use syntax::symbol::Symbol;
33 use syntax::parse;
34 use syntax::parse::ParseSess;
35 use syntax::{ast, codemap};
36 use syntax::feature_gate::AttributeType;
37 use syntax_pos::{Span, MultiSpan};
38
39 use rustc_back::{LinkerFlavor, PanicStrategy};
40 use rustc_back::target::Target;
41 use rustc_data_structures::flock;
42 use jobserver::Client;
43
44 use std::cell::{self, Cell, RefCell};
45 use std::collections::HashMap;
46 use std::env;
47 use std::fmt;
48 use std::io::Write;
49 use std::path::{Path, PathBuf};
50 use std::rc::Rc;
51 use std::sync::{Once, ONCE_INIT};
52 use std::time::Duration;
53
54 mod code_stats;
55 pub mod config;
56 pub mod filesearch;
57 pub mod search_paths;
58
59 /// Represents the data associated with a compilation
60 /// session for a single crate.
61 pub struct Session {
62     pub target: config::Config,
63     pub host: Target,
64     pub opts: config::Options,
65     pub parse_sess: ParseSess,
66     /// For a library crate, this is always none
67     pub entry_fn: RefCell<Option<(NodeId, Span)>>,
68     pub entry_type: Cell<Option<config::EntryFnType>>,
69     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
70     pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
71     pub default_sysroot: Option<PathBuf>,
72     /// The name of the root source file of the crate, in the local file system.
73     /// `None` means that there is no source file.
74     pub local_crate_source_file: Option<PathBuf>,
75     /// The directory the compiler has been executed in plus a flag indicating
76     /// if the value stored here has been affected by path remapping.
77     pub working_dir: (PathBuf, bool),
78     pub lint_store: RefCell<lint::LintStore>,
79     pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
80     /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
81     /// (sub)diagnostics that have been set once, but should not be set again,
82     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
83     pub one_time_diagnostics: RefCell<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
84     pub plugin_llvm_passes: RefCell<Vec<String>>,
85     pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
86     pub crate_types: RefCell<Vec<config::CrateType>>,
87     pub dependency_formats: RefCell<dependency_format::Dependencies>,
88         /// The crate_disambiguator is constructed out of all the `-C metadata`
89     /// arguments passed to the compiler. Its value together with the crate-name
90     /// forms a unique global identifier for the crate. It is used to allow
91     /// multiple crates with the same name to coexist. See the
92     /// trans::back::symbol_names module for more information.
93     pub crate_disambiguator: RefCell<Option<CrateDisambiguator>>,
94     pub features: RefCell<feature_gate::Features>,
95
96     /// The maximum recursion limit for potentially infinitely recursive
97     /// operations such as auto-dereference and monomorphization.
98     pub recursion_limit: Cell<usize>,
99
100     /// The maximum length of types during monomorphization.
101     pub type_length_limit: Cell<usize>,
102
103     /// The metadata::creader module may inject an allocator/panic_runtime
104     /// dependency if it didn't already find one, and this tracks what was
105     /// injected.
106     pub injected_allocator: Cell<Option<CrateNum>>,
107     pub allocator_kind: Cell<Option<AllocatorKind>>,
108     pub injected_panic_runtime: Cell<Option<CrateNum>>,
109
110     /// Map from imported macro spans (which consist of
111     /// the localized span for the macro body) to the
112     /// macro name and definition span in the source crate.
113     pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
114
115     incr_comp_session: RefCell<IncrCompSession>,
116
117     /// A cache of attributes ignored by StableHashingContext
118     pub ignored_attr_names: FxHashSet<Symbol>,
119
120     /// Some measurements that are being gathered during compilation.
121     pub perf_stats: PerfStats,
122
123     /// Data about code being compiled, gathered during compilation.
124     pub code_stats: RefCell<CodeStats>,
125
126     next_node_id: Cell<ast::NodeId>,
127
128     /// If -zfuel=crate=n is specified, Some(crate).
129     optimization_fuel_crate: Option<String>,
130     /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
131     optimization_fuel_limit: Cell<u64>,
132     /// We're rejecting all further optimizations.
133     out_of_fuel: Cell<bool>,
134
135     // The next two are public because the driver needs to read them.
136
137     /// If -zprint-fuel=crate, Some(crate).
138     pub print_fuel_crate: Option<String>,
139     /// Always set to zero and incremented so that we can print fuel expended by a crate.
140     pub print_fuel: Cell<u64>,
141
142     /// Loaded up early on in the initialization of this `Session` to avoid
143     /// false positives about a job server in our environment.
144     pub jobserver_from_env: Option<Client>,
145
146     /// Metadata about the allocators for the current crate being compiled
147     pub has_global_allocator: Cell<bool>,
148 }
149
150 pub struct PerfStats {
151     /// The accumulated time needed for computing the SVH of the crate
152     pub svh_time: Cell<Duration>,
153     /// The accumulated time spent on computing incr. comp. hashes
154     pub incr_comp_hashes_time: Cell<Duration>,
155     /// The number of incr. comp. hash computations performed
156     pub incr_comp_hashes_count: Cell<u64>,
157     /// The number of bytes hashed when computing ICH values
158     pub incr_comp_bytes_hashed: Cell<u64>,
159     /// The accumulated time spent on computing symbol hashes
160     pub symbol_hash_time: Cell<Duration>,
161     /// The accumulated time spent decoding def path tables from metadata
162     pub decode_def_path_tables_time: Cell<Duration>,
163 }
164
165 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
166 enum DiagnosticBuilderMethod {
167     Note,
168     SpanNote,
169     SpanSuggestion(String), // suggestion
170     // add more variants as needed to support one-time diagnostics
171 }
172
173 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
174 /// emitting the same message more than once
175 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
176 pub enum DiagnosticMessageId {
177     ErrorId(u16), // EXXXX error code as integer
178     LintId(lint::LintId),
179     StabilityId(u32) // issue number
180 }
181
182 impl From<&'static lint::Lint> for DiagnosticMessageId {
183     fn from(lint: &'static lint::Lint) -> Self {
184         DiagnosticMessageId::LintId(lint::LintId::of(lint))
185     }
186 }
187
188 impl Session {
189     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
190         match *self.crate_disambiguator.borrow() {
191             Some(value) => value,
192             None => bug!("accessing disambiguator before initialization"),
193         }
194     }
195     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
196                                                     sp: S,
197                                                     msg: &str)
198                                                     -> DiagnosticBuilder<'a> {
199         self.diagnostic().struct_span_warn(sp, msg)
200     }
201     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
202                                                               sp: S,
203                                                               msg: &str,
204                                                               code: DiagnosticId)
205                                                               -> DiagnosticBuilder<'a> {
206         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
207     }
208     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
209         self.diagnostic().struct_warn(msg)
210     }
211     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
212                                                    sp: S,
213                                                    msg: &str)
214                                                    -> DiagnosticBuilder<'a> {
215         self.diagnostic().struct_span_err(sp, msg)
216     }
217     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
218                                                              sp: S,
219                                                              msg: &str,
220                                                              code: DiagnosticId)
221                                                              -> DiagnosticBuilder<'a> {
222         self.diagnostic().struct_span_err_with_code(sp, msg, code)
223     }
224     // FIXME: This method should be removed (every error should have an associated error code).
225     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
226         self.diagnostic().struct_err(msg)
227     }
228     pub fn struct_err_with_code<'a>(
229         &'a self,
230         msg: &str,
231         code: DiagnosticId,
232     ) -> DiagnosticBuilder<'a> {
233         self.diagnostic().struct_err_with_code(msg, code)
234     }
235     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
236                                                      sp: S,
237                                                      msg: &str)
238                                                      -> DiagnosticBuilder<'a> {
239         self.diagnostic().struct_span_fatal(sp, msg)
240     }
241     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
242                                                                sp: S,
243                                                                msg: &str,
244                                                                code: DiagnosticId)
245                                                                -> DiagnosticBuilder<'a> {
246         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
247     }
248     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
249         self.diagnostic().struct_fatal(msg)
250     }
251
252     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
253         panic!(self.diagnostic().span_fatal(sp, msg))
254     }
255     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
256         &self,
257         sp: S,
258         msg: &str,
259         code: DiagnosticId,
260     ) -> ! {
261         panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
262     }
263     pub fn fatal(&self, msg: &str) -> ! {
264         panic!(self.diagnostic().fatal(msg))
265     }
266     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
267         if is_warning {
268             self.span_warn(sp, msg);
269         } else {
270             self.span_err(sp, msg);
271         }
272     }
273     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
274         self.diagnostic().span_err(sp, msg)
275     }
276     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
277         self.diagnostic().span_err_with_code(sp, &msg, code)
278     }
279     pub fn err(&self, msg: &str) {
280         self.diagnostic().err(msg)
281     }
282     pub fn err_count(&self) -> usize {
283         self.diagnostic().err_count()
284     }
285     pub fn has_errors(&self) -> bool {
286         self.diagnostic().has_errors()
287     }
288     pub fn abort_if_errors(&self) {
289         self.diagnostic().abort_if_errors();
290     }
291     pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
292         compile_result_from_err_count(self.err_count())
293     }
294     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
295         where F: FnOnce() -> T
296     {
297         let old_count = self.err_count();
298         let result = f();
299         let errors = self.err_count() - old_count;
300         if errors == 0 {
301             Ok(result)
302         } else {
303             Err(ErrorReported)
304         }
305     }
306     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
307         self.diagnostic().span_warn(sp, msg)
308     }
309     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
310         self.diagnostic().span_warn_with_code(sp, msg, code)
311     }
312     pub fn warn(&self, msg: &str) {
313         self.diagnostic().warn(msg)
314     }
315     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
316         match opt_sp {
317             Some(sp) => self.span_warn(sp, msg),
318             None => self.warn(msg),
319         }
320     }
321     /// Delay a span_bug() call until abort_if_errors()
322     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
323         self.diagnostic().delay_span_bug(sp, msg)
324     }
325     pub fn note_without_error(&self, msg: &str) {
326         self.diagnostic().note_without_error(msg)
327     }
328     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
329         self.diagnostic().span_note_without_error(sp, msg)
330     }
331     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
332         self.diagnostic().span_unimpl(sp, msg)
333     }
334     pub fn unimpl(&self, msg: &str) -> ! {
335         self.diagnostic().unimpl(msg)
336     }
337
338     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
339                                            lint: &'static lint::Lint,
340                                            id: ast::NodeId,
341                                            sp: S,
342                                            msg: &str) {
343         match *self.buffered_lints.borrow_mut() {
344             Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg),
345             None => bug!("can't buffer lints after HIR lowering"),
346         }
347     }
348
349     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
350         let id = self.next_node_id.get();
351
352         match id.as_usize().checked_add(count) {
353             Some(next) => {
354                 self.next_node_id.set(ast::NodeId::new(next));
355             }
356             None => bug!("Input too large, ran out of node ids!")
357         }
358
359         id
360     }
361     pub fn next_node_id(&self) -> NodeId {
362         self.reserve_node_ids(1)
363     }
364     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
365         &self.parse_sess.span_diagnostic
366     }
367
368     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
369     /// deduplicates on lint ID, span (if any), and message for this `Session`
370     fn diag_once<'a, 'b>(&'a self,
371                          diag_builder: &'b mut DiagnosticBuilder<'a>,
372                          method: DiagnosticBuilderMethod,
373                          msg_id: DiagnosticMessageId,
374                          message: &str,
375                          span_maybe: Option<Span>) {
376
377         let id_span_message = (msg_id, span_maybe, message.to_owned());
378         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
379         if fresh {
380             match method {
381                 DiagnosticBuilderMethod::Note => {
382                     diag_builder.note(message);
383                 },
384                 DiagnosticBuilderMethod::SpanNote => {
385                     let span = span_maybe.expect("span_note needs a span");
386                     diag_builder.span_note(span, message);
387                 },
388                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
389                     let span = span_maybe.expect("span_suggestion needs a span");
390                     diag_builder.span_suggestion(span, message, suggestion);
391                 }
392             }
393         }
394     }
395
396     pub fn diag_span_note_once<'a, 'b>(&'a self,
397                                        diag_builder: &'b mut DiagnosticBuilder<'a>,
398                                        msg_id: DiagnosticMessageId, span: Span, message: &str) {
399         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote,
400                        msg_id, message, Some(span));
401     }
402
403     pub fn diag_note_once<'a, 'b>(&'a self,
404                                   diag_builder: &'b mut DiagnosticBuilder<'a>,
405                                   msg_id: DiagnosticMessageId, message: &str) {
406         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
407     }
408
409     pub fn diag_span_suggestion_once<'a, 'b>(&'a self,
410                                              diag_builder: &'b mut DiagnosticBuilder<'a>,
411                                              msg_id: DiagnosticMessageId,
412                                              span: Span,
413                                              message: &str,
414                                              suggestion: String) {
415         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanSuggestion(suggestion),
416                        msg_id, message, Some(span));
417     }
418
419     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
420         self.parse_sess.codemap()
421     }
422     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
423     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
424     pub fn profile_queries(&self) -> bool {
425         self.opts.debugging_opts.profile_queries ||
426             self.opts.debugging_opts.profile_queries_and_keys
427     }
428     pub fn profile_queries_and_keys(&self) -> bool {
429         self.opts.debugging_opts.profile_queries_and_keys
430     }
431     pub fn count_llvm_insns(&self) -> bool {
432         self.opts.debugging_opts.count_llvm_insns
433     }
434     pub fn time_llvm_passes(&self) -> bool {
435         self.opts.debugging_opts.time_llvm_passes
436     }
437     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
438     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
439     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
440     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
441     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
442     pub fn print_llvm_passes(&self) -> bool {
443         self.opts.debugging_opts.print_llvm_passes
444     }
445
446     /// If true, we should use NLL-style region checking instead of
447     /// lexical style.
448     pub fn nll(&self) -> bool {
449         self.features.borrow().nll || self.opts.debugging_opts.nll
450     }
451
452     /// If true, we should use the MIR-based borrowck (we may *also* use
453     /// the AST-based borrowck).
454     pub fn use_mir(&self) -> bool {
455         self.borrowck_mode().use_mir()
456     }
457
458     /// If true, we should gather causal information during NLL
459     /// checking. This will eventually be the normal thing, but right
460     /// now it is too unoptimized.
461     pub fn nll_dump_cause(&self) -> bool {
462         self.opts.debugging_opts.nll_dump_cause
463     }
464
465     /// If true, we should enable two-phase borrows checks. This is
466     /// done with either `-Ztwo-phase-borrows` or with
467     /// `#![feature(nll)]`.
468     pub fn two_phase_borrows(&self) -> bool {
469         self.features.borrow().nll || self.opts.debugging_opts.two_phase_borrows
470     }
471
472     /// What mode(s) of borrowck should we run? AST? MIR? both?
473     /// (Also considers the `#![feature(nll)]` setting.)
474     pub fn borrowck_mode(&self) -> BorrowckMode {
475         match self.opts.borrowck_mode {
476             mode @ BorrowckMode::Mir |
477             mode @ BorrowckMode::Compare => mode,
478
479             mode @ BorrowckMode::Ast => {
480                 if self.nll() {
481                     BorrowckMode::Mir
482                 } else {
483                     mode
484                 }
485             }
486
487         }
488     }
489
490     /// Should we emit EndRegion MIR statements? These are consumed by
491     /// MIR borrowck, but not when NLL is used. They are also consumed
492     /// by the validation stuff.
493     pub fn emit_end_regions(&self) -> bool {
494         // FIXME(#46875) -- we should not emit end regions when NLL is enabled,
495         // but for now we can't stop doing so because it causes false positives
496         self.opts.debugging_opts.emit_end_regions ||
497             self.opts.debugging_opts.mir_emit_validate > 0 ||
498             self.use_mir()
499     }
500
501     /// Calculates the flavor of LTO to use for this compilation.
502     pub fn lto(&self) -> config::Lto {
503         // If our target has codegen requirements ignore the command line
504         if self.target.target.options.requires_lto {
505             return config::Lto::Fat
506         }
507
508         // If the user specified something, return that. If they only said `-C
509         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
510         // then ensure we can't use a ThinLTO.
511         match self.opts.cg.lto {
512             config::Lto::No => {}
513             config::Lto::Yes if self.opts.cli_forced_thinlto_off => {
514                 return config::Lto::Fat
515             }
516             other => return other,
517         }
518
519         // Ok at this point the target doesn't require anything and the user
520         // hasn't asked for anything. Our next decision is whether or not
521         // we enable "auto" ThinLTO where we use multiple codegen units and
522         // then do ThinLTO over those codegen units. The logic below will
523         // either return `No` or `ThinLocal`.
524
525         // If processing command line options determined that we're incompatible
526         // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
527         if self.opts.cli_forced_thinlto_off {
528             return config::Lto::No
529         }
530
531         // If `-Z thinlto` specified process that, but note that this is mostly
532         // a deprecated option now that `-C lto=thin` exists.
533         if let Some(enabled) = self.opts.debugging_opts.thinlto {
534             if enabled {
535                 return config::Lto::ThinLocal
536             } else {
537                 return config::Lto::No
538             }
539         }
540
541         // If there's only one codegen unit and LTO isn't enabled then there's
542         // no need for ThinLTO so just return false.
543         if self.codegen_units() == 1 {
544             return config::Lto::No
545         }
546
547         // Right now ThinLTO isn't compatible with incremental compilation.
548         if self.opts.incremental.is_some() {
549             return config::Lto::No
550         }
551
552         // Now we're in "defaults" territory. By default we enable ThinLTO for
553         // optimized compiles (anything greater than O0).
554         match self.opts.optimize {
555             config::OptLevel::No => config::Lto::No,
556             _ => config::Lto::ThinLocal,
557         }
558     }
559
560     /// Returns the panic strategy for this compile session. If the user explicitly selected one
561     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
562     pub fn panic_strategy(&self) -> PanicStrategy {
563         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
564     }
565     pub fn linker_flavor(&self) -> LinkerFlavor {
566         self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
567     }
568
569     pub fn fewer_names(&self) -> bool {
570         let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly) ||
571                          self.opts.output_types.contains_key(&OutputType::Bitcode);
572         self.opts.debugging_opts.fewer_names || !more_names
573     }
574
575     pub fn no_landing_pads(&self) -> bool {
576         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
577     }
578     pub fn unstable_options(&self) -> bool {
579         self.opts.debugging_opts.unstable_options
580     }
581     pub fn nonzeroing_move_hints(&self) -> bool {
582         self.opts.debugging_opts.enable_nonzeroing_move_hints
583     }
584     pub fn overflow_checks(&self) -> bool {
585         self.opts.cg.overflow_checks
586             .or(self.opts.debugging_opts.force_overflow_checks)
587             .unwrap_or(self.opts.debug_assertions)
588     }
589
590     pub fn crt_static(&self) -> bool {
591         // If the target does not opt in to crt-static support, use its default.
592         if self.target.target.options.crt_static_respected {
593             self.crt_static_feature()
594         } else {
595             self.target.target.options.crt_static_default
596         }
597     }
598
599     pub fn crt_static_feature(&self) -> bool {
600         let requested_features = self.opts.cg.target_feature.split(',');
601         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
602         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
603
604         // If the target we're compiling for requests a static crt by default,
605         // then see if the `-crt-static` feature was passed to disable that.
606         // Otherwise if we don't have a static crt by default then see if the
607         // `+crt-static` feature was passed.
608         if self.target.target.options.crt_static_default {
609             !found_negative
610         } else {
611             found_positive
612         }
613     }
614
615     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
616         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
617         !self.target.target.options.eliminate_frame_pointer
618     }
619
620     /// Returns the symbol name for the registrar function,
621     /// given the crate Svh and the function DefIndex.
622     pub fn generate_plugin_registrar_symbol(&self,
623                                             disambiguator: CrateDisambiguator)
624                                             -> String {
625         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
626     }
627
628     pub fn generate_derive_registrar_symbol(&self,
629                                             disambiguator: CrateDisambiguator)
630                                             -> String {
631         format!("__rustc_derive_registrar_{}__", disambiguator.to_fingerprint().to_hex())
632     }
633
634     pub fn sysroot<'a>(&'a self) -> &'a Path {
635         match self.opts.maybe_sysroot {
636             Some (ref sysroot) => sysroot,
637             None => self.default_sysroot.as_ref()
638                         .expect("missing sysroot and default_sysroot in Session")
639         }
640     }
641     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
642         filesearch::FileSearch::new(self.sysroot(),
643                                     &self.opts.target_triple,
644                                     &self.opts.search_paths,
645                                     kind)
646     }
647     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
648         filesearch::FileSearch::new(
649             self.sysroot(),
650             config::host_triple(),
651             &self.opts.search_paths,
652             kind)
653     }
654
655     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
656         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
657
658         match *incr_comp_session {
659             IncrCompSession::Active { ref mut load_dep_graph, .. } => {
660                 *load_dep_graph = load;
661             }
662             _ => {}
663         }
664     }
665
666     pub fn incr_session_load_dep_graph(&self) -> bool {
667         let incr_comp_session = self.incr_comp_session.borrow();
668         match *incr_comp_session {
669             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
670             _ => false,
671         }
672     }
673
674     pub fn init_incr_comp_session(&self,
675                                   session_dir: PathBuf,
676                                   lock_file: flock::Lock,
677                                   load_dep_graph: bool) {
678         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
679
680         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
681             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
682         }
683
684         *incr_comp_session = IncrCompSession::Active {
685             session_directory: session_dir,
686             lock_file,
687             load_dep_graph,
688         };
689     }
690
691     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
692         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
693
694         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
695             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
696         }
697
698         // Note: This will also drop the lock file, thus unlocking the directory
699         *incr_comp_session = IncrCompSession::Finalized {
700             session_directory: new_directory_path,
701         };
702     }
703
704     pub fn mark_incr_comp_session_as_invalid(&self) {
705         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
706
707         let session_directory = match *incr_comp_session {
708             IncrCompSession::Active { ref session_directory, .. } => {
709                 session_directory.clone()
710             }
711             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
712             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
713                       *incr_comp_session),
714         };
715
716         // Note: This will also drop the lock file, thus unlocking the directory
717         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
718             session_directory,
719         };
720     }
721
722     pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
723         let incr_comp_session = self.incr_comp_session.borrow();
724         cell::Ref::map(incr_comp_session, |incr_comp_session| {
725             match *incr_comp_session {
726                 IncrCompSession::NotInitialized => {
727                     bug!("Trying to get session directory from IncrCompSession `{:?}`",
728                         *incr_comp_session)
729                 }
730                 IncrCompSession::Active { ref session_directory, .. } |
731                 IncrCompSession::Finalized { ref session_directory } |
732                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
733                     session_directory
734                 }
735             }
736         })
737     }
738
739     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
740         if self.opts.incremental.is_some() {
741             Some(self.incr_comp_session_dir())
742         } else {
743             None
744         }
745     }
746
747     pub fn print_perf_stats(&self) {
748         println!("Total time spent computing SVHs:               {}",
749                  duration_to_secs_str(self.perf_stats.svh_time.get()));
750         println!("Total time spent computing incr. comp. hashes: {}",
751                  duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
752         println!("Total number of incr. comp. hashes computed:   {}",
753                  self.perf_stats.incr_comp_hashes_count.get());
754         println!("Total number of bytes hashed for incr. comp.:  {}",
755                  self.perf_stats.incr_comp_bytes_hashed.get());
756         if self.perf_stats.incr_comp_hashes_count.get() != 0 {
757             println!("Average bytes hashed per incr. comp. HIR node: {}",
758                     self.perf_stats.incr_comp_bytes_hashed.get() /
759                     self.perf_stats.incr_comp_hashes_count.get());
760         } else {
761             println!("Average bytes hashed per incr. comp. HIR node: N/A");
762         }
763         println!("Total time spent computing symbol hashes:      {}",
764                  duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
765         println!("Total time spent decoding DefPath tables:      {}",
766                  duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
767     }
768
769     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
770     /// This expends fuel if applicable, and records fuel if applicable.
771     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
772         let mut ret = true;
773         match self.optimization_fuel_crate {
774             Some(ref c) if c == crate_name => {
775                 let fuel = self.optimization_fuel_limit.get();
776                 ret = fuel != 0;
777                 if fuel == 0 && !self.out_of_fuel.get() {
778                     println!("optimization-fuel-exhausted: {}", msg());
779                     self.out_of_fuel.set(true);
780                 } else if fuel > 0 {
781                     self.optimization_fuel_limit.set(fuel-1);
782                 }
783             }
784             _ => {}
785         }
786         match self.print_fuel_crate {
787             Some(ref c) if c == crate_name=> {
788                 self.print_fuel.set(self.print_fuel.get()+1);
789             },
790             _ => {}
791         }
792         ret
793     }
794
795     /// Returns the number of query threads that should be used for this
796     /// compilation
797     pub fn query_threads(&self) -> usize {
798         self.opts.debugging_opts.query_threads.unwrap_or(1)
799     }
800
801     /// Returns the number of codegen units that should be used for this
802     /// compilation
803     pub fn codegen_units(&self) -> usize {
804         if let Some(n) = self.opts.cli_forced_codegen_units {
805             return n
806         }
807         if let Some(n) = self.target.target.options.default_codegen_units {
808             return n as usize
809         }
810
811         // Why is 16 codegen units the default all the time?
812         //
813         // The main reason for enabling multiple codegen units by default is to
814         // leverage the ability for the trans backend to do translation and
815         // codegen in parallel. This allows us, especially for large crates, to
816         // make good use of all available resources on the machine once we've
817         // hit that stage of compilation. Large crates especially then often
818         // take a long time in trans/codegen and this helps us amortize that
819         // cost.
820         //
821         // Note that a high number here doesn't mean that we'll be spawning a
822         // large number of threads in parallel. The backend of rustc contains
823         // global rate limiting through the `jobserver` crate so we'll never
824         // overload the system with too much work, but rather we'll only be
825         // optimizing when we're otherwise cooperating with other instances of
826         // rustc.
827         //
828         // Rather a high number here means that we should be able to keep a lot
829         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
830         // to build we'll be guaranteed that all cpus will finish pretty closely
831         // to one another and we should make relatively optimal use of system
832         // resources
833         //
834         // Note that the main cost of codegen units is that it prevents LLVM
835         // from inlining across codegen units. Users in general don't have a lot
836         // of control over how codegen units are split up so it's our job in the
837         // compiler to ensure that undue performance isn't lost when using
838         // codegen units (aka we can't require everyone to slap `#[inline]` on
839         // everything).
840         //
841         // If we're compiling at `-O0` then the number doesn't really matter too
842         // much because performance doesn't matter and inlining is ok to lose.
843         // In debug mode we just want to try to guarantee that no cpu is stuck
844         // doing work that could otherwise be farmed to others.
845         //
846         // In release mode, however (O1 and above) performance does indeed
847         // matter! To recover the loss in performance due to inlining we'll be
848         // enabling ThinLTO by default (the function for which is just below).
849         // This will ensure that we recover any inlining wins we otherwise lost
850         // through codegen unit partitioning.
851         //
852         // ---
853         //
854         // Ok that's a lot of words but the basic tl;dr; is that we want a high
855         // number here -- but not too high. Additionally we're "safe" to have it
856         // always at the same number at all optimization levels.
857         //
858         // As a result 16 was chosen here! Mostly because it was a power of 2
859         // and most benchmarks agreed it was roughly a local optimum. Not very
860         // scientific.
861         16
862     }
863 }
864
865 pub fn build_session(sopts: config::Options,
866                      local_crate_source_file: Option<PathBuf>,
867                      registry: errors::registry::Registry)
868                      -> Session {
869     let file_path_mapping = sopts.file_path_mapping();
870
871     build_session_with_codemap(sopts,
872                                local_crate_source_file,
873                                registry,
874                                Rc::new(codemap::CodeMap::new(file_path_mapping)),
875                                None)
876 }
877
878 pub fn build_session_with_codemap(sopts: config::Options,
879                                   local_crate_source_file: Option<PathBuf>,
880                                   registry: errors::registry::Registry,
881                                   codemap: Rc<codemap::CodeMap>,
882                                   emitter_dest: Option<Box<Write + Send>>)
883                                   -> Session {
884     // FIXME: This is not general enough to make the warning lint completely override
885     // normal diagnostic warnings, since the warning lint can also be denied and changed
886     // later via the source code.
887     let warnings_allow = sopts.lint_opts
888         .iter()
889         .filter(|&&(ref key, _)| *key == "warnings")
890         .map(|&(_, ref level)| *level == lint::Allow)
891         .last()
892         .unwrap_or(false);
893     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
894
895     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
896
897     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
898
899     let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
900
901     let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
902         (config::ErrorOutputType::HumanReadable(color_config), None) => {
903             Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), false))
904         }
905         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
906             Box::new(EmitterWriter::new(dst, Some(codemap.clone()), false))
907         }
908         (config::ErrorOutputType::Json(pretty), None) => {
909             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone(), pretty))
910         }
911         (config::ErrorOutputType::Json(pretty), Some(dst)) => {
912             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone(), pretty))
913         }
914         (config::ErrorOutputType::Short(color_config), None) => {
915             Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), true))
916         }
917         (config::ErrorOutputType::Short(_), Some(dst)) => {
918             Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true))
919         }
920     };
921
922     let diagnostic_handler =
923         errors::Handler::with_emitter_and_flags(
924             emitter,
925             errors::HandlerFlags {
926                 can_emit_warnings,
927                 treat_err_as_bug,
928                 external_macro_backtrace,
929                 .. Default::default()
930             });
931
932     build_session_(sopts,
933                    local_crate_source_file,
934                    diagnostic_handler,
935                    codemap)
936 }
937
938 pub fn build_session_(sopts: config::Options,
939                       local_crate_source_file: Option<PathBuf>,
940                       span_diagnostic: errors::Handler,
941                       codemap: Rc<codemap::CodeMap>)
942                       -> Session {
943     let host = match Target::search(config::host_triple()) {
944         Ok(t) => t,
945         Err(e) => {
946             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
947         }
948     };
949     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
950
951     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
952     let default_sysroot = match sopts.maybe_sysroot {
953         Some(_) => None,
954         None => Some(filesearch::get_or_default_sysroot())
955     };
956
957     let file_path_mapping = sopts.file_path_mapping();
958
959     let local_crate_source_file = local_crate_source_file.map(|path| {
960         file_path_mapping.map_prefix(path).0
961     });
962
963     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
964     let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
965         .map(|i| i.1).unwrap_or(0));
966     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
967     let print_fuel = Cell::new(0);
968
969     let working_dir = match env::current_dir() {
970         Ok(dir) => dir,
971         Err(e) => {
972             panic!(p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)))
973         }
974     };
975     let working_dir = file_path_mapping.map_prefix(working_dir);
976
977     let sess = Session {
978         target: target_cfg,
979         host,
980         opts: sopts,
981         parse_sess: p_s,
982         // For a library crate, this is always none
983         entry_fn: RefCell::new(None),
984         entry_type: Cell::new(None),
985         plugin_registrar_fn: Cell::new(None),
986         derive_registrar_fn: Cell::new(None),
987         default_sysroot,
988         local_crate_source_file,
989         working_dir,
990         lint_store: RefCell::new(lint::LintStore::new()),
991         buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
992         one_time_diagnostics: RefCell::new(FxHashSet()),
993         plugin_llvm_passes: RefCell::new(Vec::new()),
994         plugin_attributes: RefCell::new(Vec::new()),
995         crate_types: RefCell::new(Vec::new()),
996         dependency_formats: RefCell::new(FxHashMap()),
997         crate_disambiguator: RefCell::new(None),
998         features: RefCell::new(feature_gate::Features::new()),
999         recursion_limit: Cell::new(64),
1000         type_length_limit: Cell::new(1048576),
1001         next_node_id: Cell::new(NodeId::new(1)),
1002         injected_allocator: Cell::new(None),
1003         allocator_kind: Cell::new(None),
1004         injected_panic_runtime: Cell::new(None),
1005         imported_macro_spans: RefCell::new(HashMap::new()),
1006         incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
1007         ignored_attr_names: ich::compute_ignored_attr_names(),
1008         perf_stats: PerfStats {
1009             svh_time: Cell::new(Duration::from_secs(0)),
1010             incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
1011             incr_comp_hashes_count: Cell::new(0),
1012             incr_comp_bytes_hashed: Cell::new(0),
1013             symbol_hash_time: Cell::new(Duration::from_secs(0)),
1014             decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
1015         },
1016         code_stats: RefCell::new(CodeStats::new()),
1017         optimization_fuel_crate,
1018         optimization_fuel_limit,
1019         print_fuel_crate,
1020         print_fuel,
1021         out_of_fuel: Cell::new(false),
1022         // Note that this is unsafe because it may misinterpret file descriptors
1023         // on Unix as jobserver file descriptors. We hopefully execute this near
1024         // the beginning of the process though to ensure we don't get false
1025         // positives, or in other words we try to execute this before we open
1026         // any file descriptors ourselves.
1027         //
1028         // Also note that we stick this in a global because there could be
1029         // multiple `Session` instances in this process, and the jobserver is
1030         // per-process.
1031         jobserver_from_env: unsafe {
1032             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
1033             static INIT: Once = ONCE_INIT;
1034             INIT.call_once(|| {
1035                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
1036             });
1037             (*GLOBAL_JOBSERVER).clone()
1038         },
1039         has_global_allocator: Cell::new(false),
1040     };
1041
1042     sess
1043 }
1044
1045 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1046 /// compiler. Together with the crate-name forms a unique global identifier for
1047 /// the crate.
1048 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1049 pub struct CrateDisambiguator(Fingerprint);
1050
1051 impl CrateDisambiguator {
1052     pub fn to_fingerprint(self) -> Fingerprint {
1053         self.0
1054     }
1055 }
1056
1057 impl From<Fingerprint> for CrateDisambiguator {
1058     fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1059         CrateDisambiguator(fingerprint)
1060     }
1061 }
1062
1063 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1064
1065 /// Holds data on the current incremental compilation session, if there is one.
1066 #[derive(Debug)]
1067 pub enum IncrCompSession {
1068     /// This is the state the session will be in until the incr. comp. dir is
1069     /// needed.
1070     NotInitialized,
1071     /// This is the state during which the session directory is private and can
1072     /// be modified.
1073     Active {
1074         session_directory: PathBuf,
1075         lock_file: flock::Lock,
1076         load_dep_graph: bool,
1077     },
1078     /// This is the state after the session directory has been finalized. In this
1079     /// state, the contents of the directory must not be modified any more.
1080     Finalized {
1081         session_directory: PathBuf,
1082     },
1083     /// This is an error state that is reached when some compilation error has
1084     /// occurred. It indicates that the contents of the session directory must
1085     /// not be used, since they might be invalid.
1086     InvalidBecauseOfErrors {
1087         session_directory: PathBuf,
1088     }
1089 }
1090
1091 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1092     let emitter: Box<Emitter> = match output {
1093         config::ErrorOutputType::HumanReadable(color_config) => {
1094             Box::new(EmitterWriter::stderr(color_config, None, false))
1095         }
1096         config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1097         config::ErrorOutputType::Short(color_config) => {
1098             Box::new(EmitterWriter::stderr(color_config, None, true))
1099         }
1100     };
1101     let handler = errors::Handler::with_emitter(true, false, emitter);
1102     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1103     panic!(errors::FatalError);
1104 }
1105
1106 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1107     let emitter: Box<Emitter> = match output {
1108         config::ErrorOutputType::HumanReadable(color_config) => {
1109             Box::new(EmitterWriter::stderr(color_config, None, false))
1110         }
1111         config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1112         config::ErrorOutputType::Short(color_config) => {
1113             Box::new(EmitterWriter::stderr(color_config, None, true))
1114         }
1115     };
1116     let handler = errors::Handler::with_emitter(true, false, emitter);
1117     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1118 }
1119
1120 #[derive(Copy, Clone, Debug)]
1121 pub enum CompileIncomplete {
1122     Stopped,
1123     Errored(ErrorReported)
1124 }
1125 impl From<ErrorReported> for CompileIncomplete {
1126     fn from(err: ErrorReported) -> CompileIncomplete {
1127         CompileIncomplete::Errored(err)
1128     }
1129 }
1130 pub type CompileResult = Result<(), CompileIncomplete>;
1131
1132 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1133     if err_count == 0 {
1134         Ok(())
1135     } else {
1136         Err(CompileIncomplete::Errored(ErrorReported))
1137     }
1138 }
1139
1140 #[cold]
1141 #[inline(never)]
1142 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1143     // this wrapper mostly exists so I don't have to write a fully
1144     // qualified path of None::<Span> inside the bug!() macro definition
1145     opt_span_bug_fmt(file, line, None::<Span>, args);
1146 }
1147
1148 #[cold]
1149 #[inline(never)]
1150 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1151                                         line: u32,
1152                                         span: S,
1153                                         args: fmt::Arguments) -> ! {
1154     opt_span_bug_fmt(file, line, Some(span), args);
1155 }
1156
1157 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1158                                         line: u32,
1159                                         span: Option<S>,
1160                                         args: fmt::Arguments) -> ! {
1161     tls::with_opt(move |tcx| {
1162         let msg = format!("{}:{}: {}", file, line, args);
1163         match (tcx, span) {
1164             (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1165             (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1166             (None, _) => panic!(msg)
1167         }
1168     });
1169     unreachable!();
1170 }